### Setup: clone, install tools, and start database Source: https://github.com/supabase-community/postgres-language-server/blob/main/CONTRIBUTING.md Clones the repository with submodules, installs required cargo and JS tooling via `just install-tools`, and starts the Postgres database with Docker Compose. The test database listens on `postgresql://postgres:postgres@127.0.0.1:5432/postgres`. ```bash git clone --recurse-submodules https://github.com/supabase-community/postgres-language-server.git cd postgres-language-server # install the cargo and JS tooling (tree-sitter-cli, cargo-insta, taplo, sqlx-cli, uv, ...) just install-tools # start the Postgres database the tests and the sqlx queries run against docker compose up -d ``` -------------------------------- ### Development Setup Commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/AGENTS.md Install development tools, start the database for schema introspection, and enter the Nix environment. ```bash # Install development tools just install-tools # Start database for schema introspection docker-compose up -d # For Nix users nix develop && docker-compose up -d ``` -------------------------------- ### Development Setup Commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/README.md Commands to start the development environment. The first command enters a Nix shell (optional if not using Nix), and the second starts the Docker Compose services. ```bash nix develop # or skip if not using Nix docker-compose up -d ``` -------------------------------- ### Full configuration file example Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md A complete configuration file showing all available sections: linter, typecheck, plpgsqlCheck, and format. All tools are enabled by default, but some require additional setup like a database connection or the plpgsql_check extension. ```json { "$schema": "https://pg-language-server.com/latest/schema.json", "linter": { "enabled": true, "rules": { "recommended": true, "banDropColumn": "off", "preferBigInt": { "level": "warn", "options": { "checkSmallint": false } } }, "groups": { "safety": "warn", "style": "off" } }, "typecheck": { "enabled": true }, "plpgsqlCheck": { "enabled": true }, "format": { "enabled": true, "keywordCase": "lower" } } ``` -------------------------------- ### Run a command through the daemon with --use-server Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md After starting the daemon, add the --use-server option to every command. This example runs a check on a file. Operations via the daemon are significantly slower than the CLI. ```shell postgres-language-server check --use-server --stdin-file-path=dummy.sql ``` -------------------------------- ### Example output with uppercase keywords and constants Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md SQL example output with uppercase keywords and constants. ```sql CREATE TABLE users ( id serial PRIMARY KEY, name text NOT NULL, active boolean DEFAULT TRUE ); SELECT * FROM users WHERE active = TRUE; ``` -------------------------------- ### Legacy setup for postgres_lsp on older Neovim Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md For Neovim versions before 0.11, use the legacy setup function from lspconfig. ```lua require('lspconfig').postgres_lsp.setup{} ``` -------------------------------- ### Install via Nix Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/manual_installation.md Install the CLI into your Nix profile or run it without installing. The nixpkgs version may lag behind the latest GitHub release. ```sh # Install into your profile nix profile install nixpkgs#postgres-language-server # Or try it without installing nix run nixpkgs#postgres-language-server -- --version ``` -------------------------------- ### Example output with default lowercase settings Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md SQL example output with default settings (lowercase keywords and constants). ```sql create table users ( id serial primary key, name text not null, active boolean default true ); select * from users where active = true; ``` -------------------------------- ### File structure example Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_test_macros/README.md Shows the expected file structure for the test macro. ```txt crate/ |-- src/ |-- tests/ |-- queries/ |-- test.sql |-- test.expected.sql |-- querytest.rs ``` -------------------------------- ### Install via Homebrew Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/manual_installation.md Installs the Postgres Language Server using Homebrew on macOS and Linux. ```sh brew install postgres-language-server ``` -------------------------------- ### Install Postgres Language Server via Mason Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md Use this command in Neovim to install the language server through Mason, the recommended method. ```vim :MasonInstall postgres-language-server ``` -------------------------------- ### Extends configuration file with schema and database settings Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md Shares linter setup between projects by listing other configuration files in the extends array. Paths starting with '.' or ending in '.jsonc' are resolved relative to the configuration file. Files are applied left to right, with later files overriding earlier ones, and the current file's settings take precedence. ```json { "$schema": "https://pg-language-server.com/latest/schema.json", "extends": ["../postgres-language-server.base.jsonc"], "db": { "database": "billing" } } ``` -------------------------------- ### Install @postgres-language-server/wasm with npm or bun Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Install the package using npm or bun. The comment shows the alternative bun command. ```bash npm install @postgres-language-server/wasm # or bun add @postgres-language-server/wasm ``` -------------------------------- ### Start the Postgres Language Server daemon Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md Run this command to start the daemon process. You are responsible for stopping it with the stop command to avoid ghost processes. ```shell postgres-language-server start ``` -------------------------------- ### Install @postgres-language-server/wasm Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/browser.md Install the WebAssembly package via npm. Required before using the Workspace or LanguageServer APIs. ```bash npm install @postgres-language-server/wasm ``` -------------------------------- ### Check binary executable and version Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md Verify the language server binary is installed and accessible. ```bash which postgres-language-server postgres-language-server --version ``` -------------------------------- ### Workspace API: parse, split, lint, complete, hover Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Create a workspace and use its methods to parse SQL, split statements, insert files, lint, get completions, and hover info. The example shows expected outputs for parse and splitStatements. ```typescript import { createWorkspace } from "@postgres-language-server/wasm/workspace"; const workspace = await createWorkspace(); // Parse SQL and get errors const errors = workspace.parse("SELECT * FROM users;"); console.log(errors); // [] // Split SQL into individual statements const statements = workspace.splitStatements("SELECT 1; SELECT 2;"); // [{ sql: "SELECT 1;", start: 0, end: 9 }, { sql: "SELECT 2;", start: 10, end: 19 }] // Insert a file and lint it workspace.insertFile("/query.sql", "SELECT * FROM users;"); const diagnostics = workspace.lint("/query.sql"); // Get completions const completions = workspace.complete("/query.sql", 14); // position after "FROM " // Get hover info const hover = workspace.hover("/query.sql", 14); // position over "users" ``` -------------------------------- ### Documentation example for a lint rule Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Shows how to document a rule with a brief description, examples section with invalid and valid snippets, and the expect_diagnostic property for invalid snippets. ```rust declare_lint_rule! { /// Dropping a column may break existing clients. /// /// Update your application code to no longer read or write the column. /// /// You can leave the column as nullable or delete the column once queries no longer select or modify the column. /// /// ## Examples /// /// ### Invalid /// /// ```sql,expect_diagnostic /// alter table test drop column id; /// ``` /// pub BanDropColumn { version: "next", name: "banDropColumn", recommended: true, severity: Severity::Error, sources: &[RuleSource::Squawk("ban-drop-column")], } } ``` -------------------------------- ### Valid SQL: create type and use it Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-type.md Shows a valid example where a type is created and then used in a query. ```sql create type mood as enum ('happy', 'sad'); select null::mood; ``` -------------------------------- ### Install CLI with pnpm Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/getting_started.md Adds the Postgres Language Server CLI as a development dependency with exact version pinning. ```sh pnpm add -D -E @postgres-language-server/cli ``` -------------------------------- ### Configuration JSON for avoidAttachingPartition Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/avoid-attaching-partition.md Configuration example showing how to set the rule to 'error' in the linter settings. ```json { "linter": { "rules": { "avoidAttachingPartition": "error" } } } ``` -------------------------------- ### Workspace.complete Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets completions at a position in a file. ```APIDOC ## Workspace.complete ### Description Gets completions at a position in a file. ### Method complete(path, offset) ### Parameters - **path** (string) - Required - The file path. - **offset** (number) - Required - The character offset. ### Returns - **Completions** - The completions at the position. ``` -------------------------------- ### Valid SQL: create temp table and select Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-relation.md Shows a valid example where a temporary table is created and then queried, avoiding the unknownRelation diagnostic. ```sql create temp table scratch (id int8); select * from scratch; ``` -------------------------------- ### workspace.complete Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets completions at a given position in a file. ```APIDOC ## workspace.complete ### Description Gets completions at a given position in a file. ### Method function (synchronous) ### Signature `complete(uri: string, position: number): Completion[]` ### Parameters - **uri** (string) - Required - The file URI or path. - **position** (number) - Required - The character offset in the file. ### Returns - **Completion[]** (array) - Array of completion items. ### Example ```typescript const completions = workspace.complete("/query.sql", 14); // position after "FROM " ``` ``` -------------------------------- ### Configure banDropDatabase rule in JSON Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/ban-drop-database.md Configuration example for the banDropDatabase rule, setting it to 'error' level in the linter rules. ```json { "linter": { "rules": { "banDropDatabase": "error" } } } ``` -------------------------------- ### Valid SQL: create function add_one and select add_one(1); Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-function.md Shows a valid example where a function is created and then called, avoiding the unknownFunction diagnostic. ```sql create function add_one(value int8) returns int8 language sql as 'select value + 1'; select add_one(1); ``` -------------------------------- ### Workspace.version Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets the library version. ```APIDOC ## Workspace.version ### Description Gets the library version. ### Method version() ### Returns - **string** - The library version. ``` -------------------------------- ### JSON configuration for rule options Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Example of setting rule options in postgres-language-server.jsonc. The options include behavior, threshold, and behaviorExceptions. ```json { "linter": { "rules": { "safety": { "myRule": { "level": "warn", "options": { "behavior": "A", "threshold": 20, "behaviorExceptions": ["one", "two"] } } } } } } ``` -------------------------------- ### Example Test Directory Structure Source: https://github.com/supabase-community/postgres-language-server/blob/main/agentic/port_eugene_rules.md Shows the expected file layout for a rule's test directory, with basic, variant, and valid case files. ```text tests/specs/safety/addSerialColumn/ ├── basic.sql # Basic case triggering the rule ├── bigserial.sql # Variant (bigserial type) ├── generated_stored.sql # Another variant (GENERATED) ├── valid_regular_column.sql # Valid: regular column └── valid_create_table.sql # Valid: CREATE TABLE context ``` -------------------------------- ### SQL example triggering banDropTable Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/ban-drop-table.md Shows a SQL statement that drops a table, which triggers the banDropTable diagnostic. ```sql drop table some_table; ``` -------------------------------- ### Valid SQL example for insertColumnMismatch Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/insert-column-mismatch.md Shows a correct INSERT statement where the number of values matches the number of target columns. ```sql create table users (id int8, name text); insert into users (id, name) values (1, 'Ada'); ``` -------------------------------- ### Configuration JSON for multipleAlterTable Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/multiple-alter-table.md Example configuration to set the rule to 'error' in the linter settings. ```json { "linter": { "rules": { "multipleAlterTable": "error" } } } ``` -------------------------------- ### Diagnostic Output for creatingEnum Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/creating-enum.md Example output from the linter when the invalid SQL is checked. It shows the diagnostic message and suggestions. ```sh code-block.sql:1:1 lint/creatingEnum ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ! Creating enum type document_type is not recommended. > 1 │ CREATE TYPE document_type AS ENUM ('invoice', 'receipt', 'other'); │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2 │ i Enum types are difficult to modify: removing values requires complex migrations, and associating additional data with values is not possible. i Consider using a lookup table with a foreign key constraint instead, which provides more flexibility and easier maintenance. ``` -------------------------------- ### Diagnostic output for unknownType Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-type.md Example output from the linter showing the diagnostic message for the invalid query. ```sh code-block.sql:1:14 lint/unknownType ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Type missing_type does not exist. > 1 │ select null::missing_type; │ ^^^^^^^^^^^^ 2 │ ``` -------------------------------- ### Example test structure for addSerialColumn rule Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Shows the expected directory layout for snapshot tests of the addSerialColumn rule, including SQL files and their auto-generated snapshots. ```text tests/specs/safety/addSerialColumn/ ├── basic.sql # Basic case that triggers the rule ├── basic.sql.snap # Auto-generated snapshot ├── bigserial.sql # Test bigserial type ├── bigserial.sql.snap ├── generated_stored.sql # Test GENERATED ... STORED ├── generated_stored.sql.snap ├── valid_regular_column.sql # Valid case - should NOT trigger └── valid_regular_column.sql.snap ``` -------------------------------- ### Valid SQL example for assignmentTypeMismatch Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/assignment-type-mismatch.md Shows a correct insert that assigns an integer to an integer column, avoiding the diagnostic. ```sql create table typecheck_assignment (qty integer); insert into typecheck_assignment values (1); ``` -------------------------------- ### Exclude test folders via files.ignore configuration Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md Uses the files.ignore field to exclude files and folders from processing. Negated patterns starting with '!' can also be used. This example includes all files except those in any test/ folder. ```json { "files": { "ignore": [ "**/test", ] } } ``` -------------------------------- ### Generated test example Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_test_macros/README.md Shows the generated test code for a file `some_test_abc.sql`. The macro generates a test function that calls `run_test` with the file paths. ```rust #[test] pub fn some_test_abc() { let test_file = "/tests/queries/some_test_abc.sql"; let test_expected_file = "/tests/queries/some_test_abc.expected.sql"; let parent = "/tests/queries"; run_test(test_file, test_expected_file, parent); } ``` -------------------------------- ### Configuration: Configure rule groups with linter.groups Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/upgrading_to_0_27.md Shows how to configure rule groups separately under `linter.groups`. This example turns off the `style` group and sets `destructive` to `error`. ```json { "linter": { "groups": { "style": "off", "destructive": "error" } } } ``` -------------------------------- ### Valid SQL example for unknownColumn Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-column.md Shows a SQL statement that does not trigger the unknownColumn diagnostic because the column 'name' exists on the 'users' table. ```sql create table users (id int8, name text); select name from users; ``` -------------------------------- ### Initialize configuration file Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/getting_started.md Creates a postgres-language-server.jsonc configuration file in the project root. This step is optional if defaults are acceptable. ```sh postgres-language-server init ``` -------------------------------- ### Diagnostic output for invalid CREATE TABLE Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-text-field.md Shows the lint/preferTextField diagnostic output for the invalid CREATE TABLE example, including the error message and suggestion. ```sh code-block.sql:1:1 lint/preferTextField ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ! Changing the size of a varchar field requires an ACCESS EXCLUSIVE lock. > 1 │ CREATE TABLE "core_bar" ( │ ^^^^^^^^^^^^^^^^^^^^^^^^^ > 2 │ "id" serial NOT NULL PRIMARY KEY, > 3 │ "alpha" varchar(100) NOT NULL > 4 │ ); │ ^^ 5 │ i Use a text field with a check constraint. ``` -------------------------------- ### VALUES with expanded layout and leading commas Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md SQL example showing the effect of 'valuesRowLayout: expanded' and 'commaStyle: leading'. Each tuple starts on its own indented line, even when rows fit within lineWidth. Applies to INSERT, standalone VALUES, and VALUES in subqueries and CTEs. ```sql values ('MONTHLY', 1) , ('QUARTERLY', 3); ``` -------------------------------- ### Diagnostic output for multipleAlterTable Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/multiple-alter-table.md Example output from the linter when the rule is triggered. It reports the location and explains the performance issue and the suggested fix. ```sh code-block.sql:2:1 lint/multipleAlterTable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ! Multiple ALTER TABLE statements found for table public.authors. 1 │ ALTER TABLE authors ALTER COLUMN name SET NOT NULL; > 2 │ ALTER TABLE authors ALTER COLUMN email SET NOT NULL; │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 │ i Multiple ALTER TABLE statements on the same table require scanning and potentially rewriting the table multiple times. i Combine the ALTER TABLE statements into a single statement with comma-separated actions to scan the table only once. ``` -------------------------------- ### LSP Method: initialize Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Initializes the language server with client capabilities. ```APIDOC ## LSP Method: initialize ### Description Initializes the language server with client capabilities. ### Method initialize ### Parameters - **params.capabilities** (object) - Required - The client capabilities. ### Example ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "capabilities": {} } } ``` ``` -------------------------------- ### Monaco editor setup with SQL language and LSP integration Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/e2e/index.html Loads Monaco from CDN, registers the SQL language, creates an editor with initial SQL content, and initializes the LSP worker client. Sends an initialize request and sets up diagnostics on content change. ```javascript // Load Monaco require.config({ paths: { vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.45.0/min/vs" } }); require(["vs/editor/editor.main"], async function () { setStatus("Monaco loaded, loading WASM..."); // Register SQL language monaco.languages.register({ id: "sql" }); // Create editor const editor = monaco.editor.create(document.getElementById("container"), { value: "-- Type SQL here\nSELECT * FROM users;", language: "sql", theme: "vs-dark", automaticLayout: true, minimap: { enabled: false }, }); // Expose editor for tests window.monacoEditor = editor; try { // Create worker-based LSP client for Monaco integration const lspClient = new LspWorkerClient(); await lspClient.init(); window.pglsLspClient = lspClient; // Initialize LSP via worker await lspClient.sendMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { capabilities: {} }, }); setStatus("Ready", "ready"); // Set up diagnostics on content change using the worker LSP let debounceTimer; let documentVersion = 0; const updateDiagnostics = async () => { const content = editor.getValue(); const uri = "file:///test.sql"; documentVersion++; // Send didOpen/didChange via LSP worker const messages = await lspClient.sendMessage({ jsonrpc: "2.0", method: documentVersion === 1 ? "textDocument/didOpen" : "textDocument/didChange", params: documentVersion === 1 ? { textDocument: { uri: uri, languageId: "sql", version: documentVersion, text: content, }, } : { textDocument: { uri: uri, version: documentVersion, }, contentChanges: [{ text: content }], }, }); // Find publishDiagnostics notification const diagNotification = messages.find( (m) => m.method === "textDocument/publishDiagnostics", ); const diagnostics = diagNotification?.params?.diagnostics || []; // Update Monaco markers const model = editor.getModel(); const markers = diagnostics.map((d) => ({ severity: d.severity === 1 ? monaco.MarkerSeverity.Error : d.severity === 2 ? monaco.MarkerSeverity.Warning : monaco.MarkerSeverity.Info, message: d.message, startLineNumber: d.range.start.line + 1, startColumn: d.range.start.character + 1, endLineNumber: d.range.end.line + 1, endColumn: d.range.end.character + 1, })); monaco.editor.setModelMarkers(model, "pgls", markers); // Show in diagnostics panel showDiagnostics( diagnostics.map((d) => ({ severity: d.severity === 1 ? "error" : d.severity === 2 ? "warning" : "info", message: d.message, })), ); // Expose diagnostics for tests window.lastDiagnostics = diagnostics; }; editor.onDidChangeModelContent(() => { clearTimeout(debounceTimer); debounceTimer = setTimeout(updateDiagnostics, 300); }); // Initial diagnostics updateDiagnostics(); } catch (err) { console.error("Failed to load WASM:", err); setStatus("Error: " + err.message, "error"); window.pglsError = err; } }); ``` -------------------------------- ### Manual Test SQL File Source: https://github.com/supabase-community/postgres-language-server/blob/main/agentic/port_eugene_rules.md Example SQL file to manually test a rule, showing an ALTER TABLE statement that adds a serial column. ```sql -- test.sql ALTER TABLE users ADD COLUMN id serial; ``` -------------------------------- ### Invalid SQL example for unknownColumn Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-column.md Shows a SQL statement that triggers the unknownColumn diagnostic because the column 'email' does not exist on the 'users' table. The output shows the diagnostic message and location. ```sql create table users (id int8, name text); select email from users; ``` ```sh code-block.sql:2:8 lint/unknownColumn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Column email does not exist. 1 │ create table users (id int8, name text); > 2 │ select email from users; │ ^^^^^ 3 │ ``` -------------------------------- ### Emacs Eglot: Register postgres-language-server for sql-mode Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md Registers the server with Eglot so it can be used in SQL buffers. After adding this, run 'M-x eglot' or add the hook to start it automatically. ```elisp (with-eval-after-load 'eglot (add-to-list 'eglot-server-programs '(sql-mode . ("postgres-language-server" "lsp-proxy")))) ``` -------------------------------- ### Building and Testing Commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/AGENTS.md Run all tests, test a specific crate, and run doc tests. ```bash # Run all tests just test # or: cargo test run --no-fail-fast # Test specific crate just test-crate pgls_lsp # Run doc tests just test-doc ``` -------------------------------- ### Basic format commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md Shows how to check formatting, write changes, and format a directory using the postgres-language-server format command. ```bash # Check formatting and show a diff for every statement that would change postgres-language-server format file.sql # Format and write changes postgres-language-server format file.sql --write # Format entire directory postgres-language-server format migrations/ --write ``` -------------------------------- ### Download and run published binary Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/manual_installation.md Downloads the appropriate binary for your platform from the latest GitHub release and grants execution permission. After downloading, run the server with ./postgres-language-server. ```bash # macOS arm (M1 or newer) curl -L https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_aarch64-apple-darwin -o postgres-language-server chmod +x postgres-language-server # macOS x86_64 curl -L https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_x86_64-apple-darwin -o postgres-language-server chmod +x postgres-language-server # Linux (x86_64) curl -L https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_x86_64-unknown-linux-gnu -o postgres-language-server chmod +x postgres-language-server # Linux (aarch64) curl -L https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_aarch64-unknown-linux-gnu -o postgres-language-server chmod +x postgres-language-server # Windows (x86_64, PowerShell) Invoke-WebRequest -Uri "https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_x86_64-pc-windows-msvc.exe" -OutFile "postgres-language-server.exe" # Windows (aarch64, PowerShell) Invoke-WebRequest -Uri "https://github.com/supabase-community/postgres-language-server/releases/latest/download/postgres-language-server_aarch64-pc-windows-msvc.exe" -OutFile "postgres-language-server.exe" ``` -------------------------------- ### Formatting stdin with output Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md Formats SQL piped through stdin using --stdin-file-path. The formatted SQL is printed to stdout, and the example shows the expected output. ```bash echo "SELECT a,b FROM t;" | postgres-language-server format --stdin-file-path=query.sql # select a, b from t; ``` -------------------------------- ### Workspace.lint Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets diagnostics for a file. ```APIDOC ## Workspace.lint ### Description Gets diagnostics for a file. ### Method lint(path) ### Parameters - **path** (string) - Required - The file path. ### Returns - **Diagnostics** - The diagnostics for the file. ``` -------------------------------- ### Use the ignore file Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/vcs_integration.md Enable `vcs.useIgnoreFile` to ignore files and directories listed in the project's VCS ignore file as well as a `.ignore` file. ```json { "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true } } ``` -------------------------------- ### Workspace.hover Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets hover info at a position in a file. ```APIDOC ## Workspace.hover ### Description Gets hover info at a position in a file. ### Method hover(path, offset) ### Parameters - **path** (string) - Required - The file path. - **offset** (number) - Required - The character offset. ### Returns - **HoverInfo** - The hover information. ``` -------------------------------- ### Pre-PR checks: format, lint, and ready Source: https://github.com/supabase-community/postgres-language-server/blob/main/CONTRIBUTING.md Commands to format code, run linters, and run codegen plus format and lint. `just ready` fails if anything changes and expects a clean working tree. ```bash just format # Rust, TOML and JS/TS just lint # clippy, rules_check and oxlint just ready # codegen, format and lint; fails if anything changes ``` -------------------------------- ### clauseBodyStyle compact example Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md SQL example showing 'clauseBodyStyle: compact'. The first relation stays on the FROM line and the condition on the WHERE line. A select list of a single item stays on the SELECT line, while a list of several items puts one item per line. ```sql select count(*) from memberships where memberships.user_id = $1 and memberships.role = 'admin' and memberships.active; select memberships.user_id, memberships.role from memberships where memberships.organization_id = $1 and memberships.active; ``` -------------------------------- ### Configure ignore and include options for formatting Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/features/formatting.md JSON configuration example showing how to use the 'ignore' and 'include' options to control which files are formatted. The 'ignore' option excludes files matching the glob patterns, and 'include' specifies which files to format. ```json { "format": { "ignore": ["**/generated/**", "**/vendor/**"], "include": ["**/*.sql"] } } ``` -------------------------------- ### workspace.hover Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Gets hover information at a given position in a file. ```APIDOC ## workspace.hover ### Description Gets hover information at a given position in a file. ### Method function (synchronous) ### Signature `hover(uri: string, position: number): Hover` ### Parameters - **uri** (string) - Required - The file URI or path. - **position** (number) - Required - The character offset in the file. ### Returns - **Hover** (object) - Hover information. ### Example ```typescript const hover = workspace.hover("/query.sql", 14); // position over "users" ``` ``` -------------------------------- ### Enable VCS integration in configuration Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/vcs_integration.md Opt-in to the VCS integration by setting `vcs.enabled` to true and specifying `vcs.clientKind` (e.g., "git"). This alone does not enable any features; you must opt-in to specific features. ```json { "vcs": { "enabled": true, "clientKind": "git" } } ``` -------------------------------- ### Valid cast example Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/invalid-cast.md Shows a permitted cast from integer to text, which does not trigger the invalidCast rule. ```sql select 1::text; ``` -------------------------------- ### Configuration: Enable preferBigInt rule Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-big-int.md JSON configuration to enable the preferBigInt rule as an error in the linter settings. ```json { "linter": { "rules": { "preferBigInt": "error" } } } ``` -------------------------------- ### Diagnostic output for missing_table Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/unknown-relation.md Example output from the linter for the invalid query, showing the diagnostic message and location. ```sh code-block.sql:1:15 lint/unknownRelation ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Relation missing_table does not exist. > 1 │ select * from missing_table; │ ^^^^^^^^^^^^^ 2 │ ``` -------------------------------- ### Run Tests and Accept Snapshots Source: https://github.com/supabase-community/postgres-language-server/blob/main/agentic/port_eugene_rules.md Command to run tests and accept snapshot changes for the pgls_analyser crate. ```bash cargo insta test -p pgls_analyser --accept ``` -------------------------------- ### CLI Usage Commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/AGENTS.md Run the CLI binary to check a SQL file, either via cargo or the built binary. ```bash cargo run -p pgls_cli -- check file.sql # or after building: ./target/release/postgres-language-server check file.sql ``` -------------------------------- ### Extends configuration with JSONC Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md Lists configuration files to inherit from, applied left to right. The declaring file's settings take precedence. Paths starting with ~/ resolve to home, . or .jsonc resolve relative to the file, others resolve as packages. ```jsonc { "extends": [ // relative to this file "./shared/base.jsonc", // relative to your home directory "~/.config/postgres-language-server/postgres-language-server.jsonc", // a package in node_modules "@acme/pgls-config" ] } ``` -------------------------------- ### Diagnostic output for assignmentTypeMismatch Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/assignment-type-mismatch.md Example output from the linter showing the error message and location for the invalid insert. ```sh code-block.sql:2:1 lint/assignmentTypeMismatch ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Column "qty" is of type integer but expression is of type timestamp without time zone. 1 │ create table typecheck_assignment (qty integer); > 2 │ insert into typecheck_assignment values (timestamp '2020-01-01'); │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 │ i You will need to rewrite or cast the expression. ``` -------------------------------- ### Configuring linter rules with options Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md Shows how to set a rule to a simple level or provide options. The preferBigInt rule accepts options checkInt (default true) and checkSmallint (default true). ```jsonc "linter": { "rules": { "banDropColumn": "off", // simple level: "off" | "info" | "warn" | "error" "preferBigInt": { // or with options "level": "warn", "options": { "checkInt": true, "checkSmallint": false } } } } ``` -------------------------------- ### Diagnostic output for insertColumnMismatch Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/insert-column-mismatch.md Example output from the linter showing the error message and location for the invalid INSERT statement. ```sh code-block.sql:2:1 lint/insertColumnMismatch ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × INSERT has more target columns than expressions. 1 │ create table users (id int8, name text); > 2 │ insert into users (id, name) values (1); │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 │ i Expected 2 values, found 1. ``` -------------------------------- ### Print tree-sitter tree for an SQL query Source: https://github.com/supabase-community/postgres-language-server/blob/main/AGENTS.md Create a file with an SQL query and run this command to see the tree-sitter tree, which helps debug and implement features. ```bash just tree-print ``` -------------------------------- ### Set up a web worker for the Postgres Language Server Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/browser.md Creates a web worker that hosts the language server. It imports createLanguageServer from the WASM LSP package, handles incoming messages with handleMessage, and posts each outgoing message back. It also signals the main thread when the WASM module is loaded. ```TypeScript // pgls-worker.ts import { createLanguageServer } from "@postgres-language-server/wasm/lsp"; const languageServer = createLanguageServer(); self.onmessage = async (event: MessageEvent) => { const lsp = await languageServer; for (const message of lsp.handleMessage(event.data)) { self.postMessage(message); } }; // Signal the main thread that the WASM module is loaded languageServer.then(() => self.postMessage({ type: "ready" })); ``` -------------------------------- ### Valid: ALTER TABLE with timestamptz Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-timestamptz.md This SQL example alters a column to type timestamptz, which is valid and does not trigger the preferTimestamptz diagnostic. ```sql ALTER TABLE app.users ALTER COLUMN created_ts TYPE timestamptz; ``` -------------------------------- ### Enable postgres_lsp on Neovim 0.11+ Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/ide_setup.md For Neovim 0.11 and later, enable the built-in LSP client with this Lua command. ```lua vim.lsp.enable('postgres_lsp') ``` -------------------------------- ### Valid: CREATE TABLE with timestamptz Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-timestamptz.md This SQL example creates a table with a timestamptz column, which is valid and does not trigger the preferTimestamptz diagnostic. ```sql CREATE TABLE app.users ( created_ts timestamptz ); ``` -------------------------------- ### Run tests and generate snapshots Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Commands to run the rules tests, accept new snapshots, and review snapshots interactively. ```shell # Run tests and generate snapshots cargo test -p pgls_analyser --test rules_tests # Review and accept new/changed snapshots cargo insta test --accept # Or review snapshots interactively cargo insta review ``` -------------------------------- ### Include SQL files via files.include configuration Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/configuration.md Uses the files.include field to specify glob patterns for files to process. Paths and globs are resolved relative to the configuration file's folder, except when extended by another configuration. This example includes only .sql files inside the sql/ folder. ```json { "files": { "include": ["sql/**/*.sql"] } } ``` -------------------------------- ### Valid function call example Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/function-argument-mismatch.md Shows a function definition and a call with a matching argument type (integer) that does not trigger the diagnostic. ```sql create function example_fn(value integer) returns integer language sql as 'select value'; select example_fn(1); ``` -------------------------------- ### Run tests Source: https://github.com/supabase-community/postgres-language-server/blob/main/CONTRIBUTING.md Commands to run all tests, a single crate's tests, and doc tests. Use `just test`, `just test-crate pgls_lsp`, and `just test-doc`. ```bash just test # all tests just test-crate pgls_lsp # a single crate just test-doc # doc tests ``` -------------------------------- ### Invalid cast diagnostic output Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/invalid-cast.md Output from the linter for the invalid cast example, showing the error message and the location of the cast. ```sh code-block.sql:1:30 lint/invalidCast ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Cannot cast type timestamp without time zone to integer. > 1 │ select timestamp '2020-01-01'::integer; │ ^^^^^^^^^ 2 │ ``` -------------------------------- ### Build WASM and TypeScript for PostgreSQL Language Server Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Build the WASM binary using the build script with the --release flag, then build the TypeScript package with bun. Requires the Emscripten SDK. ```bash # Build WASM ./crates/pgls_wasm/build-wasm.sh --release # Build TypeScript cd packages/@postgres-language-server/wasm bun run build ``` -------------------------------- ### Invalid cast example Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/invalid-cast.md Shows a cast from timestamp to integer that is not permitted, triggering the lint/invalidCast diagnostic with Postgres error 42846. ```sql select timestamp '2020-01-01'::integer; ``` -------------------------------- ### Invalid SQL example for assignmentTypeMismatch Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/assignment-type-mismatch.md Shows a failing insert that assigns a timestamp to an integer column, triggering the lint diagnostic. ```sql create table typecheck_assignment (qty integer); insert into typecheck_assignment values (timestamp '2020-01-01'); ``` -------------------------------- ### Create and use the language server with createLanguageServer Source: https://github.com/supabase-community/postgres-language-server/blob/main/packages/@postgres-language-server/wasm/README.md Initializes the language server and handles an LSP message, returning an array of outgoing messages. Use this for Monaco editor integration with monaco-languageclient or any LSP-compatible editor. ```typescript import { createLanguageServer } from "@postgres-language-server/wasm/lsp"; const lsp = await createLanguageServer(); // Handle LSP messages const responses = lsp.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { capabilities: {} }, }); // responses is an array of outgoing messages for (const msg of responses) { // Send to client... } ``` -------------------------------- ### Valid SQL example for ambiguousColumn Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/ambiguous-column.md Shows the corrected query that qualifies the column reference with the table name to avoid the ambiguity. ```sql create table users (id int8, name text); create table posts (id int8, user_id int8); select users.id from users join posts on posts.user_id = users.id; ``` -------------------------------- ### Diagnostic output for ambiguousColumn Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/ambiguous-column.md Example output from the linter showing the diagnostic message for the invalid query, including the location and explanation. ```sh code-block.sql:3:8 lint/ambiguousColumn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Column reference id is ambiguous. 1 │ create table users (id int8, name text); 2 │ create table posts (id int8, user_id int8); > 3 │ select id from users join posts on posts.user_id = users.id; │ ^^ 4 │ i It matches columns of users, posts. ``` -------------------------------- ### Code Quality Commands Source: https://github.com/supabase-community/postgres-language-server/blob/main/AGENTS.md Format code, lint the codebase, fix linting issues, and run the full ready check before committing. ```bash # Format all code (Rust, TOML, JS/TS) just format # Lint entire codebase just lint # or: cargo clippy && cargo run -p rules_check && bun oxlint packages/ # Fix linting issues just lint-fix # Full ready check (run before committing) just ready ``` -------------------------------- ### Valid: CREATE TABLE with bigserial type Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-big-int.md This SQL example shows a valid usage of the bigserial type, which does not trigger the preferBigInt diagnostic. ```sql CREATE TABLE users ( id bigserial ); ``` -------------------------------- ### Pass migrationsDir and after via CLI flags Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/checking_migrations.md Alternative to configuration file, passing the same options directly to the `check` command. ```sh postgres-language-server check supabase/migrations --migrations-dir="supabase/migrations" --after=20250301120000 ``` -------------------------------- ### GitHub Actions workflow for linting with a Postgres service Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/guides/continuous_integration.md Sets up a Postgres service container and runs `postgres-language-server check sql/` to enable more advanced checks that require a database. The service uses the `postgres:latest` image with default credentials. ```yaml jobs: lint: runs-on: ubuntu-latest services: postgres: image: postgres:latest env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432:5432 steps: - uses: actions/checkout@v4 - uses: supabase-community/postgres-language-server-cli-action@main with: version: latest - run: postgres-language-server check sql/ ``` -------------------------------- ### Valid: CREATE TABLE with bigint type Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/prefer-big-int.md This SQL example shows a valid usage of the bigint type, which does not trigger the preferBigInt diagnostic. ```sql CREATE TABLE users ( id bigint ); ``` -------------------------------- ### Retrieve rule options with ctx.options() Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Shows how a rule can access its options via ctx.options(). ```rust let options = ctx.options(); ``` -------------------------------- ### Diagnostic output for invalid SQL Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/operator-type-mismatch.md The diagnostic output produced by the linter for the invalid example. It shows the error message and the location of the issue. ```sh code-block.sql:1:10 lint/operatorTypeMismatch ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Operator does not exist: integer + timestamp without time zone > 1 │ select 1 + timestamp '2020-01-01'; │ ^ 2 │ i No operator matches the given name and argument types. You might need to add explicit type casts. ``` -------------------------------- ### Stage and commit changes Source: https://github.com/supabase-community/postgres-language-server/blob/main/crates/pgls_analyser/CONTRIBUTING.md Commands to stage and commit your rule implementation. ```shell > git add -A > git commit -m 'feat(pgls_analyser): myRuleName' ``` -------------------------------- ### Diagnostic output for banTruncate Source: https://github.com/supabase-community/postgres-language-server/blob/main/docs/reference/rules/ban-truncate.md Example output from the linter when banTruncate is triggered, showing the error message and suggestion to use DELETE with a WHERE clause. ```sh code-block.sql:1:1 lint/banTruncate ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ × Truncating a table removes all rows and can cause data loss. > 1 │ truncate my_table; │ ^^^^^^^^^^^^^^^^^^ 2 │ i Use DELETE with a WHERE clause instead, or ensure this is intentional and not part of a migration. ```