1pub(crate) mod csharp_microsoft_sqlite;
2pub(crate) mod csharp_mysqlconnector;
3pub(crate) mod csharp_npgsql;
4pub(crate) mod csharp_oracle;
5pub(crate) mod csharp_snowflake;
6pub(crate) mod csharp_sqlclient;
7pub(crate) mod elixir_common;
8pub(crate) mod elixir_ecto;
9pub(crate) mod elixir_exqlite;
10pub(crate) mod elixir_jamdb;
11pub(crate) mod elixir_myxql;
12pub(crate) mod elixir_postgrex;
13pub(crate) mod elixir_tds;
14pub(crate) mod go_common;
15pub(crate) mod go_database_sql;
16pub(crate) mod go_godror;
17pub(crate) mod go_gosnowflake;
18pub(crate) mod go_pgx;
19pub(crate) mod java_jdbc;
20pub(crate) mod java_r2dbc;
21pub(crate) mod jvm_common;
22pub(crate) mod kotlin_exposed;
23pub(crate) mod kotlin_jdbc;
24pub(crate) mod kotlin_r2dbc;
25pub(crate) mod php_amphp;
26pub(crate) mod php_common;
27pub(crate) mod php_pdo;
28pub(crate) mod python_aiomysql;
29pub(crate) mod python_aiosqlite;
30pub(crate) mod python_asyncpg;
31pub(crate) mod python_common;
32pub(crate) mod python_duckdb;
33pub(crate) mod python_oracledb;
34pub(crate) mod python_psycopg3;
35pub(crate) mod python_pyodbc;
36pub(crate) mod python_snowflake;
37pub(crate) mod ruby_mysql2;
38pub(crate) mod ruby_oci8;
39pub(crate) mod ruby_pg;
40pub(crate) mod ruby_rbs;
41pub(crate) mod ruby_sqlite3;
42pub(crate) mod ruby_tiny_tds;
43pub(crate) mod ruby_trilogy;
44pub(crate) mod rust_sibyl;
45pub(crate) mod rust_tiberius;
46pub(crate) mod sqlx;
47pub(crate) mod tokio_postgres;
48pub(crate) mod typescript_better_sqlite3;
49pub(crate) mod typescript_common;
50pub(crate) mod typescript_duckdb;
51pub(crate) mod typescript_kysely;
52pub(crate) mod typescript_mssql;
53pub(crate) mod typescript_mysql2;
54pub(crate) mod typescript_node_sqlite;
55pub(crate) mod typescript_oracledb;
56pub(crate) mod typescript_pg;
57pub(crate) mod typescript_postgres;
58pub(crate) mod typescript_snowflake;
59pub(crate) mod typescript_wasm_sqlite;
60
61use scythe_backend::manifest::BackendManifest;
62use scythe_backend::naming::NamingConfig;
63use scythe_core::SqlDialect;
64use scythe_core::analyzer::AnalyzedParam;
65use scythe_core::errors::{ErrorCode, ScytheError};
66
67use crate::backend_trait::{CodegenBackend, ResolvedParam};
68
69pub(crate) fn parse_manifest(manifest_toml: &str) -> Result<BackendManifest, ScytheError> {
75 toml::from_str(manifest_toml).map_err(|e| ScytheError::new(ErrorCode::InternalError, format!("manifest: {e}")))
76}
77
78pub(crate) fn apply_field_case_option(
95 naming: &mut NamingConfig,
96 backend_name: &str,
97 value: &str,
98) -> Result<(), ScytheError> {
99 match value {
100 "snake_case" | "camelCase" => {
101 naming.field_case = value.to_string();
102 Ok(())
103 }
104 other => Err(ScytheError::new(
105 ErrorCode::InvalidConfig,
106 format!("{backend_name}: invalid field_case '{other}' (expected 'snake_case' or 'camelCase')"),
107 )),
108 }
109}
110
111pub(crate) fn engine_supports_nested_aggregates(engine: &str) -> bool {
126 matches!(engine, "postgresql" | "postgres" | "pg")
127}
128
129pub(crate) fn csharp_typed_reader_method(lang_type: &str) -> String {
157 format!("GetFieldValue<{lang_type}>")
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170enum SqlSpanKind {
171 Code,
173 SingleQuoted,
175 DoubleQuoted,
177 DollarQuoted,
179 Backtick,
183 Bracketed,
188 LineComment,
191 BlockComment,
194}
195
196fn tokenize_sql(sql: &str, dialect: SqlDialect) -> Vec<(SqlSpanKind, String)> {
209 let chars: Vec<char> = sql.chars().collect();
210 let len = chars.len();
211 let mut spans: Vec<(SqlSpanKind, String)> = Vec::new();
212 let mut code_buf = String::new();
213 let mut i = 0;
214
215 while i < len {
216 let c = chars[i];
217
218 if c == '-' && i + 1 < len && chars[i + 1] == '-' {
219 flush_code_buf(&mut code_buf, &mut spans);
220 let start = i;
221 i += 2;
222 while i < len && chars[i] != '\n' {
223 i += 1;
224 }
225 spans.push((SqlSpanKind::LineComment, chars[start..i].iter().collect()));
226 continue;
227 }
228
229 if c == '/' && i + 1 < len && chars[i + 1] == '*' {
230 flush_code_buf(&mut code_buf, &mut spans);
231 let start = i;
232 i += 2;
233 let mut depth = 1u32;
234 while i < len && depth > 0 {
235 if chars[i] == '/' && i + 1 < len && chars[i + 1] == '*' {
236 depth += 1;
237 i += 2;
238 } else if chars[i] == '*' && i + 1 < len && chars[i + 1] == '/' {
239 depth -= 1;
240 i += 2;
241 } else {
242 i += 1;
243 }
244 }
245 spans.push((SqlSpanKind::BlockComment, chars[start..i].iter().collect()));
246 continue;
247 }
248
249 if c == '\'' {
250 flush_code_buf(&mut code_buf, &mut spans);
251 let start = i;
252 i += 1;
253 while i < len {
254 if chars[i] == '\'' {
255 if i + 1 < len && chars[i + 1] == '\'' {
256 i += 2;
257 continue;
258 }
259 i += 1;
260 break;
261 }
262 i += 1;
263 }
264 spans.push((SqlSpanKind::SingleQuoted, chars[start..i].iter().collect()));
265 continue;
266 }
267
268 if c == '"' {
269 flush_code_buf(&mut code_buf, &mut spans);
270 let start = i;
271 i += 1;
272 while i < len {
273 if chars[i] == '"' {
274 if i + 1 < len && chars[i + 1] == '"' {
275 i += 2;
276 continue;
277 }
278 i += 1;
279 break;
280 }
281 i += 1;
282 }
283 spans.push((SqlSpanKind::DoubleQuoted, chars[start..i].iter().collect()));
284 continue;
285 }
286
287 if c == '`' && dialect == SqlDialect::MySQL {
288 flush_code_buf(&mut code_buf, &mut spans);
289 let start = i;
290 i += 1;
291 while i < len {
292 if chars[i] == '`' {
293 if i + 1 < len && chars[i + 1] == '`' {
294 i += 2;
295 continue;
296 }
297 i += 1;
298 break;
299 }
300 i += 1;
301 }
302 spans.push((SqlSpanKind::Backtick, chars[start..i].iter().collect()));
303 continue;
304 }
305
306 if c == '#' && dialect == SqlDialect::MySQL {
307 flush_code_buf(&mut code_buf, &mut spans);
308 let start = i;
309 while i < len && chars[i] != '\n' {
310 i += 1;
311 }
312 spans.push((SqlSpanKind::LineComment, chars[start..i].iter().collect()));
313 continue;
314 }
315
316 if c == '[' && dialect == SqlDialect::MsSql {
317 flush_code_buf(&mut code_buf, &mut spans);
318 let start = i;
319 i += 1;
320 while i < len {
321 if chars[i] == ']' {
322 if i + 1 < len && chars[i + 1] == ']' {
323 i += 2;
324 continue;
325 }
326 i += 1;
327 break;
328 }
329 i += 1;
330 }
331 spans.push((SqlSpanKind::Bracketed, chars[start..i].iter().collect()));
332 continue;
333 }
334
335 if c == '$'
336 && let Some(open_end) = match_dollar_quote_open(&chars, i)
337 {
338 flush_code_buf(&mut code_buf, &mut spans);
339 let start = i;
340 let delim: Vec<char> = chars[i..open_end].to_vec();
341 let mut j = open_end;
342 let mut found = false;
343 while j < len {
344 if chars[j] == '$' && j + delim.len() <= len && chars[j..j + delim.len()] == delim[..] {
345 j += delim.len();
346 found = true;
347 break;
348 }
349 j += 1;
350 }
351 if !found {
352 j = len;
353 }
354 spans.push((SqlSpanKind::DollarQuoted, chars[start..j].iter().collect()));
355 i = j;
356 continue;
357 }
358
359 code_buf.push(c);
360 i += 1;
361 }
362
363 flush_code_buf(&mut code_buf, &mut spans);
364 spans
365}
366
367fn flush_code_buf(code_buf: &mut String, spans: &mut Vec<(SqlSpanKind, String)>) {
368 if !code_buf.is_empty() {
369 spans.push((SqlSpanKind::Code, std::mem::take(code_buf)));
370 }
371}
372
373fn match_dollar_quote_open(chars: &[char], i: usize) -> Option<usize> {
378 let mut j = i + 1;
379 if j < chars.len() && chars[j] == '$' {
380 return Some(j + 1);
381 }
382 let tag_start = j;
383 while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
384 j += 1;
385 }
386 if j > tag_start && j < chars.len() && chars[j] == '$' && !chars[tag_start].is_ascii_digit() {
387 return Some(j + 1);
388 }
389 None
390}
391
392pub(crate) fn clean_sql(sql: &str) -> String {
401 clean_sql_lines(sql, SqlDialect::PostgreSQL)
402 .join("\n")
403 .trim()
404 .trim_end_matches(';')
405 .trim()
406 .to_string()
407}
408
409pub(crate) fn clean_sql_oneline(sql: &str) -> String {
412 clean_sql_lines(sql, SqlDialect::PostgreSQL)
413 .join(" ")
414 .trim()
415 .trim_end_matches(';')
416 .trim()
417 .to_string()
418}
419
420#[cfg_attr(
432 not(test),
433 expect(dead_code, reason = "staged board #148 migration; see doc comment")
434)]
435pub(crate) fn clean_sql_dialect(sql: &str, dialect: SqlDialect) -> String {
436 clean_sql_lines(sql, dialect)
437 .join("\n")
438 .trim()
439 .trim_end_matches(';')
440 .trim()
441 .to_string()
442}
443
444pub(crate) fn clean_sql_oneline_dialect(sql: &str, dialect: SqlDialect) -> String {
446 clean_sql_lines(sql, dialect)
447 .join(" ")
448 .trim()
449 .trim_end_matches(';')
450 .trim()
451 .to_string()
452}
453
454fn clean_sql_lines(sql: &str, dialect: SqlDialect) -> Vec<String> {
466 let normalized = sql.replace("\r\n", "\n");
467 let spans = tokenize_sql(&normalized, dialect);
468
469 let mut lines: Vec<String> = vec![String::new()];
470 let mut touched_by_comment: Vec<bool> = vec![false];
471
472 for (kind, text) in &spans {
473 let is_comment = matches!(kind, SqlSpanKind::LineComment | SqlSpanKind::BlockComment);
474 for ch in text.chars() {
475 if ch == '\n' {
476 if is_comment {
477 *touched_by_comment.last_mut().expect("at least one line") = true;
478 }
479 lines.push(String::new());
480 touched_by_comment.push(false);
481 } else if is_comment {
482 *touched_by_comment.last_mut().expect("at least one line") = true;
483 } else {
484 lines.last_mut().expect("at least one line").push(ch);
485 }
486 }
487 }
488
489 lines
490 .into_iter()
491 .zip(touched_by_comment)
492 .filter(|(kept, touched)| !(*touched && kept.trim().is_empty()))
493 .map(|(kept, _)| kept)
494 .collect()
495}
496
497pub(crate) fn rewrite_optional_params(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
505 if optional_params.is_empty() {
506 return sql.to_string();
507 }
508
509 let mut result = sql.to_string();
510
511 for opt_name in optional_params {
512 let Some(param) = params.iter().find(|p| p.name == *opt_name) else {
513 continue;
514 };
515 let placeholder = format!("${}", param.position);
516
517 for op in &[
518 ">=",
519 "<=",
520 "<>",
521 "!=",
522 ">",
523 "<",
524 "=",
525 "NOT ILIKE",
526 "not ilike",
527 "NOT LIKE",
528 "not like",
529 "ILIKE",
530 "ilike",
531 "LIKE",
532 "like",
533 ] {
534 result = rewrite_comparison(&result, &placeholder, op);
535 }
536 }
537
538 result
539}
540
541fn pg_cast_suffix(neutral_type: &str) -> Option<String> {
550 use scythe_core::analyzer::neutral_to_sql_label;
551
552 if let Some(enum_name) = neutral_type.strip_prefix("enum::") {
553 return Some(enum_name.to_string());
554 }
555 if let Some(composite_name) = neutral_type.strip_prefix("composite::") {
556 return Some(format!("text::{composite_name}"));
558 }
559 if neutral_type.starts_with("json_typed<") {
560 return Some("jsonb".to_string());
561 }
562 if let Some(inner) = neutral_type
563 .strip_prefix("array<")
564 .and_then(|rest| rest.strip_suffix('>'))
565 {
566 let element = match inner {
567 "json" | "json_array" => "jsonb".to_string(),
568 other => neutral_to_sql_label(other).to_string(),
569 };
570 return Some(format!("{element}[]"));
571 }
572 match neutral_type {
573 "json" => Some("jsonb".to_string()),
574 "json_array" => Some("jsonb[]".to_string()),
575 "bool" | "int16" | "int32" | "int64" | "float32" | "float64" | "string" | "bytes" | "uuid" | "decimal"
576 | "date" | "time" | "time_tz" | "datetime" | "datetime_tz" | "interval" | "inet" => {
577 Some(neutral_to_sql_label(neutral_type).to_string())
578 }
579 _ => None,
580 }
581}
582
583pub(crate) fn rewrite_optional_params_pg(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
586 if optional_params.is_empty() {
587 return sql.to_string();
588 }
589
590 let mut result = sql.to_string();
591
592 for opt_name in optional_params {
593 let Some(param) = params.iter().find(|p| p.name == *opt_name) else {
594 continue;
595 };
596 let placeholder = format!("${}", param.position);
597 let cast = pg_cast_suffix(¶m.neutral_type);
598
599 for op in &[
600 ">=",
601 "<=",
602 "<>",
603 "!=",
604 ">",
605 "<",
606 "=",
607 "NOT ILIKE",
608 "not ilike",
609 "NOT LIKE",
610 "not like",
611 "ILIKE",
612 "ilike",
613 "LIKE",
614 "like",
615 ] {
616 result = rewrite_comparison_typed(&result, &placeholder, op, cast.as_deref());
617 }
618 }
619
620 result
621}
622
623fn rewrite_comparison(sql: &str, placeholder: &str, op: &str) -> String {
626 rewrite_comparison_typed(sql, placeholder, op, None)
627}
628
629fn rewrite_comparison_typed(sql: &str, placeholder: &str, op: &str, cast: Option<&str>) -> String {
632 let typed_placeholder = match cast {
633 Some(cast) => format!("{placeholder}::{cast}"),
634 None => placeholder.to_string(),
635 };
636 let mut result = String::with_capacity(sql.len() + 32);
637 let chars: Vec<char> = sql.chars().collect();
638 let len = chars.len();
639 let mut i = 0;
640
641 while i < len {
642 if let Some((_start, col, end)) = try_match_col_op_ph(&chars, i, op, placeholder) {
643 result.push_str(&format!("({typed_placeholder} IS NULL OR {col} {op} {placeholder})"));
644 i = end;
645 continue;
646 }
647
648 if let Some((end, col)) = try_match_ph_op_col(&chars, i, op, placeholder) {
649 result.push_str(&format!("({typed_placeholder} IS NULL OR {col} {op} {placeholder})"));
650 i = end;
651 continue;
652 }
653
654 result.push(chars[i]);
655 i += 1;
656 }
657
658 result
659}
660
661fn is_reserved_non_column_keyword(ident: &str) -> bool {
670 matches!(
671 ident.to_ascii_uppercase().as_str(),
672 "NOT" | "AND" | "OR" | "IS" | "NULL"
673 )
674}
675
676fn match_op_tokens(chars: &[char], mut j: usize, op: &str) -> Option<usize> {
681 for (idx, word) in op.split_whitespace().enumerate() {
682 if idx > 0 {
683 let ws_start = j;
684 while j < chars.len() && chars[j].is_whitespace() {
685 j += 1;
686 }
687 if j == ws_start {
688 return None;
689 }
690 }
691 let word_chars: Vec<char> = word.chars().collect();
692 if j + word_chars.len() > chars.len() {
693 return None;
694 }
695 for (k, wc) in word_chars.iter().enumerate() {
696 if chars[j + k] != *wc {
697 return None;
698 }
699 }
700 j += word_chars.len();
701 }
702 Some(j)
703}
704
705fn try_match_col_op_ph(chars: &[char], i: usize, op: &str, placeholder: &str) -> Option<(usize, String, usize)> {
708 if !is_ident_char(chars[i]) {
709 return None;
710 }
711 if i > 0 && is_ident_char(chars[i - 1]) {
712 return None;
713 }
714
715 let ident_start = i;
716 let mut j = i;
717 while j < chars.len() && is_ident_char(chars[j]) {
718 j += 1;
719 }
720 let ident: String = chars[ident_start..j].iter().collect();
721 if is_reserved_non_column_keyword(&ident) {
722 return None;
723 }
724
725 while j < chars.len() && chars[j].is_whitespace() {
726 j += 1;
727 }
728
729 j = match_op_tokens(chars, j, op)?;
730
731 while j < chars.len() && chars[j].is_whitespace() {
732 j += 1;
733 }
734
735 let ph_chars: Vec<char> = placeholder.chars().collect();
736 if j + ph_chars.len() > chars.len() {
737 return None;
738 }
739 for (k, pc) in ph_chars.iter().enumerate() {
740 if chars[j + k] != *pc {
741 return None;
742 }
743 }
744 j += ph_chars.len();
745
746 if j < chars.len() && chars[j].is_ascii_digit() {
747 return None;
748 }
749
750 Some((i, ident, j))
751}
752
753fn try_match_ph_op_col(chars: &[char], i: usize, op: &str, placeholder: &str) -> Option<(usize, String)> {
756 let ph_chars: Vec<char> = placeholder.chars().collect();
757 if i + ph_chars.len() > chars.len() {
758 return None;
759 }
760
761 if i > 0 && (chars[i - 1] == '$' || chars[i - 1].is_ascii_digit()) {
762 return None;
763 }
764
765 for (k, pc) in ph_chars.iter().enumerate() {
766 if chars[i + k] != *pc {
767 return None;
768 }
769 }
770 let mut j = i + ph_chars.len();
771
772 if j < chars.len() && chars[j].is_ascii_digit() {
773 return None;
774 }
775
776 while j < chars.len() && chars[j].is_whitespace() {
777 j += 1;
778 }
779
780 j = match_op_tokens(chars, j, op)?;
781
782 while j < chars.len() && chars[j].is_whitespace() {
783 j += 1;
784 }
785
786 if j >= chars.len() || !is_ident_char(chars[j]) {
787 return None;
788 }
789 let ident_start = j;
790 while j < chars.len() && is_ident_char(chars[j]) {
791 j += 1;
792 }
793 let ident: String = chars[ident_start..j].iter().collect();
794
795 if is_reserved_non_column_keyword(&ident) {
796 return None;
797 }
798
799 Some((j, ident))
800}
801
802pub(crate) fn clean_sql_with_optional(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
805 let cleaned = clean_sql(sql);
806 rewrite_optional_params(&cleaned, optional_params, params)
807}
808
809pub(crate) fn clean_sql_with_optional_pg(sql: &str, optional_params: &[String], params: &[AnalyzedParam]) -> String {
812 let cleaned = clean_sql(sql);
813 rewrite_optional_params_pg(&cleaned, optional_params, params)
814}
815
816pub(crate) fn clean_sql_oneline_with_optional(
819 sql: &str,
820 optional_params: &[String],
821 params: &[AnalyzedParam],
822) -> String {
823 let cleaned = clean_sql_oneline(sql);
824 rewrite_optional_params(&cleaned, optional_params, params)
825}
826
827pub(crate) fn clean_sql_oneline_with_optional_dialect(
829 sql: &str,
830 dialect: SqlDialect,
831 optional_params: &[String],
832 params: &[AnalyzedParam],
833) -> String {
834 let cleaned = clean_sql_oneline_dialect(sql, dialect);
835 rewrite_optional_params(&cleaned, optional_params, params)
836}
837
838fn is_ident_char(c: char) -> bool {
839 c.is_alphanumeric() || c == '_' || c == '.'
840}
841
842pub(crate) fn rewrite_pg_placeholders(sql: &str, formatter: impl Fn(u32) -> String) -> String {
862 let spans = tokenize_sql(sql, SqlDialect::PostgreSQL);
863 let uses_dollar_placeholders = spans
864 .iter()
865 .any(|(kind, text)| *kind == SqlSpanKind::Code && code_span_has_dollar_number(text));
866
867 let mut result = String::with_capacity(sql.len());
868 let mut positional_counter: u32 = 0;
869 let mut occurrences: Vec<u32> = Vec::new();
870 for (kind, text) in &spans {
871 if *kind == SqlSpanKind::Code {
872 rewrite_code_span_placeholders(
873 text,
874 !uses_dollar_placeholders,
875 &formatter,
876 &mut positional_counter,
877 &mut result,
878 &mut occurrences,
879 );
880 } else {
881 result.push_str(text);
882 }
883 }
884 result
885}
886
887fn dialect_allows_bare_question_mark_placeholder(dialect: SqlDialect) -> bool {
906 !matches!(dialect, SqlDialect::PostgreSQL)
907}
908
909pub(crate) fn rewrite_placeholders_indexed(
928 sql: &str,
929 dialect: SqlDialect,
930 formatter: impl Fn(u32) -> String,
931) -> (String, Vec<u32>) {
932 let spans = tokenize_sql(sql, dialect);
933 let bare_question_is_placeholder = dialect_allows_bare_question_mark_placeholder(dialect);
934
935 let mut result = String::with_capacity(sql.len());
936 let mut positional_counter: u32 = 0;
937 let mut occurrences: Vec<u32> = Vec::new();
938 for (kind, text) in &spans {
939 if *kind == SqlSpanKind::Code {
940 rewrite_code_span_placeholders(
941 text,
942 bare_question_is_placeholder,
943 &formatter,
944 &mut positional_counter,
945 &mut result,
946 &mut occurrences,
947 );
948 } else {
949 result.push_str(text);
950 }
951 }
952 (result, occurrences)
953}
954
955pub(crate) fn resolved_param_for_position<'a>(
974 analyzed_params: &[AnalyzedParam],
975 resolved: &'a [ResolvedParam],
976 position: u32,
977) -> &'a ResolvedParam {
978 let idx = analyzed_params
979 .iter()
980 .position(|p| p.position == i64::from(position))
981 .unwrap_or_else(|| panic!("no analyzed parameter at position {position}; analyzed_params={analyzed_params:?}"));
982 &resolved[idx]
983}
984
985pub(crate) fn rewrite_pg_typed_placeholders(
987 sql: &str,
988 analyzed_params: &[AnalyzedParam],
989 resolved_params: &[ResolvedParam],
990 cast_enums: bool,
991 formatter: impl Fn(u32) -> String,
992) -> (String, Vec<u32>) {
993 rewrite_placeholders_indexed(sql, SqlDialect::PostgreSQL, |position| {
994 let mut placeholder = formatter(position);
995 let param = resolved_param_for_position(analyzed_params, resolved_params, position);
996 if cast_enums && let Some(enum_type) = param.neutral_type.strip_prefix("enum::") {
997 placeholder.push_str("::");
998 placeholder.push_str(enum_type);
999 } else if let Some(composite_type) = param.neutral_type.strip_prefix("composite::") {
1000 placeholder.push_str("::text::");
1001 placeholder.push_str(composite_type);
1002 }
1003 placeholder
1004 })
1005}
1006
1007fn code_span_has_dollar_number(text: &str) -> bool {
1010 let chars: Vec<char> = text.chars().collect();
1011 (0..chars.len()).any(|i| chars[i] == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()))
1012}
1013
1014const UNAMBIGUOUS_OPERATORS: [&str; 6] = ["?-|", "?||", "?|", "?&", "?-", "@?"];
1022
1023fn match_unambiguous_operator(chars: &[char], i: usize) -> Option<usize> {
1026 UNAMBIGUOUS_OPERATORS.iter().find_map(|op| {
1027 let op_chars: Vec<char> = op.chars().collect();
1028 let end = i + op_chars.len();
1029 (end <= chars.len() && chars[i..end] == op_chars[..]).then_some(op_chars.len())
1030 })
1031}
1032
1033fn rewrite_code_span_placeholders(
1047 text: &str,
1048 bare_question_is_placeholder: bool,
1049 formatter: &impl Fn(u32) -> String,
1050 counter: &mut u32,
1051 out: &mut String,
1052 occurrences: &mut Vec<u32>,
1053) {
1054 let chars: Vec<char> = text.chars().collect();
1055 let len = chars.len();
1056 let mut i = 0;
1057 while i < len {
1058 if let Some(op_len) = match_unambiguous_operator(&chars, i) {
1059 out.extend(&chars[i..i + op_len]);
1060 i += op_len;
1061 continue;
1062 }
1063
1064 let ch = chars[i];
1065 if ch == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
1066 let mut j = i + 1;
1067 let mut num_str = String::new();
1068 while j < len && chars[j].is_ascii_digit() {
1069 num_str.push(chars[j]);
1070 j += 1;
1071 }
1072 let num: u32 = num_str.parse().unwrap_or(0);
1073 out.push_str(&formatter(num));
1074 occurrences.push(num);
1075 i = j;
1076 } else if ch == '?' && bare_question_is_placeholder && !chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
1077 *counter += 1;
1078 out.push_str(&formatter(*counter));
1079 occurrences.push(*counter);
1080 i += 1;
1081 } else {
1082 out.push(ch);
1083 i += 1;
1084 }
1085 }
1086}
1087
1088pub fn get_backend(name: &str, engine: &str) -> Result<Box<dyn CodegenBackend>, ScytheError> {
1093 let canonical_engine = normalize_engine(engine);
1094 let backend: Box<dyn CodegenBackend> = match name {
1095 "rust-sqlx" | "sqlx" | "rust" => Box::new(sqlx::SqlxBackend::new(canonical_engine)?),
1096 "rust-tokio-postgres" | "tokio-postgres" => {
1097 Box::new(tokio_postgres::TokioPostgresBackend::new(canonical_engine)?)
1098 }
1099 "python-psycopg3" | "python" => Box::new(python_psycopg3::PythonPsycopg3Backend::new(canonical_engine)?),
1100 "python-asyncpg" => Box::new(python_asyncpg::PythonAsyncpgBackend::new(canonical_engine)?),
1101 "python-aiomysql" => Box::new(python_aiomysql::PythonAiomysqlBackend::new(canonical_engine)?),
1102 "python-aiosqlite" => Box::new(python_aiosqlite::PythonAiosqliteBackend::new(canonical_engine)?),
1103 "python-duckdb" => Box::new(python_duckdb::PythonDuckdbBackend::new(canonical_engine)?),
1104 "typescript-postgres" | "ts" | "typescript" => {
1105 Box::new(typescript_postgres::TypescriptPostgresBackend::new(canonical_engine)?)
1106 }
1107 "javascript-postgres" => Box::new(typescript_postgres::TypescriptPostgresBackend::new_js(
1108 canonical_engine,
1109 )?),
1110 "typescript-pg" => Box::new(typescript_pg::TypescriptPgBackend::new(canonical_engine)?),
1111 "javascript-pg" => Box::new(typescript_pg::TypescriptPgBackend::new_js(canonical_engine)?),
1112 "typescript-mysql2" => Box::new(typescript_mysql2::TypescriptMysql2Backend::new(canonical_engine)?),
1113 "javascript-mysql2" => Box::new(typescript_mysql2::TypescriptMysql2Backend::new_js(canonical_engine)?),
1114 "typescript-better-sqlite3" => Box::new(typescript_better_sqlite3::TypescriptBetterSqlite3Backend::new(
1115 canonical_engine,
1116 )?),
1117 "javascript-better-sqlite3" => Box::new(typescript_better_sqlite3::TypescriptBetterSqlite3Backend::new_js(
1118 canonical_engine,
1119 )?),
1120 "typescript-duckdb" => Box::new(typescript_duckdb::TypescriptDuckdbBackend::new(canonical_engine)?),
1121 "javascript-duckdb" => Box::new(typescript_duckdb::TypescriptDuckdbBackend::new_js(canonical_engine)?),
1122 "typescript-node-sqlite" => Box::new(typescript_node_sqlite::TypescriptNodeSqliteBackend::new(
1123 canonical_engine,
1124 )?),
1125 "javascript-node-sqlite" => Box::new(typescript_node_sqlite::TypescriptNodeSqliteBackend::new_js(
1126 canonical_engine,
1127 )?),
1128 "typescript-wasm-sqlite" => Box::new(typescript_wasm_sqlite::TypescriptWasmSqliteBackend::new(
1129 canonical_engine,
1130 )?),
1131 "javascript-wasm-sqlite" => Box::new(typescript_wasm_sqlite::TypescriptWasmSqliteBackend::new_js(
1132 canonical_engine,
1133 )?),
1134 "typescript-kysely" | "kysely" => Box::new(typescript_kysely::TypescriptKyselyBackend::new(canonical_engine)?),
1135 "go-database-sql" => Box::new(go_database_sql::GoDatabaseSqlBackend::new(canonical_engine)?),
1136 "go-pgx" | "go" => Box::new(go_pgx::GoPgxBackend::new(canonical_engine)?),
1137 "java-jdbc" | "java" => Box::new(java_jdbc::JavaJdbcBackend::new(canonical_engine)?),
1138 "java-r2dbc" | "r2dbc-java" => Box::new(java_r2dbc::JavaR2dbcBackend::new(canonical_engine)?),
1139 "kotlin-exposed" | "exposed" => Box::new(kotlin_exposed::KotlinExposedBackend::new(canonical_engine)?),
1140 "kotlin-jdbc" | "kotlin" | "kt" => Box::new(kotlin_jdbc::KotlinJdbcBackend::new(canonical_engine)?),
1141 "kotlin-r2dbc" | "r2dbc-kotlin" => Box::new(kotlin_r2dbc::KotlinR2dbcBackend::new(canonical_engine)?),
1142 "csharp-npgsql" | "csharp" | "c#" | "dotnet" => {
1143 Box::new(csharp_npgsql::CsharpNpgsqlBackend::new(canonical_engine)?)
1144 }
1145 "csharp-mysqlconnector" => Box::new(csharp_mysqlconnector::CsharpMysqlConnectorBackend::new(
1146 canonical_engine,
1147 )?),
1148 "csharp-microsoft-sqlite" => Box::new(csharp_microsoft_sqlite::CsharpMicrosoftSqliteBackend::new(
1149 canonical_engine,
1150 )?),
1151 "elixir-postgrex" | "elixir" | "ex" => Box::new(elixir_postgrex::ElixirPostgrexBackend::new(canonical_engine)?),
1152 "elixir-ecto" | "ecto" => Box::new(elixir_ecto::ElixirEctoBackend::new(canonical_engine)?),
1153 "elixir-myxql" => Box::new(elixir_myxql::ElixirMyxqlBackend::new(canonical_engine)?),
1154 "elixir-exqlite" => Box::new(elixir_exqlite::ElixirExqliteBackend::new(canonical_engine)?),
1155 "ruby-pg" | "ruby" | "rb" => Box::new(ruby_pg::RubyPgBackend::new(canonical_engine)?),
1156 "ruby-mysql2" => Box::new(ruby_mysql2::RubyMysql2Backend::new(canonical_engine)?),
1157 "ruby-sqlite3" => Box::new(ruby_sqlite3::RubySqlite3Backend::new(canonical_engine)?),
1158 "ruby-trilogy" | "trilogy" => Box::new(ruby_trilogy::RubyTrilogyBackend::new(canonical_engine)?),
1159 "php-pdo" | "php" => Box::new(php_pdo::PhpPdoBackend::new(canonical_engine)?),
1160 "php-amphp" | "amphp" => Box::new(php_amphp::PhpAmphpBackend::new(canonical_engine)?),
1161 "rust-tiberius" | "tiberius" => Box::new(rust_tiberius::RustTiberiusBackend::new(canonical_engine)?),
1162 "python-pyodbc" | "pyodbc" => Box::new(python_pyodbc::PythonPyodbcBackend::new(canonical_engine)?),
1163 "typescript-mssql" | "tedious" => Box::new(typescript_mssql::TypescriptMssqlBackend::new(canonical_engine)?),
1164 "javascript-mssql" => Box::new(typescript_mssql::TypescriptMssqlBackend::new_js(canonical_engine)?),
1165 "csharp-sqlclient" => Box::new(csharp_sqlclient::CsharpSqlClientBackend::new(canonical_engine)?),
1166 "ruby-tiny-tds" | "tiny-tds" | "tiny_tds" => {
1167 Box::new(ruby_tiny_tds::RubyTinyTdsBackend::new(canonical_engine)?)
1168 }
1169 "elixir-tds" | "tds" => Box::new(elixir_tds::ElixirTdsBackend::new(canonical_engine)?),
1170 "rust-sibyl" | "sibyl" => Box::new(rust_sibyl::RustSibylBackend::new(canonical_engine)?),
1171 "python-oracledb" | "oracledb" => Box::new(python_oracledb::PythonOracledbBackend::new(canonical_engine)?),
1172 "typescript-oracledb" => Box::new(typescript_oracledb::TypescriptOracledbBackend::new(canonical_engine)?),
1173 "javascript-oracledb" => Box::new(typescript_oracledb::TypescriptOracledbBackend::new_js(
1174 canonical_engine,
1175 )?),
1176 "go-godror" | "godror" => Box::new(go_godror::GoGodrorBackend::new(canonical_engine)?),
1177 "csharp-oracle" => Box::new(csharp_oracle::CsharpOracleBackend::new(canonical_engine)?),
1178 "ruby-oci8" | "oci8" => Box::new(ruby_oci8::RubyOci8Backend::new(canonical_engine)?),
1179 "elixir-jamdb" | "jamdb" => Box::new(elixir_jamdb::ElixirJamdbBackend::new(canonical_engine)?),
1180 "python-snowflake" => Box::new(python_snowflake::PythonSnowflakeBackend::new(canonical_engine)?),
1181 "typescript-snowflake" => Box::new(typescript_snowflake::TypescriptSnowflakeBackend::new(canonical_engine)?),
1182 "javascript-snowflake" => Box::new(typescript_snowflake::TypescriptSnowflakeBackend::new_js(
1183 canonical_engine,
1184 )?),
1185 "go-gosnowflake" | "gosnowflake" => Box::new(go_gosnowflake::GoGosnowflakeBackend::new(canonical_engine)?),
1186 "csharp-snowflake" => Box::new(csharp_snowflake::CsharpSnowflakeBackend::new(canonical_engine)?),
1187 _ => {
1188 return Err(ScytheError::new(
1189 ErrorCode::InvalidConfig,
1190 format!("unknown backend: {}", name),
1191 ));
1192 }
1193 };
1194
1195 if !backend
1196 .supported_engines()
1197 .iter()
1198 .any(|e| normalize_engine(e) == canonical_engine)
1199 {
1200 return Err(ScytheError::new(
1201 ErrorCode::InvalidConfig,
1202 format!(
1203 "backend '{}' does not support engine '{}'. Supported: {:?}",
1204 name,
1205 engine,
1206 backend.supported_engines()
1207 ),
1208 ));
1209 }
1210
1211 Ok(backend)
1212}
1213
1214pub fn normalize_engine(engine: &str) -> &str {
1221 match engine {
1222 "postgresql" | "postgres" | "pg" | "cockroachdb" | "crdb" => "postgresql",
1223 "mysql" => "mysql",
1224 "mariadb" => "mariadb",
1225 "sqlite" | "sqlite3" => "sqlite",
1226 "duckdb" => "duckdb",
1227 "mssql" | "sqlserver" | "tsql" => "mssql",
1228 "oracle" => "oracle",
1229 "snowflake" => "snowflake",
1230 "redshift" => "redshift",
1231 other => other,
1232 }
1233}
1234
1235#[cfg(test)]
1240mod sql_text_characterization_tests;
1241
1242#[cfg(test)]
1243mod tests {
1244 use super::*;
1245
1246 fn param(name: &str, position: i64) -> AnalyzedParam {
1247 AnalyzedParam {
1248 name: name.to_string(),
1249 neutral_type: "string".to_string(),
1250 nullable: true,
1251 position,
1252 source_relation: None,
1253 }
1254 }
1255
1256 fn resolved_param(name: &str, neutral_type: &str) -> ResolvedParam {
1257 ResolvedParam {
1258 name: name.to_string(),
1259 field_name: name.to_string(),
1260 lang_type: "String".to_string(),
1261 full_type: "String".to_string(),
1262 borrowed_type: "&str".to_string(),
1263 neutral_type: neutral_type.to_string(),
1264 nullable: false,
1265 }
1266 }
1267
1268 #[test]
1269 fn typed_placeholder_casts_only_rewrite_live_tokens_and_keep_number_boundaries() {
1270 let analyzed: Vec<AnalyzedParam> = (1..=10)
1271 .map(|position| param(&format!("p{position}"), position))
1272 .collect();
1273 let resolved: Vec<ResolvedParam> = (1..=10)
1274 .map(|position| {
1275 let neutral_type = match position {
1276 1 => "composite::address",
1277 10 => "enum::status",
1278 _ => "string",
1279 };
1280 resolved_param(&format!("p{position}"), neutral_type)
1281 })
1282 .collect();
1283 let sql = "SELECT $1, $10, '$1', \"$10\", $$ $1 $10 $$ -- $1\n/* $10 */ WHERE x = $2";
1284
1285 let (rewritten, occurrences) =
1286 rewrite_pg_typed_placeholders(sql, &analyzed, &resolved, true, |position| format!("@p{position}"));
1287
1288 assert_eq!(
1289 rewritten,
1290 "SELECT @p1::text::address, @p10::status, '$1', \"$10\", $$ $1 $10 $$ -- $1\n/* $10 */ WHERE x = @p2"
1291 );
1292 assert_eq!(occurrences, vec![1, 10, 2]);
1293 }
1294
1295 #[test]
1307 fn test_no_backends_relative_manifest_path_literals() {
1308 let root = concat!(env!("CARGO_MANIFEST_DIR"), "/src/backends");
1309 let word: String = format!("backend{}", "s/");
1310 let needle: String = format!("{}{}", '"', word);
1311
1312 let mut offenders = Vec::new();
1313 collect_rs_files(std::path::Path::new(root), &mut offenders);
1314
1315 let offenders: Vec<_> = offenders
1316 .into_iter()
1317 .filter(|path| {
1318 let contents = std::fs::read_to_string(path).expect("failed to read source file");
1319 contents.contains(&needle)
1320 })
1321 .collect();
1322
1323 assert!(
1324 offenders.is_empty(),
1325 "found a working-directory-relative manifest path literal in: {offenders:?} (#82 regression \
1326 -- manifest selection must be a pure function of (backend, engine), no filesystem lookup)"
1327 );
1328 }
1329
1330 fn collect_rs_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
1332 let entries = std::fs::read_dir(dir).expect("failed to read backends dir");
1333 for entry in entries {
1334 let entry = entry.expect("failed to read dir entry");
1335 let path = entry.path();
1336 if path.is_dir() {
1337 collect_rs_files(&path, out);
1338 } else if path.extension().and_then(|e| e.to_str()) == Some("rs") {
1339 out.push(path);
1340 }
1341 }
1342 }
1343
1344 #[test]
1350 fn test_get_backend_rust_sqlx_mysql_has_no_postgresql_scalars() {
1351 let backend = get_backend("rust-sqlx", "mysql").expect("rust-sqlx should support mysql");
1352 let scalars = &backend.manifest().types.scalars;
1353 assert_ne!(
1354 scalars.get("uuid").map(String::as_str),
1355 Some("uuid::Uuid"),
1356 "rust-sqlx/mysql manifest should not carry the PostgreSQL-specific 'uuid' mapping"
1357 );
1358 assert_ne!(
1359 scalars.get("inet").map(String::as_str),
1360 Some("ipnetwork::IpNetwork"),
1361 "rust-sqlx/mysql manifest should not carry the PostgreSQL-specific 'inet' mapping"
1362 );
1363 }
1364
1365 #[test]
1366 fn test_get_backend_java_jdbc_sqlite_has_no_postgresql_scalars() {
1367 let backend = get_backend("java-jdbc", "sqlite").expect("java-jdbc should support sqlite");
1368 let scalars = &backend.manifest().types.scalars;
1369 assert_ne!(
1370 scalars.get("uuid").map(String::as_str),
1371 Some("java.util.UUID"),
1372 "java-jdbc/sqlite manifest should not carry the PostgreSQL-specific 'uuid' mapping"
1373 );
1374 assert_ne!(
1375 scalars.get("decimal").map(String::as_str),
1376 Some("java.math.BigDecimal"),
1377 "java-jdbc/sqlite manifest should not carry the PostgreSQL-specific 'decimal' mapping"
1378 );
1379 }
1380
1381 #[test]
1382 fn test_normalize_engine_cockroachdb() {
1383 assert_eq!(normalize_engine("cockroachdb"), "postgresql");
1384 assert_eq!(normalize_engine("crdb"), "postgresql");
1385 }
1386
1387 #[test]
1388 fn test_get_backend_cockroachdb_with_pg_backends() {
1389 let pg_backends = [
1390 "rust-sqlx",
1391 "rust-tokio-postgres",
1392 "python-psycopg3",
1393 "python-asyncpg",
1394 "typescript-postgres",
1395 "typescript-pg",
1396 "typescript-kysely",
1397 "go-pgx",
1398 "ruby-pg",
1399 "elixir-postgrex",
1400 "csharp-npgsql",
1401 "php-pdo",
1402 "php-amphp",
1403 ];
1404 for backend_name in &pg_backends {
1405 let result = get_backend(backend_name, "cockroachdb");
1406 assert!(
1407 result.is_ok(),
1408 "backend '{}' should accept cockroachdb engine, got: {:?}",
1409 backend_name,
1410 result.err()
1411 );
1412 }
1413 }
1414
1415 #[test]
1416 fn test_get_backend_crdb_alias() {
1417 let result = get_backend("rust-sqlx", "crdb");
1418 assert!(result.is_ok(), "rust-sqlx should accept 'crdb' engine alias");
1419 }
1420
1421 #[test]
1422 fn test_normalize_engine_duckdb() {
1423 assert_eq!(normalize_engine("duckdb"), "duckdb");
1424 }
1425
1426 #[test]
1427 fn test_get_backend_duckdb_with_compatible_backends() {
1428 let duckdb_backends = [
1429 "python-duckdb",
1430 "typescript-duckdb",
1431 "go-database-sql",
1432 "java-jdbc",
1433 "kotlin-jdbc",
1434 ];
1435 for backend_name in &duckdb_backends {
1436 let result = get_backend(backend_name, "duckdb");
1437 assert!(
1438 result.is_ok(),
1439 "backend '{}' should accept duckdb engine, got: {:?}",
1440 backend_name,
1441 result.err()
1442 );
1443 }
1444 }
1445
1446 #[test]
1447 fn test_get_backend_duckdb_rejected_by_pg_only() {
1448 let result = get_backend("rust-sqlx", "duckdb");
1449 assert!(result.is_err(), "rust-sqlx should reject duckdb engine");
1450 }
1451
1452 #[test]
1453 fn test_rewrite_simple_equality() {
1454 let sql = "SELECT * FROM users WHERE status = $1";
1455 let params = vec![param("status", 1)];
1456 let result = rewrite_optional_params(sql, &["status".to_string()], ¶ms);
1457 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR status = $1)");
1458 }
1459
1460 #[test]
1463 fn test_rewrite_pg_simple_equality_casts_the_placeholder() {
1464 let sql = "SELECT * FROM users WHERE status = $1";
1465 let params = vec![param("status", 1)];
1466 let result = rewrite_optional_params_pg(sql, &["status".to_string()], ¶ms);
1467 assert_eq!(result, "SELECT * FROM users WHERE ($1::text IS NULL OR status = $1)");
1468 }
1469
1470 #[test]
1471 fn test_rewrite_pg_casts_enum_array_and_json_but_not_unknown() {
1472 let mut enum_param = param("status", 1);
1473 enum_param.neutral_type = "enum::user_status".to_string();
1474 assert_eq!(
1475 rewrite_optional_params_pg(
1476 "SELECT * FROM users WHERE status = $1",
1477 &["status".to_string()],
1478 &[enum_param]
1479 ),
1480 "SELECT * FROM users WHERE ($1::user_status IS NULL OR status = $1)"
1481 );
1482
1483 let mut array_param = param("ids", 1);
1484 array_param.neutral_type = "array<int32>".to_string();
1485 assert_eq!(
1486 rewrite_optional_params_pg(
1487 "SELECT * FROM users WHERE id = $1",
1488 &["ids".to_string()],
1489 &[array_param]
1490 ),
1491 "SELECT * FROM users WHERE ($1::integer[] IS NULL OR id = $1)"
1492 );
1493
1494 let mut json_param = param("doc", 1);
1495 json_param.neutral_type = "json".to_string();
1496 assert_eq!(
1497 rewrite_optional_params_pg(
1498 "SELECT * FROM users WHERE doc = $1",
1499 &["doc".to_string()],
1500 &[json_param]
1501 ),
1502 "SELECT * FROM users WHERE ($1::jsonb IS NULL OR doc = $1)"
1503 );
1504
1505 let mut unknown_param = param("mystery", 1);
1506 unknown_param.neutral_type = "unknown".to_string();
1507 assert_eq!(
1508 rewrite_optional_params_pg(
1509 "SELECT * FROM users WHERE mystery = $1",
1510 &["mystery".to_string()],
1511 &[unknown_param]
1512 ),
1513 "SELECT * FROM users WHERE ($1 IS NULL OR mystery = $1)"
1514 );
1515 }
1516
1517 #[test]
1518 fn test_rewrite_qualified_column() {
1519 let sql = "SELECT * FROM users u WHERE u.status = $1";
1520 let params = vec![param("status", 1)];
1521 let result = rewrite_optional_params(sql, &["status".to_string()], ¶ms);
1522 assert_eq!(result, "SELECT * FROM users u WHERE ($1 IS NULL OR u.status = $1)");
1523 }
1524
1525 #[test]
1526 fn test_rewrite_multiple_optional() {
1527 let sql = "SELECT * FROM users WHERE status = $1 AND name = $2";
1528 let params = vec![param("status", 1), param("name", 2)];
1529 let result = rewrite_optional_params(sql, &["status".to_string(), "name".to_string()], ¶ms);
1530 assert_eq!(
1531 result,
1532 "SELECT * FROM users WHERE ($1 IS NULL OR status = $1) AND ($2 IS NULL OR name = $2)"
1533 );
1534 }
1535
1536 #[test]
1537 fn test_rewrite_mixed_optional_required() {
1538 let sql = "SELECT * FROM users WHERE id = $1 AND status = $2";
1539 let params = vec![param("id", 1), param("status", 2)];
1540 let result = rewrite_optional_params(sql, &["status".to_string()], ¶ms);
1541 assert_eq!(
1542 result,
1543 "SELECT * FROM users WHERE id = $1 AND ($2 IS NULL OR status = $2)"
1544 );
1545 }
1546
1547 #[test]
1548 fn test_rewrite_like_operator() {
1549 let sql = "SELECT * FROM users WHERE name LIKE $1";
1550 let params = vec![param("name", 1)];
1551 let result = rewrite_optional_params(sql, &["name".to_string()], ¶ms);
1552 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR name LIKE $1)");
1553 }
1554
1555 #[test]
1556 fn test_rewrite_ilike_operator() {
1557 let sql = "SELECT * FROM users WHERE name ILIKE $1";
1558 let params = vec![param("name", 1)];
1559 let result = rewrite_optional_params(sql, &["name".to_string()], ¶ms);
1560 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR name ILIKE $1)");
1561 }
1562
1563 #[test]
1564 fn test_rewrite_comparison_operators() {
1565 let sql = "SELECT * FROM users WHERE age >= $1";
1566 let params = vec![param("age", 1)];
1567 let result = rewrite_optional_params(sql, &["age".to_string()], ¶ms);
1568 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR age >= $1)");
1569 }
1570
1571 #[test]
1572 fn test_rewrite_less_than() {
1573 let sql = "SELECT * FROM users WHERE age < $1";
1574 let params = vec![param("age", 1)];
1575 let result = rewrite_optional_params(sql, &["age".to_string()], ¶ms);
1576 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR age < $1)");
1577 }
1578
1579 #[test]
1580 fn test_no_rewrite_without_optional() {
1581 let sql = "SELECT * FROM users WHERE status = $1";
1582 let params = vec![param("status", 1)];
1583 let result = rewrite_optional_params(sql, &[], ¶ms);
1584 assert_eq!(result, sql);
1585 }
1586
1587 #[test]
1588 fn test_rewrite_not_equal() {
1589 let sql = "SELECT * FROM users WHERE status <> $1";
1590 let params = vec![param("status", 1)];
1591 let result = rewrite_optional_params(sql, &["status".to_string()], ¶ms);
1592 assert_eq!(result, "SELECT * FROM users WHERE ($1 IS NULL OR status <> $1)");
1593 }
1594
1595 #[test]
1596 fn test_rewrite_does_not_match_similar_placeholder() {
1597 let sql = "SELECT * FROM users WHERE status = $10";
1598 let params = vec![param("status", 1)];
1599 let result = rewrite_optional_params(sql, &["status".to_string()], ¶ms);
1600 assert_eq!(result, sql);
1601 }
1602
1603 #[test]
1604 fn test_normalize_engine_mariadb() {
1605 assert_eq!(normalize_engine("mariadb"), "mariadb");
1606 }
1607
1608 #[test]
1609 fn test_get_backend_mariadb_with_mysql_backends() {
1610 let mariadb_backends = [
1611 "rust-sqlx",
1612 "python-aiomysql",
1613 "typescript-mysql2",
1614 "go-database-sql",
1615 "java-jdbc",
1616 "java-r2dbc",
1617 "kotlin-jdbc",
1618 "kotlin-r2dbc",
1619 "csharp-mysqlconnector",
1620 "elixir-myxql",
1621 "ruby-mysql2",
1622 "ruby-trilogy",
1623 "php-pdo",
1624 "php-amphp",
1625 ];
1626 for backend_name in &mariadb_backends {
1627 let result = get_backend(backend_name, "mariadb");
1628 assert!(
1629 result.is_ok(),
1630 "backend '{}' should accept mariadb engine, got: {:?}",
1631 backend_name,
1632 result.err()
1633 );
1634 }
1635 }
1636
1637 #[test]
1647 fn test_clean_sql_oneline_strips_mid_line_comment_but_keeps_rest_of_query() {
1648 let sql = "SELECT id, name\nFROM users\nWHERE id > $1 -- skip low ids\n AND name IS NOT NULL;";
1649 let result = clean_sql_oneline(sql);
1650 assert!(
1651 result.contains("AND name IS NOT NULL"),
1652 "mid-line comment must not swallow the rest of the query, got: {result:?}"
1653 );
1654 assert!(
1655 !result.contains("--"),
1656 "comment marker must be stripped, got: {result:?}"
1657 );
1658 }
1659
1660 #[test]
1661 fn test_clean_sql_strips_mid_line_comment_but_keeps_rest_of_query() {
1662 let sql = "SELECT id\nFROM users\nWHERE id > $1 -- skip low ids\nAND active = true;";
1663 let result = clean_sql(sql);
1664 assert!(result.contains("AND active = true"), "got: {result:?}");
1665 assert!(!result.contains("--"), "got: {result:?}");
1666 }
1667
1668 #[test]
1669 fn test_clean_sql_preserves_double_dash_inside_single_quoted_string() {
1670 let sql = "SELECT * FROM t WHERE label = 'a -- not a comment' AND id = $1;";
1671 let result = clean_sql_oneline(sql);
1672 assert!(result.contains("'a -- not a comment'"), "got: {result:?}");
1673 assert!(result.contains("id = $1"), "got: {result:?}");
1674 }
1675
1676 #[test]
1677 fn test_clean_sql_preserves_double_dash_inside_double_quoted_identifier() {
1678 let sql = "SELECT \"weird--col\" FROM t WHERE id = $1;";
1679 let result = clean_sql_oneline(sql);
1680 assert!(result.contains("\"weird--col\""), "got: {result:?}");
1681 }
1682
1683 #[test]
1684 fn test_clean_sql_preserves_double_dash_inside_dollar_quoted_string() {
1685 let sql = "SELECT $$has -- inside$$ AS x FROM t WHERE id = $1;";
1686 let result = clean_sql_oneline(sql);
1687 assert!(result.contains("$$has -- inside$$"), "got: {result:?}");
1688 }
1689
1690 #[test]
1691 fn test_clean_sql_strips_nested_block_comments() {
1692 let sql = "SELECT id /* outer /* inner */ still outer */ FROM t WHERE id = $1;";
1693 let result = clean_sql_oneline(sql);
1694 assert!(!result.contains("outer"), "got: {result:?}");
1695 assert!(!result.contains("inner"), "got: {result:?}");
1696 assert!(result.contains("SELECT id"), "got: {result:?}");
1697 assert!(result.contains("FROM t WHERE id = $1"), "got: {result:?}");
1698 }
1699
1700 #[test]
1701 fn test_clean_sql_unterminated_block_comment_consumes_to_end_without_panicking() {
1702 let sql = "SELECT id FROM t /* oops forgot to close";
1703 let result = clean_sql_oneline(sql);
1704 assert_eq!(result, "SELECT id FROM t");
1705 }
1706
1707 #[test]
1708 fn test_clean_sql_drops_lines_that_are_only_a_header_comment() {
1709 let sql = "-- @name Foo\n-- @returns :many\nSELECT id FROM t WHERE id = $1;";
1713 let result = clean_sql(sql);
1714 assert_eq!(result, "SELECT id FROM t WHERE id = $1");
1715 }
1716
1717 #[test]
1718 fn test_rewrite_pg_placeholders_preserves_dollar_quoted_body() {
1719 let sql =
1720 "SELECT id FROM t WHERE body = $$literal -- not comment, ' quote, $1 not a placeholder$$ AND id = $2;";
1721 let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1722 assert!(
1723 result.contains("$$literal -- not comment, ' quote, $1 not a placeholder$$"),
1724 "dollar-quoted body must survive untouched, got: {result:?}"
1725 );
1726 assert!(result.contains("id = @p2"), "got: {result:?}");
1727 }
1728
1729 #[test]
1730 fn test_rewrite_pg_placeholders_handles_escaped_single_quotes() {
1731 let sql = "SELECT id FROM t WHERE label = 'it''s $1 not a placeholder' AND id = $2;";
1732 let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1733 assert!(result.contains("'it''s $1 not a placeholder'"), "got: {result:?}");
1734 assert!(result.contains("id = @p2"), "got: {result:?}");
1735 }
1736
1737 #[test]
1738 fn test_rewrite_pg_placeholders_preserves_jsonb_operators() {
1739 let sql = "SELECT id FROM docs WHERE data ? 'mykey' AND tags ?| array['a','b'] AND tags ?& array['a','b'] AND id = $1;";
1740 let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1741 assert!(result.contains("data ? 'mykey'"), "got: {result:?}");
1742 assert!(result.contains("tags ?| array"), "got: {result:?}");
1743 assert!(result.contains("tags ?& array"), "got: {result:?}");
1744 assert!(result.contains("id = @p1"), "got: {result:?}");
1745 }
1746
1747 #[test]
1756 fn test_rewrite_pg_placeholders_preserves_jsonb_multi_char_operators_with_zero_dollar_placeholders() {
1757 let sql = "SELECT * FROM docs WHERE data ? 'active' AND tags ?| ARRAY['a'] AND meta ?& ARRAY['b']";
1758 let result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1759 assert!(result.contains("tags ?| ARRAY['a']"), "got: {result:?}");
1760 assert!(result.contains("meta ?& ARRAY['b']"), "got: {result:?}");
1761 }
1762
1763 #[test]
1764 fn test_rewrite_pg_placeholders_preserves_geometry_operators() {
1765 let sql = "SELECT id FROM shapes WHERE line1 ?- line2 AND line1 ?-| line2 AND line1 ?|| line2 AND id = $1;";
1766 let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1767 assert!(result.contains("line1 ?- line2"), "got: {result:?}");
1768 assert!(result.contains("line1 ?-| line2"), "got: {result:?}");
1769 assert!(result.contains("line1 ?|| line2"), "got: {result:?}");
1770 assert!(result.contains("id = @p1"), "got: {result:?}");
1771 }
1772
1773 #[test]
1774 fn test_rewrite_pg_placeholders_preserves_operators_mixed_with_dollar_placeholder() {
1775 let sql = "SELECT id FROM docs WHERE tags ?| ARRAY['a'] AND doc @? '$.a' AND id = $1;";
1776 let result = rewrite_pg_placeholders(sql, |n| format!("@p{n}"));
1777 assert!(result.contains("tags ?| ARRAY['a']"), "got: {result:?}");
1778 assert!(result.contains("doc @? '$.a'"), "got: {result:?}");
1779 assert!(result.contains("id = @p1"), "got: {result:?}");
1780 }
1781
1782 #[test]
1783 fn test_rewrite_pg_placeholders_number_boundary() {
1784 let sql = "SELECT $1, $10, $1x";
1785 let result = rewrite_pg_placeholders(sql, |n| format!("P{n}"));
1786 assert_eq!(result, "SELECT P1, P10, P1x");
1787 }
1788
1789 #[test]
1790 fn test_rewrite_pg_placeholders_ignores_question_mark_inside_string_literal() {
1791 let sql = "SELECT id FROM t WHERE note = 'is this a question?' AND age > ?;";
1792 let result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1793 assert!(result.contains("'is this a question?'"), "got: {result:?}");
1794 assert!(result.contains("age > $1"), "got: {result:?}");
1795 }
1796
1797 #[test]
1798 fn test_clean_sql_handles_non_ascii_in_comment_and_string() {
1799 let sql = "SELECT name -- 名前を取得 comment\nFROM t WHERE label = 'héllo wörld' AND id = $1;";
1800 let result = clean_sql_oneline(sql);
1801 assert!(!result.contains('名'), "got: {result:?}");
1802 assert!(result.contains("'héllo wörld'"), "got: {result:?}");
1803 assert!(result.contains("id = $1"), "got: {result:?}");
1804 }
1805
1806 #[test]
1807 fn test_clean_sql_handles_crlf_line_endings() {
1808 let sql = "SELECT id\r\nFROM users\r\n-- a comment\r\nWHERE id = $1;";
1809 let result = clean_sql(sql);
1810 assert!(!result.contains('\r'), "got: {result:?}");
1811 assert!(!result.contains("-- a comment"), "got: {result:?}");
1812 assert_eq!(result, "SELECT id\nFROM users\nWHERE id = $1");
1813 }
1814
1815 #[test]
1816 fn test_rewrite_optional_params_handles_not_like() {
1817 let sql = "SELECT id FROM t WHERE name NOT LIKE $1";
1818 let params = vec![param("name", 1)];
1819 let result = rewrite_optional_params(sql, &["name".to_string()], ¶ms);
1820 assert_eq!(result, "SELECT id FROM t WHERE ($1 IS NULL OR name NOT LIKE $1)");
1821 }
1822
1823 #[test]
1845 fn test_bare_question_mark_is_never_a_placeholder_under_postgresql_even_with_zero_dollar_placeholders() {
1846 let sql = "SELECT * FROM docs WHERE data ? 'active'";
1847
1848 let old_result = rewrite_pg_placeholders(sql, |n| format!("${n}"));
1849 assert_eq!(
1850 old_result, "SELECT * FROM docs WHERE data $1 'active'",
1851 "pins the OLD heuristic's corruption of the JSONB operator"
1852 );
1853
1854 let (new_result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::PostgreSQL, |n| format!("${n}"));
1855 assert_eq!(
1856 new_result, sql,
1857 "dialect-driven rewrite must leave the JSONB operator untouched"
1858 );
1859 assert!(
1860 occurrences.is_empty(),
1861 "no placeholder was ever present; got: {occurrences:?}"
1862 );
1863 }
1864
1865 #[test]
1869 fn test_bare_question_mark_is_a_placeholder_under_mysql() {
1870 let sql = "SELECT * FROM docs WHERE data ? 'active'";
1871 let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MySQL, |n| format!("${n}"));
1872 assert_eq!(result, "SELECT * FROM docs WHERE data $1 'active'");
1873 assert_eq!(occurrences, vec![1]);
1874 }
1875
1876 #[test]
1881 fn test_rewrite_placeholders_indexed_returns_positions_in_textual_order_out_of_order() {
1882 let (result, occurrences) =
1883 rewrite_placeholders_indexed("WHERE b = $2 AND a = $1", SqlDialect::PostgreSQL, |_| "?".to_string());
1884 assert_eq!(result, "WHERE b = ? AND a = ?");
1885 assert_eq!(occurrences, vec![2, 1]);
1886 }
1887
1888 #[test]
1892 fn test_rewrite_placeholders_indexed_repeated_placeholder_reports_one_occurrence_per_use() {
1893 let (result, occurrences) =
1894 rewrite_placeholders_indexed("WHERE a = $1 OR b = $1", SqlDialect::PostgreSQL, |_| "?".to_string());
1895 assert_eq!(result, "WHERE a = ? OR b = ?");
1896 assert_eq!(occurrences, vec![1, 1]);
1897 }
1898
1899 #[test]
1906 fn test_mysql_backtick_identifier_is_not_corrupted_by_bare_question_mark() {
1907 let sql = "SELECT `a?b` FROM t WHERE c = ?";
1908 let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MySQL, |n| format!("[P{n}]"));
1909 assert_eq!(result, "SELECT `a?b` FROM t WHERE c = [P1]");
1910 assert_eq!(occurrences, vec![1]);
1911 }
1912
1913 #[test]
1915 fn test_mssql_bracket_identifier_is_not_corrupted_by_bare_question_mark() {
1916 let sql = "SELECT [a?b] FROM t WHERE c = ?";
1917 let (result, occurrences) = rewrite_placeholders_indexed(sql, SqlDialect::MsSql, |n| format!("[P{n}]"));
1918 assert_eq!(result, "SELECT [a?b] FROM t WHERE c = [P1]");
1919 assert_eq!(occurrences, vec![1]);
1920 }
1921
1922 #[test]
1929 fn test_clean_sql_dialect_mysql_backtick_preserves_double_dash_inside() {
1930 let sql = "SELECT `a -- b` FROM t";
1931 assert_eq!(
1932 clean_sql(sql),
1933 "SELECT `a",
1934 "pins the OLD dialect-blind clean_sql's corruption"
1935 );
1936 assert_eq!(clean_sql_dialect(sql, SqlDialect::MySQL), sql);
1937 }
1938
1939 #[test]
1941 fn test_clean_sql_dialect_mssql_bracket_preserves_double_dash_inside() {
1942 let sql = "SELECT [a -- b] FROM t";
1943 assert_eq!(
1944 clean_sql(sql),
1945 "SELECT [a",
1946 "pins the OLD dialect-blind clean_sql's corruption"
1947 );
1948 assert_eq!(clean_sql_dialect(sql, SqlDialect::MsSql), sql);
1949 }
1950
1951 #[test]
1956 fn test_clean_sql_dialect_mysql_hash_comment_is_stripped() {
1957 let sql = "SELECT 1 # note\nFROM t";
1958 assert_eq!(
1959 clean_sql(sql),
1960 "SELECT 1 # note\nFROM t",
1961 "pins the OLD dialect-blind clean_sql leaving the # comment in place"
1962 );
1963 assert_eq!(clean_sql_dialect(sql, SqlDialect::MySQL), "SELECT 1 \nFROM t");
1968 }
1969
1970 #[test]
1974 fn test_clean_sql_oneline_dialect_mysql_hash_comment_is_stripped() {
1975 let sql = "SELECT 1 # note\nFROM t";
1976 assert_eq!(clean_sql_oneline_dialect(sql, SqlDialect::MySQL), "SELECT 1 FROM t");
1977 }
1978
1979 #[test]
1983 fn test_clean_sql_dialect_postgresql_hash_is_not_a_comment() {
1984 let sql = "SELECT data #> '{a,b}' AS x FROM t";
1985 assert_eq!(clean_sql_dialect(sql, SqlDialect::PostgreSQL), sql);
1986 }
1987}