Skip to main content

dsl_hover/
ddl.rs

1//! Lookups against the *current buffer's* CREATE TABLE statements.
2//!
3//! When the cursor sits inside a column declaration of a CREATE TABLE in
4//! the buffer being edited, we want a hover card that explains that
5//! specific declaration -- type, NOT NULL, DEFAULT -- even when the live
6//! catalog doesn't know about the table yet (because the user is in the
7//! middle of writing it). dsl-parse gives us the parsed shape; we use it
8//! here to map the cursor to a column def.
9
10use crate::render;
11use dsl_parse::{ParsedFile, StatementKind};
12use text_size::TextSize;
13
14/// Try to render a column-declaration hover for the cursor position.
15/// Returns None when the cursor isn't inside a column declaration.
16pub fn column_decl_at(file: &ParsedFile, source: &str, offset: TextSize) -> Option<String> {
17  let pos: u32 = offset.into();
18  for stmt in &file.statements {
19    let StatementKind::CreateTable(ct) = &stmt.kind else {
20      continue;
21    };
22    if !contains(stmt.range, pos) {
23      continue;
24    }
25
26    // Locate the parenthesised body inside the statement so we can
27    // map the cursor to a column position.
28    let stmt_start: u32 = stmt.range.start().into();
29    let stmt_end: u32 = stmt.range.end().into();
30    let slice = &source[stmt_start as usize..stmt_end as usize];
31
32    let body = match column_body_range(slice) {
33      Some(r) => r,
34      None => continue,
35    };
36
37    // Position relative to the body's interior.
38    if pos < stmt_start + body.0 || pos >= stmt_start + body.1 {
39      continue;
40    }
41    let body_text = &slice[body.0 as usize..body.1 as usize];
42
43    // Walk the body splitting on top-level commas. The split
44    // honours nested parens (e.g. NUMERIC(10,2)) so a comma inside
45    // a type spec does not begin a new column.
46    let mut piece_start = 0usize;
47    let mut depth: i32 = 0;
48    let mut entries: Vec<(usize, usize)> = Vec::new();
49    for (i, ch) in body_text.char_indices() {
50      match ch {
51        '(' => depth += 1,
52        ')' => depth -= 1,
53        ',' if depth == 0 => {
54          entries.push((piece_start, i));
55          piece_start = i + 1;
56        },
57        _ => {},
58      }
59    }
60    if piece_start < body_text.len() {
61      entries.push((piece_start, body_text.len()));
62    }
63
64    // Map the cursor to one of the entries.
65    let cursor_in_body = (pos - (stmt_start + body.0)) as usize;
66    let entry = entries.into_iter().find(|(s, e)| cursor_in_body >= *s && cursor_in_body <= *e)?;
67
68    let piece = body_text[entry.0..entry.1].trim();
69    if piece.is_empty() {
70      continue;
71    }
72
73    // Skip constraint-only lines; those are resolved by the
74    // constraint-identifier resolver instead.
75    let upper = piece.to_ascii_uppercase();
76    if upper.starts_with("CONSTRAINT")
77      || upper.starts_with("PRIMARY KEY")
78      || upper.starts_with("FOREIGN KEY")
79      || upper.starts_with("UNIQUE ")
80      || upper.starts_with("CHECK ")
81    {
82      continue;
83    }
84
85    // Tighten: only fire when the cursor sits ON the column-name
86    // token itself. The type, NOT NULL, DEFAULT, and expression
87    // tokens each have their own hover (keyword / type / function),
88    // and overriding them here would mask the richer card.
89    let token = crate::token::token_at(source, offset)?;
90    let ident =
91      piece.split(|c: char| c.is_whitespace() || c == '(' || c == ',').find(|s| !s.is_empty())?.trim_matches('"');
92    if !token.eq_ignore_ascii_case(ident) {
93      return None;
94    }
95
96    let col = ct.columns.iter().find(|c| c.name.eq_ignore_ascii_case(ident))?;
97    let implicit = crate::implicit::derive(body_text, col);
98    return Some(render::column_decl_with_implicit(&ct.table.name, col, &implicit));
99  }
100  None
101}
102
103fn contains(range: text_size::TextRange, pos: u32) -> bool {
104  let s: u32 = range.start().into();
105  let e: u32 = range.end().into();
106  pos >= s && pos <= e
107}
108
109/// Find the open and close paren of the column body within a CREATE
110/// TABLE statement slice. Returns offsets relative to the slice.
111fn column_body_range(slice: &str) -> Option<(u32, u32)> {
112  let open = slice.find('(')?;
113  let mut depth: i32 = 1;
114  let mut i = open + 1;
115  let bytes = slice.as_bytes();
116  while i < slice.len() {
117    match bytes[i] as char {
118      '(' => depth += 1,
119      ')' => {
120        depth -= 1;
121        if depth == 0 {
122          return Some(((open + 1) as u32, i as u32));
123        }
124      },
125      _ => {},
126    }
127    i += 1;
128  }
129  None
130}