qail-core 0.27.9

AST-native query builder - type-safe expressions, zero SQL strings
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Semantic Rust analyzer using shared scanner/IR utilities.
//!
//! This module intentionally avoids `syn` so analyzer mode and build mode
//! use one semantic extraction path for QAIL usage and SQL-literal detection.

use std::fs;
use std::path::Path;

use crate::analyzer::{CodeReference, QueryType};

use super::sql_semantics::classify_sql_kind;

/// Rust source analyzer backed by QAIL semantic scanner.
pub struct RustAnalyzer;

impl RustAnalyzer {
    /// Scan a Rust file for QAIL patterns.
    pub fn scan_file(path: &Path) -> Vec<CodeReference> {
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let mut usages = Vec::new();
        crate::build::scanner::scan_file_silent(&path.display().to_string(), &content, &mut usages);

        usages
            .into_iter()
            .map(|usage| CodeReference {
                file: path.to_path_buf(),
                line: usage.line,
                table: usage.table.clone(),
                columns: usage.columns,
                query_type: QueryType::Qail,
                snippet: usage_to_snippet(&usage.action, &usage.table),
            })
            .collect()
    }

    /// Check if this is a Rust project (has Cargo.toml)
    pub fn is_rust_project(path: &Path) -> bool {
        let cargo_toml = if path.is_file() {
            path.parent().map(|p| p.join("Cargo.toml"))
        } else {
            Some(path.join("Cargo.toml"))
        };

        cargo_toml.map(|p| p.exists()).unwrap_or(false)
    }

    /// Scan a directory for Rust files.
    pub fn scan_directory(dir: &Path) -> Vec<CodeReference> {
        let mut refs = Vec::new();
        Self::scan_dir_recursive(dir, &mut refs);
        refs
    }

    fn scan_dir_recursive(dir: &Path, refs: &mut Vec<CodeReference>) {
        let entries = match fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => return,
        };

        for entry in entries.flatten() {
            let path = entry.path();

            if path.is_dir() {
                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if name == "target" || name == ".git" || name == "node_modules" {
                    continue;
                }
                Self::scan_dir_recursive(&path, refs);
            } else if path.extension().is_some_and(|e| e == "rs") {
                refs.extend(Self::scan_file(&path));
            }
        }
    }
}

fn usage_to_snippet(action: &str, table: &str) -> String {
    match action {
        "GET" => format!("Qail::get(\"{}\")", table),
        "ADD" => format!("Qail::add(\"{}\")", table),
        "SET" => format!("Qail::set(\"{}\")", table),
        "DEL" => format!("Qail::del(\"{}\")", table),
        "PUT" => format!("Qail::put(\"{}\")", table),
        "TYPED" => format!("Qail::typed(/* {} */)", table),
        _ => format!("Qail::get(\"{}\")", table),
    }
}

// =============================================================================
// Raw SQL Detection (for VS Code extension)
// =============================================================================

/// A raw SQL statement detected in Rust source code.
#[derive(Debug, Clone)]
pub struct RawSqlMatch {
    /// Line number (1-indexed)
    pub line: usize,
    pub column: usize,
    /// End line number (1-indexed)
    pub end_line: usize,
    /// End column number (0-indexed, exclusive)
    pub end_column: usize,
    /// Type of SQL statement
    pub sql_type: String,
    /// The raw SQL content
    pub raw_sql: String,
    /// Suggested QAIL equivalent
    pub suggested_qail: String,
}

#[derive(Debug, Clone)]
struct StringLiteralMatch {
    start_offset: usize,
    end_offset: usize,
    value: String,
}

/// Detect raw SQL strings in Rust source code.
pub fn detect_raw_sql(source: &str) -> Vec<RawSqlMatch> {
    let line_starts = compute_line_starts(source);
    let literals = scan_rust_string_literals(source);

    let mut out = Vec::new();
    for lit in literals {
        let Some(sql_type) = classify_sql_type(&lit.value) else {
            continue;
        };

        let (line, column) = offset_to_line_col(&line_starts, lit.start_offset);
        let (end_line, end_column) = offset_to_line_col(&line_starts, lit.end_offset);

        out.push(RawSqlMatch {
            line,
            column,
            end_line,
            end_column,
            sql_type: sql_type.to_string(),
            raw_sql: lit.value.clone(),
            suggested_qail: super::transformer::sql_to_qail(&lit.value)
                .unwrap_or_else(|_| "// Could not parse SQL".to_string()),
        });
    }

    out
}

/// Detect raw SQL strings in a file by path.
pub fn detect_raw_sql_in_file(path: &Path) -> Vec<RawSqlMatch> {
    match fs::read_to_string(path) {
        Ok(source) => detect_raw_sql(&source),
        Err(_) => Vec::new(),
    }
}

fn compute_line_starts(source: &str) -> Vec<usize> {
    let mut starts = Vec::with_capacity(source.lines().count() + 1);
    starts.push(0);
    for (idx, b) in source.bytes().enumerate() {
        if b == b'\n' {
            starts.push(idx + 1);
        }
    }
    starts
}

fn offset_to_line_col(line_starts: &[usize], offset: usize) -> (usize, usize) {
    let idx = line_starts.partition_point(|&start| start <= offset);
    let line_idx = idx.saturating_sub(1);
    let line_start = line_starts.get(line_idx).copied().unwrap_or(0);
    (line_idx + 1, offset.saturating_sub(line_start))
}

fn classify_sql_type(value: &str) -> Option<&'static str> {
    classify_sql_kind(value).map(|kind| kind.as_str())
}

fn scan_rust_string_literals(source: &str) -> Vec<StringLiteralMatch> {
    let bytes = source.as_bytes();
    let mut out = Vec::new();
    let mut i = 0usize;

    while i < bytes.len() {
        if starts_with(bytes, i, b"//") {
            i += 2;
            while i < bytes.len() && bytes[i] != b'\n' {
                i += 1;
            }
            continue;
        }

        if starts_with(bytes, i, b"/*") {
            i += 2;
            let mut depth = 1usize;
            while i < bytes.len() && depth > 0 {
                if starts_with(bytes, i, b"/*") {
                    depth += 1;
                    i += 2;
                } else if starts_with(bytes, i, b"*/") {
                    depth = depth.saturating_sub(1);
                    i += 2;
                } else {
                    i += 1;
                }
            }
            continue;
        }

        if let Some((prefix_start, content_start, hashes)) = raw_string_prefix(bytes, i) {
            if let Some(end_quote) = find_raw_string_end(bytes, content_start, hashes) {
                let end_offset = end_quote + 1 + hashes;
                if let Some(raw) = source.get(content_start..end_quote) {
                    out.push(StringLiteralMatch {
                        start_offset: prefix_start,
                        end_offset,
                        value: raw.to_string(),
                    });
                }
                i = end_offset;
                continue;
            }
            break;
        }

        if bytes[i] == b'"' || starts_with(bytes, i, b"b\"") {
            let start_offset = i;
            let quote_offset = if bytes[i] == b'"' { i } else { i + 1 };
            let mut j = quote_offset + 1;

            while j < bytes.len() {
                if bytes[j] == b'\\' {
                    j = (j + 2).min(bytes.len());
                    continue;
                }
                if bytes[j] == b'"' {
                    let end_offset = j + 1;
                    if let Some(raw) = source.get(quote_offset + 1..j) {
                        out.push(StringLiteralMatch {
                            start_offset,
                            end_offset,
                            value: unescape_rust_string(raw),
                        });
                    }
                    i = end_offset;
                    break;
                }
                j += 1;
            }

            if j >= bytes.len() {
                break;
            }
            continue;
        }

        if bytes[i] == b'\'' {
            i += 1;
            while i < bytes.len() {
                if bytes[i] == b'\\' {
                    i = (i + 2).min(bytes.len());
                    continue;
                }
                if bytes[i] == b'\'' {
                    i += 1;
                    break;
                }
                i += 1;
            }
            continue;
        }

        i += 1;
    }

    out
}

fn starts_with(haystack: &[u8], idx: usize, needle: &[u8]) -> bool {
    haystack
        .get(idx..idx.saturating_add(needle.len()))
        .is_some_and(|s| s == needle)
}

fn raw_string_prefix(bytes: &[u8], idx: usize) -> Option<(usize, usize, usize)> {
    if bytes.get(idx).copied() == Some(b'r') {
        let mut j = idx + 1;
        while bytes.get(j).copied() == Some(b'#') {
            j += 1;
        }
        if bytes.get(j).copied() == Some(b'"') {
            let hashes = j - (idx + 1);
            return Some((idx, j + 1, hashes));
        }
        return None;
    }

    if bytes.get(idx).copied() == Some(b'b') && bytes.get(idx + 1).copied() == Some(b'r') {
        let mut j = idx + 2;
        while bytes.get(j).copied() == Some(b'#') {
            j += 1;
        }
        if bytes.get(j).copied() == Some(b'"') {
            let hashes = j - (idx + 2);
            return Some((idx, j + 1, hashes));
        }
    }

    None
}

fn find_raw_string_end(bytes: &[u8], mut idx: usize, hashes: usize) -> Option<usize> {
    while idx < bytes.len() {
        if bytes[idx] == b'"' {
            let mut ok = true;
            for off in 0..hashes {
                if bytes.get(idx + 1 + off).copied() != Some(b'#') {
                    ok = false;
                    break;
                }
            }
            if ok {
                return Some(idx);
            }
        }
        idx += 1;
    }
    None
}

fn unescape_rust_string(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut chars = raw.chars();

    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }

        match chars.next() {
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('0') => out.push('\0'),
            Some('"') => out.push('"'),
            Some('\\') => out.push('\\'),
            Some('x') => {
                let h1 = chars.next();
                let h2 = chars.next();
                if let (Some(a), Some(b)) = (h1, h2)
                    && let (Some(ha), Some(hb)) = (a.to_digit(16), b.to_digit(16))
                    && let Some(decoded) = char::from_u32((ha * 16) + hb)
                {
                    out.push(decoded);
                    continue;
                }
                out.push('\\');
                out.push('x');
                if let Some(a) = h1 {
                    out.push(a);
                }
                if let Some(b) = h2 {
                    out.push(b);
                }
            }
            Some(other) => {
                // Keep unknown escapes stable for downstream SQL parsing.
                out.push('\\');
                out.push(other);
            }
            None => out.push('\\'),
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_qail_scan_file() {
        let tmp_name = format!(
            "qail_detector_test_{}_{}.rs",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(tmp_name);

        let code = r#"
            fn query() {
                let cmd = Qail::get("users")
                    .filter("status", Operator::Eq, "active")
                    .columns(["id", "name", "email"]);
            }
        "#;

        fs::write(&path, code).expect("write temp rust file");
        let refs = RustAnalyzer::scan_file(&path);
        let _ = fs::remove_file(&path);

        assert!(!refs.is_empty());
        assert!(refs.iter().any(|r| r.table == "users"));
        assert!(
            refs.iter()
                .any(|r| r.columns.contains(&"status".to_string()))
        );
    }

    #[test]
    fn test_detect_raw_sql() {
        let code = r#"
            fn query() {
                let sql = "SELECT id, name FROM users WHERE status = 'active'";
                query(sql);
            }
        "#;

        let matches = detect_raw_sql(code);
        assert!(!matches.is_empty());
        assert_eq!(matches[0].sql_type, "SELECT");
        assert!(matches[0].suggested_qail.contains("Qail::get"));
    }

    #[test]
    fn test_detect_raw_multiline_cte_sql() {
        let code = r##"
            fn get_insights() {
                let sql = r#"
                    WITH stats AS (
                        SELECT COUNT(*) FILTER (WHERE direction = 'outbound'
                        AND created_at > NOW() - INTERVAL '24 hours') AS sent
                        FROM messages
                    )
                    SELECT sent FROM stats
                "#;
            }
        "##;

        let matches = detect_raw_sql(code);
        assert!(!matches.is_empty());

        let qail = &matches[0].suggested_qail;
        assert!(
            qail.contains("CTE 'stats'") || qail.contains("stats_cte"),
            "Should generate CTE variable: {}",
            qail
        );
        assert!(
            qail.contains("messages"),
            "Should find source table 'messages': {}",
            qail
        );
    }

    #[test]
    fn ignores_sql_in_comments() {
        let code = r#"
            // SELECT id FROM users
            /*
              DELETE FROM sessions
            */
            fn ok() {
                let msg = "just text";
            }
        "#;

        let matches = detect_raw_sql(code);
        assert!(matches.is_empty(), "matches: {matches:?}");
    }
}