Repository navigation
Expand file tree
/
Copy pathsqlite-diff.ts
More file actions
252 lines (234 loc) · 12.7 KB
/
Copy pathsqlite-diff.ts
File metadata and controls
252 lines (234 loc) · 12.7 KB
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
// Diff two SQLite schemas into migration ops.
//
// Pure and offline, like `diffPgSchemas`, with the same data-loss rule:
// dropping a table or a column needs a `confirm_data_loss` hint. A change
// SQLite's ALTER TABLE can make becomes an ALTER TABLE; any other change to a
// table becomes one `rebuild_table` op that carries the whole new table (see
// `sqlite-ops.ts`). Renames are never guessed: a `confirm_rename` hint turns
// a drop plus an add into a RENAME.
import { canonicalJson, entityKey } from "./entities"
import { hintKey, type DiffResult, type Hint, type UnsupportedChange } from "./diff"
import type { SqliteColumnEntity, SqliteIndexEntity, SqliteSchemaEntity, SqliteTableEntity, SqliteUniqueEntity } from "./sqlite-entities"
import type { SqliteMigrationOp } from "./sqlite-ops"
import { sqliteIdent } from "./sqlite-render"
const same = (a: unknown, b: unknown): boolean => canonicalJson(a) === canonicalJson(b)
const pick = <K extends SqliteSchemaEntity["kind"]>(entities: ReadonlyArray<SqliteSchemaEntity>, kind: K) =>
entities.filter((e): e is Extract<SqliteSchemaEntity, { kind: K }> => e.kind === kind)
// Renames first, so later ops use the new names. Index drops before column
// drops, so no dropped column is still indexed. Column adds before column
// drops: SQLite cannot drop a table's last column, and replacing every column
// would otherwise try to. Tables and columns exist before the indexes that
// need them, and a rebuilt table before its indexes.
const opOrder: Record<SqliteMigrationOp["op"], number> = {
rename_table: 0,
rename_column: 1,
drop_index: 2,
add_column: 3,
drop_column: 4,
drop_table: 5,
create_table: 6,
rebuild_table: 7,
create_index: 8,
}
export const diffSqliteSchemas = (
original: ReadonlyArray<SqliteSchemaEntity>,
next: ReadonlyArray<SqliteSchemaEntity>,
hints: ReadonlyArray<Hint> = [],
): DiffResult<SqliteMigrationOp> => {
// SQLite compares table and column names without case: `Name` to `name` is the same column,
// renamed, never a drop and an add (which would collide). No hint needed: nothing is lost.
hints = [...hints, ...caseOnlyRenames(original, next, hints)]
const given = new Set(hints.map(hintKey))
const ops: Array<SqliteMigrationOp> = []
const missingHints: Array<Hint> = []
const unsupported: Array<UnsupportedChange> = []
// Renames run first; everything after compares the renamed schema with the next one.
const prev = applyRenames(original, next, hints, ops, unsupported)
/** Push `op` once every hint it needs was given; otherwise report the missing ones. */
const confirm = (needed: Hint | ReadonlyArray<Hint>, op: SqliteMigrationOp): void => {
const missing = (Array.isArray(needed) ? needed : [needed]).filter((hint) => !given.has(hintKey(hint)))
if (missing.length === 0) ops.push(op)
else missingHints.push(...missing)
}
const tablesOf = (entities: ReadonlyArray<SqliteSchemaEntity>) => new Map(pick(entities, "table").map((t) => [t.name, t]))
const prevTables = tablesOf(prev)
const nextTables = tablesOf(next)
const partsOf = <E extends SqliteColumnEntity | SqliteUniqueEntity | SqliteIndexEntity>(list: ReadonlyArray<E>, table: string) =>
list.filter((e) => e.table === table)
const columns = (entities: ReadonlyArray<SqliteSchemaEntity>, table: string) =>
partsOf(pick(entities, "column"), table).sort((a, b) => a.position - b.position)
for (const [name, table] of nextTables) {
if (!prevTables.has(name)) ops.push({ op: "create_table", table, columns: columns(next, name), uniques: partsOf(pick(next, "unique"), name) })
}
for (const name of prevTables.keys()) {
if (!nextTables.has(name)) confirm({ type: "confirm_data_loss", kind: "table", entity: name }, { op: "drop_table", name })
}
for (const [name, after] of nextTables) {
const before = prevTables.get(name)
if (before === undefined) continue
diffTable(
{ table: before, columns: columns(prev, name), uniques: partsOf(pick(prev, "unique"), name) },
{ table: after, columns: columns(next, name), uniques: partsOf(pick(next, "unique"), name) },
ops,
confirm,
)
}
const rebuilt = new Set(ops.flatMap((op) => (op.op === "rebuild_table" ? [op.table.name] : [])))
const prevIndexes = new Map(pick(prev, "index").map((i) => [entityKey(i), i]))
const nextIndexes = new Map(pick(next, "index").map((i) => [entityKey(i), i]))
for (const [key, index] of nextIndexes) {
const old = prevIndexes.get(key)
// A rebuilt table lost its indexes with the old table; all of them are created again.
if (old !== undefined && same(old, index) && !rebuilt.has(index.table)) continue
if (old !== undefined && !rebuilt.has(index.table)) ops.push({ op: "drop_index", name: old.name })
ops.push({ op: "create_index", index })
}
for (const [key, index] of prevIndexes) {
// A dropped table takes its indexes with it.
if (!nextIndexes.has(key) && nextTables.has(index.table) && !rebuilt.has(index.table)) ops.push({ op: "drop_index", name: index.name })
}
return {
ops: ops
.map((op, i) => [op, i] as const)
.sort(([a, i], [b, j]) => opOrder[a.op] - opOrder[b.op] || i - j)
.map(([op]) => op),
missingHints,
unsupported,
}
}
interface TableState {
readonly table: SqliteTableEntity
readonly columns: ReadonlyArray<SqliteColumnEntity>
readonly uniques: ReadonlyArray<SqliteUniqueEntity>
}
/** What a column is, apart from its place in the table. */
const definition = (column: SqliteColumnEntity) => ({ type: column.type, notNull: column.notNull, default: column.default })
/**
* Can `ALTER TABLE ADD COLUMN` add it? Not to a key or a UNIQUE constraint,
* not NOT NULL without a default, and not with an expression default, which
* SQLite refuses there.
*/
const addable = (column: SqliteColumnEntity, after: TableState): boolean =>
!(after.table.primaryKey?.columns ?? []).includes(column.name) &&
!after.uniques.some((u) => u.columns.includes(column.name)) &&
(!column.notNull || (column.default !== null && column.default.toUpperCase() !== "NULL")) &&
(column.default === null || !/^\s*\(|^\s*current_(time|date|timestamp)\b/i.test(column.default))
/** Can `ALTER TABLE DROP COLUMN` drop it? Not from a key or a UNIQUE constraint. */
const droppable = (name: string, before: TableState): boolean =>
!(before.table.primaryKey?.columns ?? []).includes(name) && !before.uniques.some((u) => u.columns.includes(name))
/**
* One table's changes: ALTER TABLE where SQLite allows it, otherwise a
* rebuild. A rebuild copies every column the two tables share.
*/
const diffTable = (
before: TableState,
after: TableState,
ops: Array<SqliteMigrationOp>,
confirm: (needed: Hint | ReadonlyArray<Hint>, op: SqliteMigrationOp) => void,
): void => {
const name = after.table.name
const old = new Map(before.columns.map((c) => [c.name, c]))
const kept = new Set(after.columns.map((c) => c.name))
const added = after.columns.filter((c) => !old.has(c.name))
const dropped = before.columns.filter((c) => !kept.has(c.name))
const changed = after.columns.filter((c) => old.has(c.name) && !same(definition(old.get(c.name)!), definition(c)))
// A new type rewrites the column's values by SQLite's affinity rules ('007' becomes 7): confirm it like a drop.
const retyped = changed.filter((c) => old.get(c.name)!.type !== c.type)
const needsRebuild =
changed.length > 0 ||
!same(before.table.primaryKey, after.table.primaryKey) ||
!same(byName(before.uniques), byName(after.uniques)) ||
added.some((c) => !addable(c, after)) ||
dropped.some((c) => !droppable(c.name, before))
const dropHint = (column: string): Hint => ({ type: "confirm_data_loss", kind: "column", entity: `${name}.${column}` })
if (needsRebuild) {
const rebuild: SqliteMigrationOp = {
op: "rebuild_table",
table: after.table,
columns: after.columns,
uniques: after.uniques,
copy: after.columns.filter((c) => old.has(c.name)).map((c) => c.name),
}
confirm([...dropped, ...retyped].map((c) => dropHint(c.name)), rebuild)
return
}
for (const column of added) ops.push({ op: "add_column", column })
for (const column of dropped) confirm(dropHint(column.name), { op: "drop_column", table: name, name: column.name })
}
/**
* `confirm_rename` hints for names that differ only in case, tables first: a
* next table or column with no exact match whose name, ignoring case, is an
* old one's that is gone. Columns are matched in the table's new name.
*/
const caseOnlyRenames = (prev: ReadonlyArray<SqliteSchemaEntity>, next: ReadonlyArray<SqliteSchemaEntity>, hints: ReadonlyArray<Hint>): Array<Hint> => {
const renames: Array<Hint> = []
const tables = (entities: ReadonlyArray<SqliteSchemaEntity>) => pick(entities, "table").map((t) => t.name)
const match = (before: ReadonlyArray<string>, after: ReadonlyArray<string>) =>
after.flatMap((name) => {
if (before.includes(name)) return []
const old = before.find((b) => b.toLowerCase() === name.toLowerCase() && !after.includes(b))
return old === undefined ? [] : [[old, name] as const]
})
const hinted = new Map(hints.flatMap((h) => (h.type === "confirm_rename" && h.kind === "table" ? [[h.to, h.entity] as const] : [])))
const tableRenames = match(tables(prev).filter((t) => ![...hinted.values()].includes(t)), tables(next).filter((t) => !hinted.has(t)))
for (const [from, to] of tableRenames) renames.push({ type: "confirm_rename", kind: "table", entity: from, to })
const source = new Map([...hinted, ...tableRenames.map(([from, to]) => [to, from] as const)])
const columnsOf = (entities: ReadonlyArray<SqliteSchemaEntity>, table: string) => pick(entities, "column").filter((c) => c.table === table).map((c) => c.name)
const hintedColumns = new Set(hints.flatMap((h) => (h.type === "confirm_rename" && h.kind === "column" ? [h.entity] : [])))
for (const table of tables(next)) {
const before = columnsOf(prev, source.get(table) ?? table)
for (const [from, to] of match(before, columnsOf(next, table))) {
if (!hintedColumns.has(`${table}.${from}`)) renames.push({ type: "confirm_rename", kind: "column", entity: `${table}.${from}`, to })
}
}
return renames
}
const byName = (uniques: ReadonlyArray<SqliteUniqueEntity>) =>
[...uniques].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
/**
* Apply the `confirm_rename` hints for tables and columns: an op for each, and
* `prev` as it reads after them. SQLite's RENAME rewrites the indexes and
* constraints that name the table or column, so they are renamed here too.
* A hint that does not match the two schemas is reported.
*/
const applyRenames = (
prev: ReadonlyArray<SqliteSchemaEntity>,
next: ReadonlyArray<SqliteSchemaEntity>,
hints: ReadonlyArray<Hint>,
ops: Array<SqliteMigrationOp>,
unsupported: Array<UnsupportedChange>,
): ReadonlyArray<SqliteSchemaEntity> => {
let entities = prev
const has = (list: ReadonlyArray<SqliteSchemaEntity>, kind: "table" | "column", table: string, name?: string) =>
list.some((e) => (kind === "table" ? e.kind === "table" && e.name === table : e.kind === "column" && e.table === table && e.name === name))
for (const hint of hints) {
if (hint.type !== "confirm_rename" || hint.kind !== "table") continue
if (!has(entities, "table", hint.entity) || has(entities, "table", hint.to) || !has(next, "table", hint.to) || has(next, "table", hint.entity)) {
unsupported.push({ entity: hint.entity, message: `cannot rename to ${hint.to}: the old table must exist only before, and the new one only after` })
continue
}
ops.push({ op: "rename_table", from: hint.entity, to: hint.to })
entities = entities.map((e) => (e.kind === "table" ? (e.name === hint.entity ? { ...e, name: hint.to } : e) : e.table === hint.entity ? { ...e, table: hint.to } : e))
}
for (const hint of hints) {
if (hint.type !== "confirm_rename" || hint.kind !== "column") continue
const dot = hint.entity.lastIndexOf(".")
const table = hint.entity.slice(0, dot)
const from = hint.entity.slice(dot + 1)
if (dot <= 0 || !has(entities, "column", table, from) || has(entities, "column", table, hint.to) || !has(next, "column", table, hint.to) || has(next, "column", table, from)) {
unsupported.push({ entity: hint.entity, message: `cannot rename to ${hint.to}: the old column must exist only before, and the new one only after` })
continue
}
ops.push({ op: "rename_column", table, from, to: hint.to })
const rename = (name: string) => (name === from ? hint.to : name)
const quoted = sqliteIdent(from)
entities = entities.map((e): SqliteSchemaEntity => {
if (e.kind === "table") return e.name === table && e.primaryKey !== null ? { ...e, primaryKey: { columns: e.primaryKey.columns.map(rename) } } : e
if (e.table !== table) return e
if (e.kind === "column") return { ...e, name: rename(e.name) }
if (e.kind === "unique") return { ...e, columns: e.columns.map(rename) }
return { ...e, columns: e.columns.map((part) => part.split(quoted).join(sqliteIdent(hint.to))) }
})
}
return entities
}