postgres-lsp-analysis 1.3.2

Symbol extraction, workspace index, and name resolution for PostgreSQL
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
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
use tree_sitter::{Node, Tree};

/// The kind of a SQL symbol definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolKind {
    Schema,
    Table,
    View,
    MaterializedView,
    Column,
    Function,
    Procedure,
    Trigger,
    Index,
    Sequence,
    Type,
    Domain,
    Extension,
    Role,
    Policy,
    Publication,
    Subscription,
    ForeignTable,
    Variable,
    Cursor,
}

impl SymbolKind {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Schema => "schema",
            Self::Table => "table",
            Self::View => "view",
            Self::MaterializedView => "materialized view",
            Self::Column => "column",
            Self::Function => "function",
            Self::Procedure => "procedure",
            Self::Trigger => "trigger",
            Self::Index => "index",
            Self::Sequence => "sequence",
            Self::Type => "type",
            Self::Domain => "domain",
            Self::Extension => "extension",
            Self::Role => "role",
            Self::Policy => "policy",
            Self::Publication => "publication",
            Self::Subscription => "subscription",
            Self::ForeignTable => "foreign table",
            Self::Variable => "variable",
            Self::Cursor => "cursor",
        }
    }
}

/// A fully qualified name (schema.name).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QualifiedName {
    pub schema: Option<String>,
    pub name: String,
}

impl QualifiedName {
    pub fn new(name: String) -> Self {
        Self { schema: None, name }
    }

    pub fn with_schema(schema: String, name: String) -> Self {
        Self {
            schema: Some(schema),
            name,
        }
    }

    pub fn display(&self) -> String {
        match &self.schema {
            Some(s) => format!("{s}.{}", self.name),
            None => self.name.clone(),
        }
    }
}

/// A symbol definition extracted from the parse tree.
#[derive(Debug, Clone)]
pub struct Symbol {
    pub kind: SymbolKind,
    pub name: QualifiedName,
    pub uri: String,
    /// Full statement range.
    pub start_byte: usize,
    pub end_byte: usize,
    pub start_line: usize,
    pub start_col: usize,
    pub end_line: usize,
    pub end_col: usize,
    /// Name-only range (for rename operations).
    pub name_start_line: usize,
    pub name_start_col: usize,
    pub name_end_line: usize,
    pub name_end_col: usize,
    pub definition_text: String,
    pub children: Vec<Symbol>,
}

/// A reference to a symbol (usage, not definition).
#[derive(Debug, Clone)]
pub struct SymbolRef {
    /// The qualified name being referenced.
    pub name: QualifiedName,
    /// The URI of the document containing this reference.
    pub uri: String,
    /// Byte range within the source.
    pub start_byte: usize,
    pub end_byte: usize,
    /// Line/column range (0-based).
    pub start_line: usize,
    pub start_col: usize,
    pub end_line: usize,
    pub end_col: usize,
}

/// Extract all symbol definitions from a parsed document.
pub fn extract_symbols(tree: &Tree, source: &str, uri: &str) -> Vec<Symbol> {
    let mut symbols = Vec::new();
    collect_definitions(tree.root_node(), source, uri, &mut symbols);
    symbols
}

/// Recursively walk the tree looking for DDL statement nodes.
///
/// The tree structure is: source_file -> toplevel_stmt -> stmt -> CreateStmt/etc.
/// We recurse through wrapper nodes to find the actual statement types.
fn collect_definitions(node: Node, source: &str, uri: &str, symbols: &mut Vec<Symbol>) {
    if let Some(symbol) = try_extract_definition(node, source, uri) {
        symbols.push(symbol);
        return; // Don't recurse into statements we've already extracted.
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_definitions(child, source, uri, symbols);
    }
}

/// Try to extract a symbol definition from a node.
fn try_extract_definition(node: Node, source: &str, uri: &str) -> Option<Symbol> {
    // Each arm returns (kind, name, name_node) where name_node has the position of the name.
    let result: Option<(SymbolKind, QualifiedName, Node)> = match node.kind() {
        "CreateStmt" => find_descendant(node, "qualified_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Table, qn, n))
        }),
        "CreateMatViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::MaterializedView, qn, n))
        }),
        "ViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::View, qn, n))
        }),
        "CreateFunctionStmt" => {
            let kind = if has_child_kind(node, "kw_procedure") {
                SymbolKind::Procedure
            } else {
                SymbolKind::Function
            };
            find_descendant(node, "func_name")
                .and_then(|n| extract_func_name(n, source).map(|qn| (kind, qn, n)))
        }
        "IndexStmt" => extract_name_or_col_id(node, source, SymbolKind::Index),
        "CreateSeqStmt" => find_descendant(node, "qualified_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Sequence, qn, n))
        }),
        "CreateSchemaStmt" => find_descendant(node, "ColId")
            .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Schema, qn, n))),
        "CompositeTypeStmt" | "CreateEnumStmt" | "CreateRangeStmt" => {
            find_descendant(node, "any_name")
                .and_then(|n| {
                    extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
                })
                .or_else(|| {
                    find_descendant(node, "qualified_name").and_then(|n| {
                        extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
                    })
                })
        }
        "CreateDomainStmt" => find_descendant(node, "any_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Domain, qn, n))
        }),
        "CreateExtensionStmt" => extract_name_or_col_id(node, source, SymbolKind::Extension),
        "CreateTrigStmt" => extract_name_or_col_id(node, source, SymbolKind::Trigger),
        "CreateRoleStmt" => find_descendant(node, "RoleId")
            .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
            .or_else(|| {
                find_descendant(node, "ColId")
                    .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
            }),
        "CreatePolicyStmt" => find_descendant(node, "name")
            .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Policy, qn, n))),
        "CreatePublicationStmt" => find_descendant(node, "ColId")
            .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Publication, qn, n))),
        "CreateSubscriptionStmt" => find_descendant(node, "ColId")
            .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Subscription, qn, n))),
        "CreateForeignTableStmt" => find_descendant(node, "qualified_name").and_then(|n| {
            extract_qualified_name_node(n, source).map(|qn| (SymbolKind::ForeignTable, qn, n))
        }),
        _ => None,
    };

    let (kind, name, name_node) = result?;
    let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();

    let mut symbol = Symbol {
        kind,
        name,
        uri: uri.to_string(),
        start_byte: node.start_byte(),
        end_byte: node.end_byte(),
        start_line: node.start_position().row,
        start_col: node.start_position().column,
        end_line: node.end_position().row,
        end_col: node.end_position().column,
        name_start_line: name_node.start_position().row,
        name_start_col: name_node.start_position().column,
        name_end_line: name_node.end_position().row,
        name_end_col: name_node.end_position().column,
        definition_text: def_text,
        children: Vec::new(),
    };

    if kind == SymbolKind::Table {
        symbol.children = extract_columns(node, source, uri);
    }

    Some(symbol)
}

/// Helper: try "name" descendant then "ColId" descendant for a given kind.
fn extract_name_or_col_id<'a>(
    node: Node<'a>,
    source: &str,
    kind: SymbolKind,
) -> Option<(SymbolKind, QualifiedName, Node<'a>)> {
    find_descendant(node, "name")
        .and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
        .or_else(|| {
            find_descendant(node, "ColId")
                .and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
        })
}

/// Extract a QualifiedName from a `qualified_name` or `any_name` node.
///
/// Tree structure for unqualified: `qualified_name` -> `ColId` -> `identifier`
/// Tree structure for qualified: `qualified_name` -> `ColId` + `indirection` ->
///   `indirection_el` -> `.` + `attr_name` -> `ColLabel` -> `identifier`
fn extract_qualified_name_node(node: Node, source: &str) -> Option<QualifiedName> {
    let mut first_name = None;
    let mut indirection_name = None;

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "ColId" => {
                first_name = leaf_text(child, source);
            }
            "indirection" => {
                // Look for attr_name inside indirection_el
                let mut ic = child.walk();
                for indirection_child in child.children(&mut ic) {
                    if indirection_child.kind() == "indirection_el" {
                        let mut ec = indirection_child.walk();
                        for el_child in indirection_child.children(&mut ec) {
                            if el_child.kind() == "attr_name" {
                                indirection_name = leaf_text(el_child, source);
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }

    match (first_name, indirection_name) {
        (Some(schema), Some(name)) => Some(QualifiedName::with_schema(schema, name)),
        (Some(name), None) => Some(QualifiedName::new(name)),
        _ => None,
    }
}

/// Extract a name from a `func_name` node.
///
/// Tree structure: `func_name` -> `type_function_name` -> (`identifier` | `unreserved_keyword` -> `kw_*`)
pub fn extract_func_name(node: Node, source: &str) -> Option<QualifiedName> {
    // func_name may contain qualified names too
    if let Some(indirection) = find_child(node, "indirection") {
        // Schema-qualified function name
        let schema = find_child(node, "ColId").and_then(|n| leaf_text(n, source));
        let mut name = None;
        let mut ic = indirection.walk();
        for child in indirection.children(&mut ic) {
            if child.kind() == "indirection_el" {
                let mut ec = child.walk();
                for el_child in child.children(&mut ec) {
                    if el_child.kind() == "attr_name" {
                        name = leaf_text(el_child, source);
                    }
                }
            }
        }
        if let (Some(s), Some(n)) = (schema, name) {
            return Some(QualifiedName::with_schema(s, n));
        }
    }

    // Simple function name: func_name -> type_function_name -> identifier/kw_*
    leaf_text(node, source).map(QualifiedName::new)
}

/// Extract a simple name from a leaf-like node.
fn extract_leaf_name(node: Node, source: &str) -> Option<QualifiedName> {
    leaf_text(node, source).map(QualifiedName::new)
}

/// Get the text content of a node, recursing to find the deepest identifier/keyword text.
pub fn leaf_text(node: Node, source: &str) -> Option<String> {
    // If it's a leaf, return its text directly.
    if node.child_count() == 0 {
        let text = node.utf8_text(source.as_bytes()).ok()?;
        return Some(text.trim().replace('"', ""));
    }

    // Recurse into children to find identifier or keyword text.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "identifier" => {
                return child
                    .utf8_text(source.as_bytes())
                    .ok()
                    .map(|t| t.trim().replace('"', ""));
            }
            _ if child.kind().starts_with("kw_") => {
                return child
                    .utf8_text(source.as_bytes())
                    .ok()
                    .map(|t| t.trim().to_string());
            }
            _ => {
                if let Some(text) = leaf_text(child, source) {
                    return Some(text);
                }
            }
        }
    }
    None
}

/// Find a direct child node of the given kind.
pub fn find_child<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    node.children(&mut cursor).find(|c| c.kind() == kind)
}

/// Find a descendant node of the given kind (breadth-first, limited depth).
fn find_descendant<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
    // Direct children first
    if let Some(child) = find_child(node, kind) {
        return Some(child);
    }
    // Then grandchildren
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(grandchild) = find_child(child, kind) {
            return Some(grandchild);
        }
    }
    None
}

/// Check if a node has a direct child of the given kind.
fn has_child_kind(node: Node, kind: &str) -> bool {
    find_child(node, kind).is_some()
}

/// Extract column symbols from a CREATE TABLE statement.
fn extract_columns(table_node: Node, source: &str, uri: &str) -> Vec<Symbol> {
    let mut columns = Vec::new();
    collect_column_defs(table_node, source, uri, &mut columns);
    columns
}

fn collect_column_defs(node: Node, source: &str, uri: &str, columns: &mut Vec<Symbol>) {
    if node.kind() == "columnDef" {
        if let Some(col_id) = find_descendant(node, "ColId")
            && let Some(name) = leaf_text(col_id, source)
        {
            let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
            columns.push(Symbol {
                kind: SymbolKind::Column,
                name: QualifiedName::new(name),
                uri: uri.to_string(),
                start_byte: node.start_byte(),
                end_byte: node.end_byte(),
                start_line: node.start_position().row,
                start_col: node.start_position().column,
                end_line: node.end_position().row,
                end_col: node.end_position().column,
                name_start_line: col_id.start_position().row,
                name_start_col: col_id.start_position().column,
                name_end_line: col_id.end_position().row,
                name_end_col: col_id.end_position().column,
                definition_text: def_text,
                children: Vec::new(),
            });
        }
        return;
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_column_defs(child, source, uri, columns);
    }
}

/// Extract all symbol references (usages) from a parsed document.
pub fn extract_references(tree: &Tree, source: &str, uri: &str) -> Vec<SymbolRef> {
    let mut refs = Vec::new();
    collect_references(tree.root_node(), source, uri, &mut refs);
    refs
}

fn collect_references(node: Node, source: &str, uri: &str, refs: &mut Vec<SymbolRef>) {
    match node.kind() {
        "func_application" => {
            // For function calls, index only the callee name (not the full
            // node which includes arguments), then continue recursing into
            // children so argument references are also indexed.
            if let Some(name_node) = find_descendant(node, "func_name")
                && let Some(name) = extract_func_name(name_node, source)
            {
                refs.push(SymbolRef {
                    name,
                    uri: uri.to_string(),
                    start_byte: name_node.start_byte(),
                    end_byte: name_node.end_byte(),
                    start_line: name_node.start_position().row,
                    start_col: name_node.start_position().column,
                    end_line: name_node.end_position().row,
                    end_col: name_node.end_position().column,
                });
            }
            // Don't return — fall through to recurse into arguments.
        }
        "columnref" | "relation_expr" => {
            let name = extract_qualified_name_node(node, source).or_else(|| {
                find_descendant(node, "ColId").and_then(|n| extract_leaf_name(n, source))
            });

            if let Some(name) = name {
                refs.push(SymbolRef {
                    name,
                    uri: uri.to_string(),
                    start_byte: node.start_byte(),
                    end_byte: node.end_byte(),
                    start_line: node.start_position().row,
                    start_col: node.start_position().column,
                    end_line: node.end_position().row,
                    end_col: node.end_position().column,
                });
                return;
            }
        }
        _ => {}
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_references(child, source, uri, refs);
    }
}

/// Extract PL/pgSQL variable and cursor declarations from a PL/pgSQL parse tree.
///
/// The `parent_start_byte`, `parent_start_line`, and `parent_start_col` map
/// local positions to the parent document's coordinate space.
pub fn extract_plpgsql_symbols(
    tree: &Tree,
    source: &str,
    uri: &str,
    parent_start_line: usize,
    parent_start_col: usize,
) -> Vec<Symbol> {
    let mut symbols = Vec::new();
    collect_plpgsql_decls(
        tree.root_node(),
        source,
        uri,
        parent_start_line,
        parent_start_col,
        &mut symbols,
    );
    symbols
}

fn collect_plpgsql_decls(
    node: Node,
    source: &str,
    uri: &str,
    parent_start_line: usize,
    parent_start_col: usize,
    symbols: &mut Vec<Symbol>,
) {
    if node.kind() == "decl_statement" {
        let name_node = find_child(node, "decl_varname");
        let name = name_node.and_then(|n| leaf_text(n, source));
        let type_text = find_child(node, "decl_datatype")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
            .unwrap_or("")
            .trim()
            .to_string();

        let is_cursor = find_child(node, "decl_cursor_query").is_some()
            || type_text.to_uppercase().contains("CURSOR");

        if let (Some(var_name), Some(name_node)) = (name, name_node) {
            let kind = if is_cursor {
                SymbolKind::Cursor
            } else {
                SymbolKind::Variable
            };

            let (start_line, start_col) = map_position(
                node.start_position().row,
                node.start_position().column,
                parent_start_line,
                parent_start_col,
            );
            let (end_line, end_col) = map_position(
                node.end_position().row,
                node.end_position().column,
                parent_start_line,
                parent_start_col,
            );

            let (name_sl, name_sc) = map_position(
                name_node.start_position().row,
                name_node.start_position().column,
                parent_start_line,
                parent_start_col,
            );
            let (name_el, name_ec) = map_position(
                name_node.end_position().row,
                name_node.end_position().column,
                parent_start_line,
                parent_start_col,
            );

            let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();

            symbols.push(Symbol {
                kind,
                name: QualifiedName::new(var_name),
                uri: uri.to_string(),
                start_byte: node.start_byte(),
                end_byte: node.end_byte(),
                start_line,
                start_col,
                end_line,
                end_col,
                name_start_line: name_sl,
                name_start_col: name_sc,
                name_end_line: name_el,
                name_end_col: name_ec,
                definition_text: def_text,
                children: Vec::new(),
            });
        }
        return;
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_plpgsql_decls(
            child,
            source,
            uri,
            parent_start_line,
            parent_start_col,
            symbols,
        );
    }
}

/// Map a position within an injected region to the parent document.
fn map_position(
    local_line: usize,
    local_col: usize,
    parent_start_line: usize,
    parent_start_col: usize,
) -> (usize, usize) {
    if local_line == 0 {
        (parent_start_line, parent_start_col + local_col)
    } else {
        (parent_start_line + local_line, local_col)
    }
}

#[cfg(test)]
mod tests {
    use postgres_lsp_parse::ParserPool;

    use super::*;

    fn parse_and_extract(sql: &str) -> Vec<Symbol> {
        let pool = ParserPool::new();
        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
        let tree = guard.parser_mut().parse(sql, None).unwrap();
        extract_symbols(&tree, sql, "test.sql")
    }

    #[test]
    fn extract_create_table() {
        let symbols = parse_and_extract("CREATE TABLE users (id int, name text);");
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].kind, SymbolKind::Table);
        assert_eq!(symbols[0].name.name, "users");
        assert_eq!(symbols[0].children.len(), 2);
        assert_eq!(symbols[0].children[0].name.name, "id");
        assert_eq!(symbols[0].children[1].name.name, "name");
    }

    #[test]
    fn extract_create_function() {
        let symbols = parse_and_extract(
            "CREATE FUNCTION add(a int, b int) RETURNS int LANGUAGE sql AS 'SELECT a + b';",
        );
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].kind, SymbolKind::Function);
        assert_eq!(symbols[0].name.name, "add");
    }

    #[test]
    fn extract_schema_qualified() {
        let symbols = parse_and_extract("CREATE TABLE public.users (id int);");
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].name.schema.as_deref(), Some("public"));
        assert_eq!(symbols[0].name.name, "users");
    }

    #[test]
    fn extract_references_from_select() {
        let pool = ParserPool::new();
        let sql = "SELECT id, name FROM users WHERE id > 0;";
        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
        let tree = guard.parser_mut().parse(sql, None).unwrap();
        let refs = extract_references(&tree, sql, "test.sql");
        assert!(!refs.is_empty(), "should find references in SELECT");
    }

    #[test]
    fn extract_plpgsql_variables() {
        let pool = ParserPool::new();
        let plpgsql = "DECLARE\n  v_count int;\n  v_name text;\nBEGIN\n  RETURN v_count;\nEND;";
        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::PlPgSql);
        let tree = guard.parser_mut().parse(plpgsql, None).unwrap();
        drop(guard);

        let symbols = extract_plpgsql_symbols(&tree, plpgsql, "test.sql", 5, 0);
        assert_eq!(symbols.len(), 2, "should find 2 variable declarations");
        assert_eq!(symbols[0].kind, SymbolKind::Variable);
        assert_eq!(symbols[0].name.name, "v_count");
        assert_eq!(symbols[1].kind, SymbolKind::Variable);
        assert_eq!(symbols[1].name.name, "v_name");
    }

    #[test]
    fn plpgsql_variables_indexed_from_create_function() {
        let pool = ParserPool::new();
        let sql = r#"CREATE FUNCTION test() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  v_result int;
BEGIN
  v_result := 42;
  RETURN v_result;
END;
$$;"#;
        let doc = postgres_lsp_parse::Document::new("test.sql".into(), sql, &pool);
        let tree = doc.tree().unwrap();
        let injections = doc.injections();

        let index = crate::index::WorkspaceIndex::new();
        index.update_file("file:///test.sql", tree, sql, injections);

        // Should find the function
        let funcs = index.find_definitions(SymbolKind::Function, "test");
        assert_eq!(funcs.len(), 1);

        // Should also find the PL/pgSQL variable
        let vars = index.find_definitions(SymbolKind::Variable, "v_result");
        assert_eq!(vars.len(), 1, "PL/pgSQL variable should be indexed");
        assert_eq!(vars[0].name.name, "v_result");
    }
}