patchworks 0.3.0

Git-style visual diffs for SQLite databases. Inspect, compare, snapshot, and generate SQL migrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Streaming row-level diff support for SQLite tables.

use std::cmp::Ordering;
use std::collections::BTreeSet;
use std::path::Path;

use rusqlite::Rows;

use crate::db::inspector::{
    compare_sql_values, compare_value_slices, open_read_only, quote_identifier, read_value_row,
};
use crate::db::types::{
    DatabaseSummary, DiffStats, RowModification, SqlValue, TableDataDiff, TableInfo,
};
use crate::error::{PatchworksError, Result};

const LARGE_TABLE_THRESHOLD: u64 = 100_000;
const ROWID_ALIAS: &str = "__patchworks_rowid";

/// Progress update emitted while diffing shared tables.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataDiffProgress {
    /// Shared table currently being diffed.
    pub table_name: String,
    /// Zero-based index of the current shared table.
    pub table_index: usize,
    /// Total number of shared tables that will be diffed.
    pub total_tables: usize,
}

#[derive(Clone, Debug, PartialEq)]
struct StreamRow {
    pk_values: Vec<SqlValue>,
    row_values: Vec<SqlValue>,
}

#[derive(Clone, Debug, PartialEq)]
enum IdentityExpr {
    RowId,
    Column(String),
}

impl IdentityExpr {
    fn select_sql(&self, alias: Option<&str>) -> String {
        let expression = match self {
            Self::RowId => "rowid".to_owned(),
            Self::Column(column) => quote_identifier(column),
        };

        match alias {
            Some(alias) => format!("{expression} AS {}", quote_identifier(alias)),
            None => expression,
        }
    }

    fn order_sql(&self) -> String {
        match self {
            Self::RowId => "rowid".to_owned(),
            Self::Column(column) => quote_identifier(column),
        }
    }
}

/// Computes row-level diffs for all shared tables between two databases.
pub fn diff_all_tables(
    left_path: &Path,
    right_path: &Path,
    left: &DatabaseSummary,
    right: &DatabaseSummary,
) -> Result<Vec<TableDataDiff>> {
    diff_all_tables_with_progress(left_path, right_path, left, right, |_| {})
}

/// Computes row-level diffs for all shared tables and reports table-level progress.
pub fn diff_all_tables_with_progress<F>(
    left_path: &Path,
    right_path: &Path,
    left: &DatabaseSummary,
    right: &DatabaseSummary,
    mut on_progress: F,
) -> Result<Vec<TableDataDiff>>
where
    F: FnMut(DataDiffProgress),
{
    let shared_tables = left
        .tables
        .iter()
        .filter_map(|left_table| {
            right
                .tables
                .iter()
                .find(|table| table.name == left_table.name)
                .map(|right_table| (left_table, right_table))
        })
        .collect::<Vec<_>>();
    let total_tables = shared_tables.len();
    let mut diffs = Vec::with_capacity(total_tables);

    for (table_index, (left_table, right_table)) in shared_tables.into_iter().enumerate() {
        on_progress(DataDiffProgress {
            table_name: left_table.name.clone(),
            table_index,
            total_tables,
        });
        diffs.push(diff_table(left_path, right_path, left_table, right_table)?);
    }

    Ok(diffs)
}

/// Computes a streaming row diff for a single table.
pub fn diff_table(
    left_path: &Path,
    right_path: &Path,
    left_table: &TableInfo,
    right_table: &TableInfo,
) -> Result<TableDataDiff> {
    let common_columns = shared_column_names(left_table, right_table);
    let same_primary_key = !left_table.primary_key.is_empty()
        && !right_table.primary_key.is_empty()
        && left_table.primary_key == right_table.primary_key
        && left_table
            .primary_key
            .iter()
            .all(|column| common_columns.iter().any(|candidate| candidate == column));

    let mut warnings = Vec::new();
    if !same_primary_key {
        warnings.push(
            "No shared primary key was found. Falling back to table-local row identity (rowid when available, otherwise each table's declared primary key), which may be unreliable after deletes, reinserts, or primary-key changes."
                .to_owned(),
        );
    }
    if left_table.row_count > LARGE_TABLE_THRESHOLD || right_table.row_count > LARGE_TABLE_THRESHOLD
    {
        warnings.push(
            "Large table detected. Diff is streamed, but very large tables may still take noticeable time."
                .to_owned(),
        );
    }

    let comparison_columns = if common_columns.is_empty() && same_primary_key {
        left_table.primary_key.clone()
    } else {
        common_columns.clone()
    };
    let (left_identity, right_identity, identity_embedded_in_values) = if same_primary_key {
        let identity = left_table
            .primary_key
            .iter()
            .cloned()
            .map(IdentityExpr::Column)
            .collect::<Vec<_>>();
        (identity.clone(), identity, true)
    } else if table_supports_rowid(left_table) && table_supports_rowid(right_table) {
        (vec![IdentityExpr::RowId], vec![IdentityExpr::RowId], false)
    } else {
        (
            fallback_identity_exprs(left_table)?,
            fallback_identity_exprs(right_table)?,
            false,
        )
    };

    let left_connection = open_read_only(left_path)?;
    let right_connection = open_read_only(right_path)?;

    let left_sql = build_stream_sql(
        left_table,
        &comparison_columns,
        &left_identity,
        identity_embedded_in_values,
    );
    let right_sql = build_stream_sql(
        right_table,
        &comparison_columns,
        &right_identity,
        identity_embedded_in_values,
    );

    let mut left_statement = left_connection.prepare(&left_sql)?;
    let mut right_statement = right_connection.prepare(&right_sql)?;
    let mut left_rows = left_statement.query([])?;
    let mut right_rows = right_statement.query([])?;
    let mut left_current = next_stream_row(
        &mut left_rows,
        &comparison_columns,
        &left_identity,
        identity_embedded_in_values,
    )?;
    let mut right_current = next_stream_row(
        &mut right_rows,
        &comparison_columns,
        &right_identity,
        identity_embedded_in_values,
    )?;

    let mut added_rows = Vec::new();
    let mut removed_rows = Vec::new();
    let mut removed_row_keys = Vec::new();
    let mut modified_rows = Vec::new();
    let mut stats = DiffStats {
        total_rows_left: left_table.row_count,
        total_rows_right: right_table.row_count,
        ..DiffStats::default()
    };

    loop {
        match (left_current.as_ref(), right_current.as_ref()) {
            (Some(left_row), Some(right_row)) => {
                match compare_value_slices(&left_row.pk_values, &right_row.pk_values) {
                    Ordering::Less => {
                        removed_rows.push(left_row.row_values.clone());
                        removed_row_keys.push(left_row.pk_values.clone());
                        stats.removed += 1;
                        left_current = next_stream_row(
                            &mut left_rows,
                            &comparison_columns,
                            &left_identity,
                            identity_embedded_in_values,
                        )?;
                    }
                    Ordering::Greater => {
                        added_rows.push(right_row.row_values.clone());
                        stats.added += 1;
                        right_current = next_stream_row(
                            &mut right_rows,
                            &comparison_columns,
                            &right_identity,
                            identity_embedded_in_values,
                        )?;
                    }
                    Ordering::Equal => {
                        let changes = comparison_columns
                            .iter()
                            .zip(left_row.row_values.iter().zip(right_row.row_values.iter()))
                            .filter_map(|(column, (left_value, right_value))| {
                                if compare_sql_values(left_value, right_value) == Ordering::Equal {
                                    None
                                } else {
                                    Some(crate::db::types::CellChange {
                                        column: column.clone(),
                                        old_value: left_value.clone(),
                                        new_value: right_value.clone(),
                                    })
                                }
                            })
                            .collect::<Vec<_>>();

                        if changes.is_empty() {
                            stats.unchanged += 1;
                        } else {
                            modified_rows.push(RowModification {
                                primary_key: left_row.pk_values.clone(),
                                changes,
                            });
                            stats.modified += 1;
                        }
                        left_current = next_stream_row(
                            &mut left_rows,
                            &comparison_columns,
                            &left_identity,
                            identity_embedded_in_values,
                        )?;
                        right_current = next_stream_row(
                            &mut right_rows,
                            &comparison_columns,
                            &right_identity,
                            identity_embedded_in_values,
                        )?;
                    }
                }
            }
            (Some(left_row), None) => {
                removed_rows.push(left_row.row_values.clone());
                removed_row_keys.push(left_row.pk_values.clone());
                stats.removed += 1;
                left_current = next_stream_row(
                    &mut left_rows,
                    &comparison_columns,
                    &left_identity,
                    identity_embedded_in_values,
                )?;
            }
            (None, Some(right_row)) => {
                added_rows.push(right_row.row_values.clone());
                stats.added += 1;
                right_current = next_stream_row(
                    &mut right_rows,
                    &comparison_columns,
                    &right_identity,
                    identity_embedded_in_values,
                )?;
            }
            (None, None) => break,
        }
    }

    Ok(TableDataDiff {
        table_name: left_table.name.clone(),
        columns: comparison_columns,
        added_rows,
        removed_rows,
        removed_row_keys,
        modified_rows,
        stats,
        warnings,
    })
}

fn shared_column_names(left: &TableInfo, right: &TableInfo) -> Vec<String> {
    let right_names = right
        .columns
        .iter()
        .map(|column| column.name.clone())
        .collect::<BTreeSet<_>>();
    left.columns
        .iter()
        .filter(|column| right_names.contains(&column.name))
        .map(|column| column.name.clone())
        .collect()
}

fn build_stream_sql(
    table: &TableInfo,
    comparison_columns: &[String],
    identity_columns: &[IdentityExpr],
    identity_embedded_in_values: bool,
) -> String {
    let mut select_terms = if identity_embedded_in_values {
        comparison_columns
            .iter()
            .map(|column| quote_identifier(column))
            .collect::<Vec<_>>()
    } else {
        identity_columns
            .iter()
            .enumerate()
            .map(|(index, column)| column.select_sql(Some(&identity_alias(index))))
            .collect::<Vec<_>>()
    };
    select_terms.extend(
        comparison_columns
            .iter()
            .map(|column| quote_identifier(column)),
    );

    format!(
        "SELECT {} FROM {} ORDER BY {}",
        select_terms.join(", "),
        quote_identifier(&table.name),
        identity_columns
            .iter()
            .map(IdentityExpr::order_sql)
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn next_stream_row(
    rows: &mut Rows<'_>,
    comparison_columns: &[String],
    identity_columns: &[IdentityExpr],
    identity_embedded_in_values: bool,
) -> Result<Option<StreamRow>> {
    let Some(row) = rows.next()? else {
        return Ok(None);
    };

    if identity_embedded_in_values {
        let row_values = read_value_row(row, comparison_columns.len(), 0)?;
        let mut pk_values = Vec::with_capacity(identity_columns.len());
        for key in identity_columns {
            let IdentityExpr::Column(key) = key else {
                return Err(PatchworksError::InvalidState(
                    "embedded diff identity cannot use rowid".to_owned(),
                ));
            };
            let index = comparison_columns
                .iter()
                .position(|column| column == key)
                .ok_or_else(|| {
                    PatchworksError::InvalidState(format!(
                        "primary key column `{key}` missing from comparison set"
                    ))
                })?;
            pk_values.push(row_values[index].clone());
        }

        Ok(Some(StreamRow {
            pk_values,
            row_values,
        }))
    } else {
        let pk_values = read_value_row(row, identity_columns.len(), 0)?;
        let row_values = read_value_row(row, comparison_columns.len(), identity_columns.len())?;
        Ok(Some(StreamRow {
            pk_values,
            row_values,
        }))
    }
}

fn fallback_identity_exprs(table: &TableInfo) -> Result<Vec<IdentityExpr>> {
    if !table.primary_key.is_empty() {
        Ok(table
            .primary_key
            .iter()
            .cloned()
            .map(IdentityExpr::Column)
            .collect())
    } else if table_supports_rowid(table) {
        Ok(vec![IdentityExpr::RowId])
    } else {
        Err(PatchworksError::InvalidState(format!(
            "table `{}` has no shared primary key and no usable row identity for diffing",
            table.name
        )))
    }
}

fn table_supports_rowid(table: &TableInfo) -> bool {
    table
        .create_sql
        .as_ref()
        .map(|sql| !sql.to_ascii_uppercase().contains("WITHOUT ROWID"))
        .unwrap_or(true)
}

fn identity_alias(index: usize) -> String {
    format!("{ROWID_ALIAS}_{index}")
}