Repository navigation
Expand file tree
/
Copy pathdiff.ts
More file actions
255 lines (231 loc) · 9.51 KB
/
Copy pathdiff.ts
File metadata and controls
255 lines (231 loc) · 9.51 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
253
254
255
// Diff two schemas into migration ops.
//
// Pure and offline, like drizzle-kit's `generate`. Two things stop it from
// writing a migration on its own:
//
// - Data loss (dropping a table or a column) needs a `confirm_data_loss` hint,
// from a prompt or from `--hints`. Without one the change is reported as a
// missing hint and nothing is written, the way drizzle-kit exits 2.
// - Changes ClickHouse cannot make with ALTER (engine, sorting key, partition
// key, primary key, column type) are reported as unsupported. They need a
// table rebuild, which this version does not generate.
//
// Renames are not detected yet: a renamed column reads as a drop plus an add,
// and the drop asks for confirmation, so a rename never loses data silently.
import { Schema } from "effect"
import {
canonicalJson,
entityKey,
type ColumnEntity,
type IndexEntity,
type MaterializedViewEntity,
type SchemaEntity,
type TableEntity,
} from "./entities"
import type { MigrationOp } from "./ops"
export const Hint = Schema.Union([
Schema.Struct({
type: Schema.Literal("confirm_data_loss"),
/** `enum`: dropping a Postgres enum type. */
kind: Schema.Literals(["table", "column", "enum"]),
/** `table`, `table.column`, or the enum's name. */
entity: Schema.String,
}),
/**
* A rename. `enum_value`: a Postgres enum label renamed in place (`ALTER
* TYPE ... RENAME VALUE`), so rows holding it now hold `to`. `table` and
* `column` (SQLite): `ALTER TABLE ... RENAME`, instead of a drop and a create.
*/
Schema.Struct({
type: Schema.Literal("confirm_rename"),
kind: Schema.Literals(["enum_value", "table", "column"]),
/** `<enum>.<old label>`, the old table name, or `<table>.<old column>` with the table's new name. */
entity: Schema.String,
to: Schema.String,
}),
])
export type Hint = typeof Hint.Type
export const Hints = Schema.Array(Hint)
export interface UnsupportedChange {
readonly entity: string
readonly message: string
}
export interface DiffResult<Op = MigrationOp> {
readonly ops: ReadonlyArray<Op>
readonly missingHints: ReadonlyArray<Hint>
readonly unsupported: ReadonlyArray<UnsupportedChange>
}
/** Hints match on this; a rename's target is part of what was confirmed. */
export const hintKey = (hint: Hint): string =>
`${hint.type}:${hint.kind}:${hint.entity}${hint.type === "confirm_rename" ? `>${hint.to}` : ""}`
const byKind = <K extends SchemaEntity["kind"]>(entities: ReadonlyArray<SchemaEntity>, kind: K) =>
new Map(
entities
.filter((e): e is Extract<SchemaEntity, { kind: K }> => e.kind === kind)
.map((e) => [entityKey(e), e] as const),
)
/** Key order is not a change; the snapshot hash ignores it too. */
const same = (a: unknown, b: unknown): boolean => canonicalJson(a) === canonicalJson(b)
const opOrder: Record<MigrationOp["op"], number> = {
drop_view: 0,
drop_index: 1,
drop_column: 2,
drop_table: 3,
create_table: 4,
add_column: 5,
modify_column: 6,
modify_ttl: 7,
modify_settings: 8,
modify_comment: 9,
add_index: 10,
create_view: 11,
// Never generated; listed so the order covers every op.
backfill: 12,
}
export const diffSchemas = (
prev: ReadonlyArray<SchemaEntity>,
next: ReadonlyArray<SchemaEntity>,
hints: ReadonlyArray<Hint> = [],
): DiffResult => {
const given = new Set(hints.map(hintKey))
const ops: Array<MigrationOp> = []
const missingHints: Array<Hint> = []
const unsupported: Array<UnsupportedChange> = []
const confirm = (hint: Hint, op: MigrationOp): void => {
if (given.has(hintKey(hint))) ops.push(op)
else missingHints.push(hint)
}
const prevTables = byKind(prev, "table")
const nextTables = byKind(next, "table")
const prevColumns = byKind(prev, "column")
const nextColumns = byKind(next, "column")
const prevIndexes = byKind(prev, "index")
const nextIndexes = byKind(next, "index")
const columnsOf = (columns: Map<string, ColumnEntity>, table: string): ReadonlyArray<ColumnEntity> =>
[...columns.values()].filter((c) => c.table === table).sort((a, b) => a.position - b.position)
const indexesOf = (indexes: Map<string, IndexEntity>, table: string): ReadonlyArray<IndexEntity> =>
[...indexes.values()].filter((i) => i.table === table)
for (const [key, table] of nextTables) {
if (!prevTables.has(key)) {
ops.push({
op: "create_table",
table,
columns: columnsOf(nextColumns, table.name),
indexes: indexesOf(nextIndexes, table.name),
})
}
}
for (const [key, table] of prevTables) {
if (!nextTables.has(key)) {
confirm({ type: "confirm_data_loss", kind: "table", entity: table.name }, { op: "drop_table", name: table.name })
}
}
for (const [key, after] of nextTables) {
const before = prevTables.get(key)
if (before === undefined) continue
diffTable(before, after, ops, unsupported)
const beforeColumns = columnsOf(prevColumns, after.name)
const afterColumns = columnsOf(nextColumns, after.name)
const beforeByName = new Map(beforeColumns.map((c) => [c.name, c]))
const afterNames = new Set(afterColumns.map((c) => c.name))
afterColumns.forEach((column, i) => {
const old = beforeByName.get(column.name)
if (old === undefined) {
ops.push({ op: "add_column", column, after: i === 0 ? null : afterColumns[i - 1]!.name })
return
}
if (old.type !== column.type) {
unsupported.push({
entity: `${after.name}.${column.name}`,
message: `type ${old.type} -> ${column.type} rewrites data and is not generated yet`,
})
return
}
if (!same(old.default, column.default) || old.codec !== column.codec || old.comment !== column.comment) {
ops.push({ op: "modify_column", from: old, to: column })
}
})
for (const column of beforeColumns) {
if (!afterNames.has(column.name)) {
confirm(
{ type: "confirm_data_loss", kind: "column", entity: `${after.name}.${column.name}` },
{ op: "drop_column", table: after.name, name: column.name },
)
}
}
const beforeIndexes = new Map(indexesOf(prevIndexes, after.name).map((i) => [i.name, i]))
const afterIndexes = indexesOf(nextIndexes, after.name)
for (const index of afterIndexes) {
const old = beforeIndexes.get(index.name)
if (old !== undefined && same(old, index)) continue
if (old !== undefined) ops.push({ op: "drop_index", table: after.name, name: index.name })
ops.push({ op: "add_index", index })
}
for (const old of beforeIndexes.values()) {
if (!afterIndexes.some((i) => i.name === old.name)) {
ops.push({ op: "drop_index", table: after.name, name: old.name })
}
}
}
diffViews(byKind(prev, "materialized_view"), byKind(next, "materialized_view"), ops)
// Dropping a table a kept view still reads would leave that view failing every insert.
const droppedTables = new Set(ops.flatMap((op) => (op.op === "drop_table" ? [op.name] : [])))
for (const view of byKind(next, "materialized_view").values()) {
for (const source of view.sources) {
if (droppedTables.has(source)) {
unsupported.push({ entity: view.name, message: `reads ${source}, which this migration drops` })
}
}
}
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,
}
}
const diffTable = (
before: TableEntity,
after: TableEntity,
ops: Array<MigrationOp>,
unsupported: Array<UnsupportedChange>,
): void => {
const rebuild = (what: string, from: unknown, to: unknown) =>
unsupported.push({
entity: after.name,
message: `${what} ${JSON.stringify(from)} -> ${JSON.stringify(to)} needs a table rebuild, which is not generated yet`,
})
if (!same(before.engine, after.engine)) rebuild("engine", before.engine, after.engine)
if (before.orderBy !== after.orderBy) rebuild("ORDER BY", before.orderBy, after.orderBy)
if (before.partitionBy !== after.partitionBy) rebuild("PARTITION BY", before.partitionBy, after.partitionBy)
if (before.primaryKey !== after.primaryKey) rebuild("PRIMARY KEY", before.primaryKey, after.primaryKey)
if (before.ttl !== after.ttl) ops.push({ op: "modify_ttl", table: after.name, ttl: after.ttl })
const set = Object.fromEntries(Object.entries(after.settings).filter(([k, v]) => before.settings[k] !== v))
const reset = Object.keys(before.settings).filter((k) => !(k in after.settings))
if (Object.keys(set).length > 0 || reset.length > 0) ops.push({ op: "modify_settings", table: after.name, set, reset })
if (before.comment !== after.comment) ops.push({ op: "modify_comment", table: after.name, comment: after.comment })
}
/**
* A view's SELECT with the backticks off the names that are plain words. The builder quotes a
* few of them since 1.0 (`null`, `all`, `top`, … which ClickHouse can read as something else),
* so a snapshot written before says `AS top` where the schema now says ``AS `top` ``: the same
* query, and no reason to drop a view and create it again.
*/
const viewBody = (select: string): string => select.replace(/`([A-Za-z_][A-Za-z0-9_]*)`/g, "$1")
const sameView = (a: MaterializedViewEntity, b: MaterializedViewEntity): boolean =>
same({ ...a, select: viewBody(a.select) }, { ...b, select: viewBody(b.select) })
/** A view's body is frozen at creation, so any change is a drop and a re-create. */
const diffViews = (
before: Map<string, MaterializedViewEntity>,
after: Map<string, MaterializedViewEntity>,
ops: Array<MigrationOp>,
): void => {
for (const [key, view] of after) {
const old = before.get(key)
if (old !== undefined && sameView(old, view)) continue
if (old !== undefined) ops.push({ op: "drop_view", name: view.name })
ops.push({ op: "create_view", view })
}
for (const [key, view] of before) {
if (!after.has(key)) ops.push({ op: "drop_view", name: view.name })
}
}