Skip to main content

scythe_core/parser/
mod.rs

1use sqlparser::parser::Parser;
2
3use crate::dialect::SqlDialect;
4use crate::errors::ScytheError;
5
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum QueryCommand {
9    One,
10    Opt,
11    Many,
12    #[default]
13    Exec,
14    ExecResult,
15    ExecRows,
16    Batch,
17    Grouped,
18}
19
20impl std::fmt::Display for QueryCommand {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            QueryCommand::One => write!(f, "one"),
24            QueryCommand::Opt => write!(f, "opt"),
25            QueryCommand::Many => write!(f, "many"),
26            QueryCommand::Exec => write!(f, "exec"),
27            QueryCommand::ExecResult => write!(f, "exec_result"),
28            QueryCommand::ExecRows => write!(f, "exec_rows"),
29            QueryCommand::Batch => write!(f, "batch"),
30            QueryCommand::Grouped => write!(f, "grouped"),
31        }
32    }
33}
34
35impl QueryCommand {
36    fn from_str(s: &str) -> Result<Self, ScytheError> {
37        match s {
38            "one" => Ok(QueryCommand::One),
39            "opt" => Ok(QueryCommand::Opt),
40            "many" => Ok(QueryCommand::Many),
41            "exec" => Ok(QueryCommand::Exec),
42            "exec_result" => Ok(QueryCommand::ExecResult),
43            "exec_rows" => Ok(QueryCommand::ExecRows),
44            "batch" => Ok(QueryCommand::Batch),
45            "grouped" => Ok(QueryCommand::Grouped),
46            other => Err(ScytheError::invalid_annotation(format!(
47                "invalid @returns value: {other}"
48            ))),
49        }
50    }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55pub struct ParamDoc {
56    pub name: String,
57    pub description: String,
58}
59
60/// An explicit `-- @param $N name[: description]` annotation that binds a
61/// position number to a human-chosen parameter name, overriding the `pN`
62/// fallback name that the analyzer would otherwise infer.
63///
64/// The positional form (`$N` as first token) is distinct from the existing
65/// docs-only `-- @param name: description` form, which is preserved unchanged
66/// for backward compatibility.
67#[derive(Debug, Clone, PartialEq, Eq)]
68#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
69pub struct PositionalParamDoc {
70    /// 1-based parameter position (`$N`).
71    pub position: i64,
72    /// Caller-chosen name that replaces the `pN` fallback.
73    pub name: String,
74    /// Optional description (everything after the `:` separator).
75    pub description: String,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
80pub struct JsonMapping {
81    pub column: String,
82    pub rust_type: String,
83}
84
85/// A custom (non-native) annotation captured verbatim from the SQL source.
86///
87/// Scythe parses its known annotations (`@name`, `@returns`, `@param`, `@nullable`,
88/// `@nonnull`, `@json`, `@optional`, `@group_by`, `@deprecated`, `@type`) into typed fields.
89/// `@type` is captured here as a custom annotation and applied by the analyzer, rather than
90/// adding a field every downstream `Annotations { .. }` literal would have to spell out.
91/// Any other `-- @<name> <value>` line is captured here as an opaque triple and
92/// exposed to crate consumers, who can layer their own annotation vocabulary on
93/// top of scythe without coupling scythe to their domain.
94///
95/// That escape hatch means an unrecognised annotation can never be a hard parse
96/// error -- rejecting it outright would break every legitimate consumer-defined
97/// annotation (e.g. `@http`, `@http_auth`) alongside the typos it was meant to
98/// catch. [`suggested_keyword`](Self::suggested_keyword) is the softer signal:
99/// it flags names close enough to a known keyword to plausibly be a typo of it
100/// (`@nullible` for `@nullable`, `@optionall` for `@optional`), for a caller to
101/// surface as a warning without duplicating scythe's keyword list or edit-distance
102/// logic. See #152 -- before this field existed, a misspelled `@nullable` /
103/// `@nonnull` / `@optional` was captured here and never inspected by anything,
104/// so `scythe generate`, `scythe check` and `scythe lint` all reported success
105/// while the override it named was silently discarded.
106#[derive(Debug, Clone, PartialEq, Eq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub struct CustomAnnotation {
109    /// Annotation name, lowercased, without the leading `@` (e.g. `http`, `http_param`).
110    pub name: String,
111    /// Everything after the name on the line, trimmed. Empty if the annotation had no value.
112    pub value: String,
113    /// 1-based line number within the query SQL, for diagnostics.
114    pub line: usize,
115    /// A known annotation keyword within edit distance 2 of `name`, if any -- e.g.
116    /// `Some("nullable".to_string())` for `nullible`. `None` when `name` is not close to
117    /// any known keyword (the common case: a genuine consumer-defined annotation). An owned
118    /// `String` rather than `&'static str` so the type stays trivially `Deserialize` (a
119    /// borrowed-forever `&'static str` field cannot round-trip through an arbitrary
120    /// deserializer's input lifetime).
121    #[cfg_attr(feature = "serde", serde(default))]
122    pub suggested_keyword: Option<String>,
123}
124
125/// The annotation keywords [`parse_query_with_dialect`] recognises natively. Anything else
126/// becomes a [`CustomAnnotation`]; [`suggest_known_keyword`] checks a rejected name against
127/// this list to flag likely typos.
128const KNOWN_ANNOTATION_KEYWORDS: &[&str] = &[
129    "name",
130    "returns",
131    "param",
132    "nullable",
133    "nonnull",
134    "json",
135    "deprecated",
136    "group_by",
137    "optional",
138    "type",
139];
140
141/// Maximum Levenshtein edit distance at which an unrecognised annotation name is flagged as a
142/// likely typo of a known keyword. Matches the threshold `scythe-codegen::backend_options` and
143/// `scythe-backend::manifest` already use for "did you mean" suggestions on unknown option/type
144/// keys -- close enough to catch `nullible` -> `nullable` or `optionall` -> `optional` without
145/// false-positiving on a genuinely unrelated custom annotation name.
146const ANNOTATION_TYPO_DISTANCE_THRESHOLD: usize = 2;
147
148/// Suggest a known annotation keyword for an unrecognised annotation `name`, if one is within
149/// [`ANNOTATION_TYPO_DISTANCE_THRESHOLD`] edits.
150fn suggest_known_keyword(name: &str) -> Option<&'static str> {
151    KNOWN_ANNOTATION_KEYWORDS
152        .iter()
153        .map(|&candidate| (candidate, annotation_levenshtein_distance(name, candidate)))
154        .filter(|&(_, distance)| distance <= ANNOTATION_TYPO_DISTANCE_THRESHOLD)
155        .min_by_key(|&(_, distance)| distance)
156        .map(|(candidate, _)| candidate)
157}
158
159/// Levenshtein edit distance between two strings, used by [`suggest_known_keyword`].
160fn annotation_levenshtein_distance(a: &str, b: &str) -> usize {
161    let a: Vec<char> = a.chars().collect();
162    let b: Vec<char> = b.chars().collect();
163
164    let mut prev_row: Vec<usize> = (0..=b.len()).collect();
165    let mut curr_row = vec![0usize; b.len() + 1];
166
167    for (i, &char_a) in a.iter().enumerate() {
168        curr_row[0] = i + 1;
169        for (j, &char_b) in b.iter().enumerate() {
170            let substitution_cost = usize::from(char_a != char_b);
171            curr_row[j + 1] = (prev_row[j + 1] + 1)
172                .min(curr_row[j] + 1)
173                .min(prev_row[j] + substitution_cost);
174        }
175        std::mem::swap(&mut prev_row, &mut curr_row);
176    }
177
178    prev_row[b.len()]
179}
180
181#[derive(Debug, Clone, Default, PartialEq, Eq)]
182#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
183pub struct Annotations {
184    pub name: String,
185    pub command: QueryCommand,
186    pub param_docs: Vec<ParamDoc>,
187    pub nullable_overrides: Vec<String>,
188    pub nonnull_overrides: Vec<String>,
189    pub json_mappings: Vec<JsonMapping>,
190    pub deprecated: Option<String>,
191    pub optional_params: Vec<String>,
192    pub group_by: Option<String>,
193    /// Explicit `-- @param $N name[: description]` annotations that override
194    /// the inferred or fallback `pN` name for a specific positional parameter.
195    #[cfg_attr(feature = "serde", serde(default))]
196    pub positional_param_docs: Vec<PositionalParamDoc>,
197    /// Annotations scythe does not natively recognise, preserved in source order
198    /// for crate consumers to interpret.
199    pub custom: Vec<CustomAnnotation>,
200}
201
202#[derive(Debug)]
203pub struct Query {
204    pub name: String,
205    pub command: QueryCommand,
206    pub sql: String,
207    pub stmt: sqlparser::ast::Statement,
208    pub annotations: Annotations,
209}
210
211/// Reject an `@name` value that cannot become an identifier in generated
212/// code.
213///
214/// Every backend uses this value verbatim (after case conversion) as the
215/// generated function's name and as the stem of its row type, so anything
216/// that is not an identifier produces a file that does not compile -- and
217/// says so nowhere. `-- @name` with no value was accepted outright until
218/// #174: it emitted `async def (conn):` in Python and collapsed the row type
219/// to a bare `Row` that collides with every other unnamed query in the file,
220/// at exit code 0.
221///
222/// The accepted set is deliberately the intersection every target language
223/// can spell: an ASCII letter or `_` followed by ASCII letters, digits and
224/// `_`. A dot, dash, space or quote in the value is a mistake in every one of
225/// them.
226fn validate_query_name(name: &str) -> Result<(), ScytheError> {
227    if name.is_empty() {
228        return Err(ScytheError::invalid_annotation(
229            "@name requires a value (e.g. `-- @name GetUser`)",
230        ));
231    }
232
233    let mut chars = name.chars();
234    let first = chars.next().expect("name is non-empty");
235    if !first.is_ascii_alphabetic() && first != '_' {
236        return Err(ScytheError::invalid_annotation(format!(
237            "@name \"{name}\" must start with an ASCII letter or underscore to be a valid \
238             identifier in generated code"
239        )));
240    }
241    if let Some(invalid) = chars.find(|c| !c.is_ascii_alphanumeric() && *c != '_') {
242        return Err(ScytheError::invalid_annotation(format!(
243            "@name \"{name}\" contains '{invalid}'; only ASCII letters, digits and underscores \
244             are valid in generated code"
245        )));
246    }
247
248    Ok(())
249}
250
251/// Parse a single annotated SQL query into a `Query` using the PostgreSQL dialect.
252pub fn parse_query(query_sql: &str) -> Result<Query, ScytheError> {
253    parse_query_with_dialect(query_sql, &SqlDialect::PostgreSQL)
254}
255
256/// Parse a single annotated SQL query into a `Query` using the specified dialect.
257pub fn parse_query_with_dialect(query_sql: &str, dialect: &SqlDialect) -> Result<Query, ScytheError> {
258    let mut name: Option<String> = None;
259    let mut command: Option<QueryCommand> = None;
260    let mut param_docs = Vec::new();
261    let mut positional_param_docs: Vec<PositionalParamDoc> = Vec::new();
262    let mut nullable_overrides = Vec::new();
263    let mut nonnull_overrides = Vec::new();
264    let mut json_mappings = Vec::new();
265    let mut deprecated: Option<String> = None;
266    let mut optional_params = Vec::new();
267    let mut group_by: Option<String> = None;
268    let mut custom: Vec<CustomAnnotation> = Vec::new();
269
270    let mut sql_lines = Vec::new();
271
272    for (line_idx, line) in query_sql.lines().enumerate() {
273        let line_no = line_idx + 1;
274        let trimmed = line.trim();
275
276        let annotation_body = if let Some(rest) = trimmed.strip_prefix("--") {
277            let rest = rest.trim_start();
278            rest.strip_prefix('@')
279        } else {
280            None
281        };
282
283        if let Some(body) = annotation_body {
284            let (keyword, value) = match body.find(|c: char| c.is_whitespace()) {
285                Some(pos) => (&body[..pos], body[pos..].trim()),
286                None => (body, ""),
287            };
288
289            match keyword.to_ascii_lowercase().as_str() {
290                "name" => {
291                    name = Some(value.to_string());
292                }
293                "returns" => {
294                    let cmd_str = value.strip_prefix(':').unwrap_or(value);
295                    command = Some(QueryCommand::from_str(cmd_str)?);
296                }
297                "param" => {
298                    //   Positional: -- @param $N name[: description]
299                    //   Docs-only:  -- @param name[: description]
300                    let first_end = value.find(|c: char| c.is_whitespace());
301                    let first_token = first_end.map(|p| &value[..p]).unwrap_or(value);
302
303                    if let Some(digits) = first_token.strip_prefix('$')
304                        && let Ok(pos) = digits.parse::<i64>()
305                        && pos > 0
306                    {
307                        let rest = first_end.map(|p| value[p..].trim()).unwrap_or("").trim();
308                        if !rest.is_empty() {
309                            let (param_name, description) = if let Some(colon_pos) = rest.find(':') {
310                                (
311                                    rest[..colon_pos].trim().to_string(),
312                                    rest[colon_pos + 1..].trim().to_string(),
313                                )
314                            } else {
315                                (rest.to_string(), String::new())
316                            };
317                            if !param_name.is_empty() {
318                                positional_param_docs.push(PositionalParamDoc {
319                                    position: pos,
320                                    name: param_name,
321                                    description,
322                                });
323                            }
324                        }
325                    } else {
326                        if let Some(colon_pos) = value.find(':') {
327                            let param_name = value[..colon_pos].trim().to_string();
328                            let description = value[colon_pos + 1..].trim().to_string();
329                            param_docs.push(ParamDoc {
330                                name: param_name,
331                                description,
332                            });
333                        } else {
334                            param_docs.push(ParamDoc {
335                                name: value.to_string(),
336                                description: String::new(),
337                            });
338                        }
339                    }
340                }
341                "nullable" => {
342                    for col in value.split(',') {
343                        let col = col.trim();
344                        if !col.is_empty() {
345                            nullable_overrides.push(col.to_string());
346                        }
347                    }
348                }
349                "nonnull" => {
350                    for col in value.split(',') {
351                        let col = col.trim();
352                        if !col.is_empty() {
353                            nonnull_overrides.push(col.to_string());
354                        }
355                    }
356                }
357                "json" => {
358                    if let Some(eq_pos) = value.find('=') {
359                        let column = value[..eq_pos].trim().to_string();
360                        let rust_type = value[eq_pos + 1..].trim().to_string();
361                        json_mappings.push(JsonMapping { column, rust_type });
362                    }
363                }
364                "deprecated" => {
365                    deprecated = Some(value.to_string());
366                }
367                "group_by" => {
368                    group_by = Some(value.to_string());
369                }
370                "optional" => {
371                    for param in value.split(',') {
372                        let param = param.trim();
373                        if !param.is_empty() {
374                            optional_params.push(param.to_string());
375                        }
376                    }
377                }
378                other => {
379                    custom.push(CustomAnnotation {
380                        name: other.to_string(),
381                        value: value.to_string(),
382                        line: line_no,
383                        suggested_keyword: suggest_known_keyword(other).map(str::to_string),
384                    });
385                }
386            }
387        } else {
388            sql_lines.push(line);
389        }
390    }
391
392    let name = name.ok_or_else(|| ScytheError::missing_annotation("name"))?;
393    validate_query_name(&name)?;
394    let command = command.ok_or_else(|| ScytheError::missing_annotation("returns"))?;
395
396    if command == QueryCommand::Grouped && group_by.is_none() {
397        return Err(ScytheError::invalid_annotation(
398            "@returns :grouped requires a @group_by annotation (e.g. @group_by users.id)",
399        ));
400    }
401
402    let sql = sql_lines.join("\n").trim().to_string();
403
404    if sql.is_empty() {
405        return Err(ScytheError::syntax("empty SQL body"));
406    }
407
408    let (sql, parse_sql) = if *dialect == SqlDialect::Oracle {
409        let processed = preprocess_oracle_sql(&sql);
410        (processed.clone(), processed)
411    } else if *dialect == SqlDialect::MsSql {
412        let codegen_sql = convert_mssql_placeholders(&sql);
413        let parse_sql = preprocess_mssql_sql(&sql);
414        (codegen_sql, parse_sql)
415    } else if *dialect == SqlDialect::PostgreSQL {
416        let parse_sql = preprocess_postgres_sql(&sql);
417        (sql.clone(), parse_sql)
418    } else {
419        (sql.clone(), sql)
420    };
421
422    let parser_dialect = dialect.to_sqlparser_dialect();
423    let statements = Parser::parse_sql(parser_dialect.as_ref(), &parse_sql)
424        .map_err(|e| ScytheError::syntax(format!("syntax error: {}", e)))?;
425
426    if statements.len() != 1 {
427        let non_empty: Vec<_> = statements
428            .into_iter()
429            .filter(|s| !matches!(s, sqlparser::ast::Statement::Flush { .. }) && format!("{s}") != "")
430            .collect();
431        if non_empty.len() != 1 {
432            return Err(ScytheError::syntax("expected exactly one SQL statement"));
433        }
434        let stmt = non_empty.into_iter().next().expect("filtered to exactly one statement");
435        let annotations = Annotations {
436            name: name.clone(),
437            command: command.clone(),
438            param_docs,
439            positional_param_docs: positional_param_docs.clone(),
440            nullable_overrides,
441            nonnull_overrides,
442            json_mappings,
443            deprecated,
444            optional_params,
445            group_by: group_by.clone(),
446            custom,
447        };
448        return Ok(Query {
449            name,
450            command,
451            sql,
452            stmt,
453            annotations,
454        });
455    }
456
457    let stmt = statements
458        .into_iter()
459        .next()
460        .expect("filtered to exactly one statement");
461
462    let annotations = Annotations {
463        name: name.clone(),
464        command: command.clone(),
465        param_docs,
466        positional_param_docs,
467        nullable_overrides,
468        nonnull_overrides,
469        json_mappings,
470        deprecated,
471        optional_params,
472        group_by,
473        custom,
474    };
475
476    Ok(Query {
477        name,
478        command,
479        sql,
480        stmt,
481        annotations,
482    })
483}
484
485/// Strip the `WHERE …` predicate that PostgreSQL allows between
486/// `ON CONFLICT (cols)` and `DO …` (the index-inference form for partial
487/// unique indexes). sqlparser-rs through 0.61 does not parse this construct;
488/// we lift it out for the parser and let the caller keep the original SQL
489/// for codegen + runtime, where Postgres validates it.
490fn preprocess_postgres_sql(sql: &str) -> String {
491    let mask = mask_postgres_for_scan(sql);
492    let mask_bytes = mask.as_bytes();
493    let bytes = sql.as_bytes();
494    let mut search_from = 0;
495    let mut result = String::with_capacity(sql.len());
496    let mut last = 0;
497    while let Some(rel) = find_keyword(&mask[search_from..], "ON CONFLICT") {
498        let on_conflict_pos = search_from + rel;
499        let after_on_conflict = on_conflict_pos + "ON CONFLICT".len();
500        let mut idx = after_on_conflict;
501        while idx < mask_bytes.len() && mask_bytes[idx].is_ascii_whitespace() {
502            idx += 1;
503        }
504        if idx >= mask_bytes.len() || mask_bytes[idx] != b'(' {
505            search_from = after_on_conflict;
506            continue;
507        }
508        let mut depth = 0i32;
509        let mut close = idx;
510        while close < mask_bytes.len() {
511            match mask_bytes[close] {
512                b'(' => depth += 1,
513                b')' => {
514                    depth -= 1;
515                    if depth == 0 {
516                        break;
517                    }
518                }
519                _ => {}
520            }
521            close += 1;
522        }
523        if depth != 0 {
524            return sql.to_string();
525        }
526        let mut after_cols = close + 1;
527        while after_cols < mask_bytes.len() && mask_bytes[after_cols].is_ascii_whitespace() {
528            after_cols += 1;
529        }
530        if mask[after_cols..].starts_with("WHERE")
531            && let Some(do_rel) = find_keyword(&mask[after_cols + "WHERE".len()..], "DO")
532        {
533            let do_abs = after_cols + "WHERE".len() + do_rel;
534            result.push_str(std::str::from_utf8(&bytes[last..after_cols]).unwrap_or(""));
535            last = do_abs;
536            search_from = do_abs;
537            continue;
538        }
539        search_from = close + 1;
540    }
541    result.push_str(std::str::from_utf8(&bytes[last..]).unwrap_or(""));
542    result
543}
544
545/// Build an ASCII-uppercase, fixed-byte-offset mask of `sql` where `--` line
546/// comments, `/* … */` block comments, and `'…'` / `$$…$$` string literals are
547/// replaced with spaces. Multi-byte UTF-8 is collapsed to ASCII spaces of the
548/// same byte length so positions in the mask line up with the original `sql`.
549fn mask_postgres_for_scan(sql: &str) -> String {
550    let bytes = sql.as_bytes();
551    let mut out = vec![b' '; bytes.len()];
552    let mut i = 0;
553    while i < bytes.len() {
554        let b = bytes[i];
555        if b == b'-' && i + 1 < bytes.len() && bytes[i + 1] == b'-' {
556            while i < bytes.len() && bytes[i] != b'\n' {
557                out[i] = b' ';
558                i += 1;
559            }
560            continue;
561        }
562        if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
563            out[i] = b' ';
564            out[i + 1] = b' ';
565            i += 2;
566            while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
567                out[i] = b' ';
568                i += 1;
569            }
570            if i + 1 < bytes.len() {
571                out[i] = b' ';
572                out[i + 1] = b' ';
573                i += 2;
574            }
575            continue;
576        }
577        if b == b'\'' {
578            out[i] = b' ';
579            i += 1;
580            while i < bytes.len() {
581                if bytes[i] == b'\'' {
582                    if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
583                        out[i] = b' ';
584                        out[i + 1] = b' ';
585                        i += 2;
586                        continue;
587                    }
588                    out[i] = b' ';
589                    i += 1;
590                    break;
591                }
592                out[i] = b' ';
593                i += 1;
594            }
595            continue;
596        }
597        if b.is_ascii() {
598            out[i] = b.to_ascii_uppercase();
599        } else {
600            out[i] = b' ';
601        }
602        i += 1;
603    }
604    String::from_utf8(out).expect("mask is ASCII by construction")
605}
606
607/// Locate a whitespace-separated keyword in an uppercase haystack. Returns the
608/// byte offset of the keyword's start, or None if not found.
609fn find_keyword(haystack: &str, keyword: &str) -> Option<usize> {
610    let bytes = haystack.as_bytes();
611    let key = keyword.as_bytes();
612    let mut i = 0;
613    while i + key.len() <= bytes.len() {
614        if &bytes[i..i + key.len()] == key {
615            let prev_ok = i == 0 || !bytes[i - 1].is_ascii_alphanumeric();
616            let next = i + key.len();
617            let next_ok = next >= bytes.len() || !bytes[next].is_ascii_alphanumeric();
618            if prev_ok && next_ok {
619                return Some(i);
620            }
621        }
622        i += 1;
623    }
624    None
625}
626
627/// Preprocess Oracle SQL before parsing:
628/// 1. Strip `INTO :N, :N, ...` suffix from `RETURNING ... INTO` clauses.
629/// 2. Convert `:N` positional placeholders to `$N`, preserving the declared
630///    position (#149).
631///
632/// `$N`, not bare `?`: collapsing every `:N` to the same `?` spelling
633/// discarded which N a repeated (`:1 ... :1`) or out-of-order
634/// (`:2` before `:1`) placeholder referred to, so a backend binding by SQL
635/// occurrence order could no longer recover the caller's intended argument
636/// -- a repeated placeholder produced too few binds (runtime error) and an
637/// out-of-order one silently bound the wrong argument to the wrong slot.
638/// `$N` is safe to emit here for two independent reasons: sqlparser's
639/// tokenizer accepts `$<digits>` as `Token::Placeholder` under the default
640/// `Dialect` impl that `OracleDialect` inherits (verified by inspecting
641/// `tokenize_dollar_preceded_value` in sqlparser 0.62's `tokenizer.rs`: a
642/// `$`-prefixed all-digit run with no following `$` always falls through to
643/// `Token::Placeholder(format!("${value}"))`), and the downstream SQL-text
644/// pipeline (`rewrite_placeholders_indexed` in scythe-codegen) already
645/// treats Oracle and PostgreSQL identically as "`$N`-style" dialects.
646fn preprocess_oracle_sql(sql: &str) -> String {
647    let sql = strip_returning_into(sql);
648
649    let mut result = String::with_capacity(sql.len());
650    let mut chars = sql.chars().peekable();
651    while let Some(ch) = chars.next() {
652        if ch == '\'' {
653            result.push(ch);
654            while let Some(inner) = chars.next() {
655                result.push(inner);
656                if inner == '\'' {
657                    if chars.peek() == Some(&'\'') {
658                        result.push(chars.next().unwrap());
659                    } else {
660                        break;
661                    }
662                }
663            }
664        } else if ch == ':' && chars.peek().is_some_and(|c| c.is_ascii_digit()) {
665            result.push('$');
666            while chars.peek().is_some_and(|c| c.is_ascii_digit()) {
667                result.push(chars.next().unwrap());
668            }
669        } else {
670            result.push(ch);
671        }
672    }
673    result
674}
675
676/// Convert MSSQL `@pN` positional placeholders to `$N` (outside string
677/// literals), preserving the declared position (#149) instead of collapsing
678/// every occurrence to bare `?` -- see [`preprocess_oracle_sql`]'s doc
679/// comment for why `$N` and not `?`, and why it is safe to hand sqlparser's
680/// `MsSqlDialect` (which, like `OracleDialect`, inherits the default
681/// `Dialect::supports_dollar_placeholder` impl that makes `$N` tokenize as
682/// `Token::Placeholder`). MsSqlDialect treats bare `@` as an identifier
683/// start, so `@p1` would otherwise become an identifier rather than a
684/// `Placeholder` token.
685fn convert_mssql_placeholders(sql: &str) -> String {
686    let mut result = String::with_capacity(sql.len());
687    let mut chars = sql.chars().peekable();
688    while let Some(ch) = chars.next() {
689        if ch == '\'' {
690            result.push(ch);
691            while let Some(inner) = chars.next() {
692                result.push(inner);
693                if inner == '\'' {
694                    if chars.peek() == Some(&'\'') {
695                        result.push(chars.next().unwrap());
696                    } else {
697                        break;
698                    }
699                }
700            }
701        } else if ch == '@' && chars.peek().is_some_and(|c| *c == 'p' || *c == 'P') {
702            let mut lookahead = chars.clone();
703            lookahead.next();
704            if lookahead.peek().is_some_and(|c| c.is_ascii_digit()) {
705                chars.next();
706                result.push('$');
707                while chars.peek().is_some_and(|c| c.is_ascii_digit()) {
708                    result.push(chars.next().unwrap());
709                }
710            } else {
711                result.push(ch);
712            }
713        } else {
714            result.push(ch);
715        }
716    }
717    result
718}
719
720/// Preprocess MSSQL SQL before parsing:
721/// 1. Strip `OUTPUT INSERTED.col, ...` clauses and convert to RETURNING
722/// 2. Convert `@pN` positional placeholders to `$N` (see
723///    [`convert_mssql_placeholders`])
724fn preprocess_mssql_sql(sql: &str) -> String {
725    let sql = strip_and_convert_mssql_output(sql);
726    convert_mssql_placeholders(&sql)
727}
728
729/// Strip MSSQL `OUTPUT INSERTED.col1, INSERTED.col2, ...` from INSERT statements
730/// and convert it to a `RETURNING col1, col2, ...` clause.
731/// The OUTPUT clause appears between the column list and VALUES clause:
732///   INSERT INTO table (cols) OUTPUT INSERTED.col1, INSERTED.col2, ... VALUES (...)
733/// becomes:
734///   INSERT INTO table (cols) VALUES (...) RETURNING col1, col2, ...
735fn strip_and_convert_mssql_output(sql: &str) -> String {
736    let upper = sql.to_uppercase();
737
738    if !upper.contains("INSERT") || !upper.contains("OUTPUT") {
739        return sql.to_string();
740    }
741
742    if let Some(output_pos) = find_word_position(&upper, "OUTPUT") {
743        let before_output = &upper[..output_pos];
744        if !before_output.contains("INSERT") {
745            return sql.to_string();
746        }
747
748        let after_output = &upper[output_pos + "OUTPUT".len()..];
749        if let Some(values_offset) = find_word_position(after_output, "VALUES") {
750            let values_pos = output_pos + "OUTPUT".len() + values_offset;
751
752            let output_cols_str = &sql[output_pos + "OUTPUT".len()..values_pos];
753
754            let cols = parse_inserted_columns(output_cols_str);
755
756            if !cols.is_empty() {
757                let before_output_sql = sql[..output_pos].trim_end();
758                let after_values = sql[values_pos..].trim_end();
759                let (values_body, trailing) = if let Some(stripped) = after_values.strip_suffix(';') {
760                    (stripped, ";")
761                } else {
762                    (after_values, "")
763                };
764
765                return format!("{}\n{} RETURNING {}{}", before_output_sql, values_body, cols, trailing);
766            }
767        }
768    }
769
770    sql.to_string()
771}
772
773/// Find the position of a word (case-insensitive) in the text.
774/// The word must be a separate word, not part of another identifier.
775fn find_word_position(text: &str, word: &str) -> Option<usize> {
776    let mut pos = 0;
777    let word_len = word.len();
778    while let Some(idx) = text[pos..].find(word) {
779        let abs_idx = pos + idx;
780
781        let before_ok = abs_idx == 0
782            || !text
783                .as_bytes()
784                .get(abs_idx - 1)
785                .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_');
786
787        let after_idx = abs_idx + word_len;
788        let after_ok = after_idx >= text.len()
789            || !text
790                .as_bytes()
791                .get(after_idx)
792                .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_');
793
794        if before_ok && after_ok {
795            return Some(abs_idx);
796        }
797        pos = abs_idx + 1;
798    }
799    None
800}
801
802/// Parse INSERTED.col1, INSERTED.col2, ... and extract column names as "col1, col2, ..."
803fn parse_inserted_columns(output_str: &str) -> String {
804    let mut cols = Vec::new();
805
806    for part in output_str.split(',') {
807        let trimmed = part.trim();
808
809        if let Some(after_inserted) = trimmed
810            .strip_prefix("INSERTED.")
811            .or_else(|| trimmed.strip_prefix("inserted."))
812            .or_else(|| trimmed.strip_prefix("INSERTED"))
813            .or_else(|| trimmed.strip_prefix("inserted"))
814        {
815            let col_name = after_inserted.trim().to_string();
816            if !col_name.is_empty() {
817                cols.push(col_name);
818            }
819        }
820    }
821
822    cols.join(", ")
823}
824
825/// Strip the `INTO :N, :N, ...` suffix from an Oracle `RETURNING ... INTO` clause.
826fn strip_returning_into(sql: &str) -> String {
827    let upper = sql.to_uppercase();
828    if let Some(ret_pos) = upper.rfind("RETURNING") {
829        let after_returning = &upper[ret_pos + "RETURNING".len()..];
830        if let Some(into_offset) = after_returning.find("INTO") {
831            let into_pos = ret_pos + "RETURNING".len() + into_offset;
832            let trimmed = sql[..into_pos].trim_end();
833            return trimmed.to_string();
834        }
835    }
836    sql.to_string()
837}
838
839#[cfg(test)]
840mod tests {
841    use super::*;
842    use crate::errors::ErrorCode;
843
844    fn parse(sql: &str) -> Result<Query, ScytheError> {
845        parse_query(sql)
846    }
847
848    #[test]
849    fn test_basic_parse() {
850        let input = "-- @name GetUsers\n-- @returns :many\nSELECT * FROM users;";
851        let q = parse(input).unwrap();
852        assert_eq!(q.name, "GetUsers");
853        assert_eq!(q.command, QueryCommand::Many);
854        assert!(q.sql.contains("SELECT"));
855    }
856
857    #[test]
858    fn test_all_command_types() {
859        let cases = vec![
860            (":one", QueryCommand::One),
861            (":many", QueryCommand::Many),
862            (":exec", QueryCommand::Exec),
863            (":exec_result", QueryCommand::ExecResult),
864            (":exec_rows", QueryCommand::ExecRows),
865        ];
866        for (tag, expected) in cases {
867            let input = format!("-- @name Q\n-- @returns {}\nSELECT 1", tag);
868            let q = parse(&input).unwrap();
869            assert_eq!(q.command, expected, "failed for {}", tag);
870        }
871    }
872
873    #[test]
874    fn test_case_insensitive_keywords() {
875        let input = "-- @Name GetUsers\n-- @RETURNS :many\nSELECT 1";
876        let q = parse(input).unwrap();
877        assert_eq!(q.name, "GetUsers");
878        assert_eq!(q.command, QueryCommand::Many);
879    }
880
881    #[test]
882    fn test_missing_name_errors() {
883        let input = "-- @returns :many\nSELECT 1";
884        let err = parse(input).unwrap_err();
885        assert_eq!(err.code, ErrorCode::MissingAnnotation);
886        assert!(err.message.contains("name"));
887    }
888
889    #[test]
890    fn test_missing_returns_errors() {
891        let input = "-- @name Foo\nSELECT 1";
892        let err = parse(input).unwrap_err();
893        assert_eq!(err.code, ErrorCode::MissingAnnotation);
894        assert!(err.message.contains("returns"));
895    }
896
897    #[test]
898    fn test_invalid_returns_value() {
899        let input = "-- @name Foo\n-- @returns :invalid\nSELECT 1";
900        let err = parse(input).unwrap_err();
901        assert_eq!(err.code, ErrorCode::InvalidAnnotation);
902    }
903
904    /// Inverted with #174: this used to assert that `-- @name` with no value
905    /// parses to an empty name, which generated `async def (conn):` and a
906    /// bare `Row` type at exit 0.
907    #[test]
908    fn test_empty_name_value_is_rejected() {
909        let input = "-- @name\n-- @returns :one\nSELECT 1";
910        let err = parse(input).unwrap_err();
911        assert_eq!(err.code, ErrorCode::InvalidAnnotation);
912        assert!(
913            err.message.contains("@name requires a value"),
914            "message must say what is missing; got: {}",
915            err.message
916        );
917    }
918
919    #[test]
920    fn test_name_value_that_is_not_an_identifier_is_rejected() {
921        for bad in ["Get User", "get-user", "users.get", "2fast", "\"GetUser\""] {
922            let input = format!("-- @name {bad}\n-- @returns :one\nSELECT 1");
923            let err = parse(&input).unwrap_err();
924            assert_eq!(
925                err.code,
926                ErrorCode::InvalidAnnotation,
927                "@name \"{bad}\" must be rejected"
928            );
929        }
930    }
931
932    #[test]
933    fn test_identifier_name_values_are_accepted() {
934        for good in ["GetUser", "get_user", "_private", "Query2"] {
935            let input = format!("-- @name {good}\n-- @returns :one\nSELECT 1");
936            let query = parse(&input).unwrap_or_else(|e| panic!("@name \"{good}\" must parse; got: {e}"));
937            assert_eq!(query.name, good);
938        }
939    }
940
941    #[test]
942    fn test_param_annotation() {
943        let input = "-- @name Foo\n-- @returns :one\n-- @param id: the user ID\nSELECT 1";
944        let q = parse(input).unwrap();
945        assert_eq!(q.annotations.param_docs.len(), 1);
946        assert_eq!(q.annotations.param_docs[0].name, "id");
947        assert_eq!(q.annotations.param_docs[0].description, "the user ID");
948    }
949
950    #[test]
951    fn test_param_no_description() {
952        let input = "-- @name Foo\n-- @returns :one\n-- @param id\nSELECT 1";
953        let q = parse(input).unwrap();
954        assert_eq!(q.annotations.param_docs.len(), 1);
955        assert_eq!(q.annotations.param_docs[0].name, "id");
956        assert_eq!(q.annotations.param_docs[0].description, "");
957    }
958
959    #[test]
960    fn test_nullable_annotation() {
961        let input = "-- @name Foo\n-- @returns :one\n-- @nullable col1, col2\nSELECT 1";
962        let q = parse(input).unwrap();
963        assert_eq!(q.annotations.nullable_overrides, vec!["col1", "col2"]);
964    }
965
966    #[test]
967    fn test_nonnull_annotation() {
968        let input = "-- @name Foo\n-- @returns :one\n-- @nonnull col1\nSELECT 1";
969        let q = parse(input).unwrap();
970        assert_eq!(q.annotations.nonnull_overrides, vec!["col1"]);
971    }
972
973    #[test]
974    fn test_json_annotation() {
975        let input = "-- @name Foo\n-- @returns :one\n-- @json data = EventData\nSELECT 1";
976        let q = parse(input).unwrap();
977        assert_eq!(q.annotations.json_mappings.len(), 1);
978        assert_eq!(q.annotations.json_mappings[0].column, "data");
979        assert_eq!(q.annotations.json_mappings[0].rust_type, "EventData");
980    }
981
982    #[test]
983    fn test_custom_annotations_captured() {
984        let input = "-- @name GetUser
985-- @returns :one
986-- @http GET /users/{id}
987-- @http_auth bearer:jwt
988-- @http_status 200,404
989SELECT id FROM users WHERE id = $1";
990        let q = parse(input).unwrap();
991        assert_eq!(q.annotations.custom.len(), 3);
992        assert_eq!(q.annotations.custom[0].name, "http");
993        assert_eq!(q.annotations.custom[0].value, "GET /users/{id}");
994        assert_eq!(q.annotations.custom[0].line, 3);
995        assert_eq!(q.annotations.custom[1].name, "http_auth");
996        assert_eq!(q.annotations.custom[1].value, "bearer:jwt");
997        assert_eq!(q.annotations.custom[1].line, 4);
998        assert_eq!(q.annotations.custom[2].name, "http_status");
999        assert_eq!(q.annotations.custom[2].value, "200,404");
1000        assert_eq!(q.annotations.custom[2].line, 5);
1001    }
1002
1003    #[test]
1004    fn test_custom_annotation_without_value() {
1005        let input = "-- @name GetUser
1006-- @returns :one
1007-- @http_internal
1008SELECT 1";
1009        let q = parse(input).unwrap();
1010        assert_eq!(q.annotations.custom.len(), 1);
1011        assert_eq!(q.annotations.custom[0].name, "http_internal");
1012        assert_eq!(q.annotations.custom[0].value, "");
1013    }
1014
1015    #[cfg(feature = "serde")]
1016    #[test]
1017    fn test_custom_annotation_serde_round_trip() {
1018        let original = CustomAnnotation {
1019            name: "http".to_string(),
1020            value: "GET /users/{id}".to_string(),
1021            line: 7,
1022            suggested_keyword: None,
1023        };
1024        let json = serde_json::to_string(&original).unwrap();
1025        let back: CustomAnnotation = serde_json::from_str(&json).unwrap();
1026        assert_eq!(back, original);
1027    }
1028
1029    #[test]
1030    fn test_custom_annotation_name_lowercased() {
1031        let input = "-- @name GetUser
1032-- @returns :one
1033-- @HTTP_Auth Bearer
1034SELECT 1";
1035        let q = parse(input).unwrap();
1036        assert_eq!(q.annotations.custom.len(), 1);
1037        assert_eq!(q.annotations.custom[0].name, "http_auth");
1038        assert_eq!(q.annotations.custom[0].value, "Bearer");
1039    }
1040
1041    /// Regression for #152: a misspelled `@nullable` / `@nonnull` / `@optional` used to be
1042    /// captured as an opaque `CustomAnnotation` that nothing ever inspected -- `scythe generate`,
1043    /// `scythe check` and `scythe lint` all reported success while the nullability override the
1044    /// user wrote never took effect. `suggested_keyword` must name the intended keyword so a
1045    /// caller can turn this into a warning instead of silence.
1046    #[test]
1047    fn test_typo_annotation_suggests_known_keyword() {
1048        let input = "-- @name GetUser
1049-- @returns :one
1050-- @nullible email
1051-- @optionall email
1052-- @nonull name
1053SELECT id, name, email FROM users WHERE id = $1";
1054        let q = parse(input).unwrap();
1055        assert_eq!(q.annotations.custom.len(), 3);
1056        assert_eq!(q.annotations.custom[0].name, "nullible");
1057        assert_eq!(q.annotations.custom[0].suggested_keyword.as_deref(), Some("nullable"));
1058        assert_eq!(q.annotations.custom[1].name, "optionall");
1059        assert_eq!(q.annotations.custom[1].suggested_keyword.as_deref(), Some("optional"));
1060        assert_eq!(q.annotations.custom[2].name, "nonull");
1061        assert_eq!(q.annotations.custom[2].suggested_keyword.as_deref(), Some("nonnull"));
1062
1063        // The override itself must NOT have silently applied under its misspelled name --
1064        // otherwise the typo would behave identically to the real keyword and there would be
1065        // nothing to warn about.
1066        assert!(q.annotations.nullable_overrides.is_empty());
1067        assert!(q.annotations.optional_params.is_empty());
1068        assert!(q.annotations.nonnull_overrides.is_empty());
1069    }
1070
1071    /// A genuinely consumer-defined annotation vocabulary (`@http`, `@http_auth`, ...) must not
1072    /// be flagged -- `suggested_keyword` is a typo signal, not a closed-vocabulary rejection; see
1073    /// the `CustomAnnotation` doc comment for why an unrecognised annotation is never a hard
1074    /// error.
1075    #[test]
1076    fn test_custom_annotation_far_from_any_keyword_has_no_suggestion() {
1077        let input = "-- @name GetUser
1078-- @returns :one
1079-- @http GET /users/{id}
1080-- @http_auth bearer:jwt
1081-- @http_status 200,404
1082SELECT id FROM users WHERE id = $1";
1083        let q = parse(input).unwrap();
1084        assert_eq!(q.annotations.custom.len(), 3);
1085        for annotation in &q.annotations.custom {
1086            assert_eq!(
1087                annotation.suggested_keyword, None,
1088                "{:?} must not be flagged as a typo of a known keyword",
1089                annotation.name
1090            );
1091        }
1092    }
1093
1094    // ---- @param positional form ----
1095
1096    #[test]
1097    fn test_positional_param_basic() {
1098        let input = "-- @name Foo\n-- @returns :one\n-- @param $1 user_id\nSELECT 1";
1099        let q = parse(input).unwrap();
1100        assert_eq!(q.annotations.positional_param_docs.len(), 1);
1101        assert_eq!(q.annotations.positional_param_docs[0].position, 1);
1102        assert_eq!(q.annotations.positional_param_docs[0].name, "user_id");
1103        assert_eq!(q.annotations.positional_param_docs[0].description, "");
1104        assert_eq!(q.annotations.param_docs.len(), 0);
1105    }
1106
1107    #[test]
1108    fn test_positional_param_with_description() {
1109        let input = "-- @name Foo\n-- @returns :one\n-- @param $4 bucket: time bucket as text\nSELECT 1";
1110        let q = parse(input).unwrap();
1111        assert_eq!(q.annotations.positional_param_docs.len(), 1);
1112        assert_eq!(q.annotations.positional_param_docs[0].position, 4);
1113        assert_eq!(q.annotations.positional_param_docs[0].name, "bucket");
1114        assert_eq!(
1115            q.annotations.positional_param_docs[0].description,
1116            "time bucket as text"
1117        );
1118    }
1119
1120    #[test]
1121    fn test_positional_param_does_not_affect_docs_only_param() {
1122        let input = "-- @name Foo\n-- @returns :one\n-- @param id: the user ID\n-- @param $2 name\nSELECT 1";
1123        let q = parse(input).unwrap();
1124        assert_eq!(q.annotations.param_docs.len(), 1);
1125        assert_eq!(q.annotations.param_docs[0].name, "id");
1126        assert_eq!(q.annotations.positional_param_docs.len(), 1);
1127        assert_eq!(q.annotations.positional_param_docs[0].position, 2);
1128        assert_eq!(q.annotations.positional_param_docs[0].name, "name");
1129    }
1130
1131    #[test]
1132    fn test_positional_param_multiple() {
1133        let input =
1134            "-- @name Foo\n-- @returns :one\n-- @param $1 start_date: start\n-- @param $2 end_date: end\nSELECT 1";
1135        let q = parse(input).unwrap();
1136        assert_eq!(q.annotations.positional_param_docs.len(), 2);
1137        assert_eq!(q.annotations.positional_param_docs[0].position, 1);
1138        assert_eq!(q.annotations.positional_param_docs[0].name, "start_date");
1139        assert_eq!(q.annotations.positional_param_docs[1].position, 2);
1140        assert_eq!(q.annotations.positional_param_docs[1].name, "end_date");
1141    }
1142
1143    #[test]
1144    fn test_deprecated_annotation() {
1145        let input = "-- @name Foo\n-- @returns :one\n-- @deprecated Use V2\nSELECT 1";
1146        let q = parse(input).unwrap();
1147        assert_eq!(q.annotations.deprecated, Some("Use V2".to_string()));
1148    }
1149
1150    #[test]
1151    fn test_sql_syntax_error() {
1152        let input = "-- @name Foo\n-- @returns :one\nSELCT * FROM users";
1153        let err = parse(input).unwrap_err();
1154        assert_eq!(err.code, ErrorCode::SyntaxError);
1155    }
1156
1157    #[test]
1158    fn test_trailing_semicolon() {
1159        let input = "-- @name Foo\n-- @returns :one\nSELECT 1;";
1160        let q = parse(input).unwrap();
1161        assert_eq!(q.name, "Foo");
1162    }
1163
1164    #[test]
1165    fn test_multiple_statements_error() {
1166        let input = "-- @name Foo\n-- @returns :one\nSELECT 1; SELECT 2;";
1167        let err = parse(input).unwrap_err();
1168        assert_eq!(err.code, ErrorCode::SyntaxError);
1169    }
1170
1171    #[test]
1172    fn test_sql_preserved_without_annotations() {
1173        let input = "-- @name Foo\n-- @returns :one\nSELECT id, name FROM users WHERE id = $1";
1174        let q = parse(input).unwrap();
1175        assert_eq!(q.sql, "SELECT id, name FROM users WHERE id = $1");
1176    }
1177
1178    /// End-to-end confirmation for #149: sqlparser must actually accept the
1179    /// `$N` spelling `preprocess_oracle_sql`/`convert_mssql_placeholders` now
1180    /// emit under `OracleDialect`/`MsSqlDialect` -- not just produce text that
1181    /// looks plausible. An out-of-order `:2 ... :1` (Oracle) / `@p2 ... @p1`
1182    /// (MSSQL) proves the position survives into `Query.sql` unrenumbered,
1183    /// which is what lets a codegen backend bind by occurrence instead of by
1184    /// declaration order.
1185    #[test]
1186    fn test_oracle_out_of_order_placeholders_parse_and_preserve_position_in_sql() {
1187        let input = "-- @name Foo\n-- @returns :one\nSELECT * FROM users WHERE b = :2 AND a = :1";
1188        let q = parse_query_with_dialect(input, &SqlDialect::Oracle).unwrap();
1189        assert_eq!(q.sql, "SELECT * FROM users WHERE b = $2 AND a = $1");
1190    }
1191
1192    #[test]
1193    fn test_mssql_out_of_order_placeholders_parse_and_preserve_position_in_sql() {
1194        let input = "-- @name Foo\n-- @returns :one\nSELECT * FROM users WHERE b = @p2 AND a = @p1";
1195        let q = parse_query_with_dialect(input, &SqlDialect::MsSql).unwrap();
1196        assert_eq!(q.sql, "SELECT * FROM users WHERE b = $2 AND a = $1");
1197    }
1198
1199    #[test]
1200    fn test_returns_without_colon_prefix() {
1201        let input = "-- @name Foo\n-- @returns many\nSELECT 1";
1202        let q = parse(input).unwrap();
1203        assert_eq!(q.command, QueryCommand::Many);
1204    }
1205
1206    #[test]
1207    fn test_batch_command() {
1208        let input = "-- @name Foo\n-- @returns :batch\nSELECT 1";
1209        let q = parse(input).unwrap();
1210        assert_eq!(q.command, QueryCommand::Batch);
1211    }
1212
1213    #[test]
1214    fn test_grouped_command_with_group_by() {
1215        let input = "-- @name GetUsersWithOrders\n-- @returns :grouped\n-- @group_by users.id\nSELECT u.id, u.name FROM users u JOIN orders o ON o.user_id = u.id";
1216        let q = parse(input).unwrap();
1217        assert_eq!(q.command, QueryCommand::Grouped);
1218        assert_eq!(q.annotations.group_by, Some("users.id".to_string()));
1219    }
1220
1221    #[test]
1222    fn test_grouped_command_without_group_by_errors() {
1223        let input = "-- @name Foo\n-- @returns :grouped\nSELECT 1";
1224        let err = parse(input).unwrap_err();
1225        assert_eq!(err.code, ErrorCode::InvalidAnnotation);
1226        assert!(err.message.contains("@group_by"));
1227    }
1228
1229    #[test]
1230    fn test_group_by_without_grouped_is_ignored() {
1231        let input = "-- @name Foo\n-- @returns :many\n-- @group_by users.id\nSELECT 1";
1232        let q = parse(input).unwrap();
1233        assert_eq!(q.command, QueryCommand::Many);
1234        assert_eq!(q.annotations.group_by, Some("users.id".to_string()));
1235    }
1236
1237    #[test]
1238    fn test_preprocess_postgres_strips_partial_index_where() {
1239        let sql = "INSERT INTO billing_events (project_id, stripe_event_id) \
1240                   VALUES ($1, $2) \
1241                   ON CONFLICT (stripe_event_id) WHERE stripe_event_id IS NOT NULL DO NOTHING";
1242        let cleaned = preprocess_postgres_sql(sql);
1243        assert!(
1244            !cleaned.to_uppercase().contains("WHERE STRIPE_EVENT_ID IS NOT NULL"),
1245            "WHERE clause must be stripped between ON CONFLICT cols and DO; got: {cleaned}"
1246        );
1247        assert!(
1248            cleaned
1249                .to_uppercase()
1250                .contains("ON CONFLICT (STRIPE_EVENT_ID) DO NOTHING")
1251        );
1252        sqlparser::parser::Parser::parse_sql(&sqlparser::dialect::PostgreSqlDialect {}, &cleaned)
1253            .expect("cleaned SQL should parse");
1254    }
1255
1256    #[test]
1257    fn test_preprocess_postgres_no_op_when_no_partial_clause() {
1258        let sql = "INSERT INTO t (a) VALUES ($1) ON CONFLICT (a) DO UPDATE SET a = EXCLUDED.a";
1259        assert_eq!(preprocess_postgres_sql(sql), sql);
1260    }
1261
1262    #[test]
1263    fn test_preprocess_postgres_leaves_on_conflict_on_constraint_alone() {
1264        let sql = "INSERT INTO t (a) VALUES ($1) ON CONFLICT ON CONSTRAINT t_a_uidx DO NOTHING";
1265        assert_eq!(preprocess_postgres_sql(sql), sql);
1266    }
1267
1268    #[test]
1269    fn test_preprocess_postgres_handles_compound_index_cols() {
1270        let sql = "INSERT INTO t (a, b) VALUES ($1, $2) \
1271                   ON CONFLICT (a, b) WHERE a IS NOT NULL AND b > 0 DO UPDATE SET b = EXCLUDED.b";
1272        let cleaned = preprocess_postgres_sql(sql);
1273        assert!(cleaned.to_uppercase().contains("ON CONFLICT (A, B) DO UPDATE"));
1274        assert!(!cleaned.to_uppercase().contains("WHERE A IS NOT NULL"));
1275    }
1276
1277    #[test]
1278    fn test_preprocess_postgres_preserves_unrelated_where() {
1279        let sql = "DELETE FROM t WHERE id = $1";
1280        assert_eq!(preprocess_postgres_sql(sql), sql);
1281    }
1282
1283    #[test]
1284    fn test_preprocess_postgres_ignores_text_inside_line_comments() {
1285        let sql = "-- inline doc: `ON CONFLICT (col) WHERE …` is the partial form\n\
1286                   INSERT INTO t (a) VALUES ($1) \
1287                   ON CONFLICT (a) WHERE a IS NOT NULL DO NOTHING";
1288        let cleaned = preprocess_postgres_sql(sql);
1289        assert!(
1290            cleaned.contains("-- inline doc"),
1291            "comment must survive the pass; got: {cleaned}"
1292        );
1293        assert!(cleaned.contains("ON CONFLICT (a) DO NOTHING"));
1294    }
1295
1296    #[test]
1297    fn test_preprocess_postgres_ignores_text_inside_string_literals() {
1298        let sql = "SELECT 'ON CONFLICT (a) WHERE a IS NOT NULL DO NOTHING' AS s";
1299        assert_eq!(preprocess_postgres_sql(sql), sql);
1300    }
1301
1302    #[test]
1303    fn test_preprocess_oracle_colon_placeholders() {
1304        assert_eq!(
1305            preprocess_oracle_sql("SELECT * FROM users WHERE id = :1"),
1306            "SELECT * FROM users WHERE id = $1"
1307        );
1308        assert_eq!(
1309            preprocess_oracle_sql("INSERT INTO users (name, email) VALUES (:1, :2)"),
1310            "INSERT INTO users (name, email) VALUES ($1, $2)"
1311        );
1312    }
1313
1314    #[test]
1315    fn test_preprocess_oracle_preserves_string_literals() {
1316        assert_eq!(
1317            preprocess_oracle_sql("SELECT * FROM users WHERE name = ':1' AND id = :1"),
1318            "SELECT * FROM users WHERE name = ':1' AND id = $1"
1319        );
1320    }
1321
1322    #[test]
1323    fn test_preprocess_oracle_strips_returning_into() {
1324        assert_eq!(
1325            preprocess_oracle_sql("INSERT INTO users (name) VALUES (:1) RETURNING id, name INTO :2, :3"),
1326            "INSERT INTO users (name) VALUES ($1) RETURNING id, name"
1327        );
1328    }
1329
1330    #[test]
1331    fn test_preprocess_oracle_full_insert_returning_into() {
1332        let sql = "INSERT INTO users (name, email, active) VALUES (:1, :2, :3) RETURNING id, name, email, active, created_at INTO :4, :5, :6, :7, :8";
1333        let result = preprocess_oracle_sql(sql);
1334        assert_eq!(
1335            result,
1336            "INSERT INTO users (name, email, active) VALUES ($1, $2, $3) RETURNING id, name, email, active, created_at"
1337        );
1338    }
1339
1340    #[test]
1341    fn test_preprocess_oracle_no_returning_into_unchanged() {
1342        assert_eq!(
1343            preprocess_oracle_sql("DELETE FROM users WHERE id = :1"),
1344            "DELETE FROM users WHERE id = $1"
1345        );
1346    }
1347
1348    /// #149: a repeated `:1` must resolve to two occurrences of the *same*
1349    /// position, not collapse to indistinguishable bare `?`s a bind-per-
1350    /// occurrence backend can no longer tell apart.
1351    #[test]
1352    fn test_preprocess_oracle_repeated_placeholder_keeps_its_own_position() {
1353        assert_eq!(
1354            preprocess_oracle_sql("SELECT * FROM users WHERE id = :1 OR parent_id = :1"),
1355            "SELECT * FROM users WHERE id = $1 OR parent_id = $1"
1356        );
1357    }
1358
1359    /// #149: `:2` declared before `:1` in the SQL text must keep its own
1360    /// number rather than being renumbered by text order -- renumbering is
1361    /// exactly what silently swapped a caller's arguments before this fix.
1362    #[test]
1363    fn test_preprocess_oracle_out_of_order_placeholders_keep_their_own_numbers() {
1364        assert_eq!(
1365            preprocess_oracle_sql("SELECT * FROM users WHERE b = :2 AND a = :1"),
1366            "SELECT * FROM users WHERE b = $2 AND a = $1"
1367        );
1368    }
1369
1370    #[test]
1371    fn test_preprocess_mssql_single_placeholder() {
1372        assert_eq!(
1373            preprocess_mssql_sql("SELECT * FROM users WHERE id = @p1"),
1374            "SELECT * FROM users WHERE id = $1"
1375        );
1376    }
1377
1378    #[test]
1379    fn test_preprocess_mssql_multiple_placeholders() {
1380        assert_eq!(
1381            preprocess_mssql_sql("INSERT INTO users (name, email) VALUES (@p1, @p2)"),
1382            "INSERT INTO users (name, email) VALUES ($1, $2)"
1383        );
1384    }
1385
1386    #[test]
1387    fn test_preprocess_mssql_preserves_string_literals() {
1388        assert_eq!(
1389            preprocess_mssql_sql("SELECT * FROM users WHERE name = '@p1' AND id = @p1"),
1390            "SELECT * FROM users WHERE name = '@p1' AND id = $1"
1391        );
1392    }
1393
1394    #[test]
1395    fn test_preprocess_mssql_case_insensitive_p() {
1396        assert_eq!(
1397            preprocess_mssql_sql("SELECT * FROM users WHERE id = @P1"),
1398            "SELECT * FROM users WHERE id = $1"
1399        );
1400    }
1401
1402    #[test]
1403    fn test_preprocess_mssql_non_placeholder_at_variable_unchanged() {
1404        assert_eq!(preprocess_mssql_sql("SELECT @myvar"), "SELECT @myvar");
1405    }
1406
1407    #[test]
1408    fn test_preprocess_mssql_multi_digit_placeholder() {
1409        assert_eq!(preprocess_mssql_sql("SELECT @p10, @p2"), "SELECT $10, $2");
1410    }
1411
1412    /// #149: a repeated `@p1` must resolve to two occurrences of the same
1413    /// position; see the Oracle counterpart above for the full reasoning.
1414    #[test]
1415    fn test_preprocess_mssql_repeated_placeholder_keeps_its_own_position() {
1416        assert_eq!(
1417            preprocess_mssql_sql("SELECT * FROM users WHERE id = @p1 OR parent_id = @p1"),
1418            "SELECT * FROM users WHERE id = $1 OR parent_id = $1"
1419        );
1420    }
1421
1422    /// #149: `@p2` declared before `@p1` must keep its own number.
1423    #[test]
1424    fn test_preprocess_mssql_out_of_order_placeholders_keep_their_own_numbers() {
1425        assert_eq!(
1426            preprocess_mssql_sql("SELECT * FROM users WHERE b = @p2 AND a = @p1"),
1427            "SELECT * FROM users WHERE b = $2 AND a = $1"
1428        );
1429    }
1430
1431    #[test]
1432    fn test_preprocess_mssql_output_inserted_simple() {
1433        let sql = "INSERT INTO users (id, name) OUTPUT INSERTED.id, INSERTED.name VALUES (@p1, @p2)";
1434        let result = preprocess_mssql_sql(sql);
1435        assert!(result.contains("RETURNING id, name"), "got: {}", result);
1436        assert!(result.contains("VALUES ($1, $2)"), "got: {}", result);
1437        assert!(!result.contains("OUTPUT"), "got: {}", result);
1438    }
1439
1440    #[test]
1441    fn test_preprocess_mssql_output_inserted_full_example() {
1442        let sql = "INSERT INTO users (id, name, email, active) OUTPUT INSERTED.id, INSERTED.name, INSERTED.email, INSERTED.active, INSERTED.created_at VALUES (@p1, @p2, @p3, @p4)";
1443        let result = preprocess_mssql_sql(sql);
1444        assert!(
1445            result.contains("RETURNING id, name, email, active, created_at"),
1446            "got: {}",
1447            result
1448        );
1449        assert!(result.contains("VALUES ($1, $2, $3, $4)"), "got: {}", result);
1450    }
1451
1452    #[test]
1453    fn test_preprocess_mssql_output_case_insensitive() {
1454        let sql = "INSERT INTO users (id) output inserted.id values (@p1)";
1455        let result = preprocess_mssql_sql(sql);
1456        assert!(result.contains("RETURNING id"), "got: {}", result);
1457        assert!(
1458            result.contains("values ($1)") || result.contains("VALUES ($1)"),
1459            "got: {}",
1460            result
1461        );
1462    }
1463
1464    #[test]
1465    fn test_preprocess_mssql_no_output_unchanged() {
1466        let sql = "INSERT INTO users (id, name) VALUES (@p1, @p2)";
1467        let result = preprocess_mssql_sql(sql);
1468        assert_eq!(result, "INSERT INTO users (id, name) VALUES ($1, $2)");
1469    }
1470
1471    #[test]
1472    fn test_preprocess_mssql_output_with_string_literal() {
1473        let sql = "INSERT INTO users (id, name) OUTPUT INSERTED.id, INSERTED.name VALUES (@p1, '@p2')";
1474        let result = preprocess_mssql_sql(sql);
1475        assert!(result.contains("RETURNING id, name"), "got: {}", result);
1476        assert!(result.contains("($1, '@p2')"), "got: {}", result);
1477    }
1478
1479    #[test]
1480    fn test_preprocess_mssql_output_with_whitespace() {
1481        let sql = "INSERT INTO users (id, name)\nOUTPUT INSERTED.id,\n  INSERTED.name\nVALUES (@p1, @p2)";
1482        let result = preprocess_mssql_sql(sql);
1483        assert!(result.contains("RETURNING id, name"), "got: {}", result);
1484        assert!(result.contains("VALUES ($1, $2)"), "got: {}", result);
1485    }
1486}