Skip to main content

dsl_completion/
sources.rs

1//! Item producers, one per kind of source data.
2//!
3//! Each emitter pushes onto an output vector; the engine decides which
4//! emitters to call based on the detected [`Context`](crate::context::Context).
5
6use crate::item::{Item, ItemKind};
7use crate::render;
8use dsl_catalog::{Catalog, Column, Table, TableKind, display_type};
9use dsl_knowledge::{self as kb, Entry};
10use dsl_resolve::Scope;
11
12pub fn keywords(out: &mut Vec<Item>) {
13  for (label, e) in kb::keywords() {
14    out.push(from_entry(label, e, ItemKind::Keyword));
15  }
16}
17
18pub fn types(out: &mut Vec<Item>) {
19  for (label, e) in kb::types() {
20    out.push(from_entry(label, e, ItemKind::Type));
21  }
22}
23
24pub fn functions(out: &mut Vec<Item>) {
25  for (label, e) in kb::functions() {
26    out.push(from_entry(label, e, ItemKind::Function));
27  }
28}
29
30/// User-defined functions from the catalog. Surfaced alongside the
31/// built-ins so completion shows app code next to standard SQL.
32/// User-defined types from the live catalog (enum / domain / composite).
33/// Emitted after `sources::types()` in CastType phase so built-in PG
34/// types still sort first.
35pub fn db_types(cat: &Catalog, out: &mut Vec<Item>) {
36  for t in &cat.types {
37    let kind_label = match t.kind {
38      dsl_catalog::TypeKind::Enum => "enum",
39      dsl_catalog::TypeKind::Domain => "domain",
40      dsl_catalog::TypeKind::Composite => "composite",
41    };
42    let doc = format!("**User-defined {kind_label}** `{}.{}`\n\n_From catalog._\n", t.schema, t.name);
43    out.push(Item {
44      label: t.name.clone(),
45      kind: ItemKind::Type,
46      detail: Some(format!("{kind_label} type")),
47      description: Some(format!("{} (db)", t.schema)),
48      documentation_md: Some(doc),
49      insert_text: t.name.clone(),
50      is_snippet: false,
51      kb_entry: None,
52      sort_priority: 5,
53    });
54  }
55}
56
57pub fn db_functions(cat: &Catalog, out: &mut Vec<Item>) {
58  for f in &cat.functions {
59    let args = f
60      .arguments
61      .iter()
62      .map(|a| match &a.name {
63        Some(n) => format!("{n} {}", display_type(&a.data_type)),
64        None => display_type(&a.data_type).to_string(),
65      })
66      .collect::<Vec<_>>()
67      .join(", ");
68    let signature = format!("{}({}) -> {}", f.name, args, display_type(&f.return_type));
69    // Include the full DDL body when we have it (CREATE FUNCTION ...).
70    // Without the fenced code block, editors render the body as plain
71    // monospace text -- with it, treesitter/markdown highlighters
72    // color the SQL.
73    let body_block = f
74      .comment
75      .as_ref()
76      .filter(|c| !c.trim().is_empty())
77      .map(|c| {
78        let t = c.trim();
79        if t.starts_with("```") { format!("\n\n{t}") } else { format!("\n\n```sql\n{t}\n```") }
80      })
81      .unwrap_or_default();
82    let doc = format!("**DB function** `{}.{}`\n\n```sql\n{}\n```{}\n", f.schema, f.name, signature, body_block);
83    let insert_text = if f.arguments.is_empty() { format!("{}()", f.name) } else { format!("{}($0)", f.name) };
84    out.push(Item {
85      label: f.name.clone(),
86      kind: ItemKind::Function,
87      detail: Some(signature),
88      description: Some(format!("{} (db)", f.schema)),
89      documentation_md: Some(doc),
90      insert_text,
91      is_snippet: !f.arguments.is_empty(),
92      kb_entry: None,
93      sort_priority: 5,
94    });
95  }
96}
97
98/// Subset of [`functions`] safe inside a SELECT projection / expression:
99/// aggregates, common scalar helpers, conditionals, window functions.
100/// Excludes the long tail (JSON/array helpers) that would be noise.
101pub fn projection_functions(out: &mut Vec<Item>) {
102  const KEEP: &[&str] = &[
103    "count",
104    "sum",
105    "avg",
106    "min",
107    "max",
108    "array_agg",
109    "string_agg",
110    "json_agg",
111    "jsonb_agg",
112    "coalesce",
113    "nullif",
114    "greatest",
115    "least",
116    "lower",
117    "upper",
118    "length",
119    "substring",
120    "trim",
121    "concat",
122    "replace",
123    "split_part",
124    "now",
125    "current_date",
126    "age",
127    "date_trunc",
128    "extract",
129    "to_char",
130    "abs",
131    "round",
132    "gen_random_uuid",
133    "row_number",
134    "rank",
135    "dense_rank",
136    "lag",
137    "lead",
138  ];
139  let table = kb::functions();
140  for name in KEEP {
141    if let Some(e) = table.get(*name) {
142      out.push(from_entry(name, e, ItemKind::Function));
143    }
144  }
145}
146
147/// Keywords valid inside expression position. Excludes DDL/DML statement
148/// keywords so SELECT projection doesn't get polluted with CREATE TABLE etc.
149pub fn expression_keywords(out: &mut Vec<Item>) {
150  const KEEP: &[&str] = &[
151    "AS",
152    "DISTINCT",
153    "ALL",
154    "CASE",
155    "WHEN",
156    "THEN",
157    "ELSE",
158    "END",
159    "AND",
160    "OR",
161    "NOT",
162    "IS NULL",
163    "IS NOT NULL",
164    "NULL",
165    "IS",
166    "IN",
167    "EXISTS",
168    "BETWEEN",
169    "LIKE",
170    "ILIKE",
171    "OVER",
172    "PARTITION BY",
173    "FILTER",
174  ];
175  emit_keyword_subset(out, KEEP);
176}
177
178/// Keywords valid at the start of a statement.
179pub fn statement_keywords(out: &mut Vec<Item>) {
180  const KEEP: &[&str] = &[
181    "SELECT",
182    "WITH",
183    "INSERT INTO",
184    "UPDATE",
185    "DELETE FROM",
186    "CREATE TABLE",
187    "CREATE INDEX",
188    "CREATE UNIQUE INDEX",
189    "CREATE VIEW",
190    "CREATE SCHEMA",
191    "CREATE SEQUENCE",
192    "ALTER TABLE",
193    "DROP TABLE",
194    "TRUNCATE",
195    "EXPLAIN",
196    "EXPLAIN ANALYZE",
197    "BEGIN",
198    "COMMIT",
199    "ROLLBACK",
200    "SAVEPOINT",
201    "GRANT",
202    "REVOKE",
203    "MERGE",
204    "REFRESH",
205    "REINDEX",
206    "VACUUM",
207    "ANALYZE",
208    "SET",
209    "SHOW",
210    "COMMENT",
211    "COPY",
212    "CALL",
213  ];
214  emit_keyword_subset(out, KEEP);
215  statement_snippets(out);
216}
217
218/// Common multi-line scaffolds. These ride above the plain statement
219/// keywords because typing `ctable` / `fn` / `trig` is faster than
220/// hand-rolling the full skeleton every time.
221fn statement_snippets(out: &mut Vec<Item>) {
222  out.push(Item {
223        label: "ctable".into(),
224        kind: ItemKind::Keyword,
225        detail: Some("CREATE TABLE skeleton".into()),
226        description: Some("snippet".into()),
227        documentation_md: Some(
228            "Expands to a CREATE TABLE with id PK, created_at, and a tab-stop \
229             for the table name and additional columns.".into()
230        ),
231        insert_text: "CREATE TABLE ${1:name} (\n    id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,\n    ${2:col} ${3:type} NOT NULL,\n    created_at timestamptz NOT NULL DEFAULT now()\n);$0".into(),
232        is_snippet: true,
233        kb_entry: None,
234        sort_priority: 3,
235    });
236  out.push(Item {
237        label: "fn".into(),
238        kind: ItemKind::Keyword,
239        detail: Some("CREATE OR REPLACE FUNCTION skeleton".into()),
240        description: Some("snippet".into()),
241        documentation_md: Some(
242            "Expands to a CREATE OR REPLACE FUNCTION with plpgsql body.".into()
243        ),
244        insert_text: "CREATE OR REPLACE FUNCTION ${1:name}(${2:args})\n    RETURNS ${3:void}\n    LANGUAGE plpgsql\nAS $$\nBEGIN\n    $0\nEND;\n$$;".into(),
245        is_snippet: true,
246        kb_entry: None,
247        sort_priority: 3,
248    });
249  out.push(Item {
250        label: "trig".into(),
251        kind: ItemKind::Keyword,
252        detail: Some("CREATE TRIGGER + handler function skeleton".into()),
253        description: Some("snippet".into()),
254        documentation_md: Some(
255            "Expands to a row-level AFTER trigger + matching plpgsql handler.".into()
256        ),
257        insert_text: "CREATE OR REPLACE FUNCTION ${1:handler}()\n    RETURNS TRIGGER\n    LANGUAGE plpgsql\nAS $$\nBEGIN\n    $0\n    RETURN NEW;\nEND;\n$$;\n\nCREATE TRIGGER ${2:trg_name}\n    AFTER INSERT OR UPDATE ON ${3:table}\n    FOR EACH ROW\n    EXECUTE FUNCTION ${1:handler}();".into(),
258        is_snippet: true,
259        kb_entry: None,
260        sort_priority: 3,
261    });
262  out.push(Item {
263    label: "idx".into(),
264    kind: ItemKind::Keyword,
265    detail: Some("CREATE INDEX skeleton".into()),
266    description: Some("snippet".into()),
267    documentation_md: Some("Index on a single column.".into()),
268    insert_text: "CREATE INDEX ${1:idx_name} ON ${2:table} (${3:col});$0".into(),
269    is_snippet: true,
270    kb_entry: None,
271    sort_priority: 3,
272  });
273  out.push(Item {
274    label: "view".into(),
275    kind: ItemKind::Keyword,
276    detail: Some("CREATE VIEW skeleton".into()),
277    description: Some("snippet".into()),
278    documentation_md: Some("CREATE OR REPLACE VIEW with a body.".into()),
279    insert_text: "CREATE OR REPLACE VIEW ${1:name} AS\nSELECT $0\nFROM ${2:table};".into(),
280    is_snippet: true,
281    kb_entry: None,
282    sort_priority: 3,
283  });
284  out.push(Item {
285    label: "mat".into(),
286    kind: ItemKind::Keyword,
287    detail: Some("CREATE MATERIALIZED VIEW skeleton".into()),
288    description: Some("snippet".into()),
289    documentation_md: Some("Materialised view + REFRESH hint.".into()),
290    insert_text: "CREATE MATERIALIZED VIEW ${1:name} AS\nSELECT $0\nFROM ${2:table}\nWITH DATA;".into(),
291    is_snippet: true,
292    kb_entry: None,
293    sort_priority: 3,
294  });
295  out.push(Item {
296    label: "enum".into(),
297    kind: ItemKind::Keyword,
298    detail: Some("CREATE TYPE ... AS ENUM skeleton".into()),
299    description: Some("snippet".into()),
300    documentation_md: Some("Enum type with a couple of starter values.".into()),
301    insert_text: "CREATE TYPE ${1:name} AS ENUM (\n    '${2:value_a}',\n    '${3:value_b}'\n);$0".into(),
302    is_snippet: true,
303    kb_entry: None,
304    sort_priority: 3,
305  });
306  out.push(Item {
307    label: "dom".into(),
308    kind: ItemKind::Keyword,
309    detail: Some("CREATE DOMAIN skeleton".into()),
310    description: Some("snippet".into()),
311    documentation_md: Some("Domain over an underlying type with optional CHECK.".into()),
312    insert_text: "CREATE DOMAIN ${1:name} AS ${2:text}\n    CHECK (VALUE ${3:~ '^.+$'});$0".into(),
313    is_snippet: true,
314    kb_entry: None,
315    sort_priority: 3,
316  });
317  out.push(Item {
318        label: "pol".into(),
319        kind: ItemKind::Keyword,
320        detail: Some("CREATE POLICY skeleton".into()),
321        description: Some("snippet".into()),
322        documentation_md: Some("Row-level security policy.".into()),
323        insert_text: "CREATE POLICY ${1:name} ON ${2:table}\n    FOR ${3|ALL,SELECT,INSERT,UPDATE,DELETE|}\n    TO ${4:role}\n    USING (${5:true});$0".into(),
324        is_snippet: true,
325        kb_entry: None,
326        sort_priority: 3,
327    });
328  out.push(Item {
329    label: "do".into(),
330    kind: ItemKind::Keyword,
331    detail: Some("DO $$ ... $$ anonymous block".into()),
332    description: Some("snippet".into()),
333    documentation_md: Some("Anonymous plpgsql block (no function declaration).".into()),
334    insert_text: "DO $$\nBEGIN\n    $0\nEND;\n$$;".into(),
335    is_snippet: true,
336    kb_entry: None,
337    sort_priority: 3,
338  });
339  out.push(Item {
340    label: "addcol".into(),
341    kind: ItemKind::Keyword,
342    detail: Some("ALTER TABLE ADD COLUMN".into()),
343    description: Some("snippet".into()),
344    documentation_md: Some("Add a new column.".into()),
345    insert_text: "ALTER TABLE ${1:table} ADD COLUMN ${2:name} ${3:type} ${4|NOT NULL,NULL|}${5: DEFAULT ${6:expr}};$0"
346      .into(),
347    is_snippet: true,
348    kb_entry: None,
349    sort_priority: 3,
350  });
351  out.push(Item {
352    label: "rencol".into(),
353    kind: ItemKind::Keyword,
354    detail: Some("ALTER TABLE RENAME COLUMN".into()),
355    description: Some("snippet".into()),
356    documentation_md: Some("Rename a column.".into()),
357    insert_text: "ALTER TABLE ${1:table} RENAME COLUMN ${2:old_name} TO ${3:new_name};$0".into(),
358    is_snippet: true,
359    kb_entry: None,
360    sort_priority: 3,
361  });
362  out.push(Item {
363    label: "rentab".into(),
364    kind: ItemKind::Keyword,
365    detail: Some("ALTER TABLE RENAME TO".into()),
366    description: Some("snippet".into()),
367    documentation_md: Some("Rename a table.".into()),
368    insert_text: "ALTER TABLE ${1:old_name} RENAME TO ${2:new_name};$0".into(),
369    is_snippet: true,
370    kb_entry: None,
371    sort_priority: 3,
372  });
373  out.push(Item {
374        label: "copyin".into(),
375        kind: ItemKind::Keyword,
376        detail: Some("COPY ... FROM CSV".into()),
377        description: Some("snippet".into()),
378        documentation_md: Some("Bulk load from a CSV file with HEADER + DELIMITER.".into()),
379        insert_text: "COPY ${1:table} (${2:col1, col2})\nFROM '${3:/path/to/file.csv}'\nWITH (FORMAT csv, HEADER true, DELIMITER ',');$0".into(),
380        is_snippet: true,
381        kb_entry: None,
382        sort_priority: 3,
383    });
384  out.push(Item {
385    label: "copyout".into(),
386    kind: ItemKind::Keyword,
387    detail: Some("COPY ... TO CSV".into()),
388    description: Some("snippet".into()),
389    documentation_md: Some("Export to a CSV file with HEADER.".into()),
390    insert_text: "COPY (SELECT ${1:*} FROM ${2:table})\nTO '${3:/path/to/file.csv}'\nWITH (FORMAT csv, HEADER true);$0"
391      .into(),
392    is_snippet: true,
393    kb_entry: None,
394    sort_priority: 3,
395  });
396  out.push(Item {
397    label: "listen".into(),
398    kind: ItemKind::Keyword,
399    detail: Some("LISTEN / UNLISTEN pair".into()),
400    description: Some("snippet".into()),
401    documentation_md: Some("LISTEN to a channel; remember to UNLISTEN on session end.".into()),
402    insert_text: "LISTEN ${1:channel};\n-- ... do work ...\nUNLISTEN ${1:channel};$0".into(),
403    is_snippet: true,
404    kb_entry: None,
405    sort_priority: 3,
406  });
407  out.push(Item {
408    label: "notify".into(),
409    kind: ItemKind::Keyword,
410    detail: Some("NOTIFY <channel>, '<payload>'".into()),
411    description: Some("snippet".into()),
412    documentation_md: Some("Send a notification on a channel.".into()),
413    insert_text: "NOTIFY ${1:channel}, '${2:payload}';$0".into(),
414    is_snippet: true,
415    kb_entry: None,
416    sort_priority: 3,
417  });
418  out.push(Item {
419        label: "upsert".into(),
420        kind: ItemKind::Keyword,
421        detail: Some("INSERT ... ON CONFLICT DO UPDATE".into()),
422        description: Some("snippet".into()),
423        documentation_md: Some("Insert or update on conflict (PG-native upsert).".into()),
424        insert_text: "INSERT INTO ${1:table} (${2:cols})\nVALUES (${3:vals})\nON CONFLICT (${4:conflict_col})\nDO UPDATE SET ${5:col} = EXCLUDED.${5:col};$0".into(),
425        is_snippet: true,
426        kb_entry: None,
427        sort_priority: 3,
428    });
429}
430
431/// Keywords expected after a finished table reference: JOIN / WHERE /
432/// GROUP BY / HAVING / ORDER BY / LIMIT / set ops.
433pub fn after_table_keywords(out: &mut Vec<Item>) {
434  const KEEP: &[&str] = &[
435    "INNER JOIN",
436    "LEFT JOIN",
437    "RIGHT JOIN",
438    "FULL OUTER JOIN",
439    "CROSS JOIN",
440    "JOIN",
441    "ON",
442    "USING",
443    "AS",
444    "LATERAL",
445    "WHERE",
446    "GROUP BY",
447    "HAVING",
448    "ORDER BY",
449    "LIMIT",
450    "OFFSET",
451    "UNION",
452    "INTERSECT",
453    "EXCEPT",
454  ];
455  emit_keyword_subset(out, KEEP);
456}
457
458/// Keywords valid at the end of a projection item (between SELECT and FROM).
459pub fn after_projection_keywords(out: &mut Vec<Item>) {
460  const KEEP: &[&str] = &["FROM", "AS", "INTO"];
461  emit_keyword_subset(out, KEEP);
462}
463
464/// Sort modifiers used inside ORDER BY.
465pub fn order_modifiers(out: &mut Vec<Item>) {
466  const KEEP: &[&str] = &["ASC", "DESC", "NULLS FIRST", "NULLS LAST"];
467  emit_keyword_subset(out, KEEP);
468}
469
470/// Column-constraint keywords valid right after a column type inside a
471/// CREATE TABLE definition.
472pub fn column_constraint_keywords(out: &mut Vec<Item>) {
473  const KEEP: &[&str] =
474    &["NOT NULL", "NULL", "DEFAULT", "PRIMARY KEY", "UNIQUE", "CHECK", "REFERENCES", "GENERATED", "COLLATE"];
475  emit_keyword_subset(out, KEEP);
476}
477
478/// Starter keywords that may begin an entry inside a CREATE TABLE body
479/// in lieu of a fresh column name.
480pub fn create_table_entry_starters(out: &mut Vec<Item>) {
481  const KEEP: &[&str] = &["PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK", "LIKE"];
482  emit_keyword_subset(out, KEEP);
483  // CONSTRAINT gets a snippet template so the user only types the
484  // constraint name, picks the kind, and types the column list.
485  out.push(Item {
486    label: "CONSTRAINT".into(),
487    kind: ItemKind::Keyword,
488    detail: Some("CONSTRAINT <name> <kind> (<cols>)".into()),
489    description: Some("named constraint".into()),
490    documentation_md: Some(
491      "Insert a named constraint. After the snippet expands you fill in:\n\n\
492             1. constraint name\n\
493             2. constraint kind (`PRIMARY KEY` / `UNIQUE` / `FOREIGN KEY` / `CHECK`)\n\
494             3. column list"
495        .into(),
496    ),
497    insert_text: "CONSTRAINT ${1:name} ${2|PRIMARY KEY,UNIQUE,FOREIGN KEY,CHECK|} (${3:col})$0".into(),
498    is_snippet: true,
499    kb_entry: None,
500    sort_priority: 4,
501  });
502}
503
504/// Constraint-kind keywords that follow `CONSTRAINT <name>`.
505pub fn constraint_kinds(out: &mut Vec<Item>) {
506  const KEEP: &[&str] = &["PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK"];
507  emit_keyword_subset(out, KEEP);
508}
509
510/// Privilege keywords valid after `GRANT` / `REVOKE`. Mirrors the
511/// PG GRANT grammar. ALL [PRIVILEGES] short-hand is offered first
512/// so a quick "GRANT ALL ..." stays one keystroke away.
513pub fn grant_privileges(out: &mut Vec<Item>) {
514  const PRIVS: &[(&str, &str)] = &[
515    ("ALL PRIVILEGES", "every privilege the role is allowed to grant"),
516    ("SELECT", "read rows / call function / read sequence value"),
517    ("INSERT", "add new rows"),
518    ("UPDATE", "modify existing rows"),
519    ("DELETE", "remove rows"),
520    ("TRUNCATE", "TRUNCATE table"),
521    ("REFERENCES", "create FK referencing the table/column"),
522    ("TRIGGER", "create trigger on the table"),
523    ("USAGE", "use schema / sequence / language / type"),
524    ("EXECUTE", "call a function or procedure"),
525    ("CREATE", "create objects in the database/schema"),
526    ("CONNECT", "connect to the database"),
527    ("TEMPORARY", "create temporary tables in the database"),
528    ("MAINTAIN", "PG17+ -- VACUUM/ANALYZE/REINDEX/REFRESH MV/CLUSTER/LOCK TABLE without owning the table"),
529  ];
530  for (label, doc) in PRIVS {
531    out.push(Item {
532      label: (*label).into(),
533      kind: ItemKind::Keyword,
534      detail: Some((*doc).into()),
535      description: Some("GRANT / REVOKE".into()),
536      documentation_md: None,
537      insert_text: (*label).into(),
538      is_snippet: false,
539      kb_entry: None,
540      sort_priority: 0,
541    });
542  }
543  out.push(Item {
544    label: "ON".into(),
545    kind: ItemKind::Keyword,
546    detail: Some("introduces the target object list".into()),
547    description: Some("GRANT / REVOKE".into()),
548    documentation_md: None,
549    insert_text: "ON".into(),
550    is_snippet: false,
551    kb_entry: None,
552    sort_priority: 1,
553  });
554}
555
556/// Object-class keywords valid after `GRANT ... ON`. Real catalog
557/// targets are emitted alongside by the engine.
558pub fn grant_object_classes(out: &mut Vec<Item>) {
559  const CLASSES: &[(&str, &str)] = &[
560    ("TABLE", "ON TABLE <name>[, ...]"),
561    ("ALL TABLES IN SCHEMA", "ON ALL TABLES IN SCHEMA <schema>[, ...]"),
562    ("SEQUENCE", "ON SEQUENCE <name>[, ...]"),
563    ("ALL SEQUENCES IN SCHEMA", "ON ALL SEQUENCES IN SCHEMA <schema>[, ...]"),
564    ("FUNCTION", "ON FUNCTION <name>(<args>)[, ...]"),
565    ("ALL FUNCTIONS IN SCHEMA", "ON ALL FUNCTIONS IN SCHEMA <schema>[, ...]"),
566    ("PROCEDURE", "ON PROCEDURE <name>[, ...]"),
567    ("SCHEMA", "ON SCHEMA <name>[, ...]"),
568    ("DATABASE", "ON DATABASE <name>[, ...]"),
569    ("LANGUAGE", "ON LANGUAGE <name>[, ...]"),
570    ("DOMAIN", "ON DOMAIN <name>[, ...]"),
571    ("TYPE", "ON TYPE <name>[, ...]"),
572    ("FOREIGN DATA WRAPPER", "ON FOREIGN DATA WRAPPER <name>"),
573    ("FOREIGN SERVER", "ON FOREIGN SERVER <name>"),
574  ];
575  for (label, detail) in CLASSES {
576    out.push(Item {
577      label: (*label).into(),
578      kind: ItemKind::Keyword,
579      detail: Some((*detail).into()),
580      description: Some("GRANT ... ON".into()),
581      documentation_md: None,
582      insert_text: (*label).into(),
583      is_snippet: false,
584      kb_entry: None,
585      sort_priority: 0,
586    });
587  }
588}
589
590/// Role names valid after `GRANT ... TO` / `REVOKE ... FROM`. Pulled
591/// from the live catalog plus the `PUBLIC` pseudo-role. Empty live
592/// catalog -> only the four built-in / convention names so the menu
593/// still surfaces something useful offline.
594pub fn grant_roles(cat: &Catalog, out: &mut Vec<Item>) {
595  let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
596  out.push(Item {
597    label: "PUBLIC".into(),
598    kind: ItemKind::Keyword,
599    detail: Some("every existing role and every future role".into()),
600    description: Some("pseudo-role".into()),
601    documentation_md: None,
602    insert_text: "PUBLIC".into(),
603    is_snippet: false,
604    kb_entry: None,
605    sort_priority: 1,
606  });
607  seen.insert("PUBLIC".into());
608  for r in &cat.roles {
609    if seen.insert(r.to_ascii_uppercase()) {
610      out.push(Item {
611        label: r.clone(),
612        kind: ItemKind::Variable,
613        detail: Some("role".into()),
614        description: Some("catalog".into()),
615        documentation_md: None,
616        insert_text: r.clone(),
617        is_snippet: false,
618        kb_entry: None,
619        sort_priority: 0,
620      });
621    }
622  }
623  // Offline / freshly-introspected DB: surface common defaults so
624  // the menu isn't a one-item PUBLIC stub.
625  for fallback in ["postgres", "pg_read_all_data", "pg_write_all_data"] {
626    if seen.insert(fallback.to_ascii_uppercase()) {
627      out.push(Item {
628        label: fallback.into(),
629        kind: ItemKind::Variable,
630        detail: Some("built-in role".into()),
631        description: Some("default".into()),
632        documentation_md: None,
633        insert_text: fallback.into(),
634        is_snippet: false,
635        kb_entry: None,
636        sort_priority: 5,
637      });
638    }
639  }
640}
641
642/// Sub-actions valid after `ALTER TABLE <name> `. Each item is a
643/// snippet so the user lands inside the relevant placeholder. List
644/// is curated from the PG13+ ALTER TABLE grammar -- the cardinality
645/// is too high to dump every variation, so we ship the high-value
646/// ones and let users fall back to free-form typing for the rest.
647pub fn alter_table_actions(out: &mut Vec<Item>) {
648  let actions: &[(&str, &str, &str)] = &[
649    ("ADD COLUMN", "add a column", "ADD COLUMN ${1:name} ${2:type}${3| NOT NULL,|}${4: DEFAULT ${5:expr}}"),
650    ("DROP COLUMN", "drop a column", "DROP COLUMN ${1:name}${2| CASCADE,|}"),
651    ("RENAME COLUMN", "rename a column", "RENAME COLUMN ${1:old} TO ${2:new}"),
652    (
653      "ALTER COLUMN",
654      "modify a column",
655      "ALTER COLUMN ${1:name} ${2|TYPE ${3:type},SET DEFAULT ${4:expr},DROP DEFAULT,SET NOT NULL,DROP NOT NULL|}",
656    ),
657    ("RENAME TO", "rename the table", "RENAME TO ${1:new_name}"),
658    ("SET SCHEMA", "move to a different schema", "SET SCHEMA ${1:schema}"),
659    (
660      "ADD CONSTRAINT",
661      "add a named constraint",
662      "ADD CONSTRAINT ${1:name} ${2|PRIMARY KEY (${3:cols}),UNIQUE (${3:cols}),FOREIGN KEY (${4:col}) REFERENCES ${5:tbl}(${6:col}),CHECK (${7:expr})|}",
663    ),
664    ("DROP CONSTRAINT", "drop a constraint", "DROP CONSTRAINT ${1:name}${2| CASCADE,|}"),
665    ("OWNER TO", "change owner", "OWNER TO ${1:role}"),
666    ("ENABLE", "enable trigger / RLS", "ENABLE ${1|TRIGGER ${2:name},ROW LEVEL SECURITY|}"),
667    ("DISABLE", "disable trigger / RLS", "DISABLE ${1|TRIGGER ${2:name},ROW LEVEL SECURITY|}"),
668    (
669      "ATTACH PARTITION",
670      "attach a partition",
671      "ATTACH PARTITION ${1:partition} ${2|FOR VALUES IN (${3:list}),FOR VALUES FROM (${4:lo}) TO (${5:hi}),DEFAULT|}",
672    ),
673    ("DETACH PARTITION", "detach a partition", "DETACH PARTITION ${1:partition}"),
674    ("INHERIT", "add parent table", "INHERIT ${1:parent}"),
675    ("NO INHERIT", "remove parent table", "NO INHERIT ${1:parent}"),
676    ("SET TABLESPACE", "move table to tablespace", "SET TABLESPACE ${1:tablespace}"),
677    ("CLUSTER ON", "set CLUSTER index", "CLUSTER ON ${1:index_name}"),
678    ("SET WITHOUT CLUSTER", "remove CLUSTER", "SET WITHOUT CLUSTER"),
679    ("ENABLE TRIGGER", "enable a trigger by name (or ALL / USER)", "ENABLE TRIGGER ${1:name}"),
680    ("DISABLE TRIGGER", "disable a trigger by name (or ALL / USER)", "DISABLE TRIGGER ${1:name}"),
681    ("ENABLE ROW LEVEL SECURITY", "turn RLS on for the table", "ENABLE ROW LEVEL SECURITY"),
682    ("DISABLE ROW LEVEL SECURITY", "turn RLS off for the table", "DISABLE ROW LEVEL SECURITY"),
683    ("FORCE ROW LEVEL SECURITY", "apply RLS even to the table owner", "FORCE ROW LEVEL SECURITY"),
684    ("NO FORCE ROW LEVEL SECURITY", "revert FORCE RLS (default)", "NO FORCE ROW LEVEL SECURITY"),
685    (
686      "ENABLE REPLICA TRIGGER",
687      "ENABLE REPLICA TRIGGER -- fire only when in replica role",
688      "ENABLE REPLICA TRIGGER ${1:name}",
689    ),
690    ("ENABLE ALWAYS TRIGGER", "ENABLE ALWAYS TRIGGER -- fire even in replica role", "ENABLE ALWAYS TRIGGER ${1:name}"),
691    (
692      "REPLICA IDENTITY",
693      "REPLICA IDENTITY {DEFAULT|FULL|USING INDEX <ix>|NOTHING}",
694      "REPLICA IDENTITY ${1|DEFAULT,FULL,NOTHING|}",
695    ),
696    ("RESET", "RESET (<storage_param>[, ...])", "RESET (${1:storage_param})"),
697    ("SET", "SET (<storage_param> = <value>[, ...])", "SET (${1:storage_param} = ${2:value})"),
698    ("OF", "OF <type> -- bind table to a composite type", "OF ${1:type_name}"),
699    ("NOT OF", "NOT OF -- detach composite type binding", "NOT OF"),
700    ("VALIDATE CONSTRAINT", "validate a previously NOT VALID constraint", "VALIDATE CONSTRAINT ${1:name}"),
701    ("OPTIONS", "FOREIGN TABLE OPTIONS only -- key/value list edit", "OPTIONS (${1:key} '${2:value}')"),
702    ("SET ACCESS METHOD", "switch table access method (PG12+)", "SET ACCESS METHOD ${1:method}"),
703    ("SET LOGGED", "make an UNLOGGED table logged", "SET LOGGED"),
704    ("SET UNLOGGED", "make a table UNLOGGED", "SET UNLOGGED"),
705  ];
706  for (label, detail, snippet) in actions {
707    out.push(Item {
708      label: (*label).into(),
709      kind: ItemKind::Keyword,
710      detail: Some((*detail).into()),
711      description: Some("ALTER TABLE".into()),
712      documentation_md: None,
713      insert_text: (*snippet).into(),
714      is_snippet: true,
715      kb_entry: None,
716      sort_priority: 0,
717    });
718  }
719}
720
721/// All known SQL types -- used inside CREATE TABLE column-type position.
722pub fn types_only(out: &mut Vec<Item>) {
723  for (label, e) in kb::types() {
724    out.push(from_entry(label, e, ItemKind::Type));
725  }
726}
727
728/// Columns of a specific catalog table only.
729pub fn columns_of_table(cat: &Catalog, schema: Option<&str>, table_name: &str, out: &mut Vec<Item>) {
730  if let Some(t) = cat.find_table(schema, table_name) {
731    for c in &t.columns {
732      out.push(column_item(t, c));
733    }
734  }
735}
736
737/// PL/pgSQL flow-control + body essentials.
738pub fn plpgsql_keywords(out: &mut Vec<Item>) {
739  const KEEP: &[&str] = &[
740    // Control flow + block structure.
741    "DECLARE",
742    "BEGIN",
743    "END",
744    "IF",
745    "ELSIF",
746    "ELSE",
747    "THEN",
748    "LOOP",
749    "WHILE",
750    "FOR",
751    "EXIT",
752    "CONTINUE",
753    "PERFORM",
754    // Return + exception handling.
755    "RETURN",
756    "RETURNS",
757    "RAISE",
758    "NOTICE",
759    "WARNING",
760    "EXCEPTION",
761    "FOUND",
762    "STRICT",
763    "INTO STRICT",
764    // SQL inside the body.
765    "EXECUTE",
766    "SELECT",
767    "INSERT INTO",
768    "UPDATE",
769    "DELETE FROM",
770    "WHERE",
771    "AND",
772    "OR",
773    "NOT",
774    "IS NULL",
775    "IS NOT NULL",
776    "AS",
777    "FROM",
778    "JOIN",
779    "ON",
780    "GROUP BY",
781    "ORDER BY",
782    "LIMIT",
783    "VALUES",
784    "SET",
785    "RETURNING",
786    "USING",
787    "IN",
788    "EXISTS",
789  ];
790  emit_keyword_subset(out, KEEP);
791}
792
793/// NEW and OLD virtual row aliases for trigger function bodies.
794pub fn new_old_aliases(out: &mut Vec<Item>) {
795  out.push(Item {
796    label: "NEW".into(),
797    kind: ItemKind::Keyword,
798    detail: Some("trigger row (post-change)".into()),
799    description: Some("trigger".into()),
800    documentation_md: Some(
801      "**NEW**\n\nTrigger row variable: the row being inserted or updated. \
802             Use `NEW.<column>` to access its fields."
803        .into(),
804    ),
805    insert_text: "NEW".into(),
806    is_snippet: false,
807    kb_entry: None,
808    sort_priority: 5,
809  });
810  out.push(Item {
811    label: "OLD".into(),
812    kind: ItemKind::Keyword,
813    detail: Some("trigger row (pre-change)".into()),
814    description: Some("trigger".into()),
815    documentation_md: Some(
816      "**OLD**\n\nTrigger row variable: the row before UPDATE / DELETE. \
817             Use `OLD.<column>` to access its fields."
818        .into(),
819    ),
820    insert_text: "OLD".into(),
821    is_snippet: false,
822    kb_entry: None,
823    sort_priority: 5,
824  });
825}
826
827fn emit_keyword_subset(out: &mut Vec<Item>, names: &[&str]) {
828  let table = kb::keywords();
829  for name in names {
830    if let Some(e) = table.get(*name) {
831      out.push(from_entry(name, e, ItemKind::Keyword));
832    }
833  }
834}
835
836pub fn tables(cat: &Catalog, out: &mut Vec<Item>) {
837  for t in cat.tables() {
838    out.push(table_item(t));
839  }
840}
841
842/// Emit tables/views belonging to the named schema. Used by dot
843/// completion when the user types `<schema>.` and we don't have a
844/// matching alias in scope -- the next valid token in that position is
845/// a relation name in that schema. Returns the number of items emitted.
846pub fn tables_in_schema(cat: &Catalog, schema_name: &str, out: &mut Vec<Item>) -> usize {
847  let start = out.len();
848  for s in &cat.schemas {
849    if s.name.eq_ignore_ascii_case(schema_name) {
850      for t in &s.tables {
851        out.push(table_item(t));
852      }
853    }
854  }
855  out.len() - start
856}
857
858/// Emit every function declared in the given schema. Mirror of
859/// [`tables_in_schema`] but for the function namespace: invoked when
860/// the user types `schema.<cursor>` and the dot handler wants to
861/// surface `schema.fn(...)` candidates alongside `schema.table` ones.
862pub fn functions_in_schema(cat: &Catalog, schema_name: &str, out: &mut Vec<Item>) -> usize {
863  let start = out.len();
864  for f in &cat.functions {
865    if f.schema.eq_ignore_ascii_case(schema_name) {
866      let detail =
867        if f.return_type.is_empty() { "function".to_string() } else { format!("function -> {}", f.return_type) };
868      // Wrap the raw DDL in a fenced sql code block so the editor's
869      // markdown renderer picks it up for syntax-highlighted display.
870      // Without the fence the body shows as plain monospace text.
871      let documentation_md = f.comment.as_ref().map(|c| {
872        let trimmed = c.trim();
873        if trimmed.starts_with("```") { c.clone() } else { format!("```sql\n{trimmed}\n```") }
874      });
875      out.push(Item {
876        label: f.name.clone(),
877        kind: ItemKind::Function,
878        detail: Some(detail),
879        description: if f.return_type.is_empty() { None } else { Some(f.return_type.clone()) },
880        documentation_md,
881        insert_text: format!("{}(", f.name),
882        is_snippet: false,
883        kb_entry: None,
884        sort_priority: 0,
885      });
886    }
887  }
888  out.len() - start
889}
890
891/// In-scope FROM/JOIN aliases declared in the current statement. Lets
892/// the user complete `u` after writing `FROM users AS u, orders o ...`
893/// without having to remember every alias. Each alias item carries the
894/// resolved table in its `description`. Items get a high priority bump
895/// (1) by the engine so they appear right under in-scope columns.
896pub fn aliases_in_scope(scope: &Scope, out: &mut Vec<Item>) {
897  for b in scope.tables() {
898    // Skip auto-bindings keyed by the bare table name; they aren't
899    // really aliases the user typed.
900    if b.alias.eq_ignore_ascii_case(&b.table.name) {
901      continue;
902    }
903    out.push(Item {
904      label: b.alias.clone(),
905      kind: ItemKind::Table,
906      detail: Some(format!("alias of {}", b.table.name)),
907      description: Some(format!("→ {}", b.table.name)),
908      documentation_md: Some(format!("**Alias** `{}` → table `{}`\n", b.alias, b.table.name,)),
909      insert_text: b.alias.clone(),
910      is_snippet: false,
911      kb_entry: None,
912      sort_priority: 1,
913    });
914  }
915}
916
917/// Emit each column NAME exactly once -- even when the same column
918/// (`updated_at`, `created_at`, `id`) appears in many tables, the user
919/// only sees one suggestion. The detail field still names the originating
920/// table so they can tell where the type came from.
921pub fn columns(cat: &Catalog, out: &mut Vec<Item>) {
922  let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
923  for t in cat.tables() {
924    for c in &t.columns {
925      if !seen.insert(c.name.to_ascii_lowercase()) {
926        continue;
927      }
928      out.push(column_item(t, c));
929    }
930  }
931}
932
933/// Catalog-wide columns when the user has no FROM yet. Dedups by column
934/// name -- a column that appears in N tables produces one item whose
935/// `detail` lists every owner so the user still sees the origins.
936pub fn columns_all(cat: &Catalog, out: &mut Vec<Item>) {
937  use std::collections::BTreeMap;
938  #[allow(clippy::type_complexity)]
939  let mut by_name: BTreeMap<String, (Vec<(&Table, &Column)>, &Table, &Column)> = BTreeMap::new();
940  for t in cat.tables() {
941    for c in &t.columns {
942      let key = c.name.to_ascii_lowercase();
943      by_name.entry(key).and_modify(|e| e.0.push((t, c))).or_insert_with(|| (vec![(t, c)], t, c));
944    }
945  }
946  for (_, (all_owners, first_t, first_c)) in by_name {
947    let owners: Vec<String> = all_owners.iter().map(|(t, _)| t.name.clone()).collect();
948    let detail = if owners.len() == 1 {
949      format!("{}  {}", display_type(&first_c.data_type), owners[0])
950    } else {
951      format!("{}  in {} tables: {}", display_type(&first_c.data_type), owners.len(), owners.join(", "))
952    };
953    let mut item = column_item(first_t, first_c);
954    item.detail = Some(detail);
955    out.push(item);
956  }
957}
958
959pub fn schemas(cat: &Catalog, out: &mut Vec<Item>) {
960  for s in &cat.schemas {
961    out.push(Item {
962      label: s.name.clone(),
963      kind: ItemKind::Schema,
964      detail: Some("schema".into()),
965      description: Some("schema".into()),
966      documentation_md: None,
967      insert_text: s.name.clone(),
968      is_snippet: false,
969      kb_entry: None,
970      sort_priority: 5,
971    });
972  }
973}
974
975/// Emit columns of the table resolved by `alias` in `scope`, if any.
976/// Returns the number of items emitted so callers can detect "no match".
977pub fn columns_of_alias(cat: &Catalog, scope: &Scope, alias: &str, out: &mut Vec<Item>) -> usize {
978  let Some(b) = scope.get(alias) else {
979    return 0;
980  };
981  let table = match cat.find_table(b.table.schema.as_deref(), &b.table.name) {
982    Some(t) => t,
983    None => return 0,
984  };
985  let start = out.len();
986  for c in &table.columns {
987    out.push(column_item(table, c));
988  }
989  out.len() - start
990}
991
992fn table_item(t: &Table) -> Item {
993  let base = match t.kind {
994    TableKind::View => "view",
995    TableKind::MaterializedView => "matview",
996    TableKind::WithoutRowid => "table (no rowid)",
997    TableKind::Table => "table",
998  };
999  // STRICT composes with any table kind; surface it as a trailing tag.
1000  let label = if t.strict { format!("{base}, strict") } else { base.to_string() };
1001  let detail = format!("{label}  {}.{}", t.schema, t.name);
1002  Item {
1003    label: t.name.clone(),
1004    kind: if matches!(t.kind, TableKind::View) { ItemKind::View } else { ItemKind::Table },
1005    detail: Some(detail),
1006    description: Some(t.schema.clone()),
1007    documentation_md: Some(render::table(t)),
1008    insert_text: t.name.clone(),
1009    is_snippet: false,
1010    kb_entry: None,
1011    sort_priority: 5,
1012  }
1013}
1014
1015pub fn column_item(t: &Table, c: &Column) -> Item {
1016  Item {
1017    label: c.name.clone(),
1018    kind: ItemKind::Column,
1019    detail: Some(format!("{}  {}", display_type(&c.data_type), t.name)),
1020    description: Some(t.name.clone()),
1021    documentation_md: Some(render::column(t, c)),
1022    insert_text: c.name.clone(),
1023    is_snippet: false,
1024    kb_entry: None,
1025    sort_priority: 5,
1026  }
1027}
1028
1029fn from_entry(label: &str, e: &'static Entry, kind: ItemKind) -> Item {
1030  // For functions, `detail` is the signature (highly informative). For
1031  // keywords / types the signature is None -- fall back to a short doc
1032  // excerpt so detail isn't blank. The kind icon already conveys what
1033  // kind of item this is, so we don't repeat it in `description`.
1034  let detail = e.signature.map(|s| s.to_string()).or_else(|| {
1035    let first_line = e.doc.lines().next().unwrap_or("").trim();
1036    if first_line.is_empty() { None } else { Some(first_line.to_string()) }
1037  });
1038  // For built-in functions, emit a snippet template like `length($0)`
1039  // so the editor inserts `length(<cursor>)` and the user only types
1040  // the argument. Zero-arg functions still get bare `name()`.
1041  let (insert_text, is_snippet) = if kind == ItemKind::Function {
1042    // Empty-paren check: if signature ends in `()` -> no args.
1043    let zero_args = e
1044      .signature
1045      .map(|s| {
1046        let trimmed = s.trim_end_matches([' ', '\t']);
1047        trimmed.contains("()")
1048          || trimmed.ends_with("() -> ")
1049          || trimmed.split_once("(").map(|(_, rest)| rest.trim_start().starts_with(')')).unwrap_or(false)
1050      })
1051      .unwrap_or(false);
1052    if zero_args { (format!("{label}()"), false) } else { (format!("{label}($0)"), true) }
1053  } else {
1054    (label.to_string(), false)
1055  };
1056  Item {
1057    label: label.to_string(),
1058    kind,
1059    detail,
1060    description: None,
1061    // Deliberately not rendered here -- see `Item::kb_entry`.
1062    documentation_md: None,
1063    kb_entry: Some(e),
1064    insert_text,
1065    is_snippet,
1066    sort_priority: 5,
1067  }
1068}