sql-lsp 0.1.3

A high-performance, multi-dialect SQL Language Server Protocol (LSP) implementation in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# SQL LSP Server

<div align="center">

A **high-performance**, **multi-dialect** SQL Language Server Protocol (LSP) implementation in Rust.

[![Rust](https://img.shields.io/badge/rust-1.70+-orange.svg)](https://www.rust-lang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

[Features](#-features) โ€ข [Usage](#-usage) โ€ข [API Reference](#-api-reference) โ€ข [Development](#-development)

</div>

---

## โœจ Features

- ๐ŸŽฏ **Multi-Dialect Support** - MySQL, PostgreSQL, Hive, ClickHouse, Elasticsearch (EQL/DSL), Redis
- ๐Ÿ” **Intelligent Completion** - Context-aware suggestions with AST-based analysis
- ๐Ÿ“ **Code Navigation** - Go-to-definition and find references
- โšก **Real-Time Diagnostics** - Tree-sitter powered syntax error detection
- ๐ŸŽจ **SQL Formatting** - Professional code formatting with sqlformat
- ๐Ÿ“Š **Rich Hover Information** - Detailed schema information in Markdown
- ๐Ÿงต **Thread-Safe** - Concurrent request handling with async/await
- ๐Ÿ“ฆ **Schema Management** - Dynamic schema updates and auto-inference

## ๐Ÿš€ Usage

### Installation

```bash
# Build from source
git clone https://github.com/your-org/lsp_sqls.git
cd lsp_sqls
cargo build --release

# Or install via cargo
cargo install --path .
```

### Starting the Server

The LSP server communicates via stdin/stdout using JSON-RPC 2.0 protocol:

```bash
# Start server
./target/release/sql-lsp

# With debug logging
RUST_LOG=debug ./target/release/sql-lsp
```

### LSP Communication Protocol

All requests and responses follow the [LSP specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/).

#### 1. Initialize

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "processId": 12345,
    "rootUri": "file:///path/to/workspace",
    "capabilities": {
      "textDocument": {
        "completion": { "dynamicRegistration": true },
        "hover": { "dynamicRegistration": true }
      }
    }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "capabilities": {
      "textDocumentSync": 2,
      "completionProvider": { "triggerCharacters": [".", " "] },
      "hoverProvider": true,
      "definitionProvider": true,
      "referencesProvider": true,
      "documentFormattingProvider": true
    },
    "serverInfo": {
      "name": "sql-lsp",
      "version": "0.1.0"
    }
  }
}
```

#### 2. Document Sync

**Open Document:**

```json
{
  "jsonrpc": "2.0",
  "method": "textDocument/didOpen",
  "params": {
    "textDocument": {
      "uri": "file:///path/to/query.sql",
      "languageId": "sql",
      "version": 1,
      "text": "SELECT * FROM users WHERE "
    }
  }
}
```

> **Note on URIs**: The `uri` field can be either:
>
> - **File URI**: `file:///path/to/query.sql` (saved file)
> - **Virtual URI**: `untitled:Untitled-1` (in-memory, unsaved document)
> - **Custom scheme**: `inmemory://model/1` or any custom identifier
>
> The server identifies documents by their URI, so as long as the URI is unique and consistent across requests, it will work correctly.

**Update Document:**

```json
{
  "jsonrpc": "2.0",
  "method": "textDocument/didChange",
  "params": {
    "textDocument": {
      "uri": "file:///path/to/query.sql",
      "version": 2
    },
    "contentChanges": [
      {
        "text": "SELECT * FROM users WHERE id = "
      }
    ]
  }
}
```

#### 3. Completion

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "textDocument/completion",
  "params": {
    "textDocument": { "uri": "file:///path/to/query.sql" },
    "position": { "line": 0, "character": 30 }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "isIncomplete": false,
    "items": [
      {
        "label": "id",
        "kind": 5,
        "detail": "Column: id (INT)",
        "documentation": "User ID",
        "sortText": "0id",
        "insertText": "id"
      },
      {
        "label": "email",
        "kind": 5,
        "detail": "Column: email (VARCHAR)",
        "sortText": "0email",
        "insertText": "email"
      },
      {
        "label": "LIKE",
        "kind": 24,
        "detail": "Operator: LIKE",
        "sortText": "1LIKE",
        "insertText": "LIKE"
      }
    ]
  }
}
```

**Completion Item Kinds:**

- `5` = Field (column)
- `7` = Class (table)
- `3` = Function
- `14` = Keyword
- `24` = Operator

#### 4. Hover

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "textDocument/hover",
  "params": {
    "textDocument": { "uri": "file:///path/to/query.sql" },
    "position": { "line": 0, "character": 14 }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "contents": {
      "kind": "markdown",
      "value": "**Table**: `users`\n\nUser accounts\n\n**Columns** (3)\n- `id`: INT NOT NULL\n- `email`: VARCHAR(255) NOT NULL\n- `name`: VARCHAR(255) NULL"
    },
    "range": {
      "start": { "line": 0, "character": 14 },
      "end": { "line": 0, "character": 19 }
    }
  }
}
```

#### 5. Go to Definition

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "textDocument/definition",
  "params": {
    "textDocument": { "uri": "file:///path/to/query.sql" },
    "position": { "line": 0, "character": 14 }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "uri": "file:///path/to/schema.sql",
    "range": {
      "start": { "line": 42, "character": 0 },
      "end": { "line": 42, "character": 100 }
    }
  }
}
```

#### 6. Diagnostics

**Notification (Server โ†’ Client):**

```json
{
  "jsonrpc": "2.0",
  "method": "textDocument/publishDiagnostics",
  "params": {
    "uri": "file:///path/to/query.sql",
    "diagnostics": [
      {
        "range": {
          "start": { "line": 0, "character": 14 },
          "end": { "line": 0, "character": 18 }
        },
        "severity": 1,
        "code": "SYNTAX_ERROR",
        "source": "tree-sitter-sql",
        "message": "Syntax error: unexpected token"
      }
    ]
  }
}
```

**Severity Levels:**

- `1` = Error
- `2` = Warning
- `3` = Information
- `4` = Hint

#### 7. Document Formatting

**Request:**

```json
{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "textDocument/formatting",
  "params": {
    "textDocument": { "uri": "file:///path/to/query.sql" },
    "options": {
      "tabSize": 2,
      "insertSpaces": true
    }
  }
}
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": [
    {
      "range": {
        "start": { "line": 0, "character": 0 },
        "end": { "line": 0, "character": 50 }
      },
      "newText": "SELECT\n  *\nFROM\n  users\nWHERE\n  id = 1"
    }
  ]
}
```

### Schema Configuration

Configure schemas via `workspace/didChangeConfiguration`:

**Request:**

```json
{
  "jsonrpc": "2.0",
  "method": "workspace/didChangeConfiguration",
  "params": {
    "settings": {
      "sql": {
        "schemas": [
          {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "database": "my_app",
            "source_uri": "file:///path/to/schema.sql",
            "tables": [
              {
                "name": "users",
                "source_location": ["file:///path/to/schema.sql", 42],
                "comment": "User accounts",
                "columns": [
                  {
                    "name": "id",
                    "data_type": "INT",
                    "nullable": false,
                    "comment": "Primary key",
                    "source_location": null
                  },
                  {
                    "name": "email",
                    "data_type": "VARCHAR(255)",
                    "nullable": false,
                    "comment": "User email address",
                    "source_location": null
                  }
                ]
              }
            ],
            "functions": []
          }
        ]
      }
    }
  }
}
```

**Schema Structure:**

```typescript
interface Schema {
  id: string; // UUID
  database: string; // Database name
  source_uri?: string; // Optional schema file URI
  tables: Table[];
  functions: Function[];
}

interface Table {
  name: string;
  comment?: string;
  source_location?: [string, number]; // [URI, line number]
  columns: Column[];
}

interface Column {
  name: string;
  data_type: string; // e.g., "INT", "VARCHAR(255)"
  nullable: boolean;
  comment?: string;
  source_location?: [string, number];
}

interface Function {
  name: string;
  return_type: string;
  parameters: Parameter[];
  description?: string;
}

interface Parameter {
  name: string;
  data_type: string;
  optional: boolean;
}
```

## ๐Ÿ“– API Reference

### Supported LSP Methods

| Method                             | Description                    | Status |
| ---------------------------------- | ------------------------------ | ------ |
| `initialize`                       | Initialize server capabilities | โœ…     |
| `textDocument/didOpen`             | Open document notification     | โœ…     |
| `textDocument/didChange`           | Document change notification   | โœ…     |
| `textDocument/didClose`            | Close document notification    | โœ…     |
| `textDocument/completion`          | Code completion                | โœ…     |
| `textDocument/hover`               | Hover information              | โœ…     |
| `textDocument/definition`          | Go to definition               | โœ…     |
| `textDocument/references`          | Find references                | โœ…     |
| `textDocument/formatting`          | Document formatting            | โœ…     |
| `workspace/didChangeConfiguration` | Configuration updates          | โœ…     |

### Completion Context Detection

The server uses AST-based context analysis to provide accurate completions:

| Context         | Suggestions                     | Example                                 |
| --------------- | ------------------------------- | --------------------------------------- |
| `FromClause`    | Tables only                     | `SELECT * FROM โ€ธ`                       |
| `SelectClause`  | Columns + keywords              | `SELECT โ€ธ FROM users`                   |
| `WhereClause`   | Columns + operators             | `SELECT * FROM users WHERE โ€ธ`           |
| `OrderByClause` | Columns + ASC/DESC              | `SELECT * FROM users ORDER BY โ€ธ`        |
| `GroupByClause` | Columns only                    | `SELECT COUNT(*) FROM users GROUP BY โ€ธ` |
| `HavingClause`  | Columns + functions + operators | `... HAVING โ€ธ`                          |
| `JoinClause`    | Tables only                     | `SELECT * FROM users JOIN โ€ธ`            |
| `TableColumn`   | Specific table columns          | `SELECT u.โ€ธ FROM users u`               |

**Operator Filtering:**

- Only keyword operators are suggested: `LIKE`, `IN`, `BETWEEN`, `IS NULL`, `IS NOT NULL`
- Symbol operators (`=`, `>`, `<`, etc.) are excluded to reduce noise

## ๐Ÿ—„๏ธ Supported SQL Dialects

| Dialect               | Status   | Features                                    |
| --------------------- | -------- | ------------------------------------------- |
| **MySQL**             | โœ… Full  | MySQL 5.7+ syntax, context-aware completion |
| **PostgreSQL**        | โœ… Full  | PostgreSQL 12+ syntax, ILIKE support        |
| **Hive**              | โœ… Full  | HiveQL syntax, PARTITION keyword            |
| **ClickHouse**        | โœ… Full  | ClickHouse SQL, MergeTree support           |
| **Elasticsearch EQL** | โœ… Full  | Event Query Language                        |
| **Elasticsearch DSL** | โœ… Full  | Query DSL (JSON)                            |
| **Redis**             | โœ… Basic | Redis commands (FT.SEARCH, etc.)            |

## ๐Ÿ›  Development

### Prerequisites

- Rust 1.70 or later
- Cargo

### Build

```bash
# Development build
cargo build

# Release build with optimizations
cargo build --release

# Run tests
cargo test --all-features

# Run linter
cargo clippy -- -D warnings

# Format code
cargo fmt
```

### Project Structure

```
lsp_sqls/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.rs           # Entry point
โ”‚   โ”œโ”€โ”€ server.rs         # LSP server implementation
โ”‚   โ”œโ”€โ”€ dialect.rs        # Dialect trait definition
โ”‚   โ”œโ”€โ”€ dialects/         # SQL dialect implementations
โ”‚   โ”‚   โ”œโ”€โ”€ mysql.rs      # MySQL dialect
โ”‚   โ”‚   โ”œโ”€โ”€ postgres.rs   # PostgreSQL dialect
โ”‚   โ”‚   โ””โ”€โ”€ ...
โ”‚   โ”œโ”€โ”€ parser/           # SQL parsers
โ”‚   โ”‚   โ””โ”€โ”€ sql.rs        # Tree-sitter SQL parser
โ”‚   โ”œโ”€โ”€ schema.rs         # Schema management
โ”‚   โ””โ”€โ”€ token.rs          # Token definitions
โ”œโ”€โ”€ tests/                # Integration tests
โ”œโ”€โ”€ docs/                 # Documentation
โ””โ”€โ”€ scripts/              # Helper scripts
    โ””โ”€โ”€ pre-commit        # Git pre-commit hook
```

### Running Tests

```bash
# Run all tests
cargo test --all-features -- --nocapture

# Run specific test
cargo test test_comprehensive_completion_scenarios -- --nocapture

# Run with coverage
cargo tarpaulin --all-features
```

## ๐Ÿค Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and add tests
4. Run pre-commit checks: `make install-pre-commit`
5. Commit: `git commit -m 'feat: add amazing feature'`
6. Push: `git push origin feature/amazing-feature`
7. Open a Pull Request

## ๐Ÿ“ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Built with [tower-lsp]https://github.com/ebkalderon/tower-lsp - LSP framework for Rust
- Powered by [tree-sitter]https://tree-sitter.github.io/ - Parser generator
- Formatted with [sqlformat]https://github.com/shssoichiro/sqlformat-rs - SQL formatter

---

<div align="center">

Made with โค๏ธ using Rust

</div>