Files
2026-11-20 18:22:13 +03:00

14 KiB
Raw Permalink Blame History

omg-pgs

A database-aware PostgreSQL language server and REST query runner in a single binary. The language server speaks LSP over stdin/stdout; the REST API listens on an HTTP port.

omg-pgs reads the database it should talk to from the SQL file itself:

-- @database: postgresql://user:password@localhost:5432/main

SELECT * FROM users;

All diagnostics, completion, hover and highlighting for the following statements are resolved against that exact database. A file can switch databases as often as needed:

-- @database: postgresql://user:password@localhost/main
SELECT id, email FROM users;

-- @database: postgresql://user:password@localhost/analytics
SELECT * FROM events;

The statements after the second directive are checked and completed against analytics, not main.

If a file has no -- @database: directive, the server deliberately does nothing with it: no connection is opened, no diagnostics are published, and no completion or hover is returned.

Table of contents

Features

Feature Description
Connection diagnostics An invalid or unreachable database URL is underlined in red, exactly on the URL.
Syntax diagnostics Statements are parsed with libpg_query, PostgreSQL's own parser.
Semantic diagnostics Valid syntax is checked with PREPARE, which resolves tables, columns and functions without executing the statement.
Completion Tables, views, schemas, columns, functions, aliases and keywords.
Hover Table definitions with column types, column types/defaults, function signatures, schemas and the directive URL.
Semantic highlighting Keywords, strings, numbers, comments, operators, tables, columns, functions and schemas.
Formatting Whitespace-only formatting with the PostgreSQL dialect.
Document symbols One outline entry per SQL statement.
REST query execution Execute the statement at a given file/line and receive JSON or CSV.

The project is not a reimplementation of every feature of postgres-language-server. It focuses on the per-file/per-statement database context described above. See Limitations for a precise list.

Installation

Requirements:

  • Rust 1.85 or newer;
  • a C compiler;
  • Clang / libclang (used by bindgen);
  • protoc (used while building pg_query);
  • CMake is not required by this crate but is commonly needed for PostgreSQL tooling.

Debian/Ubuntu:

sudo apt-get install build-essential clang libclang-dev protobuf-compiler cmake

Arch Linux:

sudo pacman -S base-devel clang protobuf cmake

Build:

cargo build --release

The binary is target/release/omg-pgs.

Running

The LSP server uses stdin/stdout and is normally spawned by an editor. The only required argument is the REST port:

./target/release/omg-pgs --rest-port 8080

Stdout is reserved for LSP protocol messages; logs are written to stderr. The REST API binds to 127.0.0.1. Use -v for debug logs and -vv for trace logs:

./target/release/omg-pgs --rest-port 8080 -v

RUST_LOG overrides the default filter:

RUST_LOG=omg_pgs=debug ./target/release/omg-pgs --rest-port 8080

If the REST port is already in use, the process logs a warning and continues in LSP-only mode. This keeps multiple editor instances usable: the first instance owns the REST port, the others still get a working language server.

When an editor completes the LSP handshake and later closes the session, the process exits and stops the REST server. For headless REST usage (stdin closed before initialization), the process keeps the REST API running until Ctrl+C. Connection strings are redacted in logs.

Database directives

A directive is a line comment that starts with @database::

-- @database: postgresql://user:password@localhost:5432/main

Rules:

  • The directive must be a -- line comment.
  • The rest of the line, after optional whitespace, is the connection URL.
  • The directive applies to every statement after it until the next directive.
  • A directive must be placed before the statement it should affect.
  • postgres:// and postgresql:// URLs are accepted.
  • For compatibility with the original prototype, the misspelled @databse: is accepted too. New files should use @database:.
  • A file without any directive is ignored by all database-backed features.

A directive can appear anywhere between statements, including on the same line as the previous statement's terminating semicolon.

LSP setup

The language server speaks the standard LSP protocol over stdin/stdout with Content-Length framing. Spawn the binary from your editor and pass the REST port as an argument. Logs go to stderr, so stdout stays clean for the protocol.

The server advertises:

  • full document synchronization, including save notifications;
  • completion with . as a trigger character;
  • hover;
  • full-document semantic tokens;
  • document formatting;
  • document symbols.

Neovim

vim.lsp.start({
  name = "omg-pgs",
  cmd = { "/absolute/path/to/omg-pgs", "--rest-port", "8080" },
  root_dir = vim.fn.getcwd(),
})

VS Code language client

import { TransportKind } from "vscode-languageclient/node";

const serverOptions = {
  command: "/absolute/path/to/omg-pgs",
  args: ["--rest-port", "8080"],
  transport: TransportKind.stdio,
};

Any other editor or client that can spawn a stdio LSP process will work as well.

Each process serves one LSP client. If several editor instances are running, use a different --rest-port for each one that needs the REST API; instances that cannot bind the port still run the LSP in LSP-only mode.

REST API

The REST server exposes two routes:

  • GET /health
  • POST /query

POST /query

Request:

{
  "file": "/absolute/path/to/script.sql",
  "line": 3,
  "format": "json"
}
  • file is a filesystem path. Absolute paths are recommended; relative paths are resolved against the server's working directory.
  • line is a one-based line number. Any line inside a statement selects that statement. If several statements share a line, the first one is selected.
  • format is optional: json (default) or csv. The same value can be supplied as a query parameter, for example ?format=csv. A value in the JSON body takes precedence.

Example:

curl -s http://127.0.0.1:8080/query \
  -H 'content-type: application/json' \
  -d '{"file":"/home/me/script.sql","line":3,"format":"json"}'

JSON response:

{
  "database": "postgresql://postgres:***@localhost:5432/main",
  "line": 3,
  "statement": "SELECT id, email FROM users ORDER BY id;",
  "columns": ["id", "email"],
  "rows": [["1", "alice@example.com"], ["2", "bob@example.com"]],
  "row_count": 2,
  "rows_affected": 2,
  "statement_type": "SELECT",
  "elapsed_ms": 3
}

CSV response:

curl -s 'http://127.0.0.1:8080/query?format=csv' \
  -H 'content-type: application/json' \
  -d '{"file":"/home/me/script.sql","line":3}'
id,email
1,alice@example.com
2,bob@example.com

Notes:

  • All values are returned in PostgreSQL's text representation.
  • SQL NULL is null in JSON and an empty field in CSV.
  • The query must be preceded by a -- @database: directive.
  • Queries are executed with a fresh connection, so a long REST query does not block the language server.
  • The client-side timeout is 60 seconds. When the timeout fires, the statement may continue running on the server until PostgreSQL notices the closed connection.

Errors:

Status Meaning
400 Bad request, unreadable file, no statement on the line, no directive, or SQL error.
502 The database could not be reached.
504 The query exceeded the 60 second timeout.
500 Internal error (for example, CSV encoding).

Error body:

{
  "error": "relation \"missing_table\" does not exist",
  "code": "42P01",
  "position": 15
}

code is the SQLSTATE when PostgreSQL provided one. position is the server-reported one-based character position in the statement.

Diagnostics

Diagnostics have three sources:

  1. Connection — the URL in the directive is parsed and a connection is attempted. Failures are reported as errors on the URL range. Successful connections produce no connection diagnostic.
  2. Syntax — every statement is parsed with libpg_query (PostgreSQL 18’s grammar). Syntax errors are reported as errors.
  3. Semantic — statements with valid syntax are sent to the server as PREPARE omg_pgs_check AS <statement> and deallocated immediately. This resolves relation names, column names, function names and types without executing the statement. The server’s error position is mapped back to the document.

The design goal is that a statement shown without diagnostics must be executable through the REST API. Diagnostics are therefore conservative:

  • Utility statements and DDL are syntax-checked, but not semantically checked, because PostgreSQL does not allow PREPARE for them.
  • If parameter types cannot be inferred (SQLSTATE 42P18), semantic checking is skipped instead of producing a false positive.
  • When a database connection fails, query diagnostics for that database are skipped so that the only error is the URL itself.
  • If the database is reachable but a table is missing, that is a real error and is underlined.

Files without a directive produce no diagnostics, completion, hover, semantic tokens, formatting or symbols.

How it works

flowchart LR
    Editor[LSP client] -->|stdio| LSP[LSP backend]
    Caller[REST client] -->|HTTP| REST[REST API]
    LSP --> Core[SQL core]
    Core --> Parser[libpg_query]
    LSP --> Manager[Database manager]
    Manager --> Schema[Catalog cache]
    Manager --> Validate[PREPARE validation]
    REST --> Exec[Fresh connection]
    Schema --> PG[(PostgreSQL)]
    Validate --> PG
    Exec --> PG

Source layout:

Path Purpose
src/sql/lexer.rs PostgreSQL-aware lexer used for splitting and editing features.
src/sql/document.rs Directive parsing, statement splitting, line-to-statement lookup.
src/sql/analysis.rs Aliases, clause detection, identifier helpers, error-token location.
src/db/ Connections, TLS, catalog introspection, PREPARE validation, execution.
src/lsp/ LSP transport, diagnostics, completion, hover, semantic tokens, formatting, symbols.
src/rest.rs Axum REST server and JSON/CSV rendering.
src/position.rs UTF-8 byte offset ↔ LSP UTF-16 position mapping.

Catalog metadata is loaded per database and cached. Caches are invalidated on textDocument/didSave; connections are reused by the language server. Formatting is whitespace-only, so it does not rewrite keyword case or literal contents.

Limitations

  • LSP transport is stdio only. There is no TCP mode.
  • Formatting does not support range formatting.
  • Semantic diagnostics are not available for DDL/utility statements.
  • Semantic checks reflect the database's current state. Objects created by earlier statements in the same file are not applied to the validation connection, so a SELECT on a table that the file creates but the database does not yet contain is still reported as missing.
  • Type checking is limited to what PostgreSQL's parse analysis reports during PREPARE; there is no independent typechecker, linter rule set, PL/pgSQL analysis, inlay hints, rename, or code actions.
  • Semantic token classification is heuristic for identifiers, although keywords, strings, numbers, comments and operators come from libpg_query's scanner.
  • TLS uses rustls with Mozilla's root store (webpki-roots). Servers with self-signed certificates are not supported yet.
  • The REST API has no authentication and executes arbitrary SQL. It is bound to localhost and must not be exposed to an untrusted network.
  • Document synchronization is full-text, not incremental.

Security

  • The LSP uses stdin/stdout. The REST API binds to 127.0.0.1.
  • Passwords are replaced with *** in logs and REST responses via redact_url.
  • The REST endpoint reads arbitrary files that the process can access and executes arbitrary SQL with the credentials from the directive. Run it only on a trusted machine.
  • TLS certificates are verified. There is currently no option to trust a self-signed certificate.

Development

cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test --all-targets

The unit tests do not require a database. Opt-in integration tests run against a real PostgreSQL server:

OMG_PGS_TEST_DATABASE_URL=postgresql://user:password@localhost:5432/db \
    cargo test --test database

To test against a real PostgreSQL instance, create a database with the tables used in your SQL file, run the server, and point the directive at it. End-to-end testing during development used an embedded PostgreSQL instance with two databases and verified:

  • JSON and CSV responses;
  • SQL error propagation (42P01);
  • missing-directive and missing-statement errors;
  • connection-failure diagnostics on the URL range;
  • completion, hover, semantic tokens and formatting;
  • switching between two databases in one file.

See AGENTS.md for the project’s engineering rules and a map for coding agents.

License

MIT. See LICENSE.