1use std::collections::HashMap;
4
5use ruprizzle_core::ir::{Model, ScalarType, Schema};
6
7use crate::manifest::{QueryEntry, QueryManifest, SourceLocation};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum QueryCheckError {
17 UnknownTable {
19 sql: String,
21 table: String,
23 suggestion: Option<String>,
25 location: Option<SourceLocation>,
27 },
28 UnknownColumn {
30 sql: String,
32 table: String,
34 column: String,
36 suggestion: Option<String>,
38 location: Option<SourceLocation>,
40 },
41 TypeMismatch {
43 sql: String,
45 column: String,
47 expected: String,
49 received: String,
51 location: Option<SourceLocation>,
53 },
54 NullabilityViolation {
56 sql: String,
58 column: String,
60 table: String,
62 location: Option<SourceLocation>,
64 },
65 StaleSchemaFingerprint {
67 manifest_hash: String,
69 schema_hash: String,
71 },
72}
73
74impl std::fmt::Display for QueryCheckError {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 match self {
77 Self::UnknownTable {
78 sql,
79 table,
80 suggestion,
81 ..
82 } => {
83 write!(f, "unknown table `{table}` in `{sql}`")?;
84 if let Some(sug) = suggestion {
85 write!(f, " (did you mean `{sug}`?)")?;
86 }
87 Ok(())
88 }
89 Self::UnknownColumn {
90 sql,
91 table,
92 column,
93 suggestion,
94 ..
95 } => {
96 write!(f, "unknown column `{column}` on table `{table}` in `{sql}`")?;
97 if let Some(sug) = suggestion {
98 write!(f, " (did you mean `{sug}`?)")?;
99 }
100 Ok(())
101 }
102 Self::TypeMismatch {
103 sql,
104 column,
105 expected,
106 received,
107 ..
108 } => {
109 write!(
110 f,
111 "type mismatch for column `{column}` in `{sql}`: expected `{expected}`, received `{received}`"
112 )
113 }
114 Self::NullabilityViolation {
115 sql, column, table, ..
116 } => {
117 write!(
118 f,
119 "nullability violation on `{table}.{column}` in `{sql}`: non-nullable column received nullable value"
120 )
121 }
122 Self::StaleSchemaFingerprint {
123 manifest_hash,
124 schema_hash,
125 } => {
126 write!(
127 f,
128 "stale query manifest: compiled against schema hash `{manifest_hash}`, current schema hash is `{schema_hash}`"
129 )
130 }
131 }
132 }
133}
134
135impl std::error::Error for QueryCheckError {}
136
137impl QueryCheckError {
138 #[must_use]
140 pub fn location(&self) -> Option<&SourceLocation> {
141 match self {
142 Self::UnknownTable { location, .. }
143 | Self::UnknownColumn { location, .. }
144 | Self::TypeMismatch { location, .. }
145 | Self::NullabilityViolation { location, .. } => location.as_ref(),
146 Self::StaleSchemaFingerprint { .. } => None,
147 }
148 }
149
150 #[must_use]
152 pub fn title(&self) -> &'static str {
153 match self {
154 Self::UnknownTable { .. } => "Unknown Table Reference",
155 Self::UnknownColumn { .. } => "Unknown Column Reference",
156 Self::TypeMismatch { .. } => "Query Parameter Type Mismatch",
157 Self::NullabilityViolation { .. } => "Nullability Constraint Violation",
158 Self::StaleSchemaFingerprint { .. } => "Stale Query Manifest",
159 }
160 }
161}
162
163#[must_use]
165pub fn validate_manifest(schema: &Schema, manifest: &QueryManifest) -> Vec<QueryCheckError> {
166 let mut errors = Vec::new();
167
168 if !manifest.matches_schema(schema) {
169 errors.push(QueryCheckError::StaleSchemaFingerprint {
170 manifest_hash: manifest.schema_hash.clone(),
171 schema_hash: schema.fingerprint(),
172 });
173 }
174
175 for entry in &manifest.queries {
176 errors.extend(validate_query_entry(schema, entry));
177 }
178
179 errors
180}
181
182#[must_use]
184pub fn validate_query_entry(schema: &Schema, entry: &QueryEntry) -> Vec<QueryCheckError> {
185 let mut errors = validate_raw_with_location(schema, &entry.sql, entry.location.as_ref());
186
187 if !entry.params.is_empty() {
189 errors.extend(validate_params(schema, entry));
190 }
191
192 errors
193}
194
195#[must_use]
197pub fn validate_raw(schema: &Schema, sql: &str) -> Vec<QueryCheckError> {
198 validate_raw_with_location(schema, sql, None)
199}
200
201fn validate_raw_with_location(
202 schema: &Schema,
203 sql: &str,
204 location: Option<&SourceLocation>,
205) -> Vec<QueryCheckError> {
206 let mut errors = Vec::new();
207 let tokens = tokenise(sql);
208
209 let table_to_model: HashMap<&str, &Model> = schema
210 .models
211 .values()
212 .map(|m| (m.table.as_str(), m))
213 .collect();
214
215 let all_tables: Vec<&str> = table_to_model.keys().copied().collect();
216
217 for (idx, token) in tokens.iter().enumerate() {
218 if let Some(model) = table_to_model.get(token.as_str()) {
219 if let Some(next) = tokens.get(idx + 1) {
221 if next == "." {
222 if let Some(column) = tokens.get(idx + 2) {
223 if column != "*" && !model.fields.values().any(|f| f.column == *column) {
224 let all_columns: Vec<&str> =
225 model.fields.values().map(|f| f.column.as_str()).collect();
226 let suggestion = find_best_match(column, &all_columns);
227 errors.push(QueryCheckError::UnknownColumn {
228 sql: sql.to_owned(),
229 table: token.to_owned(),
230 column: column.to_owned(),
231 suggestion,
232 location: location.cloned(),
233 });
234 }
235 }
236 }
237 }
238 continue;
239 }
240
241 if tokens.get(idx + 1).is_some_and(|next| next == ".") {
244 continue;
245 }
246
247 if !is_sql_keyword(token)
250 && looks_like_identifier(token)
251 && !table_to_model.contains_key(token.as_str())
252 && idx > 0
253 && is_table_context(&tokens[idx - 1])
254 {
255 let suggestion = find_best_match(token, &all_tables);
256 errors.push(QueryCheckError::UnknownTable {
257 sql: sql.to_owned(),
258 table: token.to_owned(),
259 suggestion,
260 location: location.cloned(),
261 });
262 }
263 }
264
265 errors
266}
267
268fn validate_params(schema: &Schema, entry: &QueryEntry) -> Vec<QueryCheckError> {
269 let mut errors = Vec::new();
270 let tokens = tokenise(&entry.sql);
271
272 let target_model = tokens.iter().enumerate().find_map(|(idx, tok)| {
274 if idx > 0 && is_table_context(&tokens[idx - 1]) {
275 schema
276 .models
277 .values()
278 .find(|m| m.table == *tok || m.name.as_str() == *tok)
279 } else {
280 None
281 }
282 });
283
284 if let Some(model) = target_model {
285 for param in &entry.params {
286 if let Some(name) = ¶m.name {
287 if let Some(field) = model
288 .field(name)
289 .or_else(|| model.fields.values().find(|f| f.column == *name))
290 {
291 let expected_scalar = match &field.kind {
292 ruprizzle_core::ir::FieldKind::Scalar(s) => Some(*s),
293 ruprizzle_core::ir::FieldKind::Enum(_) => Some(ScalarType::String),
294 ruprizzle_core::ir::FieldKind::List(inner) => match inner.as_ref() {
295 ruprizzle_core::ir::FieldKind::Scalar(s) => Some(*s),
296 ruprizzle_core::ir::FieldKind::Enum(_) => Some(ScalarType::String),
297 _ => None,
298 },
299 ruprizzle_core::ir::FieldKind::Relation(_) => None,
300 };
301
302 if let Some(expected) = expected_scalar {
303 if !is_type_compatible(expected, ¶m.expected_type) {
304 errors.push(QueryCheckError::TypeMismatch {
305 sql: entry.sql.clone(),
306 column: field.column.clone(),
307 expected: expected.as_str().to_owned(),
308 received: param.expected_type.clone(),
309 location: entry.location.clone(),
310 });
311 }
312 }
313
314 if !field.optional && param.nullable && field.default.is_none() {
315 errors.push(QueryCheckError::NullabilityViolation {
316 sql: entry.sql.clone(),
317 column: field.column.clone(),
318 table: model.table.clone(),
319 location: entry.location.clone(),
320 });
321 }
322 }
323 }
324 }
325 }
326
327 errors
328}
329
330fn is_type_compatible(scalar: ScalarType, type_name: &str) -> bool {
331 let norm = type_name.trim().to_lowercase();
332 match scalar {
333 ScalarType::Int => matches!(norm.as_str(), "int" | "i32" | "integer" | "i16" | "i8"),
334 ScalarType::BigInt => matches!(norm.as_str(), "bigint" | "i64" | "int" | "i32"),
335 ScalarType::Float => matches!(norm.as_str(), "float" | "f64" | "f32" | "double"),
336 ScalarType::Decimal => matches!(
337 norm.as_str(),
338 "decimal" | "rust_decimal::decimal" | "string" | "str"
339 ),
340 ScalarType::String => matches!(norm.as_str(), "string" | "str" | "&str"),
341 ScalarType::Boolean => matches!(norm.as_str(), "bool" | "boolean"),
342 ScalarType::DateTime => matches!(
343 norm.as_str(),
344 "datetime" | "chrono::datetime<utc>" | "string" | "str"
345 ),
346 ScalarType::Date => matches!(norm.as_str(), "date" | "naivedate" | "string" | "str"),
347 ScalarType::Time => matches!(norm.as_str(), "time" | "naivetime" | "string" | "str"),
348 ScalarType::Uuid => matches!(norm.as_str(), "uuid" | "uuid::uuid" | "string" | "str"),
349 ScalarType::Json => true,
350 ScalarType::Bytes => matches!(norm.as_str(), "bytes" | "vec<u8>" | "&[u8]" | "blob"),
351 ScalarType::Point => matches!(
352 norm.as_str(),
353 "point" | "spatial::point" | "ruprizzle::spatial::point" | "string" | "str"
354 ),
355 ScalarType::Polygon => matches!(
356 norm.as_str(),
357 "polygon" | "spatial::polygon" | "ruprizzle::spatial::polygon" | "string" | "str"
358 ),
359 ScalarType::MultiPolygon => matches!(
360 norm.as_str(),
361 "multipolygon"
362 | "spatial::multipolygon"
363 | "ruprizzle::spatial::multipolygon"
364 | "string"
365 | "str"
366 ),
367 ScalarType::LineString => matches!(
368 norm.as_str(),
369 "linestring"
370 | "spatial::linestring"
371 | "ruprizzle::spatial::linestring"
372 | "string"
373 | "str"
374 ),
375 }
376}
377
378fn tokenise(sql: &str) -> Vec<String> {
379 let mut tokens = Vec::new();
380 let mut current = String::new();
381 let mut in_string = false;
382 let mut string_quote = '\0';
383
384 for c in sql.chars() {
385 if in_string {
386 current.push(c);
387 if c == string_quote {
388 in_string = false;
389 }
390 continue;
391 }
392
393 if c == '\'' || c == '"' {
394 if !current.is_empty() {
395 tokens.push(std::mem::take(&mut current));
396 }
397 in_string = true;
398 string_quote = c;
399 current.push(c);
400 continue;
401 }
402
403 if c.is_alphanumeric() || c == '_' || c == '*' {
404 current.push(c);
405 } else {
406 if !current.is_empty() {
407 tokens.push(std::mem::take(&mut current));
408 }
409 if c == '.' {
410 tokens.push(".".to_owned());
411 }
412 }
413 }
414
415 if !current.is_empty() {
416 tokens.push(current);
417 }
418
419 tokens
420}
421
422fn is_sql_keyword(token: &str) -> bool {
423 const KEYWORDS: &[&str] = &[
424 "SELECT",
425 "FROM",
426 "WHERE",
427 "AND",
428 "OR",
429 "NOT",
430 "INSERT",
431 "UPDATE",
432 "DELETE",
433 "JOIN",
434 "INNER",
435 "LEFT",
436 "RIGHT",
437 "FULL",
438 "OUTER",
439 "ON",
440 "GROUP",
441 "BY",
442 "ORDER",
443 "LIMIT",
444 "OFFSET",
445 "HAVING",
446 "VALUES",
447 "SET",
448 "AS",
449 "WITH",
450 "UNION",
451 "ALL",
452 "DISTINCT",
453 "IS",
454 "NULL",
455 "TRUE",
456 "FALSE",
457 "IN",
458 "BETWEEN",
459 "LIKE",
460 "EXISTS",
461 "CASE",
462 "WHEN",
463 "THEN",
464 "ELSE",
465 "END",
466 "RETURNING",
467 ];
468 KEYWORDS.iter().any(|&k| k == token.to_ascii_uppercase())
469}
470
471fn looks_like_identifier(token: &str) -> bool {
472 token
473 .chars()
474 .next()
475 .is_some_and(|c| c.is_alphabetic() || c == '_' || c == '"')
476}
477
478fn is_table_context(prev: &str) -> bool {
479 matches!(
480 prev.to_ascii_uppercase().as_str(),
481 "FROM" | "JOIN" | "INTO" | "UPDATE" | "TABLE"
482 )
483}
484
485fn find_best_match(candidate: &str, options: &[&str]) -> Option<String> {
486 let mut best: Option<(&str, usize)> = None;
487 for &opt in options {
488 let dist = levenshtein(candidate, opt);
489 if dist <= 3 {
490 if let Some((_, best_dist)) = best {
491 if dist < best_dist {
492 best = Some((opt, dist));
493 }
494 } else {
495 best = Some((opt, dist));
496 }
497 }
498 }
499 best.map(|(opt, _)| opt.to_owned())
500}
501
502fn levenshtein(a: &str, b: &str) -> usize {
503 let a_len = a.chars().count();
504 let b_len = b.chars().count();
505 if a_len == 0 {
506 return b_len;
507 }
508 if b_len == 0 {
509 return a_len;
510 }
511
512 let mut prev_row: Vec<usize> = (0..=b_len).collect();
513 let mut curr_row = vec![0; b_len + 1];
514
515 for (i, ca) in a.chars().enumerate() {
516 curr_row[0] = i + 1;
517 for (j, cb) in b.chars().enumerate() {
518 let cost = usize::from(!ca.eq_ignore_ascii_case(&cb));
519 curr_row[j + 1] = (curr_row[j] + 1)
520 .min(prev_row[j + 1] + 1)
521 .min(prev_row[j] + cost);
522 }
523 prev_row.copy_from_slice(&curr_row);
524 }
525
526 curr_row[b_len]
527}