sql-splitter 1.8.0

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

**Status**: Draft  
**Date**: 2025-12-20

## Overview

The `diff` command compares two SQL dump files and shows schema and/or data differences. It can generate migration SQL to transform one dump into another.

## Command Interface

```bash
# Compare two dumps (schema + data summary)
sql-splitter diff old.sql new.sql

# Schema-only comparison
sql-splitter diff old.sql new.sql --schema-only

# Data-only comparison
sql-splitter diff old.sql new.sql --data-only

# Compare specific table
sql-splitter diff old.sql new.sql --table users

# Generate migration SQL
sql-splitter diff old.sql new.sql --output migration.sql

# Output as JSON for programmatic use
sql-splitter diff old.sql new.sql --format json

# Ignore specific tables
sql-splitter diff old.sql new.sql --exclude cache,sessions,logs

# Show row-level details
sql-splitter diff old.sql new.sql --table users --verbose
```

## CLI Options

| Flag | Description | Default |
|------|-------------|---------|
| `-o, --output` | Output file for migration SQL | stdout |
| `-t, --table` | Compare specific table(s) only | all |
| `--exclude` | Exclude tables from comparison | none |
| `--schema-only` | Compare schema only, ignore data | false |
| `--data-only` | Compare data only, ignore schema | false |
| `--format` | Output format: `text`, `sql`, `json` | text |
| `--verbose` | Show detailed row-level changes | false |
| `--primary-key` | Override PK for data comparison | auto-detect |
| `-d, --dialect` | SQL dialect | auto-detect |
| `-p, --progress` | Show progress bar | false |
| `--ignore-order` | Ignore column order differences | false |
| `--ignore-whitespace` | Ignore whitespace in definitions | true |

## Output Formats

### Text (Default) — Human Readable

```
Comparing: old.sql → new.sql

Schema Changes:
  + Table 'audit_logs' (new)
  - Table 'legacy_data' (removed)
  ~ Table 'users':
    + Column 'phone' VARCHAR(20)
    - Column 'fax' VARCHAR(20)
    ~ Column 'email': VARCHAR(100) → VARCHAR(255)
    + Index 'idx_users_phone' (phone)

Data Changes:
  Table 'users':
    + 45 rows added
    - 12 rows removed
    ~ 89 rows modified
  
  Table 'products':
    + 120 rows added
    ~ 34 rows modified

Summary:
  Tables: 2 added, 1 removed, 5 modified
  Rows: 165 added, 12 removed, 123 modified
```

### SQL — Migration Script

```sql
-- Migration: old.sql → new.sql
-- Generated: 2025-12-20 12:00:00

-- Schema Changes

-- New table: audit_logs
CREATE TABLE `audit_logs` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `action` VARCHAR(50),
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Removed table: legacy_data
DROP TABLE IF EXISTS `legacy_data`;

-- Modified table: users
ALTER TABLE `users` ADD COLUMN `phone` VARCHAR(20);
ALTER TABLE `users` DROP COLUMN `fax`;
ALTER TABLE `users` MODIFY COLUMN `email` VARCHAR(255);
CREATE INDEX `idx_users_phone` ON `users` (`phone`);

-- Data Changes

-- Table: users (45 inserts, 12 deletes, 89 updates)
INSERT INTO `users` (id, email, name) VALUES
(101, 'new1@example.com', 'New User 1'),
(102, 'new2@example.com', 'New User 2');

DELETE FROM `users` WHERE id IN (5, 12, 23);

UPDATE `users` SET email = 'updated@example.com', name = 'Updated Name' WHERE id = 7;
```

### JSON — Programmatic Use

```json
{
  "old_file": "old.sql",
  "new_file": "new.sql",
  "schema": {
    "tables_added": ["audit_logs"],
    "tables_removed": ["legacy_data"],
    "tables_modified": {
      "users": {
        "columns_added": [{"name": "phone", "type": "VARCHAR(20)"}],
        "columns_removed": [{"name": "fax", "type": "VARCHAR(20)"}],
        "columns_modified": [{
          "name": "email",
          "old_type": "VARCHAR(100)",
          "new_type": "VARCHAR(255)"
        }],
        "indexes_added": [{"name": "idx_users_phone", "columns": ["phone"]}]
      }
    }
  },
  "data": {
    "users": {
      "rows_added": 45,
      "rows_removed": 12,
      "rows_modified": 89
    }
  },
  "summary": {
    "tables_added": 2,
    "tables_removed": 1,
    "tables_modified": 5,
    "rows_added": 165,
    "rows_removed": 12,
    "rows_modified": 123
  }
}
```

## Comparison Logic

### Schema Comparison

#### Tables
- **Added**: Table exists in new, not in old
- **Removed**: Table exists in old, not in new
- **Modified**: Same table name, different definition

#### Columns
Compare by column name within each table:
- **Added**: Column in new, not in old
- **Removed**: Column in old, not in new
- **Modified**: Same name, different type/constraints

**Attributes compared:**
- Data type (including size)
- NULL/NOT NULL
- DEFAULT value
- AUTO_INCREMENT/SERIAL
- Character set/collation (MySQL)

#### Indexes
Compare by index name or column combination:
- **Added/Removed/Modified**
- Compare: columns, unique, type (BTREE, FULLTEXT, etc.)

#### Constraints
- PRIMARY KEY changes
- FOREIGN KEY changes
- UNIQUE constraints
- CHECK constraints

### Data Comparison

#### Primary Key Detection

1. Parse CREATE TABLE for PRIMARY KEY
2. Use first UNIQUE index if no PK
3. Use `--primary-key` override if specified
4. Error if no PK can be determined

#### Row Matching

Match rows by primary key value:

```
Old: (1, 'alice@old.com', 'Alice')
New: (1, 'alice@new.com', 'Alice Smith')
→ Modified: id=1, email changed, name changed
```

#### Change Detection

| Old | New | Result |
|-----|-----|--------|
| Row exists | Row exists, same | No change |
| Row exists | Row exists, different | Modified |
| Row exists | Row missing | Removed |
| Row missing | Row exists | Added |

## Implementation Architecture

### Core Components

```
src/
├── cmd/
│   └── diff.rs              # CLI handler
├── differ/
│   ├── mod.rs               # Public API
│   ├── schema.rs            # Schema comparison
│   ├── data.rs              # Data comparison
│   ├── parser.rs            # Schema extraction
│   ├── matcher.rs           # Row matching
│   └── output/
│       ├── text.rs          # Text formatter
│       ├── sql.rs           # SQL generator
│       └── json.rs          # JSON formatter
```

### Key Types

```rust
pub struct DiffConfig {
    pub old_file: PathBuf,
    pub new_file: PathBuf,
    pub dialect: SqlDialect,
    pub tables: Option<Vec<String>>,
    pub exclude: Vec<String>,
    pub schema_only: bool,
    pub data_only: bool,
    pub format: DiffFormat,
    pub verbose: bool,
    pub primary_key_override: Option<Vec<String>>,
    pub progress: bool,
}

pub enum DiffFormat {
    Text,
    Sql,
    Json,
}

pub struct DiffResult {
    pub schema: SchemaDiff,
    pub data: DataDiff,
}

pub struct SchemaDiff {
    pub tables_added: Vec<TableDef>,
    pub tables_removed: Vec<String>,
    pub tables_modified: Vec<TableModification>,
}

pub struct TableModification {
    pub table_name: String,
    pub columns_added: Vec<ColumnDef>,
    pub columns_removed: Vec<ColumnDef>,
    pub columns_modified: Vec<ColumnChange>,
    pub indexes_added: Vec<IndexDef>,
    pub indexes_removed: Vec<IndexDef>,
    pub indexes_modified: Vec<IndexChange>,
}

pub struct DataDiff {
    pub tables: HashMap<String, TableDataDiff>,
}

pub struct TableDataDiff {
    pub rows_added: Vec<Row>,      // Or just count if not verbose
    pub rows_removed: Vec<PkValue>,
    pub rows_modified: Vec<RowChange>,
    pub added_count: u64,
    pub removed_count: u64,
    pub modified_count: u64,
}

pub struct RowChange {
    pub pk: PkValue,
    pub changes: Vec<ColumnValueChange>,
}
```

### Algorithm

#### Two-Pass Approach

**Pass 1: Schema Extraction**
1. Parse old file, extract all CREATE TABLE statements
2. Parse new file, extract all CREATE TABLE statements
3. Compare schemas, build SchemaDiff

**Pass 2: Data Comparison**
1. For each table in both files:
   - Build hash map of old rows by PK
   - Stream new file, compare each row
   - Track added/modified/removed

#### Memory Considerations

For large tables, can't hold all rows in memory:

**Option A: Two-file streaming (for sorted dumps)**
- Assumes rows sorted by PK
- Merge-sort comparison

**Option B: Chunked hashing**
- Hash rows into buckets by PK
- Compare buckets independently
- Spill large buckets to temp files

**Option C: Database-backed (future)**
- Load both into SQLite temp DB
- Use SQL for comparison

## Edge Cases

### 1. Column Order Changes
```sql
-- Old: (id, name, email)
-- New: (id, email, name)
```
With `--ignore-order`: No change
Without: Report as modified

### 2. Case Sensitivity
```sql
-- Old: CREATE TABLE Users
-- New: CREATE TABLE users
```
Handle per-dialect (MySQL case-insensitive on some platforms)

### 3. Renamed Tables
Cannot auto-detect renames. Shows as remove + add.
Future: `--renames "old_name:new_name"`

### 4. Renamed Columns
Same as tables. Future: heuristic matching by type/position.

### 5. No Primary Key
- Error by default
- `--primary-key "col1,col2"` override
- `--allow-no-pk` to skip data comparison for that table

### 6. Large Tables
Memory limits for data comparison:
- `--max-rows 100000` to limit comparison
- `--sample-data` to compare random sample

### 7. Binary Data
Skip BLOB/BYTEA columns in detailed diff, just note "binary data differs"

## Performance Considerations

### Schema Comparison
- Fast: only parses CREATE statements
- O(tables * columns)

### Data Comparison
- Memory: O(rows in smaller table) for hash approach
- Time: O(rows in both tables)
- Disk: May need temp storage for large tables

### Targets

| File Size | Target Time |
|-----------|-------------|
| 100 MB | < 5 seconds |
| 1 GB | < 30 seconds |
| 10 GB | < 5 minutes |

## Testing Strategy

### Unit Tests
- Schema parsing for each dialect
- Column comparison logic
- Index comparison logic
- Row matching algorithms

### Integration Tests
- Known diff scenarios with expected output
- Roundtrip: apply migration.sql, diff should be empty
- All three dialects
- Large file handling

### Edge Case Tests
- Empty tables
- Tables with no PK
- Unicode data
- Binary data
- NULL values

## Example Workflows

### 1. Pre-Deployment Review

```bash
# Compare staging vs production schema
sql-splitter diff prod_backup.sql staging_dump.sql --schema-only

# Generate and review migration
sql-splitter diff prod.sql staging.sql --output migration.sql
cat migration.sql  # Review before applying
```

### 2. Audit Data Changes

```bash
# What changed between backups?
sql-splitter diff backup_monday.sql backup_friday.sql --data-only --format json > changes.json
```

### 3. Validate Migration

```bash
# After migration, verify no unintended changes
sql-splitter diff expected.sql actual.sql
# Should show no differences
```

### 4. Generate Sync Script

```bash
# Sync dev database from production subset
sql-splitter diff dev.sql prod_subset.sql --output sync.sql
mysql dev_db < sync.sql
```

## Estimated Effort

| Component | Effort |
|-----------|--------|
| CLI and config | 2 hours |
| Schema parser (CREATE TABLE) | 6 hours |
| Schema comparison | 4 hours |
| Data comparison (hash-based) | 8 hours |
| Text output formatter | 3 hours |
| SQL migration generator | 6 hours |
| JSON output formatter | 2 hours |
| Memory-efficient large file handling | 6 hours |
| Testing | 8 hours |
| **Total** | **~45 hours** |

## Future Enhancements

1. **Rename detection**: Heuristic matching for renamed tables/columns
2. **Ignore patterns**: `--ignore-columns "*.updated_at"`
3. **Semantic comparison**: Ignore formatting differences in DEFAULT values
4. **Patch format**: Standard diff/patch output
5. **Three-way merge**: Common ancestor comparison
6. **Interactive mode**: Approve/reject each change

## Related

- [Split Command]../../src/cmd/split.rs
- [Convert Feature]CONVERT_FEASIBILITY.md
- [Merge Feature]MERGE_FEATURE.md