commit 4ecf11af48a9ca5ea99fee72e052224e9b1a0269 Author: dedal.qq Date: Fri Nov 20 18:22:13 2026 +0300 Add PostgreSQL LSP server with directive-scoped REST query API diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..14dc266 --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7313025 --- /dev/null +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23d1b16 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +*.log +.env +.idea/ +.vscode/ +.DS_Store diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2d6704b --- /dev/null +++ b/AGENTS.md @@ -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. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c675bc2 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2500 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "auto_impl" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683bf733a032aec4f8954e5c0ec9d5c2183c341c49d0939ad77acc0a19fa338a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower 0.5.3", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bindgen" +version = "0.66.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", + "which", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "der_derive", + "flagset", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid 0.10.3", + "crypto-common", + "ctutils", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lsp-types" +version = "0.94.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66bfd44a06ae10647fe3f8214762e9369fd4248df1350924b4ef9e770a85ea1" +dependencies = [ + "bitflags 1.3.2", + "serde", + "serde_json", + "serde_repr", + "url", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "omg-pgs" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "clap", + "csv", + "http-body-util", + "lsp-types", + "pg_query", + "rustls", + "serde", + "serde_json", + "sqlformat", + "tempfile", + "thiserror 2.0.21", + "tokio", + "tokio-postgres", + "tokio-postgres-rustls", + "tower 0.4.13", + "tower 0.5.3", + "tower-lsp", + "tracing", + "tracing-subscriber", + "url", + "webpki-roots", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" +dependencies = [ + "fixedbitset", + "indexmap", +] + +[[package]] +name = "pg_query" +version = "18.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457bfe74085c505ecaf5468416450969e2e52a66d26bc1a4b2f6944a2daee73f" +dependencies = [ + "bindgen", + "cc", + "fs_extra", + "glob", + "itertools 0.10.5", + "prost", + "prost-build", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64", + "byteorder", + "bytes", + "fallible-iterator", + "hmac", + "md-5", + "memchr", + "rand", + "sha2", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator", + "postgres-protocol", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf" +dependencies = [ + "heck", + "itertools 0.14.0", + "log", + "multimap", + "once_cell", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 2.0.119", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-types" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16" +dependencies = [ + "prost", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlformat" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0705994df478b895f05b8e290e0d46e53187b26f8d889d37b2a0881234922d94" +dependencies = [ + "unicode_categories", + "winnow", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-postgres" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand", + "socket2", + "tokio", + "tokio-util", + "whoami", +] + +[[package]] +name = "tokio-postgres-rustls" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb" +dependencies = [ + "rustls", + "sha2", + "tokio", + "tokio-postgres", + "tokio-rustls", + "webpki-roots", + "x509-cert", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-lsp" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ba052b54a6627628d9b3c34c176e7eda8359b7da9acd497b9f20998d118508" +dependencies = [ + "async-trait", + "auto_impl", + "bytes", + "dashmap", + "futures", + "httparse", + "lsp-types", + "memchr", + "serde", + "serde_json", + "tokio", + "tokio-util", + "tower 0.4.13", + "tower-lsp-macros", + "tracing", +] + +[[package]] +name = "tower-lsp-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84fd902d4e0b9a4b27f2f440108dc034e1758628a9b702f8ec61ad66355422fa" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "unicode_categories" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", + "tls_codec", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8dffedf --- /dev/null +++ b/Cargo.toml @@ -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 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..302942c --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9d0ee7b --- /dev/null +++ b/README.md @@ -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 ` 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). diff --git a/examples/example.sql b/examples/example.sql new file mode 100644 index 0000000..07d1e07 --- /dev/null +++ b/examples/example.sql @@ -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; diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..1bd7df9 --- /dev/null +++ b/src/cli.rs @@ -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, +} diff --git a/src/db/connection.rs b/src/db/connection.rs new file mode 100644 index 0000000..8c5bba0 --- /dev/null +++ b/src/db/connection.rs @@ -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 { + 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 { + 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" + ); + } +} diff --git a/src/db/execute.rs b/src/db/execute.rs new file mode 100644 index 0000000..81db13f --- /dev/null +++ b/src/db/execute.rs @@ -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, + /// Row values. `None` represents SQL `NULL`. + pub rows: Vec>>, + /// Number of rows selected or affected, when the server reported it. + pub rows_affected: Option, + /// Leading statement keyword, for display purposes. + pub kind: Option, +} + +#[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, + position: Option, + }, + #[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 { + 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 { + 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(_))); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..6b19c1e --- /dev/null +++ b/src/db/mod.rs @@ -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>>, +} + +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> { + 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> { + 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>, + schema: RwLock>>, + 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> { + 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 { + 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>> { + 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")); + } +} diff --git a/src/db/schema.rs b/src/db/schema.rs new file mode 100644 index 0000000..111a3c2 --- /dev/null +++ b/src/db/schema.rs @@ -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 { + 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, +} + +#[derive(Debug, Clone)] +pub struct Table { + pub schema: String, + pub name: String, + pub kind: TableKind, + pub columns: Vec, +} + +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, +} + +impl Function { + pub fn signature(&self) -> String { + format!("{}({})", self.name, self.arguments) + } +} + +#[derive(Debug, Clone, Default)] +pub struct Schema { + pub schemas: Vec, + pub tables: Vec, + pub functions: Vec, + pub search_path: Vec, +} + +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 { + self.tables + .iter() + .filter(move |table| table.schema == schema) + } + + pub fn functions_in_schema<'a>( + &'a self, + schema: &'a str, + ) -> impl Iterator { + self.functions + .iter() + .filter(move |function| function.schema == schema) + } + + pub fn all_columns(&self) -> impl Iterator { + 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 { + 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 { + 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 { + 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> { + 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::(row, 0, "schema")) + .collect() +} + +async fn load_search_path(client: &Client) -> Result> { + let row = client + .query_one("SELECT current_schemas(true)", &[]) + .await + .context("loading search_path")?; + let path = get::>(&row, 0, "search_path")?; + if path.is_empty() { + Ok(vec!["public".to_string()]) + } else { + Ok(path) + } +} + +async fn load_tables(client: &Client) -> Result> { + 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 = 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> { + 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 +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()" + ); + } +} diff --git a/src/db/validate.rs b/src/db/validate.rs new file mode 100644 index 0000000..f8debb0 --- /dev/null +++ b/src/db/validate.rs @@ -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, + 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, + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..86460db --- /dev/null +++ b/src/lib.rs @@ -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; diff --git a/src/lsp/backend.rs b/src/lsp/backend.rs new file mode 100644 index 0000000..7d00610 --- /dev/null +++ b/src/lsp/backend.rs @@ -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, + documents: RwLock>>, + initialized: AtomicBool, +} + +impl ServerState { + pub fn new(manager: Arc) -> Self { + Self { + manager, + documents: RwLock::new(HashMap::new()), + initialized: AtomicBool::new(false), + } + } +} + +struct DocumentEntry { + generation: AtomicU64, + closed: AtomicBool, + data: RwLock, +} + +struct DocumentData { + text: String, + index: LineIndex, + parsed: Arc, + 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, +} + +impl Backend { + fn new(client: Client, state: Arc) -> Self { + Self { client, state } + } + + async fn entry(&self, uri: &Url) -> Option> { + self.state.documents.read().await.get(uri).cloned() + } + + async fn snapshot(&self, uri: &Url) -> Option<(String, Arc, 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 { + 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) { + 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> { + 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 { + 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 = { + 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> { + 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> { + 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> { + 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 = 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>> { + 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> { + 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 { + inner: S, + exit: Arc, +} + +impl Service for ExitAware +where + S: Service, Error = ExitedError> + Send + 'static, + S::Future: Send + 'static, +{ + type Response = Option; + type Error = ExitedError; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + 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) -> anyhow::Result { + 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) +} diff --git a/src/lsp/completion.rs b/src/lsp/completion.rs new file mode 100644 index 0000000..8c11ed5 --- /dev/null +++ b/src/lsp/completion.rs @@ -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 { + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 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, prefix: &str, quoted: bool) -> Vec { + 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 { + 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()); + } +} diff --git a/src/lsp/diagnostics.rs b/src/lsp/diagnostics.rs new file mode 100644 index 0000000..20a4b66 --- /dev/null +++ b/src/lsp/diagnostics.rs @@ -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 { + if parsed.directives.is_empty() { + return Vec::new(); + } + + let index = LineIndex::new(text); + let mut diagnostics = Vec::new(); + let mut connections: HashMap> = 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); + } +} diff --git a/src/lsp/formatting.rs b/src/lsp/formatting.rs new file mode 100644 index 0000000..77705ce --- /dev/null +++ b/src/lsp/formatting.rs @@ -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); + } +} diff --git a/src/lsp/hover.rs b/src/lsp/hover.rs new file mode 100644 index 0000000..ed44980 --- /dev/null +++ b/src/lsp/hover.rs @@ -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 { + 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 { + 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")); + } +} diff --git a/src/lsp/mod.rs b/src/lsp/mod.rs new file mode 100644 index 0000000..cf4ba30 --- /dev/null +++ b/src/lsp/mod.rs @@ -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)) +} diff --git a/src/lsp/semantic_tokens.rs b/src/lsp/semantic_tokens.rs new file mode 100644 index 0000000..6df8deb --- /dev/null +++ b/src/lsp/semantic_tokens.rs @@ -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::::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>, +) -> SemanticTokens { + let index = LineIndex::new(text); + let mut absolute = Vec::new(); + + match pg_query::scan_tokens(text) { + Ok(scan_tokens) => { + let scanned: Vec> = 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> = 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 { + 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>, + index: &LineIndex, + scanned: &[Scanned<'_>], + out: &mut Vec, +) { + // Previous and next non-comment token indices, used to resolve `a.b`. + let mut previous: Vec> = vec![None; scanned.len()]; + let mut next: Vec> = 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 = 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 { + 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, + 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) -> Vec { + 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) + ); + } +} diff --git a/src/lsp/symbols.rs b/src/lsp/symbols.rs new file mode 100644 index 0000000..9e7f378 --- /dev/null +++ b/src/lsp/symbols.rs @@ -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 { + 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::>().join(" "); + if label.is_empty() { + label = format!("Statement {}", number + 1); + } + if label.chars().count() > 80 { + label = label.chars().take(77).collect::() + "..."; + } + label +} + +fn statement_kind(text: &str) -> Option { + crate::sql::lexer::tokenize(text) + .into_iter() + .find(|token| token.kind == crate::sql::lexer::TokenKind::Word) + .map(|token| token.text(text).to_ascii_uppercase()) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..766f5c7 --- /dev/null +++ b/src/main.rs @@ -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::>().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, 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(); +} diff --git a/src/position.rs b/src/position.rs new file mode 100644 index 0000000..382594f --- /dev/null +++ b/src/position.rs @@ -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, +} + +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); + } +} diff --git a/src/rest.rs b/src/rest.rs new file mode 100644 index 0000000..0081177 --- /dev/null +++ b/src/rest.rs @@ -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, +} + +#[derive(Debug, Deserialize)] +struct QueryOptions { + format: Option, +} + +#[derive(Debug, Serialize)] +struct QueryResponse { + /// Connection URL with the password replaced by `***`. + database: String, + line: u32, + statement: String, + columns: Vec, + /// Each row is an array of text values; `null` is SQL `NULL`. + rows: Vec>>, + row_count: usize, + rows_affected: Option, + statement_type: Option, + elapsed_ms: u64, +} + +#[derive(Debug, Serialize)] +struct ErrorBody { + error: String, + #[serde(skip_serializing_if = "Option::is_none")] + code: Option, + #[serde(skip_serializing_if = "Option::is_none")] + position: Option, +} + +/// 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, + Query(options): Query, + payload: Result, 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 { + 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, + position: Option, +) -> 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) -> (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")); + } +} diff --git a/src/sql/analysis.rs b/src/sql/analysis.rs new file mode 100644 index 0000000..49f2608 --- /dev/null +++ b/src/sql/analysis.rs @@ -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 { + 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 { + 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_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, + tables: Vec, + ctes: HashSet, +} + +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) -> 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 { + 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 { + 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"); + } +} diff --git a/src/sql/document.rs b/src/sql/document.rs new file mode 100644 index 0000000..67470b6 --- /dev/null +++ b/src/sql/document.rs @@ -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: ` 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, + /// URL of the active directive, if it is non-empty. + pub database: Option, +} + +/// Result of parsing a whole document. +#[derive(Debug, Clone)] +pub struct ParsedFile { + pub tokens: Vec, + pub directives: Vec, + pub statements: Vec, +} + +/// 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 { + 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, +) { + let significant: Vec = 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 { + 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 { + 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> { + 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()); + } +} diff --git a/src/sql/lexer.rs b/src/sql/lexer.rs new file mode 100644 index 0000000..b127f69 --- /dev/null +++ b/src/sql/lexer.rs @@ -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 { + 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 { + 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 { + 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); + } + } +} diff --git a/src/sql/mod.rs b/src/sql/mod.rs new file mode 100644 index 0000000..ce06666 --- /dev/null +++ b/src/sql/mod.rs @@ -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}; diff --git a/tests/database.rs b/tests/database.rs new file mode 100644 index 0000000..107e73d --- /dev/null +++ b/tests/database.rs @@ -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 { + 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())]]); +}