Add PostgreSQL LSP server with directive-scoped REST query API
CI / test (push) Waiting to run

This commit is contained in:
2026-11-20 18:22:13 +03:00
commit 4ecf11af48
32 changed files with 8734 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.{md,yml,yaml,sql,toml}]
indent_size = 2
+40
View File
@@ -0,0 +1,40 @@
name: CI
on:
push:
pull_request:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v4
- name: Install native build dependencies
run: |
sudo apt-get update
sudo apt-get install -y build-essential clang libclang-dev protobuf-compiler cmake
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Cache Rust artifacts
uses: Swatinem/rust-cache@v2
- name: Check formatting
run: cargo fmt --all -- --check
- name: Run Clippy
run: cargo clippy --all-targets -- -D warnings
- name: Run tests
run: cargo test --all-targets
- name: Build release binary
run: cargo build --release
+6
View File
@@ -0,0 +1,6 @@
/target
*.log
.env
.idea/
.vscode/
.DS_Store
+171
View File
@@ -0,0 +1,171 @@
# Agent instructions
This file describes the engineering rules, architecture, and workflow for
coding agents working on `omg-pgs`.
## What this project is
`omg-pgs` is a single Rust binary that contains:
1. a database-aware PostgreSQL language server (LSP over stdin/stdout);
2. a REST API that executes the SQL statement located at a file and line.
The database used for a statement is selected by a line comment in the SQL
file:
```sql
-- @database: postgresql://user:password@localhost:5432/main
SELECT * FROM users;
```
A file may contain any number of directives. Each directive changes the
database for all following statements.
## Non-negotiable behavior
These invariants define the product. Do not change them without an explicit
request:
1. **Directive-scoped work.** A statement is connected to, checked against,
completed from, and executed against the database of the last non-empty
`-- @database:` directive before it. Never fall back to a default database.
2. **No directive means no database work.** If a document contains no
directive, do not open connections, do not publish diagnostics, and return
no completion/hover/semantic tokens/formatting/symbols. The REST API must
return an error.
3. **No false-positive diagnostics.** If the LSP shows no diagnostics for a
statement, the REST API must be able to execute it. Use `libpg_query` for
syntax and `PREPARE` for name/type resolution. Do not invent diagnostics
from heuristics in the lexer or catalog cache.
4. **Connection failure is shown on the URL.** If a directed database cannot
be reached, underline the URL range in red and skip query diagnostics for
that database. A successful connection produces no connection diagnostic.
5. **Passwords never leak.** Use `redact_url` for logs and API responses. Do
not log raw connection strings.
6. **Statement context follows directives.** Directives apply from their
position forward. Comments before the first significant token are not part
of the statement text passed to PostgreSQL.
7. **REST port is explicit; LSP is stdio.** `--rest-port` is required and the
REST listener binds to `127.0.0.1`. The LSP uses stdin/stdout; stdout must
contain only LSP protocol frames. If the REST port cannot be bound, log a
warning and keep the LSP running in LSP-only mode.
8. **English only.** Code comments, doc comments, diagnostics, documentation,
commit messages, and agent-facing text are written in English.
## Architecture map
| Path | Responsibility |
| --- | --- |
| `src/sql/lexer.rs` | PostgreSQL-aware lexer that keeps working on malformed SQL. Used for splitting and editing features. |
| `src/sql/document.rs` | Directive parsing, statement splitting, line/offset lookup, REST query selection. |
| `src/sql/analysis.rs` | Alias extraction, clause detection, identifier helpers, `libpg_query` error-token location. |
| `src/db/connection.rs` | URL validation, rustls connector, connection setup, URL redaction. |
| `src/db/schema.rs` | `pg_catalog` introspection and schema lookup helpers. |
| `src/db/validate.rs` | Classification of `PREPARE` errors and error positions. |
| `src/db/execute.rs` | REST query execution over the simple query protocol. |
| `src/db/mod.rs` | `DbManager`, per-URL connection, schema cache, validation. |
| `src/lsp/backend.rs` | Stdio transport, document state, request handlers. |
| `src/lsp/diagnostics.rs` | Connection, syntax and semantic diagnostics. |
| `src/lsp/completion.rs` | Schema-aware completion. |
| `src/lsp/hover.rs` | Schema-aware hover. |
| `src/lsp/semantic_tokens.rs` | `libpg_query` scanner + schema classification + delta encoding. |
| `src/lsp/formatting.rs` | Whole-document whitespace formatting. |
| `src/lsp/symbols.rs` | One outline entry per statement. |
| `src/rest.rs` | Axum router, JSON/CSV rendering, REST errors. |
| `src/position.rs` | UTF-8 byte offsets ↔ LSP UTF-16 positions. |
Keep the pure SQL core independent of I/O so it can be unit tested without a
database. Database-dependent logic belongs in `src/db`.
## Editing rules
- Keep changes minimal and consistent with the surrounding code.
- Public items need doc comments when their purpose is not obvious.
- Business errors use `anyhow::Result` with `.context(...)`; domain errors use
`thiserror`.
- Production code must not use `unwrap`, `expect`, `panic!`, or
`unreachable!` on user input. Test code may use them.
- Do not log or return unredacted connection strings.
- Prefer existing dependencies. Adding a dependency requires a concrete
justification.
- Do not add comments that restate code. Explain non-obvious constraints.
- Preserve the no-diagnostics-means-executable invariant when changing parsing
or validation.
- Semantic checks use the live database state. Do not silently start executing
DDL from the document to make later statements validate; that would be a
side-effecting validation step.
- When behavior changes, update `README.md` and this file.
## Common tasks
### Add a completion feature
1. Add a pure helper or branch in `src/lsp/completion.rs`.
2. Use `analysis::Aliases` for alias-aware scopes.
3. Add a unit test with a hand-built `Schema`; never require a DB in unit tests.
4. If a new clause changes context detection, update `analysis::current_clause`
and its tests.
### Add a diagnostic
1. Decide whether it is authoritative. Syntax must come from `libpg_query`;
name/type errors must come from the server (`PREPARE`).
2. Map every error to a document byte span using `LineIndex`.
3. Add tests for both the valid and invalid cases.
4. Do not add heuristic diagnostics that could reject a valid query.
### Change directive or statement parsing
1. Update `src/sql/document.rs`.
2. Cover semicolons in strings, quoted identifiers, dollar strings, nested
block comments, and line comments in tests.
3. Verify directive assignment across multiple databases and CRLF files.
4. Update the REST selection tests.
### Change REST output
1. Update `src/rest.rs` for both JSON and CSV.
2. Keep values as PostgreSQL text; represent `NULL` as JSON `null` and an
empty CSV field.
3. Keep the 60-second timeout and the documented status codes.
4. Add an Axum `oneshot` test for request-validation paths.
## Validation
Before finishing a change, run:
```bash
cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test --all-targets
```
Native build prerequisites for `pg_query` are a C compiler, libclang, and
`protoc`.
Unit tests must pass without a PostgreSQL server. Opt-in integration tests
run when `OMG_PGS_TEST_DATABASE_URL` is set:
```bash
OMG_PGS_TEST_DATABASE_URL=postgresql://user:password@localhost:5432/db \
cargo test --test database
```
For end-to-end changes
involving real metadata, validation, or query execution, test against a local
PostgreSQL instance with at least two databases and verify:
- per-statement database switching in one file;
- connection error highlighting on the directive URL;
- a missing table producing a server-side diagnostic with SQLSTATE;
- JSON and CSV REST output;
- LSP completion, hover, semantic tokens, formatting, and shutdown.
Do not claim that a test passed unless it was actually run and the output was
seen.
## Scope discipline
Do not fix unrelated bugs, reformat unrelated files, or broaden the change.
If a limitation is intentional (DDL semantic checks, no inlay hints, stdio-only
transport), document it instead of silently adding a large subsystem.
Generated
+2500
View File
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
[package]
name = "omg-pgs"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"
description = "Database-aware PostgreSQL language server and REST query runner"
license = "MIT"
readme = "README.md"
keywords = ["postgres", "postgresql", "lsp", "language-server", "sql"]
categories = ["development-tools", "database"]
[lib]
name = "omg_pgs"
path = "src/lib.rs"
[[bin]]
name = "omg-pgs"
path = "src/main.rs"
[dependencies]
anyhow = "1.0"
axum = "0.8"
clap = { version = "4.5", features = ["derive"] }
csv = "1.3"
lsp-types = "0.94"
pg_query = "18.1"
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlformat = "0.5"
thiserror = "2.0"
tokio = { version = "1.40", features = ["full"] }
tokio-postgres = "0.7"
tokio-postgres-rustls = { version = "0.14", features = ["ring", "webpki-roots"] }
tower = "0.4"
tower-lsp = "0.20"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
url = "2.5"
webpki-roots = "1.0"
[dev-dependencies]
tempfile = "3.14"
tower05 = { package = "tower", version = "0.5", features = ["util"] }
http-body-util = "0.1"
[profile.release]
lto = "thin"
strip = true
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 omg-pgs contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+422
View File
@@ -0,0 +1,422 @@
# 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:
```sql
-- @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:
```sql
-- @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](#features)
- [Installation](#installation)
- [Running](#running)
- [Database directives](#database-directives)
- [LSP setup](#lsp-setup)
- [REST API](#rest-api)
- [Diagnostics](#diagnostics)
- [How it works](#how-it-works)
- [Limitations](#limitations)
- [Security](#security)
- [Development](#development)
- [License](#license)
## 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](https://github.com/supabase-community/postgres-language-server).
It focuses on the per-file/per-statement database context described above.
See [Limitations](#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:
```bash
sudo apt-get install build-essential clang libclang-dev protobuf-compiler cmake
```
Arch Linux:
```bash
sudo pacman -S base-devel clang protobuf cmake
```
Build:
```bash
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:
```bash
./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:
```bash
./target/release/omg-pgs --rest-port 8080 -v
```
`RUST_LOG` overrides the default filter:
```bash
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:`:
```sql
-- @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
```lua
vim.lsp.start({
name = "omg-pgs",
cmd = { "/absolute/path/to/omg-pgs", "--rest-port", "8080" },
root_dir = vim.fn.getcwd(),
})
```
### VS Code language client
```ts
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:
```json
{
"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:
```bash
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:
```json
{
"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:
```bash
curl -s 'http://127.0.0.1:8080/query?format=csv' \
-H 'content-type: application/json' \
-d '{"file":"/home/me/script.sql","line":3}'
```
```csv
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:
```json
{
"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
```mermaid
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
```bash
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:
```bash
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](AGENTS.md) for the project’s engineering rules and a map for
coding agents.
## License
MIT. See [LICENSE](LICENSE).
+16
View File
@@ -0,0 +1,16 @@
-- The server connects to the database named in the nearest directive.
-- Change these URLs to match your PostgreSQL instance.
-- @database: postgresql://postgres:postgres@localhost:5432/postgres
-- Try completion after FROM, hover over users, or place the cursor on the URL.
SELECT id, email
FROM users
ORDER BY id;
-- A second directive switches the database for everything below it.
-- @database: postgresql://postgres:postgres@localhost:5432/analytics
SELECT name, price
FROM widgets
ORDER BY price DESC;
+24
View File
@@ -0,0 +1,24 @@
//! Command-line interface.
use clap::Parser;
/// A database-aware PostgreSQL language server with a companion REST API.
///
/// The language server speaks LSP over stdin/stdout, so it can be spawned by
/// editors directly. The REST API listens on the explicitly configured port.
#[derive(Debug, Parser)]
#[command(
name = "omg-pgs",
version,
about = "Database-aware PostgreSQL language server and REST query runner",
long_about = None
)]
pub struct Cli {
/// TCP port for the REST API (bound to 127.0.0.1).
#[arg(long, value_name = "PORT", value_parser = clap::value_parser!(u16).range(1..))]
pub rest_port: u16,
/// Increase log verbosity: -v for debug, -vv for trace.
#[arg(short, long, action = clap::ArgAction::Count)]
pub verbose: u8,
}
+122
View File
@@ -0,0 +1,122 @@
//! Connection string handling and TLS setup.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use tokio_postgres::{Client, Config};
use tokio_postgres_rustls::MakeRustlsConnect;
use url::Url;
/// Parses and validates a PostgreSQL connection URL.
///
/// Only `postgres://` and `postgresql://` URLs are accepted, matching the
/// directive syntax. A default connect timeout is applied when the URL does not
/// specify one.
pub fn parse_config(url: &str) -> Result<Config> {
let trimmed = url.trim();
if trimmed.is_empty() {
bail!("database URL is empty");
}
let parsed = Url::parse(trimmed).context("invalid database URL")?;
match parsed.scheme() {
"postgres" | "postgresql" => {}
scheme => {
bail!("unsupported URL scheme `{scheme}`; expected `postgresql://` or `postgres://`")
}
}
let mut config: Config = trimmed
.parse()
.context("invalid PostgreSQL connection string")?;
config.application_name("omg-pgs");
if config.get_connect_timeout().is_none() {
config.connect_timeout(Duration::from_secs(10));
}
Ok(config)
}
/// Opens a connection and drives its background task.
///
/// A connection in `tokio-postgres` only makes progress while the returned
/// future is being polled, so the task is spawned here and kept alive as long as
/// the client is alive.
pub async fn connect(config: &Config) -> Result<Client> {
let (client, connection) = config
.connect(tls_connector())
.await
.context("could not connect to PostgreSQL")?;
tokio::spawn(async move {
if let Err(error) = connection.await {
tracing::debug!(error = %error, "PostgreSQL connection closed");
}
});
Ok(client)
}
fn tls_connector() -> MakeRustlsConnect {
let mut roots = rustls::RootCertStore::empty();
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
MakeRustlsConnect::new(config)
}
/// Hides the password in a connection URL before it is logged or returned.
pub fn redact_url(url: &str) -> String {
let trimmed = url.trim();
if let Ok(mut parsed) = Url::parse(trimmed) {
if parsed.password().is_some() {
let _ = parsed.set_password(Some("***"));
}
return parsed.to_string();
}
// Fallback for strings that are not valid URLs. Mask everything between
// the first credential colon and the final `@` so that a malformed
// password containing `:` is not partially exposed.
if let Some(at) = trimmed.rfind('@') {
if let Some(scheme_end) = trimmed.find("://") {
let credentials = scheme_end + 3;
if let Some(colon) = trimmed[credentials..at].find(':') {
let colon = credentials + colon;
return format!("{}:***{}", &trimmed[..colon], &trimmed[at..]);
}
}
}
trimmed.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_postgres_urls() {
let config = parse_config("postgresql://user:secret@localhost:5432/main").unwrap();
assert_eq!(config.get_dbname(), Some("main"));
assert_eq!(config.get_user(), Some("user"));
}
#[test]
fn rejects_other_schemes() {
assert!(parse_config("mysql://localhost/db").is_err());
assert!(parse_config("").is_err());
}
#[test]
fn redacts_passwords() {
assert_eq!(
redact_url("postgresql://user:secret@localhost:5432/main"),
"postgresql://user:***@localhost:5432/main"
);
assert_eq!(
redact_url("postgresql://localhost/main"),
"postgresql://localhost/main"
);
assert_eq!(
redact_url("postgresql://user:pa:ss@host/db extra"),
"postgresql://user:***@host/db%20extra"
);
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Query execution for the REST API.
//!
//! The REST endpoint intentionally uses a fresh connection per request: long
//! running user queries must not block the language server's validation
//! connection.
use std::time::Duration;
use tokio_postgres::SimpleQueryMessage;
use tokio_postgres::error::ErrorPosition;
use super::connection;
use super::parse_config;
use crate::sql::lexer::{TokenKind, tokenize};
#[derive(Debug, Clone, Default)]
pub struct ExecOutcome {
/// Column names of the result, if the statement returned rows.
pub columns: Vec<String>,
/// Row values. `None` represents SQL `NULL`.
pub rows: Vec<Vec<Option<String>>>,
/// Number of rows selected or affected, when the server reported it.
pub rows_affected: Option<u64>,
/// Leading statement keyword, for display purposes.
pub kind: Option<String>,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ExecError {
#[error("invalid database URL: {0}")]
InvalidUrl(String),
#[error("could not connect to database: {0}")]
Connect(String),
#[error("query failed: {message}")]
Sql {
message: String,
code: Option<String>,
position: Option<u32>,
},
#[error("query timed out after {0:?}")]
Timeout(Duration),
}
/// Runs a single statement and returns its result as text values.
///
/// The simple query protocol is used so that any statement (including DDL)
/// can be executed without knowing its result types. All values are returned
/// in PostgreSQL's text representation.
pub async fn execute(url: &str, sql: &str, timeout: Duration) -> Result<ExecOutcome, ExecError> {
let config = parse_config(url).map_err(|error| ExecError::InvalidUrl(format!("{error:#}")))?;
let client = connection::connect(&config)
.await
.map_err(|error| ExecError::Connect(format!("{error:#}")))?;
let messages = tokio::time::timeout(timeout, client.simple_query(sql))
.await
.map_err(|_| ExecError::Timeout(timeout))?
.map_err(classify_sql_error)?;
let mut outcome = ExecOutcome {
kind: statement_kind(sql),
..ExecOutcome::default()
};
for message in messages {
match message {
SimpleQueryMessage::RowDescription(columns) => {
outcome.columns = columns
.iter()
.map(|column| column.name().to_string())
.collect();
}
SimpleQueryMessage::Row(row) => {
if outcome.columns.is_empty() {
outcome.columns = row
.columns()
.iter()
.map(|column| column.name().to_string())
.collect();
}
let mut values = Vec::with_capacity(row.len());
for index in 0..row.len() {
values.push(row.get(index).map(str::to_string));
}
outcome.rows.push(values);
}
SimpleQueryMessage::CommandComplete(affected) => {
outcome.rows_affected = Some(affected);
}
_ => {}
}
}
Ok(outcome)
}
fn classify_sql_error(error: tokio_postgres::Error) -> ExecError {
match error.as_db_error() {
Some(db_error) => ExecError::Sql {
message: db_error.message().to_string(),
code: Some(db_error.code().code().to_string()),
position: match db_error.position() {
Some(ErrorPosition::Original(position)) => Some(*position),
Some(ErrorPosition::Internal { .. }) | None => None,
},
},
None => ExecError::Sql {
message: error.to_string(),
code: None,
position: None,
},
}
}
fn statement_kind(sql: &str) -> Option<String> {
tokenize(sql)
.into_iter()
.find(|token| token.kind == TokenKind::Word)
.map(|token| token.text(sql).to_ascii_uppercase())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_statement_kind() {
assert_eq!(statement_kind("select 1").as_deref(), Some("SELECT"));
assert_eq!(
statement_kind(" /* c */ INSERT INTO t VALUES (1)").as_deref(),
Some("INSERT")
);
}
#[test]
fn rejects_invalid_url_before_connecting() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let error = runtime
.block_on(execute("not-a-url", "SELECT 1", Duration::from_secs(1)))
.unwrap_err();
assert!(matches!(error, ExecError::InvalidUrl(_)));
}
}
+236
View File
@@ -0,0 +1,236 @@
//! Database connections, schema cache and server-side validation.
mod connection;
mod execute;
mod schema;
mod validate;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use tokio::sync::{Mutex, MutexGuard, RwLock};
use tokio_postgres::{Client, Config};
pub use connection::{parse_config, redact_url};
pub use execute::{ExecError, ExecOutcome, execute};
pub use schema::{Column, Function, Schema, Table, TableKind};
pub use validate::{Validation, classify_validation_error};
const VALIDATION_TIMEOUT: Duration = Duration::from_secs(10);
const DEALLOCATE_TIMEOUT: Duration = Duration::from_secs(2);
/// Keeps one shared connection and one schema cache per database URL.
#[derive(Default)]
pub struct DbManager {
databases: RwLock<HashMap<String, Arc<Database>>>,
}
impl DbManager {
pub fn new() -> Self {
Self::default()
}
/// Returns the database entry for `url`, creating it if necessary.
pub async fn database(&self, url: &str) -> Result<Arc<Database>> {
if let Some(database) = self.databases.read().await.get(url).cloned() {
return Ok(database);
}
let config = parse_config(url)?;
let database = Arc::new(Database::new(url.to_string(), config));
let mut databases = self.databases.write().await;
Ok(databases.entry(url.to_string()).or_insert(database).clone())
}
pub async fn get(&self, url: &str) -> Option<Arc<Database>> {
self.databases.read().await.get(url).cloned()
}
pub async fn invalidate_schema(&self, url: &str) {
if let Some(database) = self.get(url).await {
database.invalidate_schema().await;
}
}
/// Drops all cached connections. Primarily useful in tests and on shutdown.
pub async fn clear(&self) {
self.databases.write().await.clear();
}
}
/// A lazily connected database with a cached catalog and a dedicated
/// validation connection.
pub struct Database {
url: String,
config: Config,
client: Mutex<Option<Client>>,
schema: RwLock<Option<Arc<Schema>>>,
validation_sequence: AtomicU64,
}
impl Database {
fn new(url: String, config: Config) -> Self {
Self {
url,
config,
client: Mutex::new(None),
schema: RwLock::new(None),
validation_sequence: AtomicU64::new(0),
}
}
pub fn url(&self) -> &str {
&self.url
}
pub fn redacted_url(&self) -> String {
redact_url(&self.url)
}
/// Ensures that a usable connection exists.
pub async fn check_connection(&self) -> Result<()> {
self.client_guard().await.map(|_| ())
}
pub async fn invalidate_schema(&self) {
*self.schema.write().await = None;
}
/// Returns the cached schema, loading it on first use.
///
/// When `refresh` is true the cache is bypassed. If a refresh fails but an
/// older snapshot exists, the old snapshot is returned so that editor
/// features keep working while the connection is unavailable.
pub async fn schema(&self, refresh: bool) -> Result<Arc<Schema>> {
if !refresh {
if let Some(schema) = self.schema.read().await.clone() {
return Ok(schema);
}
}
let mut cached = self.schema.write().await;
if !refresh {
if let Some(schema) = cached.clone() {
return Ok(schema);
}
}
match self.load_schema().await {
Ok(schema) => {
let schema = Arc::new(schema);
*cached = Some(schema.clone());
Ok(schema)
}
Err(error) => {
if let Some(schema) = cached.clone() {
tracing::warn!(
database = %self.redacted_url(),
error = %error,
"schema refresh failed; using cached schema"
);
Ok(schema)
} else {
Err(error)
}
}
}
}
/// Validates a statement with `PREPARE`, which resolves relations, columns
/// and functions without executing the statement.
pub async fn validate(&self, statement: &str) -> Validation {
let sequence = self.validation_sequence.fetch_add(1, Ordering::Relaxed);
let name = format!("omg_pgs_check_{sequence}");
let prefix = format!("PREPARE {name} AS ");
let sql = format!("{prefix}{statement}");
let deallocate = format!("DEALLOCATE {name}");
for attempt in 0..2 {
let mut guard = match self.client_guard().await {
Ok(guard) => guard,
Err(error) => {
return Validation::Skipped(format!("connection unavailable: {error:#}"));
}
};
let result = {
let Some(client) = guard.as_mut() else {
continue;
};
tokio::time::timeout(VALIDATION_TIMEOUT, client.simple_query(&sql)).await
};
match result {
Err(_) => {
return Validation::Skipped("validation timed out".to_string());
}
Ok(Ok(_)) => {
if let Some(client) = guard.as_ref() {
let _ = tokio::time::timeout(
DEALLOCATE_TIMEOUT,
client.simple_query(&deallocate),
)
.await;
}
return Validation::Ok;
}
Ok(Err(error)) => {
if attempt == 0 && error.is_closed() {
*guard = None;
continue;
}
return classify_validation_error(&error, prefix.chars().count());
}
}
}
Validation::Skipped("connection closed during validation".to_string())
}
async fn load_schema(&self) -> Result<Schema> {
let guard = self.client_guard().await?;
let Some(client) = guard.as_ref() else {
bail!("connection unavailable");
};
schema::load(client).await
}
async fn client_guard(&self) -> Result<MutexGuard<'_, Option<Client>>> {
let mut guard = self.client.lock().await;
let healthy = guard.as_ref().is_some_and(|client| !client.is_closed());
if !healthy {
*guard = None;
let client = connection::connect(&self.config)
.await
.with_context(|| format!("database `{}`", self.redacted_url()))?;
*guard = Some(client);
}
Ok(guard)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manager_rejects_invalid_urls() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let manager = DbManager::new();
let error = runtime.block_on(manager.database("mysql://localhost/db"));
assert!(error.is_err());
}
#[test]
fn redaction_does_not_leak_passwords() {
let redacted = redact_url("postgresql://alice:hunter2@example.com/db");
assert!(!redacted.contains("hunter2"));
assert!(redacted.contains("alice"));
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Introspection of PostgreSQL catalogs.
//!
//! Only the metadata needed by completion, hover and semantic highlighting is
//! loaded. System schemas are excluded; `pg_catalog` remains available through
//! the connection's `search_path` for name resolution.
use std::collections::BTreeMap;
use anyhow::{Context, Result};
use tokio_postgres::types::FromSql;
use tokio_postgres::{Client, Row};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableKind {
Table,
PartitionedTable,
View,
MaterializedView,
ForeignTable,
}
impl TableKind {
pub fn label(self) -> &'static str {
match self {
TableKind::Table => "table",
TableKind::PartitionedTable => "partitioned table",
TableKind::View => "view",
TableKind::MaterializedView => "materialized view",
TableKind::ForeignTable => "foreign table",
}
}
fn from_relkind(kind: &str) -> Option<Self> {
match kind {
"r" => Some(TableKind::Table),
"p" => Some(TableKind::PartitionedTable),
"v" => Some(TableKind::View),
"m" => Some(TableKind::MaterializedView),
"f" => Some(TableKind::ForeignTable),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Column {
pub name: String,
pub data_type: String,
pub nullable: bool,
pub default: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Table {
pub schema: String,
pub name: String,
pub kind: TableKind,
pub columns: Vec<Column>,
}
impl Table {
pub fn qualified_name(&self) -> String {
format!("{}.{}", self.schema, self.name)
}
pub fn column(&self, name: &str) -> Option<&Column> {
self.columns.iter().find(|column| column.name == name)
}
}
#[derive(Debug, Clone)]
pub struct Function {
pub schema: String,
pub name: String,
pub arguments: String,
pub result: Option<String>,
}
impl Function {
pub fn signature(&self) -> String {
format!("{}({})", self.name, self.arguments)
}
}
#[derive(Debug, Clone, Default)]
pub struct Schema {
pub schemas: Vec<String>,
pub tables: Vec<Table>,
pub functions: Vec<Function>,
pub search_path: Vec<String>,
}
impl Schema {
/// Resolves a table name, honoring an explicit schema and `search_path`.
pub fn resolve_table(&self, schema: Option<&str>, name: &str) -> Option<&Table> {
if let Some(schema) = schema {
return self
.tables
.iter()
.find(|table| table.schema == schema && table.name == name);
}
for schema in &self.search_path {
if let Some(table) = self
.tables
.iter()
.find(|table| &table.schema == schema && table.name == name)
{
return Some(table);
}
}
let mut matches = self.tables.iter().filter(|table| table.name == name);
let first = matches.next()?;
if matches.next().is_none() {
Some(first)
} else {
None
}
}
pub fn resolve_qualified(&self, name: &str) -> Option<&Table> {
match name.split_once('.') {
Some((schema, table)) => self.resolve_table(Some(schema), table),
None => self.resolve_table(None, name),
}
}
pub fn schema_exists(&self, name: &str) -> bool {
self.schemas.iter().any(|schema| schema == name)
}
pub fn tables_in_schema<'a>(&'a self, schema: &'a str) -> impl Iterator<Item = &'a Table> {
self.tables
.iter()
.filter(move |table| table.schema == schema)
}
pub fn functions_in_schema<'a>(
&'a self,
schema: &'a str,
) -> impl Iterator<Item = &'a Function> {
self.functions
.iter()
.filter(move |function| function.schema == schema)
}
pub fn all_columns(&self) -> impl Iterator<Item = (&Table, &Column)> {
self.tables
.iter()
.flat_map(|table| table.columns.iter().map(move |column| (table, column)))
}
pub fn columns_named<'a>(
&'a self,
name: &'a str,
) -> impl Iterator<Item = (&'a Table, &'a Column)> {
self.all_columns()
.filter(move |(_, column)| column.name == name)
}
pub fn functions_named<'a>(
&'a self,
schema: Option<&'a str>,
name: &'a str,
) -> impl Iterator<Item = &'a Function> {
self.functions.iter().filter(move |function| {
function.name == name && schema.is_none_or(|schema| function.schema == schema)
})
}
}
/// Loads the catalog metadata for a connected client.
pub async fn load(client: &Client) -> Result<Schema> {
let schemas = load_schemas(client).await?;
let search_path = load_search_path(client).await?;
let tables = load_tables(client).await?;
let functions = load_functions(client).await?;
Ok(Schema {
schemas,
tables,
functions,
search_path,
})
}
async fn load_schemas(client: &Client) -> Result<Vec<String>> {
let rows = client
.query(
"SELECT nspname::text \
FROM pg_catalog.pg_namespace \
WHERE nspname NOT IN ('information_schema') \
AND nspname NOT LIKE 'pg\\_%' \
ORDER BY nspname",
&[],
)
.await
.context("loading schemas")?;
rows.iter()
.map(|row| get::<String>(row, 0, "schema"))
.collect()
}
async fn load_search_path(client: &Client) -> Result<Vec<String>> {
let row = client
.query_one("SELECT current_schemas(true)", &[])
.await
.context("loading search_path")?;
let path = get::<Vec<String>>(&row, 0, "search_path")?;
if path.is_empty() {
Ok(vec!["public".to_string()])
} else {
Ok(path)
}
}
async fn load_tables(client: &Client) -> Result<Vec<Table>> {
let rows = client
.query(
"SELECT n.nspname::text, c.relname::text, c.relkind::text, \
a.attname::text, \
pg_catalog.format_type(a.atttypid, a.atttypmod), \
NOT a.attnotnull, \
pg_catalog.pg_get_expr(d.adbin, d.adrelid) \
FROM pg_catalog.pg_class c \
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid \
LEFT JOIN pg_catalog.pg_attrdef d \
ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f') \
AND a.attnum > 0 AND NOT a.attisdropped \
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
AND n.nspname NOT LIKE 'pg\\_toast%' \
AND n.nspname NOT LIKE 'pg\\_temp%' \
ORDER BY n.nspname, c.relname, a.attnum",
&[],
)
.await
.context("loading tables")?;
let mut tables: BTreeMap<(String, String), Table> = BTreeMap::new();
for row in &rows {
let schema: String = get(row, 0, "schema")?;
let name: String = get(row, 1, "table")?;
let relkind: String = get(row, 2, "relkind")?;
let column_name: String = get(row, 3, "column")?;
let data_type: String = get(row, 4, "data_type")?;
let nullable: bool = get(row, 5, "nullable")?;
let default: Option<String> = get(row, 6, "default")?;
let Some(kind) = TableKind::from_relkind(&relkind) else {
continue;
};
let table = tables
.entry((schema.clone(), name.clone()))
.or_insert_with(|| Table {
schema,
name,
kind,
columns: Vec::new(),
});
table.columns.push(Column {
name: column_name,
data_type,
nullable,
default,
});
}
Ok(tables.into_values().collect())
}
async fn load_functions(client: &Client) -> Result<Vec<Function>> {
let rows = client
.query(
"SELECT n.nspname::text, p.proname::text, \
pg_catalog.pg_get_function_identity_arguments(p.oid), \
pg_catalog.pg_get_function_result(p.oid) \
FROM pg_catalog.pg_proc p \
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') \
AND n.nspname NOT LIKE 'pg\\_toast%' \
AND n.nspname NOT LIKE 'pg\\_temp%' \
ORDER BY n.nspname, p.proname",
&[],
)
.await
.context("loading functions")?;
let mut functions = Vec::with_capacity(rows.len());
for row in &rows {
functions.push(Function {
schema: get(row, 0, "schema")?,
name: get(row, 1, "function")?,
arguments: get(row, 2, "arguments")?,
result: get(row, 3, "result")?,
});
}
Ok(functions)
}
fn get<'a, T>(row: &'a Row, index: usize, field: &str) -> Result<T>
where
T: FromSql<'a>,
{
row.try_get(index)
.with_context(|| format!("decoding `{field}` from pg_catalog"))
}
#[cfg(test)]
mod tests {
use super::*;
fn schema() -> Schema {
Schema {
schemas: vec!["public".into(), "app".into()],
search_path: vec!["public".into(), "app".into()],
tables: vec![
Table {
schema: "public".into(),
name: "users".into(),
kind: TableKind::Table,
columns: vec![Column {
name: "id".into(),
data_type: "bigint".into(),
nullable: false,
default: None,
}],
},
Table {
schema: "app".into(),
name: "events".into(),
kind: TableKind::View,
columns: vec![Column {
name: "id".into(),
data_type: "bigint".into(),
nullable: true,
default: None,
}],
},
],
functions: vec![Function {
schema: "public".into(),
name: "now".into(),
arguments: String::new(),
result: Some("timestamp with time zone".into()),
}],
}
}
#[test]
fn resolves_qualified_and_search_path_tables() {
let schema = schema();
assert_eq!(
schema.resolve_table(None, "users").unwrap().schema,
"public"
);
assert_eq!(
schema.resolve_table(Some("app"), "events").unwrap().kind,
TableKind::View
);
assert!(schema.resolve_table(None, "events").is_some());
assert!(schema.resolve_table(None, "missing").is_none());
assert_eq!(
schema.resolve_qualified("app.events").unwrap().name,
"events"
);
}
#[test]
fn finds_columns_and_functions() {
let schema = schema();
assert_eq!(schema.columns_named("id").count(), 2);
assert_eq!(
schema
.functions_named(None, "now")
.next()
.unwrap()
.signature(),
"now()"
);
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Classification of errors returned by the server-side semantic check.
//!
//! A statement is checked with `PREPARE`. PostgreSQL parses and analyzes the
//! statement, resolving relations, columns and functions, but does not execute
//! it. The prepared statement is deallocated immediately afterwards.
use tokio_postgres::Error;
use tokio_postgres::error::ErrorPosition;
/// Outcome of a semantic validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Validation {
Ok,
/// The statement could not be checked reliably. This is not a diagnostic.
Skipped(String),
Failed {
message: String,
/// Zero-based character offset into the statement passed to the server.
position: Option<usize>,
code: String,
},
}
/// Converts a `tokio-postgres` error from `PREPARE` into a [`Validation`].
pub fn classify_validation_error(error: &Error, prefix_characters: usize) -> Validation {
let Some(db_error) = error.as_db_error() else {
// Transport-level failures are not SQL errors. Reporting them on a
// statement would be a false positive; the directive's connection check
// is responsible for connection diagnostics.
return Validation::Skipped(format!("connection error during validation: {error}"));
};
let code = db_error.code().code().to_string();
// PostgreSQL cannot infer the type of a bare parameter. This is expected in
// SQL templates and does not mean that the statement is invalid.
if code == "42P18" {
return Validation::Skipped("parameter types are not inferable".to_string());
}
if db_error
.message()
.contains("utility statements cannot be prepared")
{
return Validation::Skipped("utility statements are not validated".to_string());
}
let position = match db_error.position() {
Some(ErrorPosition::Original(position)) => {
let position = *position as usize;
if position > prefix_characters {
Some(position - 1 - prefix_characters)
} else {
None
}
}
Some(ErrorPosition::Internal { .. }) | None => None,
};
let mut message = db_error.message().to_string();
if let Some(detail) = db_error.detail() {
message.push_str(": ");
message.push_str(detail);
}
if let Some(hint) = db_error.hint() {
message.push_str(" (hint: ");
message.push_str(hint);
message.push(')');
}
Validation::Failed {
message,
position,
code,
}
}
+12
View File
@@ -0,0 +1,12 @@
//! `omg-pgs` is a database-aware PostgreSQL language server and REST query runner.
//!
//! The crate is split into a protocol-agnostic core (document parsing, catalog
//! introspection, diagnostics, completion) and thin LSP/REST adapters on top of
//! it. See `README.md` for user-facing documentation.
pub mod cli;
pub mod db;
pub mod lsp;
pub mod position;
pub mod rest;
pub mod sql;
+464
View File
@@ -0,0 +1,464 @@
//! The LSP transport and request handlers.
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::task::{Context, Poll};
use lsp_types::{
CompletionOptions, CompletionParams, CompletionResponse, DidChangeTextDocumentParams,
DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
DocumentFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, HoverParams,
HoverProviderCapability, InitializeParams, InitializeResult, InitializedParams, OneOf,
SemanticTokensFullOptions, SemanticTokensOptions, SemanticTokensParams, SemanticTokensResult,
SemanticTokensServerCapabilities, ServerCapabilities, ServerInfo, TextDocumentSyncCapability,
TextDocumentSyncKind, TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TextEdit, Url,
};
use tokio::sync::{Notify, RwLock};
use tower::Service;
use tower_lsp::jsonrpc::{Request, Response};
use tower_lsp::{Client, ExitedError, LanguageServer, LspService, Server};
use crate::db::{DbManager, Schema};
use crate::position::LineIndex;
use super::{
completion, diagnostics, formatting, hover, semantic_tokens, symbols, text_edit_range,
};
pub struct ServerState {
manager: Arc<DbManager>,
documents: RwLock<HashMap<Url, Arc<DocumentEntry>>>,
initialized: AtomicBool,
}
impl ServerState {
pub fn new(manager: Arc<DbManager>) -> Self {
Self {
manager,
documents: RwLock::new(HashMap::new()),
initialized: AtomicBool::new(false),
}
}
}
struct DocumentEntry {
generation: AtomicU64,
closed: AtomicBool,
data: RwLock<DocumentData>,
}
struct DocumentData {
text: String,
index: LineIndex,
parsed: Arc<crate::sql::ParsedFile>,
version: i32,
}
impl DocumentEntry {
fn new(text: String, version: i32) -> Self {
let index = LineIndex::new(&text);
let parsed = Arc::new(crate::sql::ParsedFile::parse(&text, &index));
Self {
generation: AtomicU64::new(0),
closed: AtomicBool::new(false),
data: RwLock::new(DocumentData {
text,
index,
parsed,
version,
}),
}
}
async fn update(&self, text: String, version: i32) {
let index = LineIndex::new(&text);
let parsed = Arc::new(crate::sql::ParsedFile::parse(&text, &index));
let mut data = self.data.write().await;
data.text = text;
data.index = index;
data.parsed = parsed;
data.version = version;
self.generation.fetch_add(1, Ordering::SeqCst);
}
}
struct Backend {
client: Client,
state: Arc<ServerState>,
}
impl Backend {
fn new(client: Client, state: Arc<ServerState>) -> Self {
Self { client, state }
}
async fn entry(&self, uri: &Url) -> Option<Arc<DocumentEntry>> {
self.state.documents.read().await.get(uri).cloned()
}
async fn snapshot(&self, uri: &Url) -> Option<(String, Arc<crate::sql::ParsedFile>, i32)> {
let entry = self.entry(uri).await?;
let data = entry.data.read().await;
Some((data.text.clone(), data.parsed.clone(), data.version))
}
async fn upsert(&self, uri: Url, text: String, version: i32) -> Arc<DocumentEntry> {
let mut documents = self.state.documents.write().await;
if let Some(entry) = documents.get(&uri).cloned() {
drop(documents);
entry.update(text, version).await;
entry
} else {
let entry = Arc::new(DocumentEntry::new(text, version));
documents.insert(uri, entry.clone());
entry
}
}
fn spawn_analysis(&self, uri: Url, entry: Arc<DocumentEntry>) {
let client = self.client.clone();
let manager = self.state.manager.clone();
tokio::spawn(async move {
let generation = entry.generation.load(Ordering::SeqCst);
let (text, parsed, version) = {
let data = entry.data.read().await;
(data.text.clone(), data.parsed.clone(), data.version)
};
let diagnostics = diagnostics::analyze(&manager, &text, &parsed).await;
if entry.closed.load(Ordering::SeqCst)
|| entry.generation.load(Ordering::SeqCst) != generation
{
return;
}
client
.publish_diagnostics(uri, diagnostics, Some(version))
.await;
});
}
async fn schema_for_url(&self, url: &str) -> Option<Arc<Schema>> {
let database = match self.state.manager.database(url).await {
Ok(database) => database,
Err(error) => {
tracing::debug!(error = %error, "could not prepare database entry");
return None;
}
};
match database.schema(false).await {
Ok(schema) => Some(schema),
Err(error) => {
tracing::debug!(
database = %database.redacted_url(),
error = %error,
"could not load schema"
);
None
}
}
}
}
#[tower_lsp::async_trait]
impl LanguageServer for Backend {
async fn initialize(
&self,
_params: InitializeParams,
) -> tower_lsp::jsonrpc::Result<InitializeResult> {
self.state.initialized.store(true, Ordering::SeqCst);
Ok(InitializeResult {
capabilities: ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Options(
TextDocumentSyncOptions {
open_close: Some(true),
change: Some(TextDocumentSyncKind::FULL),
save: Some(TextDocumentSyncSaveOptions::Supported(true)),
..Default::default()
},
)),
completion_provider: Some(CompletionOptions {
trigger_characters: Some(vec![".".to_string()]),
resolve_provider: Some(false),
..Default::default()
}),
hover_provider: Some(HoverProviderCapability::Simple(true)),
semantic_tokens_provider: Some(
SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: Default::default(),
legend: semantic_tokens::legend(),
range: Some(false),
full: Some(SemanticTokensFullOptions::Bool(true)),
},
),
),
document_formatting_provider: Some(OneOf::Left(true)),
document_symbol_provider: Some(OneOf::Left(true)),
..Default::default()
},
server_info: Some(ServerInfo {
name: "omg-pgs".to_string(),
version: Some(env!("CARGO_PKG_VERSION").to_string()),
}),
})
}
async fn initialized(&self, _params: InitializedParams) {
tracing::info!("LSP client initialized");
}
async fn shutdown(&self) -> tower_lsp::jsonrpc::Result<()> {
Ok(())
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let uri = params.text_document.uri;
let entry = self
.upsert(
uri.clone(),
params.text_document.text,
params.text_document.version,
)
.await;
self.spawn_analysis(uri, entry);
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
let Some(change) = params.content_changes.into_iter().last() else {
return;
};
let uri = params.text_document.uri;
let entry = self
.upsert(uri.clone(), change.text, params.text_document.version)
.await;
self.spawn_analysis(uri, entry);
}
async fn did_save(&self, params: DidSaveTextDocumentParams) {
let uri = params.text_document.uri;
let Some(entry) = self.entry(&uri).await else {
return;
};
if let Some(text) = params.text {
let version = entry.data.read().await.version;
entry.update(text, version).await;
}
let urls: Vec<String> = {
let data = entry.data.read().await;
data.parsed
.directives
.iter()
.map(|directive| directive.url.clone())
.filter(|url| !url.trim().is_empty())
.collect()
};
for url in urls {
self.state.manager.invalidate_schema(&url).await;
}
self.spawn_analysis(uri, entry);
}
async fn did_close(&self, params: DidCloseTextDocumentParams) {
let uri = params.text_document.uri;
if let Some(entry) = self.state.documents.write().await.remove(&uri) {
entry.closed.store(true, Ordering::SeqCst);
}
self.client.publish_diagnostics(uri, Vec::new(), None).await;
}
async fn completion(
&self,
params: CompletionParams,
) -> tower_lsp::jsonrpc::Result<Option<CompletionResponse>> {
let uri = params.text_document_position.text_document.uri;
let Some((text, parsed, _version)) = self.snapshot(&uri).await else {
return Ok(None);
};
if parsed.directives.is_empty() {
return Ok(None);
}
let index = LineIndex::new(&text);
let offset = index.offset(&text, params.text_document_position.position);
let Some(directive) = parsed.database_before(offset) else {
return Ok(None);
};
let url = directive.url.clone();
let Some(schema) = self.schema_for_url(&url).await else {
return Ok(None);
};
let items = completion::complete(&text, offset, &parsed, &schema);
Ok(Some(CompletionResponse::Array(items)))
}
async fn hover(
&self,
params: HoverParams,
) -> tower_lsp::jsonrpc::Result<Option<lsp_types::Hover>> {
let uri = params.text_document_position_params.text_document.uri;
let Some((text, parsed, _version)) = self.snapshot(&uri).await else {
return Ok(None);
};
if parsed.directives.is_empty() {
return Ok(None);
}
let index = LineIndex::new(&text);
let offset = index.offset(&text, params.text_document_position_params.position);
let schema = match parsed.database_before(offset) {
Some(directive) => self
.schema_for_url(&directive.url)
.await
.unwrap_or_default(),
None => Arc::new(Schema::default()),
};
Ok(hover::hover(&text, offset, &parsed, &schema))
}
async fn semantic_tokens_full(
&self,
params: SemanticTokensParams,
) -> tower_lsp::jsonrpc::Result<Option<SemanticTokensResult>> {
let uri = params.text_document.uri;
let Some((text, parsed, _version)) = self.snapshot(&uri).await else {
return Ok(None);
};
if parsed.directives.is_empty() {
return Ok(None);
}
let urls: HashSet<String> = parsed
.statements
.iter()
.filter_map(|statement| statement.database.clone())
.collect();
let mut schemas = HashMap::new();
for url in urls {
if let Some(schema) = self.schema_for_url(&url).await {
schemas.insert(url, schema);
}
}
let tokens =
tokio::task::spawn_blocking(move || semantic_tokens::compute(&text, &parsed, &schemas))
.await;
match tokens {
Ok(tokens) => Ok(Some(SemanticTokensResult::Tokens(tokens))),
Err(error) => {
tracing::debug!(error = %error, "semantic token task failed");
Ok(None)
}
}
}
async fn formatting(
&self,
params: DocumentFormattingParams,
) -> tower_lsp::jsonrpc::Result<Option<Vec<TextEdit>>> {
let uri = params.text_document.uri;
let Some((text, parsed, _version)) = self.snapshot(&uri).await else {
return Ok(None);
};
if parsed.directives.is_empty() {
return Ok(None);
}
let options = params.options;
let original = text.clone();
let formatted =
tokio::task::spawn_blocking(move || formatting::format_document(&text, &options)).await;
let Ok(formatted) = formatted else {
return Ok(None);
};
if formatted == original {
return Ok(Some(Vec::new()));
}
let index = LineIndex::new(&original);
let range = text_edit_range(&index, &original, 0, original.len());
Ok(Some(vec![TextEdit {
range,
new_text: formatted,
}]))
}
async fn document_symbol(
&self,
params: DocumentSymbolParams,
) -> tower_lsp::jsonrpc::Result<Option<DocumentSymbolResponse>> {
let uri = params.text_document.uri;
let Some((text, parsed, _version)) = self.snapshot(&uri).await else {
return Ok(None);
};
if parsed.directives.is_empty() {
return Ok(None);
}
Ok(Some(DocumentSymbolResponse::Nested(
symbols::document_symbols(&text, &parsed),
)))
}
}
/// Wraps the LSP service to observe the `exit` notification.
///
/// `tower-lsp` stops accepting requests after `exit`, but its stdio transport
/// only returns when stdin reaches EOF. Editors keep the pipe open after
/// sending `exit`, so the transport has to be terminated explicitly.
struct ExitAware<S> {
inner: S,
exit: Arc<Notify>,
}
impl<S> Service<Request> for ExitAware<S>
where
S: Service<Request, Response = Option<Response>, Error = ExitedError> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Option<Response>;
type Error = ExitedError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
if request.method() == "exit" {
self.exit.notify_waiters();
}
Box::pin(self.inner.call(request))
}
}
/// Runs the language server over stdin/stdout.
///
/// Stdout is reserved for LSP protocol messages; logs go to stderr. The return
/// value reports whether the client completed the LSP handshake. This lets the
/// process distinguish an editor disconnect from a headless invocation whose
/// stdin is closed.
pub async fn serve_stdio(manager: Arc<DbManager>) -> anyhow::Result<bool> {
tracing::info!("LSP server listening on stdin/stdout");
let state = Arc::new(ServerState::new(manager));
let service_state = state.clone();
let (service, socket) = LspService::new(move |client| Backend::new(client, service_state));
let exit = Arc::new(Notify::new());
let service = ExitAware {
inner: service,
exit: exit.clone(),
};
let server = Server::new(tokio::io::stdin(), tokio::io::stdout(), socket);
let exit_wait = exit.notified();
tokio::pin!(exit_wait);
tokio::select! {
() = server.serve(service) => {}
() = &mut exit_wait => {
tracing::info!("LSP exit notification received");
}
}
let initialized = state.initialized.load(Ordering::SeqCst);
tracing::info!(initialized, "LSP client disconnected");
Ok(initialized)
}
+666
View File
@@ -0,0 +1,666 @@
//! Schema-aware completion.
//!
//! Completion is intentionally conservative: it only offers objects that exist
//! in the database selected by the nearest `-- @database:` directive. Keywords
//! are offered as well, because they are useful even when the catalog query
//! failed.
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionTextEdit, Documentation, InsertTextFormat,
MarkupContent, MarkupKind, TextEdit,
};
use crate::db::{Column, Schema, Table};
use crate::position::{ByteSpan, LineIndex};
use crate::sql::ParsedFile;
use crate::sql::analysis::{self, Aliases, Clause};
use crate::sql::lexer::{Token, TokenKind};
use super::text_edit_range;
/// Builds completion items for `offset` using the active database schema.
pub fn complete(
text: &str,
offset: usize,
parsed: &ParsedFile,
schema: &Schema,
) -> Vec<CompletionItem> {
let offset = offset.min(text.len());
let line_index = LineIndex::new(text);
let current = analysis::token_at(&parsed.tokens, text, offset);
// Completion at the very end of a comment is still completion inside the
// comment (the token is not matched by `token_at` when offset == end).
if parsed.tokens.iter().any(|token| {
matches!(token.kind, TokenKind::LineComment | TokenKind::BlockComment)
&& token.start <= offset
&& offset <= token.end
}) {
return Vec::new();
}
if current.is_some_and(|token| {
matches!(
token.kind,
TokenKind::String
| TokenKind::LineComment
| TokenKind::BlockComment
| TokenKind::Number
)
}) {
return Vec::new();
}
let (prefix, replace_start, replace_end, quoted_prefix) = match current {
Some(token)
if matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent)
&& token.start <= offset =>
{
let raw = &text[token.start..offset];
let quoted = raw.starts_with('"');
let value = raw.strip_prefix('"').unwrap_or(raw);
(value.to_string(), token.start, token.end, quoted)
}
_ => (String::new(), offset, offset, false),
};
// Typing a complete keyword (`FROM`) should not filter suggestions by the
// keyword itself; the next token starts after it. Replacing the whole token
// also keeps completion correct when the cursor is in the middle of a word.
let (prefix, replace_start, replace_end) = if !quoted_prefix
&& is_complete_keyword(&prefix)
&& prefix.len() == offset.saturating_sub(replace_start)
{
(String::new(), offset, offset)
} else {
(prefix, replace_start, replace_end)
};
let statement = parsed.statement_at_offset(offset).filter(|statement| {
!(statement.content_span.end == offset && text[..offset].trim_end().ends_with(';'))
});
let region_start = statement
.map(|statement| statement.content_span.start)
.unwrap_or_else(|| previous_statement_end(parsed, text, offset));
let before = ByteSpan::new(region_start, replace_start.min(offset));
let before_tokens = analysis::significant_tokens(&parsed.tokens, before);
// Aliases are taken from the whole current statement: a SELECT list is
// completed before the FROM clause that defines its aliases has been typed.
let aliases_span = statement
.map(|statement| statement.content_span)
.unwrap_or(before);
let aliases = Aliases::parse(&parsed.tokens, text, aliases_span);
let mut clause = analysis::current_clause(&parsed.tokens, text, before);
// `INSERT INTO table (` expects column names, not another table. The
// backward clause scan sees `INTO`, so refine it when a column list has
// just been opened (or extended with a comma).
if clause == Clause::Into
&& !aliases.table_names().is_empty()
&& before_tokens.last().is_some_and(|token| {
token.kind == TokenKind::Punctuation && matches!(token.text(text), "(" | ",")
})
{
clause = Clause::Select;
}
let range = text_edit_range(&line_index, text, replace_start, replace_end);
let mut items = Vec::new();
if let Some(qualifier) = qualifier_before(&before_tokens, text) {
let (qualifier, quoted) = qualifier;
let normalized = analysis::normalize_ident(&qualifier, quoted);
if let Some(qualified) = aliases.resolve(&normalized) {
if let Some(table) = schema.resolve_qualified(qualified) {
push_columns(&mut items, table, &prefix, quoted_prefix, range);
}
} else if schema.schema_exists(&normalized) {
push_schema_objects(
&mut items,
schema,
&normalized,
&prefix,
quoted_prefix,
range,
);
} else if let Some(table) = schema.resolve_table(None, &normalized) {
push_columns(&mut items, table, &prefix, quoted_prefix, range);
}
finish(items, &prefix, quoted_prefix)
} else {
match clause {
Clause::From | Clause::Into => {
push_tables(&mut items, schema, &prefix, quoted_prefix, range);
push_schemas(&mut items, schema, &prefix, quoted_prefix, range);
}
Clause::Select | Clause::Predicate | Clause::Set => {
push_scoped_columns(&mut items, schema, &aliases, &prefix, quoted_prefix, range);
push_functions(&mut items, schema, None, &prefix, quoted_prefix, range);
}
Clause::Start | Clause::Any => {
push_tables(&mut items, schema, &prefix, quoted_prefix, range);
push_scoped_columns(&mut items, schema, &aliases, &prefix, quoted_prefix, range);
push_functions(&mut items, schema, None, &prefix, quoted_prefix, range);
}
}
push_keywords(&mut items, &prefix, quoted_prefix, range);
finish(items, &prefix, quoted_prefix)
}
}
fn qualifier_before(tokens: &[Token], text: &str) -> Option<(String, bool)> {
if tokens.len() < 2 {
return None;
}
let last = tokens.last()?;
if last.kind != TokenKind::Punctuation || last.text(text) != "." {
return None;
}
analysis::ident_value(tokens[tokens.len() - 2], text)
}
fn previous_statement_end(parsed: &ParsedFile, text: &str, offset: usize) -> usize {
parsed
.tokens
.iter()
.rev()
.find(|token| {
token.end <= offset && token.kind == TokenKind::Punctuation && token.text(text) == ";"
})
.map(|token| token.end)
.unwrap_or(0)
}
fn push_tables(
items: &mut Vec<CompletionItem>,
schema: &Schema,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
for table in &schema.tables {
if !matches_prefix(prefix, quoted, &table.name) {
continue;
}
let qualified = table.qualified_name();
let insert = if schema
.search_path
.first()
.is_some_and(|name| name == &table.schema)
{
analysis::quote_ident(&table.name)
} else {
format!(
"{}.{}",
analysis::quote_ident(&table.schema),
analysis::quote_ident(&table.name)
)
};
items.push(item(
table.name.clone(),
CompletionItemKind::CLASS,
format!("{} ({})", qualified, table.kind.label()),
Some(format!("Columns: {}", column_summary(table))),
"0",
insert,
range,
));
}
}
fn push_schemas(
items: &mut Vec<CompletionItem>,
schema: &Schema,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
for name in &schema.schemas {
if !matches_prefix(prefix, quoted, name) {
continue;
}
items.push(item(
name.clone(),
CompletionItemKind::MODULE,
"schema".to_string(),
None,
"3",
format!("{}.", analysis::quote_ident(name)),
range,
));
}
}
fn push_schema_objects(
items: &mut Vec<CompletionItem>,
schema: &Schema,
schema_name: &str,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
for table in schema.tables_in_schema(schema_name) {
if !matches_prefix(prefix, quoted, &table.name) {
continue;
}
items.push(item(
table.name.clone(),
CompletionItemKind::CLASS,
format!("{} ({})", table.qualified_name(), table.kind.label()),
Some(format!("Columns: {}", column_summary(table))),
"0",
analysis::quote_ident(&table.name),
range,
));
}
for function in schema.functions_in_schema(schema_name) {
if !matches_prefix(prefix, quoted, &function.name) {
continue;
}
items.push(item(
function.signature(),
CompletionItemKind::FUNCTION,
function
.result
.clone()
.map(|result| format!("→ {result}"))
.unwrap_or_else(|| "function".to_string()),
None,
"2",
format!("{}(", analysis::quote_ident(&function.name)),
range,
));
}
}
fn push_columns(
items: &mut Vec<CompletionItem>,
table: &Table,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
for column in &table.columns {
if !matches_prefix(prefix, quoted, &column.name) {
continue;
}
items.push(column_item(table, column, range));
}
}
fn push_scoped_columns(
items: &mut Vec<CompletionItem>,
schema: &Schema,
aliases: &Aliases,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
let mut tables: Vec<&Table> = aliases
.table_names()
.iter()
.filter_map(|name| schema.resolve_qualified(name))
.collect();
if tables.is_empty() {
tables = schema.tables.iter().collect();
}
tables.sort_by_key(|table| table.qualified_name());
tables.dedup_by_key(|table| table.qualified_name());
for table in tables {
push_columns(items, table, prefix, quoted, range);
}
}
fn push_functions(
items: &mut Vec<CompletionItem>,
schema: &Schema,
schema_name: Option<&str>,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
for function in &schema.functions {
if let Some(schema_name) = schema_name {
if function.schema != schema_name {
continue;
}
}
if !matches_prefix(prefix, quoted, &function.name) {
continue;
}
items.push(item(
function.signature(),
CompletionItemKind::FUNCTION,
function
.result
.clone()
.map(|result| format!("→ {result}"))
.unwrap_or_else(|| "function".to_string()),
Some(format!("{}()", function.name)),
"2",
format!("{}(", analysis::quote_ident(&function.name)),
range,
));
}
}
fn push_keywords(
items: &mut Vec<CompletionItem>,
prefix: &str,
quoted: bool,
range: lsp_types::Range,
) {
if quoted {
return;
}
for keyword in KEYWORDS {
if !matches_prefix(prefix, false, keyword) {
continue;
}
items.push(item(
(*keyword).to_string(),
CompletionItemKind::KEYWORD,
"keyword".to_string(),
None,
"4",
format!("{keyword} "),
range,
));
}
}
fn column_item(table: &Table, column: &Column, range: lsp_types::Range) -> CompletionItem {
let mut detail = column.data_type.clone();
if !column.nullable {
detail.push_str(" not null");
}
let mut documentation = format!(
"`{}.{}.{}` — `{}`",
table.schema, table.name, column.name, column.data_type
);
if !column.nullable {
documentation.push_str(" not null");
}
if let Some(default) = &column.default {
documentation.push_str(&format!(" default {default}"));
}
item(
column.name.clone(),
CompletionItemKind::FIELD,
detail,
Some(documentation),
"1",
analysis::quote_ident(&column.name),
range,
)
}
fn item(
label: String,
kind: CompletionItemKind,
detail: String,
documentation: Option<String>,
sort_prefix: &str,
insert: String,
range: lsp_types::Range,
) -> CompletionItem {
CompletionItem {
label: label.clone(),
kind: Some(kind),
detail: Some(detail),
documentation: documentation.map(|value| {
Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value,
})
}),
sort_text: Some(format!("{sort_prefix}{label}")),
filter_text: Some(label),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range,
new_text: insert,
})),
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
..Default::default()
}
}
fn matches_prefix(prefix: &str, quoted: bool, candidate: &str) -> bool {
if prefix.is_empty() {
return true;
}
if quoted {
candidate.starts_with(prefix)
} else {
candidate.to_lowercase().starts_with(&prefix.to_lowercase())
}
}
fn finish(mut items: Vec<CompletionItem>, prefix: &str, quoted: bool) -> Vec<CompletionItem> {
if prefix.is_empty() && !quoted {
// Stable output helps editor-side fuzzy matching and tests.
items.sort_by(|left, right| left.sort_text.as_deref().cmp(&right.sort_text.as_deref()));
}
items.truncate(1000);
items
}
fn column_summary(table: &Table) -> String {
let mut names: Vec<&str> = table
.columns
.iter()
.take(8)
.map(|column| column.name.as_str())
.collect();
if table.columns.len() > names.len() {
names.push("…");
}
names.join(", ")
}
fn is_complete_keyword(word: &str) -> bool {
KEYWORDS
.iter()
.any(|keyword| keyword.eq_ignore_ascii_case(word))
}
const KEYWORDS: &[&str] = &[
"SELECT",
"INSERT",
"UPDATE",
"DELETE",
"FROM",
"WHERE",
"JOIN",
"LEFT JOIN",
"RIGHT JOIN",
"INNER JOIN",
"FULL JOIN",
"CROSS JOIN",
"ON",
"USING",
"GROUP BY",
"ORDER BY",
"HAVING",
"LIMIT",
"OFFSET",
"RETURNING",
"WITH",
"VALUES",
"SET",
"INTO",
"AS",
"AND",
"OR",
"NOT",
"NULL",
"IS",
"IN",
"EXISTS",
"CASE",
"WHEN",
"THEN",
"ELSE",
"END",
"DISTINCT",
"UNION",
"UNION ALL",
"INTERSECT",
"EXCEPT",
"ASC",
"DESC",
"NULLS FIRST",
"NULLS LAST",
"CREATE",
"ALTER",
"DROP",
"TABLE",
"VIEW",
"INDEX",
"SCHEMA",
"FUNCTION",
"BEGIN",
"COMMIT",
"ROLLBACK",
"EXPLAIN",
"ANALYZE",
"TRUNCATE",
"REFERENCES",
"PRIMARY KEY",
"DEFAULT",
"CASCADE",
];
#[cfg(test)]
mod tests {
use super::*;
use crate::db::{Column, Function, TableKind};
fn schema() -> Schema {
Schema {
schemas: vec!["public".into(), "app".into()],
search_path: vec!["public".into(), "app".into()],
tables: vec![
Table {
schema: "public".into(),
name: "users".into(),
kind: TableKind::Table,
columns: vec![
Column {
name: "id".into(),
data_type: "bigint".into(),
nullable: false,
default: None,
},
Column {
name: "email".into(),
data_type: "text".into(),
nullable: true,
default: None,
},
],
},
Table {
schema: "public".into(),
name: "orders".into(),
kind: TableKind::Table,
columns: vec![Column {
name: "user_id".into(),
data_type: "bigint".into(),
nullable: false,
default: None,
}],
},
],
functions: vec![Function {
schema: "public".into(),
name: "count_orders".into(),
arguments: "integer".into(),
result: Some("bigint".into()),
}],
}
}
fn labels(sql: &str, schema: &Schema) -> Vec<String> {
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
complete(sql, sql.len(), &parsed, schema)
.into_iter()
.map(|item| item.label)
.collect()
}
#[test]
fn offers_tables_after_from() {
let sql = "-- @database: postgresql://localhost/db\nSELECT * FROM ";
let labels = labels(sql, &schema());
assert!(labels.contains(&"users".to_string()));
assert!(labels.contains(&"orders".to_string()));
}
#[test]
fn offers_columns_in_select_list() {
let sql = "-- @database: postgresql://localhost/db\nSELECT FROM users";
let cursor = sql.find(" FROM").unwrap() + 1;
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
let labels: Vec<_> = complete(sql, cursor, &parsed, &schema())
.into_iter()
.map(|item| item.label)
.collect();
assert!(labels.contains(&"id".to_string()));
assert!(labels.contains(&"email".to_string()));
}
#[test]
fn offers_columns_after_alias_dot() {
let sql = "-- @database: postgresql://localhost/db\nSELECT u. FROM users u";
let cursor = sql.find("u. FROM").unwrap() + 2;
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
let labels: Vec<_> = complete(sql, cursor, &parsed, &schema())
.into_iter()
.map(|item| item.label)
.collect();
assert!(labels.contains(&"id".to_string()));
assert!(!labels.contains(&"orders".to_string()));
}
#[test]
fn filters_by_prefix() {
let sql = "-- @database: postgresql://localhost/db\nSELECT * FROM us";
let labels = labels(sql, &schema());
assert!(labels.contains(&"users".to_string()));
assert!(!labels.contains(&"orders".to_string()));
}
#[test]
fn offers_columns_inside_insert_column_list() {
let sql = "-- @database: postgresql://localhost/db\nINSERT INTO users (";
let labels = labels(sql, &schema());
assert!(labels.contains(&"id".to_string()));
assert!(labels.contains(&"email".to_string()));
}
#[test]
fn replaces_the_whole_identifier_when_cursor_is_inside() {
let sql = "-- @database: postgresql://localhost/db\nSELECT * FROM users";
let cursor = sql.find("users").unwrap() + 2;
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
let items = complete(sql, cursor, &parsed, &schema());
let item = items
.iter()
.find(|item| item.label == "users")
.expect("users completion");
let Some(CompletionTextEdit::Edit(edit)) = &item.text_edit else {
panic!("expected a text edit");
};
let end = LineIndex::new(sql).offset(sql, edit.range.end);
assert_eq!(end, sql.len());
assert_eq!(edit.new_text, "users");
}
#[test]
fn offers_nothing_inside_comments_or_strings() {
let sql = "-- @database: postgresql://localhost/db\nSELECT '";
let labels = labels(sql, &schema());
assert!(labels.is_empty());
}
}
+231
View File
@@ -0,0 +1,231 @@
//! Diagnostics for database connections, syntax and server-side name resolution.
use std::collections::HashMap;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use tokio::task::spawn_blocking;
use crate::db::{DbManager, parse_config};
use crate::position::{ByteSpan, LineIndex};
use crate::sql::ParsedFile;
use crate::sql::analysis;
/// Analyzes a document and returns all diagnostics.
///
/// Files without a `-- @database:` directive deliberately produce no
/// diagnostics at all.
pub async fn analyze(manager: &DbManager, text: &str, parsed: &ParsedFile) -> Vec<Diagnostic> {
if parsed.directives.is_empty() {
return Vec::new();
}
let index = LineIndex::new(text);
let mut diagnostics = Vec::new();
let mut connections: HashMap<String, Result<(), String>> = HashMap::new();
for directive in &parsed.directives {
if directive.url.trim().is_empty() {
diagnostics.push(diagnostic(
index.range(text, directive.url_span),
"Database URL is empty".to_string(),
"connection",
));
continue;
}
let status = match connections.get(&directive.url) {
Some(status) => status.clone(),
None => {
let status = match parse_config(&directive.url) {
Err(error) => Err(format!("Invalid database URL: {error:#}")),
Ok(_) => match manager.database(&directive.url).await {
Err(error) => Err(format!("Invalid database URL: {error:#}")),
Ok(database) => database
.check_connection()
.await
.map_err(|error| format!("Cannot connect to database: {error:#}")),
},
};
connections.insert(directive.url.clone(), status.clone());
status
}
};
if let Err(message) = status {
diagnostics.push(diagnostic(
index.range(text, directive.url_span),
message,
"connection",
));
}
}
for statement in &parsed.statements {
let Some(url) = statement
.database
.as_deref()
.filter(|url| !url.trim().is_empty())
else {
continue;
};
if connections.get(url) != Some(&Ok(())) {
continue;
}
let statement_text = statement.text.clone();
let parse_result = spawn_blocking(move || match pg_query::parse(&statement_text, 0) {
Ok(_) => {
let utility = pg_query::is_utility_stmt(&statement_text)
.ok()
.and_then(|statements| statements.first().copied())
.unwrap_or(false);
Ok(utility)
}
Err(error) => Err(parse_error_message(error)),
})
.await;
let utility = match parse_result {
Ok(Ok(utility)) => utility,
Ok(Err(message)) => {
let span = analysis::locate_parse_error(&statement.text, &message)
.map(|local| {
ByteSpan::new(
statement.span.start + local.start,
statement.span.start + local.end,
)
})
.unwrap_or(statement.content_span);
diagnostics.push(diagnostic(index.range(text, span), message, "syntax"));
continue;
}
Err(error) => {
tracing::debug!(error = %error, "parser task failed");
continue;
}
};
if utility {
// Utility statements cannot be prepared. They are still checked for
// syntax above, but PostgreSQL offers no side-effect free way to
// resolve their names.
continue;
}
let Some(database) = manager.get(url).await else {
continue;
};
match database.validate(&statement.text).await {
crate::db::Validation::Ok => {}
crate::db::Validation::Skipped(reason) => {
tracing::debug!(
database = %database.redacted_url(),
reason = %reason,
"semantic validation skipped"
);
}
crate::db::Validation::Failed {
message,
position,
code,
} => {
let span = position
.map(|position| {
let local = analysis::char_offset_to_byte(&statement.text, position);
let offset = statement.span.start + local;
parsed
.tokens
.iter()
.find(|token| {
!token.is_trivia() && token.start <= offset && offset < token.end
})
.map(|token| token.span())
.unwrap_or(statement.content_span)
})
.unwrap_or(statement.content_span);
diagnostics.push(Diagnostic {
range: index.range(text, span),
severity: Some(DiagnosticSeverity::ERROR),
code: Some(NumberOrString::String(code)),
source: Some("omg-pgs".to_string()),
message,
..Default::default()
});
}
}
}
diagnostics.sort_by_key(|diagnostic| {
(
diagnostic.range.start.line,
diagnostic.range.start.character,
diagnostic.range.end.line,
diagnostic.range.end.character,
)
});
diagnostics
}
fn diagnostic(range: lsp_types::Range, message: String, code: &str) -> Diagnostic {
Diagnostic {
range,
severity: Some(DiagnosticSeverity::ERROR),
code: Some(NumberOrString::String(code.to_string())),
source: Some("omg-pgs".to_string()),
message,
..Default::default()
}
}
fn parse_error_message(error: pg_query::Error) -> String {
match error {
pg_query::Error::Parse(message)
| pg_query::Error::Scan(message)
| pg_query::Error::Split(message)
| pg_query::Error::IsUtility(message)
| pg_query::Error::InvalidJson(message) => message,
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(source: &str) -> ParsedFile {
ParsedFile::parse(source, &LineIndex::new(source))
}
#[tokio::test]
async fn files_without_directives_have_no_diagnostics() {
let manager = DbManager::new();
let source = "SELECT 1;\n";
let parsed = parse(source);
assert!(analyze(&manager, source, &parsed).await.is_empty());
}
#[tokio::test]
async fn empty_url_is_reported_on_the_directive() {
let manager = DbManager::new();
let source = "-- @database:\nSELECT 1;\n";
let parsed = parse(source);
let diagnostics = analyze(&manager, source, &parsed).await;
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
assert_eq!(
diagnostics[0].code,
Some(NumberOrString::String("connection".into()))
);
assert_eq!(diagnostics[0].range.start.line, 0);
}
#[tokio::test]
async fn invalid_scheme_is_reported_without_a_connection() {
let manager = DbManager::new();
let source = "-- @database: mysql://localhost/db\nSELECT 1;\n";
let parsed = parse(source);
let diagnostics = analyze(&manager, source, &parsed).await;
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
assert!(diagnostics[0].message.contains("Invalid database URL"));
assert_eq!(diagnostics[0].range.start.line, 0);
}
}
+47
View File
@@ -0,0 +1,47 @@
//! Document formatting.
use lsp_types::FormattingOptions;
/// Formats whitespace in a whole document.
///
/// Only layout is changed; keyword case and string contents are preserved.
pub fn format_document(text: &str, options: &FormattingOptions) -> String {
let indent = if options.insert_spaces {
sqlformat::Indent::Spaces(options.tab_size.min(255) as u8)
} else {
sqlformat::Indent::Tabs
};
sqlformat::format(
text,
&sqlformat::QueryParams::None,
&sqlformat::FormatOptions {
indent,
uppercase: None,
lines_between_queries: 1,
dialect: sqlformat::Dialect::PostgreSql,
..Default::default()
},
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_with_postgres_dialect() {
let formatted = format_document(
"-- @database: postgresql://localhost/db\nselect * from users where id=1;",
&FormattingOptions {
tab_size: 2,
insert_spaces: true,
..Default::default()
},
);
assert!(formatted.contains("select"));
assert!(formatted.contains("users"));
assert!(formatted.contains("where"));
assert!(formatted.contains("@database"));
assert!(formatted.matches('\n').count() >= 3);
}
}
+374
View File
@@ -0,0 +1,374 @@
//! Schema-aware hover information.
use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind};
use crate::db::{self, Column, Function, Schema, Table};
use crate::position::LineIndex;
use crate::sql::ParsedFile;
use crate::sql::analysis::{self, Aliases};
use crate::sql::lexer::TokenKind;
use super::text_edit_range;
/// Returns hover information for the token at `offset`.
pub fn hover(text: &str, offset: usize, parsed: &ParsedFile, schema: &Schema) -> Option<Hover> {
let offset = offset.min(text.len());
let token = analysis::token_at(&parsed.tokens, text, offset)?;
if token.kind == TokenKind::LineComment {
let directive = parsed.directives.iter().find(|directive| {
offset >= directive.full_span.start && offset <= directive.full_span.end
})?;
let url = if directive.url.trim().is_empty() {
"(empty)".to_string()
} else {
db::redact_url(&directive.url)
};
return Some(hover_response(
text,
token.start,
token.end,
format!("**Database directive**\n\n```text\n{url}\n```"),
));
}
let (value, quoted) = analysis::ident_value(token, text)?;
if value.is_empty() {
return None;
}
let normalized = analysis::normalize_ident(&value, quoted);
let statement = parsed.statement_at_offset(offset);
let signifificant = statement
.map(|statement| analysis::significant_tokens(&parsed.tokens, statement.content_span))
.unwrap_or_else(|| analysis::significant_tokens(&parsed.tokens, token.span()));
let position = signifificant
.iter()
.position(|candidate| candidate.start == token.start && candidate.end == token.end);
let aliases = statement
.map(|statement| Aliases::parse(&parsed.tokens, text, statement.content_span))
.unwrap_or_default();
let previous_is_dot = position
.and_then(|index| index.checked_sub(1))
.and_then(|index| signifificant.get(index))
.is_some_and(|token| token.kind == TokenKind::Punctuation && token.text(text) == ".");
let previous_identifier = position
.and_then(|index| index.checked_sub(2))
.and_then(|index| signifificant.get(index))
.and_then(|token| analysis::ident_value(*token, text));
let next_is_dot = position
.and_then(|index| index.checked_add(1))
.and_then(|index| signifificant.get(index))
.is_some_and(|token| token.kind == TokenKind::Punctuation && token.text(text) == ".");
// `alias.column` / `table.column` / `schema.object`
if previous_is_dot {
if let Some((qualifier, qualifier_quoted)) = previous_identifier {
let qualifier = analysis::normalize_ident(&qualifier, qualifier_quoted);
if let Some(qualified) = aliases.resolve(&qualifier) {
if let Some(table) = schema.resolve_qualified(qualified) {
if let Some(column) = table.column(&normalized) {
return Some(hover_response(
text,
token.start,
token.end,
column_markdown(table, column),
));
}
return Some(hover_response(
text,
token.start,
token.end,
table_markdown(table),
));
}
}
if schema.schema_exists(&qualifier) {
if let Some(table) = schema.resolve_table(Some(&qualifier), &normalized) {
return Some(hover_response(
text,
token.start,
token.end,
table_markdown(table),
));
}
let functions: Vec<&Function> = schema
.functions_named(Some(&qualifier), &normalized)
.collect();
if !functions.is_empty() {
return Some(hover_response(
text,
token.start,
token.end,
functions_markdown(&functions),
));
}
} else if let Some(table) = schema.resolve_table(None, &qualifier) {
if let Some(column) = table.column(&normalized) {
return Some(hover_response(
text,
token.start,
token.end,
column_markdown(table, column),
));
}
}
}
return None;
}
if next_is_dot {
if let Some(qualified) = aliases.resolve(&normalized) {
if let Some(table) = schema.resolve_qualified(qualified) {
return Some(hover_response(
text,
token.start,
token.end,
table_markdown(table),
));
}
}
if schema.schema_exists(&normalized) {
return Some(hover_response(
text,
token.start,
token.end,
schema_markdown(schema, &normalized),
));
}
}
if let Some(qualified) = aliases.resolve(&normalized) {
if let Some(table) = schema.resolve_qualified(qualified) {
return Some(hover_response(
text,
token.start,
token.end,
table_markdown(table),
));
}
}
if let Some(table) = schema.resolve_table(None, &normalized) {
return Some(hover_response(
text,
token.start,
token.end,
table_markdown(table),
));
}
let functions: Vec<&Function> = schema.functions_named(None, &normalized).collect();
if !functions.is_empty() {
return Some(hover_response(
text,
token.start,
token.end,
functions_markdown(&functions),
));
}
let scope: Vec<&Table> = aliases
.table_names()
.iter()
.filter_map(|name| schema.resolve_qualified(name))
.collect();
let candidates: Vec<(&Table, &Column)> = if scope.is_empty() {
schema.columns_named(&normalized).collect()
} else {
scope
.iter()
.flat_map(|table| {
table
.columns
.iter()
.filter(|column| column.name == normalized)
.map(move |column| (*table, column))
})
.collect()
};
if !candidates.is_empty() {
let value = if candidates.len() == 1 {
column_markdown(candidates[0].0, candidates[0].1)
} else {
columns_markdown(&candidates)
};
return Some(hover_response(text, token.start, token.end, value));
}
if schema.schema_exists(&normalized) {
return Some(hover_response(
text,
token.start,
token.end,
schema_markdown(schema, &normalized),
));
}
None
}
fn hover_response(text: &str, start: usize, end: usize, value: String) -> Hover {
let index = LineIndex::new(text);
Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value,
}),
range: Some(text_edit_range(&index, text, start, end)),
}
}
fn table_markdown(table: &Table) -> String {
let mut markdown = format!(
"**{}.{}** — {}\n\n| Column | Type | Nullable | Default |\n| --- | --- | --- | --- |\n",
escape(&table.schema),
escape(&table.name),
table.kind.label()
);
for column in table.columns.iter().take(64) {
markdown.push_str(&format!(
"| {} | `{}` | {} | {} |\n",
escape(&column.name),
escape(&column.data_type),
if column.nullable { "yes" } else { "no" },
column
.default
.as_deref()
.map(|value| format!("`{}`", escape(value)))
.unwrap_or_default()
));
}
if table.columns.len() > 64 {
markdown.push_str(&format!(
"\n… and {} more columns",
table.columns.len() - 64
));
}
markdown
}
fn column_markdown(table: &Table, column: &Column) -> String {
let mut markdown = format!(
"**{}.{}.{}** — `{}`{}",
escape(&table.schema),
escape(&table.name),
escape(&column.name),
escape(&column.data_type),
if column.nullable { "" } else { " not null" }
);
if let Some(default) = &column.default {
markdown.push_str(&format!("\n\ndefault: `{}`", escape(default)));
}
markdown
}
fn columns_markdown(columns: &[(&Table, &Column)]) -> String {
let mut markdown = format!("**{} matching columns**\n", columns.len());
for (table, column) in columns.iter().take(32) {
markdown.push_str(&format!(
"\n- `{}.{}.{}` — `{}`",
escape(&table.schema),
escape(&table.name),
escape(&column.name),
escape(&column.data_type)
));
}
markdown
}
fn functions_markdown(functions: &[&Function]) -> String {
let mut markdown = String::from("**Function**\n");
for function in functions.iter().take(32) {
markdown.push_str(&format!(
"\n- `{}.{}({})` → `{}`",
escape(&function.schema),
escape(&function.name),
escape(&function.arguments),
escape(function.result.as_deref().unwrap_or("unknown"))
));
}
markdown
}
fn schema_markdown(schema: &Schema, name: &str) -> String {
let tables = schema.tables_in_schema(name).count();
let functions = schema.functions_in_schema(name).count();
format!(
"**{}** — schema\n\n{tables} tables, {functions} functions",
escape(name)
)
}
fn escape(value: &str) -> String {
value.replace('|', "\\|").replace('\n', " ")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::{Column, TableKind};
use crate::position::LineIndex;
fn schema() -> Schema {
Schema {
schemas: vec!["public".into()],
search_path: vec!["public".into()],
tables: vec![Table {
schema: "public".into(),
name: "users".into(),
kind: TableKind::Table,
columns: vec![
Column {
name: "id".into(),
data_type: "bigint".into(),
nullable: false,
default: None,
},
Column {
name: "email".into(),
data_type: "text".into(),
nullable: true,
default: None,
},
],
}],
functions: vec![],
}
}
fn value(sql: &str, cursor: usize) -> Option<String> {
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
hover(sql, cursor, &parsed, &schema()).map(|hover| match hover.contents {
HoverContents::Markup(markup) => markup.value,
_ => String::new(),
})
}
#[test]
fn shows_table_and_column_info() {
let sql = "-- @database: postgresql://localhost/db\nSELECT * FROM users";
let table = value(sql, sql.find("users").unwrap() + 1).unwrap();
assert!(table.contains("public.users"));
assert!(table.contains("bigint"));
let column = value(sql, sql.find("SELECT").unwrap() + 2);
assert!(column.is_none());
}
#[test]
fn resolves_alias_columns() {
let sql = "-- @database: postgresql://localhost/db\nSELECT u.email FROM users u";
let hover = value(sql, sql.find("email").unwrap() + 1).unwrap();
assert!(hover.contains("public.users.email"));
assert!(hover.contains("text"));
}
#[test]
fn shows_directive_hover() {
let sql = "-- @database: postgresql://alice:secret@localhost/db\nSELECT 1";
let hover = value(sql, 5).unwrap();
assert!(hover.contains("Database directive"));
assert!(!hover.contains("secret"));
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Language Server Protocol implementation.
mod backend;
mod completion;
mod diagnostics;
mod formatting;
mod hover;
mod semantic_tokens;
mod symbols;
pub use backend::{ServerState, serve_stdio};
use crate::position::{ByteSpan, LineIndex};
/// Converts byte offsets into an LSP range.
pub(crate) fn text_edit_range(
index: &LineIndex,
text: &str,
start: usize,
end: usize,
) -> lsp_types::Range {
index.range(text, ByteSpan::new(start, end))
}
+507
View File
@@ -0,0 +1,507 @@
//! Semantic highlighting based on `libpg_query`'s scanner and the live schema.
use std::collections::HashMap;
use std::sync::Arc;
use lsp_types::{
SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens, SemanticTokensLegend,
};
use pg_query::protobuf::Token as PgToken;
use crate::db::Schema;
use crate::position::LineIndex;
use crate::sql::ParsedFile;
use crate::sql::analysis::{self, Aliases};
use crate::sql::lexer::{self, TokenKind};
const KEYWORD: u32 = 0;
const STRING: u32 = 1;
const NUMBER: u32 = 2;
const COMMENT: u32 = 3;
const OPERATOR: u32 = 4;
const FUNCTION: u32 = 5;
const CLASS: u32 = 6;
const PROPERTY: u32 = 7;
const NAMESPACE: u32 = 8;
const VARIABLE: u32 = 9;
pub fn legend() -> SemanticTokensLegend {
SemanticTokensLegend {
token_types: vec![
SemanticTokenType::KEYWORD,
SemanticTokenType::STRING,
SemanticTokenType::NUMBER,
SemanticTokenType::COMMENT,
SemanticTokenType::OPERATOR,
SemanticTokenType::FUNCTION,
SemanticTokenType::CLASS,
SemanticTokenType::PROPERTY,
SemanticTokenType::NAMESPACE,
SemanticTokenType::VARIABLE,
],
token_modifiers: Vec::<SemanticTokenModifier>::new(),
}
}
/// Computes semantic tokens for the document.
///
/// `schemas` is keyed by the exact database URL from the directive. Missing
/// schemas simply disable identifier resolution; lexical tokens are still
/// highlighted.
pub fn compute(
text: &str,
parsed: &ParsedFile,
schemas: &HashMap<String, Arc<Schema>>,
) -> SemanticTokens {
let index = LineIndex::new(text);
let mut absolute = Vec::new();
match pg_query::scan_tokens(text) {
Ok(scan_tokens) => {
let scanned: Vec<Scanned<'_>> = scan_tokens
.into_iter()
.filter(|token| token.end > token.start)
.filter_map(|token| {
let start = usize::try_from(token.start).ok()?;
let end = usize::try_from(token.end).ok()?;
let raw = text.get(start..end)?;
Some(Scanned {
start,
end,
raw,
kind: classify(raw, token.token, token.keyword_kind),
})
})
.collect();
compute_from_tokens(text, parsed, schemas, &index, &scanned, &mut absolute);
}
Err(_) => {
let scanned: Vec<Scanned<'_>> = lexer::tokenize(text)
.into_iter()
.filter_map(|token| {
let raw = text.get(token.start..token.end)?;
let kind = match token.kind {
TokenKind::Word | TokenKind::QuotedIdent => Lexical::Ident,
TokenKind::String => Lexical::String,
TokenKind::Number => Lexical::Number,
TokenKind::LineComment | TokenKind::BlockComment => Lexical::Comment,
TokenKind::Operator => Lexical::Operator,
TokenKind::Param => Lexical::Variable,
TokenKind::Punctuation => Lexical::Punctuation,
TokenKind::Whitespace | TokenKind::Other => Lexical::Skip,
};
Some(Scanned {
start: token.start,
end: token.end,
raw,
kind,
})
})
.collect();
compute_from_tokens(text, parsed, schemas, &index, &scanned, &mut absolute);
}
}
absolute.sort_by_key(|token| (token.line, token.start));
absolute.dedup();
SemanticTokens {
result_id: None,
data: delta_encode(absolute),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct AbsoluteToken {
line: u32,
start: u32,
length: u32,
token_type: u32,
}
impl PartialOrd for AbsoluteToken {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for AbsoluteToken {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(self.line, self.start, self.length, self.token_type).cmp(&(
other.line,
other.start,
other.length,
other.token_type,
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Lexical {
Keyword,
String,
Number,
Comment,
Operator,
/// Punctuation is significant for `qualifier.identifier` resolution but is
/// never emitted as a semantic token.
Punctuation,
Ident,
Variable,
Skip,
}
struct Scanned<'a> {
start: usize,
end: usize,
raw: &'a str,
kind: Lexical,
}
fn compute_from_tokens(
text: &str,
parsed: &ParsedFile,
schemas: &HashMap<String, Arc<Schema>>,
index: &LineIndex,
scanned: &[Scanned<'_>],
out: &mut Vec<AbsoluteToken>,
) {
// Previous and next non-comment token indices, used to resolve `a.b`.
let mut previous: Vec<Option<usize>> = vec![None; scanned.len()];
let mut next: Vec<Option<usize>> = vec![None; scanned.len()];
let mut last_significant = None;
for (position, token) in scanned.iter().enumerate() {
previous[position] = last_significant;
if token.kind != Lexical::Comment && token.kind != Lexical::Skip {
last_significant = Some(position);
}
}
last_significant = None;
for (position, token) in scanned.iter().enumerate().rev() {
next[position] = last_significant;
if token.kind != Lexical::Comment && token.kind != Lexical::Skip {
last_significant = Some(position);
}
}
let mut aliases: HashMap<usize, Aliases> = HashMap::new();
for (position, token) in scanned.iter().enumerate() {
let token_type = match token.kind {
Lexical::Skip => continue,
Lexical::Keyword => KEYWORD,
Lexical::String => STRING,
Lexical::Number => NUMBER,
Lexical::Comment => COMMENT,
Lexical::Operator => OPERATOR,
Lexical::Punctuation => continue,
Lexical::Variable => VARIABLE,
Lexical::Ident => {
let Some(statement_index) = parsed.statements.iter().position(|statement| {
token.start >= statement.content_span.start
&& token.start < statement.content_span.end
}) else {
continue;
};
let statement = &parsed.statements[statement_index];
let Some(schema) = statement.database.as_ref().and_then(|url| schemas.get(url))
else {
continue;
};
let aliases = aliases.entry(statement_index).or_insert_with(|| {
Aliases::parse(&parsed.tokens, text, statement.content_span)
});
let (value, quoted) = match ident_from_raw(token.raw) {
Some(value) => value,
None => continue,
};
let qualifier = previous[position]
.filter(|&index| is_dot(&scanned[index]))
.and_then(|dot| previous[dot])
.and_then(|index| ident_from_raw(scanned[index].raw));
let next_is_dot = next[position].is_some_and(|index| is_dot(&scanned[index]));
match resolve_identifier(schema, aliases, &value, quoted, qualifier, next_is_dot) {
Some(token_type) => token_type,
None => continue,
}
}
};
push_multiline(out, index, text, token.start, token.end, token_type);
}
}
fn resolve_identifier(
schema: &Schema,
aliases: &Aliases,
value: &str,
quoted: bool,
qualifier: Option<(String, bool)>,
next_is_dot: bool,
) -> Option<u32> {
let normalized = analysis::normalize_ident(value, quoted);
if let Some((qualifier, qualifier_quoted)) = qualifier {
let qualifier = analysis::normalize_ident(&qualifier, qualifier_quoted);
if let Some(qualified) = aliases.resolve(&qualifier) {
if schema.resolve_qualified(qualified).is_some() {
return Some(PROPERTY);
}
}
if schema.schema_exists(&qualifier) {
if schema
.resolve_table(Some(&qualifier), &normalized)
.is_some()
{
return Some(CLASS);
}
if schema
.functions_named(Some(&qualifier), &normalized)
.next()
.is_some()
{
return Some(FUNCTION);
}
} else if schema.resolve_table(None, &qualifier).is_some() {
return Some(PROPERTY);
}
return None;
}
if next_is_dot {
if aliases.resolve(&normalized).is_some()
|| schema.resolve_table(None, &normalized).is_some()
{
return Some(CLASS);
}
if schema.schema_exists(&normalized) {
return Some(NAMESPACE);
}
return None;
}
if schema.resolve_table(None, &normalized).is_some() {
return Some(CLASS);
}
if schema.functions_named(None, &normalized).next().is_some() {
return Some(FUNCTION);
}
if schema.columns_named(&normalized).next().is_some() {
return Some(PROPERTY);
}
if schema.schema_exists(&normalized) {
return Some(NAMESPACE);
}
None
}
fn push_multiline(
out: &mut Vec<AbsoluteToken>,
index: &LineIndex,
text: &str,
start: usize,
end: usize,
token_type: u32,
) {
let mut offset = start;
while offset < end {
let position = index.position(text, offset);
let line = position.line as usize;
let line_end = index.line_content_end(text, line);
let segment_end = end.min(line_end.max(offset));
if segment_end > offset {
let end_position = index.position(text, segment_end);
let length = end_position.character.saturating_sub(position.character);
if length > 0 {
out.push(AbsoluteToken {
line: position.line,
start: position.character,
length,
token_type,
});
}
}
if segment_end >= end {
break;
}
let next_line = line + 1;
if next_line >= index.line_count() {
break;
}
offset = index.line_start(next_line);
}
}
fn delta_encode(tokens: Vec<AbsoluteToken>) -> Vec<SemanticToken> {
let mut data = Vec::with_capacity(tokens.len());
let mut previous_line = 0u32;
let mut previous_start = 0u32;
for token in tokens {
let delta_line = token.line.saturating_sub(previous_line);
let delta_start = if delta_line == 0 {
token.start.saturating_sub(previous_start)
} else {
token.start
};
data.push(SemanticToken {
delta_line,
delta_start,
length: token.length,
token_type: token.token_type,
token_modifiers_bitset: 0,
});
previous_line = token.line;
previous_start = token.start;
}
data
}
fn classify(raw: &str, token: i32, keyword_kind: i32) -> Lexical {
if keyword_kind != 0 {
return Lexical::Keyword;
}
match PgToken::try_from(token) {
Ok(PgToken::Ident | PgToken::Uident) => Lexical::Ident,
Ok(PgToken::Sconst | PgToken::Usconst | PgToken::Bconst | PgToken::Xconst) => {
Lexical::String
}
Ok(PgToken::Fconst | PgToken::Iconst) => Lexical::Number,
Ok(PgToken::SqlComment | PgToken::CComment) => Lexical::Comment,
Ok(PgToken::Param) => Lexical::Variable,
Ok(
PgToken::Ascii40
| PgToken::Ascii41
| PgToken::Ascii44
| PgToken::Ascii46
| PgToken::Ascii58
| PgToken::Ascii59
| PgToken::Ascii91
| PgToken::Ascii93,
) => Lexical::Punctuation,
Ok(
PgToken::Op
| PgToken::Typecast
| PgToken::DotDot
| PgToken::ColonEquals
| PgToken::EqualsGreater
| PgToken::LessEquals
| PgToken::GreaterEquals
| PgToken::NotEquals
| PgToken::Ascii37
| PgToken::Ascii42
| PgToken::Ascii43
| PgToken::Ascii45
| PgToken::Ascii47
| PgToken::Ascii60
| PgToken::Ascii61
| PgToken::Ascii62
| PgToken::Ascii63
| PgToken::Ascii94,
) => Lexical::Operator,
Ok(PgToken::Ascii36) => Lexical::Variable,
_ => {
// Defensive fallback for tokens added by newer PostgreSQL versions.
if raw.starts_with('\'') || raw.starts_with('$') {
Lexical::String
} else if raw.starts_with("--") || raw.starts_with("/*") {
Lexical::Comment
} else if raw.starts_with('"') {
Lexical::Ident
} else if raw.chars().next().is_some_and(|ch| ch.is_ascii_digit()) {
Lexical::Number
} else if raw.chars().all(|ch| "+-*/<>=~!@#%^&|?`".contains(ch)) {
Lexical::Operator
} else {
Lexical::Skip
}
}
}
}
fn ident_from_raw(raw: &str) -> Option<(String, bool)> {
if raw.starts_with('"') {
let inner = raw.strip_prefix('"')?;
let inner = inner.strip_suffix('"').unwrap_or(inner);
Some((inner.replace("\"\"", "\""), true))
} else if raw.chars().next().is_some_and(|ch| {
ch == '_' || ch.is_alphabetic() || (!ch.is_ascii() && !ch.is_whitespace())
}) {
Some((raw.to_string(), false))
} else {
None
}
}
fn is_dot(token: &Scanned<'_>) -> bool {
token.raw == "."
}
#[cfg(test)]
mod tests {
use super::*;
use crate::db::{Column, Table, TableKind};
fn schema() -> Schema {
Schema {
schemas: vec!["public".into()],
search_path: vec!["public".into()],
tables: vec![Table {
schema: "public".into(),
name: "users".into(),
kind: TableKind::Table,
columns: vec![Column {
name: "id".into(),
data_type: "bigint".into(),
nullable: false,
default: None,
}],
}],
functions: vec![],
}
}
fn decode(tokens: &SemanticTokens) -> Vec<(u32, u32, u32, u32)> {
let mut line = 0u32;
let mut start = 0u32;
let mut result = Vec::new();
for token in &tokens.data {
line += token.delta_line;
start = if token.delta_line == 0 {
start + token.delta_start
} else {
token.delta_start
};
result.push((line, start, token.length, token.token_type));
}
result
}
#[test]
fn highlights_keywords_strings_and_schema_objects() {
let sql = "-- @database: postgresql://localhost/db\nSELECT id FROM users WHERE name = 'x';";
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
let url = "postgresql://localhost/db".to_string();
let mut schemas = HashMap::new();
schemas.insert(url, Arc::new(schema()));
let tokens = compute(sql, &parsed, &schemas);
let decoded = decode(&tokens);
let users = sql.find("users").unwrap();
let index = LineIndex::new(sql);
let position = index.position(sql, users);
assert!(decoded.iter().any(|(line, start, _, kind)| {
*line == position.line && *start == position.character && *kind == CLASS
}));
assert!(decoded.iter().any(|(_, _, _, kind)| *kind == KEYWORD));
assert!(decoded.iter().any(|(_, _, _, kind)| *kind == STRING));
}
#[test]
fn highlights_directive_comments() {
let sql = "-- @database: postgresql://localhost/db\nSELECT 1;";
let parsed = ParsedFile::parse(sql, &LineIndex::new(sql));
let tokens = compute(sql, &parsed, &HashMap::new());
assert!(
decode(&tokens)
.iter()
.any(|(_, _, _, kind)| *kind == COMMENT)
);
}
}
+53
View File
@@ -0,0 +1,53 @@
//! Document symbols for the editor outline.
use lsp_types::{DocumentSymbol, SymbolKind};
use crate::position::LineIndex;
use crate::sql::ParsedFile;
/// Builds one outline entry per SQL statement.
pub fn document_symbols(text: &str, parsed: &ParsedFile) -> Vec<DocumentSymbol> {
let index = LineIndex::new(text);
let mut symbols = Vec::with_capacity(parsed.statements.len());
for (number, statement) in parsed.statements.iter().enumerate() {
let label = statement_label(&statement.text, number);
let first_line_end = index.line_content_end(text, statement.line_start);
let selection_span = crate::position::ByteSpan::new(
statement.span.start,
first_line_end
.min(statement.span.end)
.max(statement.span.start),
);
#[allow(deprecated)]
symbols.push(DocumentSymbol {
name: label,
detail: statement_kind(&statement.text),
kind: SymbolKind::OBJECT,
tags: None,
deprecated: None,
range: index.range(text, statement.span),
selection_range: index.range(text, selection_span),
children: None,
});
}
symbols
}
fn statement_label(text: &str, number: usize) -> String {
let first_line = text.lines().next().unwrap_or_default().trim();
let mut label: String = first_line.split_whitespace().collect::<Vec<_>>().join(" ");
if label.is_empty() {
label = format!("Statement {}", number + 1);
}
if label.chars().count() > 80 {
label = label.chars().take(77).collect::<String>() + "...";
}
label
}
fn statement_kind(text: &str) -> Option<String> {
crate::sql::lexer::tokenize(text)
.into_iter()
.find(|token| token.kind == crate::sql::lexer::TokenKind::Word)
.map(|token| token.text(text).to_ascii_uppercase())
}
+126
View File
@@ -0,0 +1,126 @@
use std::io::Write;
use std::sync::Arc;
use anyhow::Result;
use clap::Parser;
use omg_pgs::cli::Cli;
use omg_pgs::db::DbManager;
use omg_pgs::{lsp, rest};
use tokio::net::TcpListener;
use tokio::task::JoinError;
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
init_tracing(cli.verbose);
let manager = Arc::new(DbManager::new());
// The REST port is optional in practice: when an editor starts several
// instances of the binary, only the first one can own the port. The LSP
// must keep working in the others.
let rest_listener = match TcpListener::bind(("127.0.0.1", cli.rest_port)).await {
Ok(listener) => {
tracing::info!("REST listening on http://127.0.0.1:{}", cli.rest_port);
Some(listener)
}
Err(error) => {
tracing::warn!(
port = cli.rest_port,
error = %error,
"could not bind REST port; continuing in LSP-only mode"
);
None
}
};
let rest_available = rest_listener.is_some();
let mut rest_task = tokio::spawn(async move {
match rest_listener {
Some(listener) => rest::serve(listener).await,
None => std::future::pending::<Result<()>>().await,
}
});
// Stdout belongs to the LSP protocol; all diagnostics from this process go
// to stderr through the tracing subscriber.
let lsp_result = tokio::select! {
result = lsp::serve_stdio(manager) => Some(result),
result = &mut rest_task => handle_rest_result(result),
_ = tokio::signal::ctrl_c() => {
tracing::info!("shutting down");
terminate(0);
}
};
let Some(lsp_result) = lsp_result else {
terminate(0);
};
match lsp_result {
Ok(true) => {
// The editor completed the handshake and then closed the session.
rest_task.abort();
terminate(0);
}
Ok(false) if rest_available => {
// Typical headless REST use: stdin is closed without an LSP
// handshake. Keep serving the REST API until interrupted.
tracing::warn!(
"LSP stdin closed before initialization; keeping the REST API running (Ctrl+C to stop)"
);
tokio::select! {
result = &mut rest_task => handle_rest_result(result),
_ = tokio::signal::ctrl_c() => {
tracing::info!("shutting down");
}
}
terminate(0);
}
Ok(false) => terminate(0),
Err(error) => {
tracing::error!(error = %error, "language server failed");
terminate(1);
}
}
}
fn handle_rest_result(result: std::result::Result<Result<()>, JoinError>) -> ! {
match result {
Ok(Ok(())) => {
tracing::warn!("REST server stopped");
terminate(0);
}
Ok(Err(error)) => {
tracing::error!(error = %error, "REST server failed");
terminate(1);
}
Err(error) => {
tracing::error!(error = %error, "REST task failed");
terminate(1);
}
}
}
/// Exits the process without waiting for the blocking stdin reader used by
/// `tokio::io::stdin`. That reader cannot be cancelled while the editor keeps
/// the pipe open, so a normal runtime shutdown would hang after `exit`.
fn terminate(code: i32) -> ! {
let _ = std::io::stderr().flush();
std::process::exit(code);
}
fn init_tracing(verbose: u8) {
let default = match verbose {
0 => "omg_pgs=info,warn",
1 => "omg_pgs=debug,warn",
_ => "omg_pgs=trace,warn",
};
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.with_target(false)
.init();
}
+169
View File
@@ -0,0 +1,169 @@
//! Conversions between byte offsets and LSP positions.
//!
//! LSP positions use zero-based lines and UTF-16 code units for the character
//! offset, while Rust strings are UTF-8 encoded. All protocol-facing code goes
//! through [`LineIndex`] so that non-ASCII SQL (identifiers, string literals,
//! emoji in comments) is mapped correctly.
use lsp_types::{Position, Range};
/// A half-open byte range into a UTF-8 string.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ByteSpan {
pub start: usize,
pub end: usize,
}
impl ByteSpan {
pub const fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
pub const fn is_empty(self) -> bool {
self.start >= self.end
}
pub const fn len(self) -> usize {
self.end.saturating_sub(self.start)
}
}
/// Precomputed start offset of every line in a document.
#[derive(Debug, Clone)]
pub struct LineIndex {
line_starts: Vec<usize>,
}
impl LineIndex {
pub fn new(text: &str) -> Self {
let mut line_starts = vec![0];
for (index, byte) in text.bytes().enumerate() {
if byte == b'\n' {
line_starts.push(index + 1);
}
}
Self { line_starts }
}
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
pub fn line_start(&self, line: usize) -> usize {
self.line_starts
.get(line)
.copied()
.unwrap_or_else(|| self.line_starts.last().copied().unwrap_or(0))
}
/// Byte offset of the end of `line`'s content, excluding the line break.
pub fn line_content_end(&self, text: &str, line: usize) -> usize {
let start = self.line_start(line);
let mut end = if line + 1 < self.line_starts.len() {
self.line_starts[line + 1]
} else {
text.len()
};
while end > start && matches!(text.as_bytes().get(end - 1), Some(b'\n' | b'\r')) {
end -= 1;
}
end
}
/// Converts a byte offset into an LSP position.
///
/// Offsets inside a multi-byte character are rounded down to the nearest
/// character boundary.
pub fn position(&self, text: &str, offset: usize) -> Position {
let offset = clamp_char_boundary(text, offset.min(text.len()));
let line = self
.line_starts
.partition_point(|&start| start <= offset)
.saturating_sub(1);
let start = self.line_start(line);
let end = self.line_content_end(text, line);
let mut character = 0u32;
for (relative, ch) in text[start..end].char_indices() {
if start + relative >= offset {
break;
}
character += ch.len_utf16() as u32;
}
Position::new(line as u32, character)
}
/// Converts an LSP position into a byte offset, clamping to the document.
pub fn offset(&self, text: &str, position: Position) -> usize {
let last_line = self.line_starts.len().saturating_sub(1);
let line = (position.line as usize).min(last_line);
let start = self.line_start(line);
let end = self.line_content_end(text, line);
let mut units = 0u32;
for (relative, ch) in text[start..end].char_indices() {
if units >= position.character {
return start + relative;
}
units += ch.len_utf16() as u32;
}
end
}
pub fn range(&self, text: &str, span: ByteSpan) -> Range {
Range::new(
self.position(text, span.start),
self.position(text, span.end),
)
}
}
fn clamp_char_boundary(text: &str, mut offset: usize) -> usize {
offset = offset.min(text.len());
while offset > 0 && !text.is_char_boundary(offset) {
offset -= 1;
}
offset
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_ascii_offsets() {
let text = "SELECT 1;\nSELECT 2;\n";
let index = LineIndex::new(text);
assert_eq!(index.line_count(), 3);
assert_eq!(index.position(text, 0), Position::new(0, 0));
assert_eq!(index.position(text, 9), Position::new(0, 9));
assert_eq!(index.position(text, 10), Position::new(1, 0));
assert_eq!(index.offset(text, Position::new(1, 8)), 18);
assert_eq!(index.offset(text, Position::new(99, 99)), 20);
}
#[test]
fn maps_utf16_columns() {
let text = "SELECT '😀'; -- комментарий\nSELECT \"колонка\" FROM t;\n";
let index = LineIndex::new(text);
let emoji = text.find('😀').unwrap();
assert_eq!(index.position(text, emoji), Position::new(0, 8));
// The emoji occupies two UTF-16 code units, so the closing quote is at column 10.
assert_eq!(
index.position(text, emoji + '😀'.len_utf8()),
Position::new(0, 10)
);
let line_two = index.line_start(1);
let column = text[line_two..].find('"').unwrap();
assert_eq!(
index.offset(text, Position::new(1, column as u32)),
line_two + column
);
}
#[test]
fn handles_crlf() {
let text = "SELECT 1;\r\nSELECT 2;\r\n";
let index = LineIndex::new(text);
assert_eq!(index.position(text, 11), Position::new(1, 0));
assert_eq!(index.offset(text, Position::new(1, 8)), 19);
}
}
+362
View File
@@ -0,0 +1,362 @@
//! REST API for executing a query selected by file and line.
//!
//! The server binds to localhost only (the caller controls the port). It reads
//! arbitrary files and executes arbitrary SQL with the credentials from the
//! directive, so it must not be exposed to untrusted networks.
use std::path::PathBuf;
use std::time::{Duration, Instant};
use axum::extract::rejection::JsonRejection;
use axum::extract::{Query, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
use crate::db::{ExecError, ExecOutcome, execute, redact_url};
use crate::position::LineIndex;
use crate::sql::{ParsedFile, QueryAtLineError};
const QUERY_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Clone, Copy)]
struct RestState {
timeout: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
#[default]
Json,
Csv,
}
#[derive(Debug, Deserialize)]
struct QueryRequest {
/// Absolute path, or a path relative to the server's working directory.
file: PathBuf,
/// One-based line number.
line: u32,
/// Output format. The query-string parameter is used when omitted here.
format: Option<OutputFormat>,
}
#[derive(Debug, Deserialize)]
struct QueryOptions {
format: Option<OutputFormat>,
}
#[derive(Debug, Serialize)]
struct QueryResponse {
/// Connection URL with the password replaced by `***`.
database: String,
line: u32,
statement: String,
columns: Vec<String>,
/// Each row is an array of text values; `null` is SQL `NULL`.
rows: Vec<Vec<Option<String>>>,
row_count: usize,
rows_affected: Option<u64>,
statement_type: Option<String>,
elapsed_ms: u64,
}
#[derive(Debug, Serialize)]
struct ErrorBody {
error: String,
#[serde(skip_serializing_if = "Option::is_none")]
code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
position: Option<u32>,
}
/// Builds the REST router. Exposed for tests.
pub fn router() -> Router {
Router::new()
.route("/health", get(health))
.route("/query", post(query))
.with_state(RestState {
timeout: QUERY_TIMEOUT,
})
}
pub async fn serve(listener: TcpListener) -> anyhow::Result<()> {
axum::serve(listener, router())
.await
.map_err(|error| anyhow::anyhow!("REST server failed: {error}"))
}
async fn health() -> Response {
Json(serde_json::json!({
"status": "ok",
"version": env!("CARGO_PKG_VERSION"),
}))
.into_response()
}
async fn query(
State(state): State<RestState>,
Query(options): Query<QueryOptions>,
payload: Result<Json<QueryRequest>, JsonRejection>,
) -> Response {
let Json(request) = match payload {
Ok(payload) => payload,
Err(error) => {
return error_response(
StatusCode::BAD_REQUEST,
format!("invalid request body: {error}"),
None,
None,
);
}
};
if request.line == 0 {
return error_response(
StatusCode::BAD_REQUEST,
"`line` must be a one-based line number".to_string(),
None,
None,
);
}
let source = match tokio::fs::read_to_string(&request.file).await {
Ok(source) => source,
Err(error) => {
return error_response(
StatusCode::BAD_REQUEST,
format!("could not read `{}`: {error}", request.file.display()),
None,
None,
);
}
};
let index = LineIndex::new(&source);
let parsed = ParsedFile::parse(&source, &index);
let selected = match parsed.query_at_line(request.line as usize - 1) {
Ok(selected) => selected,
Err(QueryAtLineError::NoDirective) => {
return error_response(
StatusCode::BAD_REQUEST,
"no `-- @database: ...` directive in this file".to_string(),
None,
None,
);
}
Err(QueryAtLineError::NoStatement) => {
return error_response(
StatusCode::BAD_REQUEST,
format!("no SQL statement starts on or spans line {}", request.line),
None,
None,
);
}
Err(QueryAtLineError::NoDatabase) => {
return error_response(
StatusCode::BAD_REQUEST,
format!(
"no `-- @database: ...` directive precedes the statement on line {}",
request.line
),
None,
None,
);
}
};
let started = Instant::now();
let outcome = match execute(&selected.database, &selected.text, state.timeout).await {
Ok(outcome) => outcome,
Err(error) => return execution_error(error),
};
let elapsed_ms = started.elapsed().as_millis() as u64;
let format = request.format.or(options.format).unwrap_or_default();
match format {
OutputFormat::Json => Json(QueryResponse {
database: redact_url(&selected.database),
line: request.line,
statement: selected.text,
columns: outcome.columns.clone(),
row_count: outcome.rows.len(),
rows: outcome.rows,
rows_affected: outcome.rows_affected,
statement_type: outcome.kind,
elapsed_ms,
})
.into_response(),
OutputFormat::Csv => match render_csv(&outcome) {
Ok(csv) => (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/csv; charset=utf-8")],
csv,
)
.into_response(),
Err(error) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("could not encode CSV: {error}"),
None,
None,
),
},
}
}
fn execution_error(error: ExecError) -> Response {
match error {
ExecError::InvalidUrl(message) => {
error_response(StatusCode::BAD_REQUEST, message, None, None)
}
ExecError::Connect(message) => error_response(StatusCode::BAD_GATEWAY, message, None, None),
ExecError::Timeout(timeout) => error_response(
StatusCode::GATEWAY_TIMEOUT,
format!("query timed out after {timeout:?}"),
None,
None,
),
ExecError::Sql {
message,
code,
position,
} => error_response(StatusCode::BAD_REQUEST, message, code, position),
}
}
fn render_csv(outcome: &ExecOutcome) -> Result<String, csv::Error> {
let mut writer = csv::Writer::from_writer(Vec::new());
if !outcome.columns.is_empty() {
writer.write_record(&outcome.columns)?;
}
for row in &outcome.rows {
let values: Vec<&str> = row
.iter()
.map(|value| value.as_deref().unwrap_or(""))
.collect();
writer.write_record(values)?;
}
let bytes = writer.into_inner().map_err(|error| error.into_error())?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
fn error_response(
status: StatusCode,
message: String,
code: Option<String>,
position: Option<u32>,
) -> Response {
(
status,
Json(ErrorBody {
error: message,
code,
position,
}),
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
use tower05::ServiceExt;
async fn call(request: Request<Body>) -> (StatusCode, String) {
let response = router().oneshot(request).await.unwrap();
let status = response.status();
let body = response.into_body().collect().await.unwrap().to_bytes();
(status, String::from_utf8_lossy(&body).into_owned())
}
#[tokio::test]
async fn health_is_available() {
let (status, body) = call(
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(body.contains("\"status\":\"ok\""));
}
#[tokio::test]
async fn rejects_malformed_json() {
let (status, body) = call(
Request::builder()
.method("POST")
.uri("/query")
.header("content-type", "application/json")
.body(Body::from("{"))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert!(body.contains("invalid request body"), "{body}");
}
#[tokio::test]
async fn rejects_invalid_line() {
let (status, body) = call(
Request::builder()
.method("POST")
.uri("/query")
.header("content-type", "application/json")
.body(Body::from(
r#"{"file":"/tmp/does-not-matter.sql","line":0}"#,
))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert!(body.contains("one-based"));
}
#[tokio::test]
async fn reports_missing_directive() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("query.sql");
std::fs::write(&file, "SELECT 1;\n").unwrap();
let body = serde_json::json!({ "file": file.display().to_string(), "line": 1 }).to_string();
let (status, response) = call(
Request::builder()
.method("POST")
.uri("/query")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert!(response.contains("@database"));
}
#[tokio::test]
async fn reports_missing_statement() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("query.sql");
std::fs::write(&file, "-- @database: postgresql://localhost/db\n").unwrap();
let body = serde_json::json!({ "file": file.display().to_string(), "line": 5 }).to_string();
let (status, response) = call(
Request::builder()
.method("POST")
.uri("/query")
.header("content-type", "application/json")
.body(Body::from(body))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert!(response.contains("no SQL statement"));
}
}
+507
View File
@@ -0,0 +1,507 @@
//! Shared SQL analysis helpers used by completion, hover, semantic tokens and
//! diagnostics.
//!
//! The helpers in this module are intentionally heuristic. They never report
//! errors themselves; diagnostics that must be authoritative come from
//! `libpg_query` (syntax) or the PostgreSQL server (semantic checks).
use std::collections::{HashMap, HashSet};
use super::lexer::{self, Token, TokenKind};
use crate::position::ByteSpan;
/// Significant tokens (everything except whitespace and comments) inside `span`.
pub fn significant_tokens(tokens: &[Token], span: ByteSpan) -> Vec<Token> {
tokens
.iter()
.copied()
.filter(|token| token.start >= span.start && token.end <= span.end)
.filter(|token| !token.is_trivia())
.collect()
}
/// Returns the first token that contains `offset`.
///
/// A cursor at the end of a word is considered to be inside that word, which is
/// what completion needs when it is invoked after typing a full identifier.
pub fn token_at(tokens: &[Token], source: &str, offset: usize) -> Option<Token> {
let offset = offset.min(source.len());
tokens.iter().copied().find(|token| {
(token.start <= offset && offset < token.end)
|| (offset == source.len() && token.end == offset)
})
}
/// Returns the identifier token under the cursor, if any.
pub fn ident_at(tokens: &[Token], source: &str, offset: usize) -> Option<Token> {
token_at(tokens, source, offset).filter(|token| {
matches!(token.kind, TokenKind::Word | TokenKind::QuotedIdent) && token.start <= offset
})
}
/// Extracts an identifier value and whether it was double-quoted.
pub fn ident_value(token: Token, source: &str) -> Option<(String, bool)> {
let raw = token.text(source);
match token.kind {
TokenKind::Word => Some((raw.to_string(), false)),
TokenKind::QuotedIdent => {
let inner = raw.strip_prefix('"')?;
let inner = inner.strip_suffix('"').unwrap_or(inner);
Some((inner.replace("\"\"", "\""), true))
}
_ => None,
}
}
/// Normalizes an identifier the way PostgreSQL resolves unquoted identifiers.
pub fn normalize_ident(value: &str, quoted: bool) -> String {
if quoted {
value.to_string()
} else {
value.to_lowercase()
}
}
/// Returns a quoted form of `name` when inserting it into SQL.
pub fn quote_ident(name: &str) -> String {
if is_simple_ident(name) {
name.to_string()
} else {
format!("\"{}\"", name.replace('"', "\"\""))
}
}
fn is_simple_ident(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
if !(first.is_ascii_lowercase() || first == '_') {
return false;
}
chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' || ch == '$')
}
/// Table references and aliases that are visible in a statement.
#[derive(Debug, Clone, Default)]
pub struct Aliases {
by_alias: HashMap<String, String>,
tables: Vec<String>,
ctes: HashSet<String>,
}
impl Aliases {
pub fn parse(tokens: &[Token], source: &str, span: ByteSpan) -> Self {
let sig = significant_tokens(tokens, span);
let mut aliases = Aliases::default();
let mut index = 0usize;
while index < sig.len() {
let word = word_at(&sig, index, source);
match word.as_deref() {
Some("with") => {
index = parse_ctes(&sig, source, index + 1, &mut aliases.ctes);
}
Some("from") => {
index = parse_table_list(&sig, source, index + 1, &mut aliases);
}
Some("join") => {
index = parse_one_table(&sig, source, index + 1, &mut aliases);
}
Some("update" | "into" | "truncate" | "references") => {
index = parse_one_table(&sig, source, index + 1, &mut aliases);
}
_ => index += 1,
}
}
aliases
}
/// Resolves an alias or an unqualified table name to a qualified name.
pub fn resolve(&self, normalized: &str) -> Option<&str> {
self.by_alias.get(normalized).map(String::as_str)
}
pub fn is_cte(&self, normalized: &str) -> bool {
self.ctes.contains(normalized)
}
pub fn table_names(&self) -> &[String] {
&self.tables
}
}
fn parse_ctes(sig: &[Token], source: &str, mut index: usize, ctes: &mut HashSet<String>) -> usize {
if word_at(sig, index, source).as_deref() == Some("recursive") {
index += 1;
}
loop {
let Some((name, quoted)) = ident_at_index(sig, index, source) else {
return index;
};
ctes.insert(normalize_ident(&name, quoted));
index += 1;
// Optional column list.
if punct_at(sig, index, source) == Some("(") {
index = skip_balanced(sig, index, source);
}
if word_at(sig, index, source).as_deref() != Some("as") {
return index;
}
index += 1;
// NOT MATERIALIZED / MATERIALIZED
if word_at(sig, index, source).as_deref() == Some("not") {
index += 1;
}
if word_at(sig, index, source).as_deref() == Some("materialized") {
index += 1;
}
if punct_at(sig, index, source) != Some("(") {
return index;
}
index = skip_balanced(sig, index, source);
if punct_at(sig, index, source) != Some(",") {
return index;
}
index += 1;
}
}
fn parse_table_list(sig: &[Token], source: &str, mut index: usize, aliases: &mut Aliases) -> usize {
loop {
let previous = index;
index = parse_one_table(sig, source, index, aliases);
if index == previous {
return index;
}
if punct_at(sig, index, source) == Some(",") {
index += 1;
continue;
}
return index;
}
}
fn parse_one_table(sig: &[Token], source: &str, mut index: usize, aliases: &mut Aliases) -> usize {
while matches!(
word_at(sig, index, source).as_deref(),
Some("only" | "lateral")
) {
index += 1;
}
let Some((first, quoted)) = ident_at_index(sig, index, source) else {
return index;
};
let first_normalized = normalize_ident(&first, quoted);
index += 1;
let mut qualified = first.clone();
if punct_at(sig, index, source) == Some(".") {
if let Some((second, second_quoted)) = ident_at_index(sig, index + 1, source) {
qualified = format!("{first}.{second}");
let _ = second_quoted;
index += 2;
}
}
let allowed =
!aliases.ctes.contains(&first_normalized) && !is_non_alias_keyword(&first_normalized);
if allowed {
if !aliases.tables.iter().any(|table| table == &qualified) {
aliases.tables.push(qualified.clone());
}
aliases
.by_alias
.entry(first_normalized.clone())
.or_insert_with(|| qualified.clone());
if let Some((_, last)) = qualified.rsplit_once('.') {
aliases
.by_alias
.entry(last.to_lowercase())
.or_insert_with(|| qualified.clone());
}
}
let mut alias_index = index;
if word_at(sig, alias_index, source).as_deref() == Some("as") {
alias_index += 1;
}
if let Some((alias, alias_quoted)) = ident_at_index(sig, alias_index, source) {
let normalized = normalize_ident(&alias, alias_quoted);
if !is_non_alias_keyword(&normalized) {
aliases.by_alias.insert(normalized, qualified);
index = alias_index + 1;
}
}
index
}
fn skip_balanced(sig: &[Token], mut index: usize, source: &str) -> usize {
if punct_at(sig, index, source) != Some("(") {
return index;
}
let mut depth = 0usize;
while index < sig.len() {
match punct_at(sig, index, source) {
Some("(") => depth += 1,
Some(")") => {
depth = depth.saturating_sub(1);
if depth == 0 {
return index + 1;
}
}
_ => {}
}
index += 1;
}
index
}
fn ident_at_index(sig: &[Token], index: usize, source: &str) -> Option<(String, bool)> {
sig.get(index).and_then(|token| ident_value(*token, source))
}
fn punct_at<'a>(sig: &'a [Token], index: usize, source: &'a str) -> Option<&'a str> {
sig.get(index)
.filter(|token| token.kind == TokenKind::Punctuation)
.map(|token| token.text(source))
}
fn word_at(sig: &[Token], index: usize, source: &str) -> Option<String> {
sig.get(index)
.filter(|token| token.kind == TokenKind::Word)
.map(|token| token.text(source).to_ascii_lowercase())
}
fn is_non_alias_keyword(word: &str) -> bool {
matches!(
word,
"where"
| "join"
| "inner"
| "left"
| "right"
| "full"
| "cross"
| "natural"
| "on"
| "using"
| "group"
| "order"
| "limit"
| "offset"
| "having"
| "union"
| "intersect"
| "except"
| "returning"
| "set"
| "values"
| "for"
| "window"
| "fetch"
| "tablesample"
| "as"
| "and"
| "or"
| "when"
| "then"
| "else"
| "end"
| "from"
| "into"
| "update"
| "delete"
| "insert"
| "select"
| "with"
| "recursive"
| "lateral"
| "only"
| "true"
| "false"
| "null"
| "is"
| "not"
| "in"
| "exists"
| "case"
| "distinct"
| "all"
| "asc"
| "desc"
| "nulls"
| "first"
| "last"
| "collate"
| "do"
| "nothing"
| "conflict"
| "default"
| "primary"
| "references"
| "constraint"
| "check"
| "unique"
)
}
/// The broad clause around the cursor. Used to decide what completion should
/// offer and which tables are in scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Clause {
Start,
Select,
From,
Predicate,
Set,
Into,
Any,
}
/// Finds the nearest meaningful clause keyword before the cursor.
pub fn current_clause(tokens: &[Token], source: &str, span: ByteSpan) -> Clause {
let sig = significant_tokens(tokens, span);
for token in sig.iter().rev() {
if token.kind == TokenKind::Punctuation && token.text(source) == ";" {
break;
}
if token.kind != TokenKind::Word {
continue;
}
let word = token.text(source).to_ascii_lowercase();
match word.as_str() {
"from" | "join" => return Clause::From,
"update" | "into" | "truncate" | "table" | "references" => return Clause::Into,
"set" => return Clause::Set,
"where" | "having" | "on" | "when" | "and" | "or" | "returning" | "values" => {
return Clause::Predicate;
}
"select" | "by" | "distinct" | "order" | "group" => return Clause::Select,
"insert" | "delete" => return Clause::Any,
_ => {}
}
}
Clause::Start
}
/// Locates the token mentioned by a `libpg_query` parse error.
///
/// `libpg_query` returns a message such as `syntax error at or near "FROM"`
/// without a cursor position, so the best we can do is find the first matching
/// token. When no token can be identified the caller should fall back to the
/// whole statement.
pub fn locate_parse_error(source: &str, message: &str) -> Option<ByteSpan> {
let tokens = lexer::tokenize(source);
if message.contains("at end of input") {
return tokens
.iter()
.rev()
.find(|token| !token.is_trivia() && token.text(source) != ";")
.map(|token| token.span());
}
let marker = "at or near \"";
let start = message.find(marker)? + marker.len();
let rest = &message[start..];
let end = rest.rfind('"').unwrap_or(rest.len());
let fragment = &rest[..end];
if fragment.is_empty() {
return None;
}
let candidates = tokens
.iter()
.filter(|token| !token.is_trivia() && token.text(source) != ";");
for token in candidates.clone() {
if token.text(source).eq_ignore_ascii_case(fragment) {
return Some(token.span());
}
}
for token in candidates {
let text = token.text(source);
if text.starts_with(fragment) || fragment.starts_with(text) {
return Some(token.span());
}
}
None
}
/// Converts a 0-based character offset into a byte offset inside `source`.
pub fn char_offset_to_byte(source: &str, character_offset: usize) -> usize {
source
.char_indices()
.nth(character_offset)
.map(|(byte, _)| byte)
.unwrap_or(source.len())
}
#[cfg(test)]
mod tests {
use super::*;
fn aliases(sql: &str) -> Aliases {
let tokens = lexer::tokenize(sql);
Aliases::parse(&tokens, sql, ByteSpan::new(0, sql.len()))
}
#[test]
fn finds_tables_aliases_and_ctes() {
let sql = "WITH recent AS (SELECT * FROM orders) \
SELECT u.id, o.total FROM public.users AS u \
JOIN orders o ON o.user_id = u.id";
let aliases = aliases(sql);
assert_eq!(aliases.resolve("u"), Some("public.users"));
assert_eq!(aliases.resolve("o"), Some("orders"));
assert_eq!(aliases.resolve("users"), Some("public.users"));
assert!(aliases.is_cte("recent"));
assert!(aliases.table_names().iter().any(|table| table == "orders"));
}
#[test]
fn does_not_treat_keywords_as_aliases() {
let sql = "SELECT * FROM users WHERE active";
let aliases = aliases(sql);
assert_eq!(aliases.resolve("where"), None);
assert_eq!(aliases.resolve("users"), Some("users"));
}
#[test]
fn parses_from_lists() {
let sql = "SELECT * FROM users u, accounts a WHERE u.id = a.user_id";
let aliases = aliases(sql);
assert_eq!(aliases.resolve("u"), Some("users"));
assert_eq!(aliases.resolve("a"), Some("accounts"));
}
#[test]
fn detects_clause() {
let cases = [
("SELECT ", Clause::Select),
("SELECT * FROM ", Clause::From),
("SELECT * FROM t, ", Clause::From),
("SELECT * FROM t WHERE ", Clause::Predicate),
("UPDATE t SET ", Clause::Set),
("INSERT INTO ", Clause::Into),
("DELETE FROM ", Clause::From),
];
for (sql, expected) in cases {
let tokens = lexer::tokenize(sql);
let clause = current_clause(&tokens, sql, ByteSpan::new(0, sql.len()));
assert_eq!(clause, expected, "{sql}");
}
}
#[test]
fn extracts_error_token() {
let span =
locate_parse_error("SELECT * FORM users", "syntax error at or near \"users\"").unwrap();
assert_eq!(&"SELECT * FORM users"[span.start..span.end], "users");
let eof = locate_parse_error("SELECT * FROM", "syntax error at end of input").unwrap();
assert_eq!(&"SELECT * FROM"[eof.start..eof.end], "FROM");
}
}
+414
View File
@@ -0,0 +1,414 @@
//! Parsing of database directives and SQL statements inside an editor buffer.
use crate::position::{ByteSpan, LineIndex};
use super::analysis;
use super::lexer::{self, Token, TokenKind};
/// A `-- @database: <url>` comment.
///
/// Both `@database` (canonical) and `@databse` (a common typo that is accepted
/// for compatibility with early versions of this tool) are recognized.
#[derive(Debug, Clone)]
pub struct Directive {
/// Everything after the colon, trimmed. May be empty or invalid.
pub url: String,
/// Span of the URL (or of the directive name when the URL is empty).
pub url_span: ByteSpan,
/// Span of the whole comment token.
pub full_span: ByteSpan,
/// Zero-based line containing the directive.
pub line: usize,
}
/// A single SQL statement together with its database context.
#[derive(Debug, Clone)]
pub struct Statement {
/// Trimmed span of the statement, including leading comments.
pub span: ByteSpan,
/// Span from the first to the last significant token.
pub content_span: ByteSpan,
/// Statement text passed to PostgreSQL. Includes leading comments.
pub text: String,
pub line_start: usize,
pub line_end: usize,
/// Index into [`ParsedFile::directives`] of the active directive.
pub directive_index: Option<usize>,
/// URL of the active directive, if it is non-empty.
pub database: Option<String>,
}
/// Result of parsing a whole document.
#[derive(Debug, Clone)]
pub struct ParsedFile {
pub tokens: Vec<Token>,
pub directives: Vec<Directive>,
pub statements: Vec<Statement>,
}
/// A statement selected by the REST API.
#[derive(Debug, Clone)]
pub struct QueryAtLine {
pub text: String,
pub database: String,
pub line_start: usize,
pub line_end: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum QueryAtLineError {
#[error("no `-- @database: ...` directive in this file")]
NoDirective,
#[error("no SQL statement starts on or spans this line")]
NoStatement,
#[error("no `-- @database: ...` directive precedes this statement")]
NoDatabase,
}
impl ParsedFile {
pub fn parse(source: &str, line_index: &LineIndex) -> Self {
let tokens = lexer::tokenize(source);
let directives = parse_directives(source, &tokens, line_index);
let mut statements = Vec::new();
let mut segment_start = 0usize;
for token in &tokens {
if token.kind == TokenKind::Punctuation && token.text(source) == ";" {
push_statement(
source,
&tokens,
ByteSpan::new(segment_start, token.end),
line_index,
&directives,
&mut statements,
);
segment_start = token.end;
}
}
push_statement(
source,
&tokens,
ByteSpan::new(segment_start, source.len()),
line_index,
&directives,
&mut statements,
);
Self {
tokens,
directives,
statements,
}
}
pub fn statement_at_line(&self, line: usize) -> Option<&Statement> {
self.statements
.iter()
.find(|statement| line >= statement.line_start && line <= statement.line_end)
}
pub fn statement_at_offset(&self, offset: usize) -> Option<&Statement> {
self.statements.iter().find(|statement| {
offset >= statement.content_span.start && offset <= statement.content_span.end
})
}
/// The directive that is active at `offset` (the last one before it).
pub fn directive_at_offset(&self, offset: usize) -> Option<&Directive> {
self.directives
.iter()
.rev()
.find(|directive| directive.full_span.end <= offset)
}
pub fn directive_at_line(&self, line: usize) -> Option<&Directive> {
self.directives
.iter()
.find(|directive| directive.line == line)
}
/// Selects the statement spanning `line` (zero-based) and its database.
pub fn query_at_line(&self, line: usize) -> Result<QueryAtLine, QueryAtLineError> {
if self.directives.is_empty() {
return Err(QueryAtLineError::NoDirective);
}
let statement = self
.statement_at_line(line)
.ok_or(QueryAtLineError::NoStatement)?;
let database = statement
.database
.as_ref()
.filter(|url| !url.trim().is_empty())
.ok_or(QueryAtLineError::NoDatabase)?;
Ok(QueryAtLine {
text: statement.text.clone(),
database: database.clone(),
line_start: statement.line_start,
line_end: statement.line_end,
})
}
/// Returns the most recent non-empty directive before `offset`.
pub fn database_before(&self, offset: usize) -> Option<&Directive> {
self.directive_at_offset(offset)
.filter(|directive| !directive.url.trim().is_empty())
}
}
fn push_statement(
source: &str,
tokens: &[Token],
segment: ByteSpan,
line_index: &LineIndex,
directives: &[Directive],
statements: &mut Vec<Statement>,
) {
let significant: Vec<Token> = tokens
.iter()
.copied()
.filter(|token| token.start >= segment.start && token.end <= segment.end)
.filter(|token| !token.is_trivia())
.collect();
if significant.is_empty() {
return;
}
// A lone separator (`;`) is not a statement.
if significant
.iter()
.all(|token| token.kind == TokenKind::Punctuation && token.text(source) == ";")
{
return;
}
let content_span = ByteSpan::new(
significant
.first()
.map(|token| token.start)
.unwrap_or(segment.start),
significant
.last()
.map(|token| token.end)
.unwrap_or(segment.start),
);
// Start at the first significant token so that leading comments (including
// the database directive itself) are not echoed back by the REST API or
// included in positions reported for validation errors.
let span = lexer::trim_span(
source,
ByteSpan::new(content_span.start.max(segment.start), segment.end),
);
if span.is_empty() {
return;
}
let directive_index = directives
.iter()
.enumerate()
.rev()
.find(|(_, directive)| directive.full_span.end <= content_span.start)
.map(|(index, _)| index);
let database = directive_index
.and_then(|index| directives.get(index))
.map(|directive| directive.url.clone())
.filter(|url| !url.trim().is_empty());
let text = source[span.start..span.end].to_string();
let line_start = line_index.position(source, content_span.start).line as usize;
let line_end = line_index
.position(
source,
content_span.end.saturating_sub(1).max(content_span.start),
)
.line as usize;
statements.push(Statement {
span,
content_span,
text,
line_start,
line_end,
directive_index,
database,
});
}
fn parse_directives(source: &str, tokens: &[Token], line_index: &LineIndex) -> Vec<Directive> {
let mut directives = Vec::new();
for token in tokens {
if token.kind != TokenKind::LineComment {
continue;
}
let Some(comment) = source.get(token.start..token.end) else {
continue;
};
if !comment.starts_with("--") {
continue;
}
let body = &comment[2..];
let trimmed = body.trim_start();
let name_start = token.start + 2 + (body.len() - trimmed.len());
let Some(colon) = trimmed.find(':') else {
continue;
};
let name = trimmed[..colon].trim();
if !(name.eq_ignore_ascii_case("@database") || name.eq_ignore_ascii_case("@databse")) {
continue;
}
let raw_value = &trimmed[colon + 1..];
let value = raw_value.trim();
let value_start = name_start + colon + 1 + (raw_value.len() - raw_value.trim_start().len());
let url_span = if value.is_empty() {
ByteSpan::new(name_start, name_start + name.len())
} else {
ByteSpan::new(value_start, value_start + value.len())
};
let line = line_index.position(source, token.start).line as usize;
directives.push(Directive {
url: value.to_string(),
url_span,
full_span: token.span(),
line,
});
}
directives
}
/// Returns the span of the statement that contains `offset`, including a
/// statement whose trailing semicolon is at the cursor.
pub fn statement_span_at(parsed: &ParsedFile, offset: usize) -> Option<ByteSpan> {
parsed
.statement_at_offset(offset)
.map(|statement| statement.content_span)
}
/// Helper used by completion to determine which statement is being edited.
pub fn statement_tokens_at(parsed: &ParsedFile, offset: usize) -> Option<Vec<Token>> {
let statement = parsed.statement_at_offset(offset)?;
Some(analysis::significant_tokens(
&parsed.tokens,
statement.content_span,
))
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(source: &str) -> ParsedFile {
let index = LineIndex::new(source);
ParsedFile::parse(source, &index)
}
#[test]
fn parses_directives_and_assigns_statement_context() {
let source = "\
-- @database: postgresql://a/db
SELECT 1;
-- @databse: postgresql://b/db
SELECT 2;
SELECT 3;
";
let parsed = parse(source);
assert_eq!(parsed.directives.len(), 2);
assert_eq!(parsed.statements.len(), 3);
assert_eq!(
parsed.statements[0].database.as_deref(),
Some("postgresql://a/db")
);
assert_eq!(
parsed.statements[1].database.as_deref(),
Some("postgresql://b/db")
);
assert_eq!(
parsed.statements[2].database.as_deref(),
Some("postgresql://b/db")
);
assert_eq!(
parsed.directives[0].url_span.start,
source.find("postgresql://a/db").unwrap()
);
assert_eq!(
parsed.directives[0].url_span.len(),
"postgresql://a/db".len()
);
}
#[test]
fn splits_on_real_statement_boundaries_only() {
let source = "SELECT ';' AS a; SELECT $tag$; still one$tag$; -- ;\nSELECT 3";
let parsed = parse(source);
let texts: Vec<_> = parsed
.statements
.iter()
.map(|statement| statement.text.as_str())
.collect();
assert_eq!(texts.len(), 3);
assert!(texts[0].starts_with("SELECT ';'"));
assert!(texts[1].contains("$tag$; still one$tag$"));
assert!(texts[2].starts_with("SELECT 3"));
}
#[test]
fn ignores_directive_only_lines_for_query_lookup() {
let source = "-- @database: postgresql://localhost/db\n\nSELECT 1;\n";
let parsed = parse(source);
assert!(parsed.statement_at_line(0).is_none());
assert!(parsed.statement_at_line(2).is_some());
assert_eq!(parsed.query_at_line(2).unwrap().text, "SELECT 1;");
}
#[test]
fn selects_multiline_statement_by_any_line() {
let source =
"-- @database: postgresql://localhost/db\nSELECT\n id,\n name\nFROM users;\n";
let parsed = parse(source);
for line in 1..=4 {
assert!(parsed.statement_at_line(line).is_some(), "line {line}");
assert_eq!(
parsed.query_at_line(line).unwrap().database,
"postgresql://localhost/db"
);
}
}
#[test]
fn reports_missing_directive_and_database() {
let parsed = parse("SELECT 1;");
assert_eq!(
parsed.query_at_line(0).unwrap_err(),
QueryAtLineError::NoDirective
);
let parsed = parse("-- @database:\nSELECT 1;");
assert_eq!(
parsed.query_at_line(1).unwrap_err(),
QueryAtLineError::NoDatabase
);
let parsed = parse("-- @database: postgresql://localhost/db\nSELECT 1;");
assert_eq!(
parsed.query_at_line(0).unwrap_err(),
QueryAtLineError::NoStatement
);
}
#[test]
fn supports_directive_without_space_after_dashes() {
let parsed = parse("--@database: postgresql://localhost/db\nSELECT 1;");
assert_eq!(parsed.directives.len(), 1);
assert_eq!(
parsed.statements[0].database.as_deref(),
Some("postgresql://localhost/db")
);
}
#[test]
fn handles_crlf() {
let source = "-- @database: postgresql://localhost/db\r\nSELECT\r\n 1;\r\n";
let parsed = parse(source);
assert!(parsed.query_at_line(1).is_ok());
assert!(parsed.query_at_line(2).is_ok());
}
}
+490
View File
@@ -0,0 +1,490 @@
//! A small PostgreSQL-aware lexer.
//!
//! The lexer is deliberately independent of `pg_query`: it must keep working
//! on half-typed, syntactically invalid SQL so that statement splitting,
//! directive discovery and completion remain available while the user types.
//! It only needs to understand enough PostgreSQL lexical structure to avoid
//! treating semicolons inside strings or comments as statement separators.
use crate::position::ByteSpan;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenKind {
Whitespace,
LineComment,
BlockComment,
String,
QuotedIdent,
Word,
Number,
Param,
Operator,
Punctuation,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Token {
pub kind: TokenKind,
pub start: usize,
pub end: usize,
}
impl Token {
pub fn span(self) -> ByteSpan {
ByteSpan::new(self.start, self.end)
}
pub fn text<'a>(&self, source: &'a str) -> &'a str {
source.get(self.start..self.end).unwrap_or_default()
}
pub fn is_trivia(self) -> bool {
matches!(
self.kind,
TokenKind::Whitespace | TokenKind::LineComment | TokenKind::BlockComment
)
}
}
/// Tokenizes PostgreSQL source. The returned tokens cover every byte of the
/// input exactly once.
pub fn tokenize(source: &str) -> Vec<Token> {
let bytes = source.as_bytes();
let len = bytes.len();
let mut tokens = Vec::new();
let mut index = 0usize;
while index < len {
let start = index;
let byte = bytes[index];
if byte.is_ascii_whitespace() {
index += 1;
while index < len && bytes[index].is_ascii_whitespace() {
index += 1;
}
tokens.push(Token {
kind: TokenKind::Whitespace,
start,
end: index,
});
continue;
}
if byte == b'-' && bytes.get(index + 1) == Some(&b'-') {
index += 2;
while index < len && bytes[index] != b'\n' {
index += 1;
}
tokens.push(Token {
kind: TokenKind::LineComment,
start,
end: index,
});
continue;
}
if byte == b'/' && bytes.get(index + 1) == Some(&b'*') {
index = scan_block_comment(bytes, index);
tokens.push(Token {
kind: TokenKind::BlockComment,
start,
end: index,
});
continue;
}
if byte == b'\'' {
index = scan_single_quoted(source, index, has_escape_prefix(source, index));
tokens.push(Token {
kind: TokenKind::String,
start,
end: index,
});
continue;
}
if byte == b'"' {
index = scan_double_quoted(source, index);
tokens.push(Token {
kind: TokenKind::QuotedIdent,
start,
end: index,
});
continue;
}
if byte == b'$' {
if let Some(end) = scan_dollar_quoted(source, index) {
index = end;
tokens.push(Token {
kind: TokenKind::String,
start,
end: index,
});
continue;
}
if bytes.get(index + 1).is_some_and(u8::is_ascii_digit) {
index += 1;
while index < len && bytes[index].is_ascii_digit() {
index += 1;
}
tokens.push(Token {
kind: TokenKind::Param,
start,
end: index,
});
continue;
}
index += 1;
tokens.push(Token {
kind: TokenKind::Other,
start,
end: index,
});
continue;
}
if byte.is_ascii_digit()
|| (byte == b'.' && bytes.get(index + 1).is_some_and(u8::is_ascii_digit))
{
index = scan_number(bytes, index);
tokens.push(Token {
kind: TokenKind::Number,
start,
end: index,
});
continue;
}
let ch = source[index..].chars().next().unwrap_or('\0');
if is_word_start(ch) {
index += ch.len_utf8();
while index < len {
let next = source[index..].chars().next().unwrap_or('\0');
if !is_word_continue(next) {
break;
}
index += next.len_utf8();
}
tokens.push(Token {
kind: TokenKind::Word,
start,
end: index,
});
continue;
}
if byte == b';' || matches!(byte, b'(' | b')' | b'[' | b']' | b',' | b'.') {
index += 1;
tokens.push(Token {
kind: TokenKind::Punctuation,
start,
end: index,
});
continue;
}
if byte == b':' {
if matches!(bytes.get(index + 1), Some(b':' | b'=')) {
index += 2;
tokens.push(Token {
kind: TokenKind::Operator,
start,
end: index,
});
} else {
index += 1;
tokens.push(Token {
kind: TokenKind::Punctuation,
start,
end: index,
});
}
continue;
}
if is_operator_byte(byte) {
index += 1;
while index < len && is_operator_byte(bytes[index]) {
// Do not absorb a `--` comment marker into an operator run.
if bytes[index] == b'-' && bytes.get(index + 1) == Some(&b'-') {
break;
}
index += 1;
}
tokens.push(Token {
kind: TokenKind::Operator,
start,
end: index,
});
continue;
}
index += ch.len_utf8();
tokens.push(Token {
kind: TokenKind::Other,
start,
end: index,
});
}
tokens
}
/// Trims leading and trailing whitespace from `span`, returning a sub-span.
pub fn trim_span(source: &str, span: ByteSpan) -> ByteSpan {
let start = span.start.min(source.len());
let end = span.end.min(source.len()).max(start);
let slice = &source[start..end];
let trimmed = slice.trim();
if trimmed.is_empty() {
return ByteSpan::new(start, start);
}
let lead = trimmed.as_ptr() as usize - slice.as_ptr() as usize;
ByteSpan::new(start + lead, start + lead + trimmed.len())
}
fn scan_block_comment(bytes: &[u8], mut index: usize) -> usize {
let len = bytes.len();
index += 2;
let mut depth = 1usize;
while index < len {
if bytes[index] == b'/' && bytes.get(index + 1) == Some(&b'*') {
depth += 1;
index += 2;
} else if bytes[index] == b'*' && bytes.get(index + 1) == Some(&b'/') {
depth -= 1;
index += 2;
if depth == 0 {
return index;
}
} else {
index += 1;
}
}
len
}
fn scan_single_quoted(source: &str, mut index: usize, backslash_escapes: bool) -> usize {
let bytes = source.as_bytes();
let len = bytes.len();
index += 1;
while index < len {
match bytes[index] {
b'\'' => {
if bytes.get(index + 1) == Some(&b'\'') {
index += 2;
} else {
return index + 1;
}
}
b'\\' if backslash_escapes => {
index += 1;
if index < len {
index += char_len_at(source, index);
}
}
_ => index += char_len_at(source, index),
}
}
len
}
fn scan_double_quoted(source: &str, mut index: usize) -> usize {
let bytes = source.as_bytes();
let len = bytes.len();
index += 1;
while index < len {
if bytes[index] == b'"' {
if bytes.get(index + 1) == Some(&b'"') {
index += 2;
} else {
return index + 1;
}
} else {
index += char_len_at(source, index);
}
}
len
}
fn scan_dollar_quoted(source: &str, index: usize) -> Option<usize> {
let bytes = source.as_bytes();
let len = bytes.len();
let mut tag_end = index + 1;
while tag_end < len && (bytes[tag_end].is_ascii_alphanumeric() || bytes[tag_end] == b'_') {
tag_end += 1;
}
if tag_end >= len || bytes[tag_end] != b'$' {
return None;
}
// A dollar-quote tag may be empty but cannot start with a digit; otherwise
// `$1` would be mistaken for a tag.
let tag_body = &source[index + 1..tag_end];
if tag_body
.chars()
.next()
.is_some_and(|ch| ch.is_ascii_digit())
{
return None;
}
let delimiter = &source[index..=tag_end];
let body_start = tag_end + 1;
let relative = source.get(body_start..)?.find(delimiter)?;
Some(body_start + relative + delimiter.len())
}
fn scan_number(bytes: &[u8], mut index: usize) -> usize {
let len = bytes.len();
let mut seen_dot = false;
while index < len {
let byte = bytes[index];
if byte.is_ascii_digit() || byte == b'_' {
index += 1;
} else if byte == b'.' && !seen_dot && bytes.get(index + 1) != Some(&b'.') {
seen_dot = true;
index += 1;
} else if matches!(byte, b'e' | b'E') {
index += 1;
if matches!(bytes.get(index), Some(b'+' | b'-')) {
index += 1;
}
} else {
break;
}
}
index
}
fn has_escape_prefix(source: &str, index: usize) -> bool {
let bytes = source.as_bytes();
if index == 0 || !matches!(bytes[index - 1], b'e' | b'E') {
return false;
}
if index == 1 {
return true;
}
let previous = source[..index - 1].chars().next_back().unwrap_or('\0');
!is_word_continue(previous)
}
fn is_word_start(ch: char) -> bool {
ch == '_' || ch.is_alphabetic() || (!ch.is_ascii() && !ch.is_whitespace())
}
fn is_word_continue(ch: char) -> bool {
ch == '_' || ch == '$' || ch.is_alphanumeric() || (!ch.is_ascii() && !ch.is_whitespace())
}
fn is_operator_byte(byte: u8) -> bool {
matches!(
byte,
b'+' | b'-'
| b'*'
| b'/'
| b'<'
| b'>'
| b'='
| b'~'
| b'!'
| b'@'
| b'#'
| b'%'
| b'^'
| b'&'
| b'|'
| b'?'
| b'\\'
)
}
fn char_len_at(source: &str, index: usize) -> usize {
source[index..]
.chars()
.next()
.map(char::len_utf8)
.unwrap_or(1)
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(sql: &str) -> Vec<TokenKind> {
tokenize(sql)
.into_iter()
.filter(|token| token.kind != TokenKind::Whitespace)
.map(|token| token.kind)
.collect()
}
#[test]
fn ignores_semicolons_in_lexical_constructs() {
let sql = "select ';', \"a;b\", $$;$$, $tag$; $x$ $tag$; -- ;\n; select 1";
let semicolons: Vec<_> = tokenize(sql)
.into_iter()
.filter(|token| token.kind == TokenKind::Punctuation && token.text(sql) == ";")
.collect();
assert_eq!(semicolons.len(), 2);
}
#[test]
fn handles_nested_block_comments() {
let sql = "select /* outer /* inner */ still outer */ 1;";
assert_eq!(
kinds(sql),
vec![
TokenKind::Word,
TokenKind::BlockComment,
TokenKind::Number,
TokenKind::Punctuation
]
);
}
#[test]
fn handles_escaped_quotes() {
let sql = r#"select 'it''s', E'it\'s', "a""b";"#;
let tokens = tokenize(sql);
assert_eq!(
tokens
.iter()
.filter(|t| t.kind == TokenKind::String)
.count(),
2
);
assert_eq!(
tokens
.iter()
.filter(|t| t.kind == TokenKind::QuotedIdent)
.count(),
1
);
}
#[test]
fn recognizes_parameters_and_dollar_tags() {
let sql = "select $1, $tag$ $1 $tag$;";
let tokens = tokenize(sql);
let params = tokens.iter().filter(|t| t.kind == TokenKind::Param).count();
let strings = tokens
.iter()
.filter(|t| t.kind == TokenKind::String)
.count();
assert_eq!(params, 1);
assert_eq!(strings, 1);
}
#[test]
fn covers_the_whole_input() {
let sql = "SELECT 'ж'; -- 😀\n/* x */ SELECT $$a$$";
let tokens = tokenize(sql);
assert_eq!(tokens.first().map(|t| t.start), Some(0));
assert_eq!(tokens.last().map(|t| t.end), Some(sql.len()));
for pair in tokens.windows(2) {
assert_eq!(pair[0].end, pair[1].start);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
//! SQL-specific parsing and analysis.
pub mod analysis;
pub mod document;
pub mod lexer;
pub use document::{Directive, ParsedFile, QueryAtLine, QueryAtLineError, Statement};
pub use lexer::{Token, TokenKind};
+61
View File
@@ -0,0 +1,61 @@
//! Opt-in integration tests against a real PostgreSQL server.
//!
//! Run with:
//!
//! ```bash
//! OMG_PGS_TEST_DATABASE_URL=postgresql://user:password@localhost:5432/db \
//! cargo test --test database
//! ```
//!
//! The tests only read `pg_catalog`, run `SELECT 1`, and attempt to resolve a
//! table that should not exist. They do not create or modify database objects.
use std::time::Duration;
use omg_pgs::db::{DbManager, Validation, execute};
fn test_url() -> Option<String> {
std::env::var("OMG_PGS_TEST_DATABASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
}
#[tokio::test]
async fn validates_statements_and_loads_catalog() {
let Some(url) = test_url() else {
eprintln!("skipping: OMG_PGS_TEST_DATABASE_URL is not set");
return;
};
let manager = DbManager::new();
let database = manager.database(&url).await.unwrap();
database.check_connection().await.unwrap();
assert_eq!(database.validate("SELECT 1").await, Validation::Ok);
match database
.validate("SELECT * FROM omg_pgs_table_that_does_not_exist")
.await
{
Validation::Failed { code, .. } => assert_eq!(code, "42P01"),
other => panic!("expected SQLSTATE 42P01, got {other:?}"),
}
let schema = database.schema(false).await.unwrap();
assert!(!schema.schemas.is_empty());
assert!(!schema.search_path.is_empty());
}
#[tokio::test]
async fn executes_a_simple_query() {
let Some(url) = test_url() else {
eprintln!("skipping: OMG_PGS_TEST_DATABASE_URL is not set");
return;
};
let outcome = execute(&url, "SELECT 1 AS value", Duration::from_secs(20))
.await
.unwrap();
assert_eq!(outcome.columns, vec!["value"]);
assert_eq!(outcome.rows, vec![vec![Some("1".to_string())]]);
}