Skip to main content

dsl_completion/
contexts.rs

1//! Context-aware special completions.
2//!
3//! Catches situations the phase state machine doesn't model:
4//!   * `CREATE INDEX ... USING <method>`
5//!   * `CREATE INDEX ... ON t (col <opclass>)`
6//!   * `CREATE TRIGGER ... BEFORE|AFTER|INSTEAD OF <event>`
7//!   * `CREATE TRIGGER ... ON <table>`
8//!   * `CREATE TRIGGER ... EXECUTE [FUNCTION|PROCEDURE] <fn>`
9//!   * `CALL <proc>`
10//!   * `CREATE POLICY ... FOR <cmd>`
11//!   * `CREATE POLICY ... TO <role>`
12//!   * `ALTER TABLE t ALTER COLUMN c TYPE <type>`
13//!
14//! Runs before the phase state machine: returns `Some(items)` to
15//! short-circuit; `None` to fall through.
16
17use crate::item::{Item, ItemKind};
18use crate::sources;
19use dsl_catalog::Catalog;
20use text_size::TextSize;
21
22pub fn detect(source: &str, offset: TextSize, cat: &Catalog) -> Option<Vec<Item>> {
23  let pos: usize = u32::from(offset) as usize;
24  let pos = pos.min(source.len());
25  // Walk back to the nearest statement boundary so we don't match
26  // tokens from a previous statement.
27  let stmt_start = source[..pos].rfind(';').map(|p| p + 1).unwrap_or(0);
28  let stmt = &source[stmt_start..pos];
29  let upper = stmt.to_ascii_uppercase();
30  let _ = source;
31
32  // ---- CREATE INDEX USING <method> ----
33  if upper.contains("CREATE INDEX") || upper.contains("CREATE UNIQUE INDEX") {
34    if let Some(items) = index_using_method(&upper) {
35      return Some(items);
36    }
37    if let Some(items) = index_opclass(&upper, stmt) {
38      return Some(items);
39    }
40  }
41
42  // ---- CREATE TRIGGER ----
43  if upper.contains("CREATE TRIGGER")
44    || upper.contains("CREATE OR REPLACE TRIGGER")
45    || upper.contains("CREATE CONSTRAINT TRIGGER")
46  {
47    if let Some(items) = trigger_event(&upper) {
48      return Some(items);
49    }
50    if let Some(items) = trigger_on_table(&upper, cat) {
51      return Some(items);
52    }
53    if let Some(items) = trigger_execute_function(&upper, source, cat) {
54      return Some(items);
55    }
56  }
57
58  // ---- CALL <procedure> ----
59  if let Some(items) = call_procedure(&upper, cat) {
60    return Some(items);
61  }
62
63  // ---- CREATE POLICY ----
64  if upper.contains("CREATE POLICY") || upper.contains("CREATE OR REPLACE POLICY") || upper.contains("ALTER POLICY") {
65    if let Some(items) = policy_for_command(&upper) {
66      return Some(items);
67    }
68    if let Some(items) = policy_to_role(&upper, cat) {
69      return Some(items);
70    }
71  }
72
73  // ---- ALTER TABLE ALTER COLUMN ... TYPE <type> ----
74  if upper.contains("ALTER TABLE")
75    && upper.contains("ALTER COLUMN")
76    && let Some(items) = alter_column_type(&upper)
77  {
78    return Some(items);
79  }
80
81  None
82}
83
84fn index_using_method(upper: &str) -> Option<Vec<Item>> {
85  // Cursor right after `USING ` (or with partial method already typed).
86  let using_at = upper.rfind("USING ")?;
87  let after = &upper[using_at + 6..];
88  // Bail if there's a paren already -- we're past the method.
89  if after.contains('(') {
90    return None;
91  }
92  // Bail if there's a space after a non-whitespace token (method already complete).
93  let trimmed = after.trim_start();
94  if trimmed.split_whitespace().count() > 1 {
95    return None;
96  }
97  let mut out = Vec::new();
98  for (m, doc) in [
99    ("btree", "default index, supports = < > BETWEEN ORDER BY"),
100    ("hash", "equality-only, smaller than btree"),
101    ("gist", "geometry, full-text, range types"),
102    ("gin", "jsonb, arrays, tsvector"),
103    ("brin", "huge append-only tables (logs, time series)"),
104    ("spgist", "non-balanced data: trees, points"),
105  ] {
106    out.push(Item {
107      label: m.into(),
108      kind: ItemKind::Keyword,
109      detail: Some(doc.into()),
110      description: Some("index method".into()),
111      documentation_md: None,
112      insert_text: m.into(),
113      is_snippet: false,
114      kb_entry: None,
115      sort_priority: 1,
116    });
117  }
118  Some(out)
119}
120
121fn index_opclass(upper: &str, stmt: &str) -> Option<Vec<Item>> {
122  // Cursor inside `CREATE INDEX ... USING gin (col <here>)` -- need to be
123  // past the column name with at least one whitespace.
124  let using_at = upper.rfind("USING ")?;
125  let after = &upper[using_at + 6..];
126  let method: String = after.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
127  let method_lc = method.to_ascii_lowercase();
128  let paren_rel = after.find('(')?;
129  let paren_body = &after[paren_rel + 1..];
130  // Find the last comma at depth 0 -- everything after is the current column entry.
131  let mut depth = 0i32;
132  let mut entry_start = 0usize;
133  let bytes = paren_body.as_bytes();
134  for (i, b) in bytes.iter().enumerate() {
135    match b {
136      b'(' => depth += 1,
137      b')' => depth -= 1,
138      b',' if depth == 0 => entry_start = i + 1,
139      _ => {},
140    }
141  }
142  let entry = &paren_body[entry_start..];
143  let tokens: Vec<&str> = entry.split_whitespace().collect();
144  if tokens.len() < 2 {
145    return None;
146  }
147  // After the column token, suggest opclasses appropriate to the method.
148  let opclasses: Vec<(&str, &str)> = match method_lc.as_str() {
149    "btree" => vec![
150      ("text_pattern_ops", "LIKE 'prefix%' on text"),
151      ("varchar_pattern_ops", "LIKE 'prefix%' on varchar"),
152      ("bpchar_pattern_ops", "LIKE 'prefix%' on char(n)"),
153    ],
154    "gin" => vec![
155      ("jsonb_path_ops", "smaller than jsonb_ops, only @> queries"),
156      ("jsonb_ops", "default jsonb operator class"),
157      ("array_ops", "default for ARRAY columns"),
158      ("gin_trgm_ops", "pg_trgm: LIKE/ILIKE with wildcards"),
159    ],
160    "gist" => vec![
161      ("gist_trgm_ops", "pg_trgm GIST variant"),
162      ("range_ops", "range types"),
163      ("inet_ops", "IP address range queries"),
164    ],
165    "hash" => vec![("array_ops", "array equality")],
166    _ => return None,
167  };
168  let _ = stmt;
169  let mut out = Vec::new();
170  for (op, doc) in opclasses {
171    out.push(Item {
172      label: op.into(),
173      kind: ItemKind::Keyword,
174      detail: Some(doc.into()),
175      description: Some(format!("{method_lc} operator class")),
176      documentation_md: None,
177      insert_text: op.into(),
178      is_snippet: false,
179      kb_entry: None,
180      sort_priority: 1,
181    });
182  }
183  Some(out)
184}
185
186fn trigger_event(upper: &str) -> Option<Vec<Item>> {
187  // Match the most recent BEFORE / AFTER / INSTEAD OF in the statement.
188  let kw = ["BEFORE ", "AFTER ", "INSTEAD OF "]
189    .into_iter()
190    .filter_map(|k| upper.rfind(k).map(|p| (p, k)))
191    .max_by_key(|x| x.0)?;
192  let after = &upper[kw.0 + kw.1.len()..];
193  // Bail if we already past the event (an OR / ON appears).
194  if after.contains(" ON ") {
195    return None;
196  }
197  let toks: Vec<&str> = after.split_whitespace().collect();
198  if toks.len() > 2 {
199    return None;
200  }
201  let mut out = Vec::new();
202  for (ev, doc) in [
203    ("INSERT", "row insertion"),
204    ("UPDATE", "row update"),
205    ("DELETE", "row deletion"),
206    ("TRUNCATE", "table truncate (statement-level only)"),
207  ] {
208    out.push(Item {
209      label: ev.into(),
210      kind: ItemKind::Keyword,
211      detail: Some(doc.into()),
212      description: Some("trigger event".into()),
213      documentation_md: None,
214      insert_text: ev.into(),
215      is_snippet: false,
216      kb_entry: None,
217      sort_priority: 1,
218    });
219  }
220  Some(out)
221}
222
223fn trigger_on_table(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
224  // Cursor immediately after `ON ` in a CREATE TRIGGER statement.
225  let on_at = upper.rfind(" ON ")?;
226  let after = &upper[on_at + 4..];
227  // Bail if we're past the table (FOR / EXECUTE / WHEN keyword present).
228  let post_upper = after.to_ascii_uppercase();
229  for stop in ["FOR ", "EXECUTE", "WHEN", "REFERENCING"] {
230    if post_upper.contains(stop) {
231      return None;
232    }
233  }
234  let toks: Vec<&str> = after.split_whitespace().collect();
235  if toks.len() > 1 {
236    return None;
237  }
238  let mut out = Vec::new();
239  sources::tables(cat, &mut out);
240  Some(out)
241}
242
243fn trigger_execute_function(upper: &str, stmt: &str, cat: &Catalog) -> Option<Vec<Item>> {
244  let exec_at = upper
245    .rfind("EXECUTE FUNCTION ")
246    .map(|p| p + "EXECUTE FUNCTION ".len())
247    .or_else(|| upper.rfind("EXECUTE PROCEDURE ").map(|p| p + "EXECUTE PROCEDURE ".len()))?;
248  let after = &upper[exec_at..];
249  if after.contains('(') {
250    return None;
251  }
252  let toks: Vec<&str> = after.split_whitespace().collect();
253  if toks.len() > 1 {
254    return None;
255  }
256  let mut out = Vec::new();
257  // Catalog functions returning `trigger`.
258  for f in &cat.functions {
259    if !f.return_type.eq_ignore_ascii_case("trigger") {
260      continue;
261    }
262    out.push(Item {
263      label: f.name.clone(),
264      kind: ItemKind::Function,
265      detail: Some(format!("returns trigger ({} args)", f.arguments.len())),
266      description: Some(format!("{} (db)", f.schema)),
267      documentation_md: None,
268      insert_text: format!("{}()", f.name),
269      is_snippet: false,
270      kb_entry: None,
271      sort_priority: 1,
272    });
273  }
274  // Also harvest CREATE FUNCTION ... RETURNS trigger from the buffer.
275  let upper_src = stmt.to_ascii_uppercase();
276  for needle in ["CREATE OR REPLACE FUNCTION ", "CREATE FUNCTION "] {
277    let mut from = 0;
278    while let Some(rel) = upper_src[from..].find(needle) {
279      let at = from + rel + needle.len();
280      let after_kw = &stmt[at..];
281      let name_end =
282        after_kw.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')).unwrap_or(after_kw.len());
283      let name = after_kw[..name_end].rsplit('.').next().unwrap_or(&after_kw[..name_end]).to_string();
284      let tail_upper = upper_src[at..].to_string();
285      if tail_upper.contains("RETURNS TRIGGER") && !out.iter().any(|i| i.label == name) {
286        out.push(Item {
287          label: name.clone(),
288          kind: ItemKind::Function,
289          detail: Some("returns trigger (defined in this buffer)".into()),
290          description: Some("source".into()),
291          documentation_md: None,
292          insert_text: format!("{name}()"),
293          is_snippet: false,
294          kb_entry: None,
295          sort_priority: 1,
296        });
297      }
298      from = at + name_end;
299    }
300  }
301  Some(out)
302}
303
304fn call_procedure(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
305  // CALL is a top-level keyword introducing a procedure call.
306  let trimmed = upper.trim_start();
307  if !trimmed.starts_with("CALL ") {
308    return None;
309  }
310  let after = &trimmed[5..];
311  if after.contains('(') {
312    return None;
313  }
314  let toks: Vec<&str> = after.split_whitespace().collect();
315  if toks.len() > 1 {
316    return None;
317  }
318  // Catalog functions with no return type (typical of procedures);
319  // also accept anything with `void` return.
320  let mut out = Vec::new();
321  for f in &cat.functions {
322    if !(f.return_type.is_empty() || f.return_type.eq_ignore_ascii_case("void")) {
323      continue;
324    }
325    out.push(Item {
326      label: f.name.clone(),
327      kind: ItemKind::Function,
328      detail: Some(format!("procedure ({} args)", f.arguments.len())),
329      description: Some(format!("{} (db)", f.schema)),
330      documentation_md: None,
331      insert_text: if f.arguments.is_empty() { format!("{}()", f.name) } else { format!("{}($0)", f.name) },
332      is_snippet: !f.arguments.is_empty(),
333      kb_entry: None,
334      sort_priority: 1,
335    });
336  }
337  Some(out)
338}
339
340fn policy_for_command(upper: &str) -> Option<Vec<Item>> {
341  let for_at = upper.rfind(" FOR ")?;
342  let after = &upper[for_at + 5..];
343  let toks: Vec<&str> = after.split_whitespace().collect();
344  if toks.len() > 1 {
345    return None;
346  }
347  let mut out = Vec::new();
348  for cmd in ["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"] {
349    out.push(Item {
350      label: cmd.into(),
351      kind: ItemKind::Keyword,
352      detail: Some(format!("policy applies to {cmd}")),
353      description: Some("policy command".into()),
354      documentation_md: None,
355      insert_text: cmd.into(),
356      is_snippet: false,
357      kb_entry: None,
358      sort_priority: 1,
359    });
360  }
361  Some(out)
362}
363
364fn policy_to_role(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
365  let to_at = upper.rfind(" TO ")?;
366  let after = &upper[to_at + 4..];
367  if after.contains("USING") || after.contains("WITH CHECK") {
368    return None;
369  }
370  let toks: Vec<&str> = after.split_whitespace().collect();
371  if toks.len() > 1 {
372    return None;
373  }
374  let mut out = Vec::new();
375  out.push(Item {
376    label: "PUBLIC".into(),
377    kind: ItemKind::Keyword,
378    detail: Some("every role".into()),
379    description: Some("policy role".into()),
380    documentation_md: None,
381    insert_text: "PUBLIC".into(),
382    is_snippet: false,
383    kb_entry: None,
384    sort_priority: 1,
385  });
386  for role in &cat.roles {
387    out.push(Item {
388      label: role.clone(),
389      kind: ItemKind::Keyword,
390      detail: Some("role".into()),
391      description: Some("policy role".into()),
392      documentation_md: None,
393      insert_text: role.clone(),
394      is_snippet: false,
395      kb_entry: None,
396      sort_priority: 2,
397    });
398  }
399  Some(out)
400}
401
402fn alter_column_type(upper: &str) -> Option<Vec<Item>> {
403  // `ALTER COLUMN c TYPE <here>` (with or without `SET DATA`).
404  let after = if let Some(at) = upper.rfind(" SET DATA TYPE ") {
405    &upper[at + 15..]
406  } else {
407    let at = upper.rfind(" TYPE ")?;
408    &upper[at + 6..]
409  };
410  if after.contains("USING") || after.contains(';') {
411    return None;
412  }
413  let toks: Vec<&str> = after.split_whitespace().collect();
414  if toks.len() > 1 {
415    return None;
416  }
417  let mut out = Vec::new();
418  for ty in [
419    "text",
420    "varchar",
421    "char(1)",
422    "integer",
423    "bigint",
424    "smallint",
425    "serial",
426    "bigserial",
427    "numeric",
428    "real",
429    "double precision",
430    "boolean",
431    "uuid",
432    "jsonb",
433    "json",
434    "date",
435    "time",
436    "timestamp",
437    "timestamptz",
438    "interval",
439    "bytea",
440    "inet",
441    "cidr",
442  ] {
443    out.push(Item {
444      label: ty.into(),
445      kind: ItemKind::Type,
446      detail: Some("data type".into()),
447      description: Some("ALTER COLUMN target".into()),
448      documentation_md: None,
449      insert_text: ty.into(),
450      is_snippet: false,
451      kb_entry: None,
452      sort_priority: 1,
453    });
454  }
455  Some(out)
456}