Skip to main content

kumosql_sql/
scripts.rs

1//! BigQuery scripts: break them into statements and follow what flows between them.
2//!
3//! Mirrors `kumosql.scripts`. A script is several statements run together, with variables,
4//! temporary tables, control flow and stored procedures between them. Reading happens in steps:
5//!
6//! 1. [`split_script`] cuts the text into statements with a small lexer that knows strings (raw,
7//!    triple-quoted), comments, quoted names and nested `BEGIN ... END`, `IF`, `LOOP`, `WHILE`,
8//!    `FOR`, `REPEAT` and `CASE` blocks. Semicolons inside any of those never split.
9//! 2. Each statement is *kept* (it reads or writes tables), *ignored* (scalar `DECLARE`/`SET`,
10//!    `ASSERT`, transactions, `LOAD DATA`, definitions outside tables, control-flow shells) or
11//!    *unknown* (it might read tables and could not be understood). Unknown is never guessed.
12//! 3. Kept statements are followed in order. A temporary table remembers what it was built from,
13//!    a script variable remembers the tables its value came from, a statement inside an `IF`, loop
14//!    or exception handler is a *possible* edge, and a temporary table one query defines is spliced
15//!    into the final query as a CTE so column lineage reaches the real sources.
16//!
17//! Nothing here echoes SQL text: [`ScriptAnalysis::report`] carries counts, kinds and line numbers.
18
19use std::collections::HashSet;
20use std::sync::OnceLock;
21
22use indexmap::{IndexMap, IndexSet};
23use regex::Regex;
24use serde::{Deserialize, Serialize};
25
26use crate::ast::*;
27use crate::parser::parse_statements;
28use crate::printer::to_sql_compact;
29
30/// Deepest chain of `CALL`s followed.
31pub const MAX_PROCEDURE_DEPTH: usize = 8;
32/// Deepest nesting of `EXECUTE IMMEDIATE` followed.
33pub const MAX_NESTED_SQL_DEPTH: usize = 3;
34/// Trial runs of a loop body before its variables are called unsettled.
35pub const MAX_LOOP_PASSES: usize = 12;
36/// Deepest nesting of loops followed.
37pub const MAX_LOOP_NESTING: usize = 4;
38
39type Tables = IndexMap<String, TableName>;
40
41// ------------------------------------------------------------------------ lexer
42
43/// What a script token is.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
45pub enum TokKind {
46    Word,
47    String,
48    Quoted,
49    Number,
50    Punct,
51    Semicolon,
52}
53
54/// A token of the script lexer (comments dropped, unterminated strings tolerated).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct Tok {
57    pub kind: TokKind,
58    pub text: String,
59    pub start: usize,
60    pub end: usize,
61}
62
63impl Tok {
64    /// Upper-cased text of a word, empty otherwise.
65    pub fn up(&self) -> String {
66        if self.kind == TokKind::Word {
67            self.text.to_ascii_uppercase()
68        } else {
69            String::new()
70        }
71    }
72}
73
74fn string_end(text: &str, start: usize) -> usize {
75    let bytes = text.as_bytes();
76    let quote = bytes[start];
77    let triple = bytes.get(start + 1) == Some(&quote) && bytes.get(start + 2) == Some(&quote);
78    let closer_len = if triple { 3 } else { 1 };
79    let mut i = start + closer_len;
80    while i < bytes.len() {
81        if bytes[i] == b'\\' {
82            i += 2;
83        } else if bytes[i] == quote
84            && (!triple || (bytes.get(i + 1) == Some(&quote) && bytes.get(i + 2) == Some(&quote)))
85        {
86            return i + closer_len;
87        } else if !triple && bytes[i] == b'\n' {
88            return i; // an unterminated one-line string stops at the line end
89        } else {
90            i += 1;
91        }
92    }
93    bytes.len()
94}
95
96fn char_boundary(text: &str, mut index: usize) -> usize {
97    index = index.min(text.len());
98    while !text.is_char_boundary(index) {
99        index += 1;
100    }
101    index
102}
103
104/// Tokens of BigQuery SQL with comments dropped. Unterminated strings run to the end of their line.
105pub fn lex(text: &str) -> Vec<Tok> {
106    let bytes = text.as_bytes();
107    let n = bytes.len();
108    let mut tokens = Vec::new();
109    let mut i = 0;
110    let push = |tokens: &mut Vec<Tok>, kind: TokKind, start: usize, end: usize| {
111        tokens.push(Tok {
112            kind,
113            text: text[start..end].to_string(),
114            start,
115            end,
116        })
117    };
118    while i < n {
119        let c = bytes[i];
120        if c.is_ascii_whitespace() {
121            i += 1;
122        } else if c == b'#' || text[i..].starts_with("--") {
123            i = text[i..].find('\n').map_or(n, |j| i + j + 1);
124        } else if text[i..].starts_with("/*") {
125            i = text[i + 2..].find("*/").map_or(n, |j| i + 2 + j + 2);
126        } else if c == b'\'' || c == b'"' {
127            let end = string_end(text, i);
128            push(&mut tokens, TokKind::String, i, end);
129            i = end;
130        } else if c == b'`' {
131            let mut j = i + 1;
132            while j < n && bytes[j] != b'`' {
133                j += if bytes[j] == b'\\' { 2 } else { 1 };
134            }
135            let end = char_boundary(text, (j + 1).min(n));
136            push(&mut tokens, TokKind::Quoted, i, end);
137            i = end;
138        } else if c == b';' {
139            push(&mut tokens, TokKind::Semicolon, i, i + 1);
140            i += 1;
141        } else if c.is_ascii_alphabetic() || c == b'_' {
142            let mut j = i;
143            while j < n
144                && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_' || bytes[j] == b'$')
145            {
146                j += 1;
147            }
148            let word = text[i..j].to_ascii_lowercase();
149            if matches!(word.as_str(), "r" | "b" | "rb" | "br")
150                && j < n
151                && (bytes[j] == b'\'' || bytes[j] == b'"')
152            {
153                let end = string_end(text, j);
154                push(&mut tokens, TokKind::String, i, end);
155                i = end;
156            } else {
157                push(&mut tokens, TokKind::Word, i, j);
158                i = j;
159            }
160        } else if c.is_ascii_digit() {
161            let mut j = i;
162            while j < n
163                && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_' || bytes[j] == b'.')
164            {
165                j += 1;
166            }
167            push(&mut tokens, TokKind::Number, i, j);
168            i = j;
169        } else {
170            let len = text[i..].chars().next().map_or(1, char::len_utf8);
171            push(&mut tokens, TokKind::Punct, i, i + len);
172            i += len;
173        }
174    }
175    tokens
176}
177
178/// The value of a string literal token, or `None` for bytes or an escape it does not decode.
179pub fn string_value(token: &str) -> Option<String> {
180    let prefix_len = token.find(['\'', '"'])?;
181    let prefix = token[..prefix_len].to_ascii_lowercase();
182    if prefix.contains('b') {
183        return None;
184    }
185    let body = &token[prefix_len..];
186    let triple = body.starts_with("'''") || body.starts_with("\"\"\"");
187    let q = if triple { 3 } else { 1 };
188    if body.len() < 2 * q {
189        return None;
190    }
191    let inner = &body[q..body.len() - q];
192    if prefix.contains('r') || !inner.contains('\\') {
193        return Some(inner.to_string());
194    }
195    let mut out = String::new();
196    let mut chars = inner.chars().peekable();
197    while let Some(c) = chars.next() {
198        if c == '\\' {
199            let next = chars.next()?;
200            out.push(match next {
201                'n' => '\n',
202                't' => '\t',
203                'r' => '\r',
204                '\\' => '\\',
205                '\'' => '\'',
206                '"' => '"',
207                '`' => '`',
208                '?' => '?',
209                _ => return None,
210            });
211        } else {
212            out.push(c);
213        }
214    }
215    Some(out)
216}
217
218// ------------------------------------------------------------------------ statement tree
219
220/// The kind of a script node.
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
222pub enum NodeKind {
223    Stmt,
224    Begin,
225    If,
226    While,
227    Loop,
228    For,
229    Repeat,
230    Case,
231    Procedure,
232}
233
234/// One statement or control structure of a script.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct ScriptNode {
237    pub kind: NodeKind,
238    pub start: usize,
239    pub end: usize,
240    /// A statement's text; a control structure's condition text.
241    pub header: String,
242    pub branches: Vec<Vec<ScriptNode>>,
243    /// A procedure's name, a FOR loop's variable.
244    pub name: String,
245    /// A FOR loop's query.
246    pub query: String,
247    /// A procedure's parameter list.
248    pub params: String,
249    /// Every condition that picks a path: IF/ELSEIF, CASE and WHEN, WHILE, UNTIL.
250    pub conditions: Vec<String>,
251}
252
253impl ScriptNode {
254    fn new(kind: NodeKind, start: usize) -> Self {
255        ScriptNode {
256            kind,
257            start,
258            end: start,
259            header: String::new(),
260            branches: Vec::new(),
261            name: String::new(),
262            query: String::new(),
263            params: String::new(),
264            conditions: Vec::new(),
265        }
266    }
267}
268
269struct Splitter<'a> {
270    text: &'a str,
271    toks: Vec<Tok>,
272    i: usize,
273}
274
275impl<'a> Splitter<'a> {
276    fn peek(&self, offset: usize) -> Option<&Tok> {
277        self.toks.get(self.i + offset)
278    }
279
280    fn word(&self, offset: usize) -> String {
281        self.peek(offset).map(Tok::up).unwrap_or_default()
282    }
283
284    fn n(&self) -> usize {
285        self.toks.len()
286    }
287
288    fn skip_to_semicolon(&mut self) {
289        while self.i < self.n() && self.toks[self.i].kind != TokKind::Semicolon {
290            self.i += 1;
291        }
292        if self.i < self.n() {
293            self.i += 1;
294        }
295    }
296
297    /// Token range up to a keyword in `stop` at parenthesis and CASE depth zero; leaves `i` on it.
298    fn scan_until(&mut self, stop: &[&str]) -> (usize, usize) {
299        let start = self.i;
300        let mut depth = 0usize;
301        let mut case = 0usize;
302        while self.i < self.n() {
303            let t = &self.toks[self.i];
304            match t.kind {
305                TokKind::Punct if t.text == "(" => depth += 1,
306                TokKind::Punct if t.text == ")" => depth = depth.saturating_sub(1),
307                TokKind::Word => {
308                    let up = t.up();
309                    if up == "CASE" {
310                        case += 1;
311                    } else if up == "END" && case > 0 {
312                        case -= 1;
313                    } else if depth == 0 && case == 0 && stop.contains(&up.as_str()) {
314                        break;
315                    }
316                }
317                TokKind::Semicolon if depth == 0 => break,
318                _ => {}
319            }
320            self.i += 1;
321        }
322        (start, self.i)
323    }
324
325    fn text_of(&self, a: usize, b: usize) -> String {
326        if a >= b || a >= self.n() {
327            return String::new();
328        }
329        self.text[self.toks[a].start..self.toks[b - 1].end].to_string()
330    }
331
332    fn block(&mut self, terminators: &[&str]) -> Vec<ScriptNode> {
333        let mut nodes = Vec::new();
334        while self.i < self.n() {
335            let t = &self.toks[self.i];
336            if t.kind == TokKind::Semicolon {
337                self.i += 1;
338                continue;
339            }
340            if t.kind == TokKind::Word && terminators.contains(&t.up().as_str()) {
341                break;
342            }
343            if let Some(node) = self.statement(!terminators.is_empty()) {
344                nodes.push(node);
345            }
346        }
347        nodes
348    }
349
350    fn statement(&mut self, inside_block: bool) -> Option<ScriptNode> {
351        // an optional `label:` before a block
352        if self.peek(1).is_some_and(|t| t.text == ":")
353            && self.toks[self.i].kind == TokKind::Word
354            && ["BEGIN", "LOOP", "WHILE", "FOR", "REPEAT"].contains(&self.word(2).as_str())
355        {
356            self.i += 2;
357        }
358        let first = self.word(0);
359        let begin = self.toks[self.i].start;
360        if first == "BEGIN"
361            && !["TRANSACTION", ""].contains(&self.word(1).as_str())
362            && self.peek(1).is_some_and(|t| t.kind != TokKind::Semicolon)
363        {
364            return Some(self.begin_block(begin));
365        }
366        if first == "IF"
367            && (self.peek(1).is_some_and(|t| t.text != "(") || self.control_if_call_is_statement())
368        {
369            return Some(self.if_block(begin));
370        }
371        match first.as_str() {
372            "WHILE" => return Some(self.simple_loop(begin, NodeKind::While, &["DO"])),
373            "LOOP" => return Some(self.simple_loop(begin, NodeKind::Loop, &[])),
374            "REPEAT" => return Some(self.repeat_block(begin)),
375            "FOR" if self.word(2) == "IN" => return Some(self.for_block(begin)),
376            "CASE" => return Some(self.case_block(begin)),
377            "CREATE" => {
378                if let Some(node) = self.maybe_procedure(begin) {
379                    return Some(node);
380                }
381            }
382            _ => {}
383        }
384        self.simple(inside_block)
385    }
386
387    fn control_if_call_is_statement(&self) -> bool {
388        // `IF(cond, a, b)` opens no statement of its own; an IF statement is `IF cond THEN`
389        let mut depth = 0i32;
390        for t in &self.toks[self.i..] {
391            match t.kind {
392                TokKind::Punct if t.text == "(" => depth += 1,
393                TokKind::Punct if t.text == ")" => depth -= 1,
394                TokKind::Semicolon => return false,
395                TokKind::Word if t.up() == "THEN" && depth == 0 => return true,
396                _ => {}
397            }
398        }
399        false
400    }
401
402    fn end_statement(&mut self) {
403        if self.word(0) == "END" {
404            self.i += 1;
405        }
406        self.skip_to_semicolon();
407    }
408
409    fn last_end(&self, fallback: usize) -> usize {
410        if self.i > 0 {
411            self.toks[self.i - 1].end
412        } else {
413            fallback
414        }
415    }
416
417    fn exception_handler(&mut self, node: &mut ScriptNode) {
418        if self.word(0) == "EXCEPTION" {
419            self.i += 1;
420            if self.word(0) == "WHEN" {
421                self.scan_until(&["THEN"]);
422                self.i += 1;
423            }
424            node.branches.push(self.block(&["END"]));
425        }
426    }
427
428    fn begin_block(&mut self, begin: usize) -> ScriptNode {
429        self.i += 1;
430        let mut node = ScriptNode::new(NodeKind::Begin, begin);
431        node.branches.push(self.block(&["END", "EXCEPTION"]));
432        self.exception_handler(&mut node);
433        self.end_statement();
434        node.end = self.last_end(begin);
435        node
436    }
437
438    fn if_block(&mut self, begin: usize) -> ScriptNode {
439        self.i += 1;
440        let (a, b) = self.scan_until(&["THEN"]);
441        let mut node = ScriptNode::new(NodeKind::If, begin);
442        node.header = self.text_of(a, b);
443        node.conditions.push(node.header.clone());
444        self.i += 1; // THEN
445        node.branches.push(self.block(&["ELSEIF", "ELSE", "END"]));
446        while ["ELSEIF", "ELSE"].contains(&self.word(0).as_str()) {
447            if self.word(0) == "ELSEIF" {
448                self.i += 1;
449                let (a, b) = self.scan_until(&["THEN"]);
450                node.conditions.push(self.text_of(a, b));
451            }
452            self.i += 1;
453            node.branches.push(self.block(&["ELSEIF", "ELSE", "END"]));
454        }
455        self.end_statement();
456        node.end = self.last_end(begin);
457        node
458    }
459
460    fn simple_loop(&mut self, begin: usize, kind: NodeKind, header_stop: &[&str]) -> ScriptNode {
461        self.i += 1;
462        let mut node = ScriptNode::new(kind, begin);
463        if !header_stop.is_empty() {
464            let (a, b) = self.scan_until(header_stop);
465            node.header = self.text_of(a, b);
466            node.conditions.push(node.header.clone());
467            self.i += 1;
468        }
469        node.branches.push(self.block(&["END"]));
470        self.end_statement();
471        node.end = self.last_end(begin);
472        node
473    }
474
475    fn repeat_block(&mut self, begin: usize) -> ScriptNode {
476        self.i += 1;
477        let mut node = ScriptNode::new(NodeKind::Repeat, begin);
478        node.branches.push(self.block(&["UNTIL", "END"]));
479        if self.word(0) == "UNTIL" {
480            self.i += 1;
481            let (a, b) = self.scan_until(&["END"]);
482            node.header = self.text_of(a, b);
483            node.conditions.push(node.header.clone());
484        }
485        self.end_statement();
486        node.end = self.last_end(begin);
487        node
488    }
489
490    fn for_block(&mut self, begin: usize) -> ScriptNode {
491        let variable = self.toks[self.i + 1].text.clone();
492        self.i += 3; // FOR var IN
493        let (a, b) = self.scan_until(&["DO"]);
494        let mut query = self.text_of(a, b).trim().to_string();
495        if query.starts_with('(') && query.ends_with(')') {
496            query = query[1..query.len() - 1].to_string();
497        }
498        let mut node = ScriptNode::new(NodeKind::For, begin);
499        node.name = variable;
500        node.query = query;
501        self.i += 1;
502        node.branches.push(self.block(&["END"]));
503        self.end_statement();
504        node.end = self.last_end(begin);
505        node
506    }
507
508    fn case_block(&mut self, begin: usize) -> ScriptNode {
509        self.i += 1;
510        let (a, b) = self.scan_until(&["WHEN"]);
511        let mut node = ScriptNode::new(NodeKind::Case, begin);
512        node.header = self.text_of(a, b);
513        if !node.header.trim().is_empty() {
514            node.conditions.push(node.header.clone());
515        }
516        while ["WHEN", "ELSE"].contains(&self.word(0).as_str()) {
517            if self.word(0) == "WHEN" {
518                self.i += 1;
519                let (a, b) = self.scan_until(&["THEN"]);
520                node.conditions.push(self.text_of(a, b));
521            }
522            self.i += 1;
523            node.branches.push(self.block(&["WHEN", "ELSE", "END"]));
524        }
525        self.end_statement();
526        node.end = self.last_end(begin);
527        node
528    }
529
530    fn maybe_procedure(&mut self, begin: usize) -> Option<ScriptNode> {
531        let mut j = self.i + 1;
532        while j < self.n()
533            && ["OR", "REPLACE", "TEMP", "TEMPORARY"].contains(&self.toks[j].up().as_str())
534        {
535            j += 1;
536        }
537        if !(j < self.n() && self.toks[j].up() == "PROCEDURE") {
538            return None;
539        }
540        j += 1;
541        if j < self.n() && self.toks[j].up() == "IF" {
542            j += 3; // IF NOT EXISTS
543        }
544        let mut name_parts = Vec::new();
545        while j < self.n()
546            && (matches!(self.toks[j].kind, TokKind::Word | TokKind::Quoted)
547                || self.toks[j].text == ".")
548        {
549            name_parts.push(self.toks[j].text.clone());
550            j += 1;
551        }
552        // parameter list, then OPTIONS(...) / LANGUAGE ..., then BEGIN
553        let params_start = j;
554        let mut k = j;
555        let mut depth = 0i32;
556        loop {
557            if k >= self.n() {
558                return None;
559            }
560            let t = &self.toks[k];
561            match t.kind {
562                TokKind::Punct if t.text == "(" => depth += 1,
563                TokKind::Punct if t.text == ")" => depth -= 1,
564                TokKind::Semicolon if depth == 0 => return None, // no body here (a language other than SQL)
565                TokKind::Word if t.up() == "BEGIN" && depth == 0 => break,
566                _ => {}
567            }
568            k += 1;
569        }
570        let mut node = ScriptNode::new(NodeKind::Procedure, begin);
571        node.name = name_parts.concat().replace('`', "");
572        node.params = self.text_of(params_start, k);
573        self.i = k + 1;
574        node.branches.push(self.block(&["END", "EXCEPTION"]));
575        self.exception_handler(&mut node);
576        self.end_statement();
577        node.end = self.last_end(begin);
578        Some(node)
579    }
580
581    fn simple(&mut self, inside_block: bool) -> Option<ScriptNode> {
582        let start = self.i;
583        let mut depth = 0usize;
584        let mut case = 0usize;
585        while self.i < self.n() {
586            let t = &self.toks[self.i];
587            match t.kind {
588                TokKind::Semicolon => break,
589                TokKind::Punct => {
590                    if t.text == "(" {
591                        depth += 1;
592                    } else if t.text == ")" && depth > 0 {
593                        depth -= 1;
594                    }
595                }
596                TokKind::Word => {
597                    let up = t.up();
598                    if up == "CASE" {
599                        case += 1;
600                    } else if up == "END" {
601                        if case > 0 {
602                            case -= 1;
603                        } else if inside_block && depth == 0 {
604                            break; // the block's END closes a last statement written without its semicolon
605                        }
606                    }
607                }
608                _ => {}
609            }
610            self.i += 1;
611        }
612        let stop = self.i;
613        if self.i < self.n() && self.toks[self.i].kind == TokKind::Semicolon {
614            self.i += 1;
615        }
616        if stop == start {
617            if self.i == start {
618                self.i += 1; // a stray END or keyword at the top level: step over it
619            }
620            return None;
621        }
622        let mut node = ScriptNode::new(NodeKind::Stmt, self.toks[start].start);
623        node.end = self.toks[stop - 1].end;
624        node.header = self.text_of(start, stop);
625        Some(node)
626    }
627}
628
629/// The statement tree of a script.
630pub fn script_tree(text: &str) -> Vec<ScriptNode> {
631    let mut splitter = Splitter {
632        text,
633        toks: lex(text),
634        i: 0,
635    };
636    splitter.block(&[])
637}
638
639fn walk_nodes<'n>(nodes: &'n [ScriptNode], out: &mut Vec<&'n ScriptNode>) {
640    for node in nodes {
641        out.push(node);
642        for branch in &node.branches {
643            walk_nodes(branch, out);
644        }
645    }
646}
647
648fn line_index(text: &str) -> Vec<usize> {
649    text.match_indices('\n').map(|(i, _)| i).collect()
650}
651
652fn line_at(breaks: &[usize], offset: usize) -> usize {
653    breaks.partition_point(|&b| b < offset) + 1
654}
655
656/// A statement of a script, in order, with where it sits.
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
658pub struct ScriptStatement {
659    pub text: String,
660    pub line: usize,
661    /// Inside a branch, loop or exception handler: it may not run.
662    pub conditional: bool,
663    /// The procedure it is defined in, if any.
664    pub in_procedure: String,
665    pub span: crate::token::Span,
666}
667
668/// The statements of `text` in order. Blocks and control flow are opened, not returned as statements.
669pub fn split_script(text: &str) -> Vec<ScriptStatement> {
670    fn walk(
671        nodes: &[ScriptNode],
672        conditional: bool,
673        procedure: &str,
674        breaks: &[usize],
675        out: &mut Vec<ScriptStatement>,
676    ) {
677        for node in nodes {
678            if node.kind == NodeKind::Stmt {
679                out.push(ScriptStatement {
680                    text: node.header.clone(),
681                    line: line_at(breaks, node.start),
682                    conditional,
683                    in_procedure: procedure.to_string(),
684                    span: crate::token::Span::new(node.start, node.end),
685                });
686                continue;
687            }
688            let inner = if !procedure.is_empty() {
689                procedure.to_string()
690            } else if node.kind == NodeKind::Procedure {
691                node.name.clone()
692            } else {
693                String::new()
694            };
695            for (index, branch) in node.branches.iter().enumerate() {
696                let gated = conditional
697                    || matches!(
698                        node.kind,
699                        NodeKind::If
700                            | NodeKind::While
701                            | NodeKind::For
702                            | NodeKind::Repeat
703                            | NodeKind::Case
704                            | NodeKind::Loop
705                    )
706                    || (matches!(node.kind, NodeKind::Begin | NodeKind::Procedure) && index > 0);
707                walk(branch, gated, &inner, breaks, out);
708            }
709        }
710    }
711    let breaks = line_index(text);
712    let mut out = Vec::new();
713    walk(&script_tree(text), false, "", &breaks, &mut out);
714    out
715}
716
717/// Just the statement texts, in order.
718pub fn split_statements(text: &str) -> Vec<String> {
719    split_script(text).into_iter().map(|s| s.text).collect()
720}
721
722/// The statement nodes of `text` in order, with their offsets; blocks are opened.
723pub fn leaf_statements(text: &str) -> Vec<ScriptNode> {
724    let tree = script_tree(text);
725    let mut all = Vec::new();
726    walk_nodes(&tree, &mut all);
727    all.into_iter()
728        .filter(|n| n.kind == NodeKind::Stmt)
729        .cloned()
730        .collect()
731}
732
733/// Whether `text` has `BEGIN ... END`, `IF`, a loop or a procedure around its statements.
734pub fn has_blocks(text: &str) -> bool {
735    script_tree(text).iter().any(|n| n.kind != NodeKind::Stmt)
736}
737
738/// A statement whose query text a rewrite rule may change (not a declaration, assignment or call).
739pub fn is_rewriteable(statement: &str) -> bool {
740    first_words(statement, 1).first().is_some_and(|w| {
741        [
742            "SELECT", "WITH", "FROM", "CREATE", "INSERT", "MERGE", "UPDATE", "DELETE", "(",
743        ]
744        .contains(&w.as_str())
745    })
746}
747
748fn block_words_re() -> &'static Regex {
749    static RE: OnceLock<Regex> = OnceLock::new();
750    RE.get_or_init(|| {
751        Regex::new(r"(?i)\b(?:BEGIN|LOOP|WHILE|REPEAT|THEN|DO)\b").expect("valid regex")
752    })
753}
754
755fn block_start_re() -> &'static Regex {
756    static RE: OnceLock<Regex> = OnceLock::new();
757    RE.get_or_init(|| {
758        Regex::new(r"(?i)^\s*(?:BEGIN|IF|LOOP|WHILE|REPEAT|FOR|CASE)\b").expect("valid regex")
759    })
760}
761
762/// The parsed statements a rewrite may change, in order, when `text` has blocks; `None` for plain SQL.
763pub fn block_statements(text: &str) -> Option<crate::Result<Vec<Statement>>> {
764    if !block_words_re().is_match(text) || !has_blocks(text) {
765        return None;
766    }
767    let mut out = Vec::new();
768    for node in leaf_statements(text) {
769        if is_rewriteable(&node.header) {
770            match parse_statements(&node.header) {
771                Ok(statements) => out.extend(statements),
772                Err(e) => return Some(Err(e)),
773            }
774        }
775    }
776    Some(Ok(out))
777}
778
779/// What a rewrite must leave alone in a script: its tokens with each rewriteable statement
780/// replaced by one `<statement>` placeholder (words upper-cased, strings exact).
781pub fn script_skeleton(text: &str) -> Vec<String> {
782    let ranges: Vec<(usize, usize)> = leaf_statements(text)
783        .into_iter()
784        .filter(|n| is_rewriteable(&n.header))
785        .map(|n| (n.start, n.end))
786        .collect();
787    let mut skeleton = Vec::new();
788    let mut inside: Option<usize> = None;
789    for token in lex(text) {
790        let index = ranges
791            .iter()
792            .position(|(s, e)| *s <= token.start && token.start < *e);
793        if let Some(index) = index {
794            if inside != Some(index) {
795                skeleton.push("<statement>".to_string());
796            }
797            inside = Some(index);
798            continue;
799        }
800        inside = None;
801        skeleton.push(if token.kind == TokKind::Word {
802            token.text.to_ascii_uppercase()
803        } else {
804            token.text
805        });
806    }
807    skeleton
808}
809
810/// Every name the text could use as a column (lower-cased), or `None` when it selects `*`.
811pub fn column_words(text: &str) -> Option<HashSet<String>> {
812    let mut words = HashSet::new();
813    let toks = lex(text);
814    for (i, tok) in toks.iter().enumerate() {
815        match tok.kind {
816            TokKind::Word => {
817                words.insert(tok.text.to_lowercase());
818            }
819            TokKind::Quoted => {
820                for part in tok
821                    .text
822                    .trim_matches('`')
823                    .split('.')
824                    .filter(|p| !p.is_empty())
825                {
826                    words.insert(part.to_lowercase());
827                }
828            }
829            TokKind::Punct if tok.text == "*" => {
830                let before = i.checked_sub(1).and_then(|j| toks.get(j));
831                let after = toks.get(i + 1);
832                let star_select = before.is_some_and(|b| {
833                    ["SELECT", "DISTINCT", "ALL", "STRUCT", "VALUE"].contains(&b.up().as_str())
834                        || b.text == ","
835                        || b.text == "."
836                }) || after
837                    .is_some_and(|a| ["EXCEPT", "REPLACE", "FROM"].contains(&a.up().as_str()));
838                if star_select {
839                    return None;
840                }
841            }
842            _ => {}
843        }
844    }
845    Some(words)
846}
847
848fn code_start(text: &str) -> usize {
849    let bytes = text.as_bytes();
850    let mut i = 0;
851    while i < bytes.len() {
852        if bytes[i].is_ascii_whitespace() {
853            i += 1;
854        } else if bytes[i] == b'#' || text[i..].starts_with("--") {
855            i = text[i..].find('\n').map_or(bytes.len(), |j| i + j + 1);
856        } else if text[i..].starts_with("/*") {
857            i = text[i + 2..]
858                .find("*/")
859                .map_or(bytes.len(), |j| i + 2 + j + 2);
860        } else {
861            break;
862        }
863    }
864    i
865}
866
867fn first_words(text: &str, count: usize) -> Vec<String> {
868    // only the start is lexed, measured from the first code: a long header comment must not hide the kind
869    let start = code_start(text);
870    let end = char_boundary(text, start + 600);
871    let mut words = Vec::new();
872    for tok in lex(&text[start..end]) {
873        if tok.kind == TokKind::Word {
874            words.push(tok.up());
875        } else if tok.text == "(" && words.is_empty() {
876            words.push("(".to_string());
877        } else {
878            words.push(String::new());
879        }
880        if words.len() >= count {
881            break;
882        }
883    }
884    words
885}
886
887// ------------------------------------------------------------------------ token reads
888
889const NOT_TABLES: &[&str] = &[
890    "SELECT",
891    "UNNEST",
892    "LATERAL",
893    "ONLY",
894    "WHERE",
895    "SET",
896    "VALUES",
897    "ON",
898    "AS",
899    "WITH",
900    "GENERATE_ARRAY",
901    "UNION",
902    "ALL",
903    "DISTINCT",
904    "TABLE",
905    "MODEL",
906    "DELETE",
907    "INSERT",
908    "UPDATE",
909    "MERGE",
910    "INTO",
911    "FROM",
912    "JOIN",
913    "USING",
914    "NOT",
915    "EXISTS",
916    "IF",
917    "NULL",
918    "TRUE",
919    "FALSE",
920    "CASE",
921    "WHEN",
922    "THEN",
923    "ELSE",
924    "END",
925    "OR",
926    "AND",
927    "REPLACE",
928    "TEMP",
929    "TEMPORARY",
930    "VIEW",
931    "MATERIALIZED",
932    "EXTERNAL",
933];
934const CLAUSE_END: &[&str] = &[
935    "WHERE",
936    "GROUP",
937    "ORDER",
938    "HAVING",
939    "LIMIT",
940    "UNION",
941    "INTERSECT",
942    "EXCEPT",
943    "WINDOW",
944    "QUALIFY",
945    "ON",
946    "USING",
947    "SET",
948    "WHEN",
949    "JOIN",
950    "LEFT",
951    "RIGHT",
952    "INNER",
953    "OUTER",
954    "FULL",
955    "CROSS",
956    "NATURAL",
957    "SELECT",
958    "VALUES",
959    "OPTIONS",
960    "PARTITION",
961    "CLUSTER",
962];
963const FROM_ARGUMENT_CALLS: &[&str] = &[
964    "EXTRACT",
965    "TRIM",
966    "SUBSTRING",
967    "SUBSTR",
968    "OVERLAY",
969    "POSITION",
970];
971
972/// The table named at `tokens[i]` and the index after it; `None` for a call or a subquery.
973fn name_at(tokens: &[Tok], i: usize) -> (Option<TableName>, usize) {
974    let Some(token) = tokens.get(i) else {
975        return (None, i);
976    };
977    let (text, j) = match token.kind {
978        TokKind::Quoted => (token.text.clone(), i + 1),
979        TokKind::Word if !NOT_TABLES.contains(&token.up().as_str()) => {
980            let mut parts = vec![token.text.clone()];
981            let mut j = i + 1;
982            while j + 1 < tokens.len()
983                && tokens[j].text == "."
984                && matches!(tokens[j + 1].kind, TokKind::Word | TokKind::Quoted)
985            {
986                parts.push(tokens[j + 1].text.clone());
987                j += 2;
988            }
989            (parts.join("."), j)
990        }
991        _ => {
992            let after = if token.kind == TokKind::Word
993                && tokens.get(i + 1).is_some_and(|t| t.text == "(")
994            {
995                i + 1
996            } else {
997                i
998            };
999            return (None, after);
1000        }
1001    };
1002    if tokens.get(j).is_some_and(|t| t.text == "(") {
1003        return (None, j); // a function call such as UNNEST(x) or fn(TABLE t)
1004    }
1005    let table = TableName::parse(&text);
1006    if table.name.is_empty() {
1007        (None, j)
1008    } else {
1009        (Some(table), j)
1010    }
1011}
1012
1013fn enclosing_call(tokens: &[Tok], index: usize) -> String {
1014    let mut depth = 0usize;
1015    for k in (0..index).rev() {
1016        if tokens[k].text == ")" {
1017            depth += 1;
1018        } else if tokens[k].text == "(" {
1019            if depth == 0 {
1020                return if k > 0 {
1021                    tokens[k - 1].up()
1022                } else {
1023                    String::new()
1024                };
1025            }
1026            depth -= 1;
1027        }
1028    }
1029    String::new()
1030}
1031
1032/// `(tables read, tables written)` found in the tokens of a statement that could not be parsed.
1033///
1034/// A name after `FROM`, `JOIN`, `USING` or `TABLE` is read (`FROM a, b` reads both), one after
1035/// `INTO`, `UPDATE`, `MERGE` or `CREATE ... TABLE|VIEW` is written, and a `CREATE` also reads what it
1036/// `LIKE`s or `CLONE`s. A name is a CTE, not a table, only where its WITH is in scope.
1037pub fn token_reads(text: &str) -> (Vec<TableName>, Vec<TableName>) {
1038    let tokens: Vec<Tok> = lex(text)
1039        .into_iter()
1040        .filter(|t| t.kind != TokKind::Semicolon)
1041        .collect();
1042    let creates = tokens.first().is_some_and(|t| t.up() == "CREATE");
1043    let mut reads = Vec::new();
1044    let mut writes = Vec::new();
1045    let call_end = |start: usize| -> usize {
1046        let mut depth = 0i32;
1047        for (k, t) in tokens.iter().enumerate().skip(start) {
1048            if t.text == "(" {
1049                depth += 1;
1050            } else if t.text == ")" {
1051                depth -= 1;
1052                if depth == 0 {
1053                    return k + 1;
1054                }
1055            }
1056        }
1057        tokens.len()
1058    };
1059    let mut levels = Vec::with_capacity(tokens.len());
1060    let mut level = 0i32;
1061    for t in &tokens {
1062        if t.text == ")" {
1063            level -= 1;
1064        }
1065        levels.push(level);
1066        if t.text == "(" {
1067            level += 1;
1068        }
1069    }
1070    let cte_body = |k: usize| -> Option<usize> {
1071        let mut j = k + 1;
1072        if tokens.get(j).is_some_and(|t| t.text == "(")
1073            && k > 0
1074            && ["WITH", ",", "RECURSIVE"]
1075                .contains(&tokens[k - 1].text.to_ascii_uppercase().as_str())
1076        {
1077            j = call_end(j);
1078        }
1079        if tokens.get(j).map(Tok::up).as_deref() != Some("AS") {
1080            return None;
1081        }
1082        j += 1;
1083        if tokens.get(j).is_some_and(|t| t.up() == "NOT") {
1084            j += 1;
1085        }
1086        if tokens.get(j).is_some_and(|t| t.up() == "MATERIALIZED") {
1087            j += 1;
1088        }
1089        tokens.get(j).filter(|t| t.text == "(").map(|_| j)
1090    };
1091    let mut ctes: IndexMap<String, Vec<(usize, usize)>> = IndexMap::new();
1092    for k in 1..tokens.len() {
1093        if tokens[k].kind != TokKind::Word {
1094            continue;
1095        }
1096        let Some(body) = cte_body(k) else {
1097            continue;
1098        };
1099        let mut start = call_end(body); // a WITH table does not see itself
1100        let mut w = k as i64 - 1;
1101        while w >= 0
1102            && levels[w as usize] >= levels[k]
1103            && !(levels[w as usize] == levels[k] && tokens[w as usize].up() == "WITH")
1104        {
1105            w -= 1;
1106        }
1107        if w >= 0
1108            && levels[w as usize] == levels[k]
1109            && tokens[w as usize].up() == "WITH"
1110            && tokens
1111                .get(w as usize + 1)
1112                .is_some_and(|t| t.up() == "RECURSIVE")
1113        {
1114            start = w as usize;
1115        }
1116        let end = (start..tokens.len())
1117            .find(|&i| levels[i] < levels[k])
1118            .unwrap_or(tokens.len());
1119        ctes.entry(tokens[k].text.to_lowercase())
1120            .or_default()
1121            .push((start, end));
1122    }
1123    let is_cte = |table: &TableName, at: usize| {
1124        table.dataset.is_none()
1125            && table.project.is_none()
1126            && ctes
1127                .get(&table.name.to_lowercase())
1128                .is_some_and(|ranges| ranges.iter().any(|(s, e)| *s <= at && at < *e))
1129    };
1130    let mut i = 0;
1131    while i < tokens.len() {
1132        let word = tokens[i].up();
1133        let previous = if i > 0 {
1134            tokens[i - 1].up()
1135        } else {
1136            String::new()
1137        };
1138        let kind = if word == "FROM"
1139            && (previous == "DISTINCT"
1140                || FROM_ARGUMENT_CALLS.contains(&enclosing_call(&tokens, i).as_str()))
1141        {
1142            None
1143        } else if word == "FROM" {
1144            Some(if previous == "DELETE" {
1145                "write"
1146            } else {
1147                "read"
1148            })
1149        } else if word == "JOIN" || word == "USING" {
1150            Some("read")
1151        } else if ["INTO", "UPDATE", "MERGE", "INSERT"].contains(&word.as_str()) {
1152            Some("write")
1153        } else if word == "TABLE" {
1154            Some(
1155                if [
1156                    "TEMP",
1157                    "TEMPORARY",
1158                    "REPLACE",
1159                    "CREATE",
1160                    "EXTERNAL",
1161                    "SNAPSHOT",
1162                    "DROP",
1163                    "ALTER",
1164                    "TRUNCATE",
1165                ]
1166                .contains(&previous.as_str())
1167                {
1168                    "write"
1169                } else {
1170                    "read"
1171                },
1172            )
1173        } else if word == "VIEW" && creates {
1174            Some("write")
1175        } else if (word == "LIKE" || word == "CLONE") && creates {
1176            Some("read")
1177        } else if word == "DELETE" && tokens.get(i + 1).is_some_and(|t| t.up() != "FROM") {
1178            Some("write")
1179        } else {
1180            None
1181        };
1182        let Some(kind) = kind else {
1183            i += 1;
1184            continue;
1185        };
1186        let mut j = i + 1;
1187        while tokens
1188            .get(j)
1189            .is_some_and(|t| ["INTO", "IF", "NOT", "EXISTS"].contains(&t.up().as_str()))
1190        {
1191            j += 1;
1192        }
1193        let first = j;
1194        let mut scan_to = first;
1195        loop {
1196            let (table, after) = name_at(&tokens, j);
1197            let named = table.is_some();
1198            if let Some(table) = table {
1199                if !is_cte(&table, j) {
1200                    if kind == "read" {
1201                        reads.push(table);
1202                    } else {
1203                        writes.push(table);
1204                    }
1205                }
1206            }
1207            if j == first {
1208                scan_to = scan_to.max(after); // keep scanning inside a subquery or call argument list
1209            }
1210            let mut following = if !named && after < tokens.len() && tokens[after].text == "(" {
1211                call_end(after)
1212            } else {
1213                after
1214            };
1215            if kind != "read" || word != "FROM" {
1216                break;
1217            }
1218            // an alias, then a comma list (`FROM a, b`); stop at anything else
1219            if tokens.get(following).is_some_and(|t| t.up() == "AS") {
1220                following += 2;
1221            } else if tokens
1222                .get(following)
1223                .is_some_and(|t| t.kind == TokKind::Word && !CLAUSE_END.contains(&t.up().as_str()))
1224            {
1225                following += 1;
1226            }
1227            if tokens.get(following).is_some_and(|t| t.text == ",") {
1228                j = following + 1;
1229                continue;
1230            }
1231            break;
1232        }
1233        i = (i + 1).max(scan_to);
1234    }
1235    (reads, writes)
1236}
1237
1238// ------------------------------------------------------------------------ analysis results
1239
1240/// What was decided about a statement.
1241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1242#[serde(rename_all = "lowercase")]
1243pub enum Disposition {
1244    /// It reads or writes tables and was understood.
1245    Kept,
1246    /// Thrown away on purpose (scalar variables, checks, transactions, control-flow shells).
1247    Ignored,
1248    /// It might read tables and could not be understood.
1249    Unknown,
1250}
1251
1252/// What was decided about one statement. Carries no SQL text.
1253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1254pub struct AnalysedStatement {
1255    pub index: usize,
1256    pub line: usize,
1257    pub kind: String,
1258    pub disposition: Disposition,
1259    pub reason: String,
1260    pub conditional: bool,
1261    /// `procedure` or `execute_immediate` when read from inside one.
1262    pub nested: String,
1263    /// Its columns are part of the output query's column lineage.
1264    pub traced: bool,
1265    /// Defines a routine: not a step of the data flow.
1266    pub definition: bool,
1267    /// Writes no column (DELETE, a delete-only MERGE): nothing is left to trace.
1268    pub complete: bool,
1269    /// Could not be parsed; its reads and writes come from its tokens.
1270    pub degraded: bool,
1271    /// Where the parser stopped (line and column, no SQL text).
1272    pub error: String,
1273    /// Real tables it reads directly.
1274    #[serde(skip)]
1275    pub reads: Tables,
1276}
1277
1278impl AnalysedStatement {
1279    fn new(
1280        index: usize,
1281        line: usize,
1282        kind: &str,
1283        disposition: Disposition,
1284        reason: &str,
1285        conditional: bool,
1286    ) -> Self {
1287        AnalysedStatement {
1288            index,
1289            line,
1290            kind: kind.to_string(),
1291            disposition,
1292            reason: reason.to_string(),
1293            conditional,
1294            nested: String::new(),
1295            traced: false,
1296            definition: false,
1297            complete: false,
1298            degraded: false,
1299            error: String::new(),
1300            reads: Tables::new(),
1301        }
1302    }
1303
1304    fn to_json(&self) -> serde_json::Value {
1305        let mut row = serde_json::json!({"line": self.line, "kind": self.kind, "disposition": self.disposition});
1306        let map = row.as_object_mut().expect("object");
1307        if !self.reason.is_empty() {
1308            map.insert("reason".into(), self.reason.clone().into());
1309        }
1310        if self.conditional {
1311            map.insert("conditional".into(), true.into());
1312        }
1313        if !self.nested.is_empty() {
1314            map.insert("nested".into(), self.nested.clone().into());
1315        }
1316        if self.definition {
1317            map.insert("definition".into(), true.into());
1318        }
1319        if self.degraded {
1320            map.insert("degraded".into(), true.into());
1321        }
1322        row
1323    }
1324}
1325
1326/// A table a script writes and the real tables that feed it.
1327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1328pub struct ScriptWrite {
1329    pub table: TableName,
1330    pub sources: Vec<TableName>,
1331    pub kind: String,
1332    pub conditional: bool,
1333    pub via_variable: bool,
1334}
1335
1336/// A stored procedure with a SQL body.
1337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1338pub struct Procedure {
1339    pub name: String,
1340    pub params: Vec<String>,
1341    /// `IN`, `OUT` or `INOUT` per parameter.
1342    pub modes: Vec<String>,
1343    pub body: Vec<ScriptNode>,
1344    /// The script text the body's offsets point into.
1345    pub text: String,
1346}
1347
1348/// `CREATE TABLE FUNCTION name(params) AS query`: kept so a call can be read as the query it stands for.
1349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1350pub struct TableFunction {
1351    pub name: String,
1352    /// `(name, is a table parameter, the columns it declares)`.
1353    pub params: Vec<(String, bool, Vec<String>)>,
1354    pub body: Query,
1355}
1356
1357#[derive(Debug, Clone)]
1358struct Output {
1359    statement: usize,
1360    node: Statement,
1361    query: Query,
1362    temps: Vec<usize>,
1363    target: Option<TableName>,
1364    conditional: bool,
1365    top_level: bool,
1366}
1367
1368/// The result of [`analyse_script`].
1369#[derive(Debug, Clone, Default)]
1370pub struct ScriptAnalysis {
1371    pub text: String,
1372    pub statements: Vec<AnalysedStatement>,
1373    pub writes: Vec<ScriptWrite>,
1374    /// Real tables read directly.
1375    pub reads: Tables,
1376    /// Tables read through variables or conditions.
1377    pub variable_reads: Tables,
1378    /// Tables the bodies of routine definitions read.
1379    pub definition_reads: Tables,
1380    /// Tables read outside the traced output query.
1381    pub side_reads: Tables,
1382    pub procedures: IndexMap<String, Procedure>,
1383    pub procedure_reports: Vec<serde_json::Value>,
1384    /// Temporary tables the final query reads whose query could not be followed, with why.
1385    pub opaque_temps: IndexMap<String, String>,
1386    pub temp_names: IndexSet<String>,
1387    outputs: Vec<Output>,
1388    final_output: Option<usize>,
1389    ctes: Vec<(String, Query)>,
1390}
1391
1392impl ScriptAnalysis {
1393    fn new(text: &str) -> Self {
1394        ScriptAnalysis {
1395            text: text.to_string(),
1396            ..ScriptAnalysis::default()
1397        }
1398    }
1399
1400    fn final_ref(&self) -> Option<&Output> {
1401        self.final_output.and_then(|i| self.outputs.get(i))
1402    }
1403
1404    /// The statement whose columns define the script's output (its last unconditional query),
1405    /// with temporary tables renamed to the versions it reads.
1406    pub fn final_statement(&self) -> Option<&Statement> {
1407        self.final_ref().map(|o| &o.node)
1408    }
1409
1410    /// The final statement's query.
1411    pub fn final_query(&self) -> Option<&Query> {
1412        self.final_ref().map(|o| &o.query)
1413    }
1414
1415    /// The table the final statement writes, if any.
1416    pub fn final_target(&self) -> Option<&TableName> {
1417        self.final_ref().and_then(|o| o.target.as_ref())
1418    }
1419
1420    /// `query` (the final one, with its own CTEs) with the temporary tables it reads defined in
1421    /// front of it as CTEs.
1422    pub fn with_temp_ctes(&self, mut query: Query) -> Query {
1423        if self.ctes.is_empty() {
1424            return query;
1425        }
1426        let ours: Vec<Cte> = self
1427            .ctes
1428            .iter()
1429            .map(|(alias, body)| Cte {
1430                name: Ident::new(alias.clone()),
1431                query: Box::new(body.clone()),
1432            })
1433            .collect();
1434        match &mut query.with {
1435            Some(with) => {
1436                let mut ctes = ours;
1437                ctes.append(&mut with.ctes);
1438                with.ctes = ctes;
1439            }
1440            None => {
1441                query.with = Some(With {
1442                    recursive: false,
1443                    ctes: ours,
1444                })
1445            }
1446        }
1447        query
1448    }
1449
1450    /// The final query with every single-definition temporary table it reads spliced in as a CTE.
1451    pub fn final_query_with_temps(&self) -> Option<Query> {
1452        self.final_query().map(|q| self.with_temp_ctes(q.clone()))
1453    }
1454
1455    /// Top-level statements by disposition.
1456    pub fn counts(&self) -> IndexMap<Disposition, usize> {
1457        let mut out: IndexMap<Disposition, usize> = [
1458            (Disposition::Kept, 0),
1459            (Disposition::Ignored, 0),
1460            (Disposition::Unknown, 0),
1461        ]
1462        .into_iter()
1463        .collect();
1464        for s in self.statements.iter().filter(|s| s.nested.is_empty()) {
1465            *out.entry(s.disposition).or_insert(0) += 1;
1466        }
1467        out
1468    }
1469
1470    /// Every unknown statement, nested ones included.
1471    pub fn unknown(&self) -> Vec<&AnalysedStatement> {
1472        self.statements
1473            .iter()
1474            .filter(|s| s.disposition == Disposition::Unknown)
1475            .collect()
1476    }
1477
1478    /// Statements that matter for lineage: kept or unknown, not definitions.
1479    pub fn considered(&self) -> usize {
1480        self.statements
1481            .iter()
1482            .filter(|s| {
1483                s.disposition != Disposition::Ignored && s.nested.is_empty() && !s.definition
1484            })
1485            .count()
1486    }
1487
1488    pub fn traced(&self) -> usize {
1489        self.statements
1490            .iter()
1491            .filter(|s| s.traced && s.nested.is_empty())
1492            .count()
1493    }
1494
1495    /// Kept statements whose columns are not part of the traced output.
1496    pub fn untraced_kept(&self) -> usize {
1497        self.statements
1498            .iter()
1499            .filter(|s| {
1500                s.disposition == Disposition::Kept
1501                    && !s.traced
1502                    && s.nested.is_empty()
1503                    && !s.definition
1504                    && !s.complete
1505            })
1506            .count()
1507    }
1508
1509    /// Kinds of statements that matter but whose columns are not traced.
1510    pub fn untraced_kinds(&self) -> std::collections::BTreeMap<String, usize> {
1511        let mut kinds = std::collections::BTreeMap::new();
1512        for s in &self.statements {
1513            if !s.nested.is_empty()
1514                || s.definition
1515                || s.traced
1516                || s.complete
1517                || s.disposition == Disposition::Ignored
1518            {
1519                continue;
1520            }
1521            *kinds.entry(s.kind.clone()).or_insert(0) += 1;
1522        }
1523        kinds
1524    }
1525
1526    /// Every table read, directly or through variables.
1527    pub fn all_reads(&self) -> Vec<TableName> {
1528        let mut merged = self.reads.clone();
1529        for (k, v) in &self.variable_reads {
1530            merged.insert(k.clone(), v.clone());
1531        }
1532        merged.into_values().collect()
1533    }
1534
1535    /// Counts and kinds only: no SQL text, names or paths.
1536    pub fn report(&self) -> serde_json::Value {
1537        use std::collections::BTreeMap;
1538        let mut by_kind: BTreeMap<&str, BTreeMap<String, usize>> = BTreeMap::new();
1539        let label = |d: Disposition| match d {
1540            Disposition::Kept => "kept",
1541            Disposition::Ignored => "ignored",
1542            Disposition::Unknown => "unknown",
1543        };
1544        for s in self.statements.iter().filter(|s| s.nested.is_empty()) {
1545            *by_kind
1546                .entry(label(s.disposition))
1547                .or_default()
1548                .entry(s.kind.clone())
1549                .or_insert(0) += 1;
1550        }
1551        for s in self.unknown().into_iter().filter(|s| !s.nested.is_empty()) {
1552            *by_kind
1553                .entry("unknown")
1554                .or_default()
1555                .entry(s.kind.clone())
1556                .or_insert(0) += 1;
1557        }
1558        let counts = self.counts();
1559        let mut out = serde_json::json!({
1560            "statements": counts.values().sum::<usize>(),
1561            "kept": counts[&Disposition::Kept],
1562            "ignored": counts[&Disposition::Ignored],
1563            "unknown": self.unknown().len(),
1564            "by_kind": by_kind,
1565            "conditional": self.statements.iter().filter(|s| s.conditional && s.disposition == Disposition::Kept).count(),
1566            "expanded": self.statements.iter().filter(|s| !s.nested.is_empty()).count(),
1567            "traced": self.traced(),
1568            "temporary_tables": self.temp_names.len(),
1569            "variable_dependencies": self.variable_reads.len(),
1570            "writes": self.writes.len(),
1571            "detail": self
1572                .statements
1573                .iter()
1574                .filter(|s| s.disposition != Disposition::Ignored || s.nested.is_empty())
1575                .take(200)
1576                .map(AnalysedStatement::to_json)
1577                .collect::<Vec<_>>(),
1578        });
1579        let map = out.as_object_mut().expect("object");
1580        if !self.opaque_temps.is_empty() {
1581            map.insert(
1582                "temporary_tables_untraced".into(),
1583                self.opaque_temps.len().into(),
1584            );
1585        }
1586        if !self.procedure_reports.is_empty() {
1587            map.insert("procedures".into(), self.procedure_reports.clone().into());
1588        }
1589        out
1590    }
1591
1592    /// A one-line description of what was kept, ignored and unknown, for a diagnostic.
1593    pub fn summary(&self) -> String {
1594        let c = self.counts();
1595        let mut parts = vec![
1596            format!("{} kept", c[&Disposition::Kept]),
1597            format!("{} ignored", c[&Disposition::Ignored]),
1598        ];
1599        let unknown = self.unknown();
1600        if unknown.is_empty() {
1601            parts.push("0 unknown".to_string());
1602        } else {
1603            let report = self.report();
1604            let detail = report["by_kind"]["unknown"]
1605                .as_object()
1606                .map(|m| {
1607                    m.iter()
1608                        .map(|(k, v)| format!("{k} x{v}"))
1609                        .collect::<Vec<_>>()
1610                        .join(", ")
1611                })
1612                .unwrap_or_default();
1613            let nested = unknown.iter().filter(|s| !s.nested.is_empty()).count();
1614            let nested_text = if nested > 0 {
1615                format!("; {nested} nested")
1616            } else {
1617                String::new()
1618            };
1619            parts.push(format!("{} unknown ({detail}{nested_text})", unknown.len()));
1620        }
1621        let mut extra = Vec::new();
1622        if !self.temp_names.is_empty() {
1623            extra.push(format!(
1624                "{} temporary table(s) followed",
1625                self.temp_names.len()
1626            ));
1627        }
1628        if !self.variable_reads.is_empty() {
1629            extra.push(format!(
1630                "{} table(s) read through variables or conditions",
1631                self.variable_reads.len()
1632            ));
1633        }
1634        if self
1635            .statements
1636            .iter()
1637            .any(|s| s.conditional && s.disposition == Disposition::Kept)
1638        {
1639            extra.push("statements in branches count as possible edges".to_string());
1640        }
1641        let total: usize = c.values().sum();
1642        let mut text = format!("script of {total} statements: {}", parts.join(", "));
1643        if !extra.is_empty() {
1644            text.push_str("; ");
1645            text.push_str(&extra.join("; "));
1646        }
1647        text
1648    }
1649}
1650
1651// ------------------------------------------------------------------------ definitions
1652
1653fn norm(name: &str) -> String {
1654    name.replace('`', "").to_lowercase()
1655}
1656
1657fn table_function_re() -> &'static Regex {
1658    static RE: OnceLock<Regex> = OnceLock::new();
1659    RE.get_or_init(|| {
1660        Regex::new(r"(?i)\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?TABLE\s+FUNCTION\b")
1661            .expect("valid regex")
1662    })
1663}
1664
1665fn table_function_of(statement: &CreateTableFunction) -> TableFunction {
1666    let params = statement
1667        .params
1668        .iter()
1669        .map(|p| match &p.param_type {
1670            ParamType::Table(fields) => (
1671                p.name.value.clone(),
1672                true,
1673                fields
1674                    .iter()
1675                    .filter_map(|f| f.name.as_ref().map(|n| n.value.clone()))
1676                    .collect(),
1677            ),
1678            ParamType::AnyTable => (p.name.value.clone(), true, Vec::new()),
1679            _ => (p.name.value.clone(), false, Vec::new()),
1680        })
1681        .collect();
1682    TableFunction {
1683        name: statement.name.dotted(),
1684        params,
1685        body: (*statement.query).clone(),
1686    }
1687}
1688
1689/// Table functions defined in `texts`, by lower-cased name and by bare name when unambiguous.
1690pub fn collect_table_functions<'t>(
1691    texts: impl IntoIterator<Item = &'t str>,
1692) -> IndexMap<String, TableFunction> {
1693    let mut found = IndexMap::new();
1694    let mut bare: IndexMap<String, Vec<TableFunction>> = IndexMap::new();
1695    for text in texts {
1696        if !table_function_re().is_match(text) {
1697            continue;
1698        }
1699        let tree = script_tree(text);
1700        let mut nodes = Vec::new();
1701        walk_nodes(&tree, &mut nodes);
1702        for node in nodes {
1703            if node.kind != NodeKind::Stmt || !table_function_re().is_match(&node.header) {
1704                continue;
1705            }
1706            if let Some(Statement::CreateTableFunction(def)) = parse_one(&node.header) {
1707                let function = table_function_of(&def);
1708                let key = norm(&function.name);
1709                let short = key.rsplit('.').next().unwrap_or(&key).to_string();
1710                bare.entry(short).or_default().push(function.clone());
1711                found.insert(key, function);
1712            }
1713        }
1714    }
1715    for (name, functions) in bare {
1716        if functions.len() == 1 && !found.contains_key(&name) {
1717            found.insert(name, functions.into_iter().next().expect("one"));
1718        }
1719    }
1720    found
1721}
1722
1723/// `(name, mode)` of each procedure parameter (`IN` by default, `OUT` or `INOUT`).
1724fn parameters(params: &str) -> Vec<(String, String)> {
1725    let mut inner = params.trim();
1726    if let Some(rest) = inner.strip_prefix('(') {
1727        inner = rest;
1728    }
1729    let mut found = Vec::new();
1730    let mut depth = 0i32;
1731    let mut expecting = true;
1732    let mut mode = "IN".to_string();
1733    for tok in lex(inner) {
1734        if tok.kind == TokKind::Punct && tok.text == "(" {
1735            depth += 1;
1736        } else if tok.kind == TokKind::Punct && tok.text == ")" {
1737            if depth == 0 {
1738                break;
1739            }
1740            depth -= 1;
1741        } else if tok.kind == TokKind::Punct && tok.text == "," && depth == 0 {
1742            expecting = true;
1743            mode = "IN".to_string();
1744        } else if expecting && depth == 0 && matches!(tok.kind, TokKind::Word | TokKind::Quoted) {
1745            if tok.kind == TokKind::Word && ["IN", "OUT", "INOUT"].contains(&tok.up().as_str()) {
1746                mode = tok.up();
1747                continue;
1748            }
1749            found.push((tok.text.trim_matches('`').to_string(), mode.clone()));
1750            expecting = false;
1751        }
1752    }
1753    found
1754}
1755
1756/// Procedures defined in `texts`, by lower-cased name and by bare name when unambiguous.
1757pub fn collect_procedures<'t>(
1758    texts: impl IntoIterator<Item = &'t str>,
1759) -> IndexMap<String, Procedure> {
1760    let mut found = IndexMap::new();
1761    let mut bare: IndexMap<String, Vec<Procedure>> = IndexMap::new();
1762    for text in texts {
1763        if !text.to_lowercase().contains("procedure") {
1764            continue;
1765        }
1766        let tree = script_tree(text);
1767        let mut nodes = Vec::new();
1768        walk_nodes(&tree, &mut nodes);
1769        for node in nodes {
1770            if node.kind == NodeKind::Procedure && !node.name.is_empty() {
1771                let params = parameters(&node.params);
1772                let procedure = Procedure {
1773                    name: node.name.clone(),
1774                    params: params.iter().map(|(n, _)| n.clone()).collect(),
1775                    modes: params.iter().map(|(_, m)| m.clone()).collect(),
1776                    body: node.branches.first().cloned().unwrap_or_default(),
1777                    text: text.to_string(),
1778                };
1779                let key = norm(&node.name);
1780                let short = key.rsplit('.').next().unwrap_or(&key).to_string();
1781                bare.entry(short).or_default().push(procedure.clone());
1782                found.insert(key, procedure);
1783            }
1784        }
1785    }
1786    for (name, procedures) in bare {
1787        if procedures.len() == 1 && !found.contains_key(&name) {
1788            found.insert(name, procedures.into_iter().next().expect("one"));
1789        }
1790    }
1791    found
1792}
1793
1794fn routine_name(statement: &str) -> String {
1795    static RE: OnceLock<Regex> = OnceLock::new();
1796    let re = RE.get_or_init(|| {
1797        Regex::new(r"(?i)\bFUNCTION\b\s*(?:IF\s+NOT\s+EXISTS\s+)?((?:`[^`]+`|[\w$]+)(?:\s*\.\s*(?:`[^`]+`|[\w$]+))*)\s*\(")
1798            .expect("valid regex")
1799    });
1800    re.captures(statement)
1801        .map(|c| {
1802            c[1].replace('`', "")
1803                .rsplit('.')
1804                .next()
1805                .unwrap_or("")
1806                .trim()
1807                .to_lowercase()
1808        })
1809        .unwrap_or_default()
1810}
1811
1812// ------------------------------------------------------------------------ tree helpers
1813
1814fn parse_one(sql: &str) -> Option<Statement> {
1815    let mut statements = parse_statements(sql).ok()?;
1816    if statements.len() != 1 {
1817        return None;
1818    }
1819    let statement = statements.remove(0);
1820    (!matches!(statement, Statement::Raw(_))).then_some(statement)
1821}
1822
1823fn parse_error_line(sql: &str) -> String {
1824    match parse_statements(sql) {
1825        Ok(statements) if statements.iter().any(|s| matches!(s, Statement::Raw(_))) => {
1826            "statement kept as text by the parser".to_string()
1827        }
1828        Ok(_) => String::new(),
1829        Err(e) => match e {
1830            crate::SqlError::Parse {
1831                message,
1832                line,
1833                column,
1834                ..
1835            }
1836            | crate::SqlError::Lex {
1837                message,
1838                line,
1839                column,
1840                ..
1841            } => {
1842                let first = message
1843                    .split(", found")
1844                    .next()
1845                    .unwrap_or(&message)
1846                    .to_string();
1847                let mut text = format!("{first}. Line {line}, Col: {column}.");
1848                text.truncate(160);
1849                text
1850            }
1851            other => other.message().chars().take(160).collect(),
1852        },
1853    }
1854}
1855
1856/// The query a statement reads from, without any `WITH` the statement itself carries.
1857fn query_of(statement: &Statement) -> Option<Query> {
1858    match statement {
1859        Statement::Query(q) => Some((**q).clone()),
1860        Statement::CreateTable(c) => c.query.as_deref().cloned(),
1861        Statement::CreateView(c) => Some((*c.query).clone()),
1862        Statement::Insert(i) => match &i.source {
1863            InsertSource::Query(q) => Some((**q).clone()),
1864            InsertSource::Values(_) => None,
1865        },
1866        _ => None,
1867    }
1868}
1869
1870fn table_key(table: &TableName) -> String {
1871    norm(&table.dotted())
1872}
1873
1874fn is_temp(table: &TableName) -> bool {
1875    table.is_temp_name()
1876}
1877
1878fn output_names(query: &Query) -> Option<Vec<String>> {
1879    query.output_names()
1880}
1881
1882/// `query` with its first SELECT's items renamed to `columns` (same count, no `*`).
1883fn alias_to(query: &Query, columns: &[String]) -> Option<Query> {
1884    let mut copy = query.clone();
1885    let head = copy.first_select_mut()?;
1886    if head.projection.len() != columns.len() || head.projection.iter().any(SelectItem::is_star) {
1887        return None;
1888    }
1889    for (item, name) in head.projection.iter_mut().zip(columns) {
1890        if let SelectItem::Expr { alias, .. } = item {
1891            *alias = Some(Ident::new(name.clone()));
1892        }
1893    }
1894    Some(copy)
1895}
1896
1897/// `query` named by position to fit `columns`, or `None` when its columns cannot be matched safely.
1898fn arm(query: &Query, columns: &[String], insert_columns: Option<&[String]>) -> Option<Query> {
1899    let Some(insert_columns) = insert_columns else {
1900        return alias_to(query, columns);
1901    };
1902    let SetExpr::Select(select) = &query.body else {
1903        return None;
1904    };
1905    if query.with.is_some() || !query.pipes.is_empty() {
1906        return None;
1907    }
1908    if select.projection.len() != insert_columns.len()
1909        || select.projection.iter().any(SelectItem::is_star)
1910    {
1911        return None;
1912    }
1913    let mut given: IndexMap<String, Expr> = IndexMap::new();
1914    for (name, item) in insert_columns.iter().zip(&select.projection) {
1915        if let SelectItem::Expr { expr, .. } = item {
1916            given.insert(name.to_lowercase(), expr.clone());
1917        }
1918    }
1919    let lowered: Vec<String> = columns.iter().map(|c| c.to_lowercase()).collect();
1920    if !given.keys().all(|k| lowered.contains(k)) {
1921        return None;
1922    }
1923    let mut copy = query.clone();
1924    let projection = columns
1925        .iter()
1926        .map(|c| SelectItem::Expr {
1927            expr: given
1928                .get(&c.to_lowercase())
1929                .cloned()
1930                .unwrap_or_else(Expr::null),
1931            alias: Some(Ident::new(c.clone())),
1932        })
1933        .collect();
1934    if let SetExpr::Select(select) = &mut copy.body {
1935        select.projection = projection;
1936    }
1937    Some(copy)
1938}
1939
1940/// A query as a set operation operand: a plain SELECT as itself, anything else in parentheses.
1941fn as_operand(query: Query) -> SetExpr {
1942    match query {
1943        Query {
1944            with: None,
1945            body: SetExpr::Select(select),
1946            order_by,
1947            limit: None,
1948            pipes,
1949        } if order_by.is_empty() && pipes.is_empty() => SetExpr::Select(select),
1950        other => SetExpr::Query(Box::new(other)),
1951    }
1952}
1953
1954fn union_all(queries: Vec<Query>, by_name: bool) -> Option<Query> {
1955    let mut iter = queries.into_iter();
1956    let first = iter.next()?;
1957    let mut rest = iter.peekable();
1958    if rest.peek().is_none() {
1959        return Some(first);
1960    }
1961    let mut body = as_operand(first);
1962    for next in rest {
1963        body = SetExpr::SetOperation {
1964            op: SetOperator::Union,
1965            quantifier: SetQuantifier::All,
1966            mode: None,
1967            corresponding: by_name.then(|| Corresponding::ByName(Vec::new())),
1968            left: Box::new(body),
1969            right: Box::new(as_operand(next)),
1970        };
1971    }
1972    Some(Query::from_body(body))
1973}
1974
1975/// The column a `SET` or `INSERT` writes: `t.v` and `v` are `v`, `t.a.b` is `a` (the struct column).
1976fn target_column(path: &[Ident], names: &HashSet<String>) -> Option<String> {
1977    let mut parts: Vec<&Ident> = path.iter().collect();
1978    if parts.len() > 1 && names.contains(&parts[0].value.to_lowercase()) {
1979        parts.remove(0);
1980    }
1981    parts.first().map(|p| p.value.clone())
1982}
1983
1984/// `expr` with its bare column names (outside any subquery) qualified by `alias`.
1985fn qualified_with(expr: &Expr, alias: &str) -> Expr {
1986    let mut copy = expr.clone();
1987    walk_expr_mut(&mut copy, false, &mut |e| {
1988        if let Expr::Identifier(ident) = e {
1989            *e = Expr::CompoundIdentifier(vec![Ident::new(alias), ident.clone()]);
1990        }
1991    });
1992    copy
1993}
1994
1995fn only_deletes(merge: &Merge) -> bool {
1996    !merge.clauses.is_empty()
1997        && merge
1998            .clauses
1999            .iter()
2000            .all(|c| c.action == MergeAction::Delete)
2001}
2002
2003enum ArmKind {
2004    Set(Vec<(String, Expr)>),
2005    Row,
2006    Delete,
2007}
2008
2009/// What flows into a MERGE target's columns, as a query lineage can trace; `None` when the MERGE
2010/// is not understood.
2011///
2012/// Each `WHEN` clause becomes one arm of a `UNION ALL` selecting the values it assigns (every
2013/// column it does not touch is `NULL`), from the `USING` source joined to the target on the `ON`
2014/// condition, filtered by the clause's own condition. `INSERT ROW` takes every column of the
2015/// source; a `DELETE` clause assigns nothing but still reads its condition.
2016pub fn merge_query(merge: &Merge) -> Option<Query> {
2017    let target_name = merge.target.table_name();
2018    let mut names: HashSet<String> = HashSet::new();
2019    if let Some(a) = &merge.target_alias {
2020        names.insert(a.value.to_lowercase());
2021    }
2022    names.insert(target_name.name.to_lowercase());
2023    let (using_alias, using_is_table) = match &merge.source {
2024        TableFactor::Table { name, alias, .. } => (
2025            alias
2026                .clone()
2027                .map(|a| a.value)
2028                .or_else(|| Some(name.base_name())),
2029            true,
2030        ),
2031        other => (other.alias().map(|a| a.value.clone()), false),
2032    };
2033    let referable = merge.source.alias().is_some() || using_is_table;
2034    let mut arms: Vec<(ArmKind, bool, bool, Option<Expr>)> = Vec::new();
2035    let mut columns: IndexMap<String, String> = IndexMap::new();
2036    for clause in &merge.clauses {
2037        let matched = clause.kind == MergeMatch::Matched;
2038        let by_source = clause.kind == MergeMatch::NotMatchedBySource;
2039        let condition = clause.condition.clone();
2040        match &clause.action {
2041            MergeAction::Update(assignments) => {
2042                let mut pairs = Vec::new();
2043                for a in assignments {
2044                    let column = target_column(&a.target, &names)?;
2045                    columns
2046                        .entry(column.to_lowercase())
2047                        .or_insert_with(|| column.clone());
2048                    pairs.push((column, a.value.clone()));
2049                }
2050                arms.push((ArmKind::Set(pairs), matched, by_source, condition));
2051            }
2052            MergeAction::Insert {
2053                columns: cols,
2054                values,
2055                row,
2056            } => {
2057                if *row && cols.is_empty() {
2058                    arms.push((ArmKind::Row, matched, by_source, condition));
2059                    continue;
2060                }
2061                if cols.is_empty() || *row || cols.len() != values.len() {
2062                    return None; // positions need the target's schema
2063                }
2064                let mut pairs = Vec::new();
2065                for (c, v) in cols.iter().zip(values) {
2066                    let column = target_column(std::slice::from_ref(c), &names)?;
2067                    columns
2068                        .entry(column.to_lowercase())
2069                        .or_insert_with(|| column.clone());
2070                    pairs.push((column, v.clone()));
2071                }
2072                arms.push((ArmKind::Set(pairs), matched, by_source, condition));
2073            }
2074            MergeAction::Delete => arms.push((ArmKind::Delete, matched, by_source, condition)),
2075        }
2076    }
2077    let has_row = arms.iter().any(|(k, ..)| matches!(k, ArmKind::Row));
2078    if columns.is_empty() && !has_row {
2079        return None; // only deletes: nothing is written
2080    }
2081    let ordered: Vec<String> = columns.values().cloned().collect();
2082    let source_name = using_alias.clone().unwrap_or_default();
2083    let target_factor = TableFactor::table(merge.target.clone(), merge.target_alias.clone());
2084    let mut selects = Vec::new();
2085    for (kind, matched, by_source, condition) in &arms {
2086        let sees_target = *matched || *by_source;
2087        let fix = |e: &Expr| -> Expr {
2088            if sees_target || source_name.is_empty() {
2089                e.clone()
2090            } else {
2091                qualified_with(e, &source_name)
2092            }
2093        };
2094        let projection: Vec<SelectItem> = match kind {
2095            ArmKind::Row => vec![star_of(&merge.source)],
2096            ArmKind::Delete if ordered.is_empty() => vec![star_of(&merge.source)],
2097            ArmKind::Set(pairs) if has_row => pairs
2098                .iter()
2099                .map(|(c, v)| SelectItem::expr(fix(v), Some(c)))
2100                .collect::<Vec<_>>()
2101                .into_iter()
2102                .chain(
2103                    pairs
2104                        .is_empty()
2105                        .then(|| SelectItem::expr(Expr::null(), Some(&ordered[0]))),
2106                )
2107                .collect(),
2108            ArmKind::Delete if has_row => vec![SelectItem::expr(Expr::null(), Some(&ordered[0]))],
2109            ArmKind::Set(pairs) => {
2110                let given: IndexMap<String, &Expr> =
2111                    pairs.iter().map(|(c, v)| (c.to_lowercase(), v)).collect();
2112                ordered
2113                    .iter()
2114                    .map(|c| {
2115                        SelectItem::expr(
2116                            given
2117                                .get(&c.to_lowercase())
2118                                .map_or_else(Expr::null, |v| fix(v)),
2119                            Some(c),
2120                        )
2121                    })
2122                    .collect()
2123            }
2124            ArmKind::Delete => ordered
2125                .iter()
2126                .map(|c| SelectItem::expr(Expr::null(), Some(c)))
2127                .collect(),
2128        };
2129        let mut select = Select::new(projection);
2130        if *by_source {
2131            select.from = vec![TableWithJoins {
2132                relation: target_factor.clone(),
2133                joins: vec![Join {
2134                    kind: JoinKind::Left,
2135                    natural: false,
2136                    relation: merge.source.clone(),
2137                    constraint: JoinConstraint::On(merge.on.clone()),
2138                }],
2139            }];
2140        } else if matches!(kind, ArmKind::Row) && !referable {
2141            select.from = vec![TableWithJoins {
2142                relation: merge.source.clone(),
2143                joins: Vec::new(),
2144            }];
2145        } else {
2146            select.from = vec![TableWithJoins {
2147                relation: merge.source.clone(),
2148                joins: vec![Join {
2149                    kind: if *matched {
2150                        JoinKind::Inner
2151                    } else {
2152                        JoinKind::Left
2153                    },
2154                    natural: false,
2155                    relation: target_factor.clone(),
2156                    constraint: JoinConstraint::On(merge.on.clone()),
2157                }],
2158            }];
2159        }
2160        if let Some(c) = condition {
2161            select.where_clause = Some(fix(c));
2162        }
2163        selects.push(Query::from_select(select));
2164    }
2165    let by_name = has_row && selects.len() > 1 && !ordered.is_empty();
2166    union_all(selects, by_name)
2167}
2168
2169fn star_of(source: &TableFactor) -> SelectItem {
2170    let qualifier = match source {
2171        TableFactor::Table { name, alias, .. } => Some(
2172            alias
2173                .clone()
2174                .unwrap_or_else(|| Ident::new(name.base_name())),
2175        ),
2176        other => other.alias().cloned(),
2177    };
2178    match qualifier {
2179        Some(q) => SelectItem::QualifiedWildcard {
2180            qualifier: Expr::Identifier(q),
2181            options: WildcardOptions::default(),
2182        },
2183        None => SelectItem::Wildcard(WildcardOptions::default()),
2184    }
2185}
2186
2187/// `INSERT INTO t (a, b) VALUES (...), (...)` as `SELECT ... AS a, ... AS b UNION ALL ...`;
2188/// `None` without a column list or with `DEFAULT`.
2189pub fn insert_values_query(insert: &Insert) -> Option<Query> {
2190    let InsertSource::Values(rows) = &insert.source else {
2191        return None;
2192    };
2193    if insert.columns.is_empty() {
2194        return None;
2195    }
2196    let mut selects = Vec::new();
2197    for row in rows {
2198        if row.len() != insert.columns.len() || row.iter().any(|e| matches!(e, Expr::Default)) {
2199            return None;
2200        }
2201        let projection = row
2202            .iter()
2203            .zip(&insert.columns)
2204            .map(|(e, c)| SelectItem::Expr {
2205                expr: e.clone(),
2206                alias: Some(c.clone()),
2207            })
2208            .collect();
2209        selects.push(Query::from_select(Select::new(projection)));
2210    }
2211    union_all(selects, false)
2212}
2213
2214/// The text a constant string expression stands for (literals joined by `||` or `CONCAT`).
2215fn literal_text(tokens: &[Tok]) -> Option<String> {
2216    struct P<'t> {
2217        tokens: &'t [Tok],
2218        pos: usize,
2219    }
2220    impl P<'_> {
2221        fn expression(&mut self) -> Option<String> {
2222            let mut value = self.term()?;
2223            while self.pos + 1 < self.tokens.len()
2224                && self.tokens[self.pos].text == "|"
2225                && self.tokens[self.pos + 1].text == "|"
2226            {
2227                self.pos += 2;
2228                value.push_str(&self.term()?);
2229            }
2230            Some(value)
2231        }
2232        fn term(&mut self) -> Option<String> {
2233            let t = self.tokens.get(self.pos)?;
2234            if t.kind == TokKind::String {
2235                self.pos += 1;
2236                return string_value(&t.text);
2237            }
2238            if t.kind == TokKind::Punct && t.text == "(" {
2239                self.pos += 1;
2240                let value = self.expression()?;
2241                if self.tokens.get(self.pos)?.text != ")" {
2242                    return None;
2243                }
2244                self.pos += 1;
2245                return Some(value);
2246            }
2247            if t.up() == "CONCAT" && self.tokens.get(self.pos + 1).is_some_and(|n| n.text == "(") {
2248                self.pos += 2;
2249                let mut parts = String::new();
2250                loop {
2251                    parts.push_str(&self.expression()?);
2252                    if self.tokens.get(self.pos).is_some_and(|t| t.text == ",") {
2253                        self.pos += 1;
2254                        continue;
2255                    }
2256                    break;
2257                }
2258                if self.tokens.get(self.pos)?.text != ")" {
2259                    return None;
2260                }
2261                self.pos += 1;
2262                return Some(parts);
2263            }
2264            None
2265        }
2266    }
2267    let mut p = P { tokens, pos: 0 };
2268    let value = p.expression()?;
2269    (p.pos == tokens.len()).then_some(value)
2270}
2271
2272fn split_arguments(text: &str) -> Vec<String> {
2273    let toks = lex(text);
2274    let mut args = Vec::new();
2275    let mut depth = 0i32;
2276    let mut start = 0;
2277    for t in &toks {
2278        if t.kind == TokKind::Punct && "([{".contains(t.text.as_str()) {
2279            depth += 1;
2280        } else if t.kind == TokKind::Punct && ")]}".contains(t.text.as_str()) {
2281            depth -= 1;
2282        } else if t.kind == TokKind::Punct && t.text == "," && depth == 0 {
2283            args.push(text[start..t.start].trim().to_string());
2284            start = t.end;
2285        }
2286    }
2287    if !toks.is_empty() {
2288        args.push(text[start..].trim().to_string());
2289    }
2290    args
2291}
2292
2293// ------------------------------------------------------------------------ the run
2294
2295#[derive(Debug, Clone)]
2296struct Temp {
2297    name: String,
2298    alias: String,
2299    sources: Tables,
2300    query: Option<Query>,
2301    columns: Option<Vec<String>>,
2302    deps: Vec<usize>,
2303    opaque_reason: String,
2304    sequence: usize,
2305    statements: Vec<usize>,
2306    empty: bool,
2307}
2308
2309#[derive(Debug, Clone, Default, PartialEq)]
2310struct Variable {
2311    sources: Tables,
2312}
2313
2314/// What a `CREATE TABLE`/`VIEW` names: target, kind, temporary, declared columns, copied table.
2315type CreateParts = (
2316    TableName,
2317    &'static str,
2318    bool,
2319    Vec<String>,
2320    Option<TableCopy>,
2321);
2322
2323type TempSnapshot = (
2324    IndexMap<String, usize>,
2325    IndexMap<usize, (Tables, Vec<usize>)>,
2326);
2327
2328struct SavedState {
2329    analysis: ScriptAnalysis,
2330    temps: TempSnapshot,
2331    versions: IndexMap<String, usize>,
2332    sequence: usize,
2333    function_reads: IndexMap<String, Tables>,
2334    transactions: Vec<TempSnapshot>,
2335    defaults: (String, String),
2336}
2337
2338struct Run {
2339    a: ScriptAnalysis,
2340    external: IndexMap<String, Procedure>,
2341    functions: IndexMap<String, TableFunction>,
2342    function_reads: IndexMap<String, Tables>,
2343    arena: Vec<Temp>,
2344    temps: IndexMap<String, usize>,
2345    versions: IndexMap<String, usize>,
2346    variables: IndexMap<String, Variable>,
2347    sequence: usize,
2348    used_names: HashSet<String>,
2349    call_stack: Vec<String>,
2350    breaks: Vec<usize>,
2351    nested: String,
2352    anchor_line: usize,
2353    depth: usize,
2354    control: Vec<Tables>,
2355    scopes: Vec<IndexMap<String, Option<Variable>>>,
2356    transactions: Vec<TempSnapshot>,
2357    parameters: Option<IndexMap<String, Tables>>,
2358    default_dataset: String,
2359    default_project: String,
2360    loops: usize,
2361    tvf_counter: usize,
2362}
2363
2364fn word_re() -> &'static Regex {
2365    static RE: OnceLock<Regex> = OnceLock::new();
2366    RE.get_or_init(|| Regex::new(r"\b[A-Za-z_]\w*\b").expect("valid regex"))
2367}
2368
2369impl Run {
2370    fn new(
2371        analysis: ScriptAnalysis,
2372        external: IndexMap<String, Procedure>,
2373        functions: IndexMap<String, TableFunction>,
2374    ) -> Self {
2375        Run {
2376            a: analysis,
2377            external,
2378            functions,
2379            function_reads: IndexMap::new(),
2380            arena: Vec::new(),
2381            temps: IndexMap::new(),
2382            versions: IndexMap::new(),
2383            variables: IndexMap::new(),
2384            sequence: 0,
2385            used_names: HashSet::new(),
2386            call_stack: Vec::new(),
2387            breaks: Vec::new(),
2388            nested: String::new(),
2389            anchor_line: 0,
2390            depth: 0,
2391            control: Vec::new(),
2392            scopes: vec![IndexMap::new()],
2393            transactions: Vec::new(),
2394            parameters: None,
2395            default_dataset: String::new(),
2396            default_project: String::new(),
2397            loops: 0,
2398            tvf_counter: 0,
2399        }
2400    }
2401
2402    fn run(&mut self, text: &str) {
2403        self.a.procedures = IndexMap::new();
2404        let nodes = if !text.contains(';') {
2405            // one statement, the common case
2406            if block_start_re().is_match(text) {
2407                script_tree(text)
2408            } else if text.trim().is_empty() {
2409                Vec::new()
2410            } else {
2411                let mut node = ScriptNode::new(NodeKind::Stmt, 0);
2412                node.end = text.len();
2413                node.header = text.trim().to_string();
2414                vec![node]
2415            }
2416        } else {
2417            let nodes = script_tree(text);
2418            for (_, procedure) in collect_procedures([text]) {
2419                self.a.procedures.insert(norm(&procedure.name), procedure);
2420            }
2421            if table_function_re().is_match(text) {
2422                let mut merged = collect_table_functions([text]);
2423                for (k, v) in std::mem::take(&mut self.functions) {
2424                    merged.insert(k, v);
2425                }
2426                self.functions = merged;
2427            }
2428            nodes
2429        };
2430        self.breaks = line_index(text);
2431        if text.contains(';') {
2432            self.used_names = word_re()
2433                .find_iter(text)
2434                .map(|m| m.as_str().to_lowercase())
2435                .collect();
2436        }
2437        self.nodes(&nodes, text, false, true);
2438        self.choose_final();
2439    }
2440
2441    /// The line of `offset` in the text being read now (the script, a procedure body or the text
2442    /// of an `EXECUTE IMMEDIATE`).
2443    fn line_of(&self, _text: &str, offset: usize) -> usize {
2444        line_at(&self.breaks, offset)
2445    }
2446
2447    fn nodes(&mut self, nodes: &[ScriptNode], text: &str, conditional: bool, top_level: bool) {
2448        for node in nodes {
2449            self.node(node, text, conditional, top_level);
2450        }
2451    }
2452
2453    fn node(&mut self, node: &ScriptNode, text: &str, conditional: bool, top_level: bool) {
2454        let line = self.line_of(text, node.start);
2455        if node.kind == NodeKind::Stmt {
2456            self.statement(&node.header, line, conditional, top_level);
2457            return;
2458        }
2459        if node.kind == NodeKind::Procedure {
2460            let index = self.a.statements.len();
2461            self.record(AnalysedStatement::new(
2462                index,
2463                line,
2464                "create_procedure",
2465                Disposition::Kept,
2466                "definition; read when called",
2467                conditional,
2468            ));
2469            self.describe_procedure(node, text);
2470            return;
2471        }
2472        let looping = matches!(
2473            node.kind,
2474            NodeKind::While | NodeKind::Loop | NodeKind::For | NodeKind::Repeat
2475        );
2476        let kind = match node.kind {
2477            NodeKind::Begin => "block",
2478            NodeKind::If => "if",
2479            NodeKind::While => "while",
2480            NodeKind::Loop => "loop",
2481            NodeKind::For => "for",
2482            NodeKind::Repeat => "repeat",
2483            NodeKind::Case => "case",
2484            _ => "block",
2485        };
2486        let index = self.a.statements.len();
2487        let statement = self.record(AnalysedStatement::new(
2488            index,
2489            line,
2490            kind,
2491            Disposition::Ignored,
2492            "control flow",
2493            conditional,
2494        ));
2495        if looping {
2496            self.settle_loop(node, text, statement);
2497        }
2498        self.control_flow(node, text, conditional, top_level, Some(statement));
2499    }
2500
2501    fn control_flow(
2502        &mut self,
2503        node: &ScriptNode,
2504        text: &str,
2505        conditional: bool,
2506        top_level: bool,
2507        statement: Option<usize>,
2508    ) {
2509        let looping = matches!(
2510            node.kind,
2511            NodeKind::While | NodeKind::Loop | NodeKind::For | NodeKind::Repeat
2512        );
2513        let line = self.line_of(text, node.start);
2514        let mut guard = Tables::new();
2515        for condition in &node.conditions {
2516            let (sources, ok) = self.value_sources(condition);
2517            if !ok {
2518                if let Some(s) = statement {
2519                    self.set_unknown(s, "condition could not be read");
2520                }
2521            }
2522            guard.extend(sources);
2523        }
2524        let mut hidden: IndexMap<String, Option<Variable>> = IndexMap::new();
2525        if node.kind == NodeKind::For {
2526            let key = node.name.to_lowercase();
2527            hidden.insert(key.clone(), self.variables.get(&key).cloned());
2528            guard.extend(self.bind_loop_variable(node, line));
2529        }
2530        self.note_reads(&guard);
2531        self.control.push(guard);
2532        self.scopes.push(hidden);
2533        for (index, branch) in node.branches.iter().enumerate() {
2534            let gated = conditional
2535                || matches!(node.kind, NodeKind::If | NodeKind::Case)
2536                || looping
2537                || index > 0;
2538            self.nodes(branch, text, gated, top_level);
2539        }
2540        self.control.pop();
2541        let hidden = self.scopes.pop().unwrap_or_default();
2542        self.close_scope(hidden);
2543    }
2544
2545    fn set_unknown(&mut self, statement: usize, reason: &str) {
2546        if let Some(s) = self.a.statements.get_mut(statement) {
2547            s.disposition = Disposition::Unknown;
2548            s.reason = reason.to_string();
2549        }
2550    }
2551
2552    fn close_scope(&mut self, hidden: IndexMap<String, Option<Variable>>) {
2553        for (name, previous) in hidden {
2554            match previous {
2555                None => {
2556                    self.variables.shift_remove(&name);
2557                }
2558                Some(v) => {
2559                    self.variables.insert(name, v);
2560                }
2561            }
2562        }
2563    }
2564
2565    fn note_reads(&mut self, sources: &Tables) {
2566        for (key, table) in sources {
2567            if !self.a.reads.contains_key(key) {
2568                self.a
2569                    .variable_reads
2570                    .entry(key.clone())
2571                    .or_insert_with(|| table.clone());
2572            }
2573            self.a
2574                .side_reads
2575                .entry(key.clone())
2576                .or_insert_with(|| table.clone());
2577        }
2578    }
2579
2580    fn guarded(&self) -> Tables {
2581        let mut found = Tables::new();
2582        for guard in &self.control {
2583            found.extend(guard.iter().map(|(k, v)| (k.clone(), v.clone())));
2584        }
2585        found
2586    }
2587
2588    // -- loops
2589
2590    fn settle_loop(&mut self, node: &ScriptNode, text: &str, statement: usize) {
2591        if self.loops >= MAX_LOOP_NESTING {
2592            self.set_unknown(statement, "loops nested too deeply to follow");
2593            return;
2594        }
2595        for _ in 0..MAX_LOOP_PASSES {
2596            let before = self.variable_state();
2597            let saved = self.save_state();
2598            self.loops += 1;
2599            self.control_flow(node, text, true, false, None);
2600            self.loops -= 1;
2601            self.restore_state(saved);
2602            if self.variable_state() == before {
2603                return;
2604            }
2605        }
2606        self.set_unknown(statement, "loop variables did not settle");
2607    }
2608
2609    fn variable_state(&self) -> IndexMap<String, Vec<String>> {
2610        self.variables
2611            .iter()
2612            .map(|(name, var)| {
2613                let mut keys: Vec<String> = var.sources.keys().cloned().collect();
2614                keys.sort();
2615                (name.clone(), keys)
2616            })
2617            .collect()
2618    }
2619
2620    fn save_state(&mut self) -> SavedState {
2621        let mut scratch = ScriptAnalysis::new(&self.a.text);
2622        scratch.procedures = self.a.procedures.clone();
2623        let analysis = std::mem::replace(&mut self.a, scratch);
2624        SavedState {
2625            analysis,
2626            temps: self.temp_snapshot(),
2627            versions: self.versions.clone(),
2628            sequence: self.sequence,
2629            function_reads: self.function_reads.clone(),
2630            transactions: self.transactions.clone(),
2631            defaults: (self.default_dataset.clone(), self.default_project.clone()),
2632        }
2633    }
2634
2635    fn restore_state(&mut self, saved: SavedState) {
2636        self.a = saved.analysis;
2637        self.restore_temps(saved.temps);
2638        self.versions = saved.versions;
2639        self.sequence = saved.sequence;
2640        self.function_reads = saved.function_reads;
2641        self.transactions = saved.transactions;
2642        (self.default_dataset, self.default_project) = saved.defaults;
2643    }
2644
2645    fn temp_snapshot(&self) -> TempSnapshot {
2646        let inside = self
2647            .temps
2648            .values()
2649            .map(|&id| {
2650                (
2651                    id,
2652                    (
2653                        self.arena[id].sources.clone(),
2654                        self.arena[id].statements.clone(),
2655                    ),
2656                )
2657            })
2658            .collect();
2659        (self.temps.clone(), inside)
2660    }
2661
2662    fn restore_temps(&mut self, snapshot: TempSnapshot) {
2663        let (temps, inside) = snapshot;
2664        for (id, (sources, statements)) in inside {
2665            self.arena[id].sources = sources;
2666            self.arena[id].statements = statements;
2667        }
2668        self.temps = temps;
2669    }
2670
2671    fn record(&mut self, mut statement: AnalysedStatement) -> usize {
2672        if !self.nested.is_empty() {
2673            statement.nested = self.nested.clone();
2674            if self.anchor_line > 0 {
2675                statement.line = self.anchor_line;
2676            }
2677        }
2678        statement.index = self.a.statements.len();
2679        self.a.statements.push(statement);
2680        self.a.statements.len() - 1
2681    }
2682
2683    fn stmt(&mut self, index: usize) -> &mut AnalysedStatement {
2684        &mut self.a.statements[index]
2685    }
2686
2687    // -- procedures
2688
2689    fn describe_procedure(&mut self, node: &ScriptNode, text: &str) {
2690        let mut runner = Run::new(
2691            ScriptAnalysis::new(text),
2692            self.external.clone(),
2693            IndexMap::new(),
2694        );
2695        runner.breaks = line_index(text);
2696        runner.used_names = self.used_names.clone();
2697        for (name, _) in parameters(&node.params) {
2698            runner
2699                .variables
2700                .insert(name.to_lowercase(), Variable::default());
2701        }
2702        if let Some(body) = node.branches.first() {
2703            runner.nodes(body, text, false, false);
2704        }
2705        let sub = runner.a;
2706        self.a.procedure_reports.push(serde_json::json!({
2707            "line": self.line_of(text, node.start),
2708            "statements": sub.statements.len(),
2709            "reads": sub.reads.len(),
2710            "writes": sub.writes.len(),
2711            "unknown": sub.unknown().len(),
2712        }));
2713    }
2714
2715    fn known_procedure(&self, name: &str) -> Option<Procedure> {
2716        let key = norm(name);
2717        for registry in [&self.a.procedures, &self.external] {
2718            if let Some(p) = registry.get(&key) {
2719                return Some(p.clone());
2720            }
2721            let bare = key.rsplit('.').next().unwrap_or(&key).to_string();
2722            let mut hits: Vec<&Procedure> = Vec::new();
2723            for (k, p) in registry {
2724                if (*k == bare || k.ends_with(&format!(".{bare}")))
2725                    && !hits.iter().any(|h| norm(&h.name) == norm(&p.name))
2726                {
2727                    hits.push(p);
2728                }
2729            }
2730            if hits.len() == 1 {
2731                return Some(hits[0].clone());
2732            }
2733        }
2734        None
2735    }
2736
2737    // -- variables
2738
2739    fn bind_loop_variable(&mut self, node: &ScriptNode, line: usize) -> Tables {
2740        let (sources, ok) = self.value_sources(&node.query);
2741        self.variables.insert(
2742            node.name.to_lowercase(),
2743            Variable {
2744                sources: sources.clone(),
2745            },
2746        );
2747        if !ok {
2748            let index = self.a.statements.len();
2749            self.record(AnalysedStatement::new(
2750                index,
2751                line,
2752                "for_query",
2753                Disposition::Unknown,
2754                "loop query could not be read",
2755                false,
2756            ));
2757        }
2758        sources
2759    }
2760
2761    fn value_sources(&mut self, expression: &str) -> (Tables, bool) {
2762        let (mut sources, ok) = self.sources_of_text(expression);
2763        for (key, table) in self.variable_sources_of_text(expression) {
2764            sources.entry(key).or_insert(table);
2765        }
2766        (sources, ok)
2767    }
2768
2769    fn sources_of_text(&mut self, expression: &str) -> (Tables, bool) {
2770        static QUERY: OnceLock<Regex> = OnceLock::new();
2771        static FROM_JOIN: OnceLock<Regex> = OnceLock::new();
2772        let query =
2773            QUERY.get_or_init(|| Regex::new(r"(?i)^\s*(SELECT|WITH|\()").expect("valid regex"));
2774        let from_join =
2775            FROM_JOIN.get_or_init(|| Regex::new(r"(?i)\b(from|join)\b").expect("valid regex"));
2776        // a parenthesized subquery compared with something is an expression, not a statement
2777        let tree = if query.is_match(expression) {
2778            parse_one(expression).or_else(|| parse_one(&format!("SELECT {expression}")))
2779        } else {
2780            parse_one(&format!("SELECT {expression}"))
2781        };
2782        match tree {
2783            None => (Tables::new(), !from_join.is_match(expression)),
2784            Some(tree) => (self.reads_of(&tree).0, true),
2785        }
2786    }
2787
2788    fn variable_sources_of_text(&self, expression: &str) -> Vec<(String, TableName)> {
2789        static QUERY: OnceLock<Regex> = OnceLock::new();
2790        let query =
2791            QUERY.get_or_init(|| Regex::new(r"(?i)^\s*(SELECT|WITH)\b").expect("valid regex"));
2792        let tree = if query.is_match(expression) {
2793            parse_one(expression)
2794        } else {
2795            parse_one(&format!("SELECT {expression}"))
2796        };
2797        match tree {
2798            Some(tree) => self.variable_sources(&tree).into_iter().collect(),
2799            None => Vec::new(),
2800        }
2801    }
2802
2803    fn declare_variables(&mut self, names: &[String], sources: &Tables) {
2804        let guarded = self.guarded();
2805        for name in names {
2806            let key = name.to_lowercase();
2807            let previous = self.variables.get(&key).cloned();
2808            let scope = self.scopes.last_mut().expect("scope");
2809            scope.entry(key.clone()).or_insert(previous);
2810            let mut merged = sources.clone();
2811            merged.extend(guarded.clone());
2812            self.variables.insert(key, Variable { sources: merged });
2813        }
2814    }
2815
2816    fn assign(&mut self, name: &str, sources: &Tables, conditional: bool) {
2817        let key = name.to_lowercase();
2818        let mut merged = sources.clone();
2819        merged.extend(self.guarded());
2820        match self.variables.get(&key) {
2821            Some(existing) if conditional => {
2822                let mut both = existing.sources.clone();
2823                both.extend(merged);
2824                self.variables.insert(key, Variable { sources: both });
2825            }
2826            _ => {
2827                self.variables.insert(key, Variable { sources: merged });
2828            }
2829        }
2830    }
2831
2832    fn variable_sources(&self, tree: &Statement) -> Tables {
2833        let mut found = Tables::new();
2834        let mut names: Vec<String> = Vec::new();
2835        let mut params: Vec<Option<String>> = Vec::new();
2836        tree.walk_exprs(|e| match e {
2837            Expr::Identifier(ident) => names.push(ident.value.to_lowercase()),
2838            Expr::CompoundIdentifier(parts) => {
2839                if let Some(first) = parts.first() {
2840                    names.push(first.value.to_lowercase());
2841                }
2842            }
2843            Expr::Parameter(Parameter::Named(name)) => params.push(Some(name.to_lowercase())),
2844            Expr::Parameter(Parameter::Positional) => params.push(None),
2845            _ => {}
2846        });
2847        if let Some(parameters) = &self.parameters {
2848            for p in params {
2849                let hit = p
2850                    .as_ref()
2851                    .and_then(|name| parameters.get(name))
2852                    .or_else(|| parameters.get(""));
2853                if let Some(sources) = hit {
2854                    found.extend(sources.clone());
2855                }
2856            }
2857        }
2858        if self.variables.is_empty() {
2859            return found;
2860        }
2861        for name in names {
2862            if let Some(var) = self.variables.get(&name) {
2863                found.extend(var.sources.clone());
2864            }
2865        }
2866        found
2867    }
2868
2869    // -- reading tables out of a tree
2870
2871    /// `(real tables, temporary table versions read directly, unqualified names no temp has yet)`.
2872    fn reads_of(&self, tree: &Statement) -> (Tables, Vec<usize>, Vec<String>) {
2873        let mut real = Tables::new();
2874        let mut temps: Vec<usize> = Vec::new();
2875        let mut late = Vec::new();
2876        let mut copy = tree.clone();
2877        copy.visit_tables_mut(&mut |factor, is_cte| {
2878            if is_cte {
2879                return;
2880            }
2881            let TableFactor::Table { name, .. } = factor else {
2882                return;
2883            };
2884            let table = name.table_name();
2885            if table.name.is_empty() {
2886                return;
2887            }
2888            let lower = table.name.to_lowercase();
2889            if is_temp(&table) {
2890                if let Some(&id) = self.temps.get(&lower) {
2891                    if !temps.contains(&id) {
2892                        temps.push(id);
2893                    }
2894                    real.extend(self.arena[id].sources.clone());
2895                    return;
2896                }
2897                if table.dataset.is_none() {
2898                    late.push(lower);
2899                }
2900            }
2901            real.insert(table_key(&table), table);
2902        });
2903        if !self.function_reads.is_empty() {
2904            tree.walk_exprs(|e| {
2905                if let Expr::Function(f) = e {
2906                    let name = f.name.base_name().to_lowercase();
2907                    if let Some(reads) = self.function_reads.get(&name) {
2908                        real.extend(reads.clone());
2909                    }
2910                }
2911            });
2912        }
2913        (real, temps, late)
2914    }
2915
2916    // -- statements
2917
2918    fn statement(&mut self, text: &str, line: usize, conditional: bool, top_level: bool) {
2919        let words = first_words(text, 8);
2920        let first = words.first().cloned().unwrap_or_default();
2921        let index = self.a.statements.len();
2922        let done = |kind: &str, d: Disposition, reason: &str| {
2923            AnalysedStatement::new(index, line, kind, d, reason, conditional)
2924        };
2925        match first.as_str() {
2926            "SELECT" | "WITH" | "FROM" | "TABLE" | "(" => {
2927                self.query_statement(text, line, conditional, top_level);
2928            }
2929            "CREATE" => self.create_statement(text, line, &words, conditional, top_level),
2930            "INSERT" => self.dml_statement(text, line, "insert", conditional),
2931            "MERGE" => self.dml_statement(text, line, "merge", conditional),
2932            "UPDATE" => self.dml_statement(text, line, "update", conditional),
2933            "DELETE" => self.dml_statement(text, line, "delete", conditional),
2934            "TRUNCATE" => self.ddl_statement(text, line, "truncate", conditional),
2935            "ALTER" | "DROP" => self.ddl_statement(text, line, &first.to_lowercase(), conditional),
2936            "GRANT" | "REVOKE" | "UNDROP" | "COMMENT" => {
2937                self.record(done(
2938                    &first.to_lowercase(),
2939                    Disposition::Ignored,
2940                    "definition change, no data flow",
2941                ));
2942            }
2943            "DECLARE" => self.declare_statement(text, line, conditional),
2944            "SET" => self.set_statement(text, line, conditional),
2945            "ASSERT" => {
2946                self.record(done(
2947                    "assert",
2948                    Disposition::Ignored,
2949                    "a check, not data flow",
2950                ));
2951            }
2952            "LOAD" => {
2953                self.record(done("load_data", Disposition::Ignored, "loads files"));
2954            }
2955            "EXPORT" => self.export_statement(text, line, conditional),
2956            "BEGIN" | "COMMIT" | "ROLLBACK" | "START" => {
2957                self.transaction(&first, conditional);
2958                self.record(done(
2959                    "transaction",
2960                    Disposition::Ignored,
2961                    "transaction control",
2962                ));
2963            }
2964            "RAISE" | "RETURN" | "BREAK" | "LEAVE" | "CONTINUE" | "ITERATE" => {
2965                self.record(done("flow", Disposition::Ignored, "control flow"));
2966            }
2967            "CALL" => self.call_statement(text, line, conditional),
2968            "EXECUTE" => self.execute_statement(text, line, conditional),
2969            _ => {
2970                let s = self.record(done(
2971                    "other",
2972                    Disposition::Unknown,
2973                    "statement not recognised",
2974                ));
2975                self.degrade(s, text);
2976            }
2977        }
2978    }
2979
2980    fn transaction(&mut self, first: &str, conditional: bool) {
2981        if first == "BEGIN" || first == "START" {
2982            let snapshot = self.temp_snapshot();
2983            self.transactions.push(snapshot);
2984            return;
2985        }
2986        let Some(snapshot) = self.transactions.pop() else {
2987            return;
2988        };
2989        if first != "ROLLBACK" || conditional {
2990            return; // committed, or rolled back on a path that may not run
2991        }
2992        let kept: HashSet<usize> = snapshot
2993            .1
2994            .values()
2995            .flat_map(|(_, statements)| statements.iter().copied())
2996            .collect();
2997        let current: Vec<usize> = self.temps.values().copied().collect();
2998        for id in current {
2999            for &s in &self.arena[id].statements.clone() {
3000                if !kept.contains(&s) {
3001                    if let Some(st) = self.a.statements.get_mut(s) {
3002                        st.complete = true; // undone: nothing it wrote is left to trace
3003                    }
3004                }
3005            }
3006        }
3007        self.restore_temps(snapshot);
3008    }
3009
3010    fn ddl_statement(&mut self, text: &str, line: usize, kind: &str, conditional: bool) {
3011        let index = self.a.statements.len();
3012        let tree = self.parse(text);
3013        let valid = matches!(
3014            (&tree, kind),
3015            (Some(Statement::AlterTable(_)), "alter")
3016                | (Some(Statement::Drop(_)), "drop")
3017                | (Some(Statement::Truncate { .. }), "truncate")
3018        );
3019        if !valid {
3020            // `ALTER SCHEMA`, `DROP ROW ACCESS POLICY`: kept as text by the parser, not about table data
3021            let words = first_words(text, 3);
3022            let object = words.get(1).cloned().unwrap_or_default();
3023            let object = if ["MATERIALIZED", "EXTERNAL", "SNAPSHOT"].contains(&object.as_str()) {
3024                words.get(2).cloned().unwrap_or_default()
3025            } else {
3026                object
3027            };
3028            if kind != "truncate" && !object.is_empty() && object != "TABLE" && object != "VIEW" {
3029                self.record(AnalysedStatement::new(
3030                    index,
3031                    line,
3032                    kind,
3033                    Disposition::Ignored,
3034                    "definition change outside tables",
3035                    conditional,
3036                ));
3037                return;
3038            }
3039            self.record(AnalysedStatement::new(
3040                index,
3041                line,
3042                kind,
3043                Disposition::Unknown,
3044                "could not be parsed",
3045                conditional,
3046            ));
3047            return;
3048        }
3049        let tree = tree.expect("valid");
3050        let (targets, rename): (Vec<TableName>, Option<TableName>) = match &tree {
3051            Statement::Truncate { name } => (vec![name.table_name()], None),
3052            Statement::Drop(d) => {
3053                if !d.object_type.is_relation() {
3054                    self.record(AnalysedStatement::new(
3055                        index,
3056                        line,
3057                        kind,
3058                        Disposition::Ignored,
3059                        "definition change outside tables",
3060                        conditional,
3061                    ));
3062                    return;
3063                }
3064                (vec![d.name.table_name()], None)
3065            }
3066            Statement::AlterTable(a) => {
3067                let rename = a.actions.iter().find_map(|action| match action {
3068                    AlterAction::RenameTo(to) => Some(to.table_name()),
3069                    _ => None,
3070                });
3071                (vec![a.name.table_name()], rename)
3072            }
3073            _ => unreachable!("checked above"),
3074        };
3075        if targets.iter().any(|t| t.name.is_empty()) {
3076            self.record(AnalysedStatement::new(
3077                index,
3078                line,
3079                kind,
3080                Disposition::Unknown,
3081                "target could not be read",
3082                conditional,
3083            ));
3084            return;
3085        }
3086        let s = self.record(AnalysedStatement::new(
3087            index,
3088            line,
3089            kind,
3090            Disposition::Kept,
3091            "table definition or rows changed",
3092            conditional,
3093        ));
3094        self.stmt(s).complete = true; // no output column values are assigned
3095        for target in targets {
3096            let lower = target.name.to_lowercase();
3097            if is_temp(&target) && self.temps.contains_key(&lower) {
3098                if kind == "drop" && !conditional {
3099                    self.temps.shift_remove(&lower);
3100                }
3101                continue;
3102            }
3103            let mut sources = Tables::new();
3104            let mut destination = target.clone();
3105            if let Some(to) = &rename {
3106                sources.insert(table_key(&target), target.clone());
3107                for (k, v) in &sources {
3108                    self.a.reads.insert(k.clone(), v.clone());
3109                    self.stmt(s).reads.insert(k.clone(), v.clone());
3110                }
3111                destination = to.clone();
3112                if destination.dataset.is_none() {
3113                    destination.dataset = target.dataset.clone();
3114                }
3115                if destination.project.is_none() {
3116                    destination.project = target.project.clone();
3117                }
3118            }
3119            self.write(&destination, &sources, kind, conditional);
3120        }
3121    }
3122
3123    /// The statement as a tree, with defaults qualified and table functions expanded.
3124    fn parse(&mut self, text: &str) -> Option<Statement> {
3125        let mut tree = parse_one(text)?;
3126        if !self.default_dataset.is_empty() || !self.default_project.is_empty() {
3127            self.qualify_defaults(&mut tree, text);
3128        }
3129        if !self.functions.is_empty() {
3130            self.expand_functions(&mut tree);
3131        }
3132        Some(tree)
3133    }
3134
3135    fn qualify_defaults(&self, tree: &mut Statement, text: &str) {
3136        static TEMP: OnceLock<Regex> = OnceLock::new();
3137        let temp_re = TEMP.get_or_init(|| {
3138            Regex::new(r"(?i)^\s*CREATE\s+(OR\s+REPLACE\s+)?TEMP(ORARY)?\b").expect("valid regex")
3139        });
3140        let dataset = self.default_dataset.clone();
3141        let project = self.default_project.clone();
3142        let temps: HashSet<String> = self.temps.keys().cloned().collect();
3143        let qualify = |name: &mut ObjectName, is_cte: bool| {
3144            let table = name.table_name();
3145            if table.name.is_empty() || table.project.is_some() {
3146                return;
3147            }
3148            let mut parts = name.parts();
3149            if table.dataset.is_none() {
3150                if is_cte || temps.contains(&table.name.to_lowercase()) || dataset.is_empty() {
3151                    return;
3152                }
3153                parts.insert(0, dataset.clone());
3154            } else if table
3155                .dataset
3156                .as_deref()
3157                .is_some_and(|d| d.eq_ignore_ascii_case("_session"))
3158            {
3159                return;
3160            }
3161            if !project.is_empty() {
3162                parts.insert(0, project.clone());
3163            }
3164            *name = ObjectName(parts.into_iter().map(Ident::new).collect());
3165        };
3166        tree.visit_tables_mut(&mut |factor, is_cte| {
3167            if let TableFactor::Table { name, .. } = factor {
3168                qualify(name, is_cte);
3169            }
3170        });
3171        // written targets
3172        let is_temp_create = temp_re.is_match(text);
3173        match tree {
3174            Statement::CreateTable(c) if !is_temp_create => qualify(&mut c.name, false),
3175            Statement::CreateView(c) => qualify(&mut c.name, false),
3176            Statement::Insert(i) => qualify(&mut i.table, false),
3177            Statement::Update(u) => qualify(&mut u.table, false),
3178            Statement::Delete(d) => qualify(&mut d.table, false),
3179            Statement::Merge(m) => qualify(&mut m.target, false),
3180            _ => {}
3181        }
3182    }
3183
3184    fn expand_functions(&mut self, tree: &mut Statement) {
3185        let functions = self.functions.clone();
3186        let mut counter = self.tvf_counter;
3187        tree.visit_tables_mut(&mut |factor, _| {
3188            let TableFactor::TableFunction { function, alias } = factor else {
3189                return;
3190            };
3191            let name = norm(&function.name.dotted());
3192            let short = name.rsplit('.').next().unwrap_or(&name).to_string();
3193            let Some(definition) = functions.get(&name).or_else(|| functions.get(&short)) else {
3194                return;
3195            };
3196            if let Some(query) = inline_table_function(definition, function, &mut counter) {
3197                *factor = TableFactor::Derived {
3198                    subquery: Box::new(query),
3199                    alias: alias.clone(),
3200                    sample: None,
3201                };
3202            }
3203        });
3204        self.tvf_counter = counter;
3205    }
3206
3207    /// A copy of `tree` reading each temporary table under the name of its current version.
3208    fn rewritten(&self, tree: &Statement, temps: &[usize]) -> Statement {
3209        let mut copy = tree.clone();
3210        if temps.is_empty() {
3211            return copy;
3212        }
3213        let by_name: IndexMap<String, &Temp> = temps
3214            .iter()
3215            .map(|&id| (self.arena[id].name.to_lowercase(), &self.arena[id]))
3216            .collect();
3217        copy.visit_tables_mut(&mut |factor, is_cte| {
3218            if is_cte {
3219                return;
3220            }
3221            if let TableFactor::Table { name, .. } = factor {
3222                let table = name.table_name();
3223                if !is_temp(&table) {
3224                    return;
3225                }
3226                if let Some(version) = by_name.get(&table.name.to_lowercase()) {
3227                    if version.alias != table.name || table.dataset.is_some() {
3228                        *name = ObjectName(vec![Ident::new(version.alias.clone())]);
3229                    }
3230                }
3231            }
3232        });
3233        copy
3234    }
3235
3236    fn degrade(&mut self, statement: usize, text: &str) {
3237        self.stmt(statement).error = parse_error_line(text);
3238        let (reads, writes) = token_reads(text);
3239        if reads.is_empty() && writes.is_empty() {
3240            return;
3241        }
3242        self.stmt(statement).degraded = true;
3243        let mut sources = Tables::new();
3244        for table in reads {
3245            if is_temp(&table) {
3246                if let Some(&id) = self.temps.get(&table.name.to_lowercase()) {
3247                    sources.extend(self.arena[id].sources.clone());
3248                    continue;
3249                }
3250            }
3251            sources.insert(table_key(&table), table);
3252        }
3253        for (k, v) in &sources {
3254            self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
3255        }
3256        self.stmt(statement).reads.extend(sources.clone());
3257        let conditional = self.a.statements[statement].conditional;
3258        for table in writes {
3259            if is_temp(&table) {
3260                continue;
3261            }
3262            let key = table_key(&table);
3263            let feeding: Tables = sources
3264                .iter()
3265                .filter(|(k, _)| **k != key)
3266                .map(|(k, v)| (k.clone(), v.clone()))
3267                .collect();
3268            self.write(&table, &feeding, "opaque", conditional);
3269        }
3270    }
3271
3272    fn query_statement(&mut self, text: &str, line: usize, conditional: bool, top_level: bool) {
3273        let index = self.a.statements.len();
3274        let tree = self.parse(text);
3275        let query = tree.as_ref().and_then(query_of);
3276        match (tree, query) {
3277            (Some(tree), Some(query)) if matches!(tree, Statement::Query(_)) => {
3278                let s = self.record(AnalysedStatement::new(
3279                    index,
3280                    line,
3281                    "select",
3282                    Disposition::Kept,
3283                    "",
3284                    conditional,
3285                ));
3286                self.after_query(s, &tree, query, None, conditional, top_level);
3287            }
3288            _ => {
3289                let s = self.record(AnalysedStatement::new(
3290                    index,
3291                    line,
3292                    "select",
3293                    Disposition::Unknown,
3294                    "could not be parsed",
3295                    conditional,
3296                ));
3297                self.degrade(s, text);
3298            }
3299        }
3300    }
3301
3302    fn after_query(
3303        &mut self,
3304        statement: usize,
3305        tree: &Statement,
3306        query: Query,
3307        target: Option<TableName>,
3308        conditional: bool,
3309        top_level: bool,
3310    ) -> (Tables, Vec<usize>) {
3311        let (sources, temps, _late) = self.reads_of(tree);
3312        let via = self.variable_sources(tree);
3313        for (k, v) in &sources {
3314            self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
3315        }
3316        self.stmt(statement).reads.extend(sources.clone());
3317        for (k, v) in &via {
3318            if !sources.contains_key(k) {
3319                self.a
3320                    .variable_reads
3321                    .entry(k.clone())
3322                    .or_insert_with(|| v.clone());
3323            }
3324            self.a
3325                .side_reads
3326                .entry(k.clone())
3327                .or_insert_with(|| v.clone());
3328        }
3329        let mut merged = sources;
3330        merged.extend(via);
3331        let node = self.rewritten(tree, &temps);
3332        let out_query = query_of(&node).unwrap_or(query);
3333        let top = top_level && self.nested.is_empty();
3334        self.a.outputs.push(Output {
3335            statement,
3336            node,
3337            query: out_query,
3338            temps: temps.clone(),
3339            target,
3340            conditional,
3341            top_level: top,
3342        });
3343        (merged, temps)
3344    }
3345
3346    fn create_statement(
3347        &mut self,
3348        text: &str,
3349        line: usize,
3350        words: &[String],
3351        conditional: bool,
3352        top_level: bool,
3353    ) {
3354        static ROUTINE: OnceLock<Regex> = OnceLock::new();
3355        static RELATION: OnceLock<Regex> = OnceLock::new();
3356        let routine = ROUTINE.get_or_init(|| {
3357            Regex::new(r"^CREATE (OR REPLACE )?(TEMP |TEMPORARY )?(AGGREGATE )?(TABLE )?(FUNCTION|PROCEDURE)").expect("valid regex")
3358        });
3359        let relation = RELATION.get_or_init(|| {
3360            Regex::new(r"^CREATE (OR REPLACE )?(TEMP |TEMPORARY )?(EXTERNAL |MATERIALIZED |SNAPSHOT )?(TABLE|VIEW|MODEL)").expect("valid regex")
3361        });
3362        let index = self.a.statements.len();
3363        let head = words
3364            .iter()
3365            .take(6)
3366            .filter(|w| !w.is_empty())
3367            .cloned()
3368            .collect::<Vec<_>>()
3369            .join(" ");
3370        if routine.is_match(&head) {
3371            let (body, table_params): (Option<Statement>, HashSet<String>) = match parse_one(text) {
3372                Some(Statement::CreateTableFunction(def)) => {
3373                    let params = def
3374                        .params
3375                        .iter()
3376                        .filter(|p| {
3377                            matches!(p.param_type, ParamType::Table(_) | ParamType::AnyTable)
3378                        })
3379                        .map(|p| p.name.value.to_lowercase())
3380                        .collect();
3381                    (Some(Statement::Query(def.query.clone())), params)
3382                }
3383                Some(Statement::CreateFunction(def)) => match &def.body {
3384                    FunctionBody::Expr(e) => (
3385                        Some(Statement::Query(Box::new(Query::from_select(Select::new(
3386                            vec![SelectItem::expr(e.clone(), None)],
3387                        ))))),
3388                        HashSet::new(),
3389                    ),
3390                    _ => (None, HashSet::new()),
3391                },
3392                _ => (None, HashSet::new()),
3393            };
3394            let found: Tables = match &body {
3395                Some(body) => self
3396                    .reads_of(body)
3397                    .0
3398                    .into_iter()
3399                    .filter(|(k, _)| !table_params.contains(k))
3400                    .collect(),
3401                None => Tables::new(),
3402            };
3403            if found.is_empty() {
3404                let s = self.record(AnalysedStatement::new(
3405                    index,
3406                    line,
3407                    "create_function",
3408                    Disposition::Ignored,
3409                    "defines a routine; read when called",
3410                    conditional,
3411                ));
3412                self.stmt(s).definition = true;
3413                return;
3414            }
3415            for (k, v) in &found {
3416                self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
3417                self.a
3418                    .definition_reads
3419                    .entry(k.clone())
3420                    .or_insert_with(|| v.clone());
3421                self.a
3422                    .side_reads
3423                    .entry(k.clone())
3424                    .or_insert_with(|| v.clone());
3425            }
3426            let name = routine_name(text);
3427            if !name.is_empty() {
3428                self.function_reads.insert(name, found);
3429            }
3430            let s = self.record(AnalysedStatement::new(
3431                index,
3432                line,
3433                "create_function",
3434                Disposition::Kept,
3435                "reads only: the tables its body reads when called",
3436                conditional,
3437            ));
3438            self.stmt(s).definition = true;
3439            return;
3440        }
3441        if !relation.is_match(&head) {
3442            self.record(AnalysedStatement::new(
3443                index,
3444                line,
3445                "ddl",
3446                Disposition::Ignored,
3447                "definition change, no data flow",
3448                conditional,
3449            ));
3450            return;
3451        }
3452        let tree = self.parse(text);
3453        let parsed: Option<CreateParts> = match &tree {
3454            Some(Statement::CreateTable(c)) => Some((
3455                c.name.table_name(),
3456                "create_table",
3457                c.temporary,
3458                c.columns.iter().map(|col| col.name.value.clone()).collect(),
3459                c.copy.clone(),
3460            )),
3461            Some(Statement::CreateView(c)) => {
3462                Some((c.name.table_name(), "create_view", false, Vec::new(), None))
3463            }
3464            _ => None,
3465        };
3466        let Some((target, mut kind, temporary, column_names, copy)) = parsed else {
3467            let kind = if words.iter().take(6).any(|w| w == "MODEL") {
3468                "create_model"
3469            } else {
3470                "create_table"
3471            };
3472            let s = self.record(AnalysedStatement::new(
3473                index,
3474                line,
3475                kind,
3476                Disposition::Unknown,
3477                "could not be parsed",
3478                conditional,
3479            ));
3480            self.degrade(s, text);
3481            return;
3482        };
3483        let tree = tree.expect("parsed");
3484        if target.name.is_empty() {
3485            let s = self.record(AnalysedStatement::new(
3486                index,
3487                line,
3488                "create_table",
3489                Disposition::Unknown,
3490                "could not be parsed",
3491                conditional,
3492            ));
3493            self.degrade(s, text);
3494            return;
3495        }
3496        if words.iter().take(6).any(|w| w == "VIEW") {
3497            kind = "create_view";
3498        }
3499        let temp = (temporary
3500            || words
3501                .iter()
3502                .take(6)
3503                .any(|w| w == "TEMP" || w == "TEMPORARY"))
3504            && is_temp(&target);
3505        let columns: Option<Vec<String>> = (!column_names.is_empty()).then_some(column_names);
3506        let query = query_of(&tree);
3507        if query.is_none() {
3508            if let Some(copy) = copy {
3509                let kind = if copy.kind == CopyKind::Like {
3510                    "like"
3511                } else {
3512                    "clone"
3513                };
3514                let s = self.record(AnalysedStatement::new(
3515                    index,
3516                    line,
3517                    kind,
3518                    Disposition::Kept,
3519                    "",
3520                    conditional,
3521                ));
3522                let source_tree =
3523                    Statement::Query(Box::new(Query::from_body(SetExpr::From(vec![
3524                        TableWithJoins::table(copy.source.clone()),
3525                    ]))));
3526                let (sources, _, _) = self.reads_of(&source_tree);
3527                self.write_or_temp(
3528                    &target,
3529                    sources,
3530                    "clone",
3531                    conditional,
3532                    temp,
3533                    columns,
3534                    None,
3535                    s,
3536                );
3537                return;
3538            }
3539            let s = self.record(AnalysedStatement::new(
3540                index,
3541                line,
3542                kind,
3543                Disposition::Kept,
3544                "no source query",
3545                conditional,
3546            ));
3547            if temp {
3548                self.define_temp(&target, Tables::new(), None, columns, conditional, vec![s]);
3549            } else {
3550                self.write(&target, &Tables::new(), kind, conditional);
3551            }
3552            return;
3553        }
3554        let query = query.expect("query");
3555        let s = self.record(AnalysedStatement::new(
3556            index,
3557            line,
3558            kind,
3559            Disposition::Kept,
3560            "",
3561            conditional,
3562        ));
3563        let (sources, temps) = self.after_query(
3564            s,
3565            &tree,
3566            query,
3567            Some(target.clone()),
3568            conditional,
3569            top_level && !temp,
3570        );
3571        let output = self.a.outputs.len() - 1;
3572        let _ = temps;
3573        self.write_or_temp(
3574            &target,
3575            sources,
3576            kind,
3577            conditional,
3578            temp,
3579            columns,
3580            Some(output),
3581            s,
3582        );
3583    }
3584
3585    #[allow(clippy::too_many_arguments)]
3586    fn write_or_temp(
3587        &mut self,
3588        target: &TableName,
3589        sources: Tables,
3590        kind: &str,
3591        conditional: bool,
3592        temp: bool,
3593        columns: Option<Vec<String>>,
3594        output: Option<usize>,
3595        statement: usize,
3596    ) {
3597        if temp {
3598            self.define_temp(
3599                target,
3600                sources,
3601                output,
3602                columns,
3603                conditional,
3604                vec![statement],
3605            );
3606            return;
3607        }
3608        for (k, v) in &sources {
3609            self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
3610        }
3611        if output.is_none() {
3612            self.stmt(statement).reads.extend(sources.clone());
3613        }
3614        self.write(target, &sources, kind, conditional);
3615    }
3616
3617    fn write(&mut self, target: &TableName, sources: &Tables, kind: &str, conditional: bool) {
3618        let key = table_key(target);
3619        let mut merged = sources.clone();
3620        for (k, t) in self.guarded() {
3621            if k != key {
3622                merged.insert(k, t);
3623            }
3624        }
3625        self.a.writes.push(ScriptWrite {
3626            table: target.clone(),
3627            sources: merged.into_values().collect(),
3628            kind: kind.to_string(),
3629            conditional,
3630            via_variable: false,
3631        });
3632    }
3633
3634    // -- temporary tables
3635
3636    fn used_elsewhere(&self) -> HashSet<String> {
3637        self.used_names
3638            .iter()
3639            .filter(|n| !self.a.temp_names.contains(*n))
3640            .cloned()
3641            .collect()
3642    }
3643
3644    fn define_temp(
3645        &mut self,
3646        target: &TableName,
3647        sources: Tables,
3648        output: Option<usize>,
3649        columns: Option<Vec<String>>,
3650        conditional: bool,
3651        statements: Vec<usize>,
3652    ) {
3653        let name = target.name.clone();
3654        let key = name.to_lowercase();
3655        self.a.temp_names.insert(key.clone());
3656        self.sequence += 1;
3657        let version = self.versions.get(&key).copied().unwrap_or(0) + 1;
3658        self.versions.insert(key.clone(), version);
3659        let alias = if version == 1 && !self.used_elsewhere().contains(&key) {
3660            name.clone()
3661        } else {
3662            format!("{name}__v{version}")
3663        };
3664        let mut all_sources = sources;
3665        all_sources.extend(self.guarded());
3666        let mut temp = Temp {
3667            name: name.clone(),
3668            alias,
3669            sources: all_sources,
3670            query: None,
3671            columns: None,
3672            deps: Vec::new(),
3673            opaque_reason: String::new(),
3674            sequence: self.sequence,
3675            statements,
3676            empty: false,
3677        };
3678        match output {
3679            Some(o) => {
3680                let out = self.a.outputs[o].clone();
3681                temp.deps = out.temps.clone();
3682                let query = match &columns {
3683                    Some(cols) => {
3684                        temp.columns = Some(cols.clone());
3685                        alias_to(&out.query, cols)
3686                    }
3687                    None => {
3688                        temp.columns = output_names(&out.query);
3689                        Some(out.query.clone())
3690                    }
3691                };
3692                if query.is_none() {
3693                    temp.opaque_reason =
3694                        "its columns do not line up with the declared ones".to_string();
3695                }
3696                temp.query = query;
3697            }
3698            None => {
3699                temp.columns = columns;
3700                temp.empty = true;
3701            }
3702        }
3703        if let Some(&previous) = self.temps.get(&key) {
3704            if conditional {
3705                let previous = self.arena[previous].clone();
3706                let mut merged = previous.sources.clone();
3707                merged.extend(temp.sources);
3708                temp.sources = merged;
3709                temp.query = None;
3710                temp.empty = false;
3711                temp.opaque_reason = "defined on more than one path".to_string();
3712                let mut statements = previous.statements.clone();
3713                statements.extend(temp.statements);
3714                temp.statements = statements;
3715            }
3716        }
3717        self.arena.push(temp);
3718        self.temps.insert(key, self.arena.len() - 1);
3719    }
3720
3721    fn temp_dml(
3722        &mut self,
3723        target: &TableName,
3724        kind: &str,
3725        output: Option<usize>,
3726        insert_columns: Option<Vec<String>>,
3727        sources: Tables,
3728        statement: usize,
3729    ) {
3730        let key = target.name.to_lowercase();
3731        let previous_id = self.temps[&key];
3732        let mut sources = sources;
3733        sources.extend(self.guarded());
3734        if kind == "delete" {
3735            // removes rows: the columns still come from the same query
3736            let previous = &mut self.arena[previous_id];
3737            for (k, t) in sources {
3738                previous.sources.entry(k).or_insert(t);
3739            }
3740            previous.statements.push(statement);
3741            return;
3742        }
3743        self.sequence += 1;
3744        let version = self.versions.get(&key).copied().unwrap_or(0) + 1;
3745        self.versions.insert(key.clone(), version);
3746        let previous = self.arena[previous_id].clone();
3747        let mut merged = previous.sources.clone();
3748        for (k, t) in sources {
3749            merged.entry(k).or_insert(t);
3750        }
3751        let mut statements = previous.statements.clone();
3752        statements.push(statement);
3753        let mut temp = Temp {
3754            name: previous.name.clone(),
3755            alias: format!("{}__v{version}", previous.name),
3756            sources: merged,
3757            query: previous.query.clone(),
3758            columns: previous.columns.clone(),
3759            deps: previous.deps.clone(),
3760            opaque_reason: previous.opaque_reason.clone(),
3761            sequence: self.sequence,
3762            statements,
3763            empty: previous.empty,
3764        };
3765        if let (true, Some(o), Some(columns), true) = (
3766            kind == "insert",
3767            output,
3768            temp.columns.clone(),
3769            temp.opaque_reason.is_empty(),
3770        ) {
3771            let out = self.a.outputs[o].clone();
3772            if let Some(arm) = arm(&out.query, &columns, insert_columns.as_deref()) {
3773                temp.query = if temp.empty || temp.query.is_none() {
3774                    Some(arm)
3775                } else {
3776                    union_all(vec![temp.query.clone().expect("query"), arm], false)
3777                };
3778                temp.empty = false;
3779                let mut deps = previous.deps.clone();
3780                for d in out.temps {
3781                    if !deps.contains(&d) {
3782                        deps.push(d);
3783                    }
3784                }
3785                temp.deps = deps;
3786                self.arena.push(temp);
3787                self.temps.insert(key, self.arena.len() - 1);
3788                return;
3789            }
3790        }
3791        temp.query = None;
3792        temp.empty = false;
3793        temp.opaque_reason = format!("changed by {kind} in a way it could not follow");
3794        self.arena.push(temp);
3795        self.temps.insert(key, self.arena.len() - 1);
3796    }
3797
3798    fn dml_statement(&mut self, text: &str, line: usize, kind: &str, conditional: bool) {
3799        let index = self.a.statements.len();
3800        let tree = self.parse(text);
3801        let target = match (&tree, kind) {
3802            (Some(Statement::Insert(i)), "insert") => Some(i.table.table_name()),
3803            (Some(Statement::Merge(m)), "merge") => Some(m.target.table_name()),
3804            (Some(Statement::Update(u)), "update") => Some(u.table.table_name()),
3805            (Some(Statement::Delete(d)), "delete") => Some(d.table.table_name()),
3806            _ => None,
3807        };
3808        let Some(target) = target else {
3809            let s = self.record(AnalysedStatement::new(
3810                index,
3811                line,
3812                kind,
3813                Disposition::Unknown,
3814                "could not be parsed",
3815                conditional,
3816            ));
3817            self.degrade(s, text);
3818            return;
3819        };
3820        let tree = tree.expect("parsed");
3821        if target.name.is_empty() {
3822            self.record(AnalysedStatement::new(
3823                index,
3824                line,
3825                kind,
3826                Disposition::Unknown,
3827                "target could not be read",
3828                conditional,
3829            ));
3830            return;
3831        }
3832        let s = self.record(AnalysedStatement::new(
3833            index,
3834            line,
3835            kind,
3836            Disposition::Kept,
3837            "",
3838            conditional,
3839        ));
3840        let complete = kind == "delete" || matches!(&tree, Statement::Merge(m) if only_deletes(m));
3841        self.stmt(s).complete = complete;
3842        let into_temp = is_temp(&target) && self.temps.contains_key(&target.name.to_lowercase());
3843        let query = if kind == "insert" {
3844            query_of(&tree)
3845        } else {
3846            None
3847        };
3848        let mut output = None;
3849        let mut sources;
3850        if let Some(query) = query {
3851            let (merged, _) = self.after_query(
3852                s,
3853                &tree,
3854                query,
3855                Some(target.clone()),
3856                conditional,
3857                !into_temp,
3858            );
3859            output = Some(self.a.outputs.len() - 1);
3860            sources = merged;
3861        } else {
3862            let (direct, temps, _late) = self.reads_of(&tree);
3863            let via = self.variable_sources(&tree);
3864            for (k, v) in &direct {
3865                self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
3866            }
3867            self.stmt(s).reads.extend(direct.clone());
3868            for (k, v) in &via {
3869                if !direct.contains_key(k) {
3870                    self.a
3871                        .variable_reads
3872                        .entry(k.clone())
3873                        .or_insert_with(|| v.clone());
3874                }
3875                self.a
3876                    .side_reads
3877                    .entry(k.clone())
3878                    .or_insert_with(|| v.clone());
3879            }
3880            sources = direct;
3881            sources.extend(via);
3882            if (kind == "merge" || kind == "insert") && !into_temp {
3883                let node = self.rewritten(&tree, &temps);
3884                let built = match &node {
3885                    Statement::Merge(m) => merge_query(m),
3886                    Statement::Insert(i) => insert_values_query(i),
3887                    _ => None,
3888                };
3889                if let Some(built) = built {
3890                    let top = self.nested.is_empty();
3891                    self.a.outputs.push(Output {
3892                        statement: s,
3893                        node,
3894                        query: built,
3895                        temps,
3896                        target: Some(target.clone()),
3897                        conditional,
3898                        top_level: top,
3899                    });
3900                }
3901            }
3902        }
3903        if into_temp {
3904            let insert_columns = match &tree {
3905                Statement::Insert(i) if !i.columns.is_empty() => {
3906                    Some(i.columns.iter().map(|c| c.value.clone()).collect())
3907                }
3908                _ => None,
3909            };
3910            self.temp_dml(&target, kind, output, insert_columns, sources, s);
3911            return;
3912        }
3913        sources.shift_remove(&table_key(&target));
3914        self.write(&target, &sources, kind, conditional);
3915    }
3916
3917    // -- variables
3918
3919    fn declare_statement(&mut self, text: &str, line: usize, conditional: bool) {
3920        let toks = lex(text);
3921        let mut names = Vec::new();
3922        let mut j = 1;
3923        while j < toks.len()
3924            && matches!(toks[j].kind, TokKind::Word | TokKind::Punct)
3925            && !(toks[j].kind == TokKind::Word && toks[j].up() == "DEFAULT")
3926        {
3927            if toks[j].kind == TokKind::Word {
3928                names.push(toks[j].text.clone());
3929                j += 1;
3930                if j < toks.len() && toks[j].text == "," {
3931                    j += 1;
3932                    continue;
3933                }
3934                break;
3935            }
3936            j += 1;
3937        }
3938        let index = self.a.statements.len();
3939        let s = self.record(AnalysedStatement::new(
3940            index,
3941            line,
3942            "declare",
3943            Disposition::Ignored,
3944            "scalar variable",
3945            conditional,
3946        ));
3947        let default = toks
3948            .iter()
3949            .position(|t| t.kind == TokKind::Word && t.up() == "DEFAULT");
3950        match default {
3951            Some(d) => {
3952                let expression = toks
3953                    .get(d + 1)
3954                    .map(|t| text[t.start..].to_string())
3955                    .unwrap_or_default();
3956                let (sources, ok) = self.value_sources(&expression);
3957                if !ok {
3958                    self.set_unknown(s, "value could not be read");
3959                }
3960                self.declare_variables(&names, &sources);
3961            }
3962            None => self.declare_variables(&names, &Tables::new()),
3963        }
3964    }
3965
3966    fn set_statement(&mut self, text: &str, line: usize, conditional: bool) {
3967        static RE: OnceLock<Regex> = OnceLock::new();
3968        let re = RE.get_or_init(|| {
3969            Regex::new(r"(?is)^\s*SET\s+(\([^)]*\)|[\w.@`]+)\s*=\s*(.*)$").expect("valid regex")
3970        });
3971        let index = self.a.statements.len();
3972        let s = self.record(AnalysedStatement::new(
3973            index,
3974            line,
3975            "set",
3976            Disposition::Ignored,
3977            "scalar variable",
3978            conditional,
3979        ));
3980        let Some(caps) = re.captures(text) else {
3981            return;
3982        };
3983        let target = caps[1].to_string();
3984        let expression = caps[2].to_string();
3985        let names: Vec<String> = if target.starts_with('(') {
3986            target
3987                .split(',')
3988                .map(|n| n.trim().trim_matches(['(', ')']).to_string())
3989                .collect()
3990        } else {
3991            vec![target]
3992        };
3993        let (sources, ok) = self.value_sources(&expression);
3994        if !ok {
3995            self.set_unknown(s, "value could not be read");
3996        }
3997        for name in names {
3998            let name = name.split('.').next().unwrap_or("").trim().to_lowercase();
3999            if name.starts_with("@@") {
4000                self.set_system_variable(s, &name, &expression, conditional);
4001                continue;
4002            }
4003            self.assign(&name, &sources, conditional);
4004        }
4005    }
4006
4007    fn set_system_variable(
4008        &mut self,
4009        statement: usize,
4010        name: &str,
4011        expression: &str,
4012        conditional: bool,
4013    ) {
4014        if name != "@@dataset_id" && name != "@@dataset_project_id" {
4015            return;
4016        }
4017        let toks = lex(expression);
4018        let value = if toks.len() == 1 && toks[0].kind == TokKind::String {
4019            string_value(&toks[0].text)
4020        } else {
4021            None
4022        };
4023        static NAME: OnceLock<Regex> = OnceLock::new();
4024        let name_re = NAME.get_or_init(|| Regex::new(r"^[\w\-]+$").expect("valid regex"));
4025        match value {
4026            Some(v) if !conditional && self.nested.is_empty() && name_re.is_match(&v) => {
4027                if name == "@@dataset_id" {
4028                    self.default_dataset = v;
4029                } else {
4030                    self.default_project = v;
4031                }
4032            }
4033            _ => self.set_unknown(
4034                statement,
4035                "changes the default dataset to a value that is not known here",
4036            ),
4037        }
4038    }
4039
4040    // -- other statements
4041
4042    fn export_statement(&mut self, text: &str, line: usize, conditional: bool) {
4043        static RE: OnceLock<Regex> = OnceLock::new();
4044        let re = RE.get_or_init(|| Regex::new(r"(?is)\bAS\b\s*(.*)$").expect("valid regex"));
4045        let index = self.a.statements.len();
4046        let tree = re.captures(text).and_then(|c| parse_one(&c[1]));
4047        let tree = tree.filter(|t| query_of(t).is_some());
4048        let Some(tree) = tree else {
4049            let s = self.record(AnalysedStatement::new(
4050                index,
4051                line,
4052                "export_data",
4053                Disposition::Unknown,
4054                "query could not be read",
4055                conditional,
4056            ));
4057            self.degrade(s, text);
4058            return;
4059        };
4060        let s = self.record(AnalysedStatement::new(
4061            index,
4062            line,
4063            "export_data",
4064            Disposition::Kept,
4065            "reads only: nothing is written to a table",
4066            conditional,
4067        ));
4068        let (sources, _, _) = self.reads_of(&tree);
4069        for (k, v) in &sources {
4070            self.a.reads.entry(k.clone()).or_insert_with(|| v.clone());
4071        }
4072        self.stmt(s).reads.extend(sources);
4073    }
4074
4075    fn call_statement(&mut self, text: &str, line: usize, conditional: bool) {
4076        static RE: OnceLock<Regex> = OnceLock::new();
4077        let re = RE.get_or_init(|| {
4078            Regex::new(r"(?is)^\s*CALL\s+((?:`[^`]+`|[\w.\-]+)+)\s*\((.*)\)\s*$")
4079                .expect("valid regex")
4080        });
4081        let index = self.a.statements.len();
4082        let Some(caps) = re.captures(text) else {
4083            self.record(AnalysedStatement::new(
4084                index,
4085                line,
4086                "call",
4087                Disposition::Unknown,
4088                "could not be read",
4089                conditional,
4090            ));
4091            return;
4092        };
4093        let name = caps[1].replace('`', "");
4094        let Some(procedure) = self.known_procedure(&name) else {
4095            self.record(AnalysedStatement::new(
4096                index,
4097                line,
4098                "call",
4099                Disposition::Unknown,
4100                "procedure is not defined in the project",
4101                conditional,
4102            ));
4103            return;
4104        };
4105        if self.call_stack.contains(&norm(&procedure.name))
4106            || self.call_stack.len() >= MAX_PROCEDURE_DEPTH
4107        {
4108            self.record(AnalysedStatement::new(
4109                index,
4110                line,
4111                "call",
4112                Disposition::Unknown,
4113                "recursive or too deeply nested",
4114                conditional,
4115            ));
4116            return;
4117        }
4118        let s = self.record(AnalysedStatement::new(
4119            index,
4120            line,
4121            "call",
4122            Disposition::Kept,
4123            "expanded from its definition",
4124            conditional,
4125        ));
4126        let arguments = split_arguments(&caps[2]);
4127        let modes: Vec<String> = if procedure.modes.is_empty() {
4128            vec!["IN".to_string(); procedure.params.len()]
4129        } else {
4130            procedure.modes.clone()
4131        };
4132        // the body runs in its own scope; only OUT and INOUT parameters flow back
4133        let caller = self.variables.clone();
4134        let caller_scopes = std::mem::replace(&mut self.scopes, vec![IndexMap::new()]);
4135        for (position, param) in procedure.params.iter().enumerate() {
4136            let mut sources = Tables::new();
4137            if position < arguments.len() && modes.get(position).map(String::as_str) != Some("OUT")
4138            {
4139                sources = self.value_sources(&arguments[position]).0;
4140            }
4141            sources.extend(self.guarded());
4142            self.variables
4143                .insert(param.to_lowercase(), Variable { sources });
4144        }
4145        self.call_stack.push(norm(&procedure.name));
4146        let inner_nested = if self.nested.is_empty() {
4147            "procedure".to_string()
4148        } else {
4149            self.nested.clone()
4150        };
4151        let previous_nested = std::mem::replace(&mut self.nested, inner_nested);
4152        let previous_anchor = self.anchor_line;
4153        if self.anchor_line == 0 {
4154            self.anchor_line = line;
4155        }
4156        let before_unknown = self.a.unknown().len();
4157        self.nodes_in_text(&procedure.body, &procedure.text, conditional);
4158        if self.a.unknown().len() > before_unknown {
4159            self.stmt(s).reason =
4160                "expanded from its definition; some of it could not be read".to_string();
4161        }
4162        let mut returned: Vec<(String, Tables)> = Vec::new();
4163        for (position, param) in procedure.params.iter().enumerate() {
4164            let mode = modes.get(position).map(String::as_str).unwrap_or("IN");
4165            if (mode == "OUT" || mode == "INOUT") && position < arguments.len() {
4166                let sources = self
4167                    .variables
4168                    .get(&param.to_lowercase())
4169                    .map(|v| v.sources.clone())
4170                    .unwrap_or_default();
4171                returned.push((arguments[position].clone(), sources));
4172            }
4173        }
4174        self.nested = previous_nested;
4175        self.anchor_line = previous_anchor;
4176        self.call_stack.pop();
4177        self.variables = caller;
4178        self.scopes = caller_scopes;
4179        static WORD: OnceLock<Regex> = OnceLock::new();
4180        let word = WORD.get_or_init(|| Regex::new(r"^\w+$").expect("valid regex"));
4181        for (argument, sources) in returned {
4182            let name = argument.trim().trim_matches('`').to_string();
4183            if word.is_match(&name) {
4184                self.assign(&name, &sources, conditional);
4185            } else {
4186                self.set_unknown(s, "an OUT argument is not a variable");
4187            }
4188        }
4189    }
4190
4191    fn nodes_in_text(&mut self, nodes: &[ScriptNode], text: &str, conditional: bool) {
4192        let saved = std::mem::replace(&mut self.breaks, line_index(text));
4193        self.nodes(nodes, text, conditional, false);
4194        self.breaks = saved;
4195    }
4196
4197    fn execute_statement(&mut self, text: &str, line: usize, conditional: bool) {
4198        let index = self.a.statements.len();
4199        let toks = lex(text);
4200        if toks.len() < 3 || toks[1].up() != "IMMEDIATE" {
4201            self.record(AnalysedStatement::new(
4202                index,
4203                line,
4204                "execute",
4205                Disposition::Unknown,
4206                "statement not recognised",
4207                conditional,
4208            ));
4209            return;
4210        }
4211        let mut body: Vec<Tok> = Vec::new();
4212        let mut starts: Vec<(String, usize, usize)> = Vec::new();
4213        let mut depth = 0i32;
4214        for t in &toks[2..] {
4215            if t.kind == TokKind::Punct && (t.text == "(" || t.text == "[") {
4216                depth += 1;
4217            } else if t.kind == TokKind::Punct && (t.text == ")" || t.text == "]") {
4218                depth -= 1;
4219            }
4220            if depth == 0 && t.kind == TokKind::Word && (t.up() == "INTO" || t.up() == "USING") {
4221                starts.push((t.up(), t.start, t.end));
4222            } else if starts.is_empty() {
4223                body.push(t.clone());
4224            }
4225        }
4226        let mut clauses: IndexMap<String, String> = IndexMap::new();
4227        for (i, (word, _start, end)) in starts.iter().enumerate() {
4228            let stop = starts.get(i + 1).map_or(text.len(), |n| n.1);
4229            clauses.insert(word.clone(), text[*end..stop].trim().to_string());
4230        }
4231        let Some(inner) = literal_text(&body) else {
4232            for variable in split_arguments(clauses.get("INTO").map_or("", String::as_str)) {
4233                if !variable.is_empty() {
4234                    self.assign(variable.trim_matches('`'), &Tables::new(), true);
4235                    // what dynamic text puts in it is unknown
4236                }
4237            }
4238            self.record(AnalysedStatement::new(
4239                index,
4240                line,
4241                "execute_immediate",
4242                Disposition::Unknown,
4243                "dynamic SQL text",
4244                conditional,
4245            ));
4246            return;
4247        };
4248        if self.depth >= MAX_NESTED_SQL_DEPTH {
4249            self.record(AnalysedStatement::new(
4250                index,
4251                line,
4252                "execute_immediate",
4253                Disposition::Unknown,
4254                "nested too deeply to read",
4255                conditional,
4256            ));
4257            return;
4258        }
4259        let s = self.record(AnalysedStatement::new(
4260            index,
4261            line,
4262            "execute_immediate",
4263            Disposition::Kept,
4264            "literal text, read as a script",
4265            conditional,
4266        ));
4267        // USING binds values to the text's @name and ? parameters
4268        let mut parameters: IndexMap<String, Tables> = IndexMap::new();
4269        parameters.insert(String::new(), Tables::new());
4270        static NAMED: OnceLock<Regex> = OnceLock::new();
4271        let named_re = NAMED
4272            .get_or_init(|| Regex::new(r"(?is)^(.*?)\s+AS\s+`?(\w+)`?\s*$").expect("valid regex"));
4273        static WORD: OnceLock<Regex> = OnceLock::new();
4274        let word = WORD.get_or_init(|| Regex::new(r"^\w+$").expect("valid regex"));
4275        for argument in split_arguments(clauses.get("USING").map_or("", String::as_str)) {
4276            if argument.is_empty() {
4277                continue;
4278            }
4279            let (value, name) = match named_re.captures(&argument) {
4280                Some(c) => (c[1].to_string(), c[2].to_string()),
4281                None => (argument.clone(), String::new()),
4282            };
4283            let (sources, ok) = self.value_sources(&value);
4284            if !ok {
4285                self.set_unknown(s, "a USING value could not be read");
4286            }
4287            let key = if !name.is_empty() {
4288                name.to_lowercase()
4289            } else if word.is_match(value.trim()) {
4290                value.trim().to_lowercase()
4291            } else {
4292                String::new()
4293            };
4294            if !key.is_empty() {
4295                parameters.entry(key).or_default().extend(sources.clone());
4296            }
4297            parameters.entry(String::new()).or_default().extend(sources);
4298        }
4299        self.depth += 1;
4300        let inner_nested = if self.nested.is_empty() {
4301            "execute_immediate".to_string()
4302        } else {
4303            self.nested.clone()
4304        };
4305        let previous_nested = std::mem::replace(&mut self.nested, inner_nested);
4306        let previous_anchor = self.anchor_line;
4307        if self.anchor_line == 0 {
4308            self.anchor_line = line;
4309        }
4310        let previous_parameters = self.parameters.replace(parameters);
4311        let tree = script_tree(&inner);
4312        self.nodes_in_text(&tree, &inner, conditional);
4313        let mut into = Tables::new();
4314        if clauses.get("INTO").is_some_and(|c| !c.is_empty()) {
4315            let (sources, ok) = self.value_sources(&inner);
4316            if !ok {
4317                self.set_unknown(s, "the query read INTO variables could not be read");
4318            }
4319            into = sources;
4320        }
4321        self.nested = previous_nested;
4322        self.anchor_line = previous_anchor;
4323        self.parameters = previous_parameters;
4324        self.depth -= 1;
4325        for variable in split_arguments(clauses.get("INTO").map_or("", String::as_str)) {
4326            if !variable.is_empty() {
4327                self.assign(variable.trim_matches('`'), &into, conditional);
4328            }
4329        }
4330    }
4331
4332    // -- output
4333
4334    fn choose_final(&mut self) {
4335        self.pick_final();
4336        let untraced: Vec<Tables> = self
4337            .a
4338            .statements
4339            .iter()
4340            .filter(|s| !s.traced)
4341            .map(|s| s.reads.clone())
4342            .collect();
4343        for reads in untraced {
4344            for (k, v) in reads {
4345                self.a.side_reads.entry(k).or_insert(v);
4346            }
4347        }
4348    }
4349
4350    fn pick_final(&mut self) {
4351        let candidates: Vec<usize> = (0..self.a.outputs.len())
4352            .filter(|&i| {
4353                let o = &self.a.outputs[i];
4354                o.top_level
4355                    && self
4356                        .a
4357                        .statements
4358                        .get(o.statement)
4359                        .is_some_and(|s| s.disposition == Disposition::Kept)
4360            })
4361            .collect();
4362        let unconditional: Vec<usize> = candidates
4363            .iter()
4364            .copied()
4365            .filter(|&i| !self.a.outputs[i].conditional)
4366            .collect();
4367        let Some(&final_index) = unconditional.last().or(candidates.last()) else {
4368            return;
4369        };
4370        self.a.final_output = Some(final_index);
4371        let statement = self.a.outputs[final_index].statement;
4372        self.a.statements[statement].traced = true;
4373        let mut needed: Vec<usize> = Vec::new();
4374        fn collect(id: usize, arena: &[Temp], needed: &mut Vec<usize>) {
4375            if needed.contains(&id) {
4376                return;
4377            }
4378            for &dep in &arena[id].deps {
4379                collect(dep, arena, needed);
4380            }
4381            needed.push(id);
4382        }
4383        for &id in &self.a.outputs[final_index].temps.clone() {
4384            collect(id, &self.arena, &mut needed);
4385        }
4386        needed.sort_by_key(|&id| self.arena[id].sequence);
4387        let mut ctes = Vec::new();
4388        for id in needed {
4389            let temp = &self.arena[id];
4390            match &temp.query {
4391                None => {
4392                    let reason = if temp.opaque_reason.is_empty() {
4393                        "no query".to_string()
4394                    } else {
4395                        temp.opaque_reason.clone()
4396                    };
4397                    self.a
4398                        .opaque_temps
4399                        .insert(temp.alias.to_lowercase(), reason);
4400                }
4401                Some(query) => {
4402                    ctes.push((temp.alias.clone(), query.clone()));
4403                    for &s in &temp.statements {
4404                        if let Some(st) = self.a.statements.get_mut(s) {
4405                            st.traced = true;
4406                        }
4407                    }
4408                }
4409            }
4410        }
4411        self.a.ctes = ctes;
4412    }
4413}
4414
4415/// The function's query for one call: table arguments become CTEs the body reads, scalar
4416/// arguments replace the parameters. `None` when the arguments do not fit.
4417fn inline_table_function(
4418    definition: &TableFunction,
4419    call: &Function,
4420    counter: &mut usize,
4421) -> Option<Query> {
4422    let mut body = definition.body.clone();
4423    let mut bound: IndexMap<String, FunctionArg> = IndexMap::new();
4424    let mut position = 0;
4425    for argument in &call.args {
4426        match argument {
4427            FunctionArg::Expr(Expr::NamedArg { name, value }) => {
4428                bound.insert(
4429                    name.value.to_lowercase(),
4430                    FunctionArg::Expr((**value).clone()),
4431                );
4432            }
4433            other => {
4434                let (name, _, _) = definition.params.get(position)?;
4435                bound.insert(name.to_lowercase(), other.clone());
4436                position += 1;
4437            }
4438        }
4439    }
4440    let declared: HashSet<String> = definition
4441        .params
4442        .iter()
4443        .filter(|(_, is_table, _)| *is_table)
4444        .flat_map(|(_, _, cols)| cols.iter().map(|c| c.to_lowercase()))
4445        .collect();
4446    let mut ctes = Vec::new();
4447    for (name, is_table, _) in &definition.params {
4448        let argument = bound.get(&name.to_lowercase())?.clone();
4449        if *is_table {
4450            let source: Query = match argument {
4451                FunctionArg::Table(table) => Query::from_body(SetExpr::Select(Box::new(Select {
4452                    from: vec![TableWithJoins::table(table)],
4453                    ..Select::new(vec![SelectItem::Wildcard(WildcardOptions::default())])
4454                }))),
4455                FunctionArg::Expr(Expr::Subquery(q)) => *q,
4456                FunctionArg::Expr(Expr::Identifier(ident)) => {
4457                    Query::from_body(SetExpr::Select(Box::new(Select {
4458                        from: vec![TableWithJoins::table(ObjectName(vec![ident]))],
4459                        ..Select::new(vec![SelectItem::Wildcard(WildcardOptions::default())])
4460                    })))
4461                }
4462                _ => return None,
4463            };
4464            *counter += 1;
4465            let alias = format!("__tvf_{counter}_{name}");
4466            body.visit_tables_mut(&mut |factor, is_cte| {
4467                if is_cte {
4468                    return;
4469                }
4470                if let TableFactor::Table {
4471                    name: table,
4472                    alias: table_alias,
4473                    ..
4474                } = factor
4475                {
4476                    let t = table.table_name();
4477                    if t.dataset.is_none()
4478                        && t.project.is_none()
4479                        && t.name.eq_ignore_ascii_case(name)
4480                    {
4481                        *table = ObjectName(vec![Ident::new(alias.clone())]);
4482                        if table_alias.is_none() {
4483                            *table_alias = Some(Ident::new(name.clone())); // `t.k` in the body still resolves
4484                        }
4485                    }
4486                }
4487            });
4488            ctes.push(Cte {
4489                name: Ident::new(alias),
4490                query: Box::new(source),
4491            });
4492        } else if !declared.contains(&name.to_lowercase()) {
4493            let FunctionArg::Expr(value) = argument else {
4494                return None;
4495            };
4496            let replacement = match value {
4497                Expr::Literal(_) | Expr::Identifier(_) | Expr::CompoundIdentifier(_) => value,
4498                other => Expr::Nested(Box::new(other)),
4499            };
4500            walk_query_exprs_mut(&mut body, &mut |e| {
4501                if let Expr::Identifier(ident) = e {
4502                    if ident.value.eq_ignore_ascii_case(name) {
4503                        *e = replacement.clone();
4504                    }
4505                }
4506            });
4507        }
4508    }
4509    if !ctes.is_empty() {
4510        match &mut body.with {
4511            Some(with) => {
4512                ctes.append(&mut with.ctes);
4513                with.ctes = ctes;
4514            }
4515            None => {
4516                body.with = Some(With {
4517                    recursive: false,
4518                    ctes,
4519                })
4520            }
4521        }
4522    }
4523    Some(body)
4524}
4525
4526/// Split `text` and follow what each statement reads and writes. Never fails.
4527pub fn analyse_script(text: &str) -> ScriptAnalysis {
4528    analyse_script_with(text, &IndexMap::new(), &IndexMap::new())
4529}
4530
4531/// [`analyse_script`] with procedures and table functions defined elsewhere in the project.
4532pub fn analyse_script_with(
4533    text: &str,
4534    procedures: &IndexMap<String, Procedure>,
4535    functions: &IndexMap<String, TableFunction>,
4536) -> ScriptAnalysis {
4537    let mut run = Run::new(
4538        ScriptAnalysis::new(text),
4539        procedures.clone(),
4540        functions.clone(),
4541    );
4542    run.run(text);
4543    run.a
4544}
4545
4546// ------------------------------------------------------------------------ jobs
4547
4548/// A table in a script's hidden dataset (`_script...`, `_session`, anonymous results).
4549pub fn is_temporary_reference(reference: &serde_json::Value) -> bool {
4550    let (_, dataset, table) = reference_parts(reference);
4551    (!dataset.is_empty() && dataset.starts_with('_')) || (dataset.is_empty() && !table.is_empty())
4552}
4553
4554fn reference_parts(reference: &serde_json::Value) -> (String, String, String) {
4555    if let Some(map) = reference.as_object() {
4556        let get = |keys: &[&str]| -> String {
4557            keys.iter()
4558                .find_map(|k| {
4559                    map.get(*k)
4560                        .and_then(|v| v.as_str())
4561                        .filter(|s| !s.is_empty())
4562                })
4563                .unwrap_or("")
4564                .to_string()
4565        };
4566        return (
4567            get(&["projectId", "project_id", "project"]),
4568            get(&["datasetId", "dataset_id", "dataset"]),
4569            get(&["tableId", "table_id", "table"]),
4570        );
4571    }
4572    let text = reference
4573        .as_str()
4574        .map(str::to_string)
4575        .unwrap_or_default()
4576        .replace('`', "");
4577    let mut parts: Vec<String> = text
4578        .split('.')
4579        .filter(|p| !p.is_empty())
4580        .map(str::to_string)
4581        .collect();
4582    while parts.len() < 3 {
4583        parts.insert(0, String::new());
4584    }
4585    let n = parts.len();
4586    (
4587        parts[n - 3].clone(),
4588        parts[n - 2].clone(),
4589        parts[n - 1].clone(),
4590    )
4591}
4592
4593fn reference_key(reference: &serde_json::Value) -> String {
4594    let (p, d, t) = reference_parts(reference);
4595    format!("{p}.{d}.{t}")
4596}
4597
4598/// Job-history records with script jobs reduced to the real tables they read and wrote.
4599///
4600/// Statements of a BigQuery script write temporary tables later statements read; a record that
4601/// reads or writes one is replaced by what the temporary table was built from. A script's parent
4602/// job with children is dropped; a script job with query text but no children is read with
4603/// [`analyse_script`]. Returns `(records, summary)` with counts only.
4604pub fn expand_script_jobs(
4605    records: &[serde_json::Value],
4606) -> (Vec<serde_json::Value>, serde_json::Value) {
4607    use serde_json::{json, Value};
4608    let rows: Vec<serde_json::Map<String, Value>> = records
4609        .iter()
4610        .filter_map(|r| r.as_object().cloned())
4611        .collect();
4612    let mut summary: IndexMap<&str, usize> = [
4613        ("scripts", 0),
4614        ("child_jobs", 0),
4615        ("temporary_tables_followed", 0),
4616        ("parents_dropped", 0),
4617        ("scripts_read_from_text", 0),
4618        ("records_added", 0),
4619        ("unreadable_scripts", 0),
4620    ]
4621    .into_iter()
4622    .collect();
4623    let mut by_parent: IndexMap<String, Vec<usize>> = IndexMap::new();
4624    for (index, row) in rows.iter().enumerate() {
4625        if let Some(parent) = row
4626            .get("parent_job_id")
4627            .and_then(|p| p.as_str())
4628            .filter(|p| !p.is_empty())
4629        {
4630            by_parent.entry(parent.to_string()).or_default().push(index);
4631        }
4632    }
4633    let mut drop: HashSet<usize> = HashSet::new();
4634    let mut out: IndexMap<usize, serde_json::Map<String, Value>> = IndexMap::new();
4635    for indices in by_parent.values() {
4636        *summary.get_mut("scripts").expect("key") += 1;
4637        *summary.get_mut("child_jobs").expect("key") += indices.len();
4638        let mut ordered = indices.clone();
4639        ordered.sort_by_key(|&i| {
4640            (
4641                rows[i]
4642                    .get("creation_time")
4643                    .map(|v| v.to_string())
4644                    .unwrap_or_default(),
4645                i,
4646            )
4647        });
4648        let mut built: IndexMap<String, IndexSet<String>> = IndexMap::new();
4649        for i in ordered {
4650            let mut row = rows[i].clone();
4651            let refs = row
4652                .get("referenced_tables")
4653                .or_else(|| row.get("references"))
4654                .cloned()
4655                .unwrap_or(Value::Null);
4656            let refs: Vec<Value> = match refs {
4657                Value::Array(items) => items,
4658                Value::Null => Vec::new(),
4659                other => vec![other],
4660            };
4661            let mut expanded: Vec<Value> = Vec::new();
4662            let mut seen: HashSet<String> = HashSet::new();
4663            for reference in refs {
4664                let key = reference_key(&reference);
4665                if is_temporary_reference(&reference) {
4666                    let mut sources: Vec<&String> = built
4667                        .get(&key)
4668                        .map(|s| s.iter().collect())
4669                        .unwrap_or_default();
4670                    sources.sort();
4671                    for source in sources {
4672                        if seen.insert(source.clone()) {
4673                            expanded.push(Value::String(source.clone()));
4674                        }
4675                    }
4676                } else if seen.insert(key) {
4677                    expanded.push(reference);
4678                }
4679            }
4680            let destination = row
4681                .get("destination")
4682                .or_else(|| row.get("destination_table"))
4683                .cloned();
4684            if let Some(dest) = destination.filter(|d| !d.is_null() && is_temporary_reference(d)) {
4685                let entry = built.entry(reference_key(&dest)).or_default();
4686                for r in &expanded {
4687                    entry.insert(reference_key(r));
4688                }
4689                drop.insert(i);
4690                *summary.get_mut("temporary_tables_followed").expect("key") += 1;
4691                continue;
4692            }
4693            row.insert("referenced_tables".into(), Value::Array(expanded));
4694            row.remove("references");
4695            out.insert(i, row);
4696        }
4697    }
4698    let mut result = Vec::new();
4699    let dml = ["MERGE", "INSERT", "UPDATE", "DELETE"];
4700    for (index, original) in rows.iter().enumerate() {
4701        if drop.contains(&index) {
4702            continue;
4703        }
4704        let job_id = original
4705            .get("job_id")
4706            .and_then(|v| v.as_str())
4707            .unwrap_or("")
4708            .to_string();
4709        let statement_type = original
4710            .get("statement_type")
4711            .and_then(|v| v.as_str())
4712            .unwrap_or("")
4713            .to_uppercase();
4714        if !job_id.is_empty() && by_parent.contains_key(&job_id) && statement_type == "SCRIPT" {
4715            *summary.get_mut("parents_dropped").expect("key") += 1;
4716            continue;
4717        }
4718        let row = out.get(&index).cloned().unwrap_or_else(|| original.clone());
4719        let text = row
4720            .get("query")
4721            .or_else(|| row.get("query_text"))
4722            .and_then(|v| v.as_str())
4723            .map(str::to_string);
4724        let nonempty = |v: Option<&Value>| {
4725            v.is_some_and(|v| {
4726                !(v.is_null() || v.as_array().is_some_and(Vec::is_empty) || v.as_str() == Some(""))
4727            })
4728        };
4729        let has_edges = (nonempty(row.get("referenced_tables")) || nonempty(row.get("references")))
4730            && (nonempty(row.get("destination")) || nonempty(row.get("destination_table")));
4731        let readable = text.is_some()
4732            && !has_edges
4733            && !nonempty(row.get("parent_job_id"))
4734            && (statement_type == "SCRIPT" || dml.contains(&statement_type.as_str()))
4735            && !row
4736                .get("query_truncated")
4737                .and_then(Value::as_bool)
4738                .unwrap_or(false)
4739            && !by_parent.contains_key(&job_id);
4740        if !readable {
4741            result.push(Value::Object(row));
4742            continue;
4743        }
4744        let analysis = analyse_script(text.as_deref().unwrap_or(""));
4745        let writes: Vec<&ScriptWrite> = analysis
4746            .writes
4747            .iter()
4748            .filter(|w| !w.table.name.is_empty())
4749            .collect();
4750        if dml.contains(&statement_type.as_str()) {
4751            *summary.entry("dml_read_from_text").or_insert(0) += 1;
4752            if writes.len() != 1 {
4753                *summary.get_mut("unreadable_scripts").expect("key") += 1;
4754                result.push(Value::Object(row));
4755                continue;
4756            }
4757            let mut added = row.clone();
4758            let dest = writes[0].table.dotted();
4759            added.insert("destination".into(), dest.clone().into());
4760            added.insert("destination_table".into(), dest.into());
4761            added.insert(
4762                "referenced_tables".into(),
4763                Value::Array(
4764                    writes[0]
4765                        .sources
4766                        .iter()
4767                        .map(|t| Value::String(t.dotted()))
4768                        .collect(),
4769                ),
4770            );
4771            result.push(Value::Object(added));
4772            *summary.get_mut("records_added").expect("key") += 1;
4773            continue;
4774        }
4775        *summary.get_mut("scripts_read_from_text").expect("key") += 1;
4776        if writes.is_empty() {
4777            *summary.get_mut("unreadable_scripts").expect("key") += 1;
4778            result.push(Value::Object(row));
4779            continue;
4780        }
4781        for (number, write) in writes.iter().enumerate() {
4782            let mut added = row.clone();
4783            let id = if job_id.is_empty() {
4784                format!("script#{}", number + 1)
4785            } else {
4786                format!("{job_id}#{}", number + 1)
4787            };
4788            added.insert("job_id".into(), id.into());
4789            added.insert("destination".into(), write.table.dotted().into());
4790            added.insert("destination_table".into(), write.table.dotted().into());
4791            added.insert(
4792                "referenced_tables".into(),
4793                Value::Array(
4794                    write
4795                        .sources
4796                        .iter()
4797                        .map(|t| Value::String(t.dotted()))
4798                        .collect(),
4799                ),
4800            );
4801            added.insert("statement_type".into(), "SCRIPT".into());
4802            result.push(Value::Object(added));
4803            *summary.get_mut("records_added").expect("key") += 1;
4804        }
4805    }
4806    let summary = json!(summary
4807        .into_iter()
4808        .collect::<std::collections::BTreeMap<_, _>>());
4809    (result, summary)
4810}
4811
4812/// The compact SQL of an analysis's final query with its temporary tables spliced in.
4813pub fn final_sql(analysis: &ScriptAnalysis) -> Option<String> {
4814    analysis
4815        .final_query_with_temps()
4816        .map(|q| to_sql_compact(&Statement::Query(Box::new(q))))
4817}