sqlload 0.42.1

SQL data loading tooling.
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
use crate::adapters::contract::models::BoundParameter;
use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter;
use arrow_array::RecordBatch;
use std::collections::{BTreeMap, HashMap};
use tokio_postgres::Client;

use crate::adapters::contract::models::TableName;
use crate::adapters::dispatch::main::dialect::files_destination::files_destination;
use crate::adapters::dispatch::main::session::live_columns::live_columns;
use crate::adapters::dispatch::main::session::text_values::text_values;
use crate::adapters::dispatch::models::Destination;
use crate::adapters::files::models::FolderClaim;
use crate::auth::constants::{GOOGLE_AUTHORIZE_URL, GOOGLE_TOKEN_URL};
use crate::auth::main::google_token_cache_file::google_token_cache_file;
use crate::auth::models::GoogleUser;
use crate::bigquery_source::main::bigquery_reader::bigquery_reader;
use crate::bigquery_source::main::read_catalog::read_catalog as read_bigquery_catalog;
use crate::bigquery_source::main::read_rows::read_rows as read_bigquery_rows;
use crate::bigquery_source::models::{BigQueryReadRequest, BigQueryReader};
use crate::column_types::main::arrow_field::arrow_field;
use crate::column_types::main::parse_type::parse_type;
use crate::column_types::models::{ColumnType, Warehouse};
use crate::config::models::{DestinationConfig, DestinationKind};
use crate::file_store::main::open_folder::open_folder;
use crate::files_source::constants::{
    NANOSECOND_SCALE, SOURCE_FILE_COLUMN, SOURCE_ROW_COLUMN, SOURCE_VERSION_COLUMN,
    VERSION_SEPARATOR,
};
use crate::files_source::errors::FilesError;
use crate::files_source::main::constant_columns::constant_columns;
use crate::files_source::main::discover_files::discover_files;
use crate::files_source::main::merge_order::merge_order;
use crate::files_source::main::move_to_prefix::move_to_prefix;
use crate::files_source::main::path_template::path_template;
use crate::files_source::main::read_files::read_files;
use crate::files_source::main::select_files::select_files;
use crate::files_source::models::{
    AfterLoad, BatchFooters, DataFile, FileColumn, FileSelection, FilesEncoding, FilesRead,
    FilesTable, LoadedFile, PathValues, SourceFormat, StoredRead, TextChecks,
};
use crate::http::main::http_client::build_http_client;
use crate::http::models::ConnectionCounter;
use crate::load_naming::main::loaded_name::loaded_name;
use crate::load_naming::models::Naming;
use crate::loader::_helpers::destination::table_folder;
use crate::loader::_helpers::python::{fitting_type, python_tables};
use crate::loader::_helpers::resolve::{NameRule, resolve_tables, source_target};
use crate::loader::_helpers::run_log::merged_files;
use crate::loader::_helpers::specs::is_child_column;
use crate::loader::_helpers::specs::{
    flattened_object_problems, missing_description, referenced_columns, table_name, table_naming,
};
use crate::loader::_helpers::table_plan::{blocked_plan, plan_table};
use crate::loader::constants::{
    KEPT_TABLES_COLUMN_FIX, LOCALHOST, PARALLEL_READ_MIN_BYTES, PARALLEL_READERS, RELOAD_FIX,
    SOURCE_BATCH_ROWS,
};
use crate::loader::errors::LoaderError;
use crate::loader::models::{
    CommitRule, DrainedFiles, FilesSource, PlanOptions, ProjectPlan, ResolvedTables, SkippedTable,
    SourceEnd, SourceProblem, SourceReader, TablePlan, TableSpec,
};
use crate::loader::models::{FoundSource, FoundSources};
use crate::postgres_source::constants::DEFAULT_BATCH_BYTES;
use crate::postgres_source::main::connect_postgres::connect_postgres;
use crate::postgres_source::main::copy_table::copy_table;
use crate::postgres_source::main::cursor_end::cursor_end;
use crate::postgres_source::main::read_catalog::read_catalog;
use crate::postgres_source::models::{
    CopyRequest, Encryption, PgType, PostgresAddress, ReadColumn, SourceColumn, SourceTable,
    SslMode, WireType,
};
use crate::project::main::postgres_address::postgres_address;
use crate::project::models::{
    BatchStep, ConnectionConfig, NewTables, OnDuplicateKeys, ProjectConfig, SourceConfig,
    SourceKind, TableOverride, TableSettings, WriteStrategy,
};
use crate::row_batches::main::loaded_batch::loaded_batch;
use crate::schema_plan::models::{ColumnOrigin, DesiredColumn, LiveColumn};
use crate::sheets_source::constants::{EMPTY_SHEET_COLUMN_KIND, SCOPE, SHEET_COLUMN_KIND};
use crate::sheets_source::main::duplicate_key::duplicate_key;
use crate::sheets_source::main::read_grids::read_grids;
use crate::sheets_source::main::sheet_batch::sheet_batch;
use crate::sheets_source::main::sheet_table::sheet_table;
use crate::sheets_source::main::sheets_client::sheets_client;
use crate::sheets_source::main::tab_name::tab_name;
use crate::sheets_source::main::tab_ranges::tab_ranges;
use crate::sheets_source::main::user_sheets_client::user_sheets_client;
use crate::sheets_source::models::{Grid, HeaderRule, KeySource, SheetsClient};
use crate::similar_names::main::close_name::close_name;
use crate::similar_names::main::nearest_name::nearest_name;
use crate::snowflake_source::constants::SESSION_SCHEMA;
use crate::snowflake_source::main::connect_snowflake_source::connect_snowflake_source;
use crate::snowflake_source::main::read_catalog::read_catalog as read_snowflake_catalog;
use crate::snowflake_source::main::unload_files::unload_files;
use crate::snowflake_source::main::unload_rows::unload_rows;
use crate::snowflake_source::models::{UnloadRequest, UnloadedFiles};
use crate::ssh_tunnel::models::SshTunnel;
use crate::store_paths::main::resolve_location::resolve_location;
use crate::store_paths::models::{Location, StoreKind};

/// A client for a source's Postgres connection, and what protects it.
pub(crate) async fn connect_source(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<(Client, Encryption), LoaderError> {
    let address = postgres_address(project, &source.connection).map_err(LoaderError::Invalid)?;
    Ok(connect_postgres(address).await?)
}

/// The folder a files source reads: its `path` within its connection.
pub(crate) fn files_location(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<Location, LoaderError> {
    let store = match project.connections.get(&source.connection) {
        Some(ConnectionConfig::S3 {
            bucket,
            region,
            endpoint,
            profile,
        }) => StoreKind::S3 {
            bucket: bucket.clone(),
            region: region.clone(),
            endpoint: endpoint.clone(),
            profile: profile.clone(),
        },
        Some(ConnectionConfig::Filesystem { root }) => StoreKind::Filesystem { root: root.clone() },
        Some(ConnectionConfig::Sftp {
            host,
            port,
            user,
            private_key_file,
            private_key_passphrase,
            password,
            known_hosts,
        }) => StoreKind::Sftp {
            server: Box::new(SshTunnel {
                host: host.clone(),
                port: *port,
                user: user.clone(),
                private_key_file: private_key_file.clone(),
                private_key_passphrase: private_key_passphrase.clone(),
                password: password.clone(),
                known_hosts: Some(known_hosts.clone()),
            }),
            root: String::new(),
        },
        _ => {
            return Err(LoaderError::Invalid(format!(
                "connection {:?} is not an s3, filesystem or sftp connection",
                source.connection
            )));
        }
    };
    let path = source.path.as_deref().unwrap_or_default();
    resolve_location(Some((source.connection.as_str(), &store)), path)
        .map_err(|error| LoaderError::Invalid(error.to_string()))
}

/// The Postgres connections a table's read uses: several for a large Postgres table read whole and in no order (windows and cursor-ordered reads keep one connection).
pub(crate) fn source_readers(table: &TablePlan) -> usize {
    let whole = matches!(table.commits, CommitRule::Size | CommitRule::Whole(_));
    let postgres = table.spec.python.is_none()
        && table.spec.files.is_none()
        && table.spec.sheet.is_none()
        && table.spec.warehouse_source.is_none();
    match whole && postgres && table.spec.source_table.estimated_bytes >= PARALLEL_READ_MIN_BYTES {
        true => PARALLEL_READERS,
        false => 1,
    }
}

/// A connected reader for `source`, with up to `readers` connections in all for a Postgres table read in parallel (a helper that cannot connect is left out).
pub(crate) async fn open_source(
    project: &ProjectConfig,
    source: &SourceConfig,
    readers: usize,
) -> Result<SourceReader, LoaderError> {
    match source.kind {
        SourceKind::Postgres | SourceKind::PostgresCdc => {
            let (client, _) = connect_source(project, source).await?;
            let mut helpers = Vec::with_capacity(readers.saturating_sub(1));
            for _ in 1..readers {
                match connect_source(project, source).await {
                    Ok((helper, _)) => helpers.push(helper),
                    Err(_) => break,
                }
            }
            Ok(SourceReader::Postgres(client, helpers))
        }
        SourceKind::Files => Ok(SourceReader::Files(open_folder(&files_location(
            project, source,
        )?)?)),
        SourceKind::Snowflake => Ok(SourceReader::Snowflake(Box::new(connect_snowflake_source(
            snowflake_session(project, source)?,
            source.stage.clone(),
        )?))),
        SourceKind::Odbc => Ok(open_odbc(project, source)?),
        SourceKind::BigQuery => Ok(SourceReader::BigQuery(Box::new(bigquery_source_reader(
            project, source,
        )?))),
        SourceKind::Python => Err(LoaderError::Invalid(
            "a Python source is read by calling its table functions".to_owned(),
        )),
        SourceKind::GoogleSheets => {
            let (client, spreadsheet_id) = sheets_reader(project, source)?;
            Ok(SourceReader::Sheets(client, spreadsheet_id))
        }
    }
}

/// A source's tables, its files for a files source, and warnings about reaching it; `Ok(Err(problem))` when they cannot be found, including when a Postgres source cannot be reached or its `include`/`exclude` patterns are invalid.
pub(crate) async fn source_tables(
    project: &ProjectConfig,
    source_name: &str,
    source: &SourceConfig,
) -> Result<Result<(Vec<SourceTable>, Option<FilesSource>, Vec<String>), SourceProblem>, LoaderError>
{
    match source.kind {
        SourceKind::Postgres | SourceKind::PostgresCdc => {
            let address = match postgres_address(project, &source.connection) {
                Ok(address) => address,
                Err(problem) => return Ok(Err(problem.into())),
            };
            let (client, encryption) = match connect_postgres(address.clone()).await {
                Ok(connected) => connected,
                Err(error) => return Ok(Err(LoaderError::from(error).into())),
            };
            let warnings: Vec<String> =
                plain_text_warning((source_name, &source.connection), &address, encryption)
                    .into_iter()
                    .collect();
            Ok(
                match read_catalog(&client, &source.include, &source.exclude).await {
                    Ok(discovered) => Ok((discovered, None, warnings)),
                    Err(error) => Err(LoaderError::from(error).into()),
                },
            )
        }
        SourceKind::Files => {
            let target = match source_target(project, source) {
                Ok(target) => target,
                Err(problem) => return Ok(Err(problem.into())),
            };
            let unset = TableSettings::default();
            let settings = source
                .tables
                .get(source_name)
                .map_or(&unset, |overrides| &overrides.settings);
            let naming = table_naming((settings, &source.defaults), target.naming);
            Ok(
                match discover_files_table(project, source_name, source, (target.warehouse, naming))
                    .await
                {
                    Ok((table, files)) => Ok((vec![table], Some(files), Vec::new())),
                    Err(LoaderError::Files(FilesError::NoFiles { .. }))
                        if source.after_load != AfterLoad::Keep =>
                    {
                        Ok((Vec::new(), None, Vec::new()))
                    }
                    Err(error) => Err(error.into()),
                },
            )
        }
        SourceKind::Snowflake => {
            let reader = match snowflake_session(project, source)
                .and_then(|session| Ok(connect_snowflake_source(session, None)?))
            {
                Ok(reader) => reader,
                Err(error) => return Ok(Err(error.into())),
            };
            let queries: Vec<(String, String)> = source
                .tables
                .iter()
                .filter_map(|(name, table)| Some((name.clone(), table.sql.clone()?)))
                .collect();
            Ok(
                match read_snowflake_catalog(&reader, (&source.include, &source.exclude), &queries)
                    .await
                {
                    Ok(discovered) => Ok((discovered, None, Vec::new())),
                    Err(error) => Err(LoaderError::from(error).into()),
                },
            )
        }
        SourceKind::Odbc => {
            let queries: Vec<(String, String)> = source
                .tables
                .iter()
                .filter_map(|(name, table)| Some((name.clone(), table.sql.clone()?)))
                .collect();
            Ok(discover_odbc(project, source, &queries)
                .await
                .map(|discovered| (discovered, None, Vec::new()))
                .map_err(SourceProblem::from))
        }
        SourceKind::BigQuery => {
            let reader = match bigquery_source_reader(project, source) {
                Ok(reader) => reader,
                Err(error) => return Ok(Err(error.into())),
            };
            let queries: Vec<(String, String)> = source
                .tables
                .iter()
                .filter_map(|(name, table)| Some((name.clone(), table.sql.clone()?)))
                .collect();
            Ok(
                match read_bigquery_catalog(&reader, (&source.include, &source.exclude), &queries)
                    .await
                {
                    Ok(discovered) => Ok((discovered, None, Vec::new())),
                    Err(error) => Err(LoaderError::from(error).into()),
                },
            )
        }
        SourceKind::Python => Ok(Ok((python_tables(source), None, Vec::new()))),
        SourceKind::GoogleSheets => Ok(match sheets_tables(project, source).await {
            Ok((tables, warnings)) => Ok((tables, None, warnings)),
            Err(error) => Err(error.into()),
        }),
    }
}

/// An `odbc` source's reader, for its connection's settings and the source's value caps.
#[cfg(feature = "odbc")]
pub(crate) fn odbc_source_reader(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<crate::odbc_source::models::OdbcReader, LoaderError> {
    let Some(ConnectionConfig::Odbc {
        connection_string,
        dsn,
        user,
        password,
    }) = project.connections.get(&source.connection)
    else {
        return Err(LoaderError::Invalid(format!(
            "connection {:?} is not an odbc connection",
            source.connection
        )));
    };
    let limits = crate::odbc_source::models::ValueLimits {
        max_text_size: source.max_text_size,
        max_binary_size: source.max_binary_size,
    };
    crate::odbc_source::main::odbc_reader::odbc_reader(
        (connection_string.as_ref(), dsn.as_deref()),
        (user.as_deref(), password.as_ref()),
        limits,
    )
    .map_err(LoaderError::Invalid)
}

#[cfg(feature = "odbc")]
fn open_odbc(project: &ProjectConfig, source: &SourceConfig) -> Result<SourceReader, LoaderError> {
    Ok(SourceReader::Odbc(Box::new(odbc_source_reader(
        project, source,
    )?)))
}

#[cfg(not(feature = "odbc"))]
fn open_odbc(_: &ProjectConfig, _: &SourceConfig) -> Result<SourceReader, LoaderError> {
    Err(LoaderError::Invalid(
        crate::loader::constants::NO_ODBC.to_owned(),
    ))
}

/// An `odbc` source's tables, or why they cannot be listed.
#[cfg(feature = "odbc")]
async fn discover_odbc(
    project: &ProjectConfig,
    source: &SourceConfig,
    queries: &[(String, String)],
) -> Result<Vec<SourceTable>, String> {
    let reader = odbc_source_reader(project, source).map_err(|error| error.to_string())?;
    crate::odbc_source::main::read_catalog::read_catalog(
        &reader,
        (&source.include, &source.exclude),
        queries,
    )
    .await
    .map_err(|error| error.to_string())
}

#[cfg(not(feature = "odbc"))]
async fn discover_odbc(
    _: &ProjectConfig,
    _: &SourceConfig,
    _: &[(String, String)],
) -> Result<Vec<SourceTable>, String> {
    Err(crate::loader::constants::NO_ODBC.to_owned())
}

/// A `bigquery` source's reader, for its connection and the project its tables live in.
pub(crate) fn bigquery_source_reader(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<BigQueryReader, LoaderError> {
    let connection = project.connections.get(&source.connection).ok_or_else(|| {
        LoaderError::Invalid(format!(
            "connection {:?} is not a [connections] entry",
            source.connection
        ))
    })?;
    Ok(bigquery_reader(connection, source.project.as_deref())?)
}

/// A Sheets client for a `google_sheets` source's connection, with the key it names (or `GOOGLE_APPLICATION_CREDENTIALS`'s) or as the Google user who consents to its OAuth client, and the spreadsheet it reads.
pub(crate) fn sheets_reader(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<(SheetsClient, String), LoaderError> {
    let Some(ConnectionConfig::GoogleSheets {
        service_account_file,
        service_account_json,
        service_account_json_base64,
        client_id,
        client_secret,
        refresh_token,
        base_url,
        token_url,
    }) = project.connections.get(&source.connection)
    else {
        return Err(LoaderError::Invalid(format!(
            "connection {:?} is not a google_sheets connection",
            source.connection
        )));
    };
    let given = [
        service_account_json.is_some(),
        service_account_json_base64.is_some(),
        service_account_file.is_some(),
        client_id.is_some(),
    ];
    if given.into_iter().filter(|given| *given).count() > 1 {
        return Err(LoaderError::Invalid(format!(
            "connection {:?} sets more than one of service_account_json, service_account_json_base64, service_account_file and client_id; keep one",
            source.connection
        )));
    }
    let http = build_http_client(&ConnectionCounter::default())?;
    let client = match (client_id, client_secret) {
        (Some(client_id), Some(client_secret)) => {
            let cache_file = google_token_cache_file().ok_or_else(|| {
                LoaderError::Invalid(
                    "no cache folder for the Google sign-in: set HOME or XDG_CACHE_HOME (LOCALAPPDATA on Windows)".to_owned(),
                )
            })?;
            let user = GoogleUser {
                client_id: client_id.clone(),
                client_secret: client_secret.clone(),
                refresh_token: refresh_token.clone(),
                scope: SCOPE.to_owned(),
                connection: source.connection.clone(),
                authorize_url: GOOGLE_AUTHORIZE_URL.to_owned(),
                token_url: token_url.as_deref().unwrap_or(GOOGLE_TOKEN_URL).to_owned(),
                cache_file,
            };
            user_sheets_client(http, user, base_url.as_deref())
        }
        (Some(_), None) => {
            return Err(LoaderError::Invalid(format!(
                "connection {:?} sets client_id without client_secret; set both, from the OAuth client's JSON file",
                source.connection
            )));
        }
        (None, _) if client_secret.is_some() || refresh_token.is_some() => {
            return Err(LoaderError::Invalid(format!(
                "connection {:?} sets client_secret or refresh_token without client_id; set client_id to read as a Google user",
                source.connection
            )));
        }
        (None, _) => {
            let key = match (
                service_account_json,
                service_account_json_base64,
                service_account_file,
            ) {
                (Some(json), _, _) => KeySource::Json(json.clone()),
                (None, Some(encoded), _) => KeySource::Base64(encoded.clone()),
                (None, None, Some(path)) => KeySource::File(path.clone()),
                (None, None, None) => KeySource::Environment,
            };
            sheets_client(http, &key, base_url.as_deref())?
        }
    };
    let spreadsheet_id = source.spreadsheet_id.clone().ok_or_else(|| {
        LoaderError::Invalid("a google_sheets source needs a spreadsheet_id".to_owned())
    })?;
    Ok((client, spreadsheet_id))
}

/// Where table `name` of a `google_sheets` source has its header: the table's `header` and `header_row`, else the source's, else a header in the first row.
pub(crate) fn sheet_rule(source: &SourceConfig, name: &str) -> HeaderRule {
    let table = source.tables.get(name).map(|table| &table.settings);
    let pick = |value: fn(&TableSettings) -> Option<u32>| {
        table.and_then(value).or(value(&source.defaults))
    };
    HeaderRule {
        header: pick(|settings| settings.header.map(u32::from)).is_none_or(|header| header == 1),
        header_row: pick(|settings| settings.header_row).unwrap_or(1),
    }
}

/// A `google_sheets` source's tables: each of its `ranges`, or each tab named after it when it names none (an empty tab is left out with a warning); with the warnings about how cells were typed, or every header cell that cannot name a column.
async fn sheets_tables(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<(Vec<SourceTable>, Vec<String>), LoaderError> {
    let (client, spreadsheet_id) = sheets_reader(project, source)?;
    let mut warnings: Vec<String> = Vec::new();
    let mut named: Vec<(String, Grid)> = Vec::new();
    match source.ranges.is_empty() {
        true => {
            let (_, grids) = read_grids(&client, &spreadsheet_id, None).await?;
            for grid in grids {
                match grid.rows.is_empty() {
                    true => warnings.push(format!(
                        "tab {:?} is empty, so it loads no table",
                        grid.title
                    )),
                    false => named.push((tab_name(&grid.title), grid)),
                }
            }
        }
        false => {
            for (name, range) in &source.ranges {
                let (_, grids) = read_grids(&client, &spreadsheet_id, Some(range)).await?;
                let grid = grids
                    .into_iter()
                    .next()
                    .ok_or_else(|| LoaderError::Invalid(format!("range {range:?} read no tab")))?;
                named.push((name.clone(), grid));
            }
        }
    }
    let mut problems: Vec<String> = Vec::new();
    let mut tables: Vec<SourceTable> = Vec::with_capacity(named.len());
    for (name, grid) in named {
        if tables.iter().any(|table| table.name == name) {
            problems.push(format!(
                "tab {:?} loads as table {name}, as an earlier tab does; rename one, or name the tabs in ranges",
                grid.title
            ));
            continue;
        }
        let mut read = match sheet_table(&grid, sheet_rule(source, &name)) {
            Ok(read) => read,
            Err(found) => {
                problems.extend(found);
                continue;
            }
        };
        let settings = source.tables.get(&name).map(|table| &table.settings);
        let key = settings
            .and_then(|settings| settings.unique_key.as_ref())
            .or(source.defaults.unique_key.as_ref());
        let merge = settings
            .and_then(|settings| settings.write_strategy)
            .or(source.defaults.write_strategy)
            == Some(WriteStrategy::Merge);
        let fails = settings
            .and_then(|settings| settings.on_duplicate_keys)
            .or(source.defaults.on_duplicate_keys)
            == Some(OnDuplicateKeys::Fail);
        let duplicate = key.filter(|_| merge && fails).and_then(|key| {
            let problem = duplicate_key(&grid, sheet_rule(source, &name), &read, key)?;
            Some((problem, key.first()?.clone()))
        });
        if let Some((problem, first)) = duplicate
            && let Some(column) = read
                .columns
                .iter_mut()
                .find(|column| column.name.eq_ignore_ascii_case(&first))
        {
            column.column_type = Err(problem);
        }
        warnings.extend(read.warnings);
        tables.push(SourceTable {
            schema: String::new(),
            name,
            columns: read
                .columns
                .into_iter()
                .map(|column| SourceColumn {
                    name: column.name,
                    postgres_type: match column.has_values {
                        true => SHEET_COLUMN_KIND,
                        false => EMPTY_SHEET_COLUMN_KIND,
                    }
                    .to_owned(),
                    pg_type: PgType::Other,
                    column_type: column.column_type,
                    nullable: true,
                    source_spelling: None,
                })
                .collect(),
            primary_key: Vec::new(),
            indexed_columns: Vec::new(),
            estimated_rows: read.rows as i64,
            estimated_bytes: 0,
            comment: None,
        });
    }
    match problems.is_empty() {
        true => Ok((tables, warnings)),
        false => Err(LoaderError::Invalid(problems.join("; "))),
    }
}

/// A sheet table's spec with each column typed as the live table has it when its cells fit that type (see [`fitting_type`]; dates fit a timestamp column, at midnight), and each column no cell gave a value typed as the live table has it, so a column keeps its type as its values change or empty; a column holding an error cell keeps its error. `None` when no column's type changes.
pub(crate) fn with_live_types(spec: &TableSpec, live: Option<&[LiveColumn]>) -> Option<TableSpec> {
    spec.sheet.as_ref()?;
    let live = live?;
    let mut typed = spec.clone();
    let mut changed = false;
    for column in &mut typed.source_table.columns {
        let Some(live_type) = live
            .iter()
            .find(|live| live.name.eq_ignore_ascii_case(&column.name))
            .map(|live| live.column_type.clone())
        else {
            continue;
        };
        let Ok(inferred) = &column.column_type else {
            continue;
        };
        let column_type = match (column.postgres_type.as_str(), &live_type, inferred) {
            (EMPTY_SHEET_COLUMN_KIND, _, _) | (_, ColumnType::TimestampNtz, ColumnType::Date) => {
                live_type
            }
            _ => fitting_type(inferred.clone(), Some(live_type)),
        };
        changed |= *inferred != column_type;
        column.column_type = Ok(column_type);
    }
    changed.then_some(typed)
}

/// A `google_sheets` table's rows as they are now, in its read columns' types.
async fn sheet_rows(
    client: &SheetsClient,
    spreadsheet_id: &str,
    table: &TablePlan,
) -> Result<RecordBatch, LoaderError> {
    let name = &table.spec.source_table.name;
    let read = table
        .spec
        .sheet
        .as_ref()
        .ok_or_else(|| LoaderError::Invalid(format!("{name} is not a sheet's table")))?;
    let range = match &read.range {
        Some(range) => range.clone(),
        None => {
            let (_, tabs) = tab_ranges(client, spreadsheet_id).await?;
            tabs.into_iter()
                .find(|(title, _)| tab_name(title) == *name)
                .map(|(_, range)| range)
                .ok_or_else(|| {
                    LoaderError::Invalid(format!(
                        "the spreadsheet has no tab for table {name} any more; run plan again"
                    ))
                })?
        }
    };
    let (_, grids) = read_grids(client, spreadsheet_id, Some(&range)).await?;
    let grid = grids
        .into_iter()
        .next()
        .ok_or_else(|| LoaderError::Invalid(format!("range {range:?} read no tab")))?;
    let columns: Vec<(String, ColumnType)> = table
        .read_columns
        .iter()
        .map(|column| {
            (
                table.spec.source_table.spelling(&column.name).to_owned(),
                column.output.clone(),
            )
        })
        .collect();
    sheet_batch(&grid, read.rule, &columns).map_err(LoaderError::Invalid)
}

/// A warning when source `source_name` reads `address` over the network in plain text because the server refused TLS under `sslmode = "prefer"`; none for a loopback or Unix socket host, whose traffic stays on the machine, or for an explicit `disable`.
fn plain_text_warning(
    (source_name, connection): (&str, &str),
    address: &PostgresAddress<'_>,
    encryption: Encryption,
) -> Option<String> {
    let local = address.host == LOCALHOST
        || address.host.starts_with('/')
        || address
            .host
            .parse::<std::net::IpAddr>()
            .is_ok_and(|ip| ip.is_loopback());
    (encryption == Encryption::None && address.tls.mode == SslMode::Prefer && !local).then(|| {
        format!(
            "[sources.{source_name}] reads {}:{} in plain text: the server does not offer TLS, so sslmode = \"prefer\" fell back; set sslmode = \"require\" (or \"verify-full\") on connection {connection} to refuse plain text, or \"disable\" to accept it",
            address.host, address.port
        )
    })
}

/// The session a `snowflake` source reads in: its connection's account, credentials, role and database, on the source's `warehouse` or else the connection's.
fn snowflake_session(
    project: &ProjectConfig,
    source: &SourceConfig,
) -> Result<DestinationConfig, LoaderError> {
    let Some(ConnectionConfig::Snowflake {
        account,
        user,
        auth,
        role,
        warehouse,
        database,
        base_url,
        ..
    }) = project.connections.get(&source.connection)
    else {
        return Err(LoaderError::Invalid(format!(
            "connection {:?} is not a snowflake connection",
            source.connection
        )));
    };
    Ok(DestinationConfig {
        kind: DestinationKind::Snowflake,
        account: account.clone(),
        user: user.clone(),
        auth: auth.clone(),
        role: role.clone(),
        warehouse: source.warehouse.clone().or_else(|| warehouse.clone()),
        database: database.clone(),
        schema: SESSION_SCHEMA.to_owned(),
        base_url: base_url.clone(),
    })
}

/// A files source as one source table (file columns, partition columns, the source-file column), and its files.
pub(crate) async fn discover_files_table(
    project: &ProjectConfig,
    source_name: &str,
    source: &SourceConfig,
    (warehouse, naming): (Warehouse, Naming),
) -> Result<(SourceTable, FilesSource), LoaderError> {
    let location = files_location(project, source)?;
    let folder = open_folder(&location)?;
    let (values, _) = path_values((source_name, source), warehouse)?;
    let encoding = FilesEncoding {
        flatten_objects: naming == Naming::Dlt,
        ..source.files_encoding()
    };
    let table = discover_files(&folder, &values, &encoding).await?;
    if let Some(problem) = table.problems.first() {
        return Err(LoaderError::Invalid(problem.clone()));
    }
    files_source_parts(source_name, source, (warehouse, naming), (location, table))
}

/// What files source `source_name` fills from each file's path and its configuration, and the types of those columns in table order: `partition_columns`, `path_columns` captures, then its table's `constant_columns`; a `native(...)` type, which SQLLoad's reader cannot build, is refused.
fn path_values(
    (source_name, source): (&str, &SourceConfig),
    warehouse: Warehouse,
) -> Result<(PathValues, Vec<(String, ColumnType)>), LoaderError> {
    let mut types: Vec<(String, ColumnType)> = Vec::new();
    for (name, text) in &source.partition_columns {
        let parsed = parse_type(text, &[warehouse])
            .map_err(|error| LoaderError::Invalid(format!("partition column {name}: {error}")))?;
        if matches!(parsed.column_type, ColumnType::Array(_)) {
            return Err(LoaderError::Invalid(format!(
                "partition column {name}: an array cannot come from a path"
            )));
        }
        types.push((name.clone(), parsed.column_type));
    }
    let template = source
        .path_columns
        .as_deref()
        .map(|text| path_template(text, &[warehouse]))
        .transpose()
        .map_err(LoaderError::Invalid)?;
    types.extend(
        template
            .iter()
            .flat_map(|template| template.captures.clone()),
    );
    let constants = constant_columns(&source.table_constants(source_name), &[warehouse])
        .map_err(LoaderError::Invalid)?;
    let typed = types
        .iter()
        .map(|(name, column_type)| (name, column_type))
        .chain(
            constants
                .iter()
                .map(|(name, column_type, _)| (name, column_type)),
        );
    for (name, column_type) in typed {
        if arrow_field(name, column_type).is_none() {
            return Err(LoaderError::Invalid(format!(
                "column {name}: {column_type} has no Arrow type, so a partition, path or constant column cannot be one; pin a portable type"
            )));
        }
    }
    let values = PathValues {
        partition_columns: source.partition_columns.keys().cloned().collect(),
        template,
        unmatched: source.unmatched_paths.unwrap_or_default(),
        constants: constants
            .iter()
            .map(|(name, _, text)| (name.clone(), text.clone()))
            .collect(),
    };
    types.extend(
        constants
            .into_iter()
            .map(|(name, column_type, _)| (name, column_type)),
    );
    Ok((values, types))
}

/// A files source's table and files from the files found: the file columns, partition columns and source-file columns as one source table.
pub(crate) fn files_source_parts(
    source_name: &str,
    source: &SourceConfig,
    (warehouse, naming): (Warehouse, Naming),
    (location, table): (Location, FilesTable),
) -> Result<(SourceTable, FilesSource), LoaderError> {
    let encoding = FilesEncoding {
        flatten_objects: naming == Naming::Dlt,
        ..source.files_encoding()
    };
    let (values, partition_types) = path_values((source_name, source), warehouse)?;
    let added: Vec<&str> = partition_types
        .iter()
        .map(|(name, _)| name.as_str())
        .chain([SOURCE_FILE_COLUMN, SOURCE_VERSION_COLUMN, SOURCE_ROW_COLUMN])
        .collect();
    let overrides = source.tables.get(source_name);
    let rule = (naming, sql_adapter(warehouse).max_identifier_length());
    let pinned_only = pinned_unsampled(overrides, (&table, &added, rule), encoding.format)?;
    if encoding.flatten_objects {
        let problems =
            flattened_object_problems((source, overrides), (&table.columns, &table.objects), rule)
                .map_err(LoaderError::Invalid)?;
        if !problems.is_empty() {
            return Err(LoaderError::Invalid(problems.join("; ")));
        }
    }
    let dropped = (!table.dropped.is_empty()).then(|| {
        format!(
            "dropped {} from the files (replaced by this load's)",
            table.dropped.join(", ")
        )
    });
    let notes: Vec<String> = dropped
        .into_iter()
        .chain(pinned_only.iter().map(|name| {
            format!("pinned column {name} was not seen in the sampled files (check the name)")
        }))
        .collect();
    let typed = table
        .columns
        .iter()
        .filter(|column| !added.contains(&column.name.as_str()))
        .map(|column| (column.name.clone(), column.column_type.clone()))
        .chain(
            pinned_only
                .into_iter()
                .map(|name| (name, Ok(ColumnType::Text))),
        )
        .chain(
            partition_types
                .iter()
                .map(|(name, column_type)| (name.clone(), Ok(column_type.clone()))),
        )
        .chain([
            (SOURCE_FILE_COLUMN.to_owned(), Ok(ColumnType::Text)),
            (SOURCE_VERSION_COLUMN.to_owned(), Ok(ColumnType::Text)),
            (SOURCE_ROW_COLUMN.to_owned(), Ok(ColumnType::Int)),
        ]);
    let columns: Vec<SourceColumn> = typed
        .map(|(name, column_type)| SourceColumn {
            name,
            postgres_type: encoding.format.to_string(),
            pg_type: PgType::Other,
            column_type,
            nullable: true,
            source_spelling: None,
        })
        .collect();
    let checks = TextChecks {
        known: columns.iter().map(|column| column.name.clone()).collect(),
        exclude: [
            source.exclude_columns.as_slice(),
            overrides.map_or(&[], |table| table.exclude_columns.as_slice()),
        ]
        .concat(),
        allow: [
            source.allow_columns.as_slice(),
            overrides.map_or(&[], |table| table.allow_columns.as_slice()),
        ]
        .concat(),
        inferred: Vec::new(),
    };
    let source_table = SourceTable {
        schema: String::new(),
        name: source_name.to_owned(),
        columns,
        primary_key: Vec::new(),
        indexed_columns: Vec::new(),
        estimated_rows: -1,
        comment: None,
        estimated_bytes: table
            .files
            .iter()
            .map(|data| i64::try_from(data.file.size).unwrap_or(i64::MAX))
            .sum(),
    };
    Ok((
        source_table,
        FilesSource {
            location,
            table,
            partition_types,
            constants: values.constants.into_iter().map(|(name, _)| name).collect(),
            encoding,
            checks,
            notes,
            copy_to_internal_stage: source.copy_to_internal_stage,
        },
    ))
}

/// Columns a JSON or CSV source's table pins in `columns` that sampling did not see, so a key found only in older files can be pinned; a name close to a sampled one (a typo, or another case) is an error, and a `mask` key alone never adds a column. Under `rule`'s dlt naming a pin naming a sampled column by its loaded name is one sampling saw.
fn pinned_unsampled(
    overrides: Option<&TableOverride>,
    (table, added, rule): (&FilesTable, &[&str], NameRule),
    format: SourceFormat,
) -> Result<Vec<String>, LoaderError> {
    let Some(overrides) = overrides.filter(|_| format != SourceFormat::Parquet) else {
        return Ok(Vec::new());
    };
    let sampled: Vec<&str> = table
        .columns
        .iter()
        .map(|column| column.name.as_str())
        .collect();
    let loaded = |name: &str| loaded_name(rule.0, name, rule.1);
    let seen: Vec<String> = sampled
        .iter()
        .chain(added)
        .map(|name| loaded(name))
        .collect();
    let mut unsampled: Vec<String> = Vec::new();
    for name in overrides.columns.keys() {
        if seen.contains(&loaded(name)) || is_child_column(name, overrides) {
            continue;
        }
        let known = sampled.iter().chain(added).copied();
        if let Some(close) = close_name(name, known) {
            return Err(LoaderError::Invalid(format!(
                "pinned column {name} was not seen in the sampled files; did you mean {close:?}? (pin a name exactly as it appears in the files)"
            )));
        }
        unsampled.push(name.clone());
    }
    Ok(unsampled)
}

/// What a files read reads, as the files spell it (the batches it reads are renamed to the loaded names after): each of `read_columns` in its read type, and those whose types were inferred from sampled values, not pinned and not filled from the path (`partition_types`) or the file.
pub(crate) fn files_read_as(
    spec: &TableSpec,
    read_columns: &[ReadColumn],
    partition_types: &[(String, ColumnType)],
) -> (Vec<DesiredColumn>, Vec<String>) {
    let spelled = |name: &str| spec.source_table.spelling(name).to_owned();
    let columns: Vec<DesiredColumn> = read_columns
        .iter()
        .map(|column| DesiredColumn {
            name: spelled(&column.name),
            column_type: column.output.clone(),
            origin: ColumnOrigin::Source,
        })
        .collect();
    let filled: Vec<&str> = partition_types
        .iter()
        .map(|(name, _)| name.as_str())
        .chain([SOURCE_FILE_COLUMN, SOURCE_VERSION_COLUMN, SOURCE_ROW_COLUMN])
        .collect();
    let inferred: Vec<String> = read_columns
        .iter()
        .filter(|column| !spec.pinned.contains_key(&column.name))
        .map(|column| spelled(&column.name))
        .filter(|name| !filled.contains(&name.as_str()))
        .collect();
    (columns, inferred)
}

/// The read columns of a files source: the file's types, or the pinned ones (converted while reading).
pub(crate) fn files_read_columns(spec: &TableSpec) -> Result<Vec<ReadColumn>, Vec<String>> {
    let mut problems: Vec<String> = Vec::new();
    let mut columns: Vec<ReadColumn> = Vec::new();
    for column in &spec.source_table.columns {
        let excluded = spec
            .excluded_columns
            .iter()
            .any(|(excluded, _)| *excluded == column.name);
        let output = match (spec.pinned.get(&column.name), &column.column_type) {
            _ if excluded => continue,
            (Some(pinned), _) => pinned.clone(),
            (None, Ok(column_type)) => column_type.clone(),
            (None, Err(reason)) => {
                problems.push(format!("column {}: {reason}", column.name));
                continue;
            }
        };
        columns.push(ReadColumn {
            name: column.name.clone(),
            expression: column.name.clone(),
            wire: WireType::Text,
            output,
        });
    }
    match problems.is_empty() {
        true => Ok(columns),
        false => Err(problems),
    }
}

/// What a files source's load reads: the files in the cursor window that are not loaded yet.
pub(crate) struct FilesPlanRequest<'a> {
    pub(crate) spec: &'a TableSpec,
    pub(crate) files: &'a FilesSource,
    pub(crate) loaded: LoadedSource<'a>,
    pub(crate) live: Option<&'a [LiveColumn]>,
    pub(crate) read_columns: &'a [ReadColumn],
    pub(crate) written: &'a [String],
    pub(crate) bounds: (Option<&'a str>, Option<&'a str>),
    pub(crate) options: &'a PlanOptions,
}

/// Where an `append` finds the source files already loaded.
#[derive(Debug, Clone, Copy)]
pub(crate) enum LoadedSource<'a> {
    /// The warehouse table's `_sqlload_source_file` values.
    Query(&'a Destination),
    /// A files target's records of what its loads loaded.
    Recorded(&'a [LoadedFile]),
}

/// The files a merge already merged into `request`'s table at the version listed now, which it skips (one rewritten in place since is merged again, as the newest), or why a files source cannot merge into it: only into a DuckDB or Postgres table, never with `--reload` (one commit would lose the files' order) or `state = "logged"`; none while the table does not exist.
async fn merge_ledger(
    request: &FilesPlanRequest<'_>,
) -> Result<Result<Vec<LoadedFile>, String>, LoaderError> {
    let spec = request.spec;
    let destination = match request.loaded {
        LoadedSource::Query(destination) => destination,
        LoadedSource::Recorded(_) => {
            return Ok(Err("merge is not supported for files targets".to_owned()));
        }
    };
    if !sql_adapter(spec.warehouse).merges_files() {
        return Ok(Err(format!(
            "merge from a files source loads into DuckDB and Postgres targets so far, not {}; use append, or delete_insert on a partition cursor",
            spec.warehouse
        )));
    }
    if request.options.reload {
        return Ok(Err(
            "--reload would merge every file in one commit and lose their order; drop the table and load again to merge every file anew".to_owned(),
        ));
    }
    if spec.logged {
        return Ok(Err(
            "state = \"logged\" does not apply to a files source's merge, which records each file it merges".to_owned(),
        ));
    }
    if let Some(cursor) = &spec.cursor {
        return Ok(Err(format!(
            "cursor_column {} does not apply to a files source's merge, which picks the files it has not merged from the run log, whatever their partition; remove it and set write_strategy = \"merge\", or keep it and use delete_insert",
            cursor.column
        )));
    }
    let merged = match request.live {
        None => return Ok(Ok(Vec::new())),
        Some(_) => merged_files(spec, destination).await?,
    };
    let location = request.files.location.to_string();
    let listed: HashMap<String, String> = request
        .files
        .table
        .files
        .iter()
        .map(|data| {
            (
                format!("{location}{}", data.file.relative_key),
                data.file.version(),
            )
        })
        .collect();
    Ok(merged.map(|merged| unchanged_files(merged, &listed)))
}

/// The newest record of each `merged` file (records come oldest first), kept when the file is still listed at that version or no longer listed: a file changed since, even back to an earlier version, merges again.
fn unchanged_files(merged: Vec<LoadedFile>, listed: &HashMap<String, String>) -> Vec<LoadedFile> {
    let mut newest: HashMap<String, LoadedFile> = HashMap::new();
    for file in merged {
        newest.insert(file.name.clone(), file);
    }
    newest
        .into_values()
        .filter(|file| {
            listed
                .get(&file.name)
                .is_none_or(|version| *version == file.version)
        })
        .collect()
}

/// A row of the loaded-files query: `file|version`, or just the file when `versioned` is false.
pub(crate) fn loaded_file(text: String, versioned: bool) -> LoadedFile {
    match (versioned, text.rsplit_once(VERSION_SEPARATOR)) {
        (true, Some((name, version))) => LoadedFile {
            name: name.to_owned(),
            version: version.to_owned(),
        },
        _ => LoadedFile {
            name: text,
            version: String::new(),
        },
    }
}

/// Whether the live table has `column`.
fn live_has(live: Option<&[LiveColumn]>, column: &str) -> bool {
    match live {
        Some(live) => live
            .iter()
            .any(|existing| existing.name.eq_ignore_ascii_case(column)),
        None => false,
    }
}

/// The columns of `columns` SQLLoad's reader keeps at nanoseconds for `spec`'s warehouse: those the files store at nanoseconds, unless pinned or `live` holds fewer digits.
pub(crate) fn nanosecond_columns(
    spec: &TableSpec,
    columns: &[FileColumn],
    live: Option<&[LiveColumn]>,
) -> Vec<String> {
    match sql_adapter(spec.warehouse).keeps_nanoseconds() {
        true => columns
            .iter()
            .filter(|column| {
                matches!(
                    column.stored_read,
                    StoredRead::Nanos | StoredRead::Epoch(NANOSECOND_SCALE)
                )
            })
            .filter(|column| {
                let loaded = spec.source_table.loaded_as(&column.name);
                !spec.pinned.contains_key(loaded) && fewer_digits(live, loaded).is_none()
            })
            .map(|column| column.name.clone())
            .collect(),
        false => Vec::new(),
    }
}

/// A warning for each column the files store at nanoseconds but the live table holds at fewer digits, so the load cuts them; a column whose type is pinned is the user's choice and is not warned about.
pub(crate) fn truncated_nanoseconds(spec: &TableSpec, live: Option<&[LiveColumn]>) -> Vec<String> {
    let Some(files) = &spec.files else {
        return Vec::new();
    };
    files
        .table
        .columns
        .iter()
        .filter(|column| {
            matches!(
                column.stored_read,
                StoredRead::Nanos | StoredRead::Epoch(NANOSECOND_SCALE)
            ) && !spec
                .pinned
                .contains_key(spec.source_table.loaded_as(&column.name))
        })
        .filter_map(|column| truncated_warning(live, spec.source_table.loaded_as(&column.name)))
        .collect()
}

/// The warning for column `name` when the live column holds fewer than nanosecond digits.
fn truncated_warning(live: Option<&[LiveColumn]>, name: &str) -> Option<String> {
    let digits = fewer_digits(live, name)?;
    Some(format!(
        "{name}: nanoseconds in the files, but the column holds {digits} digits after the second, so they are truncated.\nRebuild the column at (9) (--reload) to keep them."
    ))
}

/// The digits after the second the live column `name` holds, when fewer than nanoseconds, so SQLLoad's reader cuts its values.
fn fewer_digits(live: Option<&[LiveColumn]>, name: &str) -> Option<i64> {
    live.into_iter()
        .flatten()
        .find(|existing| existing.name.eq_ignore_ascii_case(name))
        .and_then(|existing| existing.fraction_digits)
        .filter(|digits| *digits < i64::from(NANOSECOND_SCALE))
}

/// How to give a table with rows a column a load needs, on `warehouse`.
pub(crate) fn column_fix(warehouse: Warehouse) -> &'static str {
    match sql_adapter(warehouse).keeps_tables() {
        true => KEPT_TABLES_COLUMN_FIX,
        false => RELOAD_FIX,
    }
}

/// The files to read, or why the table cannot be loaded.
pub(crate) async fn plan_files(
    request: &FilesPlanRequest<'_>,
) -> Result<Result<FilesRead, String>, LoaderError> {
    let spec = request.spec;
    let cursor = match &spec.cursor {
        None => None,
        Some(cursor) => match request
            .files
            .partition_types
            .iter()
            .find(|(name, _)| name == spec.source_table.spelling(&cursor.column))
        {
            Some((name, column_type)) => Some((name.as_str(), column_type)),
            None => {
                return Ok(Err(format!(
                    "cursor_column {} must be one of the partition_columns or path_columns for a files source",
                    cursor.column
                )));
            }
        },
    };
    if let Some((name, _)) = cursor
        && request
            .files
            .constants
            .iter()
            .any(|constant| constant == name)
    {
        return Ok(Err(format!(
            "cursor_column {name} is a constant column, the same in every file, so it cannot pick the files to read; use a partition_columns or path_columns column"
        )));
    }
    if let AfterLoad::MoveTo(move_to) = &spec.after_load
        && let Err(problem) = move_to_prefix(&request.files.location, move_to)
    {
        return Ok(Err(problem));
    }
    if spec.after_load != AfterLoad::Keep && request.options.reload {
        return Ok(Err(
            "--reload would rebuild the table from the files still in its folder, and after_load has deleted or moved the ones already loaded".to_owned(),
        ));
    }
    let merged = match spec.strategy == WriteStrategy::Merge {
        true => match merge_ledger(request).await? {
            Ok(merged) => Some(merged),
            Err(problem) => return Ok(Err(problem)),
        },
        false => None,
    };
    let skips_loaded = spec.strategy == WriteStrategy::Append;
    if skips_loaded
        && request.live.is_some()
        && !live_has(request.live, SOURCE_FILE_COLUMN)
        && !request.options.reload
    {
        return Ok(Err(format!(
            "the table has no {SOURCE_FILE_COLUMN} column, so append cannot tell which files are loaded and would load them all again; {}",
            column_fix(spec.warehouse)
        )));
    }
    if skips_loaded
        && !request
            .written
            .iter()
            .any(|name| name == SOURCE_FILE_COLUMN)
    {
        return Ok(Err(format!(
            "{SOURCE_FILE_COLUMN} must be loaded: append uses it to skip files already loaded"
        )));
    }
    let live_has = |column: &str| live_has(request.live, column);
    let loaded: Vec<LoadedFile> =
        match skips_loaded && live_has(SOURCE_FILE_COLUMN) && !request.options.reload {
            true => match request.loaded {
                LoadedSource::Query(destination) => {
                    let version = live_has(SOURCE_VERSION_COLUMN).then_some(SOURCE_VERSION_COLUMN);
                    let query = sql_adapter(spec.warehouse).render_loaded_files_query(
                        &spec.destination,
                        SOURCE_FILE_COLUMN,
                        version,
                    );
                    text_values(destination, query)
                        .await?
                        .into_iter()
                        .map(|text| loaded_file(text, version.is_some()))
                        .collect()
                }
                LoadedSource::Recorded(recorded) => recorded.to_vec(),
            },
            false => Vec::new(),
        };
    let loaded = merged.clone().unwrap_or(loaded);
    let location = request.files.location.to_string();
    let selection = FileSelection {
        files: &request.files.table.files,
        location: &location,
        loaded: &loaded,
        removed: spec.after_load != AfterLoad::Keep,
        cursor,
        from: request.bounds.0,
        to: request.bounds.1,
    };
    let (columns, inferred) =
        files_read_as(spec, request.read_columns, &request.files.partition_types);
    let checks = TextChecks {
        inferred,
        ..request.files.checks.clone()
    };
    let nanos = nanosecond_columns(spec, &request.files.table.columns, request.live);
    let ordered = select_files(&selection).map(|files| match merged {
        Some(_) => merge_order(files),
        None => files,
    });
    Ok(ordered.map(|files| FilesRead {
        files,
        encoding: request.files.encoding.clone(),
        checks,
        columns,
        nanos,
        batch_rows: SOURCE_BATCH_ROWS,
    }))
}

/// Which part of a table's planned read one pass reads: a cursor window's filter, an order, or some of a files source's files.
#[derive(Debug, Clone, Default)]
pub(crate) struct ReadPart {
    /// The Postgres filter; `None` reads the plan's.
    pub(crate) filter: Option<String>,
    /// The values bound to `filter`'s `?` placeholders, in order.
    #[cfg_attr(
        not(feature = "odbc"),
        expect(dead_code, reason = "only ODBC sources bind parameters")
    )]
    pub(crate) parameters: Vec<BoundParameter>,
    /// `ORDER BY` this quoted column.
    pub(crate) order_by: Option<String>,
    /// The files to read; `None` reads every planned file.
    pub(crate) files: Option<Vec<DataFile>>,
    /// The Parquet footers already read for `files`.
    pub(crate) footers: BatchFooters,
    /// A smaller byte cap for the source's batches than the usual 64 MiB (the hidden `--batch-bytes`, for tests).
    pub(crate) batch_bytes: Option<usize>,
}

/// Read `part` of `table`'s rows from `reader`, handing each batch to `on_batch`; when `on_batch` fails, the read fails with the reader's text, and stays retryable when `on_batch`'s error was.
pub(crate) async fn read_source(
    reader: &SourceReader,
    table: &TablePlan,
    part: ReadPart,
    mut on_batch: impl AsyncFnMut(RecordBatch) -> Result<(), LoaderError>,
) -> Result<u64, LoaderError> {
    let mut failed: Option<LoaderError> = None;
    let read = Box::pin(read_each(reader, table, part, async |batch| {
        on_batch(batch).await.map_err(|error| {
            let text = error.to_string();
            failed = Some(error);
            text
        })
    }))
    .await;
    match (read, failed) {
        (Err(read), Some(failed)) if failed.is_retryable() => {
            Err(LoaderError::Transient(read.to_string()))
        }
        (read, _) => read,
    }
}

/// Read `part` of `table`'s data from `reader`, passing each batch to `on_batch`; returns the row count.
async fn read_each(
    reader: &SourceReader,
    table: &TablePlan,
    part: ReadPart,
    on_batch: impl AsyncFnMut(RecordBatch) -> Result<(), String>,
) -> Result<u64, LoaderError> {
    match (reader, &table.files) {
        (SourceReader::Postgres(client, helpers), _) => {
            let whole = part.filter.is_none() && part.order_by.is_none();
            let request = CopyRequest {
                table: &table.spec.source_table,
                columns: table.read_columns.clone(),
                filter: part.filter.or_else(|| table.source_filter.clone()),
                order_by: part.order_by,
                batch_rows: SOURCE_BATCH_ROWS,
                batch_bytes: part
                    .batch_bytes
                    .map_or(DEFAULT_BATCH_BYTES, |bytes| bytes.min(DEFAULT_BATCH_BYTES)),
                helpers: match whole {
                    true => helpers,
                    false => &[],
                },
            };
            Ok(copy_table(client, request, on_batch).await?)
        }
        (SourceReader::Files(folder), Some(files)) => {
            let read = match part.files.clone() {
                Some(subset) => FilesRead {
                    files: subset,
                    ..files.clone()
                },
                None => files.clone(),
            };
            let mut on_batch = on_batch;
            let loaded = async |batch: RecordBatch| {
                on_batch(loaded_batch(&batch, &table.spec.source_table)?).await
            };
            Ok(read_files(folder, &read, &part.footers, loaded).await?)
        }
        (SourceReader::Snowflake(snowflake), _) => {
            let filter = part.filter.or_else(|| table.source_filter.clone());
            let request = unload_request(table, filter.as_deref());
            Ok(unload_rows(snowflake, &request, on_batch).await?)
        }
        #[cfg(feature = "odbc")]
        (SourceReader::Odbc(reader), _) => {
            let (filter, parameters) = match part.filter {
                Some(filter) => (Some(filter), &part.parameters[..]),
                None => (table.source_filter.clone(), &table.source_parameters[..]),
            };
            let request = crate::odbc_source::models::OdbcReadRequest {
                table: &table.spec.source_table,
                sql: table
                    .spec
                    .warehouse_source
                    .as_ref()
                    .and_then(|source| source.sql.as_deref()),
                columns: &table.read_columns,
                filter: filter.as_deref(),
                parameters,
                batch_rows: SOURCE_BATCH_ROWS,
            };
            Ok(crate::odbc_source::main::read_rows::read_rows(reader, &request, on_batch).await?)
        }
        (SourceReader::BigQuery(reader), _) => {
            let filter = part.filter.or_else(|| table.source_filter.clone());
            let request = BigQueryReadRequest {
                table: &table.spec.source_table,
                sql: table
                    .spec
                    .warehouse_source
                    .as_ref()
                    .and_then(|source| source.sql.as_deref()),
                columns: &table.read_columns,
                filter: filter.as_deref(),
            };
            Ok(read_bigquery_rows(reader, &request, on_batch).await?)
        }
        (SourceReader::Sheets(client, spreadsheet_id), _) => {
            let batch = loaded_batch(
                &sheet_rows(client, spreadsheet_id, table).await?,
                &table.spec.source_table,
            )
            .map_err(LoaderError::Invalid)?;
            let rows = batch.num_rows() as u64;
            let mut on_batch = on_batch;
            on_batch(batch).await.map_err(LoaderError::Invalid)?;
            Ok(rows)
        }
        (SourceReader::Files(_), None) => Err(LoaderError::Invalid(format!(
            "{}: a files source has no files planned",
            table.spec.source_table.qualified_name()
        ))),
    }
}

/// Unload `part` of `table`'s data from `reader` and pass the files to `load`, which has the destination read them itself; the files are removed afterwards.
pub(crate) async fn unload_source<T>(
    reader: &SourceReader,
    table: &TablePlan,
    part: ReadPart,
    load: impl AsyncFnOnce(&UnloadedFiles) -> Result<T, LoaderError>,
) -> Result<T, LoaderError> {
    let SourceReader::Snowflake(snowflake) = reader else {
        return Err(LoaderError::Invalid(format!(
            "{}: only a warehouse source unloads files",
            table.spec.source_table.qualified_name()
        )));
    };
    let filter = part.filter.or_else(|| table.source_filter.clone());
    unload_files(snowflake, &unload_request(table, filter.as_deref()), load).await
}

/// What one unload of `table` reads: its table or query, its read columns, and `filter`.
fn unload_request<'a>(table: &'a TablePlan, filter: Option<&'a str>) -> UnloadRequest<'a> {
    UnloadRequest {
        table: &table.spec.source_table,
        sql: table
            .spec
            .warehouse_source
            .as_ref()
            .and_then(|source| source.sql.as_deref()),
        columns: &table.read_columns,
        filter,
        batch_rows: SOURCE_BATCH_ROWS,
    }
}

/// `specs` with `source_end` filled for the selected Postgres tables whose integer `batch_size` has no `--end-cursor` to end its windows: the cursor's current maximum, read once at plan; the source is connected only when one needs it.
pub(crate) async fn source_ends(
    project: &ProjectConfig,
    (source_name, source): (&str, &SourceConfig),
    mut specs: Vec<TableSpec>,
    options: &PlanOptions,
) -> Result<Vec<TableSpec>, LoaderError> {
    if source.kind != SourceKind::Postgres || options.end_cursor.is_some() {
        return Ok(specs);
    }
    let mut client: Option<Client> = None;
    for spec in &mut specs {
        let integer_cursor = spec.cursor.as_ref().and_then(|cursor| {
            spec.source_table
                .columns
                .iter()
                .find(|column| column.name == cursor.column)
                .filter(|column| {
                    matches!(
                        column.column_type,
                        Ok(ColumnType::Int | ColumnType::SmallInt)
                    )
                })
                .map(|column| {
                    column
                        .source_spelling
                        .clone()
                        .unwrap_or_else(|| column.name.clone())
                })
        });
        let wanted = matches!(spec.batch, Some(BatchStep::Integer(_)))
            && selected(
                options,
                (
                    source_name,
                    &spec.destination.table,
                    &spec.source_table.qualified_name(),
                ),
            );
        let Some(column) = integer_cursor.filter(|_| wanted) else {
            continue;
        };
        if client.is_none() {
            client = Some(connect_source(project, source).await?.0);
        }
        let Some(connected) = &client else {
            continue;
        };
        spec.source_end = Some(
            match cursor_end(connected, &spec.source_table, &column).await? {
                Some((maximum, end)) => SourceEnd::Maximum { maximum, end },
                None => SourceEnd::Empty,
            },
        );
    }
    Ok(specs)
}

/// Each of `specs`' destination name and `schema.table`, which selectors may name.
pub(crate) fn destination_names(specs: &[TableSpec]) -> Vec<(String, String)> {
    specs
        .iter()
        .map(|spec| {
            (
                spec.destination.table.clone(),
                spec.source_table.qualified_name(),
            )
        })
        .collect()
}

/// A warning for each selector matching no source or table, with the nearest name: `load` would otherwise say only `0 selected`.
pub(crate) fn unmatched_selectors(
    project: &ProjectConfig,
    options: &PlanOptions,
    names: &[(String, String)],
) -> Vec<String> {
    let known: Vec<&str> = names
        .iter()
        .flat_map(|(destination, source_table)| [destination.as_str(), source_table.as_str()])
        .chain(project.sources.keys().map(String::as_str))
        .collect();
    options
        .select
        .iter()
        .chain(&options.exclude)
        .filter(|selector| !known.contains(&selector.as_str()))
        .map(
            |selector| match nearest_name(selector, known.iter().copied()) {
                Some(nearest) => format!("no table matches {selector}; did you mean {nearest}?"),
                None => format!("no table matches {selector}"),
            },
        )
        .collect()
}

/// Whether `--select` picks a table and `--exclude` does not, each by source name, destination name or `schema.table`; no `--select` picks every table.
pub(crate) fn selected(
    options: &PlanOptions,
    (source, destination, source_table): (&str, &str, &str),
) -> bool {
    let picks = |selector: &String| {
        selector == source || selector == destination || selector == source_table
    };
    (options.select.is_empty() || options.select.iter().any(picks))
        && !options.exclude.iter().any(picks)
}

/// Source `source_name`'s tables resolved to their settings, with its files for a files source, or `Err` with its problem when it cannot list them (`None` when out of scope); its problems count only when the selection in `options` takes something from it (see [`source_in_scope`]), and are dropped otherwise.
pub(crate) async fn scoped_tables(
    (project, options): (&ProjectConfig, &PlanOptions),
    (source_name, source): (&str, &SourceConfig),
) -> Result<Result<(ResolvedTables, Option<FilesSource>), Option<SourceProblem>>, LoaderError> {
    let (discovered, files, warnings) = match source_tables(project, source_name, source).await? {
        Ok(found) => found,
        Err(problem) => {
            let in_scope = source_in_scope((project, options), (source_name, source), None);
            return Ok(Err(in_scope.then(|| SourceProblem {
                message: format!("[sources.{source_name}]: {}", problem.message),
                retryable: problem.retryable,
            })));
        }
    };
    if source.kind == SourceKind::Files && discovered.is_empty() {
        return Ok(Ok((
            drained_files((project, options), (source_name, source)),
            None,
        )));
    }
    let mut resolved = resolve_tables(project, source_name, &discovered);
    match source_in_scope((project, options), (source_name, source), Some(&discovered)) {
        true => resolved.warnings = warnings,
        false => resolved.problems.clear(),
    }
    Ok(Ok((resolved, files)))
}

/// A files source whose `after_load` emptied its folder, which a load leaves alone until new files come, as with `keep` every file in the folder is already loaded: its destination table, which [`found_sources`] checks exists before skipping it (when the selection in `options` takes it).
fn drained_files(
    (project, options): (&ProjectConfig, &PlanOptions),
    (source_name, source): (&str, &SourceConfig),
) -> ResolvedTables {
    let target = match source_target(project, source) {
        Ok(target) => target,
        Err(problem) => {
            return ResolvedTables {
                problems: vec![format!("[sources.{source_name}]: {problem}")],
                ..ResolvedTables::default()
            };
        }
    };
    let overrides = source.tables.get(source_name);
    let name = overrides.and_then(|table| table.name.as_deref());
    let unset = TableSettings::default();
    let naming = table_naming(
        (
            overrides.map_or(&unset, |overrides| &overrides.settings),
            &source.defaults,
        ),
        target.naming,
    );
    let rule = (
        naming,
        sql_adapter(target.warehouse).max_identifier_length(),
    );
    let listed = SourceTable {
        schema: String::new(),
        name: source_name.to_owned(),
        columns: referenced_columns(overrides, rule),
        primary_key: Vec::new(),
        indexed_columns: Vec::new(),
        estimated_rows: -1,
        estimated_bytes: 0,
        comment: None,
    };
    let table = TableName {
        database: target.database,
        schema: target.schema,
        table: table_name((source_name, source), name, (&listed, rule)),
    };
    let in_scope = selected(options, (source_name, &table.table, source_name));
    if target.path.is_some() {
        return ResolvedTables {
            problems: in_scope
                .then(|| {
                    format!("[sources.{source_name}]: after_load is for database targets so far, not a files target")
                })
                .into_iter()
                .collect(),
            ..ResolvedTables::default()
        };
    }
    let path = source.path.as_deref().unwrap_or_default();
    let spec = resolve_tables(project, source_name, std::slice::from_ref(&listed))
        .specs
        .pop();
    ResolvedTables {
        drained: Some(DrainedFiles {
            spec,
            in_scope,
            target: target.name,
            skipped: SkippedTable {
                source_name: source_name.to_owned(),
                source_table: source_name.to_owned(),
                reason: format!(
                    "no files to load in {path}: after_load deleted or moved the ones already loaded"
                ),
            },
            problem: format!(
                "[sources.{source_name}]: no files to load in {path}, and {} was never loaded: after_load skips an emptied folder only once its table exists; check the source's path and connection",
                table.table
            ),
            table,
        }),
        ..ResolvedTables::default()
    }
}

/// Whether the selection in `options` takes anything from source `source_name`: a table it `listed`, or one named under its `tables` but not listed, by destination name or `schema.table`, or the source itself when it holds no table. A source that could not list its tables (`None`) counts when selected by name, or for any `--select` selector naming no source, since that table could be its. Only then do the source's problems count, so one source's bad settings do not fail a command run on another.
pub(crate) fn source_in_scope(
    (project, options): (&ProjectConfig, &PlanOptions),
    (source_name, source): (&str, &SourceConfig),
    listed: Option<&[SourceTable]>,
) -> bool {
    let Some(discovered) = listed else {
        return selected(options, (source_name, "", ""))
            || (!options
                .exclude
                .iter()
                .any(|selector| selector == source_name)
                && options
                    .select
                    .iter()
                    .any(|selector| !project.sources.contains_key(selector)));
    };
    let found: Vec<String> = discovered.iter().map(SourceTable::qualified_name).collect();
    let (target_naming, limit) = source_target(project, source).map_or((None, None), |target| {
        (
            target.naming,
            sql_adapter(target.warehouse).max_identifier_length(),
        )
    });
    let unset = TableSettings::default();
    let rule = |overrides: Option<&TableOverride>| {
        (
            table_naming(
                (
                    overrides.map_or(&unset, |overrides| &overrides.settings),
                    &source.defaults,
                ),
                target_naming,
            ),
            limit,
        )
    };
    let named = source
        .tables
        .iter()
        .filter(|(qualified, _)| !found.contains(qualified))
        .map(|(qualified, overrides)| {
            let destination = match overrides.name.as_deref() {
                Some(name) if !name.contains('{') => {
                    let (naming, limit) = rule(Some(overrides));
                    loaded_name(naming, name, limit)
                }
                _ => String::new(),
            };
            (destination, qualified.clone())
        });
    let tables: Vec<(String, String)> = discovered
        .iter()
        .map(|table| {
            let overrides = source.tables.get(&table.qualified_name());
            let name = overrides.and_then(|overrides| overrides.name.as_deref());
            (
                table_name((source_name, source), name, (table, rule(overrides))),
                table.qualified_name(),
            )
        })
        .chain(named)
        .collect();
    (tables.is_empty() && selected(options, (source_name, "", "")))
        || tables.iter().any(|(destination, qualified)| {
            selected(options, (source_name, destination, qualified))
        })
}

/// `planned`, the selected tables of one source, added to `plan`, which is returned (`unselected` and `found`, the destinations and options, tell whether this is the source's first load): a table that appeared after the source's first load (`first_load`: none of its tables, selected or not, existed yet) and is not named exactly in `include` is skipped or fails as `new_tables` says, and a table without a description is blocked.
pub(crate) async fn admit_tables(
    mut plan: ProjectPlan,
    (source_name, source): (&String, &SourceConfig),
    (planned, unselected): (Vec<TablePlan>, &[TableSpec]),
    found: (&BTreeMap<String, Destination>, &PlanOptions),
) -> Result<ProjectPlan, LoaderError> {
    let first_load = first_load(&planned, unselected, found).await?;
    let mut planned = planned;
    if let Some(problem) = partial_capture(source_name, source.kind, (&planned, unselected)) {
        for table in &mut planned {
            table.schema = blocked_plan(vec![problem.clone()]);
        }
    }
    for mut table in planned {
        let spec = &table.spec;
        let qualified = spec.source_table.qualified_name();
        let is_new = !first_load && !table.exists && !spec.approved;
        let has_settings = source.tables.contains_key(&qualified);
        match (is_new, spec.new_tables, has_settings) {
            (true, NewTables::Skip, true) => plan.skipped.push(SkippedTable {
                source_name: source_name.clone(),
                source_table: qualified,
                reason: "new table (new_tables = \"skip\") has settings but is not approved; add it to include".to_owned(),
            }),
            (true, NewTables::Skip, false) => plan.skipped.push(SkippedTable {
                source_name: source_name.clone(),
                source_table: qualified,
                reason: "new table (new_tables = \"skip\"); add it to include to sync it".to_owned(),
            }),
            (true, NewTables::Fail, _) => plan.problems.push(format!(
                "{qualified}: new table and new_tables = \"fail\"; add it to include or exclude it"
            )),
            _ => {
                if let Some(problem) = missing_description(source_name, source, &spec.source_table)
                {
                    table.schema = blocked_plan(vec![problem]);
                }
                plan.tables.push(table);
            }
        }
    }
    Ok(plan)
}

/// Why the selection cannot load `postgres_cdc` source `name`, which blocks every table it picks: it picks some of its tables (`planned`) but not all (`unselected`), and the slot they share would confirm the left-out tables' changes unwritten. A plan problem alone would not stop the picked tables loading.
fn partial_capture(
    name: &str,
    kind: SourceKind,
    (planned, unselected): (&[TablePlan], &[TableSpec]),
) -> Option<String> {
    let partial = kind == SourceKind::PostgresCdc && !planned.is_empty() && !unselected.is_empty();
    partial.then(|| {
        let left_out: Vec<String> = unselected
            .iter()
            .map(|spec| spec.source_table.qualified_name())
            .collect();
        format!(
            "this selection leaves out {} of source {name}, whose changes share its one slot and would be skipped; select the whole source, or move those tables to another postgres_cdc source",
            left_out.join(", ")
        )
    })
}

/// Whether this is the source's first load: none of its tables exists in the destination, whether selected (`planned`) or not (`unselected`, looked up only while none is found, a table that cannot be read counting as absent), so `--select` cannot make a later table look present at the first load.
async fn first_load(
    planned: &[TablePlan],
    unselected: &[TableSpec],
    (destinations, options): (&BTreeMap<String, Destination>, &PlanOptions),
) -> Result<bool, LoaderError> {
    if planned.iter().any(|table| table.exists) {
        return Ok(false);
    }
    for spec in unselected {
        let Some(destination) = destinations.get(&spec.target) else {
            continue;
        };
        let exists = match files_destination(destination) {
            Some(_) => plan_table(spec, destination, options)
                .await
                .is_ok_and(|table| table.exists),
            None => live_columns(destination, &spec.destination)
                .await
                .is_ok_and(|live| live.is_some()),
        };
        if exists {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Every source's tables, resolved before any is planned so each knows which others share its destination table, with the folders they claim; a source whose tables cannot be read is a problem in the plan.
pub(crate) async fn found_sources<'a>(
    project: &'a ProjectConfig,
    destinations: &BTreeMap<String, Destination>,
    options: &PlanOptions,
) -> Result<FoundSources<'a>, LoaderError> {
    let mut found = FoundSources::default();
    let mut drained_sources: Vec<(usize, DrainedFiles)> = Vec::new();
    for (source_name, source) in &project.sources {
        let (mut resolved, files) =
            match scoped_tables((project, options), (source_name, source)).await? {
                Ok(tables) => tables,
                Err(problem) => {
                    found.unresolved.push(source_name.clone());
                    if let Some(problem) = problem {
                        if problem.retryable {
                            found.plan.retryable_problems.push(problem.message.clone());
                        }
                        found.plan.problems.push(problem.message);
                    }
                    continue;
                }
            };
        if let Some(drained) = resolved.drained.take() {
            drained_sources.push((found.sources.len(), drained));
        }
        found
            .claims
            .extend(folder_claims(&resolved.specs, files.as_ref(), destinations));
        found.configured.extend(resolved.specs.iter().cloned());
        found.sources.push(FoundSource {
            name: source_name,
            source,
            resolved,
            files,
        });
    }
    let mut drained_specs: Vec<TableSpec> = Vec::new();
    for (index, drained) in drained_sources {
        let source = &mut found.sources[index];
        let shared = found
            .configured
            .iter()
            .any(|spec| spec.target == drained.target && spec.destination == drained.table);
        if shared {
            found.unresolved.push(source.name.clone());
        }
        found
            .drained
            .push((drained.table.table.clone(), source.name.clone()));
        drained_specs.extend(drained.spec);
        if !drained.in_scope {
            continue;
        }
        let exists = match destinations.get(&drained.target) {
            Some(destination) => live_columns(destination, &drained.table).await?.is_some(),
            None => false,
        };
        let path = source.source.path.as_deref().unwrap_or_default();
        let problem = match (exists, shared, options.reload) {
            (false, _, _) => Some(drained.problem),
            (true, true, _) => Some(format!(
                "[sources.{}]: no files to load in {path}, and other tables load into {} too: a load that cannot see this source could misread or remove its rows, so it fails until files come; run the others with --exclude {}",
                source.name, drained.table.table, source.name
            )),
            (true, false, true) => Some(format!(
                "[sources.{}]: --reload would rebuild the table from the files still in its folder, and after_load has deleted or moved the ones already loaded",
                source.name
            )),
            (true, false, false) => None,
        };
        match problem {
            Some(problem) => source.resolved.problems.push(problem),
            None => source.resolved.skipped.push(drained.skipped),
        }
    }
    found.configured.extend(drained_specs);
    Ok(found)
}

/// The folders files tables write to, whether or not they are selected, with the folder their files source (`files`) reads; warehouse tables and paths that do not resolve claim none.
fn folder_claims(
    specs: &[TableSpec],
    files: Option<&FilesSource>,
    destinations: &BTreeMap<String, Destination>,
) -> Vec<FolderClaim> {
    let mut claims: Vec<FolderClaim> = Vec::new();
    for spec in specs {
        let Some(target) = destinations.get(&spec.target).and_then(files_destination) else {
            continue;
        };
        let name = format!(
            "{}.{}",
            spec.source_name,
            spec.source_table.qualified_name()
        );
        if let Ok(path) = table_folder(spec, target) {
            claims.push(FolderClaim {
                id: name.clone(),
                name,
                folder: path.folder,
                template: spec.destination_path.clone().unwrap_or_default(),
                schema: spec.source_table.schema.clone(),
                source: files.map(|files| files.location.clone()),
            });
        }
    }
    claims
}