-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathlibSqlPushUtils.ts
More file actions
363 lines (320 loc) · 10.7 KB
/
libSqlPushUtils.ts
File metadata and controls
363 lines (320 loc) · 10.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
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
import chalk from 'chalk';
import { JsonStatement } from 'src/jsonStatements';
import { findAddedAndRemoved, SQLiteDB } from 'src/utils';
import { SQLiteSchemaInternal, SQLiteSchemaSquashed, SQLiteSquasher } from '../../serializer/sqliteSchema';
import {
CreateSqliteIndexConvertor,
fromJson,
LibSQLModifyColumn,
SQLiteCreateTableConvertor,
SQLiteDropTableConvertor,
SqliteRenameTableConvertor,
} from '../../sqlgenerator';
export const getOldTableName = (
tableName: string,
meta: SQLiteSchemaInternal['_meta'],
) => {
for (const key of Object.keys(meta.tables)) {
const value = meta.tables[key];
if (`"${tableName}"` === value) {
return key.substring(1, key.length - 1);
}
}
return tableName;
};
export const _moveDataStatements = (
tableName: string,
json: SQLiteSchemaSquashed,
dataLoss: boolean = false,
) => {
const statements: string[] = [];
const newTableName = `__new_${tableName}`;
// create table statement from a new json2 with proper name
const tableColumns = Object.values(json.tables[tableName].columns);
const referenceData = Object.values(json.tables[tableName].foreignKeys);
const compositePKs = Object.values(
json.tables[tableName].compositePrimaryKeys,
).map((it) => SQLiteSquasher.unsquashPK(it));
const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
const mappedCheckConstraints: string[] = checkConstraints.map((it) =>
it.replaceAll(`"${tableName}".`, `"${newTableName}".`)
.replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`)
.replaceAll(`${tableName}.`, `${newTableName}.`)
.replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
);
// create new table
statements.push(
new SQLiteCreateTableConvertor().convert({
type: 'sqlite_create_table',
tableName: newTableName,
columns: tableColumns,
referenceData: fks,
compositePKs,
checkConstraints: mappedCheckConstraints,
}),
);
// move data
if (!dataLoss) {
const columns = Object.keys(json.tables[tableName].columns).map(
(c) => `"${c}"`,
);
statements.push(
`INSERT INTO \`${newTableName}\`(${
columns.join(
', ',
)
}) SELECT ${columns.join(', ')} FROM \`${tableName}\`;`,
);
}
statements.push(
new SQLiteDropTableConvertor().convert({
type: 'drop_table',
tableName: tableName,
schema: '',
}),
);
// rename table
statements.push(
new SqliteRenameTableConvertor().convert({
fromSchema: '',
tableNameFrom: newTableName,
tableNameTo: tableName,
toSchema: '',
type: 'rename_table',
}),
);
for (const idx of Object.values(json.tables[tableName].indexes)) {
statements.push(
new CreateSqliteIndexConvertor().convert({
type: 'create_index',
tableName: tableName,
schema: '',
data: idx,
}),
);
}
return statements;
};
export const libSqlLogSuggestionsAndReturn = async (
connection: SQLiteDB,
statements: JsonStatement[],
json1: SQLiteSchemaSquashed,
json2: SQLiteSchemaSquashed,
meta: SQLiteSchemaInternal['_meta'],
) => {
let shouldAskForApprove = false;
const statementsToExecute: string[] = [];
const infoToPrint: string[] = [];
const tablesToRemove: string[] = [];
const columnsToRemove: string[] = [];
const tablesToTruncate: string[] = [];
// Track tables that have been recreated to avoid duplicate index creation
const recreatedTables = new Set<string>();
for (const statement of statements) {
if (statement.type === 'drop_table') {
const res = await connection.query<{ count: string }>(
`select count(*) as count from \`${statement.tableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to delete ${
chalk.underline(
statement.tableName,
)
} table with ${count} items`,
);
tablesToRemove.push(statement.tableName);
shouldAskForApprove = true;
}
const fromJsonStatement = fromJson([statement], 'turso', 'push', json2);
statementsToExecute.push(
...(Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]),
);
} else if (statement.type === 'alter_table_drop_column') {
const tableName = statement.tableName;
const res = await connection.query<{ count: string }>(
`select count(*) as count from \`${tableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to delete ${
chalk.underline(
statement.columnName,
)
} column in ${tableName} table with ${count} items`,
);
columnsToRemove.push(`${tableName}_${statement.columnName}`);
shouldAskForApprove = true;
}
const fromJsonStatement = fromJson([statement], 'turso', 'push', json2);
statementsToExecute.push(
...(Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]),
);
} else if (
statement.type === 'sqlite_alter_table_add_column'
&& statement.column.notNull
&& !statement.column.default
) {
const newTableName = statement.tableName;
const res = await connection.query<{ count: string }>(
`select count(*) as count from \`${newTableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to add not-null ${
chalk.underline(
statement.column.name,
)
} column without default value, which contains ${count} items`,
);
tablesToTruncate.push(newTableName);
statementsToExecute.push(`delete from ${newTableName};`);
shouldAskForApprove = true;
}
const fromJsonStatement = fromJson([statement], 'turso', 'push', json2);
statementsToExecute.push(
...(Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]),
);
} else if (statement.type === 'alter_table_alter_column_set_notnull') {
const tableName = statement.tableName;
if (
statement.type === 'alter_table_alter_column_set_notnull'
&& typeof statement.columnDefault === 'undefined'
) {
const res = await connection.query<{ count: string }>(
`select count(*) as count from \`${tableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to add not-null constraint to ${
chalk.underline(
statement.columnName,
)
} column without default value, which contains ${count} items`,
);
tablesToTruncate.push(tableName);
statementsToExecute.push(`delete from \`${tableName}\``);
shouldAskForApprove = true;
}
}
const modifyStatements = new LibSQLModifyColumn().convert(statement, json2);
statementsToExecute.push(
...(Array.isArray(modifyStatements) ? modifyStatements : [modifyStatements]),
);
} else if (statement.type === 'recreate_table') {
const tableName = statement.tableName;
// Mark table as recreated to skip duplicate index creation later
recreatedTables.add(tableName);
let dataLoss = false;
const oldTableName = getOldTableName(tableName, meta);
const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
const currentColumnNames = Object.keys(json2.tables[tableName].columns);
const { removedColumns, addedColumns } = findAddedAndRemoved(
prevColumnNames,
currentColumnNames,
);
if (removedColumns.length) {
for (const removedColumn of removedColumns) {
const res = await connection.query<{ count: string }>(
`select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to delete ${
chalk.underline(
removedColumn,
)
} column in ${tableName} table with ${count} items`,
);
columnsToRemove.push(removedColumn);
shouldAskForApprove = true;
}
}
}
if (addedColumns.length) {
for (const addedColumn of addedColumns) {
const [res] = await connection.query<{ count: string }>(
`select count(*) as count from \`${tableName}\``,
);
const columnConf = json2.tables[tableName].columns[addedColumn];
const count = Number(res.count);
if (count > 0 && columnConf.notNull && !columnConf.default) {
dataLoss = true;
infoToPrint.push(
`· You're about to add not-null ${
chalk.underline(
addedColumn,
)
} column without default value to table, which contains ${count} items`,
);
shouldAskForApprove = true;
tablesToTruncate.push(tableName);
statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
}
}
}
// check if some tables referencing current for pragma
const tablesReferencingCurrent: string[] = [];
for (const table of Object.values(json2.tables)) {
const tablesRefs = Object.values(json2.tables[table.name].foreignKeys)
.filter((t) => SQLiteSquasher.unsquashPushFK(t).tableTo === tableName)
.map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
tablesReferencingCurrent.push(...tablesRefs);
}
if (!tablesReferencingCurrent.length) {
statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
continue;
}
// recreate table
statementsToExecute.push(
..._moveDataStatements(tableName, json2, dataLoss),
);
} else if (
statement.type === 'alter_table_alter_column_set_generated'
|| statement.type === 'alter_table_alter_column_drop_generated'
) {
const tableName = statement.tableName;
const res = await connection.query<{ count: string }>(
`select count("${statement.columnName}") as count from \`${tableName}\``,
);
const count = Number(res[0].count);
if (count > 0) {
infoToPrint.push(
`· You're about to delete ${
chalk.underline(
statement.columnName,
)
} column in ${tableName} table with ${count} items`,
);
columnsToRemove.push(`${tableName}_${statement.columnName}`);
shouldAskForApprove = true;
}
const fromJsonStatement = fromJson([statement], 'turso', 'push', json2);
statementsToExecute.push(
...(Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]),
);
} else if (statement.type === 'create_index' && recreatedTables.has(statement.tableName)) {
// Skip create_index for recreated tables - indexes are already created in _moveDataStatements
continue;
} else {
const fromJsonStatement = fromJson([statement], 'turso', 'push', json2);
statementsToExecute.push(
...(Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]),
);
}
}
return {
statementsToExecute: [...new Set(statementsToExecute)],
shouldAskForApprove,
infoToPrint,
columnsToRemove: [...new Set(columnsToRemove)],
tablesToTruncate: [...new Set(tablesToTruncate)],
tablesToRemove: [...new Set(tablesToRemove)],
};
};