dre-core 0.7.0

DRE core engine: project parsing, validation and the run path
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
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
//! Runtime Jinja rendering: one environment per connection a Binding uses (its queries' SQL) plus
//! one for output paths and template values. Provides `run.*`, `var()`, `env_var()`,
//! `run_query()`, `columns()`, `ref()`, `source()`, `target.name`, `connection.*`,
//! `destination.*`, `profile()`, the calendar functions in [`crate::dates`] and every macro in
//! `macros/`.
//!
//! [`Mode::Parse`] renders without a database, as dbt's parse does, to find every `source()` a
//! query calls: `run_query()` returns no rows, `columns()` none, `connection.*` nothing, and
//! `raise_error()` doesn't fire. [`Limited`] renders the values that choose a connection or a
//! source (every `profile:`, a source's `database`/`schema`/`identifier`), where only `var()`,
//! `env_var()`, `run.*` and `target.name` exist.

use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use chrono::{NaiveDate, Utc};

use crate::dates::{Calendar, Date, DateTime};

use crate::lookups::{self, Cell, Load, Lookup, Table};
use crate::packages::{DispatchOrder, Package};
use minijinja::value::{Enumerator, Kwargs, Object, ObjectRepr, Value};
use minijinja::{Environment, Error, ErrorKind, UndefinedBehavior};
use serde_json::{Map as JsonMap, Value as Json};

const MACROS: &str = "__dre_macros__";

/// How a [`Renderer`] treats the database.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
    /// Rendering SQL to run (or compile): `run_query()` and `columns()` reach the database.
    #[default]
    Run,
    /// The parse pass: no database, to find `source()` calls.
    Parse,
}

/// Ambient `run.*` context.
#[derive(Debug, Clone)]
pub struct RunContext {
    pub report: String,
    pub set: Option<String>,
    /// The run's target (environment): `run.target` and `target.name`.
    pub target: String,
    /// The schedule's name under `dre run --schedule`, else `None`.
    pub schedule: Option<String>,
    pub date: NaiveDate,
    /// When the run started, or the instant it was scheduled for: `run.now`.
    pub now: chrono::DateTime<Utc>,
    /// `DRE_RUN_AT`: `run.scheduled_at`.
    pub scheduled_at: Option<chrono::DateTime<Utc>>,
    /// The run's timezone and week settings.
    pub calendar: Calendar,
    /// The Binding's `locale:`, for the number filters.
    pub locale: crate::numbers::Locale,
}

/// Appended to a message template's name: it turns on Markdown escaping.
const MARKDOWN_SUFFIX: &str = "\u{0}md";

/// Rows returned to templates by `run_query()`.
#[derive(Debug, Clone, Default)]
pub struct QueryRows {
    pub columns: Vec<String>,
    pub rows: Vec<Vec<Value>>,
}

/// One column of a relation, as `columns()` returns it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
    pub name: String,
    /// The Arrow type name (`Int64`, `Utf8`, `Date32`, ...).
    pub data_type: String,
}

/// Executes `run_query()` SQL on the Binding's sessions: on `profile`'s connection, else on the
/// renderer's own.
pub trait QueryRunner: Send + Sync {
    /// Run `sql`, failing if it returns more than `max_rows` rows.
    fn run_query(&self, sql: &str, max_rows: u64, profile: Option<&str>) -> Result<QueryRows, String>;
    /// The columns `sql` returns, without fetching rows.
    fn columns(&self, sql: &str, profile: Option<&str>) -> Result<Vec<Column>, String>;
    /// Load a lookup into a temp table on the renderer's own session: `Some((relation, plugin
    /// warning))`, or `None` when the source can't load rows.
    fn load(&self, _name: &str, _table: &Table) -> Result<Option<(String, Option<String>)>, String> {
        Ok(None)
    }
}

/// One profile target as templates see it: `connection.*`, `destination.*` and
/// `profile('name').*`.
#[derive(Debug, Clone, Default)]
pub struct Connection {
    /// The profile's name: `.name` and `.profile`.
    pub profile: String,
    /// The target's name (`dev`, `prod`).
    pub target: String,
    /// The plugin type.
    pub kind: String,
    /// Every field, with `env_var()` already rendered.
    pub fields: JsonMap<String, Json>,
    /// Fields that hold secrets: reading one is an error.
    pub secrets: Vec<String>,
}

/// Where `connection`, `destination` and `profile()` get their values. `role` is `connection`
/// or `destination`; `None` finds the profile in whichever section has it.
pub trait Connections: Send + Sync {
    fn profile(&self, name: &str, role: Option<&str>) -> Result<Connection, String>;
    /// The identifier quote character a source plugin type reports (`None`: it doesn't say).
    fn identifier_quote(&self, kind: &str) -> Result<Option<String>, String>;
    /// How a source plugin type wants string literals spelled (its `describe` reply's
    /// `string_literal`; `None`: it doesn't say, so `chr()`).
    fn string_literal(&self, _kind: &str) -> Result<Option<String>, String> {
        Ok(None)
    }
}

/// Which parts of a source's name to quote.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
pub struct Quoting {
    pub database: bool,
    pub schema: bool,
    pub identifier: bool,
}

impl Quoting {
    pub fn any(&self) -> bool {
        self.database || self.schema || self.identifier
    }
}

/// A declared source table with its fields rendered for one Binding: what `source()` returns.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ResolvedSource {
    pub source: String,
    pub table: String,
    /// The connection the source names, rendered; `None` runs it wherever its query runs.
    pub profile: Option<String>,
    pub database: Option<String>,
    pub schema: String,
    pub identifier: String,
    pub quoting: Quoting,
}

impl ResolvedSource {
    /// `database.schema.identifier`, or `schema.identifier` without a database, with the parts
    /// `quoting` asks for quoted by `quote` (doubled inside a name).
    pub fn relation(&self, quote: Option<&str>) -> String {
        let part = |s: &str, q: bool| match (q, quote) {
            (true, Some(c)) => format!("{c}{}{c}", s.replace(c, &format!("{c}{c}"))),
            _ => s.to_string(),
        };
        let mut parts = Vec::new();
        if let Some(d) = &self.database {
            parts.push(part(d, self.quoting.database));
        }
        parts.push(part(&self.schema, self.quoting.schema));
        parts.push(part(&self.identifier, self.quoting.identifier));
        parts.join(".")
    }

    /// `source.table`, as selectors and the manifest name it.
    pub fn key(&self) -> String {
        format!("{}.{}", self.source, self.table)
    }
}

/// Resolves `source('name', 'table')` for one Binding.
pub type SourceResolver = Arc<dyn Fn(&str, &str) -> Result<ResolvedSource, String> + Send + Sync>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderError {
    pub file: PathBuf,
    pub line: Option<usize>,
    pub message: String,
}

impl fmt::Display for RenderError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.line {
            Some(l) => write!(f, "{}:{l}: {}", self.file.display(), self.message),
            None => write!(f, "{}: {}", self.file.display(), self.message),
        }
    }
}

/// What `columns()` found, by relation and connection.
type ColumnsCache = BTreeMap<(String, Option<String>), Value>;

pub struct Renderer {
    env: Environment<'static>,
    /// The parse pass's first `raise_error()` message in the current render.
    raised: Arc<Mutex<Option<String>>>,
    /// What `columns()` found, by relation, for the file being rendered.
    columns_cache: Arc<Mutex<ColumnsCache>>,
    /// `(source, table)` of every `source()` call since the last [`Renderer::take_sources`].
    source_calls: Arc<Mutex<Vec<(String, String)>>>,
    /// The destination being rendered: `destination.*`.
    destination: Arc<Mutex<Option<Connection>>>,
    /// Warnings raised while rendering (e.g. a large lookup inlined), drained by the caller.
    warnings: Arc<Mutex<Vec<String>>>,
    import: String,
    /// Per combined macro template: `(first line, file, line count)` of each macro file in it.
    macro_files: BTreeMap<String, Vec<(usize, PathBuf, usize)>>,
}

pub struct RendererConfig<'a> {
    pub root: &'a Path,
    pub macros: &'a [PathBuf],
    pub context: RunContext,
    /// The Binding's merged vars.
    pub vars: JsonMap<String, Json>,
    /// `--var` overrides, highest precedence.
    pub cli_vars: BTreeMap<String, String>,
    pub runner: Option<Arc<dyn QueryRunner>>,
    /// Profiles for `connection`, `destination` and `profile()`; `None` offline.
    pub connections: Option<Arc<dyn Connections>>,
    pub mode: Mode,
    /// The connection `connection.*` reads and `run_query()` uses by default: the query's in
    /// query SQL, the Binding's inherited one elsewhere.
    pub connection: Option<String>,
    /// That connection's plugin type, for `dispatch()` and source quoting; empty when unknown.
    pub source_type: String,
    /// `source()`; `None`: the project declares no sources.
    pub sources: Option<SourceResolver>,
    pub run_query_max_rows: u64,
    /// Every `.sql` file `ref()` can name, by basename, relative to `root`.
    pub sql: BTreeMap<String, PathBuf>,
    /// Lookups `ref()` and `lookup()` can name.
    pub lookups: BTreeMap<String, Lookup>,
    pub lookup_inline_max_rows: u64,
    /// Macro packages, imported under their names.
    pub packages: Vec<Package>,
    /// The project's name: the root namespace in `dispatch()` search orders.
    pub project_name: String,
    pub dispatch: DispatchOrder,
}

impl Renderer {
    pub fn new(cfg: RendererConfig<'_>) -> Result<Renderer, RenderError> {
        let mut env = Environment::new();
        let parse = cfg.mode == Mode::Parse;
        // The parse pass has no data: `run_query(...)[0].x` must render as nothing, not fail.
        env.set_undefined_behavior(if parse {
            UndefinedBehavior::Chainable
        } else {
            UndefinedBehavior::Strict
        });
        env.set_syntax(
            minijinja::syntax::SyntaxConfig::builder()
                .keep_trailing_newline(true)
                .build()
                .expect("default delimiters are valid"),
        );
        // Message text is portable Markdown: every value it prints is escaped, so a `*` or `_`
        // in the data stays literal (`| safe` opts out).
        env.set_auto_escape_callback(|name| {
            if name.ends_with(MARKDOWN_SUFFIX) {
                minijinja::AutoEscape::Custom("markdown".into())
            } else {
                minijinja::AutoEscape::None
            }
        });
        env.set_formatter(|out, state, value| {
            if *state.auto_escape() == minijinja::AutoEscape::Custom("markdown".into()) {
                let text = value.to_string();
                let text = if value.is_safe() {
                    text
                } else {
                    dre_protocol::markdown::escape(&text)
                };
                return out.write_str(&text).map_err(Error::from);
            }
            minijinja::escape_formatter(out, state, value)
        });
        crate::mutable::register(&mut env);

        add_vars(&mut env, cfg.vars, cfg.cli_vars);
        // The parse pass has no data, so a `raise_error()` there may only mean `run_query()` came
        // back empty: it doesn't stop the render, but if rendering fails anyway, its message is the
        // one reported.
        let raised: Arc<Mutex<Option<String>>> = Arc::default();
        let raised_c = raised.clone();
        env.add_function("raise_error", move |message: String| -> Result<Value, Error> {
            if parse {
                raised_c.lock().unwrap().get_or_insert(message);
                return Ok(Value::from(""));
            }
            Err(Error::new(ErrorKind::InvalidOperation, message))
        });
        let source_type = cfg.source_type.clone();
        crate::dates::register(&mut env, cfg.context.calendar, cfg.context.date);
        crate::numbers::register(&mut env, cfg.context.locale);
        env.add_global("target", Value::from_object(Target(cfg.context.target.clone())));
        env.add_global("run", Value::from_object(Run(cfg.context)));
        let destination: Arc<Mutex<Option<Connection>>> = Arc::default();
        if parse {
            env.add_global("connection", Value::from_object(Lenient));
            env.add_global("destination", Value::from_object(Lenient));
            env.add_function(
                "profile",
                |_name: String, kwargs: Kwargs| -> Result<Value, Error> {
                    let role: Option<String> = kwargs.get("role")?;
                    kwargs.assert_all_used()?;
                    check_role(role.as_deref())?;
                    Ok(Value::from_object(Lenient))
                },
            );
        } else {
            env.add_global(
                "connection",
                Value::from_object(LazyConnection {
                    connections: cfg.connections.clone(),
                    name: cfg.connection.clone(),
                    resolved: std::sync::OnceLock::new(),
                }),
            );
            env.add_global(
                "destination",
                Value::from_object(DestinationSlot(destination.clone())),
            );
            let c = cfg.connections.clone();
            env.add_function(
                "profile",
                move |name: String, kwargs: Kwargs| -> Result<Value, Error> {
                    let role: Option<String> = kwargs.get("role")?;
                    kwargs.assert_all_used()?;
                    check_role(role.as_deref())?;
                    let Some(c) = &c else {
                        return Err(Error::new(
                            ErrorKind::InvalidOperation,
                            format!("`profile('{name}')`: no profiles.yml is loaded here"),
                        ));
                    };
                    c.profile(&name, role.as_deref())
                        .map(|t| Value::from_object(ConnectionValue(t)))
                        .map_err(|e| {
                            Error::new(ErrorKind::InvalidOperation, format!("`profile('{name}')`: {e}"))
                        })
                },
            );
        }
        // `source()`: every call is recorded; in a real render the relation is quoted with the
        // connection's quote character where the source asks for it.
        let source_calls: Arc<Mutex<Vec<(String, String)>>> = Arc::default();
        let relations: Arc<Mutex<Vec<(String, ResolvedSource)>>> = Arc::default();
        {
            let calls = source_calls.clone();
            let relations = relations.clone();
            let resolver = cfg.sources.clone();
            let connections = cfg.connections.clone();
            let kind = cfg.source_type.clone();
            let quote: Arc<std::sync::OnceLock<Result<Option<String>, String>>> = Arc::default();
            env.add_function(
                "source",
                move |source: String, table: String| -> Result<Value, Error> {
                    let fail = |e: String| {
                        Error::new(
                            ErrorKind::InvalidOperation,
                            format!("`source('{source}', '{table}')`: {e}"),
                        )
                    };
                    let Some(resolve) = &resolver else {
                        return Err(fail("the project declares no `sources:`".into()));
                    };
                    let r = resolve(&source, &table).map_err(fail)?;
                    calls.lock().unwrap().push((source.clone(), table.clone()));
                    let q = if parse || !r.quoting.any() {
                        None
                    } else {
                        let got = quote.get_or_init(|| match &connections {
                            Some(c) if !kind.is_empty() => c.identifier_quote(&kind),
                            _ => Err("no connection is known here to quote with".into()),
                        });
                        match got {
                            Ok(Some(q)) => Some(q.clone()),
                            Ok(None) => {
                                return Err(fail(format!(
                                    "`quoting` needs the identifier quote character, but the `{kind}` plugin doesn't report one; update it (`dre plugin update {kind}`)"
                                )));
                            }
                            Err(e) => return Err(fail(format!("can't quote: {e}"))),
                        }
                    };
                    let text = r.relation(q.as_deref());
                    relations.lock().unwrap().push((text.clone(), r));
                    Ok(Value::from(text))
                },
            );
        }
        let runner = cfg.runner;
        let warnings: Arc<Mutex<Vec<String>>> = Arc::default();
        let lookups = Arc::new(Lookups {
            connections: cfg.connections.clone(),
            kind: cfg.source_type.clone(),
            style: std::sync::OnceLock::new(),
            root: cfg.root.to_path_buf(),
            defs: cfg.lookups,
            inline_max: cfg.lookup_inline_max_rows,
            runner: runner.clone(),
            tables: Mutex::default(),
            loaded: Mutex::default(),
            warnings: warnings.clone(),
        });
        let l = lookups.clone();
        env.add_function("lookup", move |name: String| -> Result<Value, Error> {
            let t = l.table(&name)?;
            let rows = QueryRows {
                columns: t.columns.clone(),
                rows: t
                    .rows
                    .iter()
                    .map(|r| r.iter().map(cell_value).collect())
                    .collect(),
            };
            Ok(Value::from_object(QueryResult::new(rows)))
        });
        let default_max = cfg.run_query_max_rows;
        let runner_c = runner.clone();
        let rels = relations.clone();
        env.add_function(
            "run_query",
            move |sql: String, kwargs: Kwargs| -> Result<Value, Error> {
                let max_rows: Option<u64> = kwargs.get("max_rows")?;
                let profile: Option<String> = kwargs.get("profile")?;
                kwargs.assert_all_used()?;
                if parse {
                    let mut empty = QueryResult::new(QueryRows::default());
                    empty.lenient = true;
                    return Ok(Value::from_object(empty));
                }
                let profile = choose_profile("run_query()", &sql, profile, &rels)?;
                let Some(runner) = &runner else {
                    return Err(Error::new(
                        ErrorKind::InvalidOperation,
                        "`run_query()` has no connection here",
                    ));
                };
                let rows = runner
                    .run_query(&sql, max_rows.unwrap_or(default_max), profile.as_deref())
                    .map_err(|e| Error::new(ErrorKind::InvalidOperation, e))?;
                Ok(Value::from_object(QueryResult::new(rows)))
            },
        );
        // Per rendered file: a later query may have recreated the relation.
        let columns_cache: Arc<Mutex<ColumnsCache>> = Arc::default();
        let cache = columns_cache.clone();
        let rels = relations.clone();
        env.add_function(
            "columns",
            move |rel: String, kwargs: Kwargs| -> Result<Value, Error> {
                let profile: Option<String> = kwargs.get("profile")?;
                kwargs.assert_all_used()?;
                if parse {
                    return Ok(Value::from(Vec::<Value>::new()));
                }
                let what = format!("columns('{}')", crate::secrets::mask(&rel));
                let profile = choose_profile(&what, &rel, profile, &rels)?;
                let key = (rel.clone(), profile.clone());
                if let Some(v) = cache.lock().unwrap().get(&key) {
                    return Ok(v.clone());
                }
                let Some(runner) = &runner_c else {
                    return Err(Error::new(
                        ErrorKind::InvalidOperation,
                        format!("`{what}` has no connection here"),
                    ));
                };
                let sql = format!("select * from {rel} as _dre_cols where 1=0");
                let cols = runner
                    .columns(&sql, profile.as_deref())
                    .map_err(|e| Error::new(ErrorKind::InvalidOperation, format!("`{what}` failed: {e}")))?;
                let v = Value::from(
                    cols.into_iter()
                        .map(|c| {
                            Value::from_pairs([
                                ("name", Value::from(c.name)),
                                ("type", Value::from(c.data_type)),
                            ])
                        })
                        .collect::<Vec<_>>(),
                );
                cache.lock().unwrap().insert(key, v.clone());
                Ok(v)
            },
        );

        // Every macro file is combined into one template, imported (on the first line, so line
        // numbers don't move) into everything rendered. Each package gets its own template,
        // imported under the package's name.
        let root = cfg.root.to_path_buf();
        let display = |p: &Path| {
            p.strip_prefix(&root)
                .map(Path::to_path_buf)
                .unwrap_or_else(|_| p.to_path_buf())
        };
        let own: Vec<(PathBuf, PathBuf)> = cfg.macros.iter().map(|m| (cfg.root.join(m), m.clone())).collect();
        let (combined, names, spans) = combine(&own)?;
        let mut import = if names.is_empty() {
            String::new()
        } else {
            format!("{{% from \"{MACROS}\" import {} %}}", names.join(", "))
        };
        let mut templates = vec![(MACROS.to_string(), combined, spans, !names.is_empty())];
        for p in &cfg.packages {
            let files: Vec<(PathBuf, PathBuf)> = p.macros.iter().map(|m| (m.clone(), display(m))).collect();
            let (src, _, spans) = combine(&files)?;
            let t = package_template(&p.name);
            import.push_str(&format!("{{% import \"{t}\" as {} %}}", p.name));
            templates.push((t, src, spans, true));
        }
        add_ref(&mut env, cfg.root, cfg.sql, lookups, &import);
        add_dispatch(
            &mut env,
            &cfg.project_name,
            !names.is_empty(),
            &cfg.packages,
            cfg.dispatch,
            source_type,
            parse,
        );
        let mut r = Renderer {
            env,
            raised,
            columns_cache,
            source_calls,
            destination,
            warnings,
            import,
            macro_files: BTreeMap::new(),
        };
        for (name, src, spans, add) in templates {
            r.macro_files.insert(name.clone(), spans);
            if add {
                r.env
                    .add_template_owned(name.clone(), src)
                    .map_err(|e| r.error(Path::new(&name), &e))?;
            }
        }
        Ok(r)
    }

    /// Warnings raised since the last call.
    pub fn take_warnings(&self) -> Vec<String> {
        std::mem::take(&mut *self.warnings.lock().unwrap())
    }

    /// `(source, table)` of every `source()` called since the last call, in order, each once.
    pub fn take_sources(&self) -> Vec<(String, String)> {
        let mut out: Vec<(String, String)> = Vec::new();
        for c in std::mem::take(&mut *self.source_calls.lock().unwrap()) {
            if !out.contains(&c) {
                out.push(c);
            }
        }
        out
    }

    /// Set (or clear) the destination `destination.*` reads.
    pub fn set_destination(&self, d: Option<Connection>) {
        *self.destination.lock().unwrap() = d;
    }

    /// Render `src`, reporting errors against `file`.
    pub fn render(&self, file: &Path, src: &str) -> Result<String, RenderError> {
        self.render_with(file, src, Value::UNDEFINED, false)
    }

    /// Render `src` with `ctx`'s keys (a map) added to the context (`results`, `outputs`). With
    /// `markdown`, it's message text: every printed value is escaped for portable Markdown.
    pub fn render_with(
        &self,
        file: &Path,
        src: &str,
        ctx: Value,
        markdown: bool,
    ) -> Result<String, RenderError> {
        self.columns_cache.lock().unwrap().clear();
        *self.raised.lock().unwrap() = None;
        let full = format!("{}{src}", self.import);
        let mut name = file.to_string_lossy().to_string();
        if markdown {
            name.push_str(MARKDOWN_SUFFIX);
        }
        let tmpl = self
            .env
            .template_from_named_str(&name, &full)
            .map_err(|e| self.error(file, &e))?;
        let rendered = if ctx.is_undefined() {
            tmpl.render(())
        } else {
            tmpl.render(ctx)
        };
        rendered.map_err(|e| {
            let mut err = self.error(file, &e);
            if let Some(m) = self.raised.lock().unwrap().take() {
                err.message = m;
            }
            err
        })
    }

    fn error(&self, file: &Path, e: &Error) -> RenderError {
        // Report the innermost location: a macro file if the error happened inside a macro.
        let mut deepest: &Error = e;
        while let Some(src) = std::error::Error::source(deepest).and_then(|s| s.downcast_ref::<Error>()) {
            deepest = src;
        }
        let (name, line) = match (deepest.name(), deepest.line()) {
            (Some(n), l) => (n.to_string(), l),
            _ => (e.name().unwrap_or_default().to_string(), e.line()),
        };
        let (file, line) = if let Some(spans) = self.macro_files.get(&name) {
            match line.and_then(|l| {
                spans
                    .iter()
                    .find(|(s, _, n)| l >= *s && l < s + n)
                    .map(|(s, f, _)| (f, l - s + 1))
            }) {
                Some((f, l)) => (f.clone(), Some(l)),
                None => (file.to_path_buf(), line),
            }
        } else {
            (file.to_path_buf(), line)
        };
        let message = deepest
            .detail()
            .map(str::to_string)
            .unwrap_or_else(|| deepest.kind().to_string());
        RenderError { file, line, message }
    }
}

/// `var()` (`--var` first, then the Binding's vars, then the default) and `env_var()`.
/// A `--var` value as YAML 1.2's core rules read it: `true`/`false`, `null`/`~`, integers
/// (no leading zeros), floats, and flow lists and maps (`[a, b]`, `{k: v}`) are typed; anything
/// else stays a string (`yes`, `NO`, `2026-01-31`, `010`, `1.0.0`). Quoting forces a string
/// (`'"false"'`), and an empty value is the empty string.
pub fn cli_var_value(s: &str) -> Json {
    let t = s.trim();
    let int = regex_lite(t, |c, i| c.is_ascii_digit() || (i == 0 && (c == '-' || c == '+')));
    match t {
        "" => return Json::String(String::new()),
        "true" | "True" | "TRUE" => return Json::Bool(true),
        "false" | "False" | "FALSE" => return Json::Bool(false),
        "null" | "Null" | "NULL" | "~" => return Json::Null,
        _ => {}
    }
    if int {
        let digits = t.trim_start_matches(['-', '+']);
        if !digits.is_empty()
            && !(digits.len() > 1 && digits.starts_with('0'))
            && let Ok(n) = t.parse::<i64>()
        {
            return Json::from(n);
        }
        return Json::String(s.to_string());
    }
    let float = t.trim_start_matches(['-', '+']);
    let is_float = !float.is_empty()
        && float
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '-' | '+'))
        && float
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_digit() || c == '.')
        && float.chars().filter(|c| *c == '.').count() <= 1
        && !float.starts_with("00")
        && !(float.starts_with('0') && float.len() > 1 && float.as_bytes()[1].is_ascii_digit());
    if is_float
        && (float.contains('.') || float.contains(['e', 'E']))
        && let Ok(f) = t.parse::<f64>()
        && let Some(n) = serde_json::Number::from_f64(f)
    {
        return Json::Number(n);
    }
    let quoted = (t.starts_with('"') && t.ends_with('"') && t.len() >= 2)
        || (t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2);
    let flow = (t.starts_with('[') && t.ends_with(']')) || (t.starts_with('{') && t.ends_with('}'));
    if (quoted || flow)
        && let Ok(v) = serde_saphyr::from_str::<Json>(t)
    {
        return v;
    }
    Json::String(s.to_string())
}

/// Whether every character passes `ok(c, index)`.
fn regex_lite(s: &str, ok: impl Fn(char, usize) -> bool) -> bool {
    !s.is_empty() && s.chars().enumerate().all(|(i, c)| ok(c, i))
}

fn add_vars(env: &mut Environment<'static>, vars: JsonMap<String, Json>, cli: BTreeMap<String, String>) {
    env.add_function(
        "var",
        move |name: String, default: Option<Value>| -> Result<Value, Error> {
            if let Some(v) = cli.get(&name) {
                return Ok(Value::from(minijinja::value::Serde(cli_var_value(v))));
            }
            if let Some(v) = vars.get(&name) {
                return Ok(Value::from(minijinja::value::Serde(v)));
            }
            default.ok_or_else(|| {
                Error::new(
                    ErrorKind::UndefinedError,
                    format!("`var('{name}')` has no value and no default"),
                )
            })
        },
    );
    env.add_function("env_var", |name: String, default: Option<Value>| -> Result<Value, Error> {
        match std::env::var(&name) {
            Ok(v) => Ok(Value::from(v)),
            Err(_) => default.ok_or_else(|| {
                Error::new(
                    ErrorKind::UndefinedError,
                    format!("`env_var('{name}')`: environment variable `{name}` is not set and no default is given"),
                )
            }),
        }
    });
}

/// What every DRE template reads, for an environment built outside core's renderers (the
/// `document` plugin's html and pdf templates): `var()`, `raise_error()`, the date functions,
/// the number filters, `run.*`, `target.name` and Python-style methods. `env_var()` isn't
/// available: a document is data that's delivered, and environment variables hold secrets.
pub fn add_common(
    env: &mut Environment<'static>,
    context: RunContext,
    vars: JsonMap<String, Json>,
    cli_vars: BTreeMap<String, String>,
) {
    crate::mutable::register(env);
    add_vars(env, vars, cli_vars);
    env.add_function(
        "env_var",
        |name: String, _default: Option<Value>| -> Result<Value, Error> {
            Err(Error::new(
                ErrorKind::InvalidOperation,
                format!("`env_var('{name}')` can't be used in a document template; pass the value as a var"),
            ))
        },
    );
    env.add_function("raise_error", |message: String| -> Result<Value, Error> {
        Err(Error::new(ErrorKind::InvalidOperation, message))
    });
    crate::dates::register(env, context.calendar, context.date);
    crate::numbers::register(env, context.locale);
    env.add_global("target", Value::from_object(Target(context.target.clone())));
    env.add_global("run", Value::from_object(Run(context)));
}

/// Renders the values that choose a connection or a source: every `profile:` value and a
/// source's `profile`, `database`, `schema` and `identifier`. Only `var()`, `env_var()`, `run.*`,
/// `target.name` and the calendar functions exist, because these are rendered before any
/// connection is chosen: the parse pass, `dre ls` and the manifest need no database.
pub struct Limited {
    env: Environment<'static>,
}

/// What a [`Limited`] value can't use, and why.
const LIMITED_FUNCTIONS: &[&str] = &[
    "run_query",
    "columns",
    "source",
    "ref",
    "lookup",
    "dispatch",
    "profile",
];
const LIMITED_GLOBALS: &[&str] = &["connection", "destination"];

impl Limited {
    pub fn new(
        context: RunContext,
        vars: JsonMap<String, Json>,
        cli_vars: BTreeMap<String, String>,
    ) -> Limited {
        let mut env = Environment::new();
        env.set_undefined_behavior(UndefinedBehavior::Strict);
        crate::mutable::register(&mut env);
        add_vars(&mut env, vars, cli_vars);
        env.add_function("raise_error", |message: String| -> Result<Value, Error> {
            Err(Error::new(ErrorKind::InvalidOperation, message))
        });
        crate::dates::register(&mut env, context.calendar, context.date);
        crate::numbers::register(&mut env, context.locale);
        env.add_global("target", Value::from_object(Target(context.target.clone())));
        env.add_global("run", Value::from_object(Run(context)));
        for f in LIMITED_FUNCTIONS {
            let name = *f;
            env.add_function(name, move |_args: minijinja::value::Rest<Value>| -> Result<Value, Error> {
                Err(Error::new(
                    ErrorKind::InvalidOperation,
                    format!("`{name}()` can't be used here: this value chooses a connection or a source, so it's rendered before any connection is open"),
                ))
            });
        }
        for g in LIMITED_GLOBALS {
            env.add_global(*g, Value::from_object(Forbidden(g)));
        }
        Limited { env }
    }

    /// Render `src`, the value of `key` (named in errors, e.g. "`profile`").
    pub fn render(&self, key: &str, src: &str) -> Result<String, String> {
        if !crate::preflight::is_templated(src) {
            return Ok(src.to_string());
        }
        self.env
            .render_str(src, ())
            .map(|v| v.trim().to_string())
            .map_err(|e| {
                let mut deepest: &Error = &e;
                while let Some(s) = std::error::Error::source(deepest).and_then(|s| s.downcast_ref::<Error>())
                {
                    deepest = s;
                }
                let msg = deepest
                    .detail()
                    .map(str::to_string)
                    .unwrap_or_else(|| deepest.kind().to_string());
                format!("{key} `{src}`: {msg}")
            })
    }
}

/// `connection` or `destination` in a [`Limited`] value.
#[derive(Debug)]
struct Forbidden(&'static str);

impl Object for Forbidden {
    fn get_value(self: &Arc<Self>, _key: &Value) -> Option<Value> {
        Some(Value::from(Error::new(
            ErrorKind::InvalidOperation,
            format!(
                "`{}.*` can't be used here: this value chooses a connection or a source, so it's rendered before any connection is open",
                self.0
            ),
        )))
    }

    fn render(self: &Arc<Self>, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Err(fmt::Error)
    }
}

fn package_template(name: &str) -> String {
    format!("__dre_package_{name}__")
}

/// Concatenate macro files `(path to read, path to report)` into one template source, with
/// every macro name defined and where each file starts.
#[allow(clippy::type_complexity)]
fn combine(
    files: &[(PathBuf, PathBuf)],
) -> Result<(String, Vec<String>, Vec<(usize, PathBuf, usize)>), RenderError> {
    let re = regex::Regex::new(r"\{%-?\s*macro\s+([A-Za-z_]\w*)").unwrap();
    let mut combined = String::new();
    let mut names = Vec::new();
    let mut spans = Vec::new();
    for (read, shown) in files {
        let src = std::fs::read_to_string(read).map_err(|e| RenderError {
            file: shown.clone(),
            line: None,
            message: format!("can't read macro file: {e}"),
        })?;
        let start = combined.matches('\n').count() + 1;
        names.extend(re.captures_iter(&src).map(|c| c[1].to_string()));
        combined.push_str(&src);
        if !combined.ends_with('\n') {
            combined.push('\n');
        }
        spans.push((start, shown.clone(), src.matches('\n').count() + 1));
    }
    Ok((combined, names, spans))
}

/// `dispatch('name', 'namespace')` returns the macro to call for the active source: in each
/// namespace of the search order, `<source type>__name`, then `default__name`. The search order
/// is `dispatch:` in dre_project.yml, else the root project then the namespace, so a project can
/// override a package's macro by defining, say, `databricks__name` in its own macros/.
fn add_dispatch(
    env: &mut Environment<'static>,
    project: &str,
    project_has_macros: bool,
    packages: &[Package],
    order: DispatchOrder,
    source_type: String,
    parse: bool,
) {
    let project = project.to_string();
    let templates: BTreeMap<String, String> = packages
        .iter()
        .map(|p| (p.name.clone(), package_template(&p.name)))
        .collect();
    env.add_function(
        "dispatch",
        move |state: &minijinja::State<'_, '_>,
              name: String,
              namespace: Option<String>|
              -> Result<Value, Error> {
            let ns = namespace.unwrap_or_else(|| project.clone());
            let search = order.get(&ns).cloned().unwrap_or_else(|| {
                if ns == project {
                    vec![ns.clone()]
                } else {
                    vec![project.clone(), ns.clone()]
                }
            });
            let candidates = [format!("{source_type}__{name}"), format!("default__{name}")];
            for n in &search {
                let template = if n == &project {
                    if !project_has_macros {
                        continue;
                    }
                    MACROS.to_string()
                } else {
                    match templates.get(n) {
                        Some(t) => t.clone(),
                        None => continue,
                    }
                };
                let tmpl = state.env().get_template(&template)?;
                let captured = tmpl.render_captured(())?;
                let st = captured.state();
                for c in &candidates {
                    if st.lookup(c).is_some_and(|v| !v.is_undefined()) {
                        return Ok(Value::from_object(Dispatched {
                            template,
                            name: c.clone(),
                        }));
                    }
                }
            }
            if parse {
                // The parse pass doesn't know the connection type: a macro only some types
                // implement renders as nothing.
                return Ok(Value::from_object(Dispatched {
                    template: String::new(),
                    name: String::new(),
                }));
            }
            Err(Error::new(
                ErrorKind::InvalidOperation,
                format!(
                    "`dispatch('{name}', '{ns}')`: no `{}` or `{}` in {}",
                    candidates[0],
                    candidates[1],
                    search.join(", ")
                ),
            ))
        },
    );
}

/// A macro chosen by `dispatch()`, called by name in its own template.
#[derive(Debug)]
struct Dispatched {
    template: String,
    name: String,
}

impl Object for Dispatched {
    fn call(self: &Arc<Self>, state: &mut minijinja::State<'_, '_>, args: &[Value]) -> Result<Value, Error> {
        if self.template.is_empty() {
            return Ok(Value::from(""));
        }
        let tmpl = state.env().get_template(&self.template)?;
        let out = tmpl
            .render_captured(())?
            .with_state_mut(|s| s.call_macro(&self.name, args))?;
        Ok(Value::from(out))
    }
}

/// `ref('name')`: another `.sql` file, rendered in the same context (vars, `run.*`, macros, the
/// Binding's connection) and returned in parentheses, ready to use as a subquery or CTE body.
/// DRE builds no tables, so a ref inlines SQL rather than pointing at a materialised model.
fn add_ref(
    env: &mut Environment<'static>,
    root: &Path,
    sql: BTreeMap<String, PathBuf>,
    lookups: Arc<Lookups>,
    import: &str,
) {
    let root = root.to_path_buf();
    let import = import.to_string();
    // The chain of refs being rendered, to report cycles instead of recursing forever.
    let stack: Arc<Mutex<Vec<String>>> = Arc::default();
    env.add_function(
        "ref",
        move |state: &minijinja::State<'_, '_>, name: String| -> Result<Value, Error> {
            if lookups.defs.contains_key(&name) {
                return lookups.relation(&name).map(Value::from);
            }
            let Some(rel) = sql.get(&name) else {
                return Err(Error::new(
                    ErrorKind::InvalidOperation,
                    format!("`ref('{name}')`: no `{name}.sql` and no lookup `{name}` in the project"),
                ));
            };
            {
                let mut chain = stack.lock().unwrap();
                if chain.contains(&name) {
                    chain.push(name.clone());
                    let cycle = chain.join(" → ");
                    chain.clear();
                    return Err(Error::new(
                        ErrorKind::InvalidOperation,
                        format!("`ref()` cycle: {cycle}"),
                    ));
                }
                chain.push(name.clone());
            }
            let result = (|| {
                let src = std::fs::read_to_string(root.join(rel)).map_err(|e| {
                    Error::new(
                        ErrorKind::InvalidOperation,
                        format!("can't read {}: {e}", rel.display()),
                    )
                })?;
                let file = rel.to_string_lossy().to_string();
                let rendered = state
                    .env()
                    .template_from_named_str(&file, &format!("{import}{src}"))?
                    .render(())?;
                let statements = crate::sqlsplit::split(&rendered);
                match statements.as_slice() {
                    [one] => Ok(Value::from(format!("(\n{}\n)", one.text))),
                    _ => Err(Error::new(
                        ErrorKind::InvalidOperation,
                        format!(
                            "`ref('{name}')` needs {} to hold exactly one statement, but it has {}",
                            rel.display(),
                            statements.len()
                        ),
                    )),
                }
            })();
            let mut chain = stack.lock().unwrap();
            if chain.last() == Some(&name) {
                chain.pop();
            }
            result
        },
    );
}

/// Lookups for one Binding: read once, inlined or loaded once.
struct Lookups {
    /// Asked, once, how the connection's plugin spells string literals.
    connections: Option<Arc<dyn Connections>>,
    kind: String,
    style: std::sync::OnceLock<Result<lookups::StringLiteral, String>>,
    root: PathBuf,
    defs: BTreeMap<String, Lookup>,
    inline_max: u64,
    runner: Option<Arc<dyn QueryRunner>>,
    tables: Mutex<BTreeMap<String, Arc<Table>>>,
    /// What `ref()` returns for each lookup already used: inline SQL or a temp table's name.
    loaded: Mutex<BTreeMap<String, String>>,
    warnings: Arc<Mutex<Vec<String>>>,
}

impl Lookups {
    fn table(&self, name: &str) -> Result<Arc<Table>, Error> {
        let def = self.defs.get(name).ok_or_else(|| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("no lookup `{name}` under lookups/"),
            )
        })?;
        if let Some(t) = self.tables.lock().unwrap().get(name) {
            return Ok(t.clone());
        }
        let t = Arc::new(lookups::read(&self.root, def).map_err(|e| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("{}: {e}", def.file.display()),
            )
        })?);
        self.tables.lock().unwrap().insert(name.to_string(), t.clone());
        Ok(t)
    }

    fn relation(&self, name: &str) -> Result<String, Error> {
        if let Some(r) = self.loaded.lock().unwrap().get(name) {
            return Ok(r.clone());
        }
        let t = self.table(name)?;
        let rows = t.rows.len() as u64;
        let load = match self.defs[name].load {
            Load::Inline => false,
            Load::TempTable => true,
            Load::Auto => rows > self.inline_max,
        };
        let loaded = match (&self.runner, load) {
            (Some(runner), true) => runner.load(name, &t).map_err(|e| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("loading lookup `{name}`: {e}"),
                )
            })?,
            _ => None,
        };
        let relation = match loaded {
            Some((relation, warning)) => {
                if let Some(w) = warning {
                    self.warn(format!("lookup `{name}`: {w}"));
                }
                relation
            }
            None => {
                if load && self.runner.is_some() {
                    self.warn(format!(
                        "lookup `{name}` has {rows} rows; this source can't load it into a temp table, so it's inlined in the SQL. Data this size probably belongs in a table in the database"
                    ));
                }
                t.inline_sql(self.style()?)
            }
        };
        self.loaded
            .lock()
            .unwrap()
            .insert(name.to_string(), relation.clone());
        Ok(relation)
    }

    fn warn(&self, w: String) {
        self.warnings.lock().unwrap().push(w);
    }

    /// How the source spells a string literal: its plugin's `string_literal`, or `chr()` when
    /// there's no plugin to ask (a render without a connection) or it doesn't say.
    fn style(&self) -> Result<lookups::StringLiteral, Error> {
        self.style
            .get_or_init(|| match &self.connections {
                Some(c) if !self.kind.is_empty() => {
                    let asked = c.string_literal(&self.kind).unwrap_or(None);
                    lookups::StringLiteral::from_describe(asked.as_deref())
                }
                _ => Ok(lookups::StringLiteral::Chr),
            })
            .clone()
            .map_err(|e| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("the `{}` source: {e}", self.kind),
                )
            })
    }
}

fn cell_value(c: &Cell) -> Value {
    match c {
        Cell::Null => Value::from(()),
        Cell::Text(s) => Value::from(s.clone()),
        Cell::Int(n) => Value::from(*n),
        Cell::Num(n) => Value::from(*n),
        Cell::Bool(b) => Value::from(*b),
        Cell::Date(d) => Value::from(d.to_string()),
    }
}

#[derive(Debug)]
struct Run(RunContext);

impl Object for Run {
    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        let c = &self.0;
        Some(match key.as_str()? {
            "report" => Value::from(c.report.clone()),
            "set" => c.set.clone().map(Value::from).unwrap_or(Value::from(())),
            "target" => Value::from(c.target.clone()),
            "profile" => removed("run.profile", "`connection.name` (the query's connection)"),
            "source_type" => removed("run.source_type", "`connection.type` (the query's connection)"),
            "schedule" => c.schedule.clone().map(Value::from).unwrap_or(Value::from(())),
            "date" => Date::value(c.date, c.calendar),
            "now" => DateTime::now(c.now, c.calendar),
            "scheduled_at" => c
                .scheduled_at
                .map(|t| DateTime::now(t, c.calendar))
                .unwrap_or(Value::from(())),
            "timezone" => Value::from(c.calendar.tz.name()),
            _ => return None,
        })
    }

    fn call_method(
        self: &Arc<Self>,
        _: &mut minijinja::State<'_, '_>,
        method: &str,
        args: &[Value],
    ) -> Result<Value, Error> {
        match method {
            "date_format" => {
                let fmt = args.first().and_then(|a| a.as_str()).ok_or_else(|| {
                    Error::new(
                        ErrorKind::InvalidOperation,
                        "`run.date_format()` takes a strftime format string",
                    )
                })?;
                let mut out = String::new();
                use std::fmt::Write;
                write!(out, "{}", self.0.date.format(fmt)).map_err(|_| {
                    Error::new(
                        ErrorKind::InvalidOperation,
                        format!("invalid date format `{fmt}`"),
                    )
                })?;
                Ok(Value::from(out))
            }
            _ => Err(Error::from(ErrorKind::UnknownMethod)),
        }
    }
}

/// An error value naming a removed template name and what to write instead.
fn removed(name: &str, instead: &str) -> Value {
    Value::from(Error::new(
        ErrorKind::InvalidOperation,
        format!("`{name}` was removed in DRE 0.2: use {instead}"),
    ))
}

/// `profile(..., role=)` takes `connection` or `destination`.
fn check_role(role: Option<&str>) -> Result<(), Error> {
    match role {
        None | Some("connection") | Some("destination") => Ok(()),
        Some("source") => Err(Error::new(
            ErrorKind::InvalidOperation,
            "`role='source'` was renamed in DRE 0.2: use `role='connection'`",
        )),
        Some(r) => Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("`role='{r}'`: role must be 'connection' or 'destination'"),
        )),
    }
}

/// The connection `run_query()`/`columns()` uses: `profile=` when given (it must agree with
/// every source `sql` reads), else the connection of the sources `sql` reads, else `None` (the
/// renderer's own).
fn choose_profile(
    what: &str,
    sql: &str,
    explicit: Option<String>,
    relations: &Mutex<Vec<(String, ResolvedSource)>>,
) -> Result<Option<String>, Error> {
    let mut used: Vec<(String, String)> = Vec::new();
    for (text, r) in relations.lock().unwrap().iter() {
        if let Some(p) = &r.profile
            && mentions(sql, text)
            && !used.iter().any(|(k, _)| *k == r.key())
        {
            used.push((r.key(), p.clone()));
        }
    }
    let fail = |m: String| Error::new(ErrorKind::InvalidOperation, format!("`{what}`: {m}"));
    match explicit {
        Some(p) => {
            if let Some((k, q)) = used.iter().find(|(_, q)| *q != p) {
                return Err(fail(format!(
                    "`profile='{p}'` disagrees with source `{k}`, which is on connection `{q}`"
                )));
            }
            Ok(Some(p))
        }
        None => match used.as_slice() {
            [] => Ok(None),
            [(_, p), rest @ ..] => {
                if let Some((k, q)) = rest.iter().find(|(_, q)| q != p) {
                    return Err(fail(format!(
                        "reads source `{}` on connection `{p}` and source `{k}` on `{q}`; one statement runs on one connection",
                        used[0].0
                    )));
                }
                Ok(Some(p.clone()))
            }
        },
    }
}

/// Whether `text` (a rendered relation) appears in `sql` as a whole name.
fn mentions(sql: &str, text: &str) -> bool {
    let ident = |c: char| c.is_alphanumeric() || c == '_';
    sql.match_indices(text).any(|(i, _)| {
        let before = sql[..i].chars().next_back();
        let after = sql[i + text.len()..].chars().next();
        !before.is_some_and(|c| ident(c) || c == '.') && !after.is_some_and(|c| ident(c) || c == '.')
    })
}

/// `target`: the run's environment. Only `target.name` remains; every other field moved to
/// `connection.*` in DRE 0.2.
#[derive(Debug)]
struct Target(String);

impl Object for Target {
    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        let k = key.as_str()?;
        Some(match k {
            "name" => Value::from(self.0.clone()),
            "type" => removed("target.type", "`connection.type` (the query's connection)"),
            "profile" => removed("target.profile", "`connection.name` (the query's connection)"),
            _ => removed(
                &format!("target.{k}"),
                &format!(
                    "`connection.{k}` (the query's connection) or `profile('<name>').{k}`; `target` is now only the environment, `target.name`"
                ),
            ),
        })
    }

    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The parse pass's stand-in for `connection`, `destination` and `profile()`: every field is
/// undefined, which renders as nothing.
#[derive(Debug)]
struct Lenient;

impl Object for Lenient {
    fn get_value(self: &Arc<Self>, _key: &Value) -> Option<Value> {
        None
    }

    fn render(self: &Arc<Self>, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Ok(())
    }
}

/// `profile('name')`: a profile target's fields, refusing secret ones.
#[derive(Debug)]
struct ConnectionValue(Connection);

impl Object for ConnectionValue {
    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        connection_field(&self.0, key)
    }

    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.profile)
    }
}

/// `connection`: the query's connection (or the Binding's inherited one outside query SQL),
/// looked up the first time a template reads it.
struct LazyConnection {
    connections: Option<Arc<dyn Connections>>,
    name: Option<String>,
    resolved: std::sync::OnceLock<Result<Connection, String>>,
}

impl fmt::Debug for LazyConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("connection")
    }
}

impl LazyConnection {
    fn get(&self) -> &Result<Connection, String> {
        self.resolved.get_or_init(|| {
            let name = self.name.as_deref().ok_or(
                "no connection here: this isn't a query's SQL and the Binding inherits no `profile`",
            )?;
            match &self.connections {
                Some(c) => c.profile(name, Some("connection")),
                None => Err("no profiles.yml is loaded here".into()),
            }
        })
    }
}

impl Object for LazyConnection {
    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        match self.get() {
            Ok(c) => connection_field(c, key),
            Err(e) => Some(Value::from(Error::new(
                ErrorKind::InvalidOperation,
                format!("`connection`: {e}"),
            ))),
        }
    }

    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.name {
            Some(n) => f.write_str(n),
            None => Err(fmt::Error),
        }
    }
}

/// `destination`: the destination whose `path` and options are being rendered.
#[derive(Debug)]
struct DestinationSlot(Arc<Mutex<Option<Connection>>>);

impl Object for DestinationSlot {
    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        match &*self.0.lock().unwrap() {
            Some(c) => connection_field(c, key),
            None => Some(Value::from(Error::new(
                ErrorKind::InvalidOperation,
                "`destination` only exists while rendering a destination's `path` and options",
            ))),
        }
    }

    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &*self.0.lock().unwrap() {
            Some(c) => f.write_str(&c.profile),
            None => Err(fmt::Error),
        }
    }
}

/// One field of a profile target for templates; a secret or missing one is an error value.
fn connection_field(c: &Connection, key: &Value) -> Option<Value> {
    {
        let k = key.as_str()?;
        Some(match k {
            "name" | "profile" => Value::from(c.profile.clone()),
            "target" => Value::from(c.target.clone()),
            "type" => Value::from(c.kind.clone()),
            _ if c.secrets.iter().any(|s| s == k) => Value::from(Error::new(
                ErrorKind::InvalidOperation,
                format!(
                    "`{k}` of profile `{}` holds a secret, so templates can't read it (it would end up in compiled SQL and logs)",
                    c.profile
                ),
            )),
            _ => match c.fields.get(k) {
                Some(v) => Value::from(minijinja::value::Serde(v)),
                None => Value::from(Error::new(
                    ErrorKind::UndefinedError,
                    format!(
                        "profile `{}` (target `{}`) has no field `{k}`; it has: {}",
                        c.profile,
                        c.target,
                        c.fields
                            .keys()
                            .filter(|f| !c.secrets.contains(f))
                            .cloned()
                            .collect::<Vec<_>>()
                            .join(", ")
                    ),
                )),
            },
        })
    }
}

#[derive(Debug)]
struct QueryResult {
    columns: Vec<String>,
    rows: Vec<Value>,
    /// The parse pass's empty result: any `column()` is an empty list.
    lenient: bool,
}

impl QueryResult {
    fn new(q: QueryRows) -> QueryResult {
        let cols: Arc<Vec<String>> = Arc::new(q.columns.clone());
        let rows = q
            .rows
            .into_iter()
            .map(|values| {
                Value::from_object(Row {
                    columns: cols.clone(),
                    values,
                })
            })
            .collect();
        QueryResult {
            columns: q.columns,
            rows,
            lenient: false,
        }
    }
}

impl Object for QueryResult {
    fn repr(self: &Arc<Self>) -> ObjectRepr {
        ObjectRepr::Seq
    }

    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        match key.as_str() {
            Some("rows") => Some(Value::from(self.rows.clone())),
            Some("columns") => Some(Value::from(self.columns.clone())),
            _ => self.rows.get(key.as_usize()?).cloned(),
        }
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Seq(self.rows.len())
    }

    /// `result.column('name')` (or an index): that column's values, one per row.
    fn call_method(
        self: &Arc<Self>,
        _: &mut minijinja::State<'_, '_>,
        method: &str,
        args: &[Value],
    ) -> Result<Value, Error> {
        if method != "column" {
            return Err(Error::from(ErrorKind::UnknownMethod));
        }
        if self.lenient {
            return Ok(Value::from(Vec::<Value>::new()));
        }
        let [key] = args else {
            return Err(Error::new(
                ErrorKind::InvalidOperation,
                "`column()` takes one column name or index",
            ));
        };
        let i = match key.as_str() {
            Some(n) => self.columns.iter().position(|c| c == n).ok_or_else(|| {
                Error::new(
                    ErrorKind::InvalidOperation,
                    format!("no column `{n}` (columns: {})", self.columns.join(", ")),
                )
            })?,
            None => key
                .as_usize()
                .filter(|i| *i < self.columns.len())
                .ok_or_else(|| Error::new(ErrorKind::InvalidOperation, format!("no column {key}")))?,
        };
        Ok(Value::from(
            self.rows
                .iter()
                .map(|r| r.get_item_by_index(i).unwrap_or_default())
                .collect::<Vec<_>>(),
        ))
    }
}

/// One `run_query()` row: accessible by column name (`row.region`, `row['region']`) or index.
#[derive(Debug)]
pub(crate) struct Row {
    columns: Arc<Vec<String>>,
    values: Vec<Value>,
}

impl Row {
    pub(crate) fn value(columns: Arc<Vec<String>>, values: Vec<Value>) -> Value {
        Value::from_object(Row { columns, values })
    }
}

impl Object for Row {
    fn repr(self: &Arc<Self>) -> ObjectRepr {
        ObjectRepr::Seq
    }

    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        if let Some(name) = key.as_str() {
            let i = self.columns.iter().position(|c| c == name)?;
            return self.values.get(i).cloned();
        }
        self.values.get(key.as_usize()?).cloned()
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Seq(self.values.len())
    }
}

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

    fn renderer(vars: Json, cli: &[(&str, &str)], macros: &[(&str, &str)]) -> (tempfile::TempDir, Renderer) {
        let dir = tempfile::tempdir().unwrap();
        let mut files = Vec::new();
        for (name, src) in macros {
            let p = PathBuf::from("macros").join(name);
            std::fs::create_dir_all(dir.path().join("macros")).unwrap();
            std::fs::write(dir.path().join(&p), src).unwrap();
            files.push(p);
        }
        let r = Renderer::new(RendererConfig {
            root: dir.path(),
            macros: &files,
            context: RunContext {
                report: "monthly".into(),
                set: Some("client_a".into()),
                target: "prod".into(),
                schedule: None,
                date: NaiveDate::from_ymd_opt(2026, 1, 25).unwrap(),
                now: Utc::now(),
                scheduled_at: None,
                calendar: Calendar::default(),
                locale: Default::default(),
            },
            vars: vars.as_object().cloned().unwrap_or_default(),
            cli_vars: cli.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
            runner: None,
            connections: None,
            mode: Mode::Run,
            connection: None,
            source_type: "duckdb".into(),
            sources: None,
            run_query_max_rows: 10_000,
            sql: BTreeMap::new(),
            lookups: BTreeMap::new(),
            lookup_inline_max_rows: 200,
            packages: Vec::new(),
            project_name: "acme".into(),
            dispatch: DispatchOrder::new(),
        })
        .unwrap();
        (dir, r)
    }

    fn render(r: &Renderer, src: &str) -> Result<String, RenderError> {
        r.render(Path::new("reports/q.sql"), src)
    }

    fn ok(src: &str) -> String {
        let (_d, r) = renderer(serde_json::json!({"fixed": [3, 1, 2], "m": {"a": 1}}), &[], &[]);
        render(&r, src).unwrap_or_else(|e| panic!("{src}: {e}"))
    }

    fn err(src: &str) -> String {
        let (_d, r) = renderer(serde_json::json!({"fixed": [3, 1, 2], "m": {"a": 1}}), &[], &[]);
        render(&r, src).unwrap_err().to_string()
    }

    #[test]
    fn python_string_and_dict_methods_work() {
        assert_eq!(ok("{{ 'a,b,c'.split(',') | join('-') }}"), "a-b-c");
        assert_eq!(
            ok("{{ 'y' if 'abc'.startswith('a') }}{{ 'y' if 'abc'.endswith('x') }}"),
            "y"
        );
        assert_eq!(
            ok("{{ ' x '.strip() }}|{{ 'abc'.upper() }}|{{ 'a-b'.replace('-', '_') }}"),
            "x|ABC|a_b"
        );
        assert_eq!(
            ok("{{ var('m').keys() | list }} {{ var('m').items() | list }}"),
            "['a'] [('a', 1)]"
        );
        assert_eq!(
            ok("{{ var('m').get('a') }} {{ var('m').get('z', 'none') }}"),
            "1 none"
        );
    }

    #[test]
    fn list_appends_in_a_loop_and_joins() {
        assert_eq!(
            ok(
                "{% set sq = list() %}{% for i in range(1, 5) %}{% set _ = sq.append(i * i) %}{% endfor %}{{ sq | join('+') }}"
            ),
            "1+4+9+16"
        );
    }

    #[test]
    fn list_methods_follow_python() {
        assert_eq!(
            ok("{% set l = list([3, 1, 2]) %}{% set _ = l.sort() %}{{ l }}"),
            "[1, 2, 3]"
        );
        assert_eq!(
            ok("{% set l = list([3, 1, 2]) %}{% set _ = l.sort(reverse=true) %}{{ l }}"),
            "[3, 2, 1]"
        );
        assert_eq!(
            ok("{% set l = list([1, 2]) %}{% set _ = l.extend([3, 4]) %}{{ l }} {{ l | length }}"),
            "[1, 2, 3, 4] 4"
        );
        assert_eq!(
            ok("{% set l = list([1, 2, 3]) %}{{ l.pop() }} {{ l.pop(0) }} {{ l }}"),
            "3 1 [2]"
        );
        assert_eq!(
            ok("{% set l = list([1, 2]) %}{% set _ = l.insert(0, 9) %}{% set _ = l.insert(99, 7) %}{{ l }}"),
            "[9, 1, 2, 7]"
        );
        assert_eq!(
            ok(
                "{% set l = list([1, 2, 1]) %}{% set _ = l.remove(1) %}{{ l }} {{ l.index(1) }} {{ l.count(1) }}"
            ),
            "[2, 1] 1 1"
        );
        assert_eq!(
            ok("{% set l = list([1, 2]) %}{% set _ = l.reverse() %}{{ l }}"),
            "[2, 1]"
        );
        assert_eq!(
            ok("{% set l = list([1, 2]) %}{% set _ = l.clear() %}{{ l }} {{ 'empty' if not l }}"),
            "[] empty"
        );
        assert_eq!(
            ok("{% set l = list([1, 2, 3]) %}{{ l[0] }} {{ l[-1] }} {{ l[1:] }}"),
            "1 3 [2, 3]"
        );
    }

    #[test]
    fn lists_share_by_reference_and_copy_apart() {
        assert_eq!(
            ok("{% set a = list() %}{% set b = a %}{% set _ = b.append(1) %}{{ a }}"),
            "[1]"
        );
        assert_eq!(
            ok("{% set a = list([1]) %}{% set b = a.copy() %}{% set _ = b.append(2) %}{{ a }} {{ b }}"),
            "[1] [1, 2]"
        );
    }

    #[test]
    fn a_list_changed_inside_its_own_loop_does_not_skip_or_repeat() {
        assert_eq!(
            ok(
                "{% set l = list([1, 2, 3]) %}{% for x in l %}{% set _ = l.append(x * 10) %}{{ x }} {% endfor %}{{ l }}"
            ),
            "1 2 3 [1, 2, 3, 10, 20, 30]"
        );
        assert_eq!(
            ok("{% set l = list([1, 2]) %}{% set _ = l.extend(l) %}{{ l }}"),
            "[1, 2, 1, 2]"
        );
    }

    #[test]
    fn a_list_starts_from_a_var_without_changing_it() {
        assert_eq!(
            ok("{% set l = list(var('fixed')) %}{% set _ = l.append(4) %}{{ l }} {{ var('fixed') }}"),
            "[3, 1, 2, 4] [3, 1, 2]"
        );
    }

    #[test]
    fn dict_methods_follow_python() {
        assert_eq!(
            ok("{% set d = dict(a=1) %}{% set _ = d.update(b=2) %}{% set _ = d.update({'c': 3}) %}{{ d }}"),
            "{'a': 1, 'b': 2, 'c': 3}"
        );
        // Insertion order, as in Python. (Keyword arguments and `{}` literals reach us already sorted
        // until `preserve_order` is on, and the `| items` filter sorts; so add keys one by one.)
        let make = "{% set d = dict() %}{% set _ = d.setdefault('b', 1) %}{% set _ = d.setdefault('a', 2) %}";
        assert_eq!(
            ok(&(make.to_string() + "{% for k, v in d.items() %}{{ k }}={{ v }} {% endfor %}")),
            "b=1 a=2 "
        );
        assert_eq!(
            ok(&(make.to_string() + "{% for k in d %}{{ k }} {% endfor %}{{ d.values() | list }}")),
            "b a [1, 2]"
        );
        assert_eq!(
            ok("{% set d = dict(a=1) %}{{ d.setdefault('a', 9) }} {{ d.setdefault('b', 2) }} {{ d }}"),
            "1 2 {'a': 1, 'b': 2}"
        );
        assert_eq!(
            ok("{% set d = dict(a=1) %}{{ d.pop('a') }} {{ d.pop('a', 'gone') }} {{ d }}"),
            "1 gone {}"
        );
        assert_eq!(
            ok(
                "{% set d = dict(a=1) %}{{ d.get('a') }} {{ d['a'] }} {{ d.a }} {{ 'in' if 'a' in d }} {{ d.keys() | list }}"
            ),
            "1 1 1 in ['a']"
        );
        assert_eq!(
            ok("{% set d = dict(a=1) %}{% set e = d.copy() %}{% set _ = e.update(a=2) %}{{ d.a }} {{ e.a }}"),
            "1 2"
        );
        assert_eq!(
            ok("{% set d = dict(a=1) %}{% set _ = d.update(a=5, b=6) %}{{ d | length }} {{ d.a }}"),
            "2 5"
        );
        assert_eq!(
            ok("{% set d = dict(a=1) %}{% set _ = d.update(d) %}{{ d }}"),
            "{'a': 1}"
        );
    }

    #[test]
    fn mutable_values_print_and_serialise_like_plain_ones() {
        assert_eq!(
            ok("{{ list([1, 'a']) }} {{ dict(k='v') }}"),
            "[1, 'a'] {'k': 'v'}"
        );
        assert_eq!(
            ok("{{ list(dict(k='v')) }} {{ list(list([2, 1])) | sort }}"),
            "['k'] [1, 2]"
        );
        assert_eq!(ok("{% set l = list() %}{{ 'yes' if l else 'no' }}"), "no");
    }

    /// Templates follow Jinja2 (and so dbt) where MiniJinja 2 didn't; 0.5.0's upgrade notes list these.
    #[test]
    fn expressions_follow_jinja2() {
        assert_eq!(
            ok("{{ ['a', 1] }} {{ var('m') }} {{ var('m').items() | list }}"),
            "['a', 1] {'a': 1} [('a', 1)]"
        );
        assert_eq!(ok("{{ 2.5 | round }} {{ 3.5 | round }}"), "2.0 4.0");
        assert_eq!(ok("{{ -7 // 2 }} {{ -7 % 3 }}"), "-4 2");
        assert_eq!(
            ok("{{ ['b', 'P', 'n'] | max }} {{ \"don't\" | title }}"),
            "P Don't"
        );
        assert!(err("{{ 1 / 0 }}").contains("unable to calculate 1 / 0"));
    }

    #[test]
    fn mutating_an_immutable_value_says_what_to_write() {
        let e = err("{% set l = [] %}{% set _ = l.append(1) %}");
        assert!(e.contains("append()") && e.contains("list()"), "{e}");
        let e = err("{% set _ = var('fixed').append(1) %}");
        assert!(e.contains("list()"), "{e}");
        let e = err("{% set d = {} %}{% set _ = d.update(a=1) %}");
        assert!(e.contains("dict()"), "{e}");
    }

    #[test]
    fn bad_arguments_to_mutable_methods_are_clear_errors() {
        assert!(err("{% set l = list() %}{% set _ = l.append() %}").contains("append()"));
        assert!(err("{% set l = list() %}{% set _ = l.pop() %}").contains("pop()"));
        assert!(err("{% set l = list([1]) %}{% set _ = l.remove(2) %}").contains("not in the list"));
        assert!(err("{% set d = dict() %}{% set _ = d.pop('x') %}").contains("no key"));
        assert!(err("{% set d = dict('nope') %}").contains("mapping"));
    }

    #[test]
    fn run_context_and_date_formats() {
        let (_d, r) = renderer(Json::Null, &[], &[]);
        let out = render(
            &r,
            "{{ run.report }}/{{ run.set }}/{{ run.target }}/{{ target.name }}/{{ target }} {{ run.date }} {{ run.date.yyyymmdd }} \
             {{ run.date.ddmmyyyy }} {{ run.date.yyyy }}-{{ run.date.mm }}-{{ run.date.dd }} {{ run.date_format('%Y-W%V') }}",
        )
        .unwrap();
        assert_eq!(
            out,
            "monthly/client_a/prod/prod/prod 2026-01-25 20260125 25012026 2026-01-25 2026-W04"
        );
    }

    #[test]
    fn var_precedence_is_cli_then_binding_then_default() {
        let (_d, r) = renderer(
            serde_json::json!({"a": "binding", "b": "binding", "n": 5}),
            &[("a", "cli")],
            &[],
        );
        assert_eq!(
            render(
                &r,
                "{{ var('a') }} {{ var('b') }} {{ var('c', 'dflt') }} {{ var('n') + 1 }}"
            )
            .unwrap(),
            "cli binding dflt 6"
        );
        let e = render(&r, "select\n{{ var('missing') }}").unwrap_err();
        assert_eq!(
            (e.line, e.message.contains("`var('missing')` has no value")),
            (Some(2), true),
            "{e}"
        );
    }

    #[test]
    fn env_var_reads_the_environment_or_errors() {
        let (_d, r) = renderer(Json::Null, &[], &[]);
        assert_eq!(
            render(&r, "{{ env_var('DRE_TEST_UNSET_VAR', 'x') }}").unwrap(),
            "x"
        );
        let home = std::env::var("PATH").unwrap();
        assert_eq!(render(&r, "{{ env_var('PATH') }}").unwrap(), home);
        assert!(
            render(&r, "{{ env_var('DRE_TEST_UNSET_VAR') }}")
                .unwrap_err()
                .message
                .contains("is not set")
        );
    }

    #[test]
    fn macros_from_every_file_are_callable_and_keep_line_numbers() {
        let (_d, r) = renderer(
            Json::Null,
            &[],
            &[
                ("a.sql", "{% macro double(x) %}{{ x * 2 }}{% endmacro %}\n"),
                (
                    "b.sql",
                    "{% macro broken() %}\n{{ var('nope') }}\n{% endmacro %}\n{% macro quad(x) %}{{ x * 4 }}{% endmacro %}\n",
                ),
            ],
        );
        assert_eq!(
            render(&r, "select {{ double(2) }}, {{ quad(1) }}\n").unwrap(),
            "select 4, 4\n"
        );
        let e = render(&r, "line one\nselect {{ broken() }}").unwrap_err();
        assert_eq!(e.file, PathBuf::from("macros/b.sql"), "{e}");
        assert_eq!(e.line, Some(2), "{e}");
        let e = render(&r, "one\ntwo\n{{ nope }}").unwrap_err();
        assert_eq!(
            (e.file.clone(), e.line),
            (PathBuf::from("reports/q.sql"), Some(3)),
            "{e}"
        );
    }

    struct Fake;
    impl QueryRunner for Fake {
        fn run_query(&self, sql: &str, max_rows: u64, _profile: Option<&str>) -> Result<QueryRows, String> {
            if max_rows < 2 {
                return Err(format!("`{sql}` returned more than {max_rows} rows"));
            }
            Ok(QueryRows {
                columns: vec!["region".into(), "n".into()],
                rows: vec![
                    vec![Value::from("apac"), Value::from(1)],
                    vec![Value::from("emea"), Value::from(2)],
                ],
            })
        }
        fn columns(&self, _: &str, _: Option<&str>) -> Result<Vec<Column>, String> {
            Ok(Vec::new())
        }
    }

    #[test]
    fn run_query_rows_are_accessible_by_name_and_index() {
        let dir = tempfile::tempdir().unwrap();
        let r = Renderer::new(RendererConfig {
            root: dir.path(),
            macros: &[],
            context: RunContext {
                report: "r".into(),
                set: None,
                target: "t".into(),
                schedule: None,
                date: NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(),
                now: Utc::now(),
                scheduled_at: None,
                calendar: Calendar::default(),
                locale: Default::default(),
            },
            vars: JsonMap::new(),
            cli_vars: BTreeMap::new(),
            runner: Some(Arc::new(Fake)),
            connections: None,
            mode: Mode::Run,
            connection: None,
            source_type: "duckdb".into(),
            sources: None,
            run_query_max_rows: 10_000,
            sql: BTreeMap::new(),
            lookups: BTreeMap::new(),
            lookup_inline_max_rows: 200,
            packages: Vec::new(),
            project_name: "acme".into(),
            dispatch: DispatchOrder::new(),
        })
        .unwrap();
        let src = "{% set res = run_query('select') %}{{ res.columns | join(',') }}|\
                   {% for row in res.rows %}{{ row.region }}={{ row[1] }}{{ ',' if not loop.last }}{% endfor %}|{{ res | length }}|{{ res[1]['region'] }}";
        assert_eq!(render(&r, src).unwrap(), "region,n|apac=1,emea=2|2|emea");
        let e = render(&r, "{{ run_query('select', max_rows=1) }}").unwrap_err();
        assert!(e.message.contains("more than 1 rows"), "{e}");
        assert!(render(&r, "{% if run.set is none %}none{% endif %}").unwrap() == "none");
    }

    #[test]
    fn removed_names_say_what_to_write_instead() {
        let e = err("{{ run.profile }}");
        assert!(
            e.contains("`run.profile` was removed") && e.contains("connection.name"),
            "{e}"
        );
        let e = err("{{ target.schema }}");
        assert!(
            e.contains("`target.schema` was removed") && e.contains("connection.schema"),
            "{e}"
        );
    }

    #[test]
    fn a_source_relation_quotes_the_parts_asked_for() {
        let r = ResolvedSource {
            source: "sales".into(),
            table: "orders".into(),
            profile: None,
            database: None,
            schema: "Sales".into(),
            identifier: "Or\"ders".into(),
            quoting: Quoting {
                database: true,
                schema: false,
                identifier: true,
            },
        };
        assert_eq!(r.relation(Some("\"")), "Sales.\"Or\"\"ders\"");
        assert_eq!(r.relation(None), "Sales.Or\"ders");
        let r = ResolvedSource {
            database: Some("main".into()),
            ..r
        };
        assert_eq!(r.relation(Some("`")), "`main`.Sales.`Or\"ders`");
    }

    #[test]
    fn a_relation_is_mentioned_only_as_a_whole_name() {
        assert!(mentions("select * from sales.orders where 1", "sales.orders"));
        assert!(!mentions("select * from sales.orders_old", "sales.orders"));
        assert!(!mentions("select * from x.sales.orders", "sales.orders"));
    }
}

#[cfg(test)]
mod cli_var_tests {
    use super::cli_var_value as v;
    use serde_json::json;

    #[test]
    fn yaml_1_2_core_rules() {
        assert_eq!(v("false"), json!(false));
        assert_eq!(v("TRUE"), json!(true));
        assert_eq!(v("~"), json!(null));
        assert_eq!(v("5"), json!(5));
        assert_eq!(v("-12"), json!(-12));
        assert_eq!(v("2.5"), json!(2.5));
        assert_eq!(v("[\"NAM\", EMEA]"), json!(["NAM", "EMEA"]));
        assert_eq!(v("{k: 1}"), json!({"k": 1}));
        for s in [
            "yes",
            "NO",
            "2026-01-31",
            "010",
            "1.0.0",
            "abc",
            "[unclosed",
            "0x1F",
        ] {
            assert_eq!(v(s), json!(s), "{s}");
        }
        assert_eq!(v("\"false\""), json!("false"));
        assert_eq!(v("'5'"), json!("5"));
        assert_eq!(v(""), json!(""));
    }
}