kumosql-sql 0.2.0

BigQuery/GoogleSQL lexer, parser, AST, printer, formatter, complexity scoring, read-only validation, Dataform SQLX handling and script analysis for KumoSQL-Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
//! Dataform SQLX handling shared by every reader and rewrite.
//!
//! Mirrors `kumo_sql_prover.sqlx` and `sqlx_fragments`. A SQLX file splits into `config`, `js`,
//! `pre_operations`, `post_operations` and `input "name"` blocks (kept byte for byte) and SQL
//! sections. `${...}` interpolations in SQL are masked with SQL-safe sentinels for parsing and
//! restored afterwards; a restore that finds a sentinel lost or duplicated fails rather than
//! producing different SQL.
//!
//! Dataform leaves a `${...}` inside a `--` or `/* */` comment as text, so those are never masked
//! or read as references. A `#` comment is not one of them: `@dataform/cli` 3.0.71 evaluates
//! `${ref(...)}` after `#`.

use std::sync::OnceLock;

use indexmap::IndexMap;
use regex::{Match, Regex};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::error::{Result, SqlError};
use crate::js::{parse_lenient, skip_js_braces, skip_js_string, JsValue};
use crate::token::{tokenize, Span, TokenKind};

// ------------------------------------------------------------------------ detection

fn block_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(
            r#"(?im)^[ \t]*(?:(config|js|pre_operations|post_operations)|input\s+(?:"([^"\n]*)"|'([^'\n]*)'))\s*\{"#,
        )
        .expect("valid regex")
    })
}

/// Whether `text` looks like Dataform SQLX: it has a block (`config {`, `js {`, ...) at the start
/// of a line, or a `${` anywhere.
pub fn looks_like_sqlx(text: &str) -> bool {
    block_re().is_match(text) || text.contains("${")
}

/// File text from bytes: UTF-8 with any byte-order mark dropped (it would hide a leading config
/// block), else Windows-1252.
pub fn decode_sqlx_bytes(bytes: &[u8]) -> String {
    let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
    match std::str::from_utf8(body) {
        Ok(text) => text.to_string(),
        Err(_) => {
            let (text, _) = encoding_rs::WINDOWS_1252.decode_without_bom_handling(body);
            text.into_owned()
        }
    }
}

// ------------------------------------------------------------------------ sections

/// What a section of a SQLX file is.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SqlxSectionKind {
    Sql,
    Config,
    Js,
    PreOperations,
    PostOperations,
    /// `input "name" { ... }` of a Dataform test.
    Input(String),
}

/// One section with its exact text and where it sits in the file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SqlxSection {
    pub kind: SqlxSectionKind,
    pub text: String,
    pub span: Span,
}

impl SqlxSection {
    pub fn is_block(&self) -> bool {
        self.kind != SqlxSectionKind::Sql
    }

    /// A block's text between its outer braces; a SQL section's whole text.
    pub fn body(&self) -> &str {
        if !self.is_block() {
            return &self.text;
        }
        match (self.text.find('{'), self.text.rfind('}')) {
            (Some(open), Some(close)) if close > open => &self.text[open + 1..close],
            _ => "",
        }
    }
}

/// The closing brace of the SQLX block opening at `opening`. Strings, `--`, `/* */` and `//`
/// comments are skipped: a JavaScript comment's apostrophes and braces are not code.
fn find_balanced_brace(text: &str, opening: usize) -> Result<usize> {
    let bytes = text.as_bytes();
    let mut depth = 1;
    let mut index = opening + 1;
    let mut quote: Option<u8> = None;
    let mut line_comment = false;
    let mut block_comment = false;
    while index < bytes.len() {
        let c = bytes[index];
        let next = bytes.get(index + 1).copied().unwrap_or(0);
        if line_comment {
            if c == b'\r' || c == b'\n' {
                line_comment = false;
            }
        } else if block_comment {
            if c == b'*' && next == b'/' {
                block_comment = false;
                index += 1;
            }
        } else if let Some(q) = quote {
            if c == b'\\' {
                index += 1;
            } else if c == q {
                if next == q {
                    index += 1;
                } else {
                    quote = None;
                }
            }
        } else if (c == b'-' && next == b'-') || (c == b'/' && next == b'/') {
            line_comment = true;
            index += 1;
        } else if c == b'/' && next == b'*' {
            block_comment = true;
            index += 1;
        } else if c == b'\'' || c == b'"' || c == b'`' {
            quote = Some(c);
        } else if c == b'{' {
            depth += 1;
        } else if c == b'}' {
            depth -= 1;
            if depth == 0 {
                return Ok(index);
            }
        }
        index += 1;
    }
    Err(SqlError::Sqlx("unterminated SQLX block".to_string()))
}

/// Split SQLX into SQL sections and blocks, in order. The result always ends with a SQL section
/// (possibly empty), and joining the texts gives back the input.
pub fn split_sqlx_sections(text: &str) -> Result<Vec<SqlxSection>> {
    let mut pieces = Vec::new();
    let mut cursor = 0;
    while let Some(caps) = block_re().captures_at(text, cursor) {
        let whole = caps.get(0).expect("match");
        if whole.start() > cursor {
            pieces.push(SqlxSection {
                kind: SqlxSectionKind::Sql,
                text: text[cursor..whole.start()].to_string(),
                span: Span::new(cursor, whole.start()),
            });
        }
        let kind = match caps.get(1).map(|m| m.as_str().to_ascii_lowercase()) {
            Some(word) => match word.as_str() {
                "config" => SqlxSectionKind::Config,
                "js" => SqlxSectionKind::Js,
                "pre_operations" => SqlxSectionKind::PreOperations,
                _ => SqlxSectionKind::PostOperations,
            },
            None => SqlxSectionKind::Input(
                caps.get(2)
                    .or(caps.get(3))
                    .map_or(String::new(), |m| m.as_str().to_string()),
            ),
        };
        let opening = whole.end() - 1;
        let closing = find_balanced_brace(text, opening)?;
        pieces.push(SqlxSection {
            kind,
            text: text[whole.start()..=closing].to_string(),
            span: Span::new(whole.start(), closing + 1),
        });
        cursor = closing + 1;
    }
    pieces.push(SqlxSection {
        kind: SqlxSectionKind::Sql,
        text: text[cursor..].to_string(),
        span: Span::new(cursor, text.len()),
    });
    Ok(pieces)
}

// ------------------------------------------------------------------------ comments

/// The closing `}` of the `${` at `opening`.
fn find_interpolation_end(text: &str, opening: usize) -> Result<usize> {
    let bytes = text.as_bytes();
    let mut depth = 1;
    let mut index = opening + 2;
    let mut quote: Option<u8> = None;
    while index < bytes.len() {
        let c = bytes[index];
        let next = bytes.get(index + 1).copied().unwrap_or(0);
        if let Some(q) = quote {
            if c == b'\\' {
                index += 1;
            } else if c == q {
                if next == q {
                    index += 1;
                } else {
                    quote = None;
                }
            }
        } else if c == b'\'' || c == b'"' || c == b'`' {
            quote = Some(c);
        } else if c == b'{' {
            depth += 1;
        } else if c == b'}' {
            depth -= 1;
            if depth == 0 {
                return Ok(index);
            }
        }
        index += 1;
    }
    Err(SqlError::Sqlx(
        "unterminated SQLX interpolation".to_string(),
    ))
}

/// `(start, end)` of every `--` and `/* */` comment in SQL.
///
/// Dataform leaves a `${...}` inside these as text. A `#` comment is not one of them, nor is a
/// `--` inside a string. Quotes inside a comment do not open a string, and comment markers inside
/// a string or a `${...}` do not open a comment. An unterminated block comment runs to the end.
pub fn sql_comment_spans(sql: &str) -> Vec<(usize, usize)> {
    let bytes = sql.as_bytes();
    let size = bytes.len();
    let mut spans = Vec::new();
    let mut index = 0;
    while index < size {
        let c = bytes[index];
        if sql[index..].starts_with("${") {
            match find_interpolation_end(sql, index) {
                Ok(end) => index = end + 1,
                Err(_) => return spans,
            }
        } else if sql[index..].starts_with("--") {
            let mut end = index;
            while end < size && bytes[end] != b'\r' && bytes[end] != b'\n' {
                end += 1;
            }
            spans.push((index, end));
            index = end;
        } else if sql[index..].starts_with("/*") {
            let end = sql[index + 2..]
                .find("*/")
                .map_or(size, |e| index + 2 + e + 2);
            spans.push((index, end));
            index = end;
        } else if c == b'\'' || c == b'"' || c == b'`' {
            let triple = &sql[index..(index + 3).min(size)];
            let quote: &str = if triple == "'''" || triple == "\"\"\"" {
                triple
            } else {
                &sql[index..index + 1]
            };
            let quote = quote.to_string();
            index += quote.len();
            while index < size && !sql[index..].starts_with(quote.as_str()) {
                if sql[index..].starts_with("${") {
                    match find_interpolation_end(sql, index) {
                        Ok(end) => {
                            index = end + 1;
                            continue;
                        }
                        Err(_) => return spans,
                    }
                }
                index += if bytes[index] == b'\\' { 2 } else { 1 };
            }
            index += quote.len();
        } else {
            index += 1;
        }
    }
    spans
}

fn in_spans(spans: &[(usize, usize)], at: usize) -> bool {
    spans.iter().any(|(s, e)| *s <= at && at < *e)
}

/// The matches of `pattern` in `sql` that do not start inside a `--` or `/* */` comment.
pub fn outside_sql_comments<'t>(sql: &'t str, pattern: &Regex) -> Vec<Match<'t>> {
    let spans = sql_comment_spans(sql);
    pattern
        .find_iter(sql)
        .filter(|m| !in_spans(&spans, m.start()))
        .collect()
}

/// `sql` with each `${` inside a `--` or `/* */` comment written `$ {`, so it is never read as an
/// interpolation (Dataform does not evaluate it).
pub fn defuse_comment_templates(sql: &str) -> String {
    if !sql.contains("${") {
        return sql.to_string();
    }
    let mut out = String::with_capacity(sql.len());
    let mut cursor = 0;
    for (start, end) in sql_comment_spans(sql) {
        out.push_str(&sql[cursor..start]);
        out.push_str(&sql[start..end].replace("${", "$ {"));
        cursor = end;
    }
    out.push_str(&sql[cursor..]);
    out
}

// ------------------------------------------------------------------------ masking

/// How to put one interpolation back.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SqlxRestoration {
    /// The sentinel standing for it in the masked SQL (`__sqlx_token_000__`).
    pub token: String,
    /// The interpolation as written (`${ref("t")}`).
    pub original: String,
    /// A regex for the sentinel with the SQL written around it (`WHERE __sqlx_token_000__`).
    pub pattern: String,
    /// The sentinel stands for the interpolation together with SQL around it: restoring it
    /// anywhere else would change the meaning.
    pub whole: bool,
    /// Where the interpolation was in the input.
    pub span: Span,
}

/// A Dataform function called in an interpolation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RefFunction {
    Ref,
    Resolve,
    SelfRef,
    When,
}

/// A literal `ref`/`resolve` target.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct RefTarget {
    pub database: Option<String>,
    pub schema: Option<String>,
    pub name: String,
}

/// One `ref(...)`, `resolve(...)`, `self()` or `when(...)` call in a masked interpolation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RefCall {
    pub function: RefFunction,
    /// The arguments; computed ones are [`JsValue::Expression`].
    pub args: Vec<JsValue>,
    /// The call as written (`ref("ds", "t")`).
    pub text: String,
    /// The sentinel of the interpolation the call is in.
    pub token: String,
    /// Inside another call's arguments (`when(incremental(), `... ${self()}`)`).
    pub nested: bool,
}

impl RefCall {
    /// The table a `ref`/`resolve` names when every argument is a literal: `("t")`,
    /// `("schema", "t")`, `("db", "schema", "t")` or `({database, schema, name})`.
    pub fn target(&self) -> Option<RefTarget> {
        if !matches!(self.function, RefFunction::Ref | RefFunction::Resolve) {
            return None;
        }
        match self.args.as_slice() {
            [JsValue::String(name)] => Some(RefTarget {
                name: name.clone(),
                ..RefTarget::default()
            }),
            [JsValue::String(schema), JsValue::String(name)] => Some(RefTarget {
                schema: Some(schema.clone()),
                name: name.clone(),
                ..RefTarget::default()
            }),
            [JsValue::String(db), JsValue::String(schema), JsValue::String(name)] => {
                Some(RefTarget {
                    database: Some(db.clone()),
                    schema: Some(schema.clone()),
                    name: name.clone(),
                })
            }
            [JsValue::Object(map)] => {
                let name = map.get("name")?.as_str()?.to_string();
                let field = |key: &str| -> Option<Option<String>> {
                    match map.get(key) {
                        None => Some(None),
                        Some(JsValue::String(s)) => Some(Some(s.clone())),
                        Some(_) => None,
                    }
                };
                Some(RefTarget {
                    database: field("database")?.or(field("project")?),
                    schema: field("schema")?.or(field("dataset")?),
                    name,
                })
            }
            _ => None,
        }
    }
}

/// SQL with its interpolations replaced by sentinels.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MaskedSqlx {
    /// The input as given.
    pub original: String,
    /// The SQL with sentinels in place of interpolations.
    pub masked: String,
    pub restorations: Vec<SqlxRestoration>,
    /// Every Dataform call found in the masked interpolations.
    pub refs: Vec<RefCall>,
}

impl MaskedSqlx {
    /// Sentinels of interpolations that are not single relation references
    /// (see [`is_table_reference`]): they can compile to any SQL.
    pub fn opaque_tokens(&self) -> Vec<String> {
        self.restorations
            .iter()
            .filter(|r| !is_table_reference(&r.original))
            .map(|r| r.token.clone())
            .collect()
    }
}

fn when_connective_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r#"(?i)^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*[`'"]\s*(AND|OR)\b"#)
            .expect("valid regex")
    })
}

fn when_trailing_re() -> &'static Regex {
    // `(?P<q>[`'"])(?:(?!(?P=q))[^$])*?\b(AND|OR)\s*(?P=q)` without back-references: one branch per quote
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        let head = r"^\s*when\s*\([^,()]*(?:\([^()]*\))?[^,()]*,\s*";
        let tail = r"\s*\)\s*$";
        let branch = |q: &str| format!("{head}{q}[^{q}$]*?\\b(AND|OR)\\s*{q}{tail}");
        Regex::new(&format!(
            "(?i)(?:{})|(?:{})|(?:{})",
            branch("`"),
            branch("'"),
            branch("\"")
        ))
        .expect("valid regex")
    })
}

fn clause_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?i)\b(WHERE|QUALIFY|HAVING|ORDER\s+BY)\b").expect("valid regex")
    })
}

fn preceding_clause_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?i)\b(?:WHERE|QUALIFY|HAVING|ORDER\s+BY)\s*$").expect("valid regex")
    })
}

fn preceding_condition_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"(?i)\b(?:AND|OR)\s*$").expect("valid regex"))
}

/// Replace every `${...}` outside `--`/`/* */` comments with a SQL-safe sentinel and record how
/// to restore it. An interpolation that opens or continues a condition
/// (`${when(incremental(), "WHERE x > 1")}`) is masked with the clause keyword beside it so the
/// masked text still parses.
pub fn mask_sqlx(sql: &str) -> Result<MaskedSqlx> {
    let comments = sql_comment_spans(sql);
    let mut output = String::with_capacity(sql.len());
    let mut restorations = Vec::new();
    let mut refs = Vec::new();
    let mut cursor = 0;
    let mut ordinal = 0usize;
    loop {
        let mut search = cursor;
        let opening = loop {
            match sql[search..].find("${") {
                None => break None,
                Some(found) => {
                    let at = search + found;
                    if in_spans(&comments, at) {
                        search = at + 2;
                        continue;
                    }
                    break Some(at);
                }
            }
        };
        let Some(opening) = opening else {
            output.push_str(&sql[cursor..]);
            break;
        };
        output.push_str(&sql[cursor..opening]);
        let closing = find_interpolation_end(sql, opening)?;
        let original = &sql[opening..=closing];
        let mut token = format!("__sqlx_token_{ordinal:03}__");
        while sql.contains(&token) {
            ordinal += 1;
            token = format!("__sqlx_token_{ordinal:03}__");
        }
        ordinal += 1;

        let prefix = output.trim_end();
        let body = &original[2..original.len() - 1];
        let clause = clause_re().captures(body);
        let preceding_clause = preceding_clause_re().is_match(prefix);
        let preceding_condition = preceding_condition_re().is_match(prefix);
        let escaped = regex::escape(&token);
        let mut replacement = token.clone();
        let mut pattern = escaped.clone();
        let mut whole = false;
        let trailing = when_trailing_re().captures(body);
        let connective = when_connective_re().captures(body);
        if let (Some(t), true) = (&trailing, preceding_clause || preceding_condition) {
            let keyword = (1..=3)
                .find_map(|g| t.get(g))
                .map_or("AND".to_string(), |m| m.as_str().to_ascii_uppercase());
            replacement = format!("{token} {keyword}");
            pattern = format!(r"(?i)\b{escaped}\s+{keyword}\b");
            whole = true;
        } else if let (Some(c), None, false, false) =
            (&connective, &clause, preceding_clause, preceding_condition)
        {
            let keyword = c[1].to_ascii_uppercase();
            replacement = format!("{keyword} {token}");
            pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
        } else if let (Some(c), false, false) = (&clause, preceding_clause, preceding_condition) {
            let keyword = c[1].to_ascii_uppercase();
            if keyword.starts_with("ORDER") {
                replacement = format!("ORDER BY {token}");
                pattern = format!(r"(?i)\bORDER\s+BY\s+{escaped}\b");
            } else {
                replacement = format!("{keyword} {token}");
                pattern = format!(r"(?i)\b{keyword}\s+{escaped}\b");
            }
        }
        output.push_str(&replacement);
        scan_calls(body, &token, 0, &mut refs);
        restorations.push(SqlxRestoration {
            token,
            original: original.to_string(),
            pattern,
            whole,
            span: Span::new(opening, closing + 1),
        });
        cursor = closing + 1;
    }
    Ok(MaskedSqlx {
        original: sql.to_string(),
        masked: output,
        restorations,
        refs,
    })
}

/// Put the interpolations back into `rewritten` (a rewrite of `masked.masked`). Fails when a
/// sentinel was lost or duplicated, or separated from the connective it stands with.
pub fn restore_sqlx(masked: &MaskedSqlx, rewritten: &str) -> Result<String> {
    restore_sqlx_interpolations(rewritten, &masked.restorations)
}

/// [`restore_sqlx`] from the restorations alone.
pub fn restore_sqlx_interpolations(sql: &str, restorations: &[SqlxRestoration]) -> Result<String> {
    for item in restorations {
        let count = sql.matches(item.token.as_str()).count();
        if count != 1 {
            return Err(SqlError::SqlxRestoration(format!(
                "SQLX interpolation placeholder was lost or duplicated during rewriting ({count} copies found; expected one)"
            )));
        }
    }
    let mut restored = sql.to_string();
    for item in restorations {
        let pattern = Regex::new(&item.pattern)
            .map_err(|e| SqlError::SqlxRestoration(format!("bad restoration pattern: {e}")))?;
        if item.whole && pattern.find_iter(&restored).count() != 1 {
            return Err(SqlError::SqlxRestoration(
                "a rewrite separated a SQLX interpolation from the connective it ends with"
                    .to_string(),
            ));
        }
        // a printer may quote an identifier sentinel inside a table path: restore that spelling first
        restored = restored.replace(&format!("`{}`", item.token), &item.original);
        restored = pattern
            .replace_all(&restored, regex::NoExpand(&item.original))
            .into_owned();
        restored = restored.replace(&item.token, &item.original);
    }
    Ok(restored)
}

/// Find Dataform calls in JavaScript `text` (an interpolation's body), descending into template
/// literals' `${...}` parts and into call arguments.
fn scan_calls(text: &str, token: &str, depth: usize, out: &mut Vec<RefCall>) {
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        match c {
            b'\'' | b'"' => match skip_js_string(text, i) {
                Some(end) => i = end,
                None => return,
            },
            b'`' => {
                // walk the template, scanning each `${...}` as code
                let mut j = i + 1;
                while j < bytes.len() && bytes[j] != b'`' {
                    if bytes[j] == b'\\' {
                        j += 2;
                        continue;
                    }
                    if bytes[j] == b'$' && bytes.get(j + 1) == Some(&b'{') {
                        let Some(end) = skip_js_braces(text, j + 1) else {
                            return;
                        };
                        scan_calls(&text[j + 2..end - 1], token, depth, out);
                        j = end;
                        continue;
                    }
                    j += 1;
                }
                i = j + 1;
            }
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i = text[i + 2..]
                    .find("*/")
                    .map_or(bytes.len(), |e| i + 2 + e + 2);
            }
            c if c.is_ascii_alphabetic() || c == b'_' || c == b'$' => {
                let start = i;
                while i < bytes.len()
                    && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_' || bytes[i] == b'$')
                {
                    i += 1;
                }
                let word = &text[start..i];
                let before = text[..start].trim_end();
                let member_of_ctx = before.ends_with("ctx.");
                let is_member = before.ends_with('.') && !member_of_ctx;
                let function = match word {
                    "ref" => Some(RefFunction::Ref),
                    "resolve" => Some(RefFunction::Resolve),
                    "self" => Some(RefFunction::SelfRef),
                    "when" => Some(RefFunction::When),
                    _ => None,
                };
                let after = text[i..].trim_start();
                if let (Some(function), false, true) = (function, is_member, after.starts_with('('))
                {
                    let open = i + (text[i..].len() - after.len());
                    if let Some(close) = skip_js_braces(text, open) {
                        let args_text = &text[open + 1..close - 1];
                        out.push(RefCall {
                            function,
                            args: parse_arguments(args_text),
                            text: text[start..close].to_string(),
                            token: token.to_string(),
                            nested: depth > 0,
                        });
                        scan_calls(args_text, token, depth + 1, out);
                        i = close;
                    }
                }
            }
            _ => i += 1,
        }
    }
}

/// Call arguments read leniently: literals as values, anything else as an expression.
fn parse_arguments(text: &str) -> Vec<JsValue> {
    let mut args = Vec::new();
    let mut pos = 0;
    loop {
        let rest = &text[pos..];
        if rest.trim().is_empty() {
            break;
        }
        let Some((value, end)) = parse_lenient(text, pos) else {
            args.push(JsValue::Expression(rest.trim().to_string()));
            break;
        };
        args.push(value);
        let after = &text[end..];
        let trimmed = after.trim_start();
        if let Some(next) = trimmed.strip_prefix(',') {
            pos = text.len() - next.len();
        } else {
            break;
        }
    }
    args
}

fn quoted() -> &'static str {
    r#"(?:"[^"\\]*"|'[^'\\]*'|`[^`\\]*`)"#
}

fn table_reference_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        let q = quoted();
        Regex::new(&format!(
            r"^\$\{{\s*(?:(?:ref|resolve)\s*\(\s*{q}(?:\s*,\s*{q})?\s*\)|self\s*\(\s*\))\s*\}}$"
        ))
        .expect("valid regex")
    })
}

/// `${ref("t")}`, `${ref("dataset", "t")}`, `${resolve("t")}` or `${self()}`: one table name once compiled.
pub fn is_table_reference(original: &str) -> bool {
    table_reference_re().is_match(original)
}

/// Whether a `${...}` always expands to exactly one table or view name: `self()`, or one
/// `ref(...)`/`resolve(...)` call whose closing parenthesis ends the expression, with no template
/// literal, comment, `/` or backslash in its arguments.
pub fn is_relation_reference(interpolation: &str) -> bool {
    static SELF_RE: OnceLock<Regex> = OnceLock::new();
    static CALL_RE: OnceLock<Regex> = OnceLock::new();
    static CLOSE_RE: OnceLock<Regex> = OnceLock::new();
    let self_re =
        SELF_RE.get_or_init(|| Regex::new(r"^\$\{\s*self\(\s*\)\s*\}$").expect("valid regex"));
    let call_re =
        CALL_RE.get_or_init(|| Regex::new(r"^\$\{\s*(?:ref|resolve)\s*\(").expect("valid regex"));
    let close_re = CLOSE_RE.get_or_init(|| Regex::new(r"^\s*\}$").expect("valid regex"));
    if self_re.is_match(interpolation) {
        return true;
    }
    let Some(call) = call_re.find(interpolation) else {
        return false;
    };
    let mut depth = 1;
    let mut quote: Option<char> = None;
    for (index, c) in interpolation[call.end()..].char_indices() {
        let at = call.end() + index;
        if "`/\\".contains(c) || (quote.is_some() && c == '\n') {
            return false;
        }
        if let Some(q) = quote {
            if c == q {
                quote = None;
            }
        } else if c == '\'' || c == '"' {
            quote = Some(c);
        } else if "([{".contains(c) {
            depth += 1;
        } else if ")]}".contains(c) {
            depth -= 1;
            if depth == 0 {
                return c == ')' && close_re.is_match(&interpolation[at + 1..]);
            }
        }
    }
    false
}

/// The content-derived sentinel for an interpolation: `__sqlx_<16 hex of sha256>__`.
pub fn content_sentinel(original: &str) -> String {
    let digest = Sha256::digest(original.as_bytes());
    format!("__sqlx_{}__", &hex::encode(digest)[..16])
}

/// Mask with sentinels derived from each interpolation's text, so the same interpolation has the
/// same sentinel wherever a rewrite moves it.
pub fn mask_sqlx_by_content(sql: &str) -> Result<String> {
    let masked = mask_sqlx(sql)?;
    let mut text = masked.masked.clone();
    for item in &masked.restorations {
        text = text.replace(&item.token, &content_sentinel(&item.original));
    }
    Ok(text)
}

/// Content sentinels of every interpolation in `sql` that is not a relation reference.
pub fn dynamic_sentinels(sql: &str) -> Result<Vec<String>> {
    let masked = mask_sqlx(sql)?;
    let mut out: Vec<String> = masked
        .restorations
        .iter()
        .filter(|r| !is_relation_reference(&r.original))
        .map(|r| content_sentinel(&r.original))
        .collect();
    out.sort();
    out.dedup();
    Ok(out)
}

/// Refused: the text holds a positional sentinel, which means different things in different models.
pub const LOADER_TOKEN_REASON: &str = "unsupported: it holds a Dataform expression the loader masked by position (__sqlx_token_N__), which can expand to any SQL and stands for a different expression in each model; compile the SQLX to prove it";
/// Refused: a string literal holds a masked expression, so its value is unknown.
pub const STRING_REASON: &str = "unsupported: a string literal holds a masked Dataform expression, so its value is unknown; compile the SQLX to prove it";

/// Why a prover must not read these masked texts as they are, or `None`.
pub fn masked_template_problem(sqls: &[&str]) -> Option<&'static str> {
    static LOADER: OnceLock<Regex> = OnceLock::new();
    let loader = LOADER.get_or_init(|| Regex::new(r"__sqlx_token_\d+__").expect("valid regex"));
    for sql in sqls {
        if !sql.contains("__sqlx_") {
            continue;
        }
        if loader.is_match(sql) {
            return Some(LOADER_TOKEN_REASON);
        }
        match tokenize(sql) {
            Ok(tokens) => {
                if tokens.iter().any(|t| {
                    matches!(t.kind, TokenKind::String { .. } | TokenKind::Bytes { .. })
                        && t.text.contains("__sqlx_")
                }) {
                    return Some(STRING_REASON);
                }
            }
            Err(_) => return Some(STRING_REASON),
        }
    }
    None
}

/// `transformed` with `original`'s leading and trailing whitespace.
pub fn with_preserved_whitespace(original: &str, transformed: &str) -> String {
    if transformed.is_empty() {
        return original.to_string();
    }
    let leading = &original[..original.len() - original.trim_start().len()];
    let trailing = &original[original.trim_end().len()..];
    format!("{leading}{}{trailing}", transformed.trim())
}

// ------------------------------------------------------------------------ config

/// A dependency named in `dependencies: [...]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SqlxDependency {
    Name(String),
    Target(RefTarget),
    /// Not a literal.
    Computed(String),
}

/// Documentation of one column (`columns: {a: "text"}` or `{a: {description, columns, bigqueryPolicyTags}}`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxColumn {
    pub description: Option<String>,
    pub columns: IndexMap<String, SqlxColumn>,
    pub policy_tags: Vec<String>,
}

/// The `bigquery: {...}` block (and its top-level spellings).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxBigQuery {
    pub partition_by: Option<String>,
    pub cluster_by: Vec<String>,
    pub labels: IndexMap<String, String>,
    pub require_partition_filter: Option<bool>,
    pub partition_expiration_days: Option<String>,
    pub update_partition_filter: Option<String>,
}

/// The `assertions: {...}` block.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxAssertions {
    pub unique_key: Vec<String>,
    pub unique_keys: Vec<Vec<String>>,
    pub non_null: Vec<String>,
    pub row_conditions: Vec<String>,
}

/// What a config block says, read without running it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlxConfig {
    /// `type` (`table`, `view`, `incremental`, `operations`, `assertion`, `declaration`, `test`).
    pub action_type: Option<String>,
    pub schema: Option<String>,
    pub database: Option<String>,
    pub name: Option<String>,
    pub tags: Vec<String>,
    pub disabled: Option<bool>,
    pub protected: Option<bool>,
    pub has_output: Option<bool>,
    pub description: Option<String>,
    pub columns: IndexMap<String, SqlxColumn>,
    pub dependencies: Vec<SqlxDependency>,
    pub bigquery: SqlxBigQuery,
    pub assertions: SqlxAssertions,
    /// A top-level `uniqueKey` (incremental tables).
    pub unique_key: Vec<String>,
    /// Keys whose values are computed (only known by running the project).
    pub computed: Vec<String>,
    /// What Dataform's compiler would reject: an unknown type or a key the type does not accept.
    pub problems: Vec<String>,
    /// The whole config as read.
    pub raw: IndexMap<String, JsValue>,
}

impl SqlxConfig {
    /// The action type, `table` when none is given.
    pub fn effective_type(&self) -> &str {
        self.action_type.as_deref().unwrap_or("table")
    }
}

const COMMON_CONFIG_KEYS: &[&str] = &[
    "additionalOptions",
    "assertions",
    "bigquery",
    "columns",
    "database",
    "dataset",
    "dependOnDependencyAssertions",
    "dependencies",
    "dependencyTargets",
    "description",
    "disabled",
    "filename",
    "hermetic",
    "iceberg",
    "incrementalPredicates",
    "labels",
    "metadata",
    "name",
    "preserveGovernanceControls",
    "project",
    "protected",
    "requirePartitionFilter",
    "schema",
    "tags",
    "type",
];

fn type_keys(action_type: &str) -> Option<&'static [&'static str]> {
    Some(match action_type {
        "table" | "test" => &[
            "clusterBy",
            "fileName",
            "partitionBy",
            "partitionExpirationDays",
            "reservation",
        ],
        "view" => &[
            "clusterBy",
            "fileName",
            "materialized",
            "partitionBy",
            "reservation",
        ],
        "incremental" => &[
            "clusterBy",
            "fileName",
            "incrementalStrategy",
            "onSchemaChange",
            "partitionBy",
            "partitionExpirationDays",
            "reservation",
            "uniqueKey",
            "updatePartitionFilter",
        ],
        "assertion" => &["fileName", "reservation"],
        "operations" => &["fileName", "hasOutput", "reservation"],
        "declaration" => &[],
        _ => return None,
    })
}

fn unique(items: Vec<String>) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    items
        .into_iter()
        .filter(|i| seen.insert(i.clone()))
        .collect()
}

fn literal_string(
    map: &IndexMap<String, JsValue>,
    key: &str,
    computed: &mut Vec<String>,
) -> Option<String> {
    match map.get(key)? {
        JsValue::String(s) => Some(s.clone()),
        _ => {
            computed.push(key.to_string());
            None
        }
    }
}

fn literal_bool(
    map: &IndexMap<String, JsValue>,
    key: &str,
    computed: &mut Vec<String>,
) -> Option<bool> {
    match map.get(key)? {
        JsValue::Bool(b) => Some(*b),
        _ => {
            computed.push(key.to_string());
            None
        }
    }
}

fn literal_list(
    map: &IndexMap<String, JsValue>,
    key: &str,
    path: &str,
    computed: &mut Vec<String>,
) -> Vec<String> {
    match map.get(key) {
        None => Vec::new(),
        Some(value) => value.string_list().unwrap_or_else(|| {
            computed.push(format!("{path}{key}"));
            Vec::new()
        }),
    }
}

fn read_columns(value: &JsValue) -> IndexMap<String, SqlxColumn> {
    let mut out = IndexMap::new();
    if let Some(map) = value.as_object() {
        for (name, doc) in map {
            let column = match doc {
                JsValue::String(text) => SqlxColumn {
                    description: Some(text.clone()),
                    ..SqlxColumn::default()
                },
                JsValue::Object(fields) => SqlxColumn {
                    description: fields
                        .get("description")
                        .and_then(|d| d.as_str())
                        .map(str::to_string),
                    columns: fields.get("columns").map(read_columns).unwrap_or_default(),
                    policy_tags: fields
                        .get("bigqueryPolicyTags")
                        .and_then(JsValue::string_list)
                        .unwrap_or_default(),
                },
                _ => SqlxColumn::default(),
            };
            out.insert(name.clone(), column);
        }
    }
    out
}

fn read_dependency(value: &JsValue) -> SqlxDependency {
    match value {
        JsValue::String(name) => SqlxDependency::Name(name.clone()),
        JsValue::Object(map) => {
            let get = |k: &str| map.get(k).and_then(|v| v.as_str()).map(str::to_string);
            match get("name") {
                Some(name) => SqlxDependency::Target(RefTarget {
                    database: get("database").or_else(|| get("project")),
                    schema: get("schema").or_else(|| get("dataset")),
                    name,
                }),
                None => SqlxDependency::Computed(format!("{value:?}")),
            }
        }
        JsValue::Expression(text) => SqlxDependency::Computed(text.clone()),
        other => SqlxDependency::Computed(format!("{other:?}")),
    }
}

fn unique_keys(value: &JsValue) -> Option<Vec<Vec<String>>> {
    value
        .as_array()?
        .iter()
        .map(|entry| match entry {
            JsValue::Object(map) => map.get("uniqueKey").and_then(JsValue::string_list),
            other => other.string_list(),
        })
        .collect()
}

/// Read a `config { ... }` block (or just its `{ ... }`) without running it. An empty block,
/// `tags: []`, trailing commas, unquoted keys, single-quoted strings and `//` comments are fine;
/// computed values are listed in [`SqlxConfig::computed`].
pub fn parse_sqlx_config(config_block: &str) -> Result<SqlxConfig> {
    let text = config_block.trim();
    if text.is_empty() {
        return Ok(SqlxConfig::default());
    }
    let start = if text
        .get(..6)
        .is_some_and(|head| head.eq_ignore_ascii_case("config"))
    {
        6
    } else {
        0
    };
    let rest = text[start..].trim_start();
    if !rest.starts_with('{') {
        return Err(SqlError::Sqlx(
            "a config block must be an object in braces".to_string(),
        ));
    }
    let offset = text.len() - rest.len();
    let (value, end) = parse_lenient(text, offset).ok_or_else(|| {
        SqlError::Sqlx("the config block is not a readable JavaScript object".to_string())
    })?;
    let trailing = crate::js::strip_comments(&text[end..]);
    if !trailing.trim().is_empty() {
        return Err(SqlError::Sqlx(
            "unexpected text after the config object".to_string(),
        ));
    }
    let JsValue::Object(map) = value else {
        return Err(SqlError::Sqlx(
            "a config block must be an object in braces".to_string(),
        ));
    };
    let mut config = SqlxConfig::default();
    let mut computed = Vec::new();
    config.action_type = literal_string(&map, "type", &mut computed);
    config.schema = literal_string(&map, "schema", &mut computed)
        .or_else(|| literal_string(&map, "dataset", &mut computed));
    config.database = literal_string(&map, "database", &mut computed)
        .or_else(|| literal_string(&map, "project", &mut computed));
    config.name = literal_string(&map, "name", &mut computed);
    config.tags = unique(literal_list(&map, "tags", "", &mut computed));
    config.disabled = literal_bool(&map, "disabled", &mut computed);
    config.protected = literal_bool(&map, "protected", &mut computed);
    config.has_output = literal_bool(&map, "hasOutput", &mut computed);
    config.description = literal_string(&map, "description", &mut computed);
    if let Some(columns) = map.get("columns") {
        if columns.as_object().is_none() {
            computed.push("columns".to_string());
        }
        config.columns = read_columns(columns);
    }
    match map.get("dependencies") {
        Some(JsValue::Array(items)) => {
            config.dependencies = items.iter().map(read_dependency).collect()
        }
        Some(single @ (JsValue::String(_) | JsValue::Object(_))) => {
            config.dependencies = vec![read_dependency(single)]
        }
        Some(_) => computed.push("dependencies".to_string()),
        None => {}
    }
    let bq_map = match map.get("bigquery") {
        Some(JsValue::Object(m)) => Some(m.clone()),
        Some(_) => {
            computed.push("bigquery".to_string());
            None
        }
        None => None,
    };
    let empty = IndexMap::new();
    let bq = bq_map.as_ref().unwrap_or(&empty);
    let mut bigquery = SqlxBigQuery {
        partition_by: literal_string(bq, "partitionBy", &mut computed),
        cluster_by: literal_list(bq, "clusterBy", "bigquery.", &mut computed),
        require_partition_filter: literal_bool(bq, "requirePartitionFilter", &mut computed),
        update_partition_filter: literal_string(bq, "updatePartitionFilter", &mut computed),
        partition_expiration_days: bq.get("partitionExpirationDays").map(|v| match v {
            JsValue::Number(n) => n.clone(),
            other => format!("{other:?}"),
        }),
        labels: IndexMap::new(),
    };
    for (key, source) in [("labels", bq.get("labels")), ("labels", map.get("labels"))] {
        if let Some(JsValue::Object(labels)) = source {
            for (k, v) in labels {
                match v.as_str() {
                    Some(s) => {
                        bigquery.labels.insert(k.clone(), s.to_string());
                    }
                    None => computed.push(format!("{key}.{k}")),
                }
            }
        }
    }
    // Dataform 3 also accepts these at the top level
    if bigquery.partition_by.is_none() {
        bigquery.partition_by = literal_string(&map, "partitionBy", &mut computed);
    }
    if bigquery.cluster_by.is_empty() {
        bigquery.cluster_by = literal_list(&map, "clusterBy", "", &mut computed);
    }
    if bigquery.update_partition_filter.is_none() {
        bigquery.update_partition_filter =
            literal_string(&map, "updatePartitionFilter", &mut computed);
    }
    if bigquery.require_partition_filter.is_none() {
        bigquery.require_partition_filter =
            literal_bool(&map, "requirePartitionFilter", &mut computed);
    }
    config.bigquery = bigquery;
    match map.get("assertions") {
        Some(JsValue::Object(a)) => {
            config.assertions.unique_key =
                literal_list(a, "uniqueKey", "assertions.", &mut computed);
            if let Some(keys) = a.get("uniqueKeys") {
                match unique_keys(keys) {
                    Some(keys) => config.assertions.unique_keys = keys,
                    None => computed.push("assertions.uniqueKeys".to_string()),
                }
            }
            config.assertions.non_null = literal_list(a, "nonNull", "assertions.", &mut computed);
            config.assertions.row_conditions =
                literal_list(a, "rowConditions", "assertions.", &mut computed);
        }
        Some(_) => computed.push("assertions".to_string()),
        None => {}
    }
    config.unique_key = literal_list(&map, "uniqueKey", "", &mut computed);
    // problems Dataform's compiler reports
    if map.contains_key("type") && config.action_type.is_some() {
        let declared = config.action_type.as_deref().unwrap_or("table");
        if type_keys(declared).is_none() {
            config.problems.push(format!(
                "type '{declared}' is not an action type Dataform recognizes"
            ));
        }
    }
    let type_is_known = !computed.iter().any(|c| c == "type");
    if type_is_known && config.problems.is_empty() {
        let declared = config.effective_type().to_string();
        if let Some(extra) = type_keys(&declared) {
            for key in map.keys() {
                if !COMMON_CONFIG_KEYS.contains(&key.as_str()) && !extra.contains(&key.as_str()) {
                    config.problems.push(format!(
                        "config key '{key}' is not accepted for type '{declared}'"
                    ));
                }
            }
        }
    }
    // @dataform/core 3.0.71 rejects a declaration's assertions block with anything in it (even
    // `{nonNull: []}`); `assertions: {}` passes. The keys in it are still read as the claim.
    if type_is_known && config.effective_type() == "declaration" {
        if let Some(JsValue::Object(block)) = map.get("assertions") {
            if !block.is_empty() {
                config.problems.push(
                    "config key 'assertions' must be empty ({}) for type 'declaration'".to_string(),
                );
            }
        }
    }
    config.computed = unique(computed);
    config.raw = map;
    Ok(config)
}

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

    #[test]
    fn detects_sqlx() {
        assert!(looks_like_sqlx("config { type: \"table\" }\nSELECT 1"));
        assert!(looks_like_sqlx("SELECT * FROM ${ref(\"t\")}"));
        assert!(looks_like_sqlx("  input \"a\" {\n SELECT 1 }"));
        assert!(!looks_like_sqlx("SELECT 1 -- config"));
        assert!(!looks_like_sqlx("SELECT '{config}'"));
    }

    #[test]
    fn decodes_bytes() {
        assert_eq!(decode_sqlx_bytes(b"\xEF\xBB\xBFconfig {}"), "config {}");
        assert_eq!(
            decode_sqlx_bytes(b"caf\xE9 \x93q\x94"),
            "caf\u{e9} \u{201c}q\u{201d}"
        );
        assert_eq!(decode_sqlx_bytes("é".as_bytes()), "é");
    }

    #[test]
    fn splits_sections_with_js_comments() {
        let text = "config {\n  type: \"table\", // don't { break\n  tags: ['a'] /* } */\n}\njs {\n const x = '}';\n}\nSELECT ${ref(\"t\")} -- it's\npre_operations { SET x = 1 }\ninput \"src\" { SELECT 1 }\n";
        let sections = split_sqlx_sections(text).unwrap();
        let kinds: Vec<_> = sections.iter().map(|s| s.kind.clone()).collect();
        assert_eq!(
            kinds,
            vec![
                SqlxSectionKind::Config,
                SqlxSectionKind::Sql,
                SqlxSectionKind::Js,
                SqlxSectionKind::Sql,
                SqlxSectionKind::PreOperations,
                SqlxSectionKind::Sql,
                SqlxSectionKind::Input("src".into()),
                SqlxSectionKind::Sql,
            ]
        );
        let joined: String = sections.iter().map(|s| s.text.as_str()).collect();
        assert_eq!(joined, text);
        assert!(sections[0].body().contains("tags"));
        assert!(split_sqlx_sections("config { type: 'x'").is_err());
    }

    #[test]
    fn comment_spans_skip_strings_and_interpolations() {
        let sql = "SELECT '--x', ${ref('a--b')} -- c\n/* d */ # e\n";
        let spans = sql_comment_spans(sql);
        assert_eq!(spans.len(), 2);
        assert_eq!(&sql[spans[0].0..spans[0].1], "-- c");
        assert_eq!(&sql[spans[1].0..spans[1].1], "/* d */");
        assert_eq!(
            defuse_comment_templates("-- ${x}\nSELECT ${y}"),
            "-- $ {x}\nSELECT ${y}"
        );
    }

    #[test]
    fn masks_and_restores() {
        let sql = "SELECT * FROM ${ref(\"ds\", \"t\")} AS t -- ${ref(\"ignored\")}\n# ${ref(\"evaluated\")}\nWHERE ${when(incremental(), \"ts > 1 AND\")} x = 1";
        let masked = mask_sqlx(sql).unwrap();
        assert_eq!(masked.restorations.len(), 3);
        assert!(masked.masked.contains("FROM __sqlx_token_000__ AS t"));
        assert!(masked.masked.contains("-- ${ref(\"ignored\")}"));
        assert!(masked.masked.contains("WHERE __sqlx_token_002__ AND x = 1"));
        let targets: Vec<_> = masked.refs.iter().filter_map(RefCall::target).collect();
        assert_eq!(targets.len(), 2);
        assert_eq!(targets[0].schema.as_deref(), Some("ds"));
        assert_eq!(targets[1].name, "evaluated");
        assert!(masked.refs.iter().any(|r| r.function == RefFunction::When));
        assert_eq!(restore_sqlx(&masked, &masked.masked).unwrap(), sql);
        // a rewrite that keeps every sentinel once restores
        let rewritten = masked.masked.replace("AS t", "AS u");
        assert!(restore_sqlx(&masked, &rewritten)
            .unwrap()
            .contains("${ref(\"ds\", \"t\")} AS u"));
        // lost or duplicated sentinels refuse
        let lost = masked.masked.replace("__sqlx_token_000__", "x");
        assert!(matches!(
            restore_sqlx(&masked, &lost),
            Err(SqlError::SqlxRestoration(_))
        ));
        let dup = format!("{} {}", masked.masked, "__sqlx_token_001__");
        assert!(restore_sqlx(&masked, &dup).is_err());
        // separating a `whole` sentinel from its connective refuses
        let separated = masked
            .masked
            .replace("__sqlx_token_002__ AND", "__sqlx_token_002__ OR");
        assert!(restore_sqlx(&masked, &separated).is_err());
    }

    #[test]
    fn masks_clause_interpolations() {
        let m = mask_sqlx(
            "SELECT * FROM t ${when(incremental(), `WHERE ts > (SELECT MAX(ts) FROM ${self()})`)}",
        )
        .unwrap();
        assert!(
            m.masked.ends_with("WHERE __sqlx_token_000__"),
            "{}",
            m.masked
        );
        assert!(m
            .refs
            .iter()
            .any(|r| r.function == RefFunction::SelfRef && r.nested));
        assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
        let m =
            mask_sqlx("SELECT * FROM t WHERE a > 0 ${when(incremental(), \"AND b > 1\")}").unwrap();
        assert!(
            m.masked.contains("a > 0 AND __sqlx_token_000__"),
            "{}",
            m.masked
        );
        let restored = restore_sqlx(&m, &m.masked.replace("a > 0 AND", "a > 0\n  AND")).unwrap();
        assert!(restored.contains("${when("));
        let m = mask_sqlx("SELECT 1 ${\"ORDER BY x\"}").unwrap();
        assert!(m.masked.ends_with("ORDER BY __sqlx_token_000__"));
    }

    #[test]
    fn sentinels_avoid_existing_text_and_backticks_restore() {
        let m = mask_sqlx("SELECT '__sqlx_token_000__', ${x}").unwrap();
        assert_eq!(m.restorations[0].token, "__sqlx_token_001__");
        let m = mask_sqlx("SELECT * FROM ${ref('t')}").unwrap();
        let quoted = m
            .masked
            .replace("__sqlx_token_000__", "`__sqlx_token_000__`");
        assert_eq!(restore_sqlx(&m, &quoted).unwrap(), m.original);
        let m = mask_sqlx("SELECT REGEXP_EXTRACT(a, r'\\d$1') FROM ${ref('t')}").unwrap();
        assert_eq!(restore_sqlx(&m, &m.masked).unwrap(), m.original);
    }

    #[test]
    fn relation_references() {
        assert!(is_table_reference("${ref(\"t\")}"));
        assert!(is_table_reference("${ ref('d', 't') }"));
        assert!(is_table_reference("${self()}"));
        assert!(!is_table_reference("${ref({schema: 's', name: 't'})}"));
        assert!(is_relation_reference(
            "${ref({schema: vars.S, name: \"t\"})}"
        ));
        assert!(is_relation_reference("${resolve(\"t\")}"));
        assert!(!is_relation_reference("${ref(\"t\") + \" OR x\"}"));
        assert!(!is_relation_reference("${ref(a /* ( */) + x)}"));
        assert!(!is_relation_reference("${when(incremental(), \"x\")}"));
        let m = mask_sqlx("SELECT * FROM ${ref('t')} WHERE ${\"x OR y\"}").unwrap();
        assert_eq!(m.opaque_tokens(), vec!["__sqlx_token_001__".to_string()]);
    }

    #[test]
    fn content_masking_and_problems() {
        let a = mask_sqlx_by_content("SELECT * FROM ${ref('t')}").unwrap();
        let b = mask_sqlx_by_content("SELECT x FROM ${ref('t')} AS y").unwrap();
        let sentinel = content_sentinel("${ref('t')}");
        assert!(a.contains(&sentinel) && b.contains(&sentinel));
        assert_eq!(sentinel.len(), "__sqlx_".len() + 16 + 2);
        assert_eq!(
            dynamic_sentinels("SELECT ${x}, ${ref('t')}").unwrap(),
            vec![content_sentinel("${x}")]
        );
        assert_eq!(
            masked_template_problem(&["SELECT __sqlx_token_000__"]),
            Some(LOADER_TOKEN_REASON)
        );
        assert_eq!(
            masked_template_problem(&[&format!("SELECT '{sentinel}'")]),
            Some(STRING_REASON)
        );
        assert_eq!(
            masked_template_problem(&[&format!("SELECT * FROM {sentinel}")]),
            None
        );
        assert_eq!(with_preserved_whitespace("  a \n", "b"), "  b \n");
        assert_eq!(with_preserved_whitespace("  a \n", ""), "  a \n");
    }

    #[test]
    fn parses_config_blocks() {
        let config = parse_sqlx_config(
            r#"config {
  type: 'incremental', // it's incremental {
  schema: "analytics",
  name: `daily`,
  tags: ["a", 'b',],
  disabled: false,
  description: "Daily rollup",
  columns: { id: "the key", payload: { description: "nested", columns: { x: "inner" }, bigqueryPolicyTags: ["p"] } },
  dependencies: ["dep_one", {name: "dep_two", schema: "raw"}],
  uniqueKey: ["id"],
  bigquery: { partitionBy: "DATE(ts)", clusterBy: ["id", "kind"], labels: { team: "data" } },
  assertions: { uniqueKey: ["id"], uniqueKeys: [["a", "b"], {uniqueKey: ["c"]}], nonNull: "id", rowConditions: ["x > 0"] },
}"#,
        )
        .unwrap();
        assert_eq!(config.action_type.as_deref(), Some("incremental"));
        assert_eq!(config.schema.as_deref(), Some("analytics"));
        assert_eq!(config.name.as_deref(), Some("daily"));
        assert_eq!(config.tags, vec!["a", "b"]);
        assert_eq!(config.disabled, Some(false));
        assert_eq!(
            config.columns["payload"].columns["x"]
                .description
                .as_deref(),
            Some("inner")
        );
        assert_eq!(config.columns["payload"].policy_tags, vec!["p"]);
        assert_eq!(config.dependencies.len(), 2);
        assert!(
            matches!(&config.dependencies[1], SqlxDependency::Target(t) if t.schema.as_deref() == Some("raw"))
        );
        assert_eq!(config.bigquery.partition_by.as_deref(), Some("DATE(ts)"));
        assert_eq!(config.bigquery.cluster_by, vec!["id", "kind"]);
        assert_eq!(config.bigquery.labels["team"], "data");
        assert_eq!(
            config.assertions.unique_keys,
            vec![
                vec!["a".to_string(), "b".to_string()],
                vec!["c".to_string()]
            ]
        );
        assert_eq!(config.assertions.non_null, vec!["id"]);
        assert_eq!(config.assertions.row_conditions, vec!["x > 0"]);
        assert_eq!(config.unique_key, vec!["id"]);
        assert!(config.problems.is_empty(), "{:?}", config.problems);
        assert!(config.computed.is_empty(), "{:?}", config.computed);
    }

    #[test]
    fn tolerates_empty_and_computed_configs() {
        assert_eq!(parse_sqlx_config("").unwrap(), SqlxConfig::default());
        let c = parse_sqlx_config("config {}").unwrap();
        assert_eq!(c.effective_type(), "table");
        let c = parse_sqlx_config("config { tags: [] }").unwrap();
        assert!(c.tags.is_empty());
        let c = parse_sqlx_config(
            "{ schema: dataform.projectConfig.vars.s, type: \"view\", name: \"a\" + suffix }",
        )
        .unwrap();
        assert_eq!(c.schema, None);
        assert!(c.computed.contains(&"schema".to_string()));
        assert!(c.computed.contains(&"name".to_string()));
        let c = parse_sqlx_config("config { type: \"table\", uniqueKey: [\"id\"] }").unwrap();
        assert_eq!(
            c.problems,
            vec!["config key 'uniqueKey' is not accepted for type 'table'"]
        );
        let c = parse_sqlx_config("config { type: \"tabel\" }").unwrap();
        assert_eq!(c.problems.len(), 1);
        assert!(parse_sqlx_config("config { type: ").is_err());
        assert!(parse_sqlx_config("SELECT 1").is_err());
    }
}