sqlload 0.57.0

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
use std::collections::BTreeMap;
use std::io::IsTerminal;
use std::path::Path;
use std::sync::Arc;

use crate::adapters::contract::main::cursor_text::cursor_text;
use crate::adapters::dispatch::models::Destination;
use crate::auth::main::allow_sign_in::allow_sign_in;
use crate::column_types::models::ColumnType;
use crate::command::_helpers::load_output::{
    EventsTarget, LiveState, LoadOutput, change_tally_line, planning, start_lines, summary_lines,
    write_events,
};
use crate::command::_helpers::output::{confirm_reload, print_lines};
use crate::command::_helpers::project_file::replace_file;
use crate::command::_helpers::signals::wait_for_signal;
use crate::command::constants::{
    CURSOR_FLAGS_MIXED, FORCED_STOP_EXIT, RELOAD_DECLINED, RETRYABLE_EXIT,
};
use crate::command::errors::CommandError;
use crate::command::models::{
    Command, ContractAction, EventsFormat, LoaderArgs, LoaderRequest, Progress, StateAction,
};
use crate::contract::main::compare_contracts::compare_contracts;
use crate::contract::main::render_contract::render_contract;
use crate::contract::main::write_contracts::write_contracts;
use crate::contract::models::{ContractReport, ContractRequest};
use crate::load_events::main::close::close;
use crate::load_events::main::emit::emit;
use crate::load_events::main::listen::listen;
use crate::load_events::main::take_timings::take_timings;
use crate::load_events::models::{EventKind, LoadEvent};
use crate::loader::constants::{NO_PYTHON_HOST, NO_RENAME_HOST, NO_TRANSFORM_HOST};
use crate::loader::main::apply_project::apply_project;
use crate::loader::main::connect_targets::connect_targets;
use crate::loader::main::debug_project::debug_project;
use crate::loader::main::json_report::json_report;
use crate::loader::main::load_tables::load_tables;
use crate::loader::main::plan_project::plan_project;
use crate::loader::main::render_plan::render_plan;
use crate::loader::main::render_tally::render_tally;
use crate::loader::main::state_command::state_command;
use crate::loader::models::{
    LoadRun, PlanOptions, ProjectPlan, RangeFlags, RunReport, StateKind, StateRequest,
    TableOutcome, TablePlan, TypedCursors,
};
use crate::number_text::main::thousands::thousands;
use crate::peak_memory::constants::MEMORY_PER_TABLE_NEEDS_LINUX;
use crate::peak_memory::main::run_peak_bytes::run_peak_bytes;
use crate::project::main::config_lines::config_lines;
use crate::project::main::parse_project::parse_project;
use crate::project::main::parse_python_project::parse_python_project;
use crate::project::models::{ProjectConfig, RenameSetting, SourceKind, TableSettings};
use crate::python_sources::types::PythonHost;
use tokio::sync::mpsc::UnboundedReceiver;
use tokio_util::sync::CancellationToken;

fn environment_variable(name: &str) -> Option<String> {
    match std::env::var(name) {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent | std::env::VarError::NotUnicode(_)) => None,
    }
}

/// `name`'s value for `${ENV:NAME}`: from `variables`, else the process environment.
fn variable(variables: &BTreeMap<String, String>, name: &str) -> Option<String> {
    variables
        .get(name)
        .cloned()
        .or_else(|| environment_variable(name))
}

/// The plan options `args` give.
pub(crate) fn options(args: LoaderArgs) -> Result<PlanOptions, String> {
    if args.memory_per_table && !cfg!(target_os = "linux") {
        return Err(MEMORY_PER_TABLE_NEEDS_LINUX.to_owned());
    }
    let typed_cursors = TypedCursors {
        start_ts: args.start_cursor_ts,
        end_ts: args.end_cursor_ts,
        start_int: args.start_cursor_int,
        end_int: args.end_cursor_int,
    };
    let typed = [
        (
            "--start-cursor-ts",
            &typed_cursors.start_ts,
            ColumnType::TimestampTz,
        ),
        (
            "--end-cursor-ts",
            &typed_cursors.end_ts,
            ColumnType::TimestampTz,
        ),
        (
            "--start-cursor-int",
            &typed_cursors.start_int,
            ColumnType::Int,
        ),
        ("--end-cursor-int", &typed_cursors.end_int, ColumnType::Int),
    ];
    let untyped = args.start_cursor.is_some() || args.end_cursor.is_some();
    if untyped && typed.iter().any(|(_, value, _)| value.is_some()) {
        return Err(CURSOR_FLAGS_MIXED.to_owned());
    }
    for (flag, value, column_type) in &typed {
        let Some(value) = value else {
            continue;
        };
        if cursor_text(value, column_type, chrono_tz::Tz::UTC).is_err() {
            return Err(match column_type {
                ColumnType::Int => format!("{flag} value '{value}' is not a whole number"),
                _ => format!("{flag} value '{value}' is not an RFC 3339 timestamp or a date"),
            });
        }
    }
    Ok(PlanOptions {
        typed_cursors,
        select: [args.positional_select, args.select].concat(),
        exclude: args.exclude,
        rebuild_allowed: args.allow_type_change_rebuild,
        reload: args.reload,
        start_cursor: args.start_cursor,
        end_cursor: args.end_cursor,
        range_flags: RangeFlags::default(),
        concurrency: args.concurrency.map(usize::from),
        resnapshot: args.resnapshot,
        sync_deletes: args.sync_deletes,
        fail_fast: args.fail_fast,
        memory_per_table: args.memory_per_table,
        batch_bytes: args
            .batch_bytes
            .map(|bytes| usize::try_from(bytes).unwrap_or(usize::MAX)),
    })
}

/// The project in `request.text`, with where its settings are written in its file; a project `sqlload copy` wrote has neither those lines nor the variables its connections read.
async fn load_project_config(request: &LoaderRequest<'_>) -> Result<ProjectConfig, String> {
    let mut project = parsed_project(request).await?;
    if request.generated {
        project.connection_variables.clear();
        return Ok(project);
    }
    let file = request.config.file_name().map_or_else(
        || request.config.display().to_string(),
        |name| name.to_string_lossy().into_owned(),
    );
    project.config_lines = config_lines(&file, request.text);
    Ok(project)
}

/// The project in `request.text`, with its Python sources discovered through the host when it has `python_paths`.
async fn parsed_project(request: &LoaderRequest<'_>) -> Result<ProjectConfig, String> {
    let lookup = |name: &str| variable(&request.variables, name);
    let project = parse_project(request.text, &lookup).map_err(|error| error.to_string())?;
    let transforms = transform_places(&project);
    if let (None, Some((place, _))) = (&request.host, transforms.first()) {
        return Err(NO_TRANSFORM_HOST.replace("{place}", place));
    }
    if let (None, Some((place, _))) = (&request.host, rename_places(&project).first()) {
        return Err(NO_RENAME_HOST.replace("{place}", place));
    }
    if project.python_paths.is_empty() {
        return Ok(project);
    }
    let Some(host) = request.host.clone() else {
        return Err(NO_PYTHON_HOST.to_owned());
    };
    let root = request
        .config
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    let paths = project.python_paths.clone();
    let discovering = Arc::clone(&host);
    let found = tokio::task::spawn_blocking(move || discovering.discover(&root, &paths))
        .await
        .map_err(|error| format!("Python discovery failed: {error}"))??;
    let mut project =
        parse_python_project(request.text, &lookup, &found).map_err(|error| error.to_string())?;
    for (_, function) in transforms {
        if project.transforms.contains_key(&function) {
            continue;
        }
        let checking = Arc::clone(&host);
        let called = function.clone();
        let version = tokio::task::spawn_blocking(move || checking.transform_version(&called))
            .await
            .map_err(|error| format!("Python transform check failed: {error}"))?;
        project.transforms.insert(function, version);
    }
    for (_, function) in rename_places(&project) {
        if project.renames.contains_key(&function) {
            continue;
        }
        let checking = Arc::clone(&host);
        let called = function.clone();
        let found = tokio::task::spawn_blocking(move || checking.rename(&called, None, "{}"))
            .await
            .map_err(|error| format!("Python rename check failed: {error}"))?;
        project.renames.insert(function, found.map(|_| ()));
    }
    project.python_host = Some(host);
    Ok(project)
}

/// Each source or table in `project` that sets `transform` (`source x` or `table x.y`), with its function.
fn transform_places(project: &ProjectConfig) -> Vec<(String, String)> {
    let mut places: Vec<(String, String)> = Vec::new();
    for (name, source) in &project.sources {
        if let Some(function) = &source.defaults.transform {
            places.push((format!("source {name}"), function.clone()));
        }
        for (table, overrides) in &source.tables {
            if let Some(function) = &overrides.settings.transform {
                places.push((format!("table {name}.{table}"), function.clone()));
            }
        }
    }
    places
}

/// Each source or table in `project` whose `rename` names a function (`source x` or `table x.y`), with the function.
fn rename_places(project: &ProjectConfig) -> Vec<(String, String)> {
    let function = |settings: &TableSettings| match &settings.rename {
        Some(RenameSetting::Function(function)) => Some(function.clone()),
        _ => None,
    };
    let mut places: Vec<(String, String)> = Vec::new();
    for (name, source) in &project.sources {
        if let Some(function) = function(&source.defaults) {
            places.push((format!("source {name}"), function));
        }
        for (table, overrides) in &source.tables {
            if let Some(function) = function(&overrides.settings) {
                places.push((format!("table {name}.{table}"), function));
            }
        }
    }
    places
}

/// The exit code of a command that succeeded (`ok`), or failed only in `retryable` ways, or failed otherwise.
pub(crate) fn exit_code(ok: bool, retryable: bool) -> u8 {
    match (ok, retryable) {
        (true, _) => 0,
        (false, true) => RETRYABLE_EXIT,
        (false, false) => 1,
    }
}

/// Run a loader command against the project in `request.text`: the lines to print, and its exit code. Under `--json` every failure is a JSON error document.
pub(crate) async fn run_loader(
    request: LoaderRequest<'_>,
) -> Result<(Vec<String>, u8), CommandError> {
    let name = match &request.command {
        Command::Apply(_) => "apply",
        Command::Load(_) => "load",
        _ => "plan",
    };
    let json = match &request.command {
        Command::Plan(args) | Command::Apply(args) if args.follow => {
            let error = "--follow and --max-duration apply to load only";
            return match args.json {
                true => Ok((vec![json_error(name, error, false)], 1)),
                false => Err(error.to_owned().into()),
            };
        }
        Command::Plan(args) | Command::Apply(args) | Command::Load(args) => args.json,
        _ => false,
    };
    let contract_json = match &request.command {
        Command::Contract {
            action: ContractAction::Diff(args),
        } => args.json,
        Command::Contract {
            action: ContractAction::Generate(chosen),
        } => chosen.tables.json,
        _ => false,
    };
    allow_sign_in(!(json || contract_json));
    let project = match load_project_config(&request).await {
        Ok(project) => project,
        Err(error) => return config_failure(&request.command, error).map_err(Into::into),
    };
    let outcome = match request.command {
        Command::Contract { action } => {
            let file = (request.config, request.text);
            run_contract(&project, action, file, &request.variables)
                .await
                .map(|(lines, agrees)| (lines, exit_code(agrees, false)))
                .map_err(Into::into)
        }
        command => {
            let shown = (request.no_color, request.streams, request.log_json);
            let outcome = run_command(&project, command, request.host.clone(), shown).await;
            close();
            outcome
        }
    };
    if let Some(host) = request.host {
        let _ = tokio::task::spawn_blocking(move || host.finish()).await;
    }
    match (outcome, json) {
        (Err(error), true) => Ok((
            vec![json_error(name, &error.message, error.retryable)],
            exit_code(false, error.retryable),
        )),
        (outcome, _) => outcome,
    }
}

/// Each problem in `error`: one per line of an `invalid project` list, else the whole error.
fn problems(error: &str) -> Vec<String> {
    match error.strip_prefix("invalid project:\n  - ") {
        Some(listed) => listed.split("\n  - ").map(str::to_owned).collect(),
        None => vec![error.to_owned()],
    }
}

/// `error` in sqlbuild's error shape, `{"error": {"code", "message", "help", "retryable"}}`: each problem's reason in `message` and its fix (the text after `Fix:`) in `help`, `null` when none has one; `retryable` when running the command again unchanged may succeed.
pub(crate) fn json_error(code: &str, error: &str, retryable: bool) -> String {
    let mut messages: Vec<String> = Vec::new();
    let mut helps: Vec<String> = Vec::new();
    for problem in problems(error) {
        match problem.split_once(" Fix: ") {
            Some((reason, fix)) => {
                messages.push(reason.trim_end_matches('.').to_owned());
                helps.push(fix.to_owned());
            }
            None => messages.push(problem),
        }
    }
    let help = (!helps.is_empty()).then(|| helps.join("\n"));
    serde_json::json!({ "error": { "code": code, "message": messages.join("\n"), "help": help, "retryable": retryable } })
        .to_string()
}

/// A project that does not parse: a failed plan's `Errors` for `plan`, `apply` and `load` (as JSON under `--json`), else the error.
fn config_failure(command: &Command, error: String) -> Result<(Vec<String>, u8), String> {
    let (Command::Plan(args) | Command::Apply(args) | Command::Load(args)) = command else {
        return Err(error);
    };
    match args.json {
        true => Ok((vec![json_error("config", &error, false)], 1)),
        false => {
            let (lines, ok) = render_plan(&ProjectPlan {
                problems: problems(&error),
                ..ProjectPlan::default()
            });
            Ok((lines, exit_code(ok, false)))
        }
    }
}

async fn run_command(
    project: &ProjectConfig,
    command: Command,
    host: Option<Arc<dyn PythonHost>>,
    (no_color, streams, log_json): (bool, bool, bool),
) -> Result<(Vec<String>, u8), CommandError> {
    if let Command::Debug { no_connection } = command {
        let (lines, ok) = debug_project(project, !no_connection).await;
        return match ok {
            true => Ok((lines, 0)),
            false => Err(lines.join("\n").into()),
        };
    }
    if let Command::LoggedState { action } = command {
        let destinations = connect_targets(project)
            .await
            .map_err(|error| error.to_string())?;
        return run_state(project, &destinations, action)
            .await
            .map(|lines| (lines, 0))
            .map_err(Into::into);
    }
    let (args, applies, loads) = match command {
        Command::Plan(args) => (args, false, false),
        Command::Apply(args) => (args, true, false),
        Command::Load(args) => (args, true, true),
        _ => {
            return Err(
                "this command runs on exporter configurations; this file is a loader project"
                    .to_owned()
                    .into(),
            );
        }
    };
    let (json, yes, follow) = (
        args.json,
        args.yes,
        args.follow.then_some(args.max_duration),
    );
    let started = (chrono::Utc::now(), std::time::Instant::now());
    if !loads && (args.events.is_some() || args.events_file.is_some()) {
        return Err("--events and --events-file apply to load only"
            .to_owned()
            .into());
    }
    let events = match (args.events, &args.events_file) {
        (Some(EventsFormat::Jsonl), _) => Some(EventsTarget::Stderr),
        (None, Some(path)) => Some(EventsTarget::File(std::fs::File::create(path).map_err(
            |error| format!("cannot write --events-file {}: {error}", path.display()),
        )?)),
        (None, None) => None,
    };
    let draws = match args.progress {
        Progress::Never => false,
        Progress::Always => streams,
        Progress::Auto => streams && !json && !log_json && std::io::stderr().is_terminal(),
    };
    let options = options(args)?;
    let receiver = listen(&uuid::Uuid::new_v4().to_string());
    let (destinations, mut plan) = planning(
        async {
            let destinations = connect_targets(project).await?;
            let plan = plan_project(project, &destinations, &options).await?;
            Ok::<_, CommandError>((destinations, plan))
        },
        project.sources.len(),
        (draws, streams && !json && !log_json, no_color),
    )
    .await?;
    plan.phases = take_timings();
    if json && !applies {
        let (text, ok, retryable) = json_report(&plan, None);
        return Ok((vec![text], exit_code(ok, retryable)));
    }
    let (mut lines, planned) = match json {
        true => (Vec::new(), true),
        false => render_plan(&plan),
    };
    let plan_retryable = plan.only_retryable_problems();
    if !applies {
        return Ok((lines, exit_code(planned, plan_retryable)));
    }
    if follow.is_some() && !render_plan(&plan).1 {
        return Ok(match json {
            true => {
                let (text, _, retryable) = json_report(&plan, None);
                (vec![text], exit_code(false, retryable))
            }
            false => {
                let mut lines = start_lines(lines);
                lines.extend([String::new(), follow_refused(project, &plan)]);
                (lines, exit_code(false, plan_retryable))
            }
        });
    }
    if let Some(problem) = follow.and_then(|_| follow_problem(&plan)) {
        return Err(problem.into());
    }
    let flag = match (options.reload, options.resnapshot) {
        (true, true) => "--reload and --resnapshot",
        (true, false) => "--reload",
        (false, _) => "--resnapshot",
    };
    let rebuilt: Vec<&str> = plan
        .tables
        .iter()
        .filter(|table| {
            loads
                && !yes
                && table.schema.blocked.is_none()
                && (options.reload || (options.resnapshot && table.spec.cdc.is_some()))
        })
        .map(|table| table.spec.destination.table.as_str())
        .collect();
    if !rebuilt.is_empty() && json {
        return Err(format!(
            "{flag} rebuilds {}, replacing what they hold, and --json cannot ask to confirm it; add --yes",
            rebuilt.join(", ")
        )
        .into());
    }
    if !rebuilt.is_empty() {
        match confirm_reload(&lines, flag, &rebuilt, no_color)? {
            true => lines.clear(),
            false => return Ok((vec![RELOAD_DECLINED.to_owned()], 1)),
        }
    }
    let applied = apply_project(&plan, &destinations).await?;
    let run = LoadRun {
        project,
        destinations: &destinations,
        host,
        options: &options,
    };
    if loads {
        let streamed = StreamedLoad {
            receiver,
            run: &run,
            plan: &plan,
            applied: &applied,
            stop: follow.map(follow_stop),
            output: LoadOutput {
                name_width: name_width(&plan, &applied),
                rows_width: rows_width(&plan),
                print: streams && !json,
                no_color,
                events,
                live: draws.then(|| {
                    let tables: Vec<String> = plan
                        .tables
                        .iter()
                        .filter(|table| table.schema.blocked.is_none())
                        .map(TablePlan::outcome_name)
                        .collect();
                    let state = LiveState::new(tables, options.fail_fast);
                    match follow {
                        Some(_) => state.following(),
                        None => state,
                    }
                }),
            },
            started,
            planned: (planned, plan_retryable),
        };
        lines = start_lines(lines);
        if streamed.output.print {
            print_lines(std::mem::take(&mut lines), no_color);
        }
        let ended = Box::pin(streamed_load(streamed)).await;
        if json {
            let run = RunReport {
                command: "load",
                applied: &applied,
                outcomes: &ended.outcomes,
                started: started.0,
                elapsed: started.1.elapsed(),
                peak_memory_bytes: ended.peak_memory_bytes,
            };
            let (text, ok, retryable) = json_report(&plan, Some(&run));
            return Ok((vec![text], exit_code(ok, retryable)));
        }
        lines.extend(ended.lines);
        return Ok((lines, ended.exit_code));
    }
    if json {
        let run = RunReport {
            command: "apply",
            applied: &applied,
            outcomes: &[],
            started: started.0,
            elapsed: started.1.elapsed(),
            peak_memory_bytes: run_peak_bytes(&[]),
        };
        let (text, ok, retryable) = json_report(&plan, Some(&run));
        return Ok((vec![text], exit_code(ok, retryable)));
    }
    let (tallied, completed) = render_tally(&applied, &[], started.1.elapsed(), None);
    lines.extend(tallied);
    Ok((lines, exit_code(planned && completed, plan_retryable)))
}

/// What a load streams its lines and events from: the events since the command started listening, its run and plan, what `apply` changed before it, what stops a `load --follow`, where its lines go, when it started, and whether the plan was ready and failed only in ways a rerun may get past.
struct StreamedLoad<'a> {
    receiver: UnboundedReceiver<LoadEvent>,
    run: &'a LoadRun<'a>,
    plan: &'a ProjectPlan,
    applied: &'a [String],
    stop: Option<CancellationToken>,
    output: LoadOutput,
    started: (chrono::DateTime<chrono::Utc>, std::time::Instant),
    planned: (bool, bool),
}

/// How a streamed load ended: each table's outcome, the lines not printed yet, the exit code, and the run's peak memory in bytes.
struct StreamedEnd {
    outcomes: Vec<TableOutcome>,
    lines: Vec<String>,
    exit_code: u8,
    peak_memory_bytes: Option<u64>,
}

/// Load `load.plan`, rendering its events as they come: each table's outcome, the lines not printed yet (the `created`/`altered` lines `apply` reported, each table's line as it finished, and the summary, which a load of no table leaves to the plan's closing line), the exit code, the same as a load without events, and the run's peak memory (the most of the process's before the tables loaded, after, and each table's under `--memory-per-table`, whose resets the process's own figure may miss).
async fn streamed_load(load: StreamedLoad<'_>) -> StreamedEnd {
    let width = load.output.name_width;
    let selected = load.plan.tables.len();
    let to_load = load
        .plan
        .tables
        .iter()
        .filter(|table| table.schema.blocked.is_none())
        .count();
    let mut first: Vec<String> = Vec::new();
    if to_load > 0 || !load.applied.is_empty() {
        first.push(String::new());
        first.extend(
            load.applied
                .iter()
                .map(|line| change_tally_line(line, width)),
        );
    }
    let print = load.output.print;
    let no_color = load.output.no_color;
    let mut kept: Vec<String> = Vec::new();
    match print {
        true => print_lines(first, no_color),
        false => kept.extend(first),
    }
    let writer = tokio::spawn(write_events(load.output, load.receiver));
    emit(None, EventKind::RunStarted { selected, to_load });
    let before = run_peak_bytes(&[]);
    let outcomes = load_tables(load.run, load.plan, load.stop.as_ref()).await;
    let measured: Vec<Option<u64>> = std::iter::once(before)
        .chain(outcomes.iter().map(|outcome| outcome.peak_memory_bytes))
        .collect();
    let peak_memory_bytes = run_peak_bytes(&measured);
    let (mut loaded, mut failed, mut not_started, mut rows) = (0, 0, 0, 0);
    for outcome in &outcomes {
        match (&outcome.loaded, outcome.skipped) {
            (Ok(table), false) => (loaded, rows) = (loaded + 1, rows + table.rows),
            (Ok(table), true) => rows += table.rows,
            (Err(_), false) => failed += 1,
            (Err(_), true) => not_started += 1,
        }
    }
    let completed = failed + not_started == 0;
    let retryable = outcomes.iter().all(TableOutcome::passes_on_rerun);
    let code = exit_code(load.planned.0 && completed, load.planned.1 && retryable);
    let elapsed_ms = u64::try_from(load.started.1.elapsed().as_millis()).unwrap_or(u64::MAX);
    emit(
        None,
        EventKind::RunFinished {
            loaded,
            failed,
            not_started,
            rows,
            elapsed_ms,
            exit_code: code,
            peak_memory_bytes,
        },
    );
    close();
    let (lines, tally) = writer.await.unwrap_or_default();
    kept.extend(lines);
    if to_load > 0 {
        kept.push(String::new());
        kept.extend(summary_lines(&tally, elapsed_ms, code));
    }
    StreamedEnd {
        outcomes,
        lines: kept,
        exit_code: code,
        peak_memory_bytes,
    }
}

/// The width of the tally's name column: the widest name of a table the plan loads, or of an object `applied` changed, and two spaces.
fn name_width(plan: &ProjectPlan, applied: &[String]) -> usize {
    let tables = plan
        .tables
        .iter()
        .filter(|table| table.schema.blocked.is_none())
        .map(|table| table.outcome_name().len());
    let objects = applied
        .iter()
        .map(|line| line.split_whitespace().nth(1).map_or(0, str::len));
    tables.chain(objects).max().unwrap_or(0) + 2
}

/// The width of the tally's rows column: the widest row estimate, with separators, of a table the plan loads, and at least 5; a count wider still pushes only its own line.
fn rows_width(plan: &ProjectPlan) -> usize {
    plan.tables
        .iter()
        .filter(|table| table.schema.blocked.is_none())
        .map(|table| thousands(table.spec.source_table.estimated_rows.max(0) as u64).len())
        .fold(5, usize::max)
}

/// Why `load --follow` did not start on a plan with errors: following past a source or table that did not plan would move the replication slot beyond its changes for good. Names how to leave each failing source out to follow the rest: `--exclude` for a source it does not follow, and the source's own `exclude` for the tables of a `postgres_cdc` source, which share its one slot.
fn follow_refused(project: &ProjectConfig, plan: &ProjectPlan) -> String {
    let (captured, others): (Vec<String>, Vec<String>) =
        plan.failing_sources().into_iter().partition(|name| {
            project
                .sources
                .get(name)
                .is_some_and(|source| source.kind == SourceKind::PostgresCdc)
        });
    let mut ways: Vec<String> = Vec::new();
    if !others.is_empty() {
        ways.push(format!("--exclude {}", others.join(" ")));
    }
    ways.extend(captured.iter().map(|name| {
        format!("the failing tables of {name} in exclude under [sources.{name}], as its tables share one slot")
    }));
    let leave_out = match ways.is_empty() {
        true => String::new(),
        false => format!(
            ", or leave them out to follow the rest: {}",
            ways.join("; ")
        ),
    };
    format!(
        "✗ load --follow did not start: it follows only when every selected source and table plans, since the replication slot would move past the changes of one left out; fix the errors above{leave_out}"
    )
}

/// Why `load --follow` cannot follow `plan`: it follows exactly one `postgres_cdc` source, and nothing else, since it never finishes to load other tables after; when it selects none, the plan's problems say why.
fn follow_problem(plan: &ProjectPlan) -> Option<String> {
    let others: Vec<&str> = plan
        .tables
        .iter()
        .filter(|table| table.spec.cdc.is_none())
        .map(|table| table.spec.destination.table.as_str())
        .collect();
    if !others.is_empty() {
        return Some(format!(
            "load --follow follows one postgres_cdc source and nothing else; {} {} not captured, so load them without --follow, or leave them out: --exclude {}",
            others.join(", "),
            match others.len() {
                1 => "is",
                _ => "are",
            },
            others.join(" ")
        ));
    }
    let sources: std::collections::BTreeSet<&str> = plan
        .tables
        .iter()
        .map(|table| table.spec.source_name.as_str())
        .collect();
    match sources.len() {
        0 => Some(
            std::iter::once("load --follow needs a postgres_cdc source, and selects none")
                .chain(plan.problems.iter().map(String::as_str))
                .collect::<Vec<&str>>()
                .join("; "),
        ),
        1 => None,
        _ => Some(format!(
            "load --follow follows one postgres_cdc source per process; select one of {}",
            sources.into_iter().collect::<Vec<&str>>().join(", ")
        )),
    }
}

/// What stops a follow: `max_duration` passing, or Ctrl-C/SIGTERM; a second signal exits at once with 130, confirming nothing more (a restart skips what was written).
fn follow_stop(max_duration: Option<std::time::Duration>) -> CancellationToken {
    let stop = CancellationToken::new();
    if let Some(limit) = max_duration {
        let timer = stop.clone();
        tokio::spawn(async move {
            tokio::time::sleep(limit).await;
            tracing::info!(
                "--max-duration passed; stopping once the batch or copy under way is written"
            );
            timer.cancel();
        });
    }
    let signalled = stop.clone();
    tokio::spawn(async move {
        wait_for_signal().await;
        tracing::info!(
            "stopping once the batch or copy under way is written; press Ctrl-C again to stop now"
        );
        signalled.cancel();
        wait_for_signal().await;
        std::process::exit(FORCED_STOP_EXIT);
    });
    stop
}

/// `sqlload logged-state`: plan the selected tables (which reads their run logs), then show, verify, reconcile or reset them.
async fn run_state(
    project: &ProjectConfig,
    destinations: &BTreeMap<String, Destination>,
    action: StateAction,
) -> Result<Vec<String>, String> {
    let (kind, args, to) = match action {
        StateAction::Show(args) => (StateKind::Show, args, None),
        StateAction::Verify(args) => (StateKind::Verify, args, None),
        StateAction::Reconcile(args) => (StateKind::Reconcile, args, None),
        StateAction::Reset(reset) => (StateKind::Reset, reset.tables, reset.to),
    };
    if kind == StateKind::Reset && args.select.is_empty() {
        return Err(
            "logged-state reset changes where tables read from next; name the sources or tables to reset"
                .to_owned(),
        );
    }
    let options = PlanOptions {
        select: args.select,
        ..PlanOptions::default()
    };
    let plan = plan_project(project, destinations, &options)
        .await
        .map_err(|error| error.to_string())?;
    let request = StateRequest {
        kind,
        append: args.yes,
        to,
    };
    let (lines, ok) = state_command(&plan, destinations, &request)
        .await
        .map_err(|error| error.to_string())?;
    match ok {
        true => Ok(lines),
        false => Err(lines.join("\n")),
    }
}

/// `sqlload contract diff` and `generate`: the report, and whether every selected table agrees; `generate --write` first writes the adoptions into the project `file` (its path and text).
async fn run_contract(
    project: &ProjectConfig,
    action: ContractAction,
    file: (&Path, &str),
    variables: &BTreeMap<String, String>,
) -> Result<(Vec<String>, bool), String> {
    let destinations = connect_targets(project)
        .await
        .map_err(|error| error.to_string())?;
    let (args, generate, write) = match action {
        ContractAction::Diff(args) => (args, None, false),
        ContractAction::Generate(chosen) => (chosen.tables, Some(chosen.overwrite), chosen.write),
    };
    let options = PlanOptions {
        select: [args.positional_select, args.select].concat(),
        exclude: args.exclude,
        ..PlanOptions::default()
    };
    let request = ContractRequest {
        from: args.from,
        generate,
        all_files: args.all_files,
        source: args.source,
    };
    let report = compare_contracts(project, &destinations, &options, &request)
        .await
        .map_err(|error| error.to_string())?;
    let report = match write {
        true => write_adoptions(report, file, variables)?,
        false => report,
    };
    Ok(render_contract(&report, args.json))
}

/// `report` after writing its adoptions into the project file, which is left as it was when the edited project would no longer parse.
fn write_adoptions(
    report: ContractReport,
    (config, text): (&Path, &str),
    variables: &BTreeMap<String, String>,
) -> Result<ContractReport, String> {
    let (updated, mut report) = write_contracts(text, report)?;
    let Some(updated) = updated else {
        return Ok(report);
    };
    parse_project(&updated, &|name| variable(variables, name)).map_err(|error| {
        format!(
            "contract generate --write left {} unchanged: the edited project would not parse: {error}",
            config.display()
        )
    })?;
    replace_file(config, (text, &updated))?;
    report.written_paths.push(config.file_name().map_or_else(
        || config.display().to_string(),
        |name| name.to_string_lossy().into_owned(),
    ));
    Ok(report)
}