postgres-lsp 1.3.1

Language Server Protocol implementation for PostgreSQL and PL/pgSQL
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
use std::sync::Arc;

use dashmap::DashMap;
use postgres_lsp_analysis::WorkspaceIndex;
use postgres_lsp_analysis::code_actions;
use postgres_lsp_analysis::completion::{self, CompletionContext};
use postgres_lsp_analysis::hover;
use postgres_lsp_analysis::resolve;
use postgres_lsp_analysis::signature;
use postgres_lsp_analysis::symbols::QualifiedName;
use postgres_lsp_format::Style;
use postgres_lsp_parse::ParserPool;
use postgres_lsp_parse::document::Document;
use tower_lsp::jsonrpc::{self, Result};
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer};
use tracing::info;

use crate::capabilities;
use crate::diagnostics;
use crate::semantic_tokens;

/// LSP `RequestFailed` error code: the request was valid but could not be carried out.
const REQUEST_FAILED: i64 = -32803;

pub struct Backend {
    client: Client,
    pool: Arc<ParserPool>,
    documents: DashMap<String, Document>,
    index: Arc<WorkspaceIndex>,
    format_style: Style,
    database_url: Option<String>,
}

impl Backend {
    pub fn new(client: Client, format_style: Style, database_url: Option<String>) -> Self {
        Self {
            client,
            pool: Arc::new(ParserPool::new()),
            documents: DashMap::new(),
            index: Arc::new(WorkspaceIndex::new()),
            format_style,
            database_url,
        }
    }

    async fn publish_diagnostics(&self, uri: &Url, doc: &Document) {
        if let Some(tree) = doc.tree() {
            self.index
                .update_file(uri.as_str(), tree, &doc.text(), doc.injections());
        }
        let diags = diagnostics::to_diagnostics(&doc.errors());
        self.client
            .publish_diagnostics(uri.clone(), diags, None)
            .await;
    }

    fn node_at_position<'a>(
        tree: &'a tree_sitter::Tree,
        source: &str,
        line: u32,
        character: u32,
    ) -> Option<tree_sitter::Node<'a>> {
        let line_text = source.lines().nth(line as usize).unwrap_or("");
        let byte_col = utf16_to_byte_offset(line_text, character as usize);
        let point = tree_sitter::Point {
            row: line as usize,
            column: byte_col,
        };
        tree.root_node().descendant_for_point_range(point, point)
    }

    fn name_at_position(
        tree: &tree_sitter::Tree,
        source: &str,
        line: u32,
        character: u32,
    ) -> Option<(String, Range)> {
        let node = Self::node_at_position(tree, source, line, character)?;
        let text = node.utf8_text(source.as_bytes()).ok()?;
        let name = text.trim().replace('"', "");
        if name.is_empty() {
            return None;
        }
        let range = node_range(node, source);
        Some((name, range))
    }

    fn completion_context(
        tree: &tree_sitter::Tree,
        source: &str,
        line: u32,
        character: u32,
    ) -> CompletionContext {
        let line_text = source.lines().nth(line as usize).unwrap_or("");
        let byte_col = utf16_to_byte_offset(line_text, character as usize);
        let point = tree_sitter::Point {
            row: line as usize,
            column: byte_col,
        };

        if let Some(node) = tree.root_node().descendant_for_point_range(point, point) {
            let mut current = Some(node);
            while let Some(n) = current {
                match n.kind() {
                    "from_clause" | "from_list" => return CompletionContext::AfterFrom,
                    "join_type" | "JoinExpr" => return CompletionContext::AfterJoin,
                    "target_list" => return CompletionContext::AfterSelect,
                    "set_clause_list" | "set_clause" => return CompletionContext::ColumnPosition,
                    _ => {}
                }
                current = n.parent();
            }
        }

        let line_text = source.lines().nth(line as usize).unwrap_or("");
        // Convert LSP UTF-16 character offset to a byte offset within the line.
        let byte_offset = utf16_to_byte_offset(line_text, character as usize);
        let before_cursor = &line_text[..byte_offset];
        let trimmed = before_cursor.trim_end().to_uppercase();

        if trimmed.ends_with("FROM") || trimmed.ends_with("JOIN") {
            CompletionContext::AfterFrom
        } else if trimmed.ends_with("SELECT") {
            CompletionContext::AfterSelect
        } else {
            CompletionContext::General
        }
    }
}

/// Convert an LSP UTF-16 character offset to a byte offset within a line.
fn utf16_to_byte_offset(line: &str, utf16_col: usize) -> usize {
    let mut utf16_count = 0;
    let mut byte_offset = 0;
    for ch in line.chars() {
        if utf16_count >= utf16_col {
            break;
        }
        utf16_count += ch.len_utf16();
        byte_offset += ch.len_utf8();
    }
    byte_offset.min(line.len())
}

/// Convert a byte column offset to UTF-16 code units within a line.
fn byte_col_to_utf16(line: &str, byte_col: usize) -> u32 {
    let end = byte_col.min(line.len());
    line[..end].encode_utf16().count() as u32
}

/// Build a Position from a line number and byte column, converting to UTF-16 if source is available.
fn make_position(line: usize, byte_col: usize, lines: &[&str]) -> Position {
    let line_text = lines.get(line).copied().unwrap_or("");
    Position {
        line: line as u32,
        character: byte_col_to_utf16(line_text, byte_col),
    }
}

/// Build an LSP Range from a tree-sitter node, converting byte columns to UTF-16.
fn node_range(node: tree_sitter::Node, source: &str) -> Range {
    let lines: Vec<&str> = source.lines().collect();
    Range {
        start: make_position(
            node.start_position().row,
            node.start_position().column,
            &lines,
        ),
        end: make_position(node.end_position().row, node.end_position().column, &lines),
    }
}

/// Build an LSP Range from a Symbol's statement range, converting byte columns to UTF-16.
/// `source` should be the file containing the symbol; pass the document map to look it up.
fn symbol_range_with_source(
    sym: &postgres_lsp_analysis::symbols::Symbol,
    docs: &DashMap<String, Document>,
) -> Range {
    if let Some(doc) = docs.get(&sym.uri) {
        let source = doc.text();
        let lines: Vec<&str> = source.lines().collect();
        Range {
            start: make_position(sym.start_line, sym.start_col, &lines),
            end: make_position(sym.end_line, sym.end_col, &lines),
        }
    } else {
        // Fallback: byte == utf16 (correct for ASCII)
        Range {
            start: Position {
                line: sym.start_line as u32,
                character: sym.start_col as u32,
            },
            end: Position {
                line: sym.end_line as u32,
                character: sym.end_col as u32,
            },
        }
    }
}

/// Build an LSP Range from a SymbolRef, converting byte columns to UTF-16.
fn ref_range_with_source(
    r: &postgres_lsp_analysis::symbols::SymbolRef,
    docs: &DashMap<String, Document>,
) -> Range {
    if let Some(doc) = docs.get(&r.uri) {
        let source = doc.text();
        let lines: Vec<&str> = source.lines().collect();
        Range {
            start: make_position(r.start_line, r.start_col, &lines),
            end: make_position(r.end_line, r.end_col, &lines),
        }
    } else {
        Range {
            start: Position {
                line: r.start_line as u32,
                character: r.start_col as u32,
            },
            end: Position {
                line: r.end_line as u32,
                character: r.end_col as u32,
            },
        }
    }
}

fn symbol_kind_to_lsp(kind: postgres_lsp_analysis::SymbolKind) -> tower_lsp::lsp_types::SymbolKind {
    use postgres_lsp_analysis::SymbolKind as SK;
    match kind {
        SK::Schema => tower_lsp::lsp_types::SymbolKind::NAMESPACE,
        SK::Table | SK::ForeignTable => tower_lsp::lsp_types::SymbolKind::CLASS,
        SK::View | SK::MaterializedView => tower_lsp::lsp_types::SymbolKind::CLASS,
        SK::Column => tower_lsp::lsp_types::SymbolKind::FIELD,
        SK::Function => tower_lsp::lsp_types::SymbolKind::FUNCTION,
        SK::Procedure => tower_lsp::lsp_types::SymbolKind::FUNCTION,
        SK::Trigger => tower_lsp::lsp_types::SymbolKind::EVENT,
        SK::Index => tower_lsp::lsp_types::SymbolKind::KEY,
        SK::Sequence => tower_lsp::lsp_types::SymbolKind::CONSTANT,
        SK::Type | SK::Domain => tower_lsp::lsp_types::SymbolKind::TYPE_PARAMETER,
        SK::Extension => tower_lsp::lsp_types::SymbolKind::PACKAGE,
        SK::Role => tower_lsp::lsp_types::SymbolKind::OBJECT,
        SK::Policy | SK::Publication | SK::Subscription => tower_lsp::lsp_types::SymbolKind::OBJECT,
        SK::Variable => tower_lsp::lsp_types::SymbolKind::VARIABLE,
        SK::Cursor => tower_lsp::lsp_types::SymbolKind::VARIABLE,
    }
}

fn symbol_to_symbol_information(
    sym: &postgres_lsp_analysis::symbols::Symbol,
    uri: Url,
    docs: &DashMap<String, Document>,
) -> SymbolInformation {
    #[allow(deprecated)]
    SymbolInformation {
        name: sym.name.display(),
        kind: symbol_kind_to_lsp(sym.kind),
        tags: None,
        deprecated: None,
        location: Location {
            uri,
            range: symbol_range_with_source(sym, docs),
        },
        container_name: None,
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, _params: InitializeParams) -> Result<InitializeResult> {
        info!("pg-lsp initializing");
        Ok(InitializeResult {
            capabilities: capabilities::server_capabilities(),
            server_info: Some(ServerInfo {
                name: "postgres-lsp".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
        })
    }

    async fn initialized(&self, _params: InitializedParams) {
        info!("pg-lsp initialized");

        // Load database schema in the background so it doesn't block other LSP requests.
        if let Some(ref db_url) = self.database_url {
            let index = Arc::clone(&self.index);
            let url = db_url.clone();
            tokio::spawn(async move {
                match postgres_lsp_schema::load_database_schema(&url, &index).await {
                    Ok(count) => info!("loaded {count} symbols from database"),
                    Err(e) => tracing::warn!("failed to load database schema: {e}"),
                }
            });
        }
    }

    async fn shutdown(&self) -> Result<()> {
        info!("pg-lsp shutting down");
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri;
        let text = params.text_document.text;
        let doc = Document::new(uri.to_string(), &text, &self.pool);
        self.publish_diagnostics(&uri, &doc).await;
        self.documents.insert(uri.to_string(), doc);
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri;
        let uri_str = uri.to_string();

        // Apply edits under the DashMap guard, then drop it before awaiting.
        {
            let Some(mut doc) = self.documents.get_mut(&uri_str) else {
                return;
            };
            for change in params.content_changes {
                if let Some(range) = change.range {
                    doc.apply_edit(
                        range.start.line as usize,
                        range.start.character as usize,
                        range.end.line as usize,
                        range.end.character as usize,
                        &change.text,
                        &self.pool,
                    );
                } else {
                    doc.replace_full(&change.text, &self.pool);
                }
            }
        }
        // Guard dropped — safe to await now.
        if let Some(doc) = self.documents.get(&uri_str) {
            self.publish_diagnostics(&uri, &doc).await;
        }
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri.to_string();
        self.documents.remove(&uri);
        self.index.remove_file(&uri);
        self.client
            .publish_diagnostics(params.text_document.uri, vec![], None)
            .await;
    }

    async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
        let uri = params.text_document_position.text_document.uri.to_string();
        let line = params.text_document_position.position.line;
        let character = params.text_document_position.position.character;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };

        let ctx = if let Some(tree) = doc.tree() {
            let source = doc.text();
            Self::completion_context(tree, &source, line, character)
        } else {
            CompletionContext::General
        };

        let items = completion::completions(&self.index, &ctx);
        let lsp_items: Vec<CompletionItem> = items
            .into_iter()
            .map(|item| CompletionItem {
                label: item.label,
                kind: Some(match item.kind {
                    completion::CompletionKind::Keyword => CompletionItemKind::KEYWORD,
                    completion::CompletionKind::Table | completion::CompletionKind::View => {
                        CompletionItemKind::CLASS
                    }
                    completion::CompletionKind::Column => CompletionItemKind::FIELD,
                    completion::CompletionKind::Function
                    | completion::CompletionKind::Procedure => CompletionItemKind::FUNCTION,
                    completion::CompletionKind::Type => CompletionItemKind::TYPE_PARAMETER,
                    completion::CompletionKind::Schema => CompletionItemKind::MODULE,
                    completion::CompletionKind::Sequence => CompletionItemKind::CONSTANT,
                    completion::CompletionKind::Variable => CompletionItemKind::VARIABLE,
                }),
                detail: item.detail,
                documentation: item.documentation.map(|d| {
                    Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: d,
                    })
                }),
                ..Default::default()
            })
            .collect();

        Ok(Some(CompletionResponse::Array(lsp_items)))
    }

    async fn signature_help(&self, params: SignatureHelpParams) -> Result<Option<SignatureHelp>> {
        let uri = params
            .text_document_position_params
            .text_document
            .uri
            .to_string();
        let line = params.text_document_position_params.position.line;
        let character = params.text_document_position_params.position.character;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();

        let line_text = source.lines().nth(line as usize).unwrap_or("");
        let byte_col = utf16_to_byte_offset(line_text, character as usize);

        let Some((sig, active_param)) = signature::signature_help(
            &self.index,
            &self.pool,
            tree,
            &source,
            line as usize,
            byte_col,
        ) else {
            return Ok(None);
        };

        let parameters: Vec<ParameterInformation> = sig
            .params
            .iter()
            .map(|p| ParameterInformation {
                label: ParameterLabel::Simple(p.label()),
                documentation: None,
            })
            .collect();

        Ok(Some(SignatureHelp {
            signatures: vec![SignatureInformation {
                label: sig.label(),
                documentation: None,
                parameters: Some(parameters),
                active_parameter: Some(active_param as u32),
            }],
            active_signature: Some(0),
            active_parameter: Some(active_param as u32),
        }))
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        let uri = params
            .text_document_position_params
            .text_document
            .uri
            .to_string();
        let line = params.text_document_position_params.position.line;
        let character = params.text_document_position_params.position.character;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();
        let Some((name, range)) = Self::name_at_position(tree, &source, line, character) else {
            return Ok(None);
        };

        let symbols = resolve::resolve_name(&self.index, &QualifiedName::new(name));
        if let Some(sym) = symbols.first() {
            return Ok(Some(Hover {
                contents: HoverContents::Markup(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: hover::hover_for_symbol(sym),
                }),
                range: Some(range),
            }));
        }

        Ok(None)
    }

    async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Result<Option<GotoDefinitionResponse>> {
        let uri = params
            .text_document_position_params
            .text_document
            .uri
            .to_string();
        let line = params.text_document_position_params.position.line;
        let character = params.text_document_position_params.position.character;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();
        let Some((name, _)) = Self::name_at_position(tree, &source, line, character) else {
            return Ok(None);
        };

        let symbols = resolve::resolve_name(&self.index, &QualifiedName::new(name));
        let locations: Vec<Location> = symbols
            .iter()
            .filter_map(|sym| {
                Some(Location {
                    uri: Url::parse(&sym.uri).ok()?,
                    range: symbol_range_with_source(sym, &self.documents),
                })
            })
            .collect();

        match locations.len() {
            0 => Ok(None),
            1 => Ok(Some(GotoDefinitionResponse::Scalar(
                locations.into_iter().next().unwrap(),
            ))),
            _ => Ok(Some(GotoDefinitionResponse::Array(locations))),
        }
    }

    async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
        let uri = params.text_document_position.text_document.uri.to_string();
        let line = params.text_document_position.position.line;
        let character = params.text_document_position.position.character;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();
        let Some((name, _)) = Self::name_at_position(tree, &source, line, character) else {
            return Ok(None);
        };

        let refs = self.index.find_references(&name);
        let locations: Vec<Location> = refs
            .iter()
            .filter_map(|r| {
                Some(Location {
                    uri: Url::parse(&r.uri).ok()?,
                    range: ref_range_with_source(r, &self.documents),
                })
            })
            .collect();

        if locations.is_empty() {
            Ok(None)
        } else {
            Ok(Some(locations))
        }
    }

    async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> Result<Option<DocumentSymbolResponse>> {
        let uri = params.text_document.uri.to_string();
        let symbols = self.index.file_symbols(&uri);

        let lsp_symbols: Vec<SymbolInformation> = symbols
            .iter()
            .map(|sym| {
                symbol_to_symbol_information(sym, params.text_document.uri.clone(), &self.documents)
            })
            .collect();

        Ok(Some(DocumentSymbolResponse::Flat(lsp_symbols)))
    }

    async fn symbol(
        &self,
        params: WorkspaceSymbolParams,
    ) -> Result<Option<Vec<SymbolInformation>>> {
        let symbols = self.index.search(&params.query);
        let lsp_symbols: Vec<SymbolInformation> = symbols
            .iter()
            .filter_map(|sym| {
                let uri = Url::parse(&sym.uri).ok()?;
                Some(symbol_to_symbol_information(sym, uri, &self.documents))
            })
            .collect();

        Ok(Some(lsp_symbols))
    }

    async fn semantic_tokens_full(
        &self,
        params: SemanticTokensParams,
    ) -> Result<Option<SemanticTokensResult>> {
        let uri = params.text_document.uri.to_string();

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };

        let source = doc.text();
        let tokens = semantic_tokens::collect_semantic_tokens(tree.root_node(), &source);

        Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
            result_id: None,
            data: tokens,
        })))
    }

    async fn folding_range(&self, params: FoldingRangeParams) -> Result<Option<Vec<FoldingRange>>> {
        let uri = params.text_document.uri.to_string();

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };

        let mut ranges = Vec::new();
        collect_folding_ranges(tree.root_node(), &mut ranges);
        Ok(Some(ranges))
    }

    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
        let uri = params.text_document.uri.to_string();

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();

        let start_line_text = source
            .lines()
            .nth(params.range.start.line as usize)
            .unwrap_or("");
        let end_line_text = source
            .lines()
            .nth(params.range.end.line as usize)
            .unwrap_or("");
        let start_byte_col =
            utf16_to_byte_offset(start_line_text, params.range.start.character as usize);
        let end_byte_col = utf16_to_byte_offset(end_line_text, params.range.end.character as usize);

        let actions = code_actions::compute_code_actions(
            tree,
            &source,
            params.range.start.line as usize,
            start_byte_col,
            params.range.end.line as usize,
            end_byte_col,
        );

        if actions.is_empty() {
            return Ok(None);
        }

        let lines: Vec<&str> = source.lines().collect();
        let lsp_actions: Vec<CodeActionOrCommand> = actions
            .into_iter()
            .map(|action| {
                let kind = match action.kind {
                    code_actions::CodeActionKind::QuickFix => CodeActionKind::QUICKFIX,
                    code_actions::CodeActionKind::RefactorRewrite => {
                        CodeActionKind::REFACTOR_REWRITE
                    }
                };

                let start_text = lines.get(action.edit.start_line).copied().unwrap_or("");
                let end_text = lines.get(action.edit.end_line).copied().unwrap_or("");

                let edit = TextEdit {
                    range: Range {
                        start: Position {
                            line: action.edit.start_line as u32,
                            character: byte_col_to_utf16(start_text, action.edit.start_col),
                        },
                        end: Position {
                            line: action.edit.end_line as u32,
                            character: byte_col_to_utf16(end_text, action.edit.end_col),
                        },
                    },
                    new_text: action.edit.new_text,
                };

                let mut changes = std::collections::HashMap::new();
                changes.insert(params.text_document.uri.clone(), vec![edit]);

                CodeActionOrCommand::CodeAction(tower_lsp::lsp_types::CodeAction {
                    title: action.title,
                    kind: Some(kind),
                    edit: Some(WorkspaceEdit {
                        changes: Some(changes),
                        ..Default::default()
                    }),
                    ..Default::default()
                })
            })
            .collect();

        Ok(Some(lsp_actions))
    }

    async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
        let uri = params.text_document_position.text_document.uri.to_string();
        let line = params.text_document_position.position.line;
        let character = params.text_document_position.position.character;
        let new_name = params.new_name;

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };
        let Some(tree) = doc.tree() else {
            return Ok(None);
        };
        let source = doc.text();
        let Some((name, _)) = Self::name_at_position(tree, &source, line, character) else {
            return Ok(None);
        };

        let mut changes: std::collections::HashMap<Url, Vec<TextEdit>> =
            std::collections::HashMap::new();

        // Rename all references.
        for r in &self.index.find_references(&name) {
            if let Ok(ref_uri) = Url::parse(&r.uri) {
                changes.entry(ref_uri).or_default().push(TextEdit {
                    range: ref_range_with_source(r, &self.documents),
                    new_text: new_name.clone(),
                });
            }
        }

        // Rename definition name nodes (using the name_* position, not the full statement).
        let defs = resolve::resolve_name(&self.index, &QualifiedName::new(name));
        for sym in &defs {
            if let Ok(sym_uri) = Url::parse(&sym.uri) {
                let name_range = if let Some(doc) = self.documents.get(&sym.uri) {
                    let src = doc.text();
                    let lines: Vec<&str> = src.lines().collect();
                    Range {
                        start: make_position(sym.name_start_line, sym.name_start_col, &lines),
                        end: make_position(sym.name_end_line, sym.name_end_col, &lines),
                    }
                } else {
                    Range {
                        start: Position {
                            line: sym.name_start_line as u32,
                            character: sym.name_start_col as u32,
                        },
                        end: Position {
                            line: sym.name_end_line as u32,
                            character: sym.name_end_col as u32,
                        },
                    }
                };
                changes.entry(sym_uri).or_default().push(TextEdit {
                    range: name_range,
                    new_text: new_name.clone(),
                });
            }
        }

        Ok(Some(WorkspaceEdit {
            changes: Some(changes),
            ..Default::default()
        }))
    }

    async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
        let uri = params.text_document.uri.to_string();

        let Some(doc) = self.documents.get(&uri) else {
            return Ok(None);
        };

        let source = doc.text();
        let options = postgres_lsp_format::FormatOptions {
            style: self.format_style,
        };

        match postgres_lsp_format::format_sql(&source, &options) {
            Ok(formatted) => {
                if formatted == source {
                    return Ok(None);
                }
                // Use the rope for the end position so that the line count
                // and the UTF-16 column agree with the document model.
                let (end_line, end_char) = doc.end_position();
                Ok(Some(vec![TextEdit {
                    range: Range {
                        start: Position {
                            line: 0,
                            character: 0,
                        },
                        end: Position {
                            line: end_line as u32,
                            character: end_char as u32,
                        },
                    },
                    new_text: formatted,
                }]))
            }
            Err(e) => {
                // libpgfmt rejects documents whose parse tree contains errors,
                // including stray tokens outside any statement. Report the
                // failure so the client does not silently do nothing; the
                // offending position is already flagged as a diagnostic.
                tracing::warn!("formatting failed: {e}");
                Err(jsonrpc::Error {
                    code: jsonrpc::ErrorCode::ServerError(REQUEST_FAILED),
                    message: format!("Cannot format document: {e}").into(),
                    data: None,
                })
            }
        }
    }
}

fn collect_folding_ranges(node: tree_sitter::Node, ranges: &mut Vec<FoldingRange>) {
    let start_line = node.start_position().row as u32;
    let end_line = node.end_position().row as u32;

    if end_line > start_line {
        let is_foldable = matches!(
            node.kind(),
            "CreateStmt"
                | "CreateFunctionStmt"
                | "ViewStmt"
                | "SelectStmt"
                | "InsertStmt"
                | "UpdateStmt"
                | "DeleteStmt"
                | "CreateSchemaStmt"
                | "CreateTrigStmt"
                | "IndexStmt"
                | "TransactionStmt"
                | "DoStmt"
                | "comment"
        );

        if is_foldable {
            ranges.push(FoldingRange {
                start_line,
                start_character: None,
                end_line,
                end_character: None,
                kind: if node.kind() == "comment" {
                    Some(FoldingRangeKind::Comment)
                } else {
                    Some(FoldingRangeKind::Region)
                },
                collapsed_text: None,
            });
        }
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_folding_ranges(child, ranges);
    }
}