1use crate::render;
11use dsl_parse::{ParsedFile, StatementKind};
12use text_size::TextSize;
13
14pub 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 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 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 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 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 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 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
109fn 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}