dsl-completion 3.0.0

Context-aware SQL completion for duck-sqllsp.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Context-aware special completions.
//!
//! Catches situations the phase state machine doesn't model:
//!   * `CREATE INDEX ... USING <method>`
//!   * `CREATE INDEX ... ON t (col <opclass>)`
//!   * `CREATE TRIGGER ... BEFORE|AFTER|INSTEAD OF <event>`
//!   * `CREATE TRIGGER ... ON <table>`
//!   * `CREATE TRIGGER ... EXECUTE [FUNCTION|PROCEDURE] <fn>`
//!   * `CALL <proc>`
//!   * `CREATE POLICY ... FOR <cmd>`
//!   * `CREATE POLICY ... TO <role>`
//!   * `ALTER TABLE t ALTER COLUMN c TYPE <type>`
//!
//! Runs before the phase state machine: returns `Some(items)` to
//! short-circuit; `None` to fall through.

use crate::item::{Item, ItemKind};
use crate::sources;
use dsl_catalog::Catalog;
use text_size::TextSize;

pub fn detect(source: &str, offset: TextSize, cat: &Catalog) -> Option<Vec<Item>> {
  let pos: usize = u32::from(offset) as usize;
  let pos = pos.min(source.len());
  // Walk back to the nearest statement boundary so we don't match
  // tokens from a previous statement.
  let stmt_start = source[..pos].rfind(';').map(|p| p + 1).unwrap_or(0);
  let stmt = &source[stmt_start..pos];
  let upper = stmt.to_ascii_uppercase();
  let _ = source;

  // ---- CREATE INDEX USING <method> ----
  if upper.contains("CREATE INDEX") || upper.contains("CREATE UNIQUE INDEX") {
    if let Some(items) = index_using_method(&upper) {
      return Some(items);
    }
    if let Some(items) = index_opclass(&upper, stmt) {
      return Some(items);
    }
  }

  // ---- CREATE TRIGGER ----
  if upper.contains("CREATE TRIGGER")
    || upper.contains("CREATE OR REPLACE TRIGGER")
    || upper.contains("CREATE CONSTRAINT TRIGGER")
  {
    if let Some(items) = trigger_event(&upper) {
      return Some(items);
    }
    if let Some(items) = trigger_on_table(&upper, cat) {
      return Some(items);
    }
    if let Some(items) = trigger_execute_function(&upper, source, cat) {
      return Some(items);
    }
  }

  // ---- CALL <procedure> ----
  if let Some(items) = call_procedure(&upper, cat) {
    return Some(items);
  }

  // ---- CREATE POLICY ----
  if upper.contains("CREATE POLICY") || upper.contains("CREATE OR REPLACE POLICY") || upper.contains("ALTER POLICY") {
    if let Some(items) = policy_for_command(&upper) {
      return Some(items);
    }
    if let Some(items) = policy_to_role(&upper, cat) {
      return Some(items);
    }
  }

  // ---- ALTER TABLE ALTER COLUMN ... TYPE <type> ----
  if upper.contains("ALTER TABLE")
    && upper.contains("ALTER COLUMN")
    && let Some(items) = alter_column_type(&upper)
  {
    return Some(items);
  }

  None
}

fn index_using_method(upper: &str) -> Option<Vec<Item>> {
  // Cursor right after `USING ` (or with partial method already typed).
  let using_at = upper.rfind("USING ")?;
  let after = &upper[using_at + 6..];
  // Bail if there's a paren already -- we're past the method.
  if after.contains('(') {
    return None;
  }
  // Bail if there's a space after a non-whitespace token (method already complete).
  let trimmed = after.trim_start();
  if trimmed.split_whitespace().count() > 1 {
    return None;
  }
  let mut out = Vec::new();
  for (m, doc) in [
    ("btree", "default index, supports = < > BETWEEN ORDER BY"),
    ("hash", "equality-only, smaller than btree"),
    ("gist", "geometry, full-text, range types"),
    ("gin", "jsonb, arrays, tsvector"),
    ("brin", "huge append-only tables (logs, time series)"),
    ("spgist", "non-balanced data: trees, points"),
  ] {
    out.push(Item {
      label: m.into(),
      kind: ItemKind::Keyword,
      detail: Some(doc.into()),
      description: Some("index method".into()),
      documentation_md: None,
      insert_text: m.into(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}

fn index_opclass(upper: &str, stmt: &str) -> Option<Vec<Item>> {
  // Cursor inside `CREATE INDEX ... USING gin (col <here>)` -- need to be
  // past the column name with at least one whitespace.
  let using_at = upper.rfind("USING ")?;
  let after = &upper[using_at + 6..];
  let method: String = after.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
  let method_lc = method.to_ascii_lowercase();
  let paren_rel = after.find('(')?;
  let paren_body = &after[paren_rel + 1..];
  // Find the last comma at depth 0 -- everything after is the current column entry.
  let mut depth = 0i32;
  let mut entry_start = 0usize;
  let bytes = paren_body.as_bytes();
  for (i, b) in bytes.iter().enumerate() {
    match b {
      b'(' => depth += 1,
      b')' => depth -= 1,
      b',' if depth == 0 => entry_start = i + 1,
      _ => {},
    }
  }
  let entry = &paren_body[entry_start..];
  let tokens: Vec<&str> = entry.split_whitespace().collect();
  if tokens.len() < 2 {
    return None;
  }
  // After the column token, suggest opclasses appropriate to the method.
  let opclasses: Vec<(&str, &str)> = match method_lc.as_str() {
    "btree" => vec![
      ("text_pattern_ops", "LIKE 'prefix%' on text"),
      ("varchar_pattern_ops", "LIKE 'prefix%' on varchar"),
      ("bpchar_pattern_ops", "LIKE 'prefix%' on char(n)"),
    ],
    "gin" => vec![
      ("jsonb_path_ops", "smaller than jsonb_ops, only @> queries"),
      ("jsonb_ops", "default jsonb operator class"),
      ("array_ops", "default for ARRAY columns"),
      ("gin_trgm_ops", "pg_trgm: LIKE/ILIKE with wildcards"),
    ],
    "gist" => vec![
      ("gist_trgm_ops", "pg_trgm GIST variant"),
      ("range_ops", "range types"),
      ("inet_ops", "IP address range queries"),
    ],
    "hash" => vec![("array_ops", "array equality")],
    _ => return None,
  };
  let _ = stmt;
  let mut out = Vec::new();
  for (op, doc) in opclasses {
    out.push(Item {
      label: op.into(),
      kind: ItemKind::Keyword,
      detail: Some(doc.into()),
      description: Some(format!("{method_lc} operator class")),
      documentation_md: None,
      insert_text: op.into(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}

fn trigger_event(upper: &str) -> Option<Vec<Item>> {
  // Match the most recent BEFORE / AFTER / INSTEAD OF in the statement.
  let kw = ["BEFORE ", "AFTER ", "INSTEAD OF "]
    .into_iter()
    .filter_map(|k| upper.rfind(k).map(|p| (p, k)))
    .max_by_key(|x| x.0)?;
  let after = &upper[kw.0 + kw.1.len()..];
  // Bail if we already past the event (an OR / ON appears).
  if after.contains(" ON ") {
    return None;
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 2 {
    return None;
  }
  let mut out = Vec::new();
  for (ev, doc) in [
    ("INSERT", "row insertion"),
    ("UPDATE", "row update"),
    ("DELETE", "row deletion"),
    ("TRUNCATE", "table truncate (statement-level only)"),
  ] {
    out.push(Item {
      label: ev.into(),
      kind: ItemKind::Keyword,
      detail: Some(doc.into()),
      description: Some("trigger event".into()),
      documentation_md: None,
      insert_text: ev.into(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}

fn trigger_on_table(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
  // Cursor immediately after `ON ` in a CREATE TRIGGER statement.
  let on_at = upper.rfind(" ON ")?;
  let after = &upper[on_at + 4..];
  // Bail if we're past the table (FOR / EXECUTE / WHEN keyword present).
  let post_upper = after.to_ascii_uppercase();
  for stop in ["FOR ", "EXECUTE", "WHEN", "REFERENCING"] {
    if post_upper.contains(stop) {
      return None;
    }
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  let mut out = Vec::new();
  sources::tables(cat, &mut out);
  Some(out)
}

fn trigger_execute_function(upper: &str, stmt: &str, cat: &Catalog) -> Option<Vec<Item>> {
  let exec_at = upper
    .rfind("EXECUTE FUNCTION ")
    .map(|p| p + "EXECUTE FUNCTION ".len())
    .or_else(|| upper.rfind("EXECUTE PROCEDURE ").map(|p| p + "EXECUTE PROCEDURE ".len()))?;
  let after = &upper[exec_at..];
  if after.contains('(') {
    return None;
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  let mut out = Vec::new();
  // Catalog functions returning `trigger`.
  for f in &cat.functions {
    if !f.return_type.eq_ignore_ascii_case("trigger") {
      continue;
    }
    out.push(Item {
      label: f.name.clone(),
      kind: ItemKind::Function,
      detail: Some(format!("returns trigger ({} args)", f.arguments.len())),
      description: Some(format!("{} (db)", f.schema)),
      documentation_md: None,
      insert_text: format!("{}()", f.name),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  // Also harvest CREATE FUNCTION ... RETURNS trigger from the buffer.
  let upper_src = stmt.to_ascii_uppercase();
  for needle in ["CREATE OR REPLACE FUNCTION ", "CREATE FUNCTION "] {
    let mut from = 0;
    while let Some(rel) = upper_src[from..].find(needle) {
      let at = from + rel + needle.len();
      let after_kw = &stmt[at..];
      let name_end =
        after_kw.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '.')).unwrap_or(after_kw.len());
      let name = after_kw[..name_end].rsplit('.').next().unwrap_or(&after_kw[..name_end]).to_string();
      let tail_upper = upper_src[at..].to_string();
      if tail_upper.contains("RETURNS TRIGGER") && !out.iter().any(|i| i.label == name) {
        out.push(Item {
          label: name.clone(),
          kind: ItemKind::Function,
          detail: Some("returns trigger (defined in this buffer)".into()),
          description: Some("source".into()),
          documentation_md: None,
          insert_text: format!("{name}()"),
          is_snippet: false,
          kb_entry: None,
          sort_priority: 1,
        });
      }
      from = at + name_end;
    }
  }
  Some(out)
}

fn call_procedure(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
  // CALL is a top-level keyword introducing a procedure call.
  let trimmed = upper.trim_start();
  if !trimmed.starts_with("CALL ") {
    return None;
  }
  let after = &trimmed[5..];
  if after.contains('(') {
    return None;
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  // Catalog functions with no return type (typical of procedures);
  // also accept anything with `void` return.
  let mut out = Vec::new();
  for f in &cat.functions {
    if !(f.return_type.is_empty() || f.return_type.eq_ignore_ascii_case("void")) {
      continue;
    }
    out.push(Item {
      label: f.name.clone(),
      kind: ItemKind::Function,
      detail: Some(format!("procedure ({} args)", f.arguments.len())),
      description: Some(format!("{} (db)", f.schema)),
      documentation_md: None,
      insert_text: if f.arguments.is_empty() { format!("{}()", f.name) } else { format!("{}($0)", f.name) },
      is_snippet: !f.arguments.is_empty(),
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}

fn policy_for_command(upper: &str) -> Option<Vec<Item>> {
  let for_at = upper.rfind(" FOR ")?;
  let after = &upper[for_at + 5..];
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  let mut out = Vec::new();
  for cmd in ["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"] {
    out.push(Item {
      label: cmd.into(),
      kind: ItemKind::Keyword,
      detail: Some(format!("policy applies to {cmd}")),
      description: Some("policy command".into()),
      documentation_md: None,
      insert_text: cmd.into(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}

fn policy_to_role(upper: &str, cat: &Catalog) -> Option<Vec<Item>> {
  let to_at = upper.rfind(" TO ")?;
  let after = &upper[to_at + 4..];
  if after.contains("USING") || after.contains("WITH CHECK") {
    return None;
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  let mut out = Vec::new();
  out.push(Item {
    label: "PUBLIC".into(),
    kind: ItemKind::Keyword,
    detail: Some("every role".into()),
    description: Some("policy role".into()),
    documentation_md: None,
    insert_text: "PUBLIC".into(),
    is_snippet: false,
    kb_entry: None,
    sort_priority: 1,
  });
  for role in &cat.roles {
    out.push(Item {
      label: role.clone(),
      kind: ItemKind::Keyword,
      detail: Some("role".into()),
      description: Some("policy role".into()),
      documentation_md: None,
      insert_text: role.clone(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 2,
    });
  }
  Some(out)
}

fn alter_column_type(upper: &str) -> Option<Vec<Item>> {
  // `ALTER COLUMN c TYPE <here>` (with or without `SET DATA`).
  let after = if let Some(at) = upper.rfind(" SET DATA TYPE ") {
    &upper[at + 15..]
  } else {
    let at = upper.rfind(" TYPE ")?;
    &upper[at + 6..]
  };
  if after.contains("USING") || after.contains(';') {
    return None;
  }
  let toks: Vec<&str> = after.split_whitespace().collect();
  if toks.len() > 1 {
    return None;
  }
  let mut out = Vec::new();
  for ty in [
    "text",
    "varchar",
    "char(1)",
    "integer",
    "bigint",
    "smallint",
    "serial",
    "bigserial",
    "numeric",
    "real",
    "double precision",
    "boolean",
    "uuid",
    "jsonb",
    "json",
    "date",
    "time",
    "timestamp",
    "timestamptz",
    "interval",
    "bytea",
    "inet",
    "cidr",
  ] {
    out.push(Item {
      label: ty.into(),
      kind: ItemKind::Type,
      detail: Some("data type".into()),
      description: Some("ALTER COLUMN target".into()),
      documentation_md: None,
      insert_text: ty.into(),
      is_snippet: false,
      kb_entry: None,
      sort_priority: 1,
    });
  }
  Some(out)
}