Skip to main content

dsl_completion/
engine.rs

1//! Completion engine.
2//!
3//! Routing runs through two ordered detector registries, each an
4//! array of `(source, offset, file, scopes, catalog) -> Option<Vec<Item>>`
5//! functions walked in order -- first `Some` wins, `None` falls
6//! through to the next entry. This is the *only* place precedence
7//! order lives; every entry's doc comment explains why it needs to
8//! run where it does relative to its neighbors.
9//!
10//!   1. [`PRE_PHASE_DETECTORS`], run by [`complete_with_derived`]
11//!      before the cursor's phase is even determined: fresh-name-slot
12//!      suppression, JSON-path key slot, inert-span bailout, dot
13//!      context (`<alias>.<cursor>`), grouping-sets-inner-paren, and
14//!      `contexts::detect` (index/trigger/policy/etc special cases
15//!      the phase state machine doesn't model).
16//!   2. Falling through all of those, the phase is determined --
17//!      `create_index::detect` / `create_table::detect` narrow it
18//!      when applicable, otherwise [`phase::Phase`] via
19//!      [`phase::detect`] -- and handed to `route_phase`, which runs
20//!      [`POST_PHASE_DETECTORS`] (slot-keyword shortcuts too specific
21//!      for the phase match: `FILTER (`, `WITH ORDINALITY`, window
22//!      frame bounds, etc), then falls through to the `Phase`-driven
23//!      `match` for the "ordinary, no special case" menu per phase.
24//!
25//! This two-registry split (rather than one flat list) mirrors the
26//! algorithm's actual shape: stage 1 runs pre-phase, stage 2 runs
27//! post-phase, and unifying them into one list would mean reordering
28//! stage-1 checks relative to the phase-determination step in between
29//! -- a real behavior change, not just reorganization.
30//!
31//! This is what makes the menu context-aware: after `SELECT *` we
32//! surface `FROM`, not more SELECT keywords; after a table we surface
33//! `JOIN` / `WHERE` / `GROUP BY` / etc; inside ORDER BY we surface
34//! columns + ASC/DESC; after WHERE we surface columns + expression
35//! keywords; after a semicolon we surface top-level statement starters
36//! only.
37
38use crate::create_index;
39use crate::create_table;
40// Wildcard: `detectors` is currently one large "everything not yet
41// thematically split" module (189 functions, deliberately not
42// subdivided in this Stage-1 pure-motion batch -- see its module doc).
43// Explicit per-item imports would mean ~150+ names here; a future
44// thematic split of detectors.rs would naturally restore explicit
45// `module::fn()` call sites the way merge/json_path already have.
46use crate::detectors::*;
47use crate::fallback;
48use crate::item::Item;
49use crate::json_path;
50use crate::merge;
51use crate::phase::{self, Phase};
52use crate::source_tables;
53use crate::sources;
54use dsl_catalog::Catalog;
55use dsl_parse::ParsedFile;
56use dsl_resolve::Scope;
57use text_size::TextSize;
58
59/// Extract the current SQL statement up to `offset` as (slice, upper).
60/// Statement boundary = last `;` before pos. `slice` is `source[stmt_start..pos]`
61/// verbatim; `upper` is the uppercase of `slice` with byte offsets preserved
62/// (no trim). Callers that need `upper.starts_with("CREATE …")` should do
63/// `upper.trim_start().starts_with(...)` themselves.
64pub(crate) fn stmt_slice_upper(source: &str, offset: TextSize) -> (String, String) {
65  let pos: usize = (u32::from(offset) as usize).min(source.len());
66  let stmt_start = source[..pos].rfind(';').map(|p| p + 1).unwrap_or(0);
67  let slice = source[stmt_start..pos].to_string();
68  let upper = slice.to_ascii_uppercase();
69  (slice, upper)
70}
71
72/// Byte-slice of the current statement, semicolon-delimited, covering
73/// *both* sides of the cursor (unlike `stmt_slice_upper`, which stops
74/// at `offset`). Naive `;`-scan -- doesn't account for a semicolon
75/// inside a string literal or a dollar-quoted PL/pgSQL body, same
76/// known limitation `stmt_slice_upper`'s start-boundary already has.
77///
78/// Scopes text-fallback scans (`fallback::scope_from_text` and
79/// friends) to the statement under the cursor instead of the whole
80/// buffer -- `iter_table_bindings` scans its input start-to-end for
81/// every FROM/JOIN, so an unscoped whole-buffer call is O(buffer size)
82/// regardless of cursor position. This was the dominant cost behind
83/// the Phase A perf finding (`dsl-completion/tests/perf_bench.rs`,
84/// ~25ms/call at 10k statements); see the design doc's "Phase D
85/// findings" for the full writeup.
86pub(crate) fn current_statement_span(source: &str, offset: TextSize) -> &str {
87  let pos: usize = (u32::from(offset) as usize).min(source.len());
88  let start = source[..pos].rfind(';').map(|p| p + 1).unwrap_or(0);
89  let end = source[pos..].find(';').map(|p| pos + p + 1).unwrap_or(source.len());
90  &source[start..end]
91}
92
93/// Return true when `offset` does NOT sit at a whitespace (or EOF)
94/// boundary. Phase detectors short-circuit on this so they don't yank
95/// the menu open while the user is typing a token. Matches the legacy
96/// guard `pos < bytes.len() && !bytes[pos].is_ascii_whitespace()`.
97pub(crate) fn cursor_not_at_ws_boundary(source: &str, offset: TextSize) -> bool {
98  let pos: usize = (u32::from(offset) as usize).min(source.len());
99  let bytes = source.as_bytes();
100  pos < bytes.len() && !bytes[pos].is_ascii_whitespace()
101}
102
103/// Append every `(label, detail)` pair as a fresh `Keyword` item with
104/// default sort priority. Used by every per-statement phase emitter
105/// (CREATE TABLE / TRIGGER / TYPE / ALTER ROLE / ...).
106pub(crate) fn push_keyword_kvs(out: &mut Vec<Item>, kws: &[(&'static str, &'static str)]) {
107  for (kw, doc) in kws {
108    out.push(Item {
109      label: (*kw).into(),
110      kind: crate::item::ItemKind::Keyword,
111      detail: Some((*doc).into()),
112      insert_text: (*kw).into(),
113      kb_entry: None,
114      sort_priority: 0,
115      ..Default::default()
116    });
117  }
118}
119
120/// Convenience wrapper for callers with no pre-computed buffer-derived
121/// catalog (tests, one-shot tools, `dsl-cli`). Derives it fresh from
122/// `source` via `source_tables::from_source` on every call. Callers
123/// that invoke completion repeatedly against the *same* buffer (an LSP
124/// server servicing one document across many requests) should derive
125/// this catalog once and call [`complete_with_derived`] directly
126/// instead -- see `Document::derived_catalog` in dsl-server.
127pub fn complete(source: &str, file: &ParsedFile, scopes: &[Scope], catalog: &Catalog, offset: TextSize) -> Vec<Item> {
128  let derived = source_tables::from_source(file, source);
129  complete_with_derived(source, file, scopes, catalog, &derived, offset)
130}
131
132/// Same as [`complete`] but takes the buffer-derived catalog
133/// (normally `source_tables::from_source(file, source)`) as an
134/// explicit parameter instead of computing it internally. `catalog`
135/// and `derived` are merged with `catalog` winning on collisions
136/// (matches [`source_tables::merge`]'s live-wins-over-derived
137/// semantics).
138pub fn complete_with_derived(
139  source: &str,
140  file: &ParsedFile,
141  scopes: &[Scope],
142  catalog: &Catalog,
143  derived: &Catalog,
144  offset: TextSize,
145) -> Vec<Item> {
146  // Normalise offset to the nearest valid UTF-8 char boundary so
147  // downstream slicing can't panic on multi-byte characters.
148  let raw_off: usize = offset.into();
149  let off = floor_char_boundary(source, raw_off.min(source.len()));
150  let offset = TextSize::from(off as u32);
151
152  // Merge live catalog with the (caller-supplied) buffer-derived
153  // catalog: tables from AST + sequences / types / extensions /
154  // functions / roles harvested from buffer text + the default
155  // offline roles. Live catalog wins on collisions. Computed up front
156  // (cheap -- no more scan work than a shallow struct merge) so the
157  // JSON-path key slot below can consult catalog-typed `json_keys`
158  // hints, not just same-buffer literal examples.
159  let cat = source_tables::merge(catalog, derived);
160
161  // Every pre-phase check, in the exact order they used to run as a
162  // chain of `if`/`if let` statements -- see `PRE_PHASE_DETECTORS`'s
163  // doc comment for the full list and why it's shaped this way.
164  for detector in PRE_PHASE_DETECTORS {
165    if let Some(items) = detector(source, offset, file, scopes, &cat) {
166      return items;
167    }
168  }
169
170  // CREATE INDEX scoped context wins before CREATE TABLE / generic
171  // phases. `CREATE INDEX <name> ON users (` should only ever surface
172  // columns of `users`, never a global table or column dump.
173  if let Some(ix_phase) = create_index::detect(source, offset) {
174    return route_phase(ix_phase, file, scopes, source, &cat, offset);
175  }
176  // CREATE TABLE sub-phase trumps the generic state machine because the
177  // narrower context (column name vs type vs constraint) is what the
178  // user is in the middle of writing.
179  if let Some(ct_phase) = create_table::detect(source, offset) {
180    return route_phase(ct_phase, file, scopes, source, &cat, offset);
181  }
182
183  let ph = phase::detect(source, offset);
184  route_phase(ph, file, scopes, source, &cat, offset)
185}
186
187/// Hard-suppress completion when the cursor sits at the "fresh name"
188/// slot after a `CREATE [OR REPLACE] <KIND>` keyword. The user is
189/// naming a brand-new object; no existing catalog symbol or keyword
190/// is a sensible suggestion there, with several overrides for
191/// contexts that only *look* like a fresh-name slot (PREPARE
192/// TRANSACTION, FETCH/MOVE direction, CREATE TRANSFORM, [ALTER] USER
193/// MAPPING, the SELECT-trailing-FETCH chain, PARTITION OF ... FOR
194/// VALUES). Always claims the slot once the gate matches -- even the
195/// "none of the overrides apply" case commits to an empty menu rather
196/// than falling through, since guessing at a brand-new name is worse
197/// than suggesting nothing.
198fn detect_fresh_name_slot(
199  source: &str,
200  offset: TextSize,
201  _file: &ParsedFile,
202  _scopes: &[Scope],
203  _cat: &Catalog,
204) -> Option<Vec<Item>> {
205  if !at_fresh_name_slot(source, offset) {
206    return None;
207  }
208  if let Some(label) = fresh_name_slot_optional_keyword(source, offset) {
209    return Some(vec![crate::item::Item {
210      label: label.into(),
211      kind: crate::item::ItemKind::Keyword,
212      detail: Some("optional clarifier before the new object name".into()),
213      insert_text: label.into(),
214      kb_entry: None,
215      sort_priority: 0,
216      ..Default::default()
217    }]);
218  }
219  // `PREPARE TRANSACTION` overrides the fresh-name-slot suppression
220  // because TRANSACTION is a literal kw, not a fresh statement name.
221  if let Some(kws) = txn_followup_next_keyword(source, offset) {
222    let mut out = Vec::with_capacity(kws.len());
223    push_keyword_kvs(&mut out, kws);
224    return Some(out);
225  }
226  // FETCH / MOVE -- direction keyword set is more useful than the
227  // fresh-name suppression (cursor name comes after FROM/IN).
228  if let Some(kws) = fetch_move_direction_keyword(source, offset) {
229    let mut out = Vec::with_capacity(kws.len());
230    push_keyword_kvs(&mut out, kws);
231    return Some(out);
232  }
233  // CREATE TRANSFORM -- post-keyword slot is FOR TYPE, not a name.
234  if let Some(kws) = create_transform_next_keyword(source, offset) {
235    let mut out = Vec::with_capacity(kws.len());
236    push_keyword_kvs(&mut out, kws);
237    return Some(out);
238  }
239  // CREATE/ALTER USER MAPPING -- post-keyword slot is FOR/IF NOT EXISTS,
240  // not a brand-new identifier.
241  if let Some(kws) = create_user_mapping_next_keyword(source, offset) {
242    let mut out = Vec::with_capacity(kws.len());
243    push_keyword_kvs(&mut out, kws);
244    return Some(out);
245  }
246  if let Some(kws) = alter_user_mapping_next_keyword(source, offset) {
247    let mut out = Vec::with_capacity(kws.len());
248    push_keyword_kvs(&mut out, kws);
249    return Some(out);
250  }
251  // `SELECT ... FETCH` / `... FIRST` / `... ROW(S)`: not a cursor
252  // command, it's the SELECT trailing FETCH clause. Fresh-name guard
253  // misfires because `FETCH` is in the cursor pattern list.
254  if let Some(kws) = select_fetch_offset_next_keyword(source, offset) {
255    let mut out = Vec::with_capacity(kws.len());
256    push_keyword_kvs(&mut out, kws);
257    return Some(out);
258  }
259  // `CREATE TABLE child PARTITION OF parent FOR VALUES ` -- the
260  // trailing VALUES is part of the partition spec, not a top-level
261  // VALUES (...) statement, so the partition menu (IN/FROM/WITH/
262  // DEFAULT) wins over the fresh-name suppression.
263  if let Some(kws) = partition_next_keyword(source, offset) {
264    let mut out = Vec::with_capacity(kws.len());
265    push_keyword_kvs(&mut out, kws);
266    return Some(out);
267  }
268  Some(Vec::new())
269}
270
271/// JSON-path key slot: `data->'<cursor>` or `data->>'<cursor>`.
272/// Surface keys observed in same-buffer jsonb literal defaults / CHECK
273/// constraints, falling back to catalog-recorded `Column.json_keys`
274/// when the buffer has no example literal to harvest. Highest
275/// priority -- we don't want to drown the menu in catalog table names
276/// when the user is clearly typing a JSON key. (Runs before the
277/// inert-span bailout so JSON key completion still works while the
278/// cursor sits inside the `'...'` literal.)
279fn detect_json_path_key(
280  source: &str,
281  offset: TextSize,
282  _file: &ParsedFile,
283  _scopes: &[Scope],
284  cat: &Catalog,
285) -> Option<Vec<Item>> {
286  let keys = json_path::json_path_keys_at_with_catalog(source, offset, cat)?;
287  let mut out = Vec::with_capacity(keys.len());
288  for k in keys {
289    out.push(crate::item::Item {
290      label: k.clone(),
291      kind: crate::item::ItemKind::Variable,
292      detail: Some("JSON key".into()),
293      description: Some("known JSON key".into()),
294      documentation_md: None,
295      insert_text: k,
296      is_snippet: false,
297      kb_entry: None,
298      sort_priority: 0,
299    });
300  }
301  Some(out)
302}
303
304/// `PRE_PHASE_DETECTORS` entry: cursor inside a PL/pgSQL `EXECUTE`
305/// statement's dynamic-SQL string. Extracts and (for single-quoted
306/// strings) unescapes the content, then recursively calls `complete`
307/// on it as an independent tiny buffer -- giving full phase parity
308/// with the top-level engine "for free" rather than re-implementing a
309/// subset of it. Positioned before `detect_inert_span` below so it
310/// wins the race for this specific case while every other string
311/// literal keeps that detector's inert-suppression behavior
312/// unchanged. `file`/`scopes` (the *outer* buffer's parse) are
313/// unused: this builds its own parse for the extracted substring,
314/// same as any other pure-text-check `Detector`. `Dialect::Postgres`
315/// is hardcoded -- `EXECUTE` and dollar-quoting are themselves
316/// Postgres-specific syntax.
317fn detect_execute_dynamic_sql(
318  source: &str,
319  offset: TextSize,
320  _file: &ParsedFile,
321  _scopes: &[Scope],
322  cat: &Catalog,
323) -> Option<Vec<Item>> {
324  let pos: usize = u32::from(offset) as usize;
325  let span = execute_dynamic_sql_span(source, pos)?;
326  let raw = &source[span.content_start..span.content_end];
327  let raw_cursor = pos - span.content_start;
328  let (content, inner_offset) =
329    if span.dollar_quoted { (raw.to_string(), raw_cursor) } else { unescape_single_quoted(raw, raw_cursor) };
330  let inner_file = dsl_parse::parse(&content, dsl_parse::Dialect::Postgres);
331  let inner_scopes = dsl_resolve::resolve_with_source(&inner_file.statements, &content);
332  Some(complete(&content, &inner_file, &inner_scopes, cat, TextSize::from(inner_offset as u32)))
333}
334
335/// Cursor inside a string literal or comment? Suggesting keywords /
336/// tables / columns there is just noise -- the user is typing string
337/// content. Dollar-quoted bodies (PL/pgSQL) are NOT inert -- recurse
338/// into them so completion still works inside function bodies. Claims
339/// the position with an empty menu (`Some(Vec::new())`) rather than
340/// declining (`None`) -- declining would let later detectors and the
341/// phase match compute a real, wrong answer for a cursor sitting
342/// inside a literal.
343fn detect_inert_span(
344  source: &str,
345  offset: TextSize,
346  _file: &ParsedFile,
347  _scopes: &[Scope],
348  _cat: &Catalog,
349) -> Option<Vec<Item>> {
350  if cursor_in_inert_span(source, u32::from(offset) as usize) { Some(Vec::new()) } else { None }
351}
352
353/// Dot context: `<alias>.<cursor>` -- highest priority once past the
354/// fresh-name-slot / JSON-path / inert-span checks above, beats every
355/// phase result. Resolution order for the alias's columns: NEW/OLD
356/// virtual trigger-body aliases, `EXCLUDED` (ON CONFLICT DO UPDATE),
357/// in-scope table/CTE binding (AST-resolved, falling back to a
358/// text-scan when the resolver didn't run), a PL/pgSQL local typed as
359/// a catalog table (row variable), a schema-qualified relation, and
360/// finally a bare table name with no scope binding at all. Always
361/// claims the slot once `dot_alias` matches -- even "found nothing"
362/// is a deliberate empty menu, not a fall-through, since a global
363/// column dump would be wrong once we know the user typed `x.`.
364fn detect_dot_context(
365  source: &str,
366  offset: TextSize,
367  file: &ParsedFile,
368  scopes: &[Scope],
369  cat: &Catalog,
370) -> Option<Vec<Item>> {
371  let alias = dot_alias(source, offset)?;
372  let mut out = Vec::new();
373  // NEW / OLD virtual aliases inside trigger-function bodies.
374  // Resolution order:
375  //   1. Look for `CREATE TRIGGER ... ON <table>` in the buffer.
376  //   2. If the cursor sits inside a CREATE FUNCTION body, find
377  //      the function name, then search the buffer + live catalog
378  //      for `CREATE TRIGGER ... EXECUTE [FUNCTION|PROCEDURE]
379  //      <fn>` and read the table off that trigger.
380  // Return WITHOUT completion when we can't pin down a single
381  // target -- guessing leads to broken hints.
382  let alias_upper = alias.to_ascii_uppercase();
383  if alias_upper == "NEW" || alias_upper == "OLD" {
384    let pos: usize = u32::from(offset) as usize;
385    let target = trigger_target_table(source).or_else(|| enclosing_fn_trigger_table(source, pos, cat));
386    if let Some(t) = target {
387      sources::columns_of_table(cat, None, &t, &mut out);
388      return Some(out);
389    }
390    // No table known -- emit nothing so the user doesn't get a
391    // misleading global column dump.
392    return Some(out);
393  }
394  // `EXCLUDED.<col>` (inside INSERT ... ON CONFLICT DO UPDATE SET ...):
395  // virtual row that mirrors the rejected INSERT row, so its column
396  // shape matches the INSERT target table.
397  if alias_upper == "EXCLUDED" {
398    if let Some(t) = insert_target_table_name_only(source) {
399      sources::columns_of_table(cat, None, &t, &mut out);
400    }
401    return Some(out);
402  }
403  let stmt_scope = scope_for_offset(file, scopes, offset);
404  let count = stmt_scope.map(|s| sources::columns_of_alias(cat, s, &alias, &mut out)).unwrap_or(0);
405  if count == 0
406    && let Some(fb) = fallback::scope_from_text(current_statement_span(source, offset))
407  {
408    sources::columns_of_alias(cat, &fb, &alias, &mut out);
409  }
410  // CTE alias: surface columns the resolver extracted from the
411  // CTE body projection. `cte_columns_of(alias)` returns
412  // `Some(empty)` when the CTE is declared but the body was not
413  // parsed -- in that case we have nothing useful to add.
414  if out.is_empty()
415    && let Some(s) = stmt_scope
416    && let Some(cols) = s.cte_columns_of(&alias)
417  {
418    for col in cols {
419      out.push(crate::item::Item {
420        label: col.clone(),
421        kind: crate::item::ItemKind::Column,
422        detail: Some(format!("CTE {alias}")),
423        description: None,
424        documentation_md: None,
425        insert_text: col.clone(),
426        is_snippet: false,
427        kb_entry: None,
428        sort_priority: 0,
429      });
430    }
431  }
432  // Fallback: when pg_query refused the outer statement (typical
433  // mid-typing `WITH t AS (...) SELECT t.`), the resolver never
434  // ran -- so cte_columns_of returns None even though the CTE
435  // is plainly declared. Text-scan the *current statement* for its
436  // leading WITH and surface that CTE's projected columns. Must be
437  // scoped to this statement: `cte_columns_from_text` only looks at
438  // its argument's own prefix, so the whole buffer would check
439  // statement #1 instead of the one under the cursor.
440  if out.is_empty()
441    && let Some(cols) = fallback::cte_columns_from_text(current_statement_span(source, offset), &alias)
442  {
443    for col in cols {
444      out.push(crate::item::Item {
445        label: col.clone(),
446        kind: crate::item::ItemKind::Column,
447        detail: Some(format!("CTE {alias}")),
448        description: None,
449        documentation_md: None,
450        insert_text: col.clone(),
451        is_snippet: false,
452        kb_entry: None,
453        sort_priority: 0,
454      });
455    }
456  }
457  // PL/pgSQL local typed as a catalog table (row variable).
458  // `DECLARE r users; ... r.<TAB>` should list users' columns.
459  if out.is_empty() {
460    let pos: usize = u32::from(offset) as usize;
461    let locals = crate::plpgsql_locals::extract(source, pos);
462    if let Some(ty) = crate::plpgsql_locals::type_of(&locals, &alias) {
463      // Strip `%ROWTYPE` suffix if present.
464      let bare = ty.split('%').next().unwrap_or(&ty).trim().trim_end_matches(';').trim();
465      if cat.find_table(None, bare).is_some() {
466        sources::columns_of_table(cat, None, bare, &mut out);
467      }
468    }
469  }
470  // Schema-qualified relation slot: `FROM <schema>.<TAB>` /
471  // `SELECT * FROM <schema>.|`. The alias here is the schema name,
472  // not an in-scope alias; surface the tables/views that schema
473  // exposes so the user can pick one. Emit nothing when the name
474  // is neither a schema nor an alias -- a global dump would be wrong.
475  if out.is_empty() {
476    sources::tables_in_schema(cat, &alias, &mut out);
477    // Also surface functions declared in this schema: `app.<TAB>`
478    // should offer `app.current_user_id()`, `app.user_in_org(...)`,
479    // etc., not just tables.
480    sources::functions_in_schema(cat, &alias, &mut out);
481  }
482  // Last-resort: the alias names a real table in the live or derived
483  // catalog (case-insensitive), even though it has no binding in the
484  // current scope. Common when the user types `SELECT USERS.<cursor>`
485  // before the FROM clause exists. pg_query rejects the prefix and
486  // the fallback scope is empty, but the table is still resolvable.
487  if out.is_empty() && cat.find_table(None, &alias).is_some() {
488    sources::columns_of_table(cat, None, &alias, &mut out);
489  }
490  // Filter columns already used in the same clause -- even in dot
491  // context, typing `SELECT u.id, u.|` should not re-offer `id`.
492  let used = used_columns_in_clause(source, offset);
493  if !used.is_empty() {
494    out.retain(|it| !is_column_listed(it, &used));
495  }
496  Some(out)
497}
498
499/// GROUP BY GROUPING SETS ((<cursor>...)) -- inner tuple is a column
500/// list slot. Must beat `contexts::detect` (which sees the inner
501/// paren as a function-call expression context) and every Phase
502/// variant.
503fn detect_grouping_sets_inner_paren(
504  source: &str,
505  offset: TextSize,
506  file: &ParsedFile,
507  scopes: &[Scope],
508  cat: &Catalog,
509) -> Option<Vec<Item>> {
510  if !grouping_sets_inner_paren_expects_column(source, offset) {
511    return None;
512  }
513  let mut out = Vec::new();
514  // Pull catalog columns directly off whatever the resolver or
515  // text-fallback found in FROM. Skip the aliased-table hide rule
516  // used by push_scope_columns -- inside GROUPING SETS the user
517  // wants bare column names since each entry is part of a tuple,
518  // not a free expression.
519  let mut tables: Vec<(Option<String>, String)> = Vec::new();
520  if let Some(scope) = scope_for_offset(file, scopes, offset) {
521    for b in scope.tables() {
522      tables.push((b.table.schema.clone(), b.table.name.clone()));
523    }
524  }
525  if tables.is_empty()
526    && let Some(fb) = fallback::scope_from_text(current_statement_span(source, offset))
527  {
528    for b in fb.tables() {
529      tables.push((b.table.schema.clone(), b.table.name.clone()));
530    }
531  }
532  let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
533  for (schema, name) in tables {
534    let key = format!("{}.{}", schema.as_deref().unwrap_or(""), name.to_ascii_lowercase());
535    if !seen.insert(key) {
536      continue;
537    }
538    sources::columns_of_table(cat, schema.as_deref(), &name, &mut out);
539  }
540  push_aliases(file, scopes, source, offset, &mut out);
541  Some(out)
542}
543
544/// Special context completions (INDEX USING method, TRIGGER EXECUTE
545/// FUNCTION, CALL procedure, CREATE POLICY FOR/TO, ALTER COLUMN TYPE,
546/// index opclass slot, trigger event slot, trigger ON table). All run
547/// *before* the index/table phases because they're more specific than
548/// the column dump those phases would emit.
549fn detect_contexts(
550  source: &str,
551  offset: TextSize,
552  _file: &ParsedFile,
553  _scopes: &[Scope],
554  cat: &Catalog,
555) -> Option<Vec<Item>> {
556  crate::contexts::detect(source, offset, cat)
557}
558
559/// Every pre-phase check, in the exact precedence order they used to
560/// run as a chain of `if`/`if let` statements at the top of
561/// `complete_with_derived` -- this array is now the only place that
562/// order lives. `complete_with_derived` runs them in sequence right
563/// after normalising the offset and merging the catalog; the first
564/// `Some` wins. Falling through every entry means none of these
565/// higher-priority contexts apply, so control moves on to the
566/// `create_index::detect` / `create_table::detect` phase overrides
567/// and finally `phase::detect` + `route_phase`'s own
568/// `POST_PHASE_DETECTORS` registry.
569const PRE_PHASE_DETECTORS: &[Detector] = &[
570  detect_fresh_name_slot,
571  detect_json_path_key,
572  detect_execute_dynamic_sql,
573  detect_inert_span,
574  detect_dot_context,
575  detect_grouping_sets_inner_paren,
576  detect_contexts,
577];
578
579/// A post-phase detector: given the same `(source, offset, file,
580/// scopes, cat)` `route_phase` receives, either claims the slot
581/// (`Some`, short-circuiting every remaining detector and the `Phase`
582/// match) or declines (`None`, falls through to the next entry).
583/// Unused parameters are intentional -- most detectors are pure text
584/// checks and only need `source`/`offset`, but the type must be
585/// uniform across every entry in [`POST_PHASE_DETECTORS`].
586type Detector = fn(&str, TextSize, &ParsedFile, &[Scope], &Catalog) -> Option<Vec<Item>>;
587
588/// UNION/INTERSECT/EXCEPT trailing slot expects ALL/DISTINCT/SELECT/
589/// VALUES, never an expression-list dump.
590fn detect_set_op_followup(
591  source: &str,
592  offset: TextSize,
593  _file: &ParsedFile,
594  _scopes: &[Scope],
595  _cat: &Catalog,
596) -> Option<Vec<Item>> {
597  let kws = set_op_followup_next_keyword(source, offset)?;
598  let mut out = Vec::new();
599  push_keyword_kvs(&mut out, kws);
600  Some(out)
601}
602
603/// JSON_TABLE(... COLUMNS (<cursor> at a fresh column-def slot -- a
604/// brand-new name, not a catalog entity, so must beat the generic
605/// table/column dump every phase would otherwise emit.
606fn detect_json_table_fresh_column_slot(
607  source: &str,
608  offset: TextSize,
609  _file: &ParsedFile,
610  _scopes: &[Scope],
611  _cat: &Catalog,
612) -> Option<Vec<Item>> {
613  if !json_table_fresh_column_slot(source, offset) {
614    return None;
615  }
616  let mut out = Vec::new();
617  push_keyword_kvs(&mut out, &[("FOR", "<name> FOR ORDINALITY -- 1-based row-number column")]);
618  Some(out)
619}
620
621/// JSON_TABLE column-def grammar beyond the fresh-slot case above --
622/// type slot, FOR ORDINALITY, PATH/FORMAT/EXISTS, FORMAT JSON, EXISTS
623/// PATH. See `json_table_column_slot_items`'s doc comment for the
624/// exact slot-by-slot breakdown; must beat the generic table/column
625/// dump the same way the fresh-slot case does.
626fn detect_json_table_column_slot(
627  source: &str,
628  offset: TextSize,
629  _file: &ParsedFile,
630  _scopes: &[Scope],
631  _cat: &Catalog,
632) -> Option<Vec<Item>> {
633  json_table_column_slot_items(source, offset)
634}
635
636/// CREATE TRANSFORM ... otherwise gets swallowed by the Phase::Start
637/// statement-keyword dump.
638fn detect_create_transform(
639  source: &str,
640  offset: TextSize,
641  _file: &ParsedFile,
642  _scopes: &[Scope],
643  _cat: &Catalog,
644) -> Option<Vec<Item>> {
645  let kws = create_transform_next_keyword(source, offset)?;
646  let mut out = Vec::new();
647  push_keyword_kvs(&mut out, kws);
648  Some(out)
649}
650
651/// TABLESAMPLE REPEATABLE chain must beat the SELECT trailing-clause
652/// menu (which would emit JOIN/WHERE/ORDER BY).
653fn detect_tablesample_after_paren(
654  source: &str,
655  offset: TextSize,
656  _file: &ParsedFile,
657  _scopes: &[Scope],
658  _cat: &Catalog,
659) -> Option<Vec<Item>> {
660  let kws = tablesample_after_paren_next_keyword(source, offset)?;
661  let mut out = Vec::new();
662  push_keyword_kvs(&mut out, kws);
663  Some(out)
664}
665
666/// `agg(...) FILTER (<cursor>` -- only WHERE is legal, must beat the
667/// expression/column dump every phase would otherwise emit.
668fn detect_filter_clause(
669  source: &str,
670  offset: TextSize,
671  _file: &ParsedFile,
672  _scopes: &[Scope],
673  _cat: &Catalog,
674) -> Option<Vec<Item>> {
675  let kws = filter_clause_next_keyword(source, offset)?;
676  let mut out = Vec::new();
677  push_keyword_kvs(&mut out, kws);
678  Some(out)
679}
680
681/// `CREATE POLICY ... USING (⏵` / `... WITH CHECK (⏵` -- must beat
682/// the generic phase's ~2300-item fallback dump the same way the
683/// other slot-keyword shortcuts beat the generic menu for their
684/// narrower contexts.
685fn detect_policy_expr(
686  source: &str,
687  offset: TextSize,
688  _file: &ParsedFile,
689  _scopes: &[Scope],
690  cat: &Catalog,
691) -> Option<Vec<Item>> {
692  policy_expr_items(source, offset, cat)
693}
694
695/// `<table-fn>(...) WITH <cursor>` in FROM/JOIN -- only ORDINALITY is
696/// legal, must beat the JOIN/WHERE/ORDER BY clause-continuation menu
697/// the FROM-item-just-finished phase would otherwise emit.
698fn detect_table_function_with_ordinality(
699  source: &str,
700  offset: TextSize,
701  _file: &ParsedFile,
702  _scopes: &[Scope],
703  _cat: &Catalog,
704) -> Option<Vec<Item>> {
705  let kws = table_function_with_ordinality_next_keyword(source, offset)?;
706  let mut out = Vec::new();
707  push_keyword_kvs(&mut out, kws);
708  Some(out)
709}
710
711/// `SELECT ... FETCH FIRST/NEXT <n> ROW(S) <cursor>` -- only fires
712/// when the last token before the cursor is actually part of that
713/// chain (`select_fetch_offset_next_keyword` alone over-matches).
714fn detect_select_fetch_offset(
715  source: &str,
716  offset: TextSize,
717  _file: &ParsedFile,
718  _scopes: &[Scope],
719  _cat: &Catalog,
720) -> Option<Vec<Item>> {
721  let kws = select_fetch_offset_next_keyword(source, offset)?;
722  let (_, upper) = stmt_slice_upper(source, offset);
723  let words: Vec<&str> = upper.split_ascii_whitespace().collect();
724  let last = words.last().copied();
725  if !matches!(last, Some("FETCH") | Some("FIRST") | Some("NEXT") | Some("ROW") | Some("ROWS")) {
726    return None;
727  }
728  let mut out = Vec::new();
729  push_keyword_kvs(&mut out, kws);
730  Some(out)
731}
732
733/// CREATE VIEW / MATERIALIZED VIEW trailing WITH clauses (CHECK
734/// OPTION, WITH DATA) must beat the SELECT-body phase that otherwise
735/// emits join/order kws after `WITH `.
736fn detect_create_view_post_name(
737  source: &str,
738  offset: TextSize,
739  _file: &ParsedFile,
740  _scopes: &[Scope],
741  _cat: &Catalog,
742) -> Option<Vec<Item>> {
743  let kws = create_view_post_name_next_keyword(source, offset)?;
744  let (_, upper) = stmt_slice_upper(source, offset);
745  let words: Vec<&str> = upper.split_ascii_whitespace().collect();
746  let last = words.last().copied();
747  if !matches!(last, Some("WITH") | Some("NO") | Some("CASCADED") | Some("LOCAL")) {
748    return None;
749  }
750  let mut out = Vec::new();
751  push_keyword_kvs(&mut out, kws);
752  Some(out)
753}
754
755/// WINDOW frame-bound sub-chain only -- the fresh-slot and
756/// PARTITION/ORDER BY column-list paths must keep flowing to the
757/// catalog so existing tests stay green, so this only fires when the
758/// last token before the cursor is a frame-family keyword.
759fn detect_window_clause_frame_bound(
760  source: &str,
761  offset: TextSize,
762  _file: &ParsedFile,
763  _scopes: &[Scope],
764  _cat: &Catalog,
765) -> Option<Vec<Item>> {
766  if window_clause_partition_or_order_by_expects_column(source, offset) {
767    return None;
768  }
769  let kws = window_clause_as_paren_keyword(source, offset)?;
770  let pos: usize = (u32::from(offset) as usize).min(source.len());
771  let pre = &source[..pos];
772  let stmt_start_idx = pre.rfind(';').map(|i| i + 1).unwrap_or(0);
773  let words: Vec<&str> = pre[stmt_start_idx..].split_ascii_whitespace().collect();
774  let last_up = words.last().map(|s| s.to_ascii_uppercase()).unwrap_or_default();
775  if !matches!(
776    last_up.as_str(),
777    "RANGE" | "ROWS" | "GROUPS" | "BETWEEN" | "AND" | "PRECEDING" | "FOLLOWING" | "UNBOUNDED" | "CURRENT" | "EXCLUDE"
778  ) {
779    return None;
780  }
781  let mut out = Vec::new();
782  push_keyword_kvs(&mut out, kws);
783  Some(out)
784}
785
786/// Every post-phase shortcut, in the exact precedence order they used
787/// to run as a chain of `if`/`if let` statements at the top of
788/// `route_phase` -- this array is now the only place that order
789/// lives. `route_phase` runs them in sequence; the first `Some` wins.
790///
791/// Dropped rather than migrated: a `grouping_sets_inner_paren_expects_
792/// column` check used to sit here too, but it's dead code -- `complete_
793/// with_derived` already checks the identical `(source, offset)` pair
794/// earlier and returns unconditionally when true (see the dot-context
795/// block above), and `source`/`offset` are unmodified between that
796/// check and every call into `route_phase`, so the condition is
797/// guaranteed false by the time any of these detectors run.
798const POST_PHASE_DETECTORS: &[Detector] = &[
799  detect_set_op_followup,
800  detect_json_table_fresh_column_slot,
801  detect_json_table_column_slot,
802  detect_create_transform,
803  detect_tablesample_after_paren,
804  detect_filter_clause,
805  detect_policy_expr,
806  detect_table_function_with_ordinality,
807  detect_select_fetch_offset,
808  detect_create_view_post_name,
809  detect_window_clause_frame_bound,
810];
811
812fn route_phase(
813  ph: Phase,
814  file: &ParsedFile,
815  scopes: &[Scope],
816  source: &str,
817  cat: &Catalog,
818  offset: TextSize,
819) -> Vec<Item> {
820  for detector in POST_PHASE_DETECTORS {
821    if let Some(items) = detector(source, offset, file, scopes, cat) {
822      return items;
823    }
824  }
825  let mut out = Vec::new();
826  match ph {
827    Phase::Start => {
828      // `CREATE VIEW v AS <cursor>` -- the body must start with
829      // SELECT / WITH / VALUES / TABLE. The phase machine's anchor
830      // routes us here, but the full statement-start menu (47 items)
831      // includes DDL like CREATE TABLE / DROP / INSERT which PG won't
832      // accept here. Narrow.
833      if at_create_view_body_start(source, offset) {
834        for (kw, doc) in [
835          ("SELECT", "the projection-list query that defines the view"),
836          ("WITH", "CTE list then SELECT"),
837          ("VALUES", "VALUES (...) literal-row source"),
838          ("TABLE", "TABLE <name> -- shorthand for SELECT * FROM <name>"),
839        ] {
840          out.push(crate::item::Item {
841            label: kw.into(),
842            kind: crate::item::ItemKind::Keyword,
843            detail: Some(doc.into()),
844            insert_text: kw.into(),
845            kb_entry: None,
846            sort_priority: 0,
847            ..Default::default()
848          });
849        }
850      } else {
851        sources::statement_keywords(&mut out);
852      }
853    },
854
855    Phase::SelectProjection | Phase::InProjection | Phase::NextProjection => {
856      push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
857      push_aliases(file, scopes, source, offset, &mut out);
858      push_all_functions(cat, &mut out);
859      sources::expression_keywords(&mut out);
860    },
861
862    Phase::AfterStar | Phase::ProjectionAlias => {
863      // CAST(<expr> AS <type>) is parsed as a projection-AS slot, but
864      // the legal next token is a type, not the FROM/INTO menu. Detect
865      // by walking back: the most recent unmatched `(` is preceded by
866      // `CAST`.
867      if cast_as_expects_type(source, offset) {
868        sources::types_only(&mut out);
869      } else {
870        // Just typed `*` or `AS alias`. Next legal tokens: FROM
871        // (continue the query) or `,` (more projection). Emit only
872        // the small after-projection keyword set.
873        sources::after_projection_keywords(&mut out);
874      }
875    },
876
877    Phase::ExpectTable => {
878      sources::tables(cat, &mut out);
879      push_cte_names(file, scopes, source, offset, &mut out);
880    },
881
882    Phase::AfterTable | Phase::JoinModifier | Phase::JoinComplete => {
883      // `WINDOW w AS (PARTITION BY <cursor>` or `(ORDER BY <cursor>`
884      // -- inside a window-clause body, expects column references
885      // from the FROM tables, not JOIN keywords.
886      if window_clause_partition_or_order_by_expects_column(source, offset) {
887        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
888        push_aliases(file, scopes, source, offset, &mut out);
889        return dedup_items(out);
890      }
891      // `WINDOW w AS (<cursor>` -- start of a window-clause body.
892      // First sub-clause is PARTITION BY / ORDER BY / ROWS / RANGE /
893      // GROUPS.
894      if window_clause_paren_expects_subclause(source, offset) {
895        for (kw, doc) in [
896          ("PARTITION BY", "PARTITION BY <expr>[, ...] -- frame partitioning"),
897          ("ORDER BY", "ORDER BY <expr>[, ...] -- frame ordering"),
898          ("ROWS", "ROWS BETWEEN ... -- row-relative frame"),
899          ("RANGE", "RANGE BETWEEN ... -- value-relative frame"),
900          ("GROUPS", "GROUPS BETWEEN ... -- peer-group frame"),
901        ] {
902          out.push(crate::item::Item {
903            label: kw.into(),
904            kind: crate::item::ItemKind::Keyword,
905            detail: Some(doc.into()),
906            description: None,
907            documentation_md: None,
908            insert_text: kw.into(),
909            is_snippet: false,
910            kb_entry: None,
911            sort_priority: 0,
912          });
913        }
914        return dedup_items(out);
915      }
916      // `... LATERAL <cursor>` (after JOIN or FROM,) -- the only legal
917      // followers are a set-returning function call or a parenthesized
918      // subquery. The generic AfterTable handler would offer JOIN
919      // keywords, WHERE, and the table list -- all wrong here.
920      if lateral_target_expected(source, offset) {
921        for (label, doc) in LATERAL_TARGETS {
922          out.push(crate::item::Item {
923            label: (*label).into(),
924            kind: crate::item::ItemKind::Function,
925            detail: Some((*doc).into()),
926            description: None,
927            documentation_md: None,
928            insert_text: (*label).into(),
929            is_snippet: false,
930            kb_entry: None,
931            sort_priority: 0,
932          });
933        }
934        // Catalog tables are also legal: `LATERAL <table>` is the
935        // sub-SELECT shortcut form. Surface them so the user can pick
936        // a relation as the LATERAL source without a parenthesized
937        // SELECT wrapper.
938        sources::tables(cat, &mut out);
939        return dedup_items(out);
940      }
941      // `SELECT ... <table> TABLESAMPLE <cursor>` -- sampling method
942      // slot (BERNOULLI / SYSTEM). The generic AfterTable handler
943      // would wrongly offer JOIN keywords.
944      if tablesample_expects_method(source, offset) {
945        push_keyword_kvs(
946          &mut out,
947          &[
948            ("BERNOULLI", "TABLESAMPLE BERNOULLI (<percent>) -- row-level uniform sample"),
949            ("SYSTEM", "TABLESAMPLE SYSTEM (<percent>) -- page-level random sample"),
950          ],
951        );
952        return dedup_items(out);
953      }
954      // `SELECT ... FOR <cursor>` / `... FOR UPDATE|SHARE <cursor>`
955      // -- locking clause. Narrow to those keywords instead of the
956      // generic JOIN/WHERE/GROUP follow-up dump.
957      if let Some(kws) = select_for_locking_keywords(source, offset) {
958        for (kw, doc) in kws {
959          out.push(crate::item::Item {
960            label: (*kw).into(),
961            kind: crate::item::ItemKind::Keyword,
962            detail: Some((*doc).into()),
963            description: None,
964            documentation_md: None,
965            insert_text: (*kw).into(),
966            is_snippet: false,
967            kb_entry: None,
968            sort_priority: 0,
969          });
970        }
971      } else {
972        push_aliases(file, scopes, source, offset, &mut out);
973        sources::after_table_keywords(&mut out);
974      }
975    },
976
977    Phase::OnClause | Phase::WhereClause | Phase::InPredicate | Phase::HavingClause => {
978      // `<col> IS <cursor>` and `<col> IS NOT <cursor>` are tightly-
979      // scoped slots whose only legal next tokens are NULL / TRUE /
980      // FALSE / UNKNOWN / DISTINCT FROM (NOT NULL only after `IS`).
981      // Surface just those keywords instead of the full expression
982      // menu (350+ functions).
983      if let Some(kws) = is_predicate_continuation_keywords(source, offset) {
984        for (kw, doc) in kws {
985          out.push(crate::item::Item {
986            label: (*kw).into(),
987            kind: crate::item::ItemKind::Keyword,
988            detail: Some((*doc).into()),
989            description: None,
990            documentation_md: None,
991            insert_text: (*kw).into(),
992            is_snippet: false,
993            kb_entry: None,
994            sort_priority: 0,
995          });
996        }
997      } else {
998        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
999        push_aliases(file, scopes, source, offset, &mut out);
1000        push_all_functions(cat, &mut out);
1001        sources::expression_keywords(&mut out);
1002      }
1003    },
1004
1005    Phase::UsingClause => {
1006      push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1007      push_aliases(file, scopes, source, offset, &mut out);
1008    },
1009
1010    Phase::AfterGroup | Phase::AfterOrder => {
1011      // Just typed GROUP / ORDER, next is "BY".
1012      sources::after_table_keywords(&mut out);
1013    },
1014    Phase::GroupByList => {
1015      // PG-specific set-grouping prefixes -- offer alongside columns
1016      // so `GROUP BY <cursor>` surfaces GROUPING SETS / CUBE / ROLLUP.
1017      if let Some(kws) = group_by_set_op_next_keyword(source, offset) {
1018        push_keyword_kvs(&mut out, kws);
1019      }
1020      push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1021      push_aliases(file, scopes, source, offset, &mut out);
1022      push_all_functions(cat, &mut out);
1023    },
1024    Phase::OrderByList => {
1025      // `... ORDER BY <col> NULLS <cursor>` -- after NULLS the only
1026      // legal continuation is FIRST | LAST. Suppress the full column
1027      // + function dump for this tightly-scoped slot.
1028      if order_by_nulls_expects_first_last(source, offset) {
1029        push_keyword_kvs(
1030          &mut out,
1031          &[
1032            ("FIRST", "NULLS FIRST -- NULLs sort before non-NULL values"),
1033            ("LAST", "NULLS LAST -- NULLs sort after non-NULL values"),
1034          ],
1035        );
1036      } else {
1037        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1038        push_aliases(file, scopes, source, offset, &mut out);
1039        push_all_functions(cat, &mut out);
1040        sources::order_modifiers(&mut out);
1041      }
1042    },
1043
1044    Phase::LimitClause => {
1045      // LIMIT takes an integer literal. The only useful follow-up
1046      // keyword is OFFSET. Emitting after_table_keywords (which
1047      // contains the JOIN family + WHERE / GROUP / ORDER) is wrong
1048      // here -- those don't follow LIMIT.
1049      out.push(crate::item::Item {
1050        label: "OFFSET".into(),
1051        kind: crate::item::ItemKind::Keyword,
1052        detail: Some("OFFSET <n> -- skip the first n rows".into()),
1053        description: None,
1054        documentation_md: None,
1055        insert_text: "OFFSET".into(),
1056        is_snippet: false,
1057        kb_entry: None,
1058        sort_priority: 0,
1059      });
1060    },
1061    Phase::OffsetClause => {
1062      // OFFSET takes an integer literal. Nothing meaningful follows
1063      // until the user types a comma / semicolon. Emit nothing.
1064    },
1065
1066    Phase::AfterInsert => {
1067      sources::after_projection_keywords(&mut out);
1068    },
1069    Phase::AfterInsertTable => {
1070      sources::tables(cat, &mut out);
1071    },
1072    Phase::InsertColumnList => {
1073      // OVERRIDING SYSTEM/USER mid-clause -- emit the dedicated VALUE
1074      // / SYSTEM VALUE / USER VALUE followup menu.
1075      if let Some(kws) = insert_overriding_next_keyword(source, offset) {
1076        push_keyword_kvs(&mut out, kws);
1077        return out;
1078      }
1079      // Closed paren list -> body-shape menu (VALUES/SELECT/...).
1080      // Phase machine stays InsertColumnList until VALUES/SELECT token
1081      // arrives, but the user is past the column list at `)` and wants
1082      // the next-keyword menu, not another column suggestion.
1083      if let Some(kws) = insert_into_next_keyword(source, offset) {
1084        push_keyword_kvs(&mut out, kws);
1085        return out;
1086      }
1087      // Strict: only columns of the INSERT target table. Falling back
1088      // to the global column dump showed every catalog table's columns
1089      // (huge menu) which is never what the user wants in a paren list
1090      // that PG strictly validates against the target.
1091      if let Some(target) = insert_target_table(source, offset) {
1092        sources::columns_of_table(cat, None, &target, &mut out);
1093        // Filter out columns the user already typed in this paren list.
1094        let used = used_columns_in_clause(source, offset);
1095        if !used.is_empty() {
1096          out.retain(|it| !is_column_listed(it, &used));
1097        }
1098      } else {
1099        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1100        push_aliases(file, scopes, source, offset, &mut out);
1101      }
1102    },
1103    Phase::InsertExpectValues | Phase::InsertValuesList => {
1104      // ON CONFLICT (...) and ON CONFLICT DO UPDATE SET ... are
1105      // column-LHS slots scoped to the INSERT target table -- not a
1106      // free expression context like VALUES (...). Narrow to columns
1107      // of the target so the menu isn't 300+ functions.
1108      if let Some(kws) = on_conflict_next_keyword(source, offset) {
1109        push_keyword_kvs(&mut out, kws);
1110      } else if on_conflict_expects_target_column(source, offset) {
1111        if let Some(target) = dml_target_table(source, offset) {
1112          sources::columns_of_table(cat, None, &target, &mut out);
1113          let used = used_columns_in_clause(source, offset);
1114          if !used.is_empty() {
1115            out.retain(|it| !is_column_listed(it, &used));
1116          }
1117        }
1118      } else if insert_after_values_tuple(source, offset) {
1119        // After a closed `VALUES (...)` tuple at depth 0, the legal
1120        // continuations are `,` (another tuple), `RETURNING`,
1121        // `ON CONFLICT`, or `;`. Narrow the menu instead of dumping
1122        // 351 functions.
1123        for (kw, doc) in [
1124          ("RETURNING", "RETURNING <cols> -- return inserted rows"),
1125          ("ON CONFLICT", "ON CONFLICT (cols) DO ... -- upsert handling"),
1126        ] {
1127          out.push(crate::item::Item {
1128            label: kw.into(),
1129            kind: crate::item::ItemKind::Keyword,
1130            detail: Some(doc.into()),
1131            insert_text: kw.into(),
1132            kb_entry: None,
1133            sort_priority: 0,
1134            ..Default::default()
1135          });
1136        }
1137      } else {
1138        // DEFAULT is the most-useful VALUES-list token: it tells PG
1139        // "use the column default" and is far more relevant than any
1140        // catalog function here. Promote it to the top of the menu.
1141        out.push(
1142          crate::item::Item {
1143            label: "DEFAULT".into(),
1144            kind: crate::item::ItemKind::Keyword,
1145            detail: Some("use this column's DEFAULT value".into()),
1146            insert_text: "DEFAULT".into(),
1147            ..Default::default()
1148          }
1149          .with_sort(0),
1150        );
1151        push_aliases(file, scopes, source, offset, &mut out);
1152        push_all_functions(cat, &mut out);
1153        sources::expression_keywords(&mut out);
1154      }
1155    },
1156
1157    Phase::AfterUpdate => {
1158      sources::tables(cat, &mut out);
1159    },
1160    Phase::AfterUpdateTable => {
1161      push_aliases(file, scopes, source, offset, &mut out);
1162      sources::after_table_keywords(&mut out);
1163    },
1164    Phase::UpdateAssignment => {
1165      // Two slots collapsed into one phase: the column LHS (before any
1166      // `=` since the last comma or SET) and the value expression RHS.
1167      // The LHS slot is narrow -- only the target table's columns,
1168      // minus any already named earlier in the SET list.
1169      if update_set_at_column_slot(source, offset) {
1170        if let Some(target) = dml_target_table(source, offset) {
1171          sources::columns_of_table(cat, None, &target, &mut out);
1172        } else {
1173          push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1174        }
1175        let used = used_columns_in_clause(source, offset);
1176        if !used.is_empty() {
1177          out.retain(|it| !used.contains(&it.label.to_ascii_lowercase()));
1178        }
1179      } else {
1180        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1181        push_aliases(file, scopes, source, offset, &mut out);
1182        push_all_functions(cat, &mut out);
1183        sources::expression_keywords(&mut out);
1184      }
1185    },
1186
1187    Phase::AfterDelete => {
1188      sources::after_projection_keywords(&mut out);
1189    },
1190
1191    Phase::ReturningClause => {
1192      // `RETURNING <expr> AS <cursor>` -- alias-name slot. The next
1193      // token is a free-form identifier the user types. Don't dump
1194      // the catalog (was 1100+ items pre-fix); leave the menu empty
1195      // so the user just types the name.
1196      let (_, ret_upper) = stmt_slice_upper(source, offset);
1197      let ret_words: Vec<&str> = ret_upper.split_ascii_whitespace().collect();
1198      let last_returning_word = ret_words.last().copied();
1199      if last_returning_word == Some("AS") {
1200        return out;
1201      }
1202      // INSERT / UPDATE / DELETE ... RETURNING <cursor> -- expression
1203      // context (PG accepts any expression here, not just plain
1204      // column refs). Emit target-table columns first (highest sort
1205      // priority), then the full function library + expression
1206      // keywords so things like `left(id::text, 10)`, `count(*)`,
1207      // `now()`, `coalesce(...)`, etc. complete cleanly.
1208      if let Some(target) = dml_target_table(source, offset) {
1209        sources::columns_of_table(cat, None, &target, &mut out);
1210      } else {
1211        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1212      }
1213      push_aliases(file, scopes, source, offset, &mut out);
1214      push_all_functions(cat, &mut out);
1215      sources::expression_keywords(&mut out);
1216      let used = used_columns_in_clause(source, offset);
1217      if !used.is_empty() {
1218        out.retain(|it| !is_column_listed(it, &used));
1219      }
1220    },
1221
1222    // CREATE TABLE sub-phases ---------------------------------------
1223    Phase::CtlExpectTableName => {
1224      // Fresh name slot. The only sensible keyword suggestion here is
1225      // the optional IF NOT EXISTS qualifier the user may want to add
1226      // before typing the actual table name.
1227      out.push(crate::item::Item {
1228        label: "IF NOT EXISTS".into(),
1229        kind: crate::item::ItemKind::Keyword,
1230        detail: Some("CREATE TABLE IF NOT EXISTS <name> -- skip silently if already present".into()),
1231        insert_text: "IF NOT EXISTS".into(),
1232        kb_entry: None,
1233        sort_priority: 0,
1234        ..Default::default()
1235      });
1236    },
1237    Phase::CtlBodyStart => {
1238      // EXCLUDE constraint sub-chain wins over the generic body menu
1239      // when the user has typed EXCLUDE / EXCLUDE USING.
1240      if let Some(kws) = exclude_constraint_next_keyword(source, offset) {
1241        push_keyword_kvs(&mut out, kws);
1242      } else {
1243        // User could be starting a column declaration (no completion
1244        // for the name itself) or a table-level constraint line. Also
1245        // surface types so once they have a name typed and hit space,
1246        // the next keystroke (a type letter) keeps the dropdown open
1247        // -- the LSP client filters by prefix, so the type-name slot
1248        // shows only the matching types and the constraint-starters.
1249        sources::create_table_entry_starters(&mut out);
1250        sources::types_only(&mut out);
1251      }
1252    },
1253    Phase::CtlExpectType => {
1254      // EXCLUDE / EXCLUDE USING -- specialised constraint chain wins.
1255      if let Some(kws) = exclude_constraint_next_keyword(source, offset) {
1256        push_keyword_kvs(&mut out, kws);
1257      } else {
1258        sources::types_only(&mut out);
1259      }
1260    },
1261    Phase::CtlExpectColumnConstraint => {
1262      // `... AS IDENTITY ( <cursor>` -- sequence option-name slot.
1263      if let Some(kws) = identity_paren_next_keyword(source, offset) {
1264        push_keyword_kvs(&mut out, kws);
1265      // `... GENERATED <cursor>` / `... GENERATED ALWAYS AS <cursor>` /
1266      // `... AS (expr) <cursor>` -- specialised GENERATED chain.
1267      } else if let Some(kws) = column_generated_next_keyword(source, offset) {
1268        push_keyword_kvs(&mut out, kws);
1269      // `... DEFERRABLE <cursor>` / `... INITIALLY <cursor>` -- tail of
1270      // an inline constraint (PRIMARY KEY/UNIQUE/REFERENCES/FK ON ...).
1271      // Without this branch the generic column-constraint menu fires
1272      // and drowns the user in NOT NULL/CHECK/etc.
1273      } else if let Some(kws) = column_constraint_next_keyword(source, offset) {
1274        push_keyword_kvs(&mut out, kws);
1275      } else if ctl_column_constraint_after_default(source, offset) {
1276        for (kw, doc) in DEFAULT_EXPRESSION_SUGGESTIONS {
1277          out.push(crate::item::Item {
1278            label: (*kw).into(),
1279            kind: crate::item::ItemKind::Keyword,
1280            detail: Some((*doc).into()),
1281            insert_text: (*kw).into(),
1282            kb_entry: None,
1283            sort_priority: 0,
1284            ..Default::default()
1285          });
1286        }
1287        // Surface the full function library + expression keywords so a
1288        // user typing `DEFAULT length(...)` / `DEFAULT now() + INTERVAL ...`
1289        // gets matching completions instead of just the short menu.
1290        push_all_functions(cat, &mut out);
1291        sources::expression_keywords(&mut out);
1292      } else {
1293        sources::column_constraint_keywords(&mut out);
1294        // Constraint keywords like DEFAULT / CHECK introduce
1295        // expression contexts. Surface functions + expression
1296        // keywords here too so `col text DEFAULT now()` /
1297        // `col text CHECK (length(col) > 0)` autocompletes the
1298        // function names without forcing a new phase.
1299        push_all_functions(cat, &mut out);
1300        sources::expression_keywords(&mut out);
1301      }
1302    },
1303    Phase::CtlExpectConstraintName => {
1304      // Fresh constraint name; nothing useful.
1305    },
1306    Phase::CtlExpectConstraintKind => {
1307      sources::constraint_kinds(&mut out);
1308    },
1309    Phase::CtlExpectFkTable {} => {
1310      sources::tables(cat, &mut out);
1311    },
1312    Phase::CtlCheckExpr { ref table } => {
1313      if let Some(t) = table.as_ref() {
1314        sources::columns_of_table(cat, None, t, &mut out);
1315        if out.is_empty() {
1316          for name in crate::source_tables::buffer_column_names(source, t) {
1317            out.push(crate::item::Item {
1318              label: name.clone(),
1319              kind: crate::item::ItemKind::Column,
1320              detail: Some(format!("column of `{t}` (buffer)")),
1321              description: None,
1322              documentation_md: None,
1323              insert_text: name,
1324              is_snippet: false,
1325              kb_entry: None,
1326              sort_priority: 0,
1327            });
1328          }
1329        }
1330      }
1331      push_all_functions(cat, &mut out);
1332      sources::expression_keywords(&mut out);
1333    },
1334    Phase::CtlExpectFkColumn { ref table } => {
1335      sources::columns_of_table(cat, None, table, &mut out);
1336      // Fallback: the table being created may not have parsed
1337      // cleanly yet (cursor inside an unclosed body). Scan the
1338      // buffer for `CREATE TABLE <table>` and harvest column names
1339      // directly.
1340      if out.is_empty() {
1341        for name in crate::source_tables::buffer_column_names(source, table) {
1342          out.push(crate::item::Item {
1343            label: name.clone(),
1344            kind: crate::item::ItemKind::Column,
1345            detail: Some(format!("{}.<column>", table)),
1346            description: Some("buffer".into()),
1347            documentation_md: None,
1348            insert_text: name,
1349            is_snippet: false,
1350            kb_entry: None,
1351            sort_priority: 5,
1352          });
1353        }
1354      }
1355    },
1356
1357    // PL/pgSQL body --------------------------------------------------
1358    Phase::PlpgsqlBody => {
1359      if let Some(items) = plpgsql_body_targeted_items(source, offset, file, scopes, cat) {
1360        out = items;
1361      } else {
1362        // Function parameters and DECLARE'd locals first so they
1363        // sort above the broader keyword / function lists.
1364        let locals = crate::plpgsql_locals::extract(source, u32::from(offset) as usize);
1365        crate::plpgsql_locals::push_items(&locals, &mut out);
1366        // PL/pgSQL flow keywords + standard built-ins + NEW / OLD
1367        // identifiers + any FROM/JOIN aliases inside the body.
1368        sources::plpgsql_keywords(&mut out);
1369        push_aliases(file, scopes, source, offset, &mut out);
1370        push_all_functions(cat, &mut out);
1371        sources::new_old_aliases(&mut out);
1372        sources::tables(cat, &mut out);
1373        sources::columns(cat, &mut out);
1374      }
1375    },
1376    // Right-hand side of an assignment -- expression only. Skip the
1377    // statement-starter keywords (SELECT / CREATE / DELETE / ...).
1378    // Skip the all-tables column dump too -- the user reaches for
1379    // NEW.col / OLD.col / a parameter, not a random column from
1380    // some unrelated table.
1381    Phase::PlpgsqlAssignRhs => {
1382      let locals = crate::plpgsql_locals::extract(source, u32::from(offset) as usize);
1383      crate::plpgsql_locals::push_items(&locals, &mut out);
1384      sources::new_old_aliases(&mut out);
1385      push_aliases(file, scopes, source, offset, &mut out);
1386      push_all_functions(cat, &mut out);
1387      sources::expression_keywords(&mut out);
1388    },
1389
1390    // After PG `::` cast operator -- emit types only. Built-ins
1391    // first, then user-defined enums/domains/composites from the
1392    // live catalog.
1393    Phase::CastType => {
1394      sources::types(&mut out);
1395      sources::db_types(cat, &mut out);
1396    },
1397
1398    Phase::AfterAlterTableExpectName => {
1399      sources::tables(cat, &mut out);
1400    },
1401    Phase::AfterAlterTableName => {
1402      // ALTER TABLE <t> DROP/RENAME/ALTER COLUMN <cursor> -- the user
1403      // is picking an EXISTING column of the target table, not an
1404      // action keyword. Detect that slot from the recent tokens and
1405      // surface columns instead of the action menu.
1406      if let Some(target) = alter_table_existing_column_target(source, offset) {
1407        sources::columns_of_table(cat, None, &target, &mut out);
1408      } else if alter_table_expects_type(source, offset) {
1409        // ALTER TABLE <t> ADD COLUMN <name> <cursor> -- after the fresh
1410        // column name, the next token is a type. Same shape as
1411        // CtlExpectType inside a CREATE TABLE body.
1412        sources::types_only(&mut out);
1413      } else if let Some(kws) = alter_column_set_value_keywords(source, offset) {
1414        push_keyword_kvs(&mut out, kws);
1415      } else if alter_column_after_set_subkeyword_expects_silence(source, offset) {
1416        // `ALTER COLUMN <name> SET DEFAULT|STATISTICS <cursor>` --
1417        // these slots take freeform expressions / integers that have
1418        // no useful catalog completion. SET STORAGE / SET COMPRESSION
1419        // are handled above (curated value menu).
1420      } else if let Some(kind) = alter_column_action_kind(source, offset) {
1421        // `ALTER COLUMN <name> SET <cursor>` / `... DROP <cursor>` --
1422        // the slot is a SET/DROP sub-keyword, not the top-level
1423        // ALTER TABLE action menu.
1424        let kws: &[(&str, &str)] = match kind {
1425          AlterColumnAction::Set => &[
1426            ("DEFAULT", "SET DEFAULT <expr>"),
1427            ("NOT NULL", "SET NOT NULL"),
1428            ("DATA TYPE", "SET DATA TYPE <type>"),
1429            ("STATISTICS", "SET STATISTICS <int>"),
1430            ("STORAGE", "SET STORAGE PLAIN|EXTERNAL|EXTENDED|MAIN"),
1431            ("COMPRESSION", "SET COMPRESSION pglz|lz4|default"),
1432          ],
1433          AlterColumnAction::Drop => &[
1434            ("DEFAULT", "DROP DEFAULT"),
1435            ("NOT NULL", "DROP NOT NULL"),
1436            ("IDENTITY", "DROP IDENTITY"),
1437            ("EXPRESSION", "DROP EXPRESSION"),
1438          ],
1439        };
1440        for (kw, doc) in kws {
1441          out.push(crate::item::Item {
1442            label: (*kw).into(),
1443            kind: crate::item::ItemKind::Keyword,
1444            detail: Some((*doc).into()),
1445            description: None,
1446            documentation_md: None,
1447            insert_text: (*kw).into(),
1448            is_snippet: false,
1449            kb_entry: None,
1450            sort_priority: 0,
1451          });
1452        }
1453      } else if let Some(kws) = column_constraint_next_keyword(source, offset) {
1454        // `ALTER TABLE ... REFERENCES other(col) ON DELETE <cursor>` /
1455        // `... DEFERRABLE <cursor>` etc -- FK action / deferrable slot.
1456        push_keyword_kvs(&mut out, kws);
1457      } else if let Some(kws) = column_generated_next_keyword(source, offset) {
1458        push_keyword_kvs(&mut out, kws);
1459      } else if let Some(kws) = check_constraint_no_inherit_next_keyword(source, offset) {
1460        push_keyword_kvs(&mut out, kws);
1461      } else if let Some(kws) = replica_identity_next_keyword(source, offset) {
1462        push_keyword_kvs(&mut out, kws);
1463      } else if alter_table_add_column_after_default(source, offset) {
1464        // `ALTER TABLE t ADD COLUMN c <type> DEFAULT <cursor>` --
1465        // expression slot. The action menu would suggest ADD COLUMN /
1466        // DROP COLUMN here which makes no sense. Emit a curated set of
1467        // common default expressions.
1468        for (kw, doc) in DEFAULT_EXPRESSION_SUGGESTIONS {
1469          out.push(crate::item::Item {
1470            label: (*kw).into(),
1471            kind: crate::item::ItemKind::Keyword,
1472            detail: Some((*doc).into()),
1473            insert_text: (*kw).into(),
1474            kb_entry: None,
1475            sort_priority: 0,
1476            ..Default::default()
1477          });
1478        }
1479      } else if alter_table_inherit_expects_parent(source, offset) {
1480        // `ALTER TABLE t INHERIT <cursor>` / `... NO INHERIT <cursor>`
1481        // -- the next token is a parent table name from the catalog.
1482        sources::tables(cat, &mut out);
1483      } else if let Some(kws) = alter_table_subaction_at(source, offset) {
1484        // `ALTER TABLE <t> ADD <cursor>` / `... DROP <cursor>` etc --
1485        // the user has already picked the top-level action; narrow
1486        // to the sub-keywords (COLUMN / CONSTRAINT / etc) instead
1487        // of re-listing the entire 18-item action menu.
1488        push_keyword_kvs(&mut out, kws);
1489      } else {
1490        sources::alter_table_actions(&mut out);
1491      }
1492    },
1493
1494    Phase::AfterGrantOrRevoke => {
1495      // GRANT/REVOKE follow-up chain (WITH / GRANTED BY / ON menus)
1496      // takes priority over the privilege list when those slot tokens
1497      // are present.
1498      if let Some(kws) = grant_revoke_followup_next_keyword(source, offset) {
1499        push_keyword_kvs(&mut out, kws);
1500      } else {
1501        sources::grant_privileges(&mut out);
1502        // Also surface ON so the chain can continue after the priv list.
1503        out.push(crate::item::Item {
1504          label: "ON".into(),
1505          kind: crate::item::ItemKind::Keyword,
1506          detail: Some("ON <object_class> <name>".into()),
1507          insert_text: "ON".into(),
1508          kb_entry: None,
1509          sort_priority: 0,
1510          ..Default::default()
1511        });
1512        // `REVOKE [GRANT OPTION FOR] <priv>` -- the GRANT OPTION FOR
1513        // modifier only legal on REVOKE. Surface it at the bare-REVOKE
1514        // slot so users discover it without typing.
1515        let (_, upper) = stmt_slice_upper(source, offset);
1516        if upper.trim_start().starts_with("REVOKE") {
1517          out.push(crate::item::Item {
1518            label: "GRANT OPTION FOR".into(),
1519            kind: crate::item::ItemKind::Keyword,
1520            detail: Some("REVOKE GRANT OPTION FOR <priv> -- drop forwarding right, keep the priv".into()),
1521            insert_text: "GRANT OPTION FOR".into(),
1522            kb_entry: None,
1523            sort_priority: 0,
1524            ..Default::default()
1525          });
1526        }
1527      }
1528    },
1529    Phase::AfterGrantOn => {
1530      // Object class keywords (TABLE/SEQUENCE/FUNCTION/SCHEMA/...)
1531      // plus the actual catalog targets so the user can either pick
1532      // the explicit class keyword or jump straight to a name.
1533      sources::grant_object_classes(&mut out);
1534      sources::tables(cat, &mut out);
1535    },
1536    Phase::AfterGrantTo => {
1537      // SET ROLE / SET SESSION AUTHORIZATION sneak past the phase
1538      // detector because they're parsed similarly; emit the dedicated
1539      // keyword chain (NONE / DEFAULT / etc) before the role list.
1540      if let Some(kws) = set_role_auth_next_keyword(source, offset) {
1541        push_keyword_kvs(&mut out, kws);
1542      }
1543      sources::grant_roles(cat, &mut out);
1544      // Trailing clauses legal at the end of a GRANT / REVOKE -- emit
1545      // them so users can quickly add `WITH GRANT OPTION` etc.
1546      for (kw, doc) in [
1547        ("WITH GRANT OPTION", "GRANT ... WITH GRANT OPTION -- grantee can re-grant"),
1548        ("WITH ADMIN OPTION", "GRANT <role> ... WITH ADMIN OPTION -- grantee can add other members"),
1549        ("GRANTED BY", "GRANT ... GRANTED BY <role> -- record the grantor explicitly"),
1550        ("CASCADE", "REVOKE ... CASCADE -- also revoke dependent grants"),
1551        ("RESTRICT", "REVOKE ... RESTRICT -- fail if dependent grants exist (default)"),
1552      ] {
1553        out.push(crate::item::Item {
1554          label: kw.into(),
1555          kind: crate::item::ItemKind::Keyword,
1556          detail: Some(doc.into()),
1557          insert_text: kw.into(),
1558          kb_entry: None,
1559          sort_priority: 1,
1560          ..Default::default()
1561        });
1562      }
1563    },
1564
1565    Phase::AfterCreate | Phase::AfterAlter | Phase::AfterDrop | Phase::Unknown => {
1566      // `DROP TABLE [IF EXISTS]` / `DROP VIEW [IF EXISTS]` /
1567      // `TRUNCATE [TABLE]` all expect a table-class name. Skip the
1568      // generic catch-all dump and emit only matching catalog targets.
1569      if let Some(kws) = copy_paren_options_keyword(source, offset) {
1570        // COPY ... WITH ( <cursor> ) -- option-name slot beats the generic
1571        // dml_drop_or_truncate_expects_table branch which would otherwise
1572        // emit the COPY target table list inside the option paren.
1573        push_keyword_kvs(&mut out, kws);
1574      } else if merge::merge_insert_col_list_slot(source, offset) {
1575        // MERGE ... WHEN NOT MATCHED THEN INSERT (<cursor>) -- column
1576        // list slot scoped to the MERGE target table. Surface its
1577        // columns instead of the generic table dump.
1578        let (tgt, _) = merge::merge_target_and_source(source);
1579        if let Some(t) = tgt.as_deref() {
1580          sources::columns_of_table(cat, None, t, &mut out);
1581        }
1582      } else if merge::merge_update_set_lhs_slot(source, offset) {
1583        // MERGE ... WHEN MATCHED THEN UPDATE SET <cursor> / SET c=v,
1584        // <cursor> -- LHS column slot. Must beat `dml_drop_or_truncate_
1585        // expects_table` which otherwise matches `MERGE INTO` and
1586        // dumps every catalog table (e.g. when the slice ends in a
1587        // trailing comma).
1588        let (tgt, _) = merge::merge_target_and_source(source);
1589        if let Some(t) = tgt.as_deref() {
1590          sources::columns_of_table(cat, None, t, &mut out);
1591        }
1592      } else if grouping_sets_inner_paren_expects_column(source, offset) {
1593        // GROUP BY GROUPING SETS ((<cursor>...)) -- inner tuple is a
1594        // column list, not an expression context. Phase machine sees
1595        // the double paren as a function call and would otherwise
1596        // dump the function library.
1597        push_scope_columns_or_all(file, scopes, source, cat, offset, &mut out);
1598        push_aliases(file, scopes, source, offset, &mut out);
1599      } else if vacuum_paren_expects_option(source, offset) {
1600        for (kw, doc) in [
1601          ("FULL", "FULL -- rewrite the table (locks it)"),
1602          ("FREEZE", "FREEZE -- mark tuples as committed eagerly"),
1603          ("VERBOSE", "VERBOSE -- per-relation progress"),
1604          ("ANALYZE", "ANALYZE -- update planner stats too"),
1605          ("SKIP_LOCKED", "SKIP_LOCKED -- don't wait for locks"),
1606          ("INDEX_CLEANUP", "INDEX_CLEANUP AUTO|ON|OFF"),
1607          ("PROCESS_TOAST", "PROCESS_TOAST [true|false]"),
1608          ("PROCESS_MAIN", "PROCESS_MAIN [true|false] -- PG16+"),
1609          ("TRUNCATE", "TRUNCATE [true|false] -- shrink the table file"),
1610          ("DISABLE_PAGE_SKIPPING", "DISABLE_PAGE_SKIPPING [true|false]"),
1611          ("BUFFER_USAGE_LIMIT", "BUFFER_USAGE_LIMIT '<size>' -- ring-buffer cap"),
1612          ("PARALLEL", "PARALLEL <int> -- workers for index vacuum (PG13+)"),
1613          ("SKIP_DATABASE_STATS", "SKIP_DATABASE_STATS [true|false] -- PG16+"),
1614          ("ONLY_DATABASE_STATS", "ONLY_DATABASE_STATS [true|false] -- PG16+"),
1615        ] {
1616          out.push(crate::item::Item {
1617            label: kw.into(),
1618            kind: crate::item::ItemKind::Keyword,
1619            detail: Some(doc.into()),
1620            description: None,
1621            documentation_md: None,
1622            insert_text: kw.into(),
1623            is_snippet: false,
1624            kb_entry: None,
1625            sort_priority: 0,
1626          });
1627        }
1628      } else if dml_drop_or_truncate_expects_table(source, offset) {
1629        // Surface `IF EXISTS` first when the user hasn't typed it yet,
1630        // so `DROP TABLE |` offers both the modifier and the target list.
1631        let (_, upper_drop) = stmt_slice_upper(source, offset);
1632        let words: Vec<&str> = upper_drop.split_ascii_whitespace().collect();
1633        let starts_drop = matches!(words.first().copied(), Some("DROP"));
1634        let has_if_exists = words.windows(2).any(|w| w[0] == "IF" && w[1] == "EXISTS");
1635        if starts_drop && !has_if_exists {
1636          out.push(crate::item::Item {
1637            label: "IF EXISTS".into(),
1638            kind: crate::item::ItemKind::Keyword,
1639            detail: Some("IF EXISTS -- skip silently when the target does not exist".into()),
1640            insert_text: "IF EXISTS".into(),
1641            kb_entry: None,
1642            sort_priority: 0,
1643            ..Default::default()
1644          });
1645        }
1646        sources::tables(cat, &mut out);
1647      } else if command_expects_role_name(source, offset) {
1648        // `ALTER ROLE | / DROP ROLE | / DROP USER | / REASSIGN OWNED
1649        // BY |` -- next token is an existing role from the catalog.
1650        sources::grant_roles(cat, &mut out);
1651      } else if reset_expects_subkeyword(source, offset) {
1652        // `RESET <cursor>` -> ALL | ROLE | <GUC name>. GUC names are
1653        // freeform so we only emit the two keyword candidates.
1654        for (kw, doc) in
1655          [("ALL", "RESET ALL -- reset every GUC to its default"), ("ROLE", "RESET ROLE -- undo a SET ROLE")]
1656        {
1657          out.push(crate::item::Item {
1658            label: kw.into(),
1659            kind: crate::item::ItemKind::Keyword,
1660            detail: Some(doc.into()),
1661            description: None,
1662            documentation_md: None,
1663            insert_text: kw.into(),
1664            is_snippet: false,
1665            kb_entry: None,
1666            sort_priority: 0,
1667          });
1668        }
1669      } else if raise_expects_level_keyword(source, offset) {
1670        // `RAISE <cursor>` (PL/pgSQL) -> level keyword.
1671        for (kw, doc) in [
1672          ("DEBUG", "RAISE DEBUG '...' -- developer-visible diagnostic"),
1673          ("LOG", "RAISE LOG '...' -- to server log only"),
1674          ("INFO", "RAISE INFO '...' -- to client always"),
1675          ("NOTICE", "RAISE NOTICE '...' -- default level"),
1676          ("WARNING", "RAISE WARNING '...' -- always to client"),
1677          ("EXCEPTION", "RAISE EXCEPTION '...' -- abort transaction (default if no level)"),
1678        ] {
1679          out.push(crate::item::Item {
1680            label: kw.into(),
1681            kind: crate::item::ItemKind::Keyword,
1682            detail: Some(doc.into()),
1683            description: None,
1684            documentation_md: None,
1685            insert_text: kw.into(),
1686            is_snippet: false,
1687            kb_entry: None,
1688            sort_priority: 0,
1689          });
1690        }
1691      } else if discard_expects_subkeyword(source, offset) {
1692        // `DISCARD <cursor>` -> ALL | PLANS | SEQUENCES | TEMP | TEMPORARY.
1693        for (kw, doc) in [
1694          ("ALL", "DISCARD ALL -- session reset"),
1695          ("PLANS", "DISCARD PLANS -- drop cached plans"),
1696          ("SEQUENCES", "DISCARD SEQUENCES -- forget session sequence state"),
1697          ("TEMP", "DISCARD TEMP -- drop temporary tables"),
1698          ("TEMPORARY", "DISCARD TEMPORARY -- same as DISCARD TEMP"),
1699        ] {
1700          out.push(crate::item::Item {
1701            label: kw.into(),
1702            kind: crate::item::ItemKind::Keyword,
1703            detail: Some(doc.into()),
1704            description: None,
1705            documentation_md: None,
1706            insert_text: kw.into(),
1707            is_snippet: false,
1708            kb_entry: None,
1709            sort_priority: 0,
1710          });
1711        }
1712      } else if create_index_expects_on(source, offset) {
1713        // `CREATE INDEX <name> <cursor>` -> ON.
1714        out.push(crate::item::Item {
1715          label: "ON".into(),
1716          kind: crate::item::ItemKind::Keyword,
1717          detail: Some("ON <table> (<col> [, ...])".into()),
1718          description: None,
1719          documentation_md: None,
1720          insert_text: "ON".into(),
1721          is_snippet: false,
1722          kb_entry: None,
1723          sort_priority: 0,
1724        });
1725      } else if create_policy_expects_on(source, offset) {
1726        // `CREATE POLICY <name> <cursor>` -> ON.
1727        out.push(crate::item::Item {
1728          label: "ON".into(),
1729          kind: crate::item::ItemKind::Keyword,
1730          detail: Some("ON <table> -- attach the policy to a table".into()),
1731          description: None,
1732          documentation_md: None,
1733          insert_text: "ON".into(),
1734          is_snippet: false,
1735          kb_entry: None,
1736          sort_priority: 0,
1737        });
1738      } else if create_policy_expects_table(source, offset) {
1739        // `CREATE POLICY <name> ON <cursor>` -> tables.
1740        sources::tables(cat, &mut out);
1741      } else if create_trigger_expects_timing(source, offset) {
1742        // `CREATE [OR REPLACE] TRIGGER <name> <cursor>` -- next token
1743        // is the timing keyword.
1744        for (kw, doc) in [
1745          ("BEFORE", "BEFORE <event> ON <table>"),
1746          ("AFTER", "AFTER <event> ON <table>"),
1747          ("INSTEAD OF", "INSTEAD OF <event> ON <view>"),
1748        ] {
1749          out.push(crate::item::Item {
1750            label: kw.into(),
1751            kind: crate::item::ItemKind::Keyword,
1752            detail: Some(doc.into()),
1753            description: None,
1754            documentation_md: None,
1755            insert_text: kw.into(),
1756            is_snippet: false,
1757            kb_entry: None,
1758            sort_priority: 0,
1759          });
1760        }
1761      } else if create_function_expects_return_type(source, offset) {
1762        // `CREATE [OR REPLACE] FUNCTION/PROCEDURE ... RETURNS <cursor>`
1763        // -- return type slot. Types only.
1764        sources::types_only(&mut out);
1765      } else if declare_cursor_for_expects_statement(source, offset) {
1766        // `DECLARE <name> [...] CURSOR FOR <cursor>` -- expects a
1767        // SELECT statement.
1768        sources::statement_keywords(&mut out);
1769      } else if with_cte_after_as_expects_materialized(source, offset) {
1770        // `WITH cte AS <cursor>` -> MATERIALIZED | NOT MATERIALIZED | (
1771        for (kw, doc) in [
1772          ("MATERIALIZED", "AS MATERIALIZED (...) -- always materialize the CTE"),
1773          ("NOT MATERIALIZED", "AS NOT MATERIALIZED (...) -- inline when possible"),
1774        ] {
1775          out.push(crate::item::Item {
1776            label: kw.into(),
1777            kind: crate::item::ItemKind::Keyword,
1778            detail: Some(doc.into()),
1779            description: None,
1780            documentation_md: None,
1781            insert_text: kw.into(),
1782            is_snippet: false,
1783            kb_entry: None,
1784            sort_priority: 0,
1785          });
1786        }
1787      } else if do_expects_language_or_body(source, offset) {
1788        // `DO <cursor>` -> LANGUAGE (then plpgsql) or $$ body (no
1789        // completion for the dollar-quote opener).
1790        out.push(crate::item::Item {
1791          label: "LANGUAGE".into(),
1792          kind: crate::item::ItemKind::Keyword,
1793          detail: Some("LANGUAGE plpgsql -- explicit body language (default is plpgsql)".into()),
1794          description: None,
1795          documentation_md: None,
1796          insert_text: "LANGUAGE".into(),
1797          is_snippet: false,
1798          kb_entry: None,
1799          sort_priority: 0,
1800        });
1801      } else if create_sequence_expects_option(source, offset) {
1802        // `CREATE SEQUENCE <name> <cursor>` -> sequence options.
1803        for (kw, doc) in [
1804          ("AS", "AS <type> -- smallint / integer / bigint"),
1805          ("INCREMENT", "INCREMENT [BY] <n>"),
1806          ("MINVALUE", "MINVALUE <n> | NO MINVALUE"),
1807          ("MAXVALUE", "MAXVALUE <n> | NO MAXVALUE"),
1808          ("START", "START [WITH] <n>"),
1809          ("CACHE", "CACHE <n> -- preallocate n values per session"),
1810          ("CYCLE", "CYCLE -- wrap around at MAXVALUE/MINVALUE"),
1811          ("NO CYCLE", "NO CYCLE -- error at the limit (default)"),
1812          ("OWNED BY", "OWNED BY <table>.<column> -- auto-drop with the column"),
1813        ] {
1814          out.push(crate::item::Item {
1815            label: kw.into(),
1816            kind: crate::item::ItemKind::Keyword,
1817            detail: Some(doc.into()),
1818            description: None,
1819            documentation_md: None,
1820            insert_text: kw.into(),
1821            is_snippet: false,
1822            kb_entry: None,
1823            sort_priority: 0,
1824          });
1825        }
1826      } else if create_type_enum_or_range_body(source, offset) {
1827        // `CREATE TYPE foo AS ENUM (` / `RANGE (` -- body expects
1828        // string literals or option=value pairs; nothing useful from
1829        // the catalog. Stay silent rather than dump the keyword soup.
1830      } else if create_type_as_expects_kind(source, offset) {
1831        // `CREATE TYPE <name> AS <cursor>` -> ENUM | RANGE | ( (composite).
1832        for (kw, doc) in [
1833          ("ENUM", "CREATE TYPE t AS ENUM ('a', 'b', ...) -- discrete labels"),
1834          ("RANGE", "CREATE TYPE t AS RANGE (SUBTYPE = ...) -- value-range type"),
1835        ] {
1836          out.push(crate::item::Item {
1837            label: kw.into(),
1838            kind: crate::item::ItemKind::Keyword,
1839            detail: Some(doc.into()),
1840            description: None,
1841            documentation_md: None,
1842            insert_text: kw.into(),
1843            is_snippet: false,
1844            kb_entry: None,
1845            sort_priority: 0,
1846          });
1847        }
1848      } else if explain_paren_format_value(source, offset) {
1849        for (kw, doc) in [
1850          ("TEXT", "TEXT -- default human-readable"),
1851          ("JSON", "JSON -- machine-parseable"),
1852          ("XML", "XML"),
1853          ("YAML", "YAML"),
1854        ] {
1855          out.push(crate::item::Item {
1856            label: kw.into(),
1857            kind: crate::item::ItemKind::Keyword,
1858            detail: Some(doc.into()),
1859            insert_text: kw.into(),
1860            kb_entry: None,
1861            sort_priority: 0,
1862            ..Default::default()
1863          });
1864        }
1865      } else if explain_paren_serialize_value(source, offset) {
1866        for (kw, doc) in [
1867          ("none", "none -- skip output serialization"),
1868          ("text", "text -- text-protocol serialization (default)"),
1869          ("binary", "binary -- binary-protocol serialization"),
1870        ] {
1871          out.push(crate::item::Item {
1872            label: kw.into(),
1873            kind: crate::item::ItemKind::Keyword,
1874            detail: Some(doc.into()),
1875            insert_text: kw.into(),
1876            kb_entry: None,
1877            sort_priority: 0,
1878            ..Default::default()
1879          });
1880        }
1881      } else if explain_paren_expects_option(source, offset) {
1882        // `EXPLAIN ( <cursor>` -- inside the options paren, expects
1883        // option keywords (FORMAT/ANALYZE/VERBOSE/BUFFERS/COSTS/...).
1884        for (kw, doc) in [
1885          ("ANALYZE", "ANALYZE -- actually run and time the query"),
1886          ("VERBOSE", "VERBOSE -- include extra plan detail"),
1887          ("COSTS", "COSTS [true|false] -- show estimated start/total cost"),
1888          ("BUFFERS", "BUFFERS -- include buffer-use stats (requires ANALYZE)"),
1889          ("WAL", "WAL -- include WAL stats (requires ANALYZE)"),
1890          ("TIMING", "TIMING [true|false] -- include per-node timing"),
1891          ("SUMMARY", "SUMMARY [true|false] -- include planning/exec totals"),
1892          ("SETTINGS", "SETTINGS -- include any non-default GUCs"),
1893          ("FORMAT", "FORMAT TEXT|XML|JSON|YAML -- output format"),
1894          ("GENERIC_PLAN", "GENERIC_PLAN [true|false] -- show a parameter-free plan"),
1895          ("SERIALIZE", "SERIALIZE [text|binary|none] -- include output serialization cost (PG17+, requires ANALYZE)"),
1896          ("MEMORY", "MEMORY [true|false] -- per-node peak memory used (PG17+)"),
1897        ] {
1898          out.push(crate::item::Item {
1899            label: kw.into(),
1900            kind: crate::item::ItemKind::Keyword,
1901            detail: Some(doc.into()),
1902            description: None,
1903            documentation_md: None,
1904            insert_text: kw.into(),
1905            is_snippet: false,
1906            kb_entry: None,
1907            sort_priority: 0,
1908          });
1909        }
1910      } else if explain_expects_statement(source, offset) {
1911        // `EXPLAIN [(...)] [ANALYZE [VERBOSE]] <cursor>` -- the user
1912        // is starting a statement. Surface the top-level statement
1913        // keywords (SELECT / INSERT INTO / UPDATE / DELETE FROM /
1914        // ...) plus the ANALYZE / VERBOSE / `(` modifiers that legally
1915        // sit between EXPLAIN and the statement.
1916        sources::statement_keywords(&mut out);
1917        for (kw, doc) in [
1918          ("ANALYZE", "EXPLAIN ANALYZE -- actually run, report timing"),
1919          ("VERBOSE", "EXPLAIN VERBOSE -- include extra detail"),
1920          ("(", "EXPLAIN (FORMAT JSON, ANALYZE, ...) <stmt>"),
1921        ] {
1922          out.push(crate::item::Item {
1923            label: kw.into(),
1924            kind: crate::item::ItemKind::Keyword,
1925            detail: Some(doc.into()),
1926            insert_text: kw.into(),
1927            kb_entry: None,
1928            sort_priority: 0,
1929            ..Default::default()
1930          });
1931        }
1932      } else if let Some(kw_list) = set_statement_completion(source, offset) {
1933        // `SET <cursor>` -> LOCAL/SESSION scope modifiers; `SET LOCAL
1934        // <cursor>` / `SET SESSION <cursor>` -> GUC name slot (no
1935        // catalog-derived completion). Avoid the 638-item dump.
1936        for (kw, doc) in kw_list {
1937          out.push(crate::item::Item {
1938            label: (*kw).into(),
1939            kind: crate::item::ItemKind::Keyword,
1940            detail: Some((*doc).into()),
1941            description: None,
1942            documentation_md: None,
1943            insert_text: (*kw).into(),
1944            is_snippet: false,
1945            kb_entry: None,
1946            sort_priority: 0,
1947          });
1948        }
1949      } else if let Some(kws) = txn_followup_next_keyword(source, offset) {
1950        push_keyword_kvs(&mut out, kws);
1951      } else if let Some(kw_list) = transaction_control_completion(source, offset) {
1952        // BEGIN / START TRANSACTION / COMMIT / ROLLBACK / END / ABORT
1953        // / SAVEPOINT -- emit only the keywords that make sense in
1954        // each slot. SAVEPOINT and the COMMIT-family take fresh
1955        // identifiers / no completion, so kw_list may be empty.
1956        for (kw, doc) in kw_list {
1957          out.push(crate::item::Item {
1958            label: (*kw).into(),
1959            kind: crate::item::ItemKind::Keyword,
1960            detail: Some((*doc).into()),
1961            description: None,
1962            documentation_md: None,
1963            insert_text: (*kw).into(),
1964            is_snippet: false,
1965            kb_entry: None,
1966            sort_priority: 0,
1967          });
1968        }
1969      } else if comment_on_expects_class_keyword(source, offset) {
1970        // `COMMENT ON <cursor>` -- next token is the object class
1971        // (TABLE / COLUMN / SCHEMA / FUNCTION / ROLE / ...).
1972        for (kw, doc) in COMMENT_ON_CLASSES {
1973          out.push(crate::item::Item {
1974            label: (*kw).into(),
1975            kind: crate::item::ItemKind::Keyword,
1976            detail: Some((*doc).into()),
1977            description: None,
1978            documentation_md: None,
1979            insert_text: (*kw).into(),
1980            is_snippet: false,
1981            kb_entry: None,
1982            sort_priority: 0,
1983          });
1984        }
1985      } else if let Some(kws) = set_role_auth_next_keyword(source, offset) {
1986        push_keyword_kvs(&mut out, kws);
1987      } else if let Some(kws) = show_or_set_guc_names(source, offset) {
1988        push_keyword_kvs(&mut out, kws);
1989      } else if let Some(kws) = comment_on_is_value_next_keyword(source, offset) {
1990        push_keyword_kvs(&mut out, kws);
1991      } else if let Some(kws) = security_label_next_keyword(source, offset) {
1992        push_keyword_kvs(&mut out, kws);
1993      } else if let Some(kws) = vacuum_paren_value_keyword(source, offset) {
1994        push_keyword_kvs(&mut out, kws);
1995      } else if let Some(kws) = tablesample_after_paren_next_keyword(source, offset) {
1996        push_keyword_kvs(&mut out, kws);
1997      } else if let Some(kws) = window_clause_as_paren_keyword(source, offset) {
1998        push_keyword_kvs(&mut out, kws);
1999      } else if let Some(kws) = alter_table_attach_detach_next_keyword(source, offset) {
2000        push_keyword_kvs(&mut out, kws);
2001      } else if let Some(kws) = partition_next_keyword(source, offset) {
2002        push_keyword_kvs(&mut out, kws);
2003      } else if let Some(kws) = ctas_with_data_next_keyword(source, offset) {
2004        push_keyword_kvs(&mut out, kws);
2005      } else if let Some(kws) = insert_into_next_keyword(source, offset) {
2006        push_keyword_kvs(&mut out, kws);
2007      } else if let Some(kws) = update_from_set_next_keyword(source, offset) {
2008        push_keyword_kvs(&mut out, kws);
2009      } else if let Some(kws) = delete_using_next_keyword(source, offset) {
2010        push_keyword_kvs(&mut out, kws);
2011      } else if let Some(kws) = group_by_set_op_next_keyword(source, offset) {
2012        push_keyword_kvs(&mut out, kws);
2013      } else if let Some(kws) = select_fetch_offset_next_keyword(source, offset) {
2014        push_keyword_kvs(&mut out, kws);
2015      } else if let Some(kws) = insert_overriding_next_keyword(source, offset) {
2016        push_keyword_kvs(&mut out, kws);
2017      } else if let Some(kws) = on_conflict_next_keyword(source, offset) {
2018        push_keyword_kvs(&mut out, kws);
2019      } else if let Some(kws) = prepare_next_keyword(source, offset) {
2020        push_keyword_kvs(&mut out, kws);
2021      } else if let Some(kws) = declare_cursor_next_keyword(source, offset) {
2022        push_keyword_kvs(&mut out, kws);
2023      } else if let Some(kws) = truncate_next_keyword(source, offset) {
2024        push_keyword_kvs(&mut out, kws);
2025      } else if let Some(kws) = grant_revoke_followup_next_keyword(source, offset) {
2026        push_keyword_kvs(&mut out, kws);
2027      } else if let Some(kws) = set_op_followup_next_keyword(source, offset) {
2028        push_keyword_kvs(&mut out, kws);
2029      } else if let Some(kws) = with_cte_after_paren_close_next_keyword(source, offset) {
2030        push_keyword_kvs(&mut out, kws);
2031      } else if let Some(kws) = create_table_post_body_next_keyword(source, offset) {
2032        push_keyword_kvs(&mut out, kws);
2033      } else if let Some(kws) = create_database_next_keyword(source, offset) {
2034        push_keyword_kvs(&mut out, kws);
2035      } else if let Some(kws) = alter_database_next_keyword(source, offset) {
2036        push_keyword_kvs(&mut out, kws);
2037      } else if let Some(kws) = alter_tablespace_next_keyword(source, offset) {
2038        push_keyword_kvs(&mut out, kws);
2039      } else if let Some(kws) = create_user_mapping_next_keyword(source, offset) {
2040        push_keyword_kvs(&mut out, kws);
2041      } else if let Some(kws) = alter_user_mapping_next_keyword(source, offset) {
2042        push_keyword_kvs(&mut out, kws);
2043      } else if let Some(kws) = create_language_next_keyword(source, offset) {
2044        push_keyword_kvs(&mut out, kws);
2045      } else if let Some(kws) = alter_language_next_keyword(source, offset) {
2046        push_keyword_kvs(&mut out, kws);
2047      } else if let Some(kws) = alter_server_next_keyword(source, offset) {
2048        push_keyword_kvs(&mut out, kws);
2049      } else if let Some(kws) = alter_fdw_next_keyword(source, offset) {
2050        push_keyword_kvs(&mut out, kws);
2051      } else if let Some(kws) = drop_user_mapping_next_keyword(source, offset) {
2052        push_keyword_kvs(&mut out, kws);
2053      } else if let Some(kws) = exclude_constraint_next_keyword(source, offset) {
2054        push_keyword_kvs(&mut out, kws);
2055      } else if let Some(kws) = create_function_attribute_next_keyword(source, offset) {
2056        push_keyword_kvs(&mut out, kws);
2057      } else if let Some(kws) = set_role_auth_next_keyword(source, offset) {
2058        push_keyword_kvs(&mut out, kws);
2059      } else if let Some(kws) = fetch_move_direction_keyword(source, offset) {
2060        push_keyword_kvs(&mut out, kws);
2061      } else if let Some(kws) = lock_mode_next_keyword(source, offset) {
2062        push_keyword_kvs(&mut out, kws);
2063      } else if let Some(kws) = deallocate_next_keyword(source, offset) {
2064        push_keyword_kvs(&mut out, kws);
2065      } else if let Some(kws) = alter_default_privileges_next_keyword(source, offset) {
2066        push_keyword_kvs(&mut out, kws);
2067      } else if let Some(kws) = alter_extension_next_keyword(source, offset) {
2068        push_keyword_kvs(&mut out, kws);
2069      } else if let Some(kws) = create_transform_next_keyword(source, offset) {
2070        push_keyword_kvs(&mut out, kws);
2071      } else if let Some(kws) = alter_large_object_next_keyword(source, offset) {
2072        push_keyword_kvs(&mut out, kws);
2073      } else if let Some(kws) = alter_rule_next_keyword(source, offset) {
2074        push_keyword_kvs(&mut out, kws);
2075      } else if let Some(kws) = alter_trigger_next_keyword(source, offset) {
2076        push_keyword_kvs(&mut out, kws);
2077      } else if let Some(kws) = alter_access_method_next_keyword(source, offset) {
2078        push_keyword_kvs(&mut out, kws);
2079      } else if let Some(kws) = create_conversion_next_keyword(source, offset) {
2080        push_keyword_kvs(&mut out, kws);
2081      } else if let Some(kws) = alter_conversion_next_keyword(source, offset) {
2082        push_keyword_kvs(&mut out, kws);
2083      } else if let Some(kws) = create_operator_family_next_keyword(source, offset) {
2084        push_keyword_kvs(&mut out, kws);
2085      } else if let Some(kws) = create_operator_class_next_keyword(source, offset) {
2086        push_keyword_kvs(&mut out, kws);
2087      } else if let Some(kws) = alter_event_trigger_next_keyword(source, offset) {
2088        push_keyword_kvs(&mut out, kws);
2089      } else if let Some(kws) = alter_operator_class_family_next_keyword(source, offset) {
2090        push_keyword_kvs(&mut out, kws);
2091      } else if let Some(kws) = alter_text_search_next_keyword(source, offset) {
2092        push_keyword_kvs(&mut out, kws);
2093      } else if let Some(kws) = alter_statistics_next_keyword(source, offset) {
2094        push_keyword_kvs(&mut out, kws);
2095      } else if let Some(kws) = alter_index_next_keyword(source, offset) {
2096        push_keyword_kvs(&mut out, kws);
2097      } else if let Some(kws) = alter_sequence_next_keyword(source, offset) {
2098        push_keyword_kvs(&mut out, kws);
2099      } else if let Some(kws) = alter_policy_next_keyword(source, offset) {
2100        push_keyword_kvs(&mut out, kws);
2101      } else if let Some(kws) = alter_domain_next_keyword(source, offset) {
2102        push_keyword_kvs(&mut out, kws);
2103      } else if let Some(kws) = alter_collation_next_keyword(source, offset) {
2104        push_keyword_kvs(&mut out, kws);
2105      } else if let Some(kws) = create_access_method_next_keyword(source, offset) {
2106        push_keyword_kvs(&mut out, kws);
2107      } else if let Some(kws) = alter_operator_next_keyword(source, offset) {
2108        push_keyword_kvs(&mut out, kws);
2109      } else if let Some(kws) = alter_aggregate_next_keyword(source, offset) {
2110        push_keyword_kvs(&mut out, kws);
2111      } else if let Some(kws) = alter_publication_next_keyword(source, offset) {
2112        push_keyword_kvs(&mut out, kws);
2113      } else if let Some(kws) = alter_subscription_next_keyword(source, offset) {
2114        push_keyword_kvs(&mut out, kws);
2115      } else if let Some(kws) = alter_schema_next_keyword(source, offset) {
2116        push_keyword_kvs(&mut out, kws);
2117      } else if let Some(kws) = create_text_search_next_keyword(source, offset) {
2118        push_keyword_kvs(&mut out, kws);
2119      } else if let Some(kws) = create_extension_next_keyword(source, offset) {
2120        push_keyword_kvs(&mut out, kws);
2121      } else if let Some(kws) = alter_function_next_keyword(source, offset) {
2122        push_keyword_kvs(&mut out, kws);
2123      } else if let Some(kws) = alter_view_next_keyword(source, offset) {
2124        push_keyword_kvs(&mut out, kws);
2125      } else if let Some(kws) = create_tablespace_next_keyword(source, offset) {
2126        push_keyword_kvs(&mut out, kws);
2127      } else if let Some(kws) = create_aggregate_next_keyword(source, offset) {
2128        push_keyword_kvs(&mut out, kws);
2129      } else if let Some(kws) = create_cast_next_keyword(source, offset) {
2130        push_keyword_kvs(&mut out, kws);
2131      } else if let Some(kws) = create_rule_next_keyword(source, offset) {
2132        push_keyword_kvs(&mut out, kws);
2133      } else if let Some(kws) = create_statistics_next_keyword(source, offset) {
2134        push_keyword_kvs(&mut out, kws);
2135      } else if let Some(kws) = create_type_next_keyword(source, offset) {
2136        push_keyword_kvs(&mut out, kws);
2137      } else if let Some(kws) = create_event_trigger_next_keyword(source, offset) {
2138        push_keyword_kvs(&mut out, kws);
2139      } else if let Some(kws) = create_server_next_keyword(source, offset) {
2140        push_keyword_kvs(&mut out, kws);
2141      } else if let Some(kws) = create_operator_next_keyword(source, offset) {
2142        push_keyword_kvs(&mut out, kws);
2143      } else if let Some(kws) = create_domain_next_keyword(source, offset) {
2144        push_keyword_kvs(&mut out, kws);
2145      } else if let Some(kws) = create_collation_next_keyword(source, offset) {
2146        push_keyword_kvs(&mut out, kws);
2147      } else if let Some(kws) = alter_system_next_keyword(source, offset) {
2148        push_keyword_kvs(&mut out, kws);
2149      } else if let Some(kws) = cte_search_cycle_next_keyword(source, offset) {
2150        push_keyword_kvs(&mut out, kws);
2151      } else if let Some(kws) = column_constraint_next_keyword(source, offset) {
2152        push_keyword_kvs(&mut out, kws);
2153      } else if let Some(kws) = column_generated_next_keyword(source, offset) {
2154        push_keyword_kvs(&mut out, kws);
2155      } else if let Some(kws) = create_index_trailing_next_keyword(source, offset) {
2156        push_keyword_kvs(&mut out, kws);
2157      } else if let Some(kws) = check_constraint_no_inherit_next_keyword(source, offset) {
2158        push_keyword_kvs(&mut out, kws);
2159      } else if let Some(kws) = refresh_mv_next_keyword(source, offset) {
2160        push_keyword_kvs(&mut out, kws);
2161      } else if let Some(kws) = identity_paren_next_keyword(source, offset) {
2162        push_keyword_kvs(&mut out, kws);
2163      } else if let Some(kws) = replica_identity_next_keyword(source, offset) {
2164        push_keyword_kvs(&mut out, kws);
2165      } else if let Some(kws) = create_foreign_table_next_keyword(source, offset) {
2166        push_keyword_kvs(&mut out, kws);
2167      } else if let Some(kws) = create_subscription_next_keyword(source, offset) {
2168        push_keyword_kvs(&mut out, kws);
2169      } else if let Some(kws) = create_view_post_name_next_keyword(source, offset) {
2170        push_keyword_kvs(&mut out, kws);
2171      } else if let Some(kws) = alter_materialized_view_next_keyword(source, offset) {
2172        push_keyword_kvs(&mut out, kws);
2173      } else if let Some(kws) = create_publication_next_keyword(source, offset) {
2174        push_keyword_kvs(&mut out, kws);
2175      } else if let Some(kws) = cluster_next_keyword(source, offset) {
2176        push_keyword_kvs(&mut out, kws);
2177      } else if let Some(kws) = import_foreign_schema_next_keyword(source, offset) {
2178        push_keyword_kvs(&mut out, kws);
2179      } else if let Some(kws) = create_schema_next_keyword(source, offset) {
2180        push_keyword_kvs(&mut out, kws);
2181      } else if let Some(kws) = reindex_next_keyword(source, offset) {
2182        push_keyword_kvs(&mut out, kws);
2183      } else if let Some(kws) = set_transaction_next_keyword(source, offset) {
2184        push_keyword_kvs(&mut out, kws);
2185      } else if call_expects_procedure(source, offset) {
2186        // `CALL <cursor>` -- emit catalog procedures + buffer-derived
2187        // procedures + functions (PG treats them interchangeably enough
2188        // that surfacing both is friendlier than a strict split).
2189        for f in &cat.functions {
2190          out.push(crate::item::Item {
2191            label: f.name.clone(),
2192            kind: crate::item::ItemKind::Function,
2193            detail: Some("procedure / function".into()),
2194            insert_text: format!("{}(", f.name),
2195            kb_entry: None,
2196            sort_priority: 0,
2197            ..Default::default()
2198          });
2199        }
2200      } else if let Some(kws) = reassign_owned_next_keyword(source, offset) {
2201        push_keyword_kvs(&mut out, kws);
2202      } else if let Some(kws) = release_savepoint_next_keyword(source, offset) {
2203        push_keyword_kvs(&mut out, kws);
2204      } else if let Some(kws) = txn_followup_next_keyword(source, offset) {
2205        push_keyword_kvs(&mut out, kws);
2206      } else if let Some(kws) = copy_paren_options_keyword(source, offset) {
2207        push_keyword_kvs(&mut out, kws);
2208      } else if let Some(kws) = copy_next_keyword(source, offset) {
2209        push_keyword_kvs(&mut out, kws);
2210      } else if let Some(kws) = do_block_next_keyword(source, offset) {
2211        push_keyword_kvs(&mut out, kws);
2212      } else if let Some(kws) = role_next_keyword(source, offset) {
2213        push_keyword_kvs(&mut out, kws);
2214      } else if let Some(_tbl) = create_trigger_when_table(source, offset) {
2215        // Inside `CREATE TRIGGER ... ON <tbl> ... WHEN ( <cursor> )`.
2216        // Per user feedback: only the two row aliases `NEW` and `OLD`
2217        // belong here. Once the user types `NEW.` / `OLD.` the
2218        // dot-alias handler at the top of `complete()` resolves to
2219        // the trigger's target table and emits its columns. So this
2220        // slot's menu is intentionally just the two virtual rows
2221        // plus a small comparison-operator hint set.
2222        for (kw, doc) in [
2223          ("NEW", "NEW row alias (INSERT / UPDATE triggers) -- type `NEW.<col>` to access columns"),
2224          ("OLD", "OLD row alias (UPDATE / DELETE triggers) -- type `OLD.<col>` to access columns"),
2225        ] {
2226          out.push(crate::item::Item {
2227            label: kw.into(),
2228            kind: crate::item::ItemKind::Keyword,
2229            detail: Some(doc.into()),
2230            insert_text: kw.into(),
2231            kb_entry: None,
2232            sort_priority: 0,
2233            ..Default::default()
2234          });
2235        }
2236        for (kw, doc) in [
2237          ("IS DISTINCT FROM", "row-level distinctness comparison (NULL-safe)"),
2238          ("IS NOT DISTINCT FROM", "row-level equality comparison (NULL-safe)"),
2239          ("AND", "boolean AND"),
2240          ("OR", "boolean OR"),
2241          ("NOT", "boolean NOT"),
2242          ("IS NULL", "null-ness predicate"),
2243          ("IS NOT NULL", "null-ness predicate (negated)"),
2244        ] {
2245          out.push(crate::item::Item {
2246            label: kw.into(),
2247            kind: crate::item::ItemKind::Keyword,
2248            detail: Some(doc.into()),
2249            insert_text: kw.into(),
2250            kb_entry: None,
2251            sort_priority: 1,
2252            ..Default::default()
2253          });
2254        }
2255      } else if let Some(kws) = create_trigger_next_keyword(source, offset) {
2256        push_keyword_kvs(&mut out, kws);
2257      } else if let Some(kws) = create_index_next_keyword(source, offset) {
2258        push_keyword_kvs(&mut out, kws);
2259      } else if let Some(kws) = alter_type_next_keyword(source, offset) {
2260        push_keyword_kvs(&mut out, kws);
2261      } else if merge::merge_update_set_lhs_slot(source, offset) {
2262        // `MERGE ... THEN UPDATE SET <cursor>` / `... SET col=v, <cursor>`
2263        // -- LHS slot wants target table columns only.
2264        let (tgt, _) = merge::merge_target_and_source(source);
2265        if let Some(t) = tgt.as_deref() {
2266          sources::columns_of_table(cat, None, t, &mut out);
2267        }
2268      } else if merge::merge_when_matched_and_predicate_slot(source, offset)
2269        || merge::merge_update_set_rhs_expr_slot(source, offset)
2270      {
2271        // `MERGE ... WHEN [NOT] MATCHED AND <cursor>` -- expression
2272        // slot. Same shape for `... UPDATE SET <col> = <cursor>` RHS.
2273        // Surface columns from both the MERGE target and the USING
2274        // source, plus aliases, functions, expression kws.
2275        let (tgt, src_tbl) = merge::merge_target_and_source(source);
2276        if let Some(t) = tgt.as_deref() {
2277          sources::columns_of_table(cat, None, t, &mut out);
2278        }
2279        if let Some(s) = src_tbl.as_deref() {
2280          sources::columns_of_table(cat, None, s, &mut out);
2281        }
2282        for alias in merge::merge_aliases(source) {
2283          out.push(crate::item::Item {
2284            label: alias.clone(),
2285            kind: crate::item::ItemKind::Table,
2286            detail: Some("MERGE alias".into()),
2287            insert_text: alias,
2288            kb_entry: None,
2289            sort_priority: 0,
2290            ..Default::default()
2291          });
2292        }
2293        push_all_functions(cat, &mut out);
2294        sources::expression_keywords(&mut out);
2295      } else if let Some(kws) = merge::merge_next_keyword(source, offset) {
2296        push_keyword_kvs(&mut out, kws);
2297      } else if let Some(kws) = after_top_level_create_keyword(source, offset) {
2298        // `CREATE <cursor>` -- narrow to the object-type keywords PG
2299        // accepts after CREATE.
2300        push_keyword_kvs(&mut out, kws);
2301      } else if let Some(kws) = create_class_expects_if_not_exists(source, offset) {
2302        // `CREATE TABLE <cursor>` / `CREATE INDEX <cursor>` etc -- the
2303        // next legal optional tokens are IF NOT EXISTS / ONLY / etc.
2304        push_keyword_kvs(&mut out, kws);
2305      } else if let Some(kws) = after_top_level_alter_keyword(source, offset) {
2306        push_keyword_kvs(&mut out, kws);
2307      } else if let Some(kws) = after_top_level_drop_keyword(source, offset) {
2308        // `DROP <cursor>` -- narrow to the object-type keywords PG
2309        // accepts after DROP. The catch-all fallback below would dump
2310        // 642 keywords/tables/columns which is useless here.
2311        push_keyword_kvs(&mut out, kws);
2312      } else if drop_target_trailing_slot(source, offset) {
2313        // `DROP TABLE users <cursor>` -- the user finished the target
2314        // name; the next legal tokens are CASCADE / RESTRICT / `;`.
2315        // Without this guard the catch-all dumps 641 unrelated items.
2316        for (kw, doc) in [
2317          ("CASCADE", "DROP ... CASCADE -- drop dependent objects too"),
2318          ("RESTRICT", "DROP ... RESTRICT -- refuse if dependents exist (default)"),
2319        ] {
2320          out.push(crate::item::Item {
2321            label: kw.into(),
2322            kind: crate::item::ItemKind::Keyword,
2323            detail: Some(doc.into()),
2324            insert_text: kw.into(),
2325            kb_entry: None,
2326            sort_priority: 0,
2327            ..Default::default()
2328          });
2329        }
2330      } else {
2331        // Broad fallback: keywords + tables + columns + types + funcs.
2332        sources::keywords(&mut out);
2333        sources::types(&mut out);
2334        sources::functions(&mut out);
2335        sources::tables(cat, &mut out);
2336        sources::columns(cat, &mut out);
2337      }
2338    },
2339  }
2340  // Filter columns the user already typed in the same comma-list
2341  // clause. Applies to projection / SET / GROUP BY / ORDER BY /
2342  // INSERT (cols) / CREATE INDEX ON t (cols) / CONSTRAINT (cols) /
2343  // RETURNING. Keeps the menu honest -- typing `SELECT id, ` won't
2344  // re-offer `id`.
2345  if matches!(
2346    ph,
2347    Phase::SelectProjection
2348      | Phase::InProjection
2349      | Phase::NextProjection
2350      | Phase::GroupByList
2351      | Phase::OrderByList
2352      | Phase::InsertColumnList
2353      | Phase::UpdateAssignment
2354  ) {
2355    let used = used_columns_in_clause(source, offset);
2356    if !used.is_empty() {
2357      out.retain(|it| !is_column_listed(it, &used));
2358    }
2359  }
2360  dedup_items(out)
2361}