1use dsl_parse::ColumnDef;
14
15#[derive(Debug, Clone, Default)]
16pub struct Implicit {
17 pub primary_key: bool,
18 pub unique: bool,
19 pub auto_increment: bool,
20 pub foreign_key: Option<ForeignKey>,
21 pub check_count: usize,
22}
23
24#[derive(Debug, Clone)]
25pub struct ForeignKey {
26 pub references: String, }
28
29pub fn derive(body_text: &str, col: &ColumnDef) -> Implicit {
33 let mut out = Implicit::default();
34 let name = col.name.as_str();
35 let upper_type = col.type_name.to_ascii_uppercase();
36
37 if column_line_marks_primary(body_text, name) {
41 out.primary_key = true;
42 out.unique = true;
43 }
44
45 if matches!(upper_type.as_str(), "SERIAL" | "BIGSERIAL" | "SMALLSERIAL") {
47 out.auto_increment = true;
48 }
49 if column_line_has_identity(body_text, name) {
50 out.auto_increment = true;
51 }
52
53 if table_level_primary_includes(body_text, name) {
55 out.primary_key = true;
56 out.unique = true;
57 }
58 if table_level_unique_includes(body_text, name) {
59 out.unique = true;
60 }
61 if let Some(fk) = table_level_fk(body_text, name) {
62 out.foreign_key = Some(fk);
63 }
64 if let Some(fk) = column_level_references(body_text, name) {
65 out.foreign_key = Some(fk);
66 }
67 out.check_count = table_level_check_count(body_text);
68
69 out
70}
71
72fn column_line_marks_primary(body: &str, col: &str) -> bool {
73 for entry in split_top_level(body) {
74 if first_ident(entry).is_some_and(|i| i.eq_ignore_ascii_case(col)) {
75 let upper = entry.to_ascii_uppercase();
76 if upper.contains("PRIMARY KEY") {
77 return true;
78 }
79 }
80 }
81 false
82}
83
84fn column_line_has_identity(body: &str, col: &str) -> bool {
85 for entry in split_top_level(body) {
86 if first_ident(entry).is_some_and(|i| i.eq_ignore_ascii_case(col)) {
87 let upper = entry.to_ascii_uppercase();
88 if upper.contains("GENERATED") && upper.contains("IDENTITY") {
89 return true;
90 }
91 }
92 }
93 false
94}
95
96fn column_level_references(body: &str, col: &str) -> Option<ForeignKey> {
97 for entry in split_top_level(body) {
98 if !first_ident(entry).is_some_and(|i| i.eq_ignore_ascii_case(col)) {
99 continue;
100 }
101 if let Some(idx) = entry.to_ascii_uppercase().find("REFERENCES") {
102 let after = entry[idx + "REFERENCES".len()..].trim_start();
103 let target = after.split(|c: char| c.is_whitespace() || c == ',' || c == ')').find(|s| !s.is_empty())?;
104 let rest = &after[target.len()..];
106 let ref_col = rest.trim_start().strip_prefix('(').and_then(|s| s.find(')').map(|i| s[..i].to_string()));
107 let suffix = ref_col.map(|c| format!("({c})")).unwrap_or_default();
108 return Some(ForeignKey { references: format!("{target}{suffix}") });
109 }
110 }
111 None
112}
113
114fn table_level_primary_includes(body: &str, col: &str) -> bool {
115 for entry in split_top_level(body) {
116 let upper = entry.to_ascii_uppercase();
117 let is_pk = upper.starts_with("PRIMARY KEY") || (upper.starts_with("CONSTRAINT") && upper.contains("PRIMARY KEY"));
118 if !is_pk {
119 continue;
120 }
121 if extract_paren_names(entry).iter().any(|c| c.eq_ignore_ascii_case(col)) {
122 return true;
123 }
124 }
125 false
126}
127
128fn table_level_unique_includes(body: &str, col: &str) -> bool {
129 for entry in split_top_level(body) {
130 let upper = entry.to_ascii_uppercase();
131 let is_uq = upper.starts_with("UNIQUE")
132 || (upper.starts_with("CONSTRAINT") && upper.contains("UNIQUE") && !upper.contains("PRIMARY"));
133 if !is_uq {
134 continue;
135 }
136 if extract_paren_names(entry).iter().any(|c| c.eq_ignore_ascii_case(col)) {
137 return true;
138 }
139 }
140 false
141}
142
143fn table_level_fk(body: &str, col: &str) -> Option<ForeignKey> {
144 for entry in split_top_level(body) {
145 let upper = entry.to_ascii_uppercase();
146 let is_fk = upper.contains("FOREIGN KEY") && (upper.starts_with("FOREIGN KEY") || upper.starts_with("CONSTRAINT"));
147 if !is_fk {
148 continue;
149 }
150 let cols = extract_paren_names(entry);
152 if !cols.iter().any(|c| c.eq_ignore_ascii_case(col)) {
153 continue;
154 }
155 if let Some(idx) = upper.find("REFERENCES") {
156 let after = entry[idx + "REFERENCES".len()..].trim_start();
157 let target = after.split(|c: char| c.is_whitespace() || c == ',' || c == ')').find(|s| !s.is_empty())?;
158 let rest = &after[target.len()..];
159 let ref_cols = rest.trim_start().strip_prefix('(').and_then(|s| s.find(')').map(|i| s[..i].to_string()));
160 let suffix = ref_cols.map(|c| format!("({c})")).unwrap_or_default();
161 return Some(ForeignKey { references: format!("{target}{suffix}") });
162 }
163 }
164 None
165}
166
167fn table_level_check_count(body: &str) -> usize {
168 split_top_level(body)
169 .iter()
170 .filter(|e| {
171 let u = e.to_ascii_uppercase();
172 u.starts_with("CHECK ") || u.starts_with("CHECK(") || (u.starts_with("CONSTRAINT") && u.contains("CHECK"))
173 })
174 .count()
175}
176
177fn split_top_level(body: &str) -> Vec<&str> {
180 let mut out = Vec::new();
181 let mut start = 0usize;
182 let mut depth: i32 = 0;
183 for (i, ch) in body.char_indices() {
184 match ch {
185 '(' => depth += 1,
186 ')' => depth -= 1,
187 ',' if depth == 0 => {
188 out.push(body[start..i].trim());
189 start = i + 1;
190 },
191 _ => {},
192 }
193 }
194 out.push(body[start..].trim());
195 out
196}
197
198fn first_ident(entry: &str) -> Option<&str> {
199 entry.split(|c: char| c.is_whitespace() || c == '(' || c == ',').find(|s| !s.is_empty()).map(|s| s.trim_matches('"'))
200}
201
202fn extract_paren_names(entry: &str) -> Vec<String> {
203 let open = match entry.find('(') {
204 Some(i) => i,
205 None => return Vec::new(),
206 };
207 let close = match entry[open..].find(')') {
208 Some(i) => open + i,
209 None => return Vec::new(),
210 };
211 entry[open + 1..close].split(',').map(|s| s.trim().trim_matches('"').to_string()).filter(|s| !s.is_empty()).collect()
212}