Skip to main content

kumosql_sql/
sqlx.rs

1//! Dataform SQLX handling shared by every reader and rewrite.
2//!
3//! Mirrors `kumo_sql_prover.sqlx` and `sqlx_fragments`. A SQLX file splits into `config`, `js`,
4//! `pre_operations`, `post_operations` and `input "name"` blocks (kept byte for byte) and SQL
5//! sections. `${...}` interpolations in SQL are masked with SQL-safe sentinels for parsing and
6//! restored afterwards; a restore that finds a sentinel lost or duplicated fails rather than
7//! producing different SQL.
8//!
9//! Dataform leaves a `${...}` inside a `--` or `/* */` comment as text, so those are never masked
10//! or read as references. A `#` comment is not one of them: `@dataform/cli` 3.0.71 evaluates
11//! `${ref(...)}` after `#`.
12
13use std::sync::OnceLock;
14
15use indexmap::IndexMap;
16use regex::{Match, Regex};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19
20use crate::error::{Result, SqlError};
21use crate::js::{parse_lenient, skip_js_braces, skip_js_string, JsValue};
22use crate::token::{tokenize, Span, TokenKind};
23
24// ------------------------------------------------------------------------ detection
25
26fn block_re() -> &'static Regex {
27    static RE: OnceLock<Regex> = OnceLock::new();
28    RE.get_or_init(|| {
29        Regex::new(
30            r#"(?im)^[ \t]*(?:(config|js|pre_operations|post_operations)|input\s+(?:"([^"\n]*)"|'([^'\n]*)'))\s*\{"#,
31        )
32        .expect("valid regex")
33    })
34}
35
36/// Whether `text` looks like Dataform SQLX: it has a block (`config {`, `js {`, ...) at the start
37/// of a line, or a `${` anywhere.
38pub fn looks_like_sqlx(text: &str) -> bool {
39    block_re().is_match(text) || text.contains("${")
40}
41
42/// File text from bytes: UTF-8 with any byte-order mark dropped (it would hide a leading config
43/// block), else Windows-1252.
44pub fn decode_sqlx_bytes(bytes: &[u8]) -> String {
45    let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
46    match std::str::from_utf8(body) {
47        Ok(text) => text.to_string(),
48        Err(_) => {
49            let (text, _) = encoding_rs::WINDOWS_1252.decode_without_bom_handling(body);
50            text.into_owned()
51        }
52    }
53}
54
55// ------------------------------------------------------------------------ sections
56
57/// What a section of a SQLX file is.
58#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
59pub enum SqlxSectionKind {
60    Sql,
61    Config,
62    Js,
63    PreOperations,
64    PostOperations,
65    /// `input "name" { ... }` of a Dataform test.
66    Input(String),
67}
68
69/// One section with its exact text and where it sits in the file.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct SqlxSection {
72    pub kind: SqlxSectionKind,
73    pub text: String,
74    pub span: Span,
75}
76
77impl SqlxSection {
78    pub fn is_block(&self) -> bool {
79        self.kind != SqlxSectionKind::Sql
80    }
81
82    /// A block's text between its outer braces; a SQL section's whole text.
83    pub fn body(&self) -> &str {
84        if !self.is_block() {
85            return &self.text;
86        }
87        match (self.text.find('{'), self.text.rfind('}')) {
88            (Some(open), Some(close)) if close > open => &self.text[open + 1..close],
89            _ => "",
90        }
91    }
92}
93
94/// The closing brace of the SQLX block opening at `opening`. Strings, `--`, `/* */` and `//`
95/// comments are skipped: a JavaScript comment's apostrophes and braces are not code.
96fn find_balanced_brace(text: &str, opening: usize) -> Result<usize> {
97    let bytes = text.as_bytes();
98    let mut depth = 1;
99    let mut index = opening + 1;
100    let mut quote: Option<u8> = None;
101    let mut line_comment = false;
102    let mut block_comment = false;
103    while index < bytes.len() {
104        let c = bytes[index];
105        let next = bytes.get(index + 1).copied().unwrap_or(0);
106        if line_comment {
107            if c == b'\r' || c == b'\n' {
108                line_comment = false;
109            }
110        } else if block_comment {
111            if c == b'*' && next == b'/' {
112                block_comment = false;
113                index += 1;
114            }
115        } else if let Some(q) = quote {
116            if c == b'\\' {
117                index += 1;
118            } else if c == q {
119                if next == q {
120                    index += 1;
121                } else {
122                    quote = None;
123                }
124            }
125        } else if (c == b'-' && next == b'-') || (c == b'/' && next == b'/') {
126            line_comment = true;
127            index += 1;
128        } else if c == b'/' && next == b'*' {
129            block_comment = true;
130            index += 1;
131        } else if c == b'\'' || c == b'"' || c == b'`' {
132            quote = Some(c);
133        } else if c == b'{' {
134            depth += 1;
135        } else if c == b'}' {
136            depth -= 1;
137            if depth == 0 {
138                return Ok(index);
139            }
140        }
141        index += 1;
142    }
143    Err(SqlError::Sqlx("unterminated SQLX block".to_string()))
144}
145
146/// Split SQLX into SQL sections and blocks, in order. The result always ends with a SQL section
147/// (possibly empty), and joining the texts gives back the input.
148pub fn split_sqlx_sections(text: &str) -> Result<Vec<SqlxSection>> {
149    let mut pieces = Vec::new();
150    let mut cursor = 0;
151    while let Some(caps) = block_re().captures_at(text, cursor) {
152        let whole = caps.get(0).expect("match");
153        if whole.start() > cursor {
154            pieces.push(SqlxSection {
155                kind: SqlxSectionKind::Sql,
156                text: text[cursor..whole.start()].to_string(),
157                span: Span::new(cursor, whole.start()),
158            });
159        }
160        let kind = match caps.get(1).map(|m| m.as_str().to_ascii_lowercase()) {
161            Some(word) => match word.as_str() {
162                "config" => SqlxSectionKind::Config,
163                "js" => SqlxSectionKind::Js,
164                "pre_operations" => SqlxSectionKind::PreOperations,
165                _ => SqlxSectionKind::PostOperations,
166            },
167            None => SqlxSectionKind::Input(
168                caps.get(2)
169                    .or(caps.get(3))
170                    .map_or(String::new(), |m| m.as_str().to_string()),
171            ),
172        };
173        let opening = whole.end() - 1;
174        let closing = find_balanced_brace(text, opening)?;
175        pieces.push(SqlxSection {
176            kind,
177            text: text[whole.start()..=closing].to_string(),
178            span: Span::new(whole.start(), closing + 1),
179        });
180        cursor = closing + 1;
181    }
182    pieces.push(SqlxSection {
183        kind: SqlxSectionKind::Sql,
184        text: text[cursor..].to_string(),
185        span: Span::new(cursor, text.len()),
186    });
187    Ok(pieces)
188}
189
190// ------------------------------------------------------------------------ comments
191
192/// The closing `}` of the `${` at `opening`.
193fn find_interpolation_end(text: &str, opening: usize) -> Result<usize> {
194    let bytes = text.as_bytes();
195    let mut depth = 1;
196    let mut index = opening + 2;
197    let mut quote: Option<u8> = None;
198    while index < bytes.len() {
199        let c = bytes[index];
200        let next = bytes.get(index + 1).copied().unwrap_or(0);
201        if let Some(q) = quote {
202            if c == b'\\' {
203                index += 1;
204            } else if c == q {
205                if next == q {
206                    index += 1;
207                } else {
208                    quote = None;
209                }
210            }
211        } else if c == b'\'' || c == b'"' || c == b'`' {
212            quote = Some(c);
213        } else if c == b'{' {
214            depth += 1;
215        } else if c == b'}' {
216            depth -= 1;
217            if depth == 0 {
218                return Ok(index);
219            }
220        }
221        index += 1;
222    }
223    Err(SqlError::Sqlx(
224        "unterminated SQLX interpolation".to_string(),
225    ))
226}
227
228/// `(start, end)` of every `--` and `/* */` comment in SQL.
229///
230/// Dataform leaves a `${...}` inside these as text. A `#` comment is not one of them, nor is a
231/// `--` inside a string. Quotes inside a comment do not open a string, and comment markers inside
232/// a string or a `${...}` do not open a comment. An unterminated block comment runs to the end.
233pub fn sql_comment_spans(sql: &str) -> Vec<(usize, usize)> {
234    let bytes = sql.as_bytes();
235    let size = bytes.len();
236    let mut spans = Vec::new();
237    let mut index = 0;
238    while index < size {
239        let c = bytes[index];
240        if sql[index..].starts_with("${") {
241            match find_interpolation_end(sql, index) {
242                Ok(end) => index = end + 1,
243                Err(_) => return spans,
244            }
245        } else if sql[index..].starts_with("--") {
246            let mut end = index;
247            while end < size && bytes[end] != b'\r' && bytes[end] != b'\n' {
248                end += 1;
249            }
250            spans.push((index, end));
251            index = end;
252        } else if sql[index..].starts_with("/*") {
253            let end = sql[index + 2..]
254                .find("*/")
255                .map_or(size, |e| index + 2 + e + 2);
256            spans.push((index, end));
257            index = end;
258        } else if c == b'\'' || c == b'"' || c == b'`' {
259            let triple = &sql[index..(index + 3).min(size)];
260            let quote: &str = if triple == "'''" || triple == "\"\"\"" {
261                triple
262            } else {
263                &sql[index..index + 1]
264            };
265            let quote = quote.to_string();
266            index += quote.len();
267            while index < size && !sql[index..].starts_with(quote.as_str()) {
268                if sql[index..].starts_with("${") {
269                    match find_interpolation_end(sql, index) {
270                        Ok(end) => {
271                            index = end + 1;
272                            continue;
273                        }
274                        Err(_) => return spans,
275                    }
276                }
277                index += if bytes[index] == b'\\' { 2 } else { 1 };
278            }
279            index += quote.len();
280        } else {
281            index += 1;
282        }
283    }
284    spans
285}
286
287fn in_spans(spans: &[(usize, usize)], at: usize) -> bool {
288    spans.iter().any(|(s, e)| *s <= at && at < *e)
289}
290
291/// The matches of `pattern` in `sql` that do not start inside a `--` or `/* */` comment.
292pub fn outside_sql_comments<'t>(sql: &'t str, pattern: &Regex) -> Vec<Match<'t>> {
293    let spans = sql_comment_spans(sql);
294    pattern
295        .find_iter(sql)
296        .filter(|m| !in_spans(&spans, m.start()))
297        .collect()
298}
299
300/// `sql` with each `${` inside a `--` or `/* */` comment written `$ {`, so it is never read as an
301/// interpolation (Dataform does not evaluate it).
302pub fn defuse_comment_templates(sql: &str) -> String {
303    if !sql.contains("${") {
304        return sql.to_string();
305    }
306    let mut out = String::with_capacity(sql.len());
307    let mut cursor = 0;
308    for (start, end) in sql_comment_spans(sql) {
309        out.push_str(&sql[cursor..start]);
310        out.push_str(&sql[start..end].replace("${", "$ {"));
311        cursor = end;
312    }
313    out.push_str(&sql[cursor..]);
314    out
315}
316
317// ------------------------------------------------------------------------ masking
318
319/// How to put one interpolation back.
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321pub struct SqlxRestoration {
322    /// The sentinel standing for it in the masked SQL (`__sqlx_token_000__`).
323    pub token: String,
324    /// The interpolation as written (`${ref("t")}`).
325    pub original: String,
326    /// A regex for the sentinel with the SQL written around it (`WHERE __sqlx_token_000__`).
327    pub pattern: String,
328    /// The sentinel stands for the interpolation together with SQL around it: restoring it
329    /// anywhere else would change the meaning.
330    pub whole: bool,
331    /// Where the interpolation was in the input.
332    pub span: Span,
333}
334
335/// A Dataform function called in an interpolation.
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
337pub enum RefFunction {
338    Ref,
339    Resolve,
340    SelfRef,
341    When,
342}
343
344/// A literal `ref`/`resolve` target.
345#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
346pub struct RefTarget {
347    pub database: Option<String>,
348    pub schema: Option<String>,
349    pub name: String,
350}
351
352/// One `ref(...)`, `resolve(...)`, `self()` or `when(...)` call in a masked interpolation.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354pub struct RefCall {
355    pub function: RefFunction,
356    /// The arguments; computed ones are [`JsValue::Expression`].
357    pub args: Vec<JsValue>,
358    /// The call as written (`ref("ds", "t")`).
359    pub text: String,
360    /// The sentinel of the interpolation the call is in.
361    pub token: String,
362    /// Inside another call's arguments (`when(incremental(), `... ${self()}`)`).
363    pub nested: bool,
364}
365
366impl RefCall {
367    /// The table a `ref`/`resolve` names when every argument is a literal: `("t")`,
368    /// `("schema", "t")`, `("db", "schema", "t")` or `({database, schema, name})`.
369    pub fn target(&self) -> Option<RefTarget> {
370        if !matches!(self.function, RefFunction::Ref | RefFunction::Resolve) {
371            return None;
372        }
373        match self.args.as_slice() {
374            [JsValue::String(name)] => Some(RefTarget {
375                name: name.clone(),
376                ..RefTarget::default()
377            }),
378            [JsValue::String(schema), JsValue::String(name)] => Some(RefTarget {
379                schema: Some(schema.clone()),
380                name: name.clone(),
381                ..RefTarget::default()
382            }),
383            [JsValue::String(db), JsValue::String(schema), JsValue::String(name)] => {
384                Some(RefTarget {
385                    database: Some(db.clone()),
386                    schema: Some(schema.clone()),
387                    name: name.clone(),
388                })
389            }
390            [JsValue::Object(map)] => {
391                let name = map.get("name")?.as_str()?.to_string();
392                let field = |key: &str| -> Option<Option<String>> {
393                    match map.get(key) {
394                        None => Some(None),
395                        Some(JsValue::String(s)) => Some(Some(s.clone())),
396                        Some(_) => None,
397                    }
398                };
399                Some(RefTarget {
400                    database: field("database")?.or(field("project")?),
401                    schema: field("schema")?.or(field("dataset")?),
402                    name,
403                })
404            }
405            _ => None,
406        }
407    }
408}
409
410/// SQL with its interpolations replaced by sentinels.
411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
412pub struct MaskedSqlx {
413    /// The input as given.
414    pub original: String,
415    /// The SQL with sentinels in place of interpolations.
416    pub masked: String,
417    pub restorations: Vec<SqlxRestoration>,
418    /// Every Dataform call found in the masked interpolations.
419    pub refs: Vec<RefCall>,
420}
421
422impl MaskedSqlx {
423    /// Sentinels of interpolations that are not single relation references
424    /// (see [`is_table_reference`]): they can compile to any SQL.
425    pub fn opaque_tokens(&self) -> Vec<String> {
426        self.restorations
427            .iter()
428            .filter(|r| !is_table_reference(&r.original))
429            .map(|r| r.token.clone())
430            .collect()
431    }
432}
433
434fn when_connective_re() -> &'static Regex {
435    static RE: OnceLock<Regex> = OnceLock::new();
436    RE.get_or_init(|| {
437        Regex::new(r#"(?i)^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*[`'"]\s*(AND|OR)\b"#)
438            .expect("valid regex")
439    })
440}
441
442fn when_trailing_re() -> &'static Regex {
443    // `(?P<q>[`'"])(?:(?!(?P=q))[^$])*?\b(AND|OR)\s*(?P=q)` without back-references: one branch per quote
444    static RE: OnceLock<Regex> = OnceLock::new();
445    RE.get_or_init(|| {
446        let head = r"^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*";
447        let tail = r"\s*\)\s*$";
448        let branch = |q: &str| format!("{head}{q}[^{q}$]*?\\b(AND|OR)\\s*{q}{tail}");
449        Regex::new(&format!(
450            "(?i)(?:{})|(?:{})|(?:{})",
451            branch("`"),
452            branch("'"),
453            branch("\"")
454        ))
455        .expect("valid regex")
456    })
457}
458
459fn clause_re() -> &'static Regex {
460    static RE: OnceLock<Regex> = OnceLock::new();
461    RE.get_or_init(|| {
462        Regex::new(r"(?i)\b(WHERE|QUALIFY|HAVING|ORDER\s+BY)\b").expect("valid regex")
463    })
464}
465
466fn preceding_clause_re() -> &'static Regex {
467    static RE: OnceLock<Regex> = OnceLock::new();
468    RE.get_or_init(|| {
469        Regex::new(r"(?i)\b(?:WHERE|QUALIFY|HAVING|ORDER\s+BY)\s*$").expect("valid regex")
470    })
471}
472
473fn preceding_condition_re() -> &'static Regex {
474    static RE: OnceLock<Regex> = OnceLock::new();
475    RE.get_or_init(|| Regex::new(r"(?i)\b(?:AND|OR)\s*$").expect("valid regex"))
476}
477
478/// Replace every `${...}` outside `--`/`/* */` comments with a SQL-safe sentinel and record how
479/// to restore it. An interpolation that opens or continues a condition
480/// (`${when(incremental(), "WHERE x > 1")}`) is masked with the clause keyword beside it so the
481/// masked text still parses.
482pub fn mask_sqlx(sql: &str) -> Result<MaskedSqlx> {
483    let comments = sql_comment_spans(sql);
484    let mut output = String::with_capacity(sql.len());
485    let mut restorations = Vec::new();
486    let mut refs = Vec::new();
487    let mut cursor = 0;
488    let mut ordinal = 0usize;
489    loop {
490        let mut search = cursor;
491        let opening = loop {
492            match sql[search..].find("${") {
493                None => break None,
494                Some(found) => {
495                    let at = search + found;
496                    if in_spans(&comments, at) {
497                        search = at + 2;
498                        continue;
499                    }
500                    break Some(at);
501                }
502            }
503        };
504        let Some(opening) = opening else {
505            output.push_str(&sql[cursor..]);
506            break;
507        };
508        output.push_str(&sql[cursor..opening]);
509        let closing = find_interpolation_end(sql, opening)?;
510        let original = &sql[opening..=closing];
511        let mut token = format!("__sqlx_token_{ordinal:03}__");
512        while sql.contains(&token) {
513            ordinal += 1;
514            token = format!("__sqlx_token_{ordinal:03}__");
515        }
516        ordinal += 1;
517
518        let prefix = output.trim_end();
519        let body = &original[2..original.len() - 1];
520        let clause = clause_re().captures(body);
521        let preceding_clause = preceding_clause_re().is_match(prefix);
522        let preceding_condition = preceding_condition_re().is_match(prefix);
523        let escaped = regex::escape(&token);
524        let mut replacement = token.clone();
525        let mut pattern = escaped.clone();
526        let mut whole = false;
527        let trailing = when_trailing_re().captures(body);
528        let connective = when_connective_re().captures(body);
529        if let (Some(t), true) = (&trailing, preceding_clause || preceding_condition) {
530            let keyword = (1..=3)
531                .find_map(|g| t.get(g))
532                .map_or("AND".to_string(), |m| m.as_str().to_ascii_uppercase());
533            replacement = format!("{token} {keyword}");
534            pattern = format!(r"(?i)\b{escaped}\s+{keyword}\b");
535            whole = true;
536        } else if let (Some(c), None, false, false) =
537            (&connective, &clause, preceding_clause, preceding_condition)
538        {
539            let keyword = c[1].to_ascii_uppercase();
540            replacement = format!("{keyword} {token}");
541            pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
542        } else if let (Some(c), false, false) = (&clause, preceding_clause, preceding_condition) {
543            let keyword = c[1].to_ascii_uppercase();
544            if keyword.starts_with("ORDER") {
545                replacement = format!("ORDER BY {token}");
546                pattern = format!(r"(?i)\bORDER\s+BY\s+{escaped}\b");
547            } else {
548                replacement = format!("{keyword} {token}");
549                pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
550            }
551        }
552        output.push_str(&replacement);
553        scan_calls(body, &token, 0, &mut refs);
554        restorations.push(SqlxRestoration {
555            token,
556            original: original.to_string(),
557            pattern,
558            whole,
559            span: Span::new(opening, closing + 1),
560        });
561        cursor = closing + 1;
562    }
563    Ok(MaskedSqlx {
564        original: sql.to_string(),
565        masked: output,
566        restorations,
567        refs,
568    })
569}
570
571/// Put the interpolations back into `rewritten` (a rewrite of `masked.masked`). Fails when a
572/// sentinel was lost or duplicated, or separated from the connective it stands with.
573pub fn restore_sqlx(masked: &MaskedSqlx, rewritten: &str) -> Result<String> {
574    restore_sqlx_interpolations(rewritten, &masked.restorations)
575}
576
577/// [`restore_sqlx`] from the restorations alone.
578pub fn restore_sqlx_interpolations(sql: &str, restorations: &[SqlxRestoration]) -> Result<String> {
579    for item in restorations {
580        let count = sql.matches(item.token.as_str()).count();
581        if count != 1 {
582            return Err(SqlError::SqlxRestoration(format!(
583                "SQLX interpolation placeholder was lost or duplicated during rewriting ({count} copies found; expected one)"
584            )));
585        }
586    }
587    let mut restored = sql.to_string();
588    for item in restorations {
589        let pattern = Regex::new(&item.pattern)
590            .map_err(|e| SqlError::SqlxRestoration(format!("bad restoration pattern: {e}")))?;
591        if item.whole && pattern.find_iter(&restored).count() != 1 {
592            return Err(SqlError::SqlxRestoration(
593                "a rewrite separated a SQLX interpolation from the connective it ends with"
594                    .to_string(),
595            ));
596        }
597        // a printer may quote an identifier sentinel inside a table path: restore that spelling first
598        restored = restored.replace(&format!("`{}`", item.token), &item.original);
599        restored = pattern
600            .replace_all(&restored, regex::NoExpand(&item.original))
601            .into_owned();
602        restored = restored.replace(&item.token, &item.original);
603    }
604    Ok(restored)
605}
606
607/// Find Dataform calls in JavaScript `text` (an interpolation's body), descending into template
608/// literals' `${...}` parts and into call arguments.
609fn scan_calls(text: &str, token: &str, depth: usize, out: &mut Vec<RefCall>) {
610    let bytes = text.as_bytes();
611    let mut i = 0;
612    while i < bytes.len() {
613        let c = bytes[i];
614        match c {
615            b'\'' | b'"' => match skip_js_string(text, i) {
616                Some(end) => i = end,
617                None => return,
618            },
619            b'`' => {
620                // walk the template, scanning each `${...}` as code
621                let mut j = i + 1;
622                while j < bytes.len() && bytes[j] != b'`' {
623                    if bytes[j] == b'\\' {
624                        j += 2;
625                        continue;
626                    }
627                    if bytes[j] == b'$' && bytes.get(j + 1) == Some(&b'{') {
628                        let Some(end) = skip_js_braces(text, j + 1) else {
629                            return;
630                        };
631                        scan_calls(&text[j + 2..end - 1], token, depth, out);
632                        j = end;
633                        continue;
634                    }
635                    j += 1;
636                }
637                i = j + 1;
638            }
639            b'/' if bytes.get(i + 1) == Some(&b'/') => {
640                while i < bytes.len() && bytes[i] != b'\n' {
641                    i += 1;
642                }
643            }
644            b'/' if bytes.get(i + 1) == Some(&b'*') => {
645                i = text[i + 2..]
646                    .find("*/")
647                    .map_or(bytes.len(), |e| i + 2 + e + 2);
648            }
649            c if c.is_ascii_alphabetic() || c == b'_' || c == b'$' => {
650                let start = i;
651                while i < bytes.len()
652                    && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'$')
653                {
654                    i += 1;
655                }
656                let word = &text[start..i];
657                let before = text[..start].trim_end();
658                let member_of_ctx = before.ends_with("ctx.");
659                let is_member = before.ends_with('.') && !member_of_ctx;
660                let function = match word {
661                    "ref" => Some(RefFunction::Ref),
662                    "resolve" => Some(RefFunction::Resolve),
663                    "self" => Some(RefFunction::SelfRef),
664                    "when" => Some(RefFunction::When),
665                    _ => None,
666                };
667                let after = text[i..].trim_start();
668                if let (Some(function), false, true) = (function, is_member, after.starts_with('('))
669                {
670                    let open = i + (text[i..].len() - after.len());
671                    if let Some(close) = skip_js_braces(text, open) {
672                        let args_text = &text[open + 1..close - 1];
673                        out.push(RefCall {
674                            function,
675                            args: parse_arguments(args_text),
676                            text: text[start..close].to_string(),
677                            token: token.to_string(),
678                            nested: depth > 0,
679                        });
680                        scan_calls(args_text, token, depth + 1, out);
681                        i = close;
682                    }
683                }
684            }
685            _ => i += 1,
686        }
687    }
688}
689
690/// Call arguments read leniently: literals as values, anything else as an expression.
691fn parse_arguments(text: &str) -> Vec<JsValue> {
692    let mut args = Vec::new();
693    let mut pos = 0;
694    loop {
695        let rest = &text[pos..];
696        if rest.trim().is_empty() {
697            break;
698        }
699        let Some((value, end)) = parse_lenient(text, pos) else {
700            args.push(JsValue::Expression(rest.trim().to_string()));
701            break;
702        };
703        args.push(value);
704        let after = &text[end..];
705        let trimmed = after.trim_start();
706        if let Some(next) = trimmed.strip_prefix(',') {
707            pos = text.len() - next.len();
708        } else {
709            break;
710        }
711    }
712    args
713}
714
715fn quoted() -> &'static str {
716    r#"(?:"[^"\\]*"|'[^'\\]*'|`[^`\\]*`)"#
717}
718
719fn table_reference_re() -> &'static Regex {
720    static RE: OnceLock<Regex> = OnceLock::new();
721    RE.get_or_init(|| {
722        let q = quoted();
723        Regex::new(&format!(
724            r"^\$\{{\s*(?:(?:ref|resolve)\s*\(\s*{q}(?:\s*,\s*{q})?\s*\)|self\s*\(\s*\))\s*\}}$"
725        ))
726        .expect("valid regex")
727    })
728}
729
730/// `${ref("t")}`, `${ref("dataset", "t")}`, `${resolve("t")}` or `${self()}`: one table name once compiled.
731pub fn is_table_reference(original: &str) -> bool {
732    table_reference_re().is_match(original)
733}
734
735/// Whether a `${...}` always expands to exactly one table or view name: `self()`, or one
736/// `ref(...)`/`resolve(...)` call whose closing parenthesis ends the expression, with no template
737/// literal, comment, `/` or backslash in its arguments.
738pub fn is_relation_reference(interpolation: &str) -> bool {
739    static SELF_RE: OnceLock<Regex> = OnceLock::new();
740    static CALL_RE: OnceLock<Regex> = OnceLock::new();
741    static CLOSE_RE: OnceLock<Regex> = OnceLock::new();
742    let self_re =
743        SELF_RE.get_or_init(|| Regex::new(r"^\$\{\s*self\(\s*\)\s*\}$").expect("valid regex"));
744    let call_re =
745        CALL_RE.get_or_init(|| Regex::new(r"^\$\{\s*(?:ref|resolve)\s*\(").expect("valid regex"));
746    let close_re = CLOSE_RE.get_or_init(|| Regex::new(r"^\s*\}$").expect("valid regex"));
747    if self_re.is_match(interpolation) {
748        return true;
749    }
750    let Some(call) = call_re.find(interpolation) else {
751        return false;
752    };
753    let mut depth = 1;
754    let mut quote: Option<char> = None;
755    for (index, c) in interpolation[call.end()..].char_indices() {
756        let at = call.end() + index;
757        if "`/\\".contains(c) || (quote.is_some() && c == '\n') {
758            return false;
759        }
760        if let Some(q) = quote {
761            if c == q {
762                quote = None;
763            }
764        } else if c == '\'' || c == '"' {
765            quote = Some(c);
766        } else if "([{".contains(c) {
767            depth += 1;
768        } else if ")]}".contains(c) {
769            depth -= 1;
770            if depth == 0 {
771                return c == ')' && close_re.is_match(&interpolation[at + 1..]);
772            }
773        }
774    }
775    false
776}
777
778/// The content-derived sentinel for an interpolation: `__sqlx_<16 hex of sha256>__`.
779pub fn content_sentinel(original: &str) -> String {
780    let digest = Sha256::digest(original.as_bytes());
781    format!("__sqlx_{}__", &hex::encode(digest)[..16])
782}
783
784/// Mask with sentinels derived from each interpolation's text, so the same interpolation has the
785/// same sentinel wherever a rewrite moves it.
786pub fn mask_sqlx_by_content(sql: &str) -> Result<String> {
787    let masked = mask_sqlx(sql)?;
788    let mut text = masked.masked.clone();
789    for item in &masked.restorations {
790        text = text.replace(&item.token, &content_sentinel(&item.original));
791    }
792    Ok(text)
793}
794
795/// Content sentinels of every interpolation in `sql` that is not a relation reference.
796pub fn dynamic_sentinels(sql: &str) -> Result<Vec<String>> {
797    let masked = mask_sqlx(sql)?;
798    let mut out: Vec<String> = masked
799        .restorations
800        .iter()
801        .filter(|r| !is_relation_reference(&r.original))
802        .map(|r| content_sentinel(&r.original))
803        .collect();
804    out.sort();
805    out.dedup();
806    Ok(out)
807}
808
809/// Refused: the text holds a positional sentinel, which means different things in different models.
810pub const LOADER_TOKEN_REASON: &str = "unsupported: it holds a Dataform expression the loader masked by position (__sqlx_token_N__), which can expand to any SQL and stands for a different expression in each model; compile the SQLX to prove it";
811/// Refused: a string literal holds a masked expression, so its value is unknown.
812pub const STRING_REASON: &str = "unsupported: a string literal holds a masked Dataform expression, so its value is unknown; compile the SQLX to prove it";
813
814/// Why a prover must not read these masked texts as they are, or `None`.
815pub fn masked_template_problem(sqls: &[&str]) -> Option<&'static str> {
816    static LOADER: OnceLock<Regex> = OnceLock::new();
817    let loader = LOADER.get_or_init(|| Regex::new(r"__sqlx_token_\d+__").expect("valid regex"));
818    for sql in sqls {
819        if !sql.contains("__sqlx_") {
820            continue;
821        }
822        if loader.is_match(sql) {
823            return Some(LOADER_TOKEN_REASON);
824        }
825        match tokenize(sql) {
826            Ok(tokens) => {
827                if tokens.iter().any(|t| {
828                    matches!(t.kind, TokenKind::String { .. } | TokenKind::Bytes { .. })
829                        && t.text.contains("__sqlx_")
830                }) {
831                    return Some(STRING_REASON);
832                }
833            }
834            Err(_) => return Some(STRING_REASON),
835        }
836    }
837    None
838}
839
840/// `transformed` with `original`'s leading and trailing whitespace.
841pub fn with_preserved_whitespace(original: &str, transformed: &str) -> String {
842    if transformed.is_empty() {
843        return original.to_string();
844    }
845    let leading = &original[..original.len() - original.trim_start().len()];
846    let trailing = &original[original.trim_end().len()..];
847    format!("{leading}{}{trailing}", transformed.trim())
848}
849
850// ------------------------------------------------------------------------ config
851
852/// A dependency named in `dependencies: [...]`.
853#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
854pub enum SqlxDependency {
855    Name(String),
856    Target(RefTarget),
857    /// Not a literal.
858    Computed(String),
859}
860
861/// Documentation of one column (`columns: {a: "text"}` or `{a: {description, columns, bigqueryPolicyTags}}`).
862#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
863pub struct SqlxColumn {
864    pub description: Option<String>,
865    pub columns: IndexMap<String, SqlxColumn>,
866    pub policy_tags: Vec<String>,
867}
868
869/// The `bigquery: {...}` block (and its top-level spellings).
870#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
871pub struct SqlxBigQuery {
872    pub partition_by: Option<String>,
873    pub cluster_by: Vec<String>,
874    pub labels: IndexMap<String, String>,
875    pub require_partition_filter: Option<bool>,
876    pub partition_expiration_days: Option<String>,
877    pub update_partition_filter: Option<String>,
878}
879
880/// The `assertions: {...}` block.
881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
882pub struct SqlxAssertions {
883    pub unique_key: Vec<String>,
884    pub unique_keys: Vec<Vec<String>>,
885    pub non_null: Vec<String>,
886    pub row_conditions: Vec<String>,
887}
888
889/// What a config block says, read without running it.
890#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
891pub struct SqlxConfig {
892    /// `type` (`table`, `view`, `incremental`, `operations`, `assertion`, `declaration`, `test`).
893    pub action_type: Option<String>,
894    pub schema: Option<String>,
895    pub database: Option<String>,
896    pub name: Option<String>,
897    pub tags: Vec<String>,
898    pub disabled: Option<bool>,
899    pub protected: Option<bool>,
900    pub has_output: Option<bool>,
901    pub description: Option<String>,
902    pub columns: IndexMap<String, SqlxColumn>,
903    pub dependencies: Vec<SqlxDependency>,
904    pub bigquery: SqlxBigQuery,
905    pub assertions: SqlxAssertions,
906    /// A top-level `uniqueKey` (incremental tables).
907    pub unique_key: Vec<String>,
908    /// Keys whose values are computed (only known by running the project).
909    pub computed: Vec<String>,
910    /// What Dataform's compiler would reject: an unknown type or a key the type does not accept.
911    pub problems: Vec<String>,
912    /// The whole config as read.
913    pub raw: IndexMap<String, JsValue>,
914}
915
916impl SqlxConfig {
917    /// The action type, `table` when none is given.
918    pub fn effective_type(&self) -> &str {
919        self.action_type.as_deref().unwrap_or("table")
920    }
921}
922
923const COMMON_CONFIG_KEYS: &[&str] = &[
924    "additionalOptions",
925    "assertions",
926    "bigquery",
927    "columns",
928    "database",
929    "dataset",
930    "dependOnDependencyAssertions",
931    "dependencies",
932    "dependencyTargets",
933    "description",
934    "disabled",
935    "filename",
936    "hermetic",
937    "iceberg",
938    "incrementalPredicates",
939    "labels",
940    "metadata",
941    "name",
942    "preserveGovernanceControls",
943    "project",
944    "protected",
945    "requirePartitionFilter",
946    "schema",
947    "tags",
948    "type",
949];
950
951fn type_keys(action_type: &str) -> Option<&'static [&'static str]> {
952    Some(match action_type {
953        "table" | "test" => &[
954            "clusterBy",
955            "fileName",
956            "partitionBy",
957            "partitionExpirationDays",
958            "reservation",
959        ],
960        "view" => &[
961            "clusterBy",
962            "fileName",
963            "materialized",
964            "partitionBy",
965            "reservation",
966        ],
967        "incremental" => &[
968            "clusterBy",
969            "fileName",
970            "incrementalStrategy",
971            "onSchemaChange",
972            "partitionBy",
973            "partitionExpirationDays",
974            "reservation",
975            "uniqueKey",
976            "updatePartitionFilter",
977        ],
978        "assertion" => &["fileName", "reservation"],
979        "operations" => &["fileName", "hasOutput", "reservation"],
980        "declaration" => &[],
981        _ => return None,
982    })
983}
984
985fn unique(items: Vec<String>) -> Vec<String> {
986    let mut seen = std::collections::HashSet::new();
987    items
988        .into_iter()
989        .filter(|i| seen.insert(i.clone()))
990        .collect()
991}
992
993fn literal_string(
994    map: &IndexMap<String, JsValue>,
995    key: &str,
996    computed: &mut Vec<String>,
997) -> Option<String> {
998    match map.get(key)? {
999        JsValue::String(s) => Some(s.clone()),
1000        _ => {
1001            computed.push(key.to_string());
1002            None
1003        }
1004    }
1005}
1006
1007fn literal_bool(
1008    map: &IndexMap<String, JsValue>,
1009    key: &str,
1010    computed: &mut Vec<String>,
1011) -> Option<bool> {
1012    match map.get(key)? {
1013        JsValue::Bool(b) => Some(*b),
1014        _ => {
1015            computed.push(key.to_string());
1016            None
1017        }
1018    }
1019}
1020
1021fn literal_list(
1022    map: &IndexMap<String, JsValue>,
1023    key: &str,
1024    path: &str,
1025    computed: &mut Vec<String>,
1026) -> Vec<String> {
1027    match map.get(key) {
1028        None => Vec::new(),
1029        Some(value) => value.string_list().unwrap_or_else(|| {
1030            computed.push(format!("{path}{key}"));
1031            Vec::new()
1032        }),
1033    }
1034}
1035
1036fn read_columns(value: &JsValue) -> IndexMap<String, SqlxColumn> {
1037    let mut out = IndexMap::new();
1038    if let Some(map) = value.as_object() {
1039        for (name, doc) in map {
1040            let column = match doc {
1041                JsValue::String(text) => SqlxColumn {
1042                    description: Some(text.clone()),
1043                    ..SqlxColumn::default()
1044                },
1045                JsValue::Object(fields) => SqlxColumn {
1046                    description: fields
1047                        .get("description")
1048                        .and_then(|d| d.as_str())
1049                        .map(str::to_string),
1050                    columns: fields.get("columns").map(read_columns).unwrap_or_default(),
1051                    policy_tags: fields
1052                        .get("bigqueryPolicyTags")
1053                        .and_then(JsValue::string_list)
1054                        .unwrap_or_default(),
1055                },
1056                _ => SqlxColumn::default(),
1057            };
1058            out.insert(name.clone(), column);
1059        }
1060    }
1061    out
1062}
1063
1064fn read_dependency(value: &JsValue) -> SqlxDependency {
1065    match value {
1066        JsValue::String(name) => SqlxDependency::Name(name.clone()),
1067        JsValue::Object(map) => {
1068            let get = |k: &str| map.get(k).and_then(|v| v.as_str()).map(str::to_string);
1069            match get("name") {
1070                Some(name) => SqlxDependency::Target(RefTarget {
1071                    database: get("database").or_else(|| get("project")),
1072                    schema: get("schema").or_else(|| get("dataset")),
1073                    name,
1074                }),
1075                None => SqlxDependency::Computed(format!("{value:?}")),
1076            }
1077        }
1078        JsValue::Expression(text) => SqlxDependency::Computed(text.clone()),
1079        other => SqlxDependency::Computed(format!("{other:?}")),
1080    }
1081}
1082
1083fn unique_keys(value: &JsValue) -> Option<Vec<Vec<String>>> {
1084    value
1085        .as_array()?
1086        .iter()
1087        .map(|entry| match entry {
1088            JsValue::Object(map) => map.get("uniqueKey").and_then(JsValue::string_list),
1089            other => other.string_list(),
1090        })
1091        .collect()
1092}
1093
1094/// Read a `config { ... }` block (or just its `{ ... }`) without running it. An empty block,
1095/// `tags: []`, trailing commas, unquoted keys, single-quoted strings and `//` comments are fine;
1096/// computed values are listed in [`SqlxConfig::computed`].
1097pub fn parse_sqlx_config(config_block: &str) -> Result<SqlxConfig> {
1098    let text = config_block.trim();
1099    if text.is_empty() {
1100        return Ok(SqlxConfig::default());
1101    }
1102    let start = if text
1103        .get(..6)
1104        .is_some_and(|head| head.eq_ignore_ascii_case("config"))
1105    {
1106        6
1107    } else {
1108        0
1109    };
1110    let rest = text[start..].trim_start();
1111    if !rest.starts_with('{') {
1112        return Err(SqlError::Sqlx(
1113            "a config block must be an object in braces".to_string(),
1114        ));
1115    }
1116    let offset = text.len() - rest.len();
1117    let (value, end) = parse_lenient(text, offset).ok_or_else(|| {
1118        SqlError::Sqlx("the config block is not a readable JavaScript object".to_string())
1119    })?;
1120    let trailing = crate::js::strip_comments(&text[end..]);
1121    if !trailing.trim().is_empty() {
1122        return Err(SqlError::Sqlx(
1123            "unexpected text after the config object".to_string(),
1124        ));
1125    }
1126    let JsValue::Object(map) = value else {
1127        return Err(SqlError::Sqlx(
1128            "a config block must be an object in braces".to_string(),
1129        ));
1130    };
1131    let mut config = SqlxConfig::default();
1132    let mut computed = Vec::new();
1133    config.action_type = literal_string(&map, "type", &mut computed);
1134    config.schema = literal_string(&map, "schema", &mut computed)
1135        .or_else(|| literal_string(&map, "dataset", &mut computed));
1136    config.database = literal_string(&map, "database", &mut computed)
1137        .or_else(|| literal_string(&map, "project", &mut computed));
1138    config.name = literal_string(&map, "name", &mut computed);
1139    config.tags = unique(literal_list(&map, "tags", "", &mut computed));
1140    config.disabled = literal_bool(&map, "disabled", &mut computed);
1141    config.protected = literal_bool(&map, "protected", &mut computed);
1142    config.has_output = literal_bool(&map, "hasOutput", &mut computed);
1143    config.description = literal_string(&map, "description", &mut computed);
1144    if let Some(columns) = map.get("columns") {
1145        if columns.as_object().is_none() {
1146            computed.push("columns".to_string());
1147        }
1148        config.columns = read_columns(columns);
1149    }
1150    match map.get("dependencies") {
1151        Some(JsValue::Array(items)) => {
1152            config.dependencies = items.iter().map(read_dependency).collect()
1153        }
1154        Some(single @ (JsValue::String(_) | JsValue::Object(_))) => {
1155            config.dependencies = vec![read_dependency(single)]
1156        }
1157        Some(_) => computed.push("dependencies".to_string()),
1158        None => {}
1159    }
1160    let bq_map = match map.get("bigquery") {
1161        Some(JsValue::Object(m)) => Some(m.clone()),
1162        Some(_) => {
1163            computed.push("bigquery".to_string());
1164            None
1165        }
1166        None => None,
1167    };
1168    let empty = IndexMap::new();
1169    let bq = bq_map.as_ref().unwrap_or(&empty);
1170    let mut bigquery = SqlxBigQuery {
1171        partition_by: literal_string(bq, "partitionBy", &mut computed),
1172        cluster_by: literal_list(bq, "clusterBy", "bigquery.", &mut computed),
1173        require_partition_filter: literal_bool(bq, "requirePartitionFilter", &mut computed),
1174        update_partition_filter: literal_string(bq, "updatePartitionFilter", &mut computed),
1175        partition_expiration_days: bq.get("partitionExpirationDays").map(|v| match v {
1176            JsValue::Number(n) => n.clone(),
1177            other => format!("{other:?}"),
1178        }),
1179        labels: IndexMap::new(),
1180    };
1181    for (key, source) in [("labels", bq.get("labels")), ("labels", map.get("labels"))] {
1182        if let Some(JsValue::Object(labels)) = source {
1183            for (k, v) in labels {
1184                match v.as_str() {
1185                    Some(s) => {
1186                        bigquery.labels.insert(k.clone(), s.to_string());
1187                    }
1188                    None => computed.push(format!("{key}.{k}")),
1189                }
1190            }
1191        }
1192    }
1193    // Dataform 3 also accepts these at the top level
1194    if bigquery.partition_by.is_none() {
1195        bigquery.partition_by = literal_string(&map, "partitionBy", &mut computed);
1196    }
1197    if bigquery.cluster_by.is_empty() {
1198        bigquery.cluster_by = literal_list(&map, "clusterBy", "", &mut computed);
1199    }
1200    if bigquery.update_partition_filter.is_none() {
1201        bigquery.update_partition_filter =
1202            literal_string(&map, "updatePartitionFilter", &mut computed);
1203    }
1204    if bigquery.require_partition_filter.is_none() {
1205        bigquery.require_partition_filter =
1206            literal_bool(&map, "requirePartitionFilter", &mut computed);
1207    }
1208    config.bigquery = bigquery;
1209    match map.get("assertions") {
1210        Some(JsValue::Object(a)) => {
1211            config.assertions.unique_key =
1212                literal_list(a, "uniqueKey", "assertions.", &mut computed);
1213            if let Some(keys) = a.get("uniqueKeys") {
1214                match unique_keys(keys) {
1215                    Some(keys) => config.assertions.unique_keys = keys,
1216                    None => computed.push("assertions.uniqueKeys".to_string()),
1217                }
1218            }
1219            config.assertions.non_null = literal_list(a, "nonNull", "assertions.", &mut computed);
1220            config.assertions.row_conditions =
1221                literal_list(a, "rowConditions", "assertions.", &mut computed);
1222        }
1223        Some(_) => computed.push("assertions".to_string()),
1224        None => {}
1225    }
1226    config.unique_key = literal_list(&map, "uniqueKey", "", &mut computed);
1227    // problems Dataform's compiler reports
1228    if map.contains_key("type") && config.action_type.is_some() {
1229        let declared = config.action_type.as_deref().unwrap_or("table");
1230        if type_keys(declared).is_none() {
1231            config.problems.push(format!(
1232                "type '{declared}' is not an action type Dataform recognizes"
1233            ));
1234        }
1235    }
1236    let type_is_known = !computed.iter().any(|c| c == "type");
1237    if type_is_known && config.problems.is_empty() {
1238        let declared = config.effective_type().to_string();
1239        if let Some(extra) = type_keys(&declared) {
1240            for key in map.keys() {
1241                if !COMMON_CONFIG_KEYS.contains(&key.as_str()) && !extra.contains(&key.as_str()) {
1242                    config.problems.push(format!(
1243                        "config key '{key}' is not accepted for type '{declared}'"
1244                    ));
1245                }
1246            }
1247        }
1248    }
1249    // @dataform/core 3.0.71 rejects a declaration's assertions block with anything in it (even
1250    // `{nonNull: []}`); `assertions: {}` passes. The keys in it are still read as the claim.
1251    if type_is_known && config.effective_type() == "declaration" {
1252        if let Some(JsValue::Object(block)) = map.get("assertions") {
1253            if !block.is_empty() {
1254                config.problems.push(
1255                    "config key 'assertions' must be empty ({}) for type 'declaration'".to_string(),
1256                );
1257            }
1258        }
1259    }
1260    config.computed = unique(computed);
1261    config.raw = map;
1262    Ok(config)
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267    use super::*;
1268
1269    #[test]
1270    fn detects_sqlx() {
1271        assert!(looks_like_sqlx("config { type: \"table\" }\nSELECT 1"));
1272        assert!(looks_like_sqlx("SELECT * FROM ${ref(\"t\")}"));
1273        assert!(looks_like_sqlx("  input \"a\" {\n SELECT 1 }"));
1274        assert!(!looks_like_sqlx("SELECT 1 -- config"));
1275        assert!(!looks_like_sqlx("SELECT '{config}'"));
1276    }
1277
1278    #[test]
1279    fn decodes_bytes() {
1280        assert_eq!(decode_sqlx_bytes(b"\xEF\xBB\xBFconfig {}"), "config {}");
1281        assert_eq!(
1282            decode_sqlx_bytes(b"caf\xE9 \x93q\x94"),
1283            "caf\u{e9} \u{201c}q\u{201d}"
1284        );
1285        assert_eq!(decode_sqlx_bytes("é".as_bytes()), "é");
1286    }
1287
1288    #[test]
1289    fn splits_sections_with_js_comments() {
1290        let text = "config {\n  type: \"table\", // don't { break\n  tags: ['a'] /* } */\n}\njs {\n const x = '}';\n}\nSELECT ${ref(\"t\")} -- it's\npre_operations { SET x = 1 }\ninput \"src\" { SELECT 1 }\n";
1291        let sections = split_sqlx_sections(text).unwrap();
1292        let kinds: Vec<_> = sections.iter().map(|s| s.kind.clone()).collect();
1293        assert_eq!(
1294            kinds,
1295            vec![
1296                SqlxSectionKind::Config,
1297                SqlxSectionKind::Sql,
1298                SqlxSectionKind::Js,
1299                SqlxSectionKind::Sql,
1300                SqlxSectionKind::PreOperations,
1301                SqlxSectionKind::Sql,
1302                SqlxSectionKind::Input("src".into()),
1303                SqlxSectionKind::Sql,
1304            ]
1305        );
1306        let joined: String = sections.iter().map(|s| s.text.as_str()).collect();
1307        assert_eq!(joined, text);
1308        assert!(sections[0].body().contains("tags"));
1309        assert!(split_sqlx_sections("config { type: 'x'").is_err());
1310    }
1311
1312    #[test]
1313    fn comment_spans_skip_strings_and_interpolations() {
1314        let sql = "SELECT '--x', ${ref('a--b')} -- c\n/* d */ # e\n";
1315        let spans = sql_comment_spans(sql);
1316        assert_eq!(spans.len(), 2);
1317        assert_eq!(&sql[spans[0].0..spans[0].1], "-- c");
1318        assert_eq!(&sql[spans[1].0..spans[1].1], "/* d */");
1319        assert_eq!(
1320            defuse_comment_templates("-- ${x}\nSELECT ${y}"),
1321            "-- $ {x}\nSELECT ${y}"
1322        );
1323    }
1324
1325    #[test]
1326    fn masks_and_restores() {
1327        let sql = "SELECT * FROM ${ref(\"ds\", \"t\")} AS t -- ${ref(\"ignored\")}\n# ${ref(\"evaluated\")}\nWHERE ${when(incremental(), \"ts > 1 AND\")} x = 1";
1328        let masked = mask_sqlx(sql).unwrap();
1329        assert_eq!(masked.restorations.len(), 3);
1330        assert!(masked.masked.contains("FROM __sqlx_token_000__ AS t"));
1331        assert!(masked.masked.contains("-- ${ref(\"ignored\")}"));
1332        assert!(masked.masked.contains("WHERE __sqlx_token_002__ AND x = 1"));
1333        let targets: Vec<_> = masked.refs.iter().filter_map(RefCall::target).collect();
1334        assert_eq!(targets.len(), 2);
1335        assert_eq!(targets[0].schema.as_deref(), Some("ds"));
1336        assert_eq!(targets[1].name, "evaluated");
1337        assert!(masked.refs.iter().any(|r| r.function == RefFunction::When));
1338        assert_eq!(restore_sqlx(&masked, &masked.masked).unwrap(), sql);
1339        // a rewrite that keeps every sentinel once restores
1340        let rewritten = masked.masked.replace("AS t", "AS u");
1341        assert!(restore_sqlx(&masked, &rewritten)
1342            .unwrap()
1343            .contains("${ref(\"ds\", \"t\")} AS u"));
1344        // lost or duplicated sentinels refuse
1345        let lost = masked.masked.replace("__sqlx_token_000__", "x");
1346        assert!(matches!(
1347            restore_sqlx(&masked, &lost),
1348            Err(SqlError::SqlxRestoration(_))
1349        ));
1350        let dup = format!("{} {}", masked.masked, "__sqlx_token_001__");
1351        assert!(restore_sqlx(&masked, &dup).is_err());
1352        // separating a `whole` sentinel from its connective refuses
1353        let separated = masked
1354            .masked
1355            .replace("__sqlx_token_002__ AND", "__sqlx_token_002__ OR");
1356        assert!(restore_sqlx(&masked, &separated).is_err());
1357    }
1358
1359    #[test]
1360    fn masks_clause_interpolations() {
1361        let m = mask_sqlx(
1362            "SELECT * FROM t ${when(incremental(), `WHERE ts > (SELECT MAX(ts) FROM ${self()})`)}",
1363        )
1364        .unwrap();
1365        assert!(
1366            m.masked.ends_with("WHERE __sqlx_token_000__"),
1367            "{}",
1368            m.masked
1369        );
1370        assert!(m
1371            .refs
1372            .iter()
1373            .any(|r| r.function == RefFunction::SelfRef && r.nested));
1374        assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
1375        let m =
1376            mask_sqlx("SELECT * FROM t WHERE a > 0 ${when(incremental(), \"AND b > 1\")}").unwrap();
1377        assert!(
1378            m.masked.contains("a > 0 AND __sqlx_token_000__"),
1379            "{}",
1380            m.masked
1381        );
1382        let restored = restore_sqlx(&m, &m.masked.replace("a > 0 AND", "a > 0\n  AND")).unwrap();
1383        assert!(restored.contains("${when("));
1384        let m = mask_sqlx("SELECT 1 ${\"ORDER BY x\"}").unwrap();
1385        assert!(m.masked.ends_with("ORDER BY __sqlx_token_000__"));
1386    }
1387
1388    #[test]
1389    fn sentinels_avoid_existing_text_and_backticks_restore() {
1390        let m = mask_sqlx("SELECT '__sqlx_token_000__', ${x}").unwrap();
1391        assert_eq!(m.restorations[0].token, "__sqlx_token_001__");
1392        let m = mask_sqlx("SELECT * FROM ${ref('t')}").unwrap();
1393        let quoted = m
1394            .masked
1395            .replace("__sqlx_token_000__", "`__sqlx_token_000__`");
1396        assert_eq!(restore_sqlx(&m, &quoted).unwrap(), m.original);
1397        let m = mask_sqlx("SELECT REGEXP_EXTRACT(a, r'\\d$1') FROM ${ref('t')}").unwrap();
1398        assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
1399    }
1400
1401    #[test]
1402    fn relation_references() {
1403        assert!(is_table_reference("${ref(\"t\")}"));
1404        assert!(is_table_reference("${ ref('d', 't') }"));
1405        assert!(is_table_reference("${self()}"));
1406        assert!(!is_table_reference("${ref({schema: 's', name: 't'})}"));
1407        assert!(is_relation_reference(
1408            "${ref({schema: vars.S, name: \"t\"})}"
1409        ));
1410        assert!(is_relation_reference("${resolve(\"t\")}"));
1411        assert!(!is_relation_reference("${ref(\"t\") + \" OR x\"}"));
1412        assert!(!is_relation_reference("${ref(a /* ( */) + x)}"));
1413        assert!(!is_relation_reference("${when(incremental(), \"x\")}"));
1414        let m = mask_sqlx("SELECT * FROM ${ref('t')} WHERE ${\"x OR y\"}").unwrap();
1415        assert_eq!(m.opaque_tokens(), vec!["__sqlx_token_001__".to_string()]);
1416    }
1417
1418    #[test]
1419    fn content_masking_and_problems() {
1420        let a = mask_sqlx_by_content("SELECT * FROM ${ref('t')}").unwrap();
1421        let b = mask_sqlx_by_content("SELECT x FROM ${ref('t')} AS y").unwrap();
1422        let sentinel = content_sentinel("${ref('t')}");
1423        assert!(a.contains(&sentinel) && b.contains(&sentinel));
1424        assert_eq!(sentinel.len(), "__sqlx_".len() + 16 + 2);
1425        assert_eq!(
1426            dynamic_sentinels("SELECT ${x}, ${ref('t')}").unwrap(),
1427            vec![content_sentinel("${x}")]
1428        );
1429        assert_eq!(
1430            masked_template_problem(&["SELECT __sqlx_token_000__"]),
1431            Some(LOADER_TOKEN_REASON)
1432        );
1433        assert_eq!(
1434            masked_template_problem(&[&format!("SELECT '{sentinel}'")]),
1435            Some(STRING_REASON)
1436        );
1437        assert_eq!(
1438            masked_template_problem(&[&format!("SELECT * FROM {sentinel}")]),
1439            None
1440        );
1441        assert_eq!(with_preserved_whitespace("  a \n", "b"), "  b \n");
1442        assert_eq!(with_preserved_whitespace("  a \n", ""), "  a \n");
1443    }
1444
1445    #[test]
1446    fn parses_config_blocks() {
1447        let config = parse_sqlx_config(
1448            r#"config {
1449  type: 'incremental', // it's incremental {
1450  schema: "analytics",
1451  name: `daily`,
1452  tags: ["a", 'b',],
1453  disabled: false,
1454  description: "Daily rollup",
1455  columns: { id: "the key", payload: { description: "nested", columns: { x: "inner" }, bigqueryPolicyTags: ["p"] } },
1456  dependencies: ["dep_one", {name: "dep_two", schema: "raw"}],
1457  uniqueKey: ["id"],
1458  bigquery: { partitionBy: "DATE(ts)", clusterBy: ["id", "kind"], labels: { team: "data" } },
1459  assertions: { uniqueKey: ["id"], uniqueKeys: [["a", "b"], {uniqueKey: ["c"]}], nonNull: "id", rowConditions: ["x > 0"] },
1460}"#,
1461        )
1462        .unwrap();
1463        assert_eq!(config.action_type.as_deref(), Some("incremental"));
1464        assert_eq!(config.schema.as_deref(), Some("analytics"));
1465        assert_eq!(config.name.as_deref(), Some("daily"));
1466        assert_eq!(config.tags, vec!["a", "b"]);
1467        assert_eq!(config.disabled, Some(false));
1468        assert_eq!(
1469            config.columns["payload"].columns["x"]
1470                .description
1471                .as_deref(),
1472            Some("inner")
1473        );
1474        assert_eq!(config.columns["payload"].policy_tags, vec!["p"]);
1475        assert_eq!(config.dependencies.len(), 2);
1476        assert!(
1477            matches!(&config.dependencies[1], SqlxDependency::Target(t) if t.schema.as_deref() == Some("raw"))
1478        );
1479        assert_eq!(config.bigquery.partition_by.as_deref(), Some("DATE(ts)"));
1480        assert_eq!(config.bigquery.cluster_by, vec!["id", "kind"]);
1481        assert_eq!(config.bigquery.labels["team"], "data");
1482        assert_eq!(
1483            config.assertions.unique_keys,
1484            vec![
1485                vec!["a".to_string(), "b".to_string()],
1486                vec!["c".to_string()]
1487            ]
1488        );
1489        assert_eq!(config.assertions.non_null, vec!["id"]);
1490        assert_eq!(config.assertions.row_conditions, vec!["x > 0"]);
1491        assert_eq!(config.unique_key, vec!["id"]);
1492        assert!(config.problems.is_empty(), "{:?}", config.problems);
1493        assert!(config.computed.is_empty(), "{:?}", config.computed);
1494    }
1495
1496    #[test]
1497    fn tolerates_empty_and_computed_configs() {
1498        assert_eq!(parse_sqlx_config("").unwrap(), SqlxConfig::default());
1499        let c = parse_sqlx_config("config {}").unwrap();
1500        assert_eq!(c.effective_type(), "table");
1501        let c = parse_sqlx_config("config { tags: [] }").unwrap();
1502        assert!(c.tags.is_empty());
1503        let c = parse_sqlx_config(
1504            "{ schema: dataform.projectConfig.vars.s, type: \"view\", name: \"a\" + suffix }",
1505        )
1506        .unwrap();
1507        assert_eq!(c.schema, None);
1508        assert!(c.computed.contains(&"schema".to_string()));
1509        assert!(c.computed.contains(&"name".to_string()));
1510        let c = parse_sqlx_config("config { type: \"table\", uniqueKey: [\"id\"] }").unwrap();
1511        assert_eq!(
1512            c.problems,
1513            vec!["config key 'uniqueKey' is not accepted for type 'table'"]
1514        );
1515        let c = parse_sqlx_config("config { type: \"tabel\" }").unwrap();
1516        assert_eq!(c.problems.len(), 1);
1517        assert!(parse_sqlx_config("config { type: ").is_err());
1518        assert!(parse_sqlx_config("SELECT 1").is_err());
1519    }
1520}