Skip to content

Commit 1b041b0

Browse files
committed
Merge branch 'main' into chore/more-renaming
2 parents 943d431 + 0a6a0b2 commit 1b041b0

File tree

14 files changed

+115
-104
lines changed

14 files changed

+115
-104
lines changed

.cursorignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
2+
libpg_query/
3+
lib/tree_sitter_sql/tree-sitter-sql/

.github/workflows/release.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Release PG_CLI
1+
name: Release Binary
22

33
on:
44
workflow_dispatch:
@@ -61,7 +61,7 @@ jobs:
6161
DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
6262

6363
- name: 🛠️ Run Build
64-
run: cargo build -p pg_cli --release --target ${{ matrix.config.target }}
64+
run: cargo build -p pglt_cli --release --target ${{ matrix.config.target }}
6565

6666
# windows is a special snowflake to, it saves binaries as .exe
6767
- name: 👦 Name the Binary

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 17 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -2,105 +2,29 @@
22

33
# Postgres Language Server
44

5-
A Language Server for Postgres. Not SQL with flavors, just Postgres.
5+
A collection of language tools and a Language Server Protocol (LSP) implementation for Postgres, focusing on developer experience and reliable SQL tooling.
66

7-
> [!WARNING]
8-
> This is in active development and is only ready for collaborators. But we are getting there! You can find the current roadmap and opportunities to contribute in https://github.com/supabase-community/postgres_lsp/issues/136.
7+
## Overview
98

10-
## Features
9+
This project provides a toolchain for Postgres development, built on Postgres' own parser `libpg_query` to ensure 100% syntax compatibility. It is built on a Server-Client architecture with a transport-agnostic design. This means all features can be accessed not only through the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), but also through other interfaces like a CLI, HTTP APIs, or a WebAssembly module. The goal is to make all the great Postgres tooling out there as accessible as possible, and to build anything that is missing ourselves.
1110

12-
The [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) is an open protocol between code editors and servers to provide code intelligence tools such as code completion and syntax highlighting. This project implements such a language server for Postgres, significantly enhancing the developer experience within your favorite editor by adding:
11+
Currently, the following features are implemented:
12+
- Autocompletion
13+
- Syntax Error Highlighting
14+
- Type-checking (via `EXPLAIN` error insights)
15+
- Linter, inspired by [Squawk](https://squawkhq.com)
1316

14-
- Lint
15-
- Hover
16-
- Typechecking
17-
- Syntax Error Diagnostics
18-
- Inlay Hints
19-
- Auto-Completion
20-
- Code actions such as `Execute the statement under the cursor`, or `Execute the current file`
21-
- Formatter
22-
- ... and many more
23-
24-
We plan to support all of the above for SQL and PL/pgSQL function bodies too!
25-
26-
## Motivation
27-
28-
Despite the rising popularity of Postgres, support for the PL/pgSQL in IDEs and editors is limited. While there are some _generic_ SQL Language Servers[^1] offering the Postgres syntax as a "flavor" within the parser, they usually fall short due to the ever-evolving and complex syntax of PostgreSQL. There are a few proprietary IDEs[^2] that work well, but the features are only available within the respective IDE.
29-
30-
This Language Server is designed to support Postgres, and only Postgres. The server uses [libpg_query](https://github.com/pganalyze/libpg_query), both as a git submodule for access to its protobuf file and as the [pg_query](https://crates.io/crates/pg_query/5.0.0) rust crate, therefore leveraging the PostgreSQL source to parse the SQL code reliably. Using Postgres within a Language Server might seem unconventional, but it's the only reliable way of parsing all valid PostgreSQL queries. You can find a longer rationale on why This is the Way™ [here](https://pganalyze.com/blog/parse-postgresql-queries-in-ruby). While libpg_query was built to execute SQL, and not to build a language server, any shortcomings have been successfully mitigated in the `parser` crate. You can read the [commented source code](./crates/parser/src/lib.rs) for more details on the inner workings of the parser.
31-
32-
Once the parser is stable, and a robust and scalable data model is implemented, the language server will not only provide basic features such as semantic highlighting, code completion and syntax error diagnostics, but also serve as the user interface for all the great tooling of the Postgres ecosystem.
33-
34-
## Installation
35-
36-
> [!WARNING]
37-
> This is not ready for production use. Only install this if you want to help with development.
38-
39-
> [!NOTE]
40-
> Interested in setting up a release process and client extensions for Neovim and VS Code? Please check out https://github.com/supabase-community/postgres_lsp/issues/136!
41-
42-
### Neovim
43-
44-
Add the postgres_lsp executable to your path, and add the following to your config to use it.
45-
46-
```lua
47-
local util = require 'lspconfig.util'
48-
local lspconfig = require 'lspconfig'
49-
50-
require('lspconfig.configs').postgres_lsp = {
51-
default_config = {
52-
name = 'postgres_lsp',
53-
cmd = { 'postgres_lsp' },
54-
filetypes = { 'sql' },
55-
single_file_support = true,
56-
root_dir = util.root_pattern 'root-file.txt',
57-
},
58-
}
59-
60-
lspconfig.postgres_lsp.setup { force_setup = true }
61-
```
62-
63-
### Building from source
64-
65-
You'll need _nightly_ Cargo, Node, and npm installed.
66-
67-
Install the `libpg_query` submodule by running:
68-
69-
```sh
70-
git submodule update --init --recursive
71-
```
72-
73-
If you are using VS Code, you can install both the server and the client extension by running:
74-
75-
```sh
76-
cargo xtask install
77-
```
78-
79-
If you're not using VS Code, you can install the server by running:
80-
81-
```sh
82-
cargo xtask install --server
83-
```
84-
85-
The server binary will be installed in `.cargo/bin`. Make sure that `.cargo/bin` is in `$PATH`.
86-
87-
### Github CodeSpaces
88-
89-
You can setup your development environment on [CodeSpaces](https://github.com/features/codespaces).
90-
91-
After your codespace boots up, run the following command in the shell to install Rust:
92-
93-
```shell
94-
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
95-
```
96-
97-
Proceed with the rest of the installation as usual.
17+
Our current focus is on refining and enhancing these core features while building a robust and easily accessible infrastructure. For future plans and opportunities to contribute, please check out the issues and discussions. Any contributions are welcome!
9818

9919
## Contributors
10020

101-
- [psteinroe](https://github.com/psteinroe) (Maintainer)
21+
- [psteinroe](https://github.com/psteinroe)
22+
- [juleswritescode](https://github.com/juleswritescode)
23+
24+
## Acknowledgements
10225

103-
## Footnotes
26+
A big thanks to the following projects, without which this project wouldn't have been possible:
10427

105-
[^1]: Generic SQL Solutions: [sql-language-server](https://github.com/joe-re/sql-language-server), [pgFormatter](https://github.com/darold/pgFormatter/tree/master), [sql-parser-cst](https://github.com/nene/sql-parser-cst)
106-
[^2]: Proprietary IDEs: [DataGrip](https://www.jetbrains.com/datagrip/)
28+
- [libpg_query](https://github.com/pganalyze/libpg_query): For extracting the Postgres' parser
29+
- [Biome](https://github.com/biomejs/biome): For implementing a toolchain infrastructure we could copy from
30+
- [Squawk](https://github.com/sbdchd/squawk): For the linter inspiration

crates/pglt_analyse/src/rule.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ pub trait Rule: RuleMeta + Sized {
9494
}
9595

9696
/// Diagnostic object returned by a single analysis rule
97-
#[derive(Debug, Diagnostic)]
97+
#[derive(Debug, Diagnostic, PartialEq)]
9898
pub struct RuleDiagnostic {
9999
#[category]
100100
pub(crate) category: &'static Category,
@@ -109,7 +109,7 @@ pub struct RuleDiagnostic {
109109
pub(crate) rule_advice: RuleAdvice,
110110
}
111111

112-
#[derive(Debug, Default)]
112+
#[derive(Debug, Default, PartialEq)]
113113
/// It contains possible advices to show when printing a diagnostic that belong to the rule
114114
pub struct RuleAdvice {
115115
pub(crate) details: Vec<Detail>,
@@ -118,7 +118,7 @@ pub struct RuleAdvice {
118118
pub(crate) code_suggestion_list: Vec<CodeSuggestionAdvice<MarkupBuf>>,
119119
}
120120

121-
#[derive(Debug, Default)]
121+
#[derive(Debug, Default, PartialEq)]
122122
pub struct SuggestionList {
123123
pub(crate) message: MarkupBuf,
124124
pub(crate) list: Vec<MarkupBuf>,
@@ -160,7 +160,7 @@ impl Advices for RuleAdvice {
160160
}
161161
}
162162

163-
#[derive(Debug)]
163+
#[derive(Debug, PartialEq)]
164164
pub struct Detail {
165165
pub log_category: LogCategory,
166166
pub message: MarkupBuf,

crates/pglt_analyser/CONTRIBUTING.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,20 @@ This will cause the documentation generator to ensure the rule does emit
280280
exactly one diagnostic for this code, and to include a snapshot for the
281281
diagnostic in the resulting documentation page.
282282

283+
### Testing the Rule
284+
285+
#### Quick Test
286+
287+
To quickly test your rule, head to the `pglt_analyser/src/lib.rs` file and modify the `debug_test` function.
288+
289+
You should:
290+
291+
- remove the `#[ignore]` macro if present
292+
- change the content of the `SQL` static `&str` to whatever you need
293+
- pass your group and rule to the `RuleFilter::Rule(..)`
294+
295+
If you run the test, you'll see any diagnostics your rule created in your console.
296+
283297
### Code generation
284298

285299
For simplicity, use `just` to run all the commands with:

crates/pglt_analyser/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,7 @@ pglt_analyse = { workspace = true }
1616
pglt_console = { workspace = true }
1717
pglt_query_ext = { workspace = true }
1818
serde = { workspace = true }
19+
20+
[dev-dependencies]
21+
pglt_diagnostics = { workspace = true }
22+
termcolor = { workspace = true }

crates/pglt_analyser/src/lib.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,61 @@ impl<'a> Analyser<'a> {
6565
.collect::<Vec<_>>()
6666
}
6767
}
68+
69+
#[cfg(test)]
70+
mod tests {
71+
use core::slice;
72+
73+
use pglt_analyse::{AnalyserOptions, AnalysisFilter, RuleFilter};
74+
use pglt_console::{
75+
fmt::{Formatter, Termcolor},
76+
markup, Markup,
77+
};
78+
use pglt_diagnostics::PrintDiagnostic;
79+
use termcolor::NoColor;
80+
81+
use crate::Analyser;
82+
83+
#[ignore]
84+
#[test]
85+
fn debug_test() {
86+
fn markup_to_string(markup: Markup) -> String {
87+
let mut buffer = Vec::new();
88+
let mut write = Termcolor(NoColor::new(&mut buffer));
89+
let mut fmt = Formatter::new(&mut write);
90+
fmt.write_markup(markup).unwrap();
91+
92+
String::from_utf8(buffer).unwrap()
93+
}
94+
95+
const SQL: &str = r#"alter table test drop column id;"#;
96+
let rule_filter = RuleFilter::Rule("safety", "banDropColumn");
97+
98+
let filter = AnalysisFilter {
99+
enabled_rules: Some(slice::from_ref(&rule_filter)),
100+
..Default::default()
101+
};
102+
103+
let ast = pglt_query_ext::parse(SQL).expect("failed to parse SQL");
104+
105+
let options = AnalyserOptions::default();
106+
107+
let analyser = Analyser::new(crate::AnalyserConfig {
108+
options: &options,
109+
filter,
110+
});
111+
112+
let results = analyser.run(crate::AnalyserContext { root: &ast });
113+
114+
println!("*******************");
115+
for result in &results {
116+
let text = markup_to_string(markup! {
117+
{PrintDiagnostic::simple(result)}
118+
});
119+
eprintln!("{}", text);
120+
}
121+
println!("*******************");
122+
123+
// assert_eq!(results, vec![]);
124+
}
125+
}

crates/pglt_analyser/src/lint/safety/ban_drop_column.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ declare_lint_rule! {
1212
///
1313
/// ### Invalid
1414
///
15-
/// ```sql,ignore
15+
/// ```sql,expect_diagnostic
1616
/// alter table test drop column id;
1717
/// ```
1818
///

crates/pglt_analyser/src/lint/safety/ban_drop_not_null.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ declare_lint_rule! {
1212
///
1313
/// ### Invalid
1414
///
15-
/// ```sql,ignore
15+
/// ```sql,expect_diagnostic
1616
/// alter table users alter column email drop not null;
1717
/// ```
1818
pub BanDropNotNull {

0 commit comments

Comments
 (0)