@anthonyalayo/drizzle-kit 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/api.d.mts +2891 -0
  2. package/api.d.ts +2891 -0
  3. package/api.js +47534 -0
  4. package/api.mjs +47521 -0
  5. package/bin.cjs +80043 -0
  6. package/{src/index.ts → index-Z-1TKnbX.d.mts} +123 -141
  7. package/index-Z-1TKnbX.d.ts +308 -0
  8. package/index.d.mts +2 -0
  9. package/index.d.ts +2 -0
  10. package/index.js +32 -0
  11. package/index.mjs +7 -0
  12. package/package.json +1 -1
  13. package/utils.js +6056 -0
  14. package/utils.mjs +6032 -0
  15. package/.gitignore +0 -25
  16. package/build.dev.ts +0 -51
  17. package/build.ts +0 -112
  18. package/imports-checker/analyze.ts +0 -78
  19. package/imports-checker/checker.ts +0 -296
  20. package/imports-checker/grammar/grammar.ohm +0 -121
  21. package/imports-checker/grammar/grammar.ohm-bundle.d.ts +0 -164
  22. package/imports-checker/grammar/grammar.ohm-bundle.js +0 -753
  23. package/imports-checker/index.ts +0 -48
  24. package/patches/difflib@0.2.4.patch +0 -31
  25. package/src/@types/utils.ts +0 -58
  26. package/src/api.ts +0 -504
  27. package/src/cli/commands/_es5.ts +0 -2
  28. package/src/cli/commands/check.ts +0 -52
  29. package/src/cli/commands/drop.ts +0 -60
  30. package/src/cli/commands/introspect.ts +0 -772
  31. package/src/cli/commands/libSqlPushUtils.ts +0 -355
  32. package/src/cli/commands/migrate.ts +0 -1526
  33. package/src/cli/commands/mysqlIntrospect.ts +0 -53
  34. package/src/cli/commands/mysqlPushUtils.ts +0 -352
  35. package/src/cli/commands/mysqlUp.ts +0 -102
  36. package/src/cli/commands/pgIntrospect.ts +0 -55
  37. package/src/cli/commands/pgPushUtils.ts +0 -269
  38. package/src/cli/commands/pgUp.ts +0 -217
  39. package/src/cli/commands/push.ts +0 -637
  40. package/src/cli/commands/singlestoreIntrospect.ts +0 -53
  41. package/src/cli/commands/singlestorePushUtils.ts +0 -456
  42. package/src/cli/commands/singlestoreUp.ts +0 -1
  43. package/src/cli/commands/sqliteIntrospect.ts +0 -96
  44. package/src/cli/commands/sqlitePushUtils.ts +0 -322
  45. package/src/cli/commands/sqliteUp.ts +0 -52
  46. package/src/cli/commands/utils.ts +0 -858
  47. package/src/cli/connections.ts +0 -914
  48. package/src/cli/index.ts +0 -48
  49. package/src/cli/schema.ts +0 -794
  50. package/src/cli/selector-ui.ts +0 -38
  51. package/src/cli/utils.ts +0 -112
  52. package/src/cli/validations/cli.ts +0 -79
  53. package/src/cli/validations/common.ts +0 -193
  54. package/src/cli/validations/libsql.ts +0 -27
  55. package/src/cli/validations/mysql.ts +0 -61
  56. package/src/cli/validations/outputs.ts +0 -91
  57. package/src/cli/validations/postgres.ts +0 -83
  58. package/src/cli/validations/singlestore.ts +0 -61
  59. package/src/cli/validations/sqlite.ts +0 -104
  60. package/src/cli/validations/studio.ts +0 -24
  61. package/src/cli/views.ts +0 -658
  62. package/src/extensions/getTablesFilterByExtensions.ts +0 -16
  63. package/src/extensions/vector.ts +0 -10
  64. package/src/global.ts +0 -61
  65. package/src/introspect-mysql.ts +0 -1030
  66. package/src/introspect-pg.ts +0 -1435
  67. package/src/introspect-singlestore.ts +0 -913
  68. package/src/introspect-sqlite.ts +0 -533
  69. package/src/jsonDiffer.js +0 -882
  70. package/src/jsonStatements.ts +0 -3590
  71. package/src/loader.mjs +0 -57
  72. package/src/migrationPreparator.ts +0 -217
  73. package/src/schemaValidator.ts +0 -23
  74. package/src/serializer/index.ts +0 -142
  75. package/src/serializer/mysqlImports.ts +0 -38
  76. package/src/serializer/mysqlSchema.ts +0 -423
  77. package/src/serializer/mysqlSerializer.ts +0 -999
  78. package/src/serializer/pgImports.ts +0 -106
  79. package/src/serializer/pgSchema.ts +0 -937
  80. package/src/serializer/pgSerializer.ts +0 -2223
  81. package/src/serializer/singlestoreImports.ts +0 -38
  82. package/src/serializer/singlestoreSchema.ts +0 -257
  83. package/src/serializer/singlestoreSerializer.ts +0 -767
  84. package/src/serializer/sqliteImports.ts +0 -41
  85. package/src/serializer/sqliteSchema.ts +0 -352
  86. package/src/serializer/sqliteSerializer.ts +0 -931
  87. package/src/serializer/studio.ts +0 -694
  88. package/src/serializer/utils.ts +0 -45
  89. package/src/simulator.ts +0 -157
  90. package/src/snapshotsDiffer.ts +0 -4398
  91. package/src/sqlgenerator.ts +0 -4212
  92. package/src/statementCombiner.ts +0 -597
  93. package/src/utils/certs.ts +0 -44
  94. package/src/utils/words.ts +0 -1333
  95. package/src/utils.ts +0 -370
  96. package/tests/bin.test.ts +0 -58
  97. package/tests/cli/d1http.config.ts +0 -12
  98. package/tests/cli/drizzle.config.ts +0 -9
  99. package/tests/cli/durable-sqlite.config.ts +0 -7
  100. package/tests/cli/expo.config.ts +0 -7
  101. package/tests/cli/postgres.config.ts +0 -13
  102. package/tests/cli/postgres2.config.ts +0 -17
  103. package/tests/cli/schema.ts +0 -1
  104. package/tests/cli/turso.config.ts +0 -10
  105. package/tests/cli-export.test.ts +0 -79
  106. package/tests/cli-generate.test.ts +0 -259
  107. package/tests/cli-migrate.test.ts +0 -103
  108. package/tests/cli-push.test.ts +0 -126
  109. package/tests/common.ts +0 -15
  110. package/tests/indexes/common.ts +0 -21
  111. package/tests/indexes/pg.test.ts +0 -245
  112. package/tests/introspect/libsql.test.ts +0 -35
  113. package/tests/introspect/mysql.test.ts +0 -319
  114. package/tests/introspect/pg.test.ts +0 -894
  115. package/tests/introspect/singlestore.test.ts +0 -275
  116. package/tests/introspect/sqlite.test.ts +0 -122
  117. package/tests/libsql-checks.test.ts +0 -308
  118. package/tests/libsql-statements.test.ts +0 -989
  119. package/tests/libsql-views.test.ts +0 -218
  120. package/tests/migrate/libsq-schema.ts +0 -6
  121. package/tests/migrate/libsql-migrate.test.ts +0 -58
  122. package/tests/migrate/migrations/0000_little_blizzard.sql +0 -4
  123. package/tests/migrate/migrations/0001_nebulous_storm.sql +0 -10
  124. package/tests/migrate/migrations/meta/0000_snapshot.json +0 -40
  125. package/tests/migrate/migrations/meta/0001_snapshot.json +0 -40
  126. package/tests/migrate/migrations/meta/_journal.json +0 -20
  127. package/tests/mysql-checks.test.ts +0 -291
  128. package/tests/mysql-generated.test.ts +0 -1290
  129. package/tests/mysql-schemas.test.ts +0 -156
  130. package/tests/mysql-views.test.ts +0 -553
  131. package/tests/mysql.test.ts +0 -863
  132. package/tests/pg-array.test.ts +0 -368
  133. package/tests/pg-checks.test.ts +0 -329
  134. package/tests/pg-columns.test.ts +0 -484
  135. package/tests/pg-domains.test.ts +0 -306
  136. package/tests/pg-enums.test.ts +0 -751
  137. package/tests/pg-generated.test.ts +0 -529
  138. package/tests/pg-identity.test.ts +0 -447
  139. package/tests/pg-schemas.test.ts +0 -105
  140. package/tests/pg-sequences.test.ts +0 -298
  141. package/tests/pg-tables.test.ts +0 -1021
  142. package/tests/pg-views.test.ts +0 -1929
  143. package/tests/push/common.ts +0 -58
  144. package/tests/push/libsql.test.ts +0 -1400
  145. package/tests/push/mysql-push.test.ts +0 -345
  146. package/tests/push/mysql.test.ts +0 -788
  147. package/tests/push/pg.test.ts +0 -4341
  148. package/tests/push/singlestore-push.test.ts +0 -894
  149. package/tests/push/singlestore.test.ts +0 -444
  150. package/tests/push/sqlite.test.ts +0 -1613
  151. package/tests/rls/pg-policy.test.ts +0 -1656
  152. package/tests/rls/pg-role.test.ts +0 -234
  153. package/tests/schemaDiffer.ts +0 -2852
  154. package/tests/singlestore-generated.test.ts +0 -1290
  155. package/tests/singlestore-schemas.test.ts +0 -155
  156. package/tests/singlestore.test.ts +0 -978
  157. package/tests/sqlite-checks.test.ts +0 -308
  158. package/tests/sqlite-columns.test.ts +0 -1049
  159. package/tests/sqlite-generated.test.ts +0 -1726
  160. package/tests/sqlite-tables.test.ts +0 -637
  161. package/tests/sqlite-views.test.ts +0 -218
  162. package/tests/statements-combiner/libsql-statements-combiner.test.ts +0 -1812
  163. package/tests/statements-combiner/singlestore-statements-combiner.test.ts +0 -882
  164. package/tests/statements-combiner/sqlite-statements-combiner.test.ts +0 -1211
  165. package/tests/test/sqlite.test.ts +0 -39
  166. package/tests/testsinglestore.ts +0 -29
  167. package/tests/validations.test.ts +0 -869
  168. package/tests/wrap-param.test.ts +0 -16
  169. package/tsconfig.build.json +0 -4
  170. package/tsconfig.cli-types.json +0 -9
  171. package/tsconfig.json +0 -28
  172. package/vitest.config.ts +0 -34
@@ -1,1526 +0,0 @@
1
- import fs from 'fs';
2
- import {
3
- prepareMySqlDbPushSnapshot,
4
- prepareMySqlMigrationSnapshot,
5
- preparePgDbPushSnapshot,
6
- preparePgMigrationSnapshot,
7
- prepareSingleStoreDbPushSnapshot,
8
- prepareSingleStoreMigrationSnapshot,
9
- prepareSQLiteDbPushSnapshot,
10
- prepareSqliteMigrationSnapshot,
11
- } from '../../migrationPreparator';
12
-
13
- import chalk from 'chalk';
14
- import { render } from 'hanji';
15
- import path, { join } from 'path';
16
- import { SingleStoreSchema, singlestoreSchema, squashSingleStoreScheme } from 'src/serializer/singlestoreSchema';
17
- import { TypeOf } from 'zod';
18
- import type { CommonSchema } from '../../schemaValidator';
19
- import { MySqlSchema, mysqlSchema, squashMysqlScheme, ViewSquashed } from '../../serializer/mysqlSchema';
20
- import { PgSchema, pgSchema, Policy, Role, squashPgScheme, View } from '../../serializer/pgSchema';
21
- import { SQLiteSchema, sqliteSchema, squashSqliteScheme, View as SQLiteView } from '../../serializer/sqliteSchema';
22
- import {
23
- applyLibSQLSnapshotsDiff,
24
- applyMysqlSnapshotsDiff,
25
- applyPgSnapshotsDiff,
26
- applySingleStoreSnapshotsDiff,
27
- applySqliteSnapshotsDiff,
28
- Column,
29
- ColumnsResolverInput,
30
- ColumnsResolverOutput,
31
- Domain,
32
- Enum,
33
- PolicyResolverInput,
34
- PolicyResolverOutput,
35
- ResolverInput,
36
- ResolverOutput,
37
- ResolverOutputWithMoved,
38
- RolesResolverInput,
39
- RolesResolverOutput,
40
- Sequence,
41
- Table,
42
- TablePolicyResolverInput,
43
- TablePolicyResolverOutput,
44
- } from '../../snapshotsDiffer';
45
- import { assertV1OutFolder, Journal, prepareMigrationFolder } from '../../utils';
46
- import { prepareMigrationMetadata } from '../../utils/words';
47
- import { CasingType, Driver, Prefix } from '../validations/common';
48
- import { withStyle } from '../validations/outputs';
49
- import {
50
- isRenamePromptItem,
51
- RenamePropmtItem,
52
- ResolveColumnSelect,
53
- ResolveSchemasSelect,
54
- ResolveSelect,
55
- ResolveSelectNamed,
56
- schema,
57
- } from '../views';
58
- import { ExportConfig, GenerateConfig } from './utils';
59
-
60
- export type Named = {
61
- name: string;
62
- };
63
-
64
- export type NamedWithSchema = {
65
- name: string;
66
- schema: string;
67
- };
68
-
69
- export const schemasResolver = async (
70
- input: ResolverInput<Table>,
71
- ): Promise<ResolverOutput<Table>> => {
72
- try {
73
- const { created, deleted, renamed } = await promptSchemasConflict(
74
- input.created,
75
- input.deleted,
76
- );
77
-
78
- return { created: created, deleted: deleted, renamed: renamed };
79
- } catch (e) {
80
- console.error(e);
81
- throw e;
82
- }
83
- };
84
-
85
- export const tablesResolver = async (
86
- input: ResolverInput<Table>,
87
- ): Promise<ResolverOutputWithMoved<Table>> => {
88
- try {
89
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
90
- input.created,
91
- input.deleted,
92
- 'table',
93
- );
94
-
95
- return {
96
- created: created,
97
- deleted: deleted,
98
- moved: moved,
99
- renamed: renamed,
100
- };
101
- } catch (e) {
102
- console.error(e);
103
- throw e;
104
- }
105
- };
106
-
107
- export const viewsResolver = async (
108
- input: ResolverInput<View>,
109
- ): Promise<ResolverOutputWithMoved<View>> => {
110
- try {
111
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
112
- input.created,
113
- input.deleted,
114
- 'view',
115
- );
116
-
117
- return {
118
- created: created,
119
- deleted: deleted,
120
- moved: moved,
121
- renamed: renamed,
122
- };
123
- } catch (e) {
124
- console.error(e);
125
- throw e;
126
- }
127
- };
128
-
129
- export const mySqlViewsResolver = async (
130
- input: ResolverInput<ViewSquashed & { schema: '' }>,
131
- ): Promise<ResolverOutputWithMoved<ViewSquashed>> => {
132
- try {
133
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
134
- input.created,
135
- input.deleted,
136
- 'view',
137
- );
138
-
139
- return {
140
- created: created,
141
- deleted: deleted,
142
- moved: moved,
143
- renamed: renamed,
144
- };
145
- } catch (e) {
146
- console.error(e);
147
- throw e;
148
- }
149
- };
150
-
151
- /* export const singleStoreViewsResolver = async (
152
- input: ResolverInput<SingleStoreViewSquashed & { schema: '' }>,
153
- ): Promise<ResolverOutputWithMoved<SingleStoreViewSquashed>> => {
154
- try {
155
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
156
- input.created,
157
- input.deleted,
158
- 'view',
159
- );
160
-
161
- return {
162
- created: created,
163
- deleted: deleted,
164
- moved: moved,
165
- renamed: renamed,
166
- };
167
- } catch (e) {
168
- console.error(e);
169
- throw e;
170
- }
171
- }; */
172
-
173
- export const sqliteViewsResolver = async (
174
- input: ResolverInput<SQLiteView & { schema: '' }>,
175
- ): Promise<ResolverOutputWithMoved<SQLiteView>> => {
176
- try {
177
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
178
- input.created,
179
- input.deleted,
180
- 'view',
181
- );
182
-
183
- return {
184
- created: created,
185
- deleted: deleted,
186
- moved: moved,
187
- renamed: renamed,
188
- };
189
- } catch (e) {
190
- console.error(e);
191
- throw e;
192
- }
193
- };
194
-
195
- export const sequencesResolver = async (
196
- input: ResolverInput<Sequence>,
197
- ): Promise<ResolverOutputWithMoved<Sequence>> => {
198
- try {
199
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
200
- input.created,
201
- input.deleted,
202
- 'sequence',
203
- );
204
-
205
- return {
206
- created: created,
207
- deleted: deleted,
208
- moved: moved,
209
- renamed: renamed,
210
- };
211
- } catch (e) {
212
- console.error(e);
213
- throw e;
214
- }
215
- };
216
-
217
- export const roleResolver = async (
218
- input: RolesResolverInput<Role>,
219
- ): Promise<RolesResolverOutput<Role>> => {
220
- const result = await promptNamedConflict(
221
- input.created,
222
- input.deleted,
223
- 'role',
224
- );
225
- return {
226
- created: result.created,
227
- deleted: result.deleted,
228
- renamed: result.renamed,
229
- };
230
- };
231
-
232
- export const policyResolver = async (
233
- input: TablePolicyResolverInput<Policy>,
234
- ): Promise<TablePolicyResolverOutput<Policy>> => {
235
- const result = await promptColumnsConflicts(
236
- input.tableName,
237
- input.created,
238
- input.deleted,
239
- );
240
- return {
241
- tableName: input.tableName,
242
- schema: input.schema,
243
- created: result.created,
244
- deleted: result.deleted,
245
- renamed: result.renamed,
246
- };
247
- };
248
-
249
- export const indPolicyResolver = async (
250
- input: PolicyResolverInput<Policy>,
251
- ): Promise<PolicyResolverOutput<Policy>> => {
252
- const result = await promptNamedConflict(
253
- input.created,
254
- input.deleted,
255
- 'policy',
256
- );
257
- return {
258
- created: result.created,
259
- deleted: result.deleted,
260
- renamed: result.renamed,
261
- };
262
- };
263
-
264
- export const domainsResolver = async (
265
- input: ResolverInput<Domain>,
266
- ): Promise<ResolverOutputWithMoved<Domain>> => {
267
- try {
268
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
269
- input.created,
270
- input.deleted,
271
- 'domain',
272
- );
273
-
274
- return {
275
- created: created,
276
- deleted: deleted,
277
- moved: moved,
278
- renamed: renamed,
279
- };
280
- } catch (e) {
281
- console.error(e);
282
- throw e;
283
- }
284
- };
285
-
286
- export const enumsResolver = async (
287
- input: ResolverInput<Enum>,
288
- ): Promise<ResolverOutputWithMoved<Enum>> => {
289
- try {
290
- const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
291
- input.created,
292
- input.deleted,
293
- 'enum',
294
- );
295
-
296
- return {
297
- created: created,
298
- deleted: deleted,
299
- moved: moved,
300
- renamed: renamed,
301
- };
302
- } catch (e) {
303
- console.error(e);
304
- throw e;
305
- }
306
- };
307
-
308
- export const columnsResolver = async (
309
- input: ColumnsResolverInput<Column>,
310
- ): Promise<ColumnsResolverOutput<Column>> => {
311
- const result = await promptColumnsConflicts(
312
- input.tableName,
313
- input.created,
314
- input.deleted,
315
- );
316
- return {
317
- tableName: input.tableName,
318
- schema: input.schema,
319
- created: result.created,
320
- deleted: result.deleted,
321
- renamed: result.renamed,
322
- };
323
- };
324
-
325
- export const prepareAndMigratePg = async (config: GenerateConfig) => {
326
- const outFolder = config.out;
327
- const schemaPath = config.schema;
328
- const casing = config.casing;
329
-
330
- try {
331
- assertV1OutFolder(outFolder);
332
-
333
- const { snapshots, journal } = prepareMigrationFolder(
334
- outFolder,
335
- 'postgresql',
336
- );
337
-
338
- const { prev, cur, custom } = await preparePgMigrationSnapshot(
339
- snapshots,
340
- schemaPath,
341
- casing,
342
- );
343
-
344
- const validatedPrev = pgSchema.parse(prev);
345
- const validatedCur = pgSchema.parse(cur);
346
-
347
- if (config.custom) {
348
- writeResult({
349
- cur: custom,
350
- sqlStatements: [],
351
- journal,
352
- outFolder,
353
- name: config.name,
354
- breakpoints: config.breakpoints,
355
- type: 'custom',
356
- prefixMode: config.prefix,
357
- });
358
- return;
359
- }
360
-
361
- const squashedPrev = squashPgScheme(validatedPrev);
362
- const squashedCur = squashPgScheme(validatedCur);
363
-
364
- const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
365
- squashedPrev,
366
- squashedCur,
367
- schemasResolver,
368
- domainsResolver,
369
- enumsResolver,
370
- sequencesResolver,
371
- policyResolver,
372
- indPolicyResolver,
373
- roleResolver,
374
- tablesResolver,
375
- columnsResolver,
376
- viewsResolver,
377
- validatedPrev,
378
- validatedCur,
379
- );
380
-
381
- writeResult({
382
- cur,
383
- sqlStatements,
384
- journal,
385
- outFolder,
386
- name: config.name,
387
- breakpoints: config.breakpoints,
388
- prefixMode: config.prefix,
389
- });
390
- } catch (e) {
391
- console.error(e);
392
- }
393
- };
394
-
395
- export const prepareAndExportPg = async (config: ExportConfig) => {
396
- const schemaPath = config.schema;
397
-
398
- try {
399
- const { prev, cur } = await preparePgMigrationSnapshot(
400
- [], // no snapshots before
401
- schemaPath,
402
- undefined,
403
- );
404
-
405
- const validatedPrev = pgSchema.parse(prev);
406
- const validatedCur = pgSchema.parse(cur);
407
-
408
- const squashedPrev = squashPgScheme(validatedPrev);
409
- const squashedCur = squashPgScheme(validatedCur);
410
-
411
- const { sqlStatements } = await applyPgSnapshotsDiff(
412
- squashedPrev,
413
- squashedCur,
414
- schemasResolver,
415
- domainsResolver,
416
- enumsResolver,
417
- sequencesResolver,
418
- policyResolver,
419
- indPolicyResolver,
420
- roleResolver,
421
- tablesResolver,
422
- columnsResolver,
423
- viewsResolver,
424
- validatedPrev,
425
- validatedCur,
426
- );
427
-
428
- console.log(sqlStatements.join('\n'));
429
- } catch (e) {
430
- console.error(e);
431
- }
432
- };
433
-
434
- export const preparePgPush = async (
435
- cur: PgSchema,
436
- prev: PgSchema,
437
- ) => {
438
- const validatedPrev = pgSchema.parse(prev);
439
- const validatedCur = pgSchema.parse(cur);
440
-
441
- const squashedPrev = squashPgScheme(validatedPrev, 'push');
442
- const squashedCur = squashPgScheme(validatedCur, 'push');
443
-
444
- const { sqlStatements, statements, _meta } = await applyPgSnapshotsDiff(
445
- squashedPrev,
446
- squashedCur,
447
- schemasResolver,
448
- domainsResolver,
449
- enumsResolver,
450
- sequencesResolver,
451
- policyResolver,
452
- indPolicyResolver,
453
- roleResolver,
454
- tablesResolver,
455
- columnsResolver,
456
- viewsResolver,
457
- validatedPrev,
458
- validatedCur,
459
- 'push',
460
- );
461
-
462
- return { sqlStatements, statements, squashedPrev, squashedCur };
463
- };
464
-
465
- // Not needed for now
466
- function mysqlSchemaSuggestions(
467
- curSchema: TypeOf<typeof mysqlSchema>,
468
- prevSchema: TypeOf<typeof mysqlSchema>,
469
- ) {
470
- const suggestions: string[] = [];
471
- const usedSuggestions: string[] = [];
472
- const suggestionTypes = {
473
- serial: withStyle.errorWarning(
474
- `We deprecated the use of 'serial' for MySQL starting from version 0.20.0. In MySQL, 'serial' is simply an alias for 'bigint unsigned not null auto_increment unique,' which creates all constraints and indexes for you. This may make the process less explicit for both users and drizzle-kit push commands`,
475
- ),
476
- };
477
-
478
- for (const table of Object.values(curSchema.tables)) {
479
- for (const column of Object.values(table.columns)) {
480
- if (column.type === 'serial') {
481
- if (!usedSuggestions.includes('serial')) {
482
- suggestions.push(suggestionTypes['serial']);
483
- }
484
-
485
- const uniqueForSerial = Object.values(
486
- prevSchema.tables[table.name].uniqueConstraints,
487
- ).find((it) => it.columns[0] === column.name);
488
-
489
- suggestions.push(
490
- `\n`
491
- + withStyle.suggestion(
492
- `We are suggesting to change ${
493
- chalk.blue(
494
- column.name,
495
- )
496
- } column in ${
497
- chalk.blueBright(
498
- table.name,
499
- )
500
- } table from serial to bigint unsigned\n\n${
501
- chalk.blueBright(
502
- `bigint("${column.name}", { mode: "number", unsigned: true }).notNull().autoincrement().unique(${
503
- uniqueForSerial?.name ? `"${uniqueForSerial?.name}"` : ''
504
- })`,
505
- )
506
- }`,
507
- ),
508
- );
509
- }
510
- }
511
- }
512
-
513
- return suggestions;
514
- }
515
-
516
- // Intersect with prepareAnMigrate
517
- export const prepareMySQLPush = async (
518
- schemaPath: string | string[],
519
- snapshot: MySqlSchema,
520
- casing: CasingType | undefined,
521
- ) => {
522
- try {
523
- const { prev, cur } = await prepareMySqlDbPushSnapshot(
524
- snapshot,
525
- schemaPath,
526
- casing,
527
- );
528
-
529
- const validatedPrev = mysqlSchema.parse(prev);
530
- const validatedCur = mysqlSchema.parse(cur);
531
-
532
- const squashedPrev = squashMysqlScheme(validatedPrev);
533
- const squashedCur = squashMysqlScheme(validatedCur);
534
-
535
- const { sqlStatements, statements } = await applyMysqlSnapshotsDiff(
536
- squashedPrev,
537
- squashedCur,
538
- tablesResolver,
539
- columnsResolver,
540
- mySqlViewsResolver,
541
- validatedPrev,
542
- validatedCur,
543
- 'push',
544
- );
545
-
546
- return { sqlStatements, statements, validatedCur, validatedPrev };
547
- } catch (e) {
548
- console.error(e);
549
- process.exit(1);
550
- }
551
- };
552
-
553
- export const prepareAndMigrateMysql = async (config: GenerateConfig) => {
554
- const outFolder = config.out;
555
- const schemaPath = config.schema;
556
- const casing = config.casing;
557
-
558
- try {
559
- // TODO: remove
560
- assertV1OutFolder(outFolder);
561
-
562
- const { snapshots, journal } = prepareMigrationFolder(outFolder, 'mysql');
563
- const { prev, cur, custom } = await prepareMySqlMigrationSnapshot(
564
- snapshots,
565
- schemaPath,
566
- casing,
567
- );
568
-
569
- const validatedPrev = mysqlSchema.parse(prev);
570
- const validatedCur = mysqlSchema.parse(cur);
571
-
572
- if (config.custom) {
573
- writeResult({
574
- cur: custom,
575
- sqlStatements: [],
576
- journal,
577
- outFolder,
578
- name: config.name,
579
- breakpoints: config.breakpoints,
580
- type: 'custom',
581
- prefixMode: config.prefix,
582
- });
583
- return;
584
- }
585
-
586
- const squashedPrev = squashMysqlScheme(validatedPrev);
587
- const squashedCur = squashMysqlScheme(validatedCur);
588
-
589
- const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
590
- squashedPrev,
591
- squashedCur,
592
- tablesResolver,
593
- columnsResolver,
594
- mySqlViewsResolver,
595
- validatedPrev,
596
- validatedCur,
597
- );
598
-
599
- writeResult({
600
- cur,
601
- sqlStatements,
602
- journal,
603
- _meta,
604
- outFolder,
605
- name: config.name,
606
- breakpoints: config.breakpoints,
607
- prefixMode: config.prefix,
608
- });
609
- } catch (e) {
610
- console.error(e);
611
- }
612
- };
613
-
614
- // Not needed for now
615
- function singleStoreSchemaSuggestions(
616
- curSchema: TypeOf<typeof singlestoreSchema>,
617
- prevSchema: TypeOf<typeof singlestoreSchema>,
618
- ) {
619
- const suggestions: string[] = [];
620
- const usedSuggestions: string[] = [];
621
- const suggestionTypes = {
622
- // TODO: Check if SingleStore has serial type
623
- serial: withStyle.errorWarning(
624
- `We deprecated the use of 'serial' for SingleStore starting from version 0.20.0. In SingleStore, 'serial' is simply an alias for 'bigint unsigned not null auto_increment unique,' which creates all constraints and indexes for you. This may make the process less explicit for both users and drizzle-kit push commands`,
625
- ),
626
- };
627
-
628
- for (const table of Object.values(curSchema.tables)) {
629
- for (const column of Object.values(table.columns)) {
630
- if (column.type === 'serial') {
631
- if (!usedSuggestions.includes('serial')) {
632
- suggestions.push(suggestionTypes['serial']);
633
- }
634
-
635
- const uniqueForSerial = Object.values(
636
- prevSchema.tables[table.name].uniqueConstraints,
637
- ).find((it) => it.columns[0] === column.name);
638
-
639
- suggestions.push(
640
- `\n`
641
- + withStyle.suggestion(
642
- `We are suggesting to change ${
643
- chalk.blue(
644
- column.name,
645
- )
646
- } column in ${
647
- chalk.blueBright(
648
- table.name,
649
- )
650
- } table from serial to bigint unsigned\n\n${
651
- chalk.blueBright(
652
- `bigint("${column.name}", { mode: "number", unsigned: true }).notNull().autoincrement().unique(${
653
- uniqueForSerial?.name ? `"${uniqueForSerial?.name}"` : ''
654
- })`,
655
- )
656
- }`,
657
- ),
658
- );
659
- }
660
- }
661
- }
662
-
663
- return suggestions;
664
- }
665
-
666
- // Intersect with prepareAnMigrate
667
- export const prepareSingleStorePush = async (
668
- schemaPath: string | string[],
669
- snapshot: SingleStoreSchema,
670
- casing: CasingType | undefined,
671
- ) => {
672
- try {
673
- const { prev, cur } = await prepareSingleStoreDbPushSnapshot(
674
- snapshot,
675
- schemaPath,
676
- casing,
677
- );
678
-
679
- const validatedPrev = singlestoreSchema.parse(prev);
680
- const validatedCur = singlestoreSchema.parse(cur);
681
-
682
- const squashedPrev = squashSingleStoreScheme(validatedPrev);
683
- const squashedCur = squashSingleStoreScheme(validatedCur);
684
-
685
- const { sqlStatements, statements } = await applySingleStoreSnapshotsDiff(
686
- squashedPrev,
687
- squashedCur,
688
- tablesResolver,
689
- columnsResolver,
690
- /* singleStoreViewsResolver, */
691
- validatedPrev,
692
- validatedCur,
693
- 'push',
694
- );
695
-
696
- return { sqlStatements, statements, validatedCur, validatedPrev };
697
- } catch (e) {
698
- console.error(e);
699
- process.exit(1);
700
- }
701
- };
702
-
703
- export const prepareAndMigrateSingleStore = async (config: GenerateConfig) => {
704
- const outFolder = config.out;
705
- const schemaPath = config.schema;
706
- const casing = config.casing;
707
-
708
- try {
709
- // TODO: remove
710
- assertV1OutFolder(outFolder);
711
-
712
- const { snapshots, journal } = prepareMigrationFolder(outFolder, 'singlestore');
713
- const { prev, cur, custom } = await prepareSingleStoreMigrationSnapshot(
714
- snapshots,
715
- schemaPath,
716
- casing,
717
- );
718
-
719
- const validatedPrev = singlestoreSchema.parse(prev);
720
- const validatedCur = singlestoreSchema.parse(cur);
721
-
722
- if (config.custom) {
723
- writeResult({
724
- cur: custom,
725
- sqlStatements: [],
726
- journal,
727
- outFolder,
728
- name: config.name,
729
- breakpoints: config.breakpoints,
730
- type: 'custom',
731
- prefixMode: config.prefix,
732
- });
733
- return;
734
- }
735
-
736
- const squashedPrev = squashSingleStoreScheme(validatedPrev);
737
- const squashedCur = squashSingleStoreScheme(validatedCur);
738
-
739
- const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
740
- squashedPrev,
741
- squashedCur,
742
- tablesResolver,
743
- columnsResolver,
744
- /* singleStoreViewsResolver, */
745
- validatedPrev,
746
- validatedCur,
747
- );
748
-
749
- writeResult({
750
- cur,
751
- sqlStatements,
752
- journal,
753
- _meta,
754
- outFolder,
755
- name: config.name,
756
- breakpoints: config.breakpoints,
757
- prefixMode: config.prefix,
758
- });
759
- } catch (e) {
760
- console.error(e);
761
- }
762
- };
763
-
764
- export const prepareAndExportSinglestore = async (config: ExportConfig) => {
765
- const schemaPath = config.schema;
766
-
767
- try {
768
- const { prev, cur } = await prepareSingleStoreMigrationSnapshot(
769
- [],
770
- schemaPath,
771
- undefined,
772
- );
773
-
774
- const validatedPrev = singlestoreSchema.parse(prev);
775
- const validatedCur = singlestoreSchema.parse(cur);
776
-
777
- const squashedPrev = squashSingleStoreScheme(validatedPrev);
778
- const squashedCur = squashSingleStoreScheme(validatedCur);
779
-
780
- const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
781
- squashedPrev,
782
- squashedCur,
783
- tablesResolver,
784
- columnsResolver,
785
- /* singleStoreViewsResolver, */
786
- validatedPrev,
787
- validatedCur,
788
- );
789
-
790
- console.log(sqlStatements.join('\n'));
791
- } catch (e) {
792
- console.error(e);
793
- }
794
- };
795
-
796
- export const prepareAndExportMysql = async (config: ExportConfig) => {
797
- const schemaPath = config.schema;
798
-
799
- try {
800
- const { prev, cur, custom } = await prepareMySqlMigrationSnapshot(
801
- [],
802
- schemaPath,
803
- undefined,
804
- );
805
-
806
- const validatedPrev = mysqlSchema.parse(prev);
807
- const validatedCur = mysqlSchema.parse(cur);
808
-
809
- const squashedPrev = squashMysqlScheme(validatedPrev);
810
- const squashedCur = squashMysqlScheme(validatedCur);
811
-
812
- const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
813
- squashedPrev,
814
- squashedCur,
815
- tablesResolver,
816
- columnsResolver,
817
- mySqlViewsResolver,
818
- validatedPrev,
819
- validatedCur,
820
- );
821
-
822
- console.log(sqlStatements.join('\n'));
823
- } catch (e) {
824
- console.error(e);
825
- }
826
- };
827
-
828
- export const prepareAndMigrateSqlite = async (config: GenerateConfig) => {
829
- const outFolder = config.out;
830
- const schemaPath = config.schema;
831
- const casing = config.casing;
832
-
833
- try {
834
- assertV1OutFolder(outFolder);
835
-
836
- const { snapshots, journal } = prepareMigrationFolder(outFolder, 'sqlite');
837
- const { prev, cur, custom } = await prepareSqliteMigrationSnapshot(
838
- snapshots,
839
- schemaPath,
840
- casing,
841
- );
842
-
843
- const validatedPrev = sqliteSchema.parse(prev);
844
- const validatedCur = sqliteSchema.parse(cur);
845
-
846
- if (config.custom) {
847
- writeResult({
848
- cur: custom,
849
- sqlStatements: [],
850
- journal,
851
- outFolder,
852
- name: config.name,
853
- breakpoints: config.breakpoints,
854
- bundle: config.bundle,
855
- type: 'custom',
856
- prefixMode: config.prefix,
857
- });
858
- return;
859
- }
860
-
861
- const squashedPrev = squashSqliteScheme(validatedPrev);
862
- const squashedCur = squashSqliteScheme(validatedCur);
863
-
864
- const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
865
- squashedPrev,
866
- squashedCur,
867
- tablesResolver,
868
- columnsResolver,
869
- sqliteViewsResolver,
870
- validatedPrev,
871
- validatedCur,
872
- );
873
-
874
- writeResult({
875
- cur,
876
- sqlStatements,
877
- journal,
878
- _meta,
879
- outFolder,
880
- name: config.name,
881
- breakpoints: config.breakpoints,
882
- bundle: config.bundle,
883
- prefixMode: config.prefix,
884
- driver: config.driver,
885
- });
886
- } catch (e) {
887
- console.error(e);
888
- }
889
- };
890
-
891
- export const prepareAndExportSqlite = async (config: ExportConfig) => {
892
- const schemaPath = config.schema;
893
-
894
- try {
895
- const { prev, cur } = await prepareSqliteMigrationSnapshot(
896
- [],
897
- schemaPath,
898
- undefined,
899
- );
900
-
901
- const validatedPrev = sqliteSchema.parse(prev);
902
- const validatedCur = sqliteSchema.parse(cur);
903
-
904
- const squashedPrev = squashSqliteScheme(validatedPrev);
905
- const squashedCur = squashSqliteScheme(validatedCur);
906
-
907
- const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
908
- squashedPrev,
909
- squashedCur,
910
- tablesResolver,
911
- columnsResolver,
912
- sqliteViewsResolver,
913
- validatedPrev,
914
- validatedCur,
915
- );
916
-
917
- console.log(sqlStatements.join('\n'));
918
- } catch (e) {
919
- console.error(e);
920
- }
921
- };
922
-
923
- export const prepareAndMigrateLibSQL = async (config: GenerateConfig) => {
924
- const outFolder = config.out;
925
- const schemaPath = config.schema;
926
- const casing = config.casing;
927
-
928
- try {
929
- assertV1OutFolder(outFolder);
930
-
931
- const { snapshots, journal } = prepareMigrationFolder(outFolder, 'sqlite');
932
- const { prev, cur, custom } = await prepareSqliteMigrationSnapshot(
933
- snapshots,
934
- schemaPath,
935
- casing,
936
- );
937
-
938
- const validatedPrev = sqliteSchema.parse(prev);
939
- const validatedCur = sqliteSchema.parse(cur);
940
-
941
- if (config.custom) {
942
- writeResult({
943
- cur: custom,
944
- sqlStatements: [],
945
- journal,
946
- outFolder,
947
- name: config.name,
948
- breakpoints: config.breakpoints,
949
- bundle: config.bundle,
950
- type: 'custom',
951
- prefixMode: config.prefix,
952
- });
953
- return;
954
- }
955
-
956
- const squashedPrev = squashSqliteScheme(validatedPrev);
957
- const squashedCur = squashSqliteScheme(validatedCur);
958
-
959
- const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
960
- squashedPrev,
961
- squashedCur,
962
- tablesResolver,
963
- columnsResolver,
964
- sqliteViewsResolver,
965
- validatedPrev,
966
- validatedCur,
967
- );
968
-
969
- writeResult({
970
- cur,
971
- sqlStatements,
972
- journal,
973
- _meta,
974
- outFolder,
975
- name: config.name,
976
- breakpoints: config.breakpoints,
977
- bundle: config.bundle,
978
- prefixMode: config.prefix,
979
- });
980
- } catch (e) {
981
- console.error(e);
982
- }
983
- };
984
-
985
- export const prepareAndExportLibSQL = async (config: ExportConfig) => {
986
- const schemaPath = config.schema;
987
-
988
- try {
989
- const { prev, cur, custom } = await prepareSqliteMigrationSnapshot(
990
- [],
991
- schemaPath,
992
- undefined,
993
- );
994
-
995
- const validatedPrev = sqliteSchema.parse(prev);
996
- const validatedCur = sqliteSchema.parse(cur);
997
-
998
- const squashedPrev = squashSqliteScheme(validatedPrev);
999
- const squashedCur = squashSqliteScheme(validatedCur);
1000
-
1001
- const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
1002
- squashedPrev,
1003
- squashedCur,
1004
- tablesResolver,
1005
- columnsResolver,
1006
- sqliteViewsResolver,
1007
- validatedPrev,
1008
- validatedCur,
1009
- );
1010
-
1011
- console.log(sqlStatements.join('\n'));
1012
- } catch (e) {
1013
- console.error(e);
1014
- }
1015
- };
1016
-
1017
- export const prepareSQLitePush = async (
1018
- schemaPath: string | string[],
1019
- snapshot: SQLiteSchema,
1020
- casing: CasingType | undefined,
1021
- ) => {
1022
- const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing);
1023
-
1024
- const validatedPrev = sqliteSchema.parse(prev);
1025
- const validatedCur = sqliteSchema.parse(cur);
1026
-
1027
- const squashedPrev = squashSqliteScheme(validatedPrev, 'push');
1028
- const squashedCur = squashSqliteScheme(validatedCur, 'push');
1029
-
1030
- const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
1031
- squashedPrev,
1032
- squashedCur,
1033
- tablesResolver,
1034
- columnsResolver,
1035
- sqliteViewsResolver,
1036
- validatedPrev,
1037
- validatedCur,
1038
- 'push',
1039
- );
1040
-
1041
- return {
1042
- sqlStatements,
1043
- statements,
1044
- squashedPrev,
1045
- squashedCur,
1046
- meta: _meta,
1047
- };
1048
- };
1049
-
1050
- export const prepareLibSQLPush = async (
1051
- schemaPath: string | string[],
1052
- snapshot: SQLiteSchema,
1053
- casing: CasingType | undefined,
1054
- ) => {
1055
- const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing);
1056
-
1057
- const validatedPrev = sqliteSchema.parse(prev);
1058
- const validatedCur = sqliteSchema.parse(cur);
1059
-
1060
- const squashedPrev = squashSqliteScheme(validatedPrev, 'push');
1061
- const squashedCur = squashSqliteScheme(validatedCur, 'push');
1062
-
1063
- const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
1064
- squashedPrev,
1065
- squashedCur,
1066
- tablesResolver,
1067
- columnsResolver,
1068
- sqliteViewsResolver,
1069
- validatedPrev,
1070
- validatedCur,
1071
- 'push',
1072
- );
1073
-
1074
- return {
1075
- sqlStatements,
1076
- statements,
1077
- squashedPrev,
1078
- squashedCur,
1079
- meta: _meta,
1080
- };
1081
- };
1082
-
1083
- const freeeeeeze = (obj: any) => {
1084
- Object.freeze(obj);
1085
- for (let key in obj) {
1086
- if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') {
1087
- freeeeeeze(obj[key]);
1088
- }
1089
- }
1090
- };
1091
-
1092
- export const promptColumnsConflicts = async <T extends Named>(
1093
- tableName: string,
1094
- newColumns: T[],
1095
- missingColumns: T[],
1096
- ) => {
1097
- if (newColumns.length === 0 || missingColumns.length === 0) {
1098
- return { created: newColumns, renamed: [], deleted: missingColumns };
1099
- }
1100
- const result: { created: T[]; renamed: { from: T; to: T }[]; deleted: T[] } = {
1101
- created: [],
1102
- renamed: [],
1103
- deleted: [],
1104
- };
1105
-
1106
- let index = 0;
1107
- let leftMissing = [...missingColumns];
1108
-
1109
- do {
1110
- const created = newColumns[index];
1111
-
1112
- const renames: RenamePropmtItem<T>[] = leftMissing.map((it) => {
1113
- return { from: it, to: created };
1114
- });
1115
-
1116
- const promptData: (RenamePropmtItem<T> | T)[] = [created, ...renames];
1117
-
1118
- const { status, data } = await render(
1119
- new ResolveColumnSelect<T>(tableName, created, promptData),
1120
- );
1121
- if (status === 'aborted') {
1122
- console.error('ERROR');
1123
- process.exit(1);
1124
- }
1125
-
1126
- if (isRenamePromptItem(data)) {
1127
- console.log(
1128
- `${chalk.yellow('~')} ${data.from.name} › ${data.to.name} ${
1129
- chalk.gray(
1130
- 'column will be renamed',
1131
- )
1132
- }`,
1133
- );
1134
- result.renamed.push(data);
1135
- // this will make [item1, undefined, item2]
1136
- delete leftMissing[leftMissing.indexOf(data.from)];
1137
- // this will make [item1, item2]
1138
- leftMissing = leftMissing.filter(Boolean);
1139
- } else {
1140
- console.log(
1141
- `${chalk.green('+')} ${data.name} ${
1142
- chalk.gray(
1143
- 'column will be created',
1144
- )
1145
- }`,
1146
- );
1147
- result.created.push(created);
1148
- }
1149
- index += 1;
1150
- } while (index < newColumns.length);
1151
- console.log(
1152
- chalk.gray(`--- all columns conflicts in ${tableName} table resolved ---\n`),
1153
- );
1154
-
1155
- result.deleted.push(...leftMissing);
1156
- return result;
1157
- };
1158
-
1159
- export const promptNamedConflict = async <T extends Named>(
1160
- newItems: T[],
1161
- missingItems: T[],
1162
- entity: 'role' | 'policy',
1163
- ): Promise<{
1164
- created: T[];
1165
- renamed: { from: T; to: T }[];
1166
- deleted: T[];
1167
- }> => {
1168
- if (missingItems.length === 0 || newItems.length === 0) {
1169
- return {
1170
- created: newItems,
1171
- renamed: [],
1172
- deleted: missingItems,
1173
- };
1174
- }
1175
-
1176
- const result: {
1177
- created: T[];
1178
- renamed: { from: T; to: T }[];
1179
- deleted: T[];
1180
- } = { created: [], renamed: [], deleted: [] };
1181
- let index = 0;
1182
- let leftMissing = [...missingItems];
1183
- do {
1184
- const created = newItems[index];
1185
- const renames: RenamePropmtItem<T>[] = leftMissing.map((it) => {
1186
- return { from: it, to: created };
1187
- });
1188
-
1189
- const promptData: (RenamePropmtItem<T> | T)[] = [created, ...renames];
1190
-
1191
- const { status, data } = await render(
1192
- new ResolveSelectNamed<T>(created, promptData, entity),
1193
- );
1194
- if (status === 'aborted') {
1195
- console.error('ERROR');
1196
- process.exit(1);
1197
- }
1198
-
1199
- if (isRenamePromptItem(data)) {
1200
- console.log(
1201
- `${chalk.yellow('~')} ${data.from.name} › ${data.to.name} ${
1202
- chalk.gray(
1203
- `${entity} will be renamed/moved`,
1204
- )
1205
- }`,
1206
- );
1207
-
1208
- if (data.from.name !== data.to.name) {
1209
- result.renamed.push(data);
1210
- }
1211
-
1212
- delete leftMissing[leftMissing.indexOf(data.from)];
1213
- leftMissing = leftMissing.filter(Boolean);
1214
- } else {
1215
- console.log(
1216
- `${chalk.green('+')} ${data.name} ${
1217
- chalk.gray(
1218
- `${entity} will be created`,
1219
- )
1220
- }`,
1221
- );
1222
- result.created.push(created);
1223
- }
1224
- index += 1;
1225
- } while (index < newItems.length);
1226
- console.log(chalk.gray(`--- all ${entity} conflicts resolved ---\n`));
1227
- result.deleted.push(...leftMissing);
1228
- return result;
1229
- };
1230
-
1231
- export const promptNamedWithSchemasConflict = async <T extends NamedWithSchema>(
1232
- newItems: T[],
1233
- missingItems: T[],
1234
- entity: 'table' | 'domain' | 'enum' | 'sequence' | 'view',
1235
- ): Promise<{
1236
- created: T[];
1237
- renamed: { from: T; to: T }[];
1238
- moved: { name: string; schemaFrom: string; schemaTo: string }[];
1239
- deleted: T[];
1240
- }> => {
1241
- if (missingItems.length === 0 || newItems.length === 0) {
1242
- return {
1243
- created: newItems,
1244
- renamed: [],
1245
- moved: [],
1246
- deleted: missingItems,
1247
- };
1248
- }
1249
-
1250
- const result: {
1251
- created: T[];
1252
- renamed: { from: T; to: T }[];
1253
- moved: { name: string; schemaFrom: string; schemaTo: string }[];
1254
- deleted: T[];
1255
- } = { created: [], renamed: [], moved: [], deleted: [] };
1256
- let index = 0;
1257
- let leftMissing = [...missingItems];
1258
- do {
1259
- const created = newItems[index];
1260
- const renames: RenamePropmtItem<T>[] = leftMissing.map((it) => {
1261
- return { from: it, to: created };
1262
- });
1263
-
1264
- const promptData: (RenamePropmtItem<T> | T)[] = [created, ...renames];
1265
-
1266
- const { status, data } = await render(
1267
- new ResolveSelect<T>(created, promptData, entity),
1268
- );
1269
- if (status === 'aborted') {
1270
- console.error('ERROR');
1271
- process.exit(1);
1272
- }
1273
-
1274
- if (isRenamePromptItem(data)) {
1275
- const schemaFromPrefix = !data.from.schema || data.from.schema === 'public'
1276
- ? ''
1277
- : `${data.from.schema}.`;
1278
- const schemaToPrefix = !data.to.schema || data.to.schema === 'public'
1279
- ? ''
1280
- : `${data.to.schema}.`;
1281
-
1282
- console.log(
1283
- `${chalk.yellow('~')} ${schemaFromPrefix}${data.from.name} › ${schemaToPrefix}${data.to.name} ${
1284
- chalk.gray(
1285
- `${entity} will be renamed/moved`,
1286
- )
1287
- }`,
1288
- );
1289
-
1290
- if (data.from.name !== data.to.name) {
1291
- result.renamed.push(data);
1292
- }
1293
-
1294
- if (data.from.schema !== data.to.schema) {
1295
- result.moved.push({
1296
- name: data.from.name,
1297
- schemaFrom: data.from.schema || 'public',
1298
- schemaTo: data.to.schema || 'public',
1299
- });
1300
- }
1301
-
1302
- delete leftMissing[leftMissing.indexOf(data.from)];
1303
- leftMissing = leftMissing.filter(Boolean);
1304
- } else {
1305
- console.log(
1306
- `${chalk.green('+')} ${data.name} ${
1307
- chalk.gray(
1308
- `${entity} will be created`,
1309
- )
1310
- }`,
1311
- );
1312
- result.created.push(created);
1313
- }
1314
- index += 1;
1315
- } while (index < newItems.length);
1316
- console.log(chalk.gray(`--- all ${entity} conflicts resolved ---\n`));
1317
- result.deleted.push(...leftMissing);
1318
- return result;
1319
- };
1320
-
1321
- export const promptSchemasConflict = async <T extends Named>(
1322
- newSchemas: T[],
1323
- missingSchemas: T[],
1324
- ): Promise<{ created: T[]; renamed: { from: T; to: T }[]; deleted: T[] }> => {
1325
- if (missingSchemas.length === 0 || newSchemas.length === 0) {
1326
- return { created: newSchemas, renamed: [], deleted: missingSchemas };
1327
- }
1328
-
1329
- const result: { created: T[]; renamed: { from: T; to: T }[]; deleted: T[] } = {
1330
- created: [],
1331
- renamed: [],
1332
- deleted: [],
1333
- };
1334
- let index = 0;
1335
- let leftMissing = [...missingSchemas];
1336
- do {
1337
- const created = newSchemas[index];
1338
- const renames: RenamePropmtItem<T>[] = leftMissing.map((it) => {
1339
- return { from: it, to: created };
1340
- });
1341
-
1342
- const promptData: (RenamePropmtItem<T> | T)[] = [created, ...renames];
1343
-
1344
- const { status, data } = await render(
1345
- new ResolveSchemasSelect<T>(created, promptData),
1346
- );
1347
- if (status === 'aborted') {
1348
- console.error('ERROR');
1349
- process.exit(1);
1350
- }
1351
-
1352
- if (isRenamePromptItem(data)) {
1353
- console.log(
1354
- `${chalk.yellow('~')} ${data.from.name} › ${data.to.name} ${
1355
- chalk.gray(
1356
- 'schema will be renamed',
1357
- )
1358
- }`,
1359
- );
1360
- result.renamed.push(data);
1361
- delete leftMissing[leftMissing.indexOf(data.from)];
1362
- leftMissing = leftMissing.filter(Boolean);
1363
- } else {
1364
- console.log(
1365
- `${chalk.green('+')} ${data.name} ${
1366
- chalk.gray(
1367
- 'schema will be created',
1368
- )
1369
- }`,
1370
- );
1371
- result.created.push(created);
1372
- }
1373
- index += 1;
1374
- } while (index < newSchemas.length);
1375
- console.log(chalk.gray('--- all schemas conflicts resolved ---\n'));
1376
- result.deleted.push(...leftMissing);
1377
- return result;
1378
- };
1379
-
1380
- export const BREAKPOINT = '--> statement-breakpoint\n';
1381
-
1382
- export const writeResult = ({
1383
- cur,
1384
- sqlStatements,
1385
- journal,
1386
- _meta = {
1387
- columns: {},
1388
- schemas: {},
1389
- tables: {},
1390
- },
1391
- outFolder,
1392
- breakpoints,
1393
- name,
1394
- bundle = false,
1395
- type = 'none',
1396
- prefixMode,
1397
- driver,
1398
- }: {
1399
- cur: CommonSchema;
1400
- sqlStatements: string[];
1401
- journal: Journal;
1402
- _meta?: any;
1403
- outFolder: string;
1404
- breakpoints: boolean;
1405
- prefixMode: Prefix;
1406
- name?: string;
1407
- bundle?: boolean;
1408
- type?: 'introspect' | 'custom' | 'none';
1409
- driver?: Driver;
1410
- }) => {
1411
- if (type === 'none') {
1412
- console.log(schema(cur));
1413
-
1414
- if (sqlStatements.length === 0) {
1415
- console.log('No schema changes, nothing to migrate 😴');
1416
- return;
1417
- }
1418
- }
1419
-
1420
- // append entry to _migrations.json
1421
- // append entry to _journal.json->entries
1422
- // dialect in _journal.json
1423
- // append sql file to out folder
1424
- // append snapshot file to meta folder
1425
- const lastEntryInJournal = journal.entries[journal.entries.length - 1];
1426
- const idx = typeof lastEntryInJournal === 'undefined' ? 0 : lastEntryInJournal.idx + 1;
1427
-
1428
- const { prefix, tag } = prepareMigrationMetadata(idx, prefixMode, name);
1429
-
1430
- const toSave = JSON.parse(JSON.stringify(cur));
1431
- toSave['_meta'] = _meta;
1432
-
1433
- // todo: save results to a new migration folder
1434
- const metaFolderPath = join(outFolder, 'meta');
1435
- const metaJournal = join(metaFolderPath, '_journal.json');
1436
-
1437
- fs.writeFileSync(
1438
- join(metaFolderPath, `${prefix}_snapshot.json`),
1439
- JSON.stringify(toSave, null, 2),
1440
- );
1441
-
1442
- const sqlDelimiter = breakpoints ? BREAKPOINT : '\n';
1443
- let sql = sqlStatements.join(sqlDelimiter);
1444
-
1445
- if (type === 'introspect') {
1446
- sql =
1447
- `-- Current sql file was generated after introspecting the database\n-- If you want to run this migration please uncomment this code before executing migrations\n/*\n${sql}\n*/`;
1448
- }
1449
-
1450
- if (type === 'custom') {
1451
- console.log('Prepared empty file for your custom SQL migration!');
1452
- sql = '-- Custom SQL migration file, put your code below! --';
1453
- }
1454
-
1455
- journal.entries.push({
1456
- idx,
1457
- version: cur.version,
1458
- when: +new Date(),
1459
- tag,
1460
- breakpoints: breakpoints,
1461
- });
1462
-
1463
- fs.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
1464
-
1465
- fs.writeFileSync(`${outFolder}/${tag}.sql`, sql);
1466
-
1467
- // js file with .sql imports for React Native / Expo and Durable Sqlite Objects
1468
- if (bundle) {
1469
- const js = embeddedMigrations(journal, driver);
1470
- fs.writeFileSync(`${outFolder}/migrations.js`, js);
1471
- }
1472
-
1473
- render(
1474
- `[${
1475
- chalk.green(
1476
- '✓',
1477
- )
1478
- }] Your SQL migration file ➜ ${
1479
- chalk.bold.underline.blue(
1480
- path.join(`${outFolder}/${tag}.sql`),
1481
- )
1482
- } 🚀`,
1483
- );
1484
- };
1485
-
1486
- export const embeddedMigrations = (journal: Journal, driver?: Driver) => {
1487
- let content = driver === 'expo'
1488
- ? '// This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo\n\n'
1489
- : '';
1490
-
1491
- content += "import journal from './meta/_journal.json';\n";
1492
- journal.entries.forEach((entry) => {
1493
- content += `import m${entry.idx.toString().padStart(4, '0')} from './${entry.tag}.sql';\n`;
1494
- });
1495
-
1496
- content += `
1497
- export default {
1498
- journal,
1499
- migrations: {
1500
- ${
1501
- journal.entries
1502
- .map((it) => `m${it.idx.toString().padStart(4, '0')}`)
1503
- .join(',\n')
1504
- }
1505
- }
1506
- }
1507
- `;
1508
- return content;
1509
- };
1510
-
1511
- export const prepareSnapshotFolderName = () => {
1512
- const now = new Date();
1513
- return `${now.getFullYear()}${two(now.getUTCMonth() + 1)}${
1514
- two(
1515
- now.getUTCDate(),
1516
- )
1517
- }${two(now.getUTCHours())}${two(now.getUTCMinutes())}${
1518
- two(
1519
- now.getUTCSeconds(),
1520
- )
1521
- }`;
1522
- };
1523
-
1524
- const two = (input: number): string => {
1525
- return input.toString().padStart(2, '0');
1526
- };