sqlload 0.51.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
//! One table's buffered changes as the parts its load stages.

use std::sync::Arc;

use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray, TimestampMicrosecondArray};
use arrow_schema::{Field, Schema};

use crate::adapters::contract::models::{ChangeApply, Truncation};
use crate::cdc::_helpers::fold::{Folder, fold_changes, key_of, key_positions};
use crate::cdc::_helpers::spill::{SpillFile, SpillReader};
use crate::cdc::_helpers::text_values::{arrow_type, micros_text, text_array};
use crate::cdc::constants::{
    DELETE_OP, INSERT_OP, NOT_STREAMED, SPILL_CHUNK_CHANGES, SPILL_PARTITIONS, TRUNCATE_OP,
    UPDATE_OP,
};
use crate::cdc::models::{Change, ChangeOp, Relation, TableChanges, TupleValue};
use crate::column_types::main::arrow_field::arrow_field;
use crate::postgres_source::models::{ReadColumn, SourceTable};
use crate::schema_plan::constants::{
    CDC_COMMITTED_AT_COLUMN, CDC_LSN_COLUMN, CDC_OP_COLUMN, CDC_PREFIX, CDC_SEQ_COLUMN,
    CDC_UNCHANGED_COLUMN,
};

/// The rows `changes` of `relation` write, with the columns `read` (data columns, then the change columns) in that order: a truncate is a row without values. A read column the stream never showed in this batch is left out of every change.
pub(crate) fn rows_batch(
    changes: &[Change],
    relation: &Relation,
    read: &[ReadColumn],
) -> Result<RecordBatch, String> {
    let positions = column_positions(relation, read);
    let data_positions: Vec<(&str, usize)> = read
        .iter()
        .zip(&positions)
        .filter_map(|(column, position)| Some((column.name.as_str(), (*position)?)))
        .collect();
    let mut fields: Vec<Field> = Vec::with_capacity(read.len());
    let mut arrays: Vec<ArrayRef> = Vec::with_capacity(read.len());
    for (column, position) in read.iter().zip(&positions) {
        let array = match position {
            Some(position) => data_array(changes, *position, column)?,
            None => metadata_array(changes, column, &data_positions)?,
        };
        let field = Field::new(&column.name, array.data_type().clone(), true);
        fields.push(match arrow_field(&column.name, &column.output) {
            Some(planned) if planned.data_type() == array.data_type() => {
                field.with_metadata(planned.metadata().clone())
            }
            _ => field,
        });
        arrays.push(array);
    }
    RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).map_err(|error| error.to_string())
}

/// The changes one table's batch stages, part by part: a changelog keeps every change, in chunks once spilled; `merge` keeps each key's last change after the newest truncate, folded per key partition once spilled, so no key is in two parts.
#[derive(Debug)]
pub(crate) enum ChangeParts {
    /// Changes in memory, already applied, staged as one part.
    Ready(Option<Vec<Change>>),
    /// A spilled changelog: the file, then the changes still in memory.
    Log {
        reader: SpillReader,
        memory: std::vec::IntoIter<Change>,
    },
    /// A spilled `merge` table: one file per key partition, each folded as it is read, so a part holds one change per key.
    Partitions {
        files: std::collections::btree_map::IntoIter<u64, SpillFile>,
        positions: Vec<usize>,
        /// How many partitions the keys are hashed into.
        partitions: u64,
    },
}

impl ChangeParts {
    /// The next part's changes, or `None` when every part is staged.
    pub(crate) fn next_changes(&mut self) -> Result<Option<Vec<Change>>, String> {
        match self {
            Self::Ready(changes) => Ok(changes.take()),
            Self::Log { reader, memory } => {
                let mut part: Vec<Change> = Vec::new();
                while part.len() < SPILL_CHUNK_CHANGES {
                    match reader.next_change()? {
                        Some(change) => part.push(change),
                        None => break,
                    }
                }
                part.extend(memory.take(SPILL_CHUNK_CHANGES - part.len()));
                Ok((!part.is_empty()).then_some(part))
            }
            Self::Partitions {
                files,
                positions,
                partitions,
            } => {
                let Some((partition, mut file)) = files.next() else {
                    return Ok(None);
                };
                let mut reader = file.read()?;
                let mut folder = Folder::default();
                while let Some(change) = reader.next_change()? {
                    folder.push(change, positions)?;
                }
                let mut folded = folder.finish();
                folded.retain(|change| {
                    key_partition(&key_of(&change.values, positions), *partitions) == partition
                });
                Ok(Some(folded))
            }
        }
    }
}

/// `table`'s batch as parts, with the changes `spilled` to disk before those in memory, and for `merge` the newest truncate, which applies before them; a spilled `merge` table is split into enough key partitions that each holds about a quarter of `spill_bytes`, at most [`SPILL_PARTITIONS`].
pub(crate) fn change_parts(
    table: &TableChanges,
    (spilled, spill_bytes): (Option<SpillFile>, usize),
    (apply, unique_key): (ChangeApply, &[String]),
) -> Result<(ChangeParts, Option<Truncation>), String> {
    let Some(mut spilled) = spilled else {
        let (changes, truncated) = applied_changes(table, apply, unique_key)?;
        return Ok((ChangeParts::Ready(Some(changes)), truncated));
    };
    let memory = table.changes.clone().into_iter();
    if apply == ChangeApply::Changelog {
        let reader = spilled.read()?;
        return Ok((ChangeParts::Log { reader, memory }, None));
    }
    let mut last: Option<Change> = None;
    let mut reader = spilled.read()?;
    while let Some(change) = reader.next_change()? {
        if change.op == ChangeOp::Truncate {
            last = Some(change);
        }
    }
    if let Some(change) = table
        .changes
        .iter()
        .rev()
        .find(|change| change.op == ChangeOp::Truncate)
    {
        last = Some(change.clone());
    }
    let after = last.as_ref().map(|change| (change.lsn, change.seq));
    let positions = key_positions(&table.relation, unique_key)?;
    let spilled_bytes = u64::try_from(spilled.bytes).unwrap_or(u64::MAX);
    let limit = u64::try_from(spill_bytes.max(1)).unwrap_or(u64::MAX);
    let partitions = spilled_bytes
        .saturating_mul(4)
        .div_ceil(limit)
        .clamp(1, SPILL_PARTITIONS);
    let mut files = PartitionFiles::default();
    let mut reader = spilled.read()?;
    let mut memory = memory;
    loop {
        let change = match reader.next_change()? {
            Some(change) => change,
            None => match memory.next() {
                Some(change) => change,
                None => break,
            },
        };
        if after.is_some_and(|after| (change.lsn, change.seq) <= after) {
            continue;
        }
        let key = key_of(&change.values, &positions);
        if let Some(old) = change
            .old_key
            .as_ref()
            .filter(|old| key_of(old, &positions) != key)
        {
            let deleted = Change {
                op: ChangeOp::Delete,
                values: old.clone(),
                old_key: None,
                ..change.clone()
            };
            files.push(
                key_partition(&key_of(old, &positions), partitions),
                &deleted,
            )?;
        }
        files.push(key_partition(&key, partitions), &change)?;
    }
    let truncated = last.map(|change| Truncation {
        lsn: change.lsn,
        committed_at: micros_text(change.committed_at),
    });
    let parts = ChangeParts::Partitions {
        files: files.0.into_iter(),
        positions,
        partitions,
    };
    Ok((parts, truncated))
}

/// The partition, of `partitions`, a key's changes are folded in.
fn key_partition(key: &[TupleValue], partitions: u64) -> u64 {
    let mut hasher = std::hash::DefaultHasher::new();
    std::hash::Hash::hash(key, &mut hasher);
    std::hash::Hasher::finish(&hasher) % partitions
}

/// A spilled `merge` table's changes, filed by key partition.
#[derive(Debug, Default)]
struct PartitionFiles(std::collections::BTreeMap<u64, SpillFile>);

impl PartitionFiles {
    /// Append `change` to `partition`'s file, made on first use.
    fn push(&mut self, partition: u64, change: &Change) -> Result<(), String> {
        let file = match self.0.entry(partition) {
            std::collections::btree_map::Entry::Occupied(file) => file.into_mut(),
            std::collections::btree_map::Entry::Vacant(slot) => slot.insert(SpillFile::new()?),
        };
        file.push_change(change)
    }
}

/// The changes a batch in memory writes and, for `merge`, its newest truncate.
fn applied_changes(
    table: &TableChanges,
    apply: ChangeApply,
    unique_key: &[String],
) -> Result<(Vec<Change>, Option<Truncation>), String> {
    if apply == ChangeApply::Changelog {
        return Ok((table.changes.clone(), None));
    }
    let last_truncate = table
        .changes
        .iter()
        .rposition(|change| change.op == ChangeOp::Truncate);
    let truncated = last_truncate
        .and_then(|index| table.changes.get(index))
        .map(|change| Truncation {
            lsn: change.lsn,
            committed_at: micros_text(change.committed_at),
        });
    let after = last_truncate.map_or(0, |index| index + 1);
    let positions = key_positions(&table.relation, unique_key)?;
    let kept = table.changes.get(after..).unwrap_or_default();
    Ok((fold_changes(kept, &positions)?, truncated))
}

/// `relation` with each column the load renames (under `naming = "dlt"`) under the name it loads as, so the plan's read columns and key find it; a column the plan lacks keeps the source's name. A column added since the plan whose name another column loads as is an error naming both, so neither overwrites the other.
pub(crate) fn loaded_relation(
    relation: &Relation,
    planned: &SourceTable,
) -> Result<Relation, String> {
    let mut loaded = relation.clone();
    let mut seen: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
    for column in &mut loaded.columns {
        let name = planned.loaded_as(&column.name).to_owned();
        if let Some(other) = seen.insert(name.clone(), column.name.clone()) {
            return Err(format!(
                "{}.{}: columns {other} and {} both load as {name} under naming = \"dlt\"; one was added during the load, so run the load again to plan it, and rename or exclude one of them",
                relation.schema, relation.table, column.name
            ));
        }
        column.name = name;
    }
    Ok(loaded)
}

/// The columns of `relation` on the stream that `planned`, the table as its load was planned, lacks: added (or renamed) since, so the load has nowhere to write them.
pub(crate) fn unplanned_columns(relation: &Relation, planned: &SourceTable) -> Vec<String> {
    let known: std::collections::BTreeSet<&str> = planned
        .columns
        .iter()
        .map(|column| column.name.as_str())
        .collect();
    relation
        .columns
        .iter()
        .map(|column| column.name.clone())
        .filter(|name| !known.contains(name.as_str()))
        .collect()
}

/// Each read column's position on the stream, [`NOT_STREAMED`] when the batch never showed it; `None` for the change columns.
fn column_positions(relation: &Relation, read: &[ReadColumn]) -> Vec<Option<usize>> {
    let streamed: std::collections::BTreeMap<&str, usize> = relation
        .columns
        .iter()
        .enumerate()
        .map(|(position, column)| (column.name.as_str(), position))
        .collect();
    read.iter()
        .map(|column| {
            (!column.name.starts_with(CDC_PREFIX)).then(|| {
                streamed
                    .get(column.name.as_str())
                    .copied()
                    .unwrap_or(NOT_STREAMED)
            })
        })
        .collect()
}

/// Refuse `table`'s batch when an insert or update holds a value of a `gone` column (one the source no longer has) but leaves a `read` column out: the column was renamed (or replaced) while its changes were unloaded, so its values have nowhere to go. Every change is checked, those `spilled` to disk included, before `merge` folds them, since folding fills a left-out value from the key's earlier change and would hide the rename.
pub(crate) fn refuse_renamed(
    table: &TableChanges,
    spilled: Option<&mut SpillFile>,
    (read, gone): (&[ReadColumn], &[String]),
) -> Result<(), String> {
    let relation = &table.relation;
    let gone_positions: Vec<usize> = relation
        .columns
        .iter()
        .enumerate()
        .filter(|(_, column)| gone.contains(&column.name))
        .map(|(position, _)| position)
        .collect();
    if gone_positions.is_empty() {
        return Ok(());
    }
    let read_positions: Vec<usize> = column_positions(relation, read)
        .into_iter()
        .flatten()
        .collect();
    let misplaced = |change: &Change| {
        matches!(change.op, ChangeOp::Insert | ChangeOp::Update)
            && !all_left_out(change, &gone_positions)
            && any_left_out(change, &read_positions)
    };
    let mut renamed = table.changes.iter().any(misplaced);
    if let Some(file) = spilled {
        let mut reader = file.read()?;
        while let Some(change) = reader.next_change()? {
            renamed = renamed || misplaced(&change);
        }
    }
    match renamed {
        true => Err(format!(
            "{}.{} renamed or replaced column {} while changes to it were not yet loaded, so their values cannot be placed; run `sqlload load --resnapshot` to copy every table again",
            relation.schema,
            relation.table,
            gone.join(", ")
        )),
        false => Ok(()),
    }
}

/// Whether `change` leaves the column at `position` out: its shape lacked it.
fn left_out(change: &Change, position: usize) -> bool {
    change
        .values
        .get(position)
        .is_none_or(|value| *value == TupleValue::Absent)
}

/// Whether `change` leaves out every column at `positions`.
fn all_left_out(change: &Change, positions: &[usize]) -> bool {
    positions.iter().all(|position| left_out(change, *position))
}

/// Whether `change` leaves out any column at `positions`.
fn any_left_out(change: &Change, positions: &[usize]) -> bool {
    positions.iter().any(|position| left_out(change, *position))
}

/// The values of the stream's column `position` as `column`'s type; an unchanged TOAST value is NULL here and flagged in `_sqlload_unchanged`.
fn data_array(
    changes: &[Change],
    position: usize,
    column: &ReadColumn,
) -> Result<ArrayRef, String> {
    let mut values: Vec<Option<&str>> = Vec::with_capacity(changes.len());
    for change in changes {
        values.push(match change.values.get(position) {
            Some(TupleValue::Text(text)) => Some(text.as_str()),
            _ => None,
        });
    }
    text_array(&values, column).map_err(|problem| format!("{}: {problem}", column.name))
}

/// One change column: the commit LSN, position, operation and time; `_sqlload_unchanged` flags; NULL for the rest (`_sqlload_deleted_at`, which the write sets).
fn metadata_array(
    changes: &[Change],
    column: &ReadColumn,
    data_positions: &[(&str, usize)],
) -> Result<ArrayRef, String> {
    Ok(match column.name.as_str() {
        CDC_LSN_COLUMN => Arc::new(Int64Array::from_iter_values(
            changes.iter().map(|change| change.lsn),
        )),
        CDC_SEQ_COLUMN => Arc::new(Int64Array::from_iter_values(
            changes.iter().map(|change| change.seq),
        )),
        CDC_OP_COLUMN => Arc::new(StringArray::from_iter_values(
            changes.iter().map(|change| op_name(change.op)),
        )),
        CDC_COMMITTED_AT_COLUMN => Arc::new(
            TimestampMicrosecondArray::from_iter_values(
                changes.iter().map(|change| change.committed_at),
            )
            .with_timezone("UTC"),
        ),
        CDC_UNCHANGED_COLUMN => Arc::new(StringArray::from_iter(
            changes
                .iter()
                .map(|change| unchanged_flags(change, data_positions)),
        )),
        _ => arrow_array::new_null_array(&arrow_type(&column.output)?, changes.len()),
    })
}

/// `_sqlload_op` for `op`.
fn op_name(op: ChangeOp) -> &'static str {
    match op {
        ChangeOp::Insert => INSERT_OP,
        ChangeOp::Update => UPDATE_OP,
        ChangeOp::Delete => DELETE_OP,
        ChangeOp::Truncate => TRUNCATE_OP,
    }
}

/// The data columns whose value the change left out, as `,a,b,`: an unchanged TOAST value or, for an insert or update, a column its shape lacked (a delete or truncate writes no data columns); `None` when it left none out.
fn unchanged_flags(change: &Change, data_positions: &[(&str, usize)]) -> Option<String> {
    let writes = matches!(change.op, ChangeOp::Insert | ChangeOp::Update);
    let mut names = String::new();
    for (name, position) in data_positions {
        let value = change.values.get(*position).unwrap_or(&TupleValue::Absent);
        if *value == TupleValue::Unchanged || (writes && *value == TupleValue::Absent) {
            names.push(',');
            names.push_str(name);
        }
    }
    (!names.is_empty()).then(|| format!("{names},"))
}