@anthonyalayo/drizzle-kit 1.0.1

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 (161) hide show
  1. package/.gitignore +25 -0
  2. package/README.md +79 -0
  3. package/build.dev.ts +51 -0
  4. package/build.ts +112 -0
  5. package/imports-checker/analyze.ts +78 -0
  6. package/imports-checker/checker.ts +296 -0
  7. package/imports-checker/grammar/grammar.ohm +121 -0
  8. package/imports-checker/grammar/grammar.ohm-bundle.d.ts +164 -0
  9. package/imports-checker/grammar/grammar.ohm-bundle.js +753 -0
  10. package/imports-checker/index.ts +48 -0
  11. package/package.json +142 -0
  12. package/patches/difflib@0.2.4.patch +31 -0
  13. package/src/@types/utils.ts +58 -0
  14. package/src/api.ts +504 -0
  15. package/src/cli/commands/_es5.ts +2 -0
  16. package/src/cli/commands/check.ts +52 -0
  17. package/src/cli/commands/drop.ts +60 -0
  18. package/src/cli/commands/introspect.ts +772 -0
  19. package/src/cli/commands/libSqlPushUtils.ts +355 -0
  20. package/src/cli/commands/migrate.ts +1526 -0
  21. package/src/cli/commands/mysqlIntrospect.ts +53 -0
  22. package/src/cli/commands/mysqlPushUtils.ts +352 -0
  23. package/src/cli/commands/mysqlUp.ts +102 -0
  24. package/src/cli/commands/pgIntrospect.ts +55 -0
  25. package/src/cli/commands/pgPushUtils.ts +269 -0
  26. package/src/cli/commands/pgUp.ts +217 -0
  27. package/src/cli/commands/push.ts +637 -0
  28. package/src/cli/commands/singlestoreIntrospect.ts +53 -0
  29. package/src/cli/commands/singlestorePushUtils.ts +456 -0
  30. package/src/cli/commands/singlestoreUp.ts +1 -0
  31. package/src/cli/commands/sqliteIntrospect.ts +96 -0
  32. package/src/cli/commands/sqlitePushUtils.ts +322 -0
  33. package/src/cli/commands/sqliteUp.ts +52 -0
  34. package/src/cli/commands/utils.ts +858 -0
  35. package/src/cli/connections.ts +914 -0
  36. package/src/cli/index.ts +48 -0
  37. package/src/cli/schema.ts +794 -0
  38. package/src/cli/selector-ui.ts +38 -0
  39. package/src/cli/utils.ts +112 -0
  40. package/src/cli/validations/cli.ts +79 -0
  41. package/src/cli/validations/common.ts +193 -0
  42. package/src/cli/validations/libsql.ts +27 -0
  43. package/src/cli/validations/mysql.ts +61 -0
  44. package/src/cli/validations/outputs.ts +91 -0
  45. package/src/cli/validations/postgres.ts +83 -0
  46. package/src/cli/validations/singlestore.ts +61 -0
  47. package/src/cli/validations/sqlite.ts +104 -0
  48. package/src/cli/validations/studio.ts +24 -0
  49. package/src/cli/views.ts +658 -0
  50. package/src/extensions/getTablesFilterByExtensions.ts +16 -0
  51. package/src/extensions/vector.ts +10 -0
  52. package/src/global.ts +61 -0
  53. package/src/index.ts +326 -0
  54. package/src/introspect-mysql.ts +1030 -0
  55. package/src/introspect-pg.ts +1435 -0
  56. package/src/introspect-singlestore.ts +913 -0
  57. package/src/introspect-sqlite.ts +533 -0
  58. package/src/jsonDiffer.js +882 -0
  59. package/src/jsonStatements.ts +3590 -0
  60. package/src/loader.mjs +57 -0
  61. package/src/migrationPreparator.ts +217 -0
  62. package/src/schemaValidator.ts +23 -0
  63. package/src/serializer/index.ts +142 -0
  64. package/src/serializer/mysqlImports.ts +38 -0
  65. package/src/serializer/mysqlSchema.ts +423 -0
  66. package/src/serializer/mysqlSerializer.ts +999 -0
  67. package/src/serializer/pgImports.ts +106 -0
  68. package/src/serializer/pgSchema.ts +937 -0
  69. package/src/serializer/pgSerializer.ts +2223 -0
  70. package/src/serializer/singlestoreImports.ts +38 -0
  71. package/src/serializer/singlestoreSchema.ts +257 -0
  72. package/src/serializer/singlestoreSerializer.ts +767 -0
  73. package/src/serializer/sqliteImports.ts +41 -0
  74. package/src/serializer/sqliteSchema.ts +352 -0
  75. package/src/serializer/sqliteSerializer.ts +931 -0
  76. package/src/serializer/studio.ts +694 -0
  77. package/src/serializer/utils.ts +45 -0
  78. package/src/simulator.ts +157 -0
  79. package/src/snapshotsDiffer.ts +4398 -0
  80. package/src/sqlgenerator.ts +4212 -0
  81. package/src/statementCombiner.ts +597 -0
  82. package/src/utils/certs.ts +44 -0
  83. package/src/utils/words.ts +1333 -0
  84. package/src/utils.ts +370 -0
  85. package/tests/bin.test.ts +58 -0
  86. package/tests/cli/d1http.config.ts +12 -0
  87. package/tests/cli/drizzle.config.ts +9 -0
  88. package/tests/cli/durable-sqlite.config.ts +7 -0
  89. package/tests/cli/expo.config.ts +7 -0
  90. package/tests/cli/postgres.config.ts +13 -0
  91. package/tests/cli/postgres2.config.ts +17 -0
  92. package/tests/cli/schema.ts +1 -0
  93. package/tests/cli/turso.config.ts +10 -0
  94. package/tests/cli-export.test.ts +79 -0
  95. package/tests/cli-generate.test.ts +259 -0
  96. package/tests/cli-migrate.test.ts +103 -0
  97. package/tests/cli-push.test.ts +126 -0
  98. package/tests/common.ts +15 -0
  99. package/tests/indexes/common.ts +21 -0
  100. package/tests/indexes/pg.test.ts +245 -0
  101. package/tests/introspect/libsql.test.ts +35 -0
  102. package/tests/introspect/mysql.test.ts +319 -0
  103. package/tests/introspect/pg.test.ts +894 -0
  104. package/tests/introspect/singlestore.test.ts +275 -0
  105. package/tests/introspect/sqlite.test.ts +122 -0
  106. package/tests/libsql-checks.test.ts +308 -0
  107. package/tests/libsql-statements.test.ts +989 -0
  108. package/tests/libsql-views.test.ts +218 -0
  109. package/tests/migrate/libsq-schema.ts +6 -0
  110. package/tests/migrate/libsql-migrate.test.ts +58 -0
  111. package/tests/migrate/migrations/0000_little_blizzard.sql +4 -0
  112. package/tests/migrate/migrations/0001_nebulous_storm.sql +10 -0
  113. package/tests/migrate/migrations/meta/0000_snapshot.json +40 -0
  114. package/tests/migrate/migrations/meta/0001_snapshot.json +40 -0
  115. package/tests/migrate/migrations/meta/_journal.json +20 -0
  116. package/tests/mysql-checks.test.ts +291 -0
  117. package/tests/mysql-generated.test.ts +1290 -0
  118. package/tests/mysql-schemas.test.ts +156 -0
  119. package/tests/mysql-views.test.ts +553 -0
  120. package/tests/mysql.test.ts +863 -0
  121. package/tests/pg-array.test.ts +368 -0
  122. package/tests/pg-checks.test.ts +329 -0
  123. package/tests/pg-columns.test.ts +484 -0
  124. package/tests/pg-domains.test.ts +306 -0
  125. package/tests/pg-enums.test.ts +751 -0
  126. package/tests/pg-generated.test.ts +529 -0
  127. package/tests/pg-identity.test.ts +447 -0
  128. package/tests/pg-schemas.test.ts +105 -0
  129. package/tests/pg-sequences.test.ts +298 -0
  130. package/tests/pg-tables.test.ts +1021 -0
  131. package/tests/pg-views.test.ts +1929 -0
  132. package/tests/push/common.ts +58 -0
  133. package/tests/push/libsql.test.ts +1400 -0
  134. package/tests/push/mysql-push.test.ts +345 -0
  135. package/tests/push/mysql.test.ts +788 -0
  136. package/tests/push/pg.test.ts +4341 -0
  137. package/tests/push/singlestore-push.test.ts +894 -0
  138. package/tests/push/singlestore.test.ts +444 -0
  139. package/tests/push/sqlite.test.ts +1613 -0
  140. package/tests/rls/pg-policy.test.ts +1656 -0
  141. package/tests/rls/pg-role.test.ts +234 -0
  142. package/tests/schemaDiffer.ts +2852 -0
  143. package/tests/singlestore-generated.test.ts +1290 -0
  144. package/tests/singlestore-schemas.test.ts +155 -0
  145. package/tests/singlestore.test.ts +978 -0
  146. package/tests/sqlite-checks.test.ts +308 -0
  147. package/tests/sqlite-columns.test.ts +1049 -0
  148. package/tests/sqlite-generated.test.ts +1726 -0
  149. package/tests/sqlite-tables.test.ts +637 -0
  150. package/tests/sqlite-views.test.ts +218 -0
  151. package/tests/statements-combiner/libsql-statements-combiner.test.ts +1812 -0
  152. package/tests/statements-combiner/singlestore-statements-combiner.test.ts +882 -0
  153. package/tests/statements-combiner/sqlite-statements-combiner.test.ts +1211 -0
  154. package/tests/test/sqlite.test.ts +39 -0
  155. package/tests/testsinglestore.ts +29 -0
  156. package/tests/validations.test.ts +869 -0
  157. package/tests/wrap-param.test.ts +16 -0
  158. package/tsconfig.build.json +4 -0
  159. package/tsconfig.cli-types.json +9 -0
  160. package/tsconfig.json +28 -0
  161. package/vitest.config.ts +34 -0
@@ -0,0 +1,767 @@
1
+ import chalk from 'chalk';
2
+ import { is, SQL } from 'drizzle-orm';
3
+ import {
4
+ AnySingleStoreTable,
5
+ getTableConfig,
6
+ type PrimaryKey as PrimaryKeyORM,
7
+ SingleStoreDialect,
8
+ uniqueKeyName,
9
+ } from 'drizzle-orm/singlestore-core';
10
+ import { RowDataPacket } from 'mysql2/promise';
11
+ import { withStyle } from '../cli/validations/outputs';
12
+ import { IntrospectStage, IntrospectStatus } from '../cli/views';
13
+
14
+ import { CasingType } from 'src/cli/validations/common';
15
+ import type { DB } from '../utils';
16
+ import {
17
+ Column,
18
+ Index,
19
+ PrimaryKey,
20
+ SingleStoreKitInternals,
21
+ SingleStoreSchemaInternal,
22
+ Table,
23
+ UniqueConstraint,
24
+ } from './singlestoreSchema';
25
+ import { sqlToStr } from './utils';
26
+
27
+ const dialect = new SingleStoreDialect();
28
+
29
+ export const indexName = (tableName: string, columns: string[]) => {
30
+ return `${tableName}_${columns.join('_')}_index`;
31
+ };
32
+
33
+ export const generateSingleStoreSnapshot = (
34
+ tables: AnySingleStoreTable[],
35
+ /* views: SingleStoreView[], */
36
+ casing: CasingType | undefined,
37
+ ): SingleStoreSchemaInternal => {
38
+ const dialect = new SingleStoreDialect({ casing });
39
+ const result: Record<string, Table> = {};
40
+ /* const resultViews: Record<string, View> = {}; */
41
+ const internal: SingleStoreKitInternals = { tables: {}, indexes: {} };
42
+ for (const table of tables) {
43
+ const {
44
+ name: tableName,
45
+ columns,
46
+ indexes,
47
+ schema,
48
+ primaryKeys,
49
+ uniqueConstraints,
50
+ } = getTableConfig(table);
51
+ const columnsObject: Record<string, Column> = {};
52
+ const indexesObject: Record<string, Index> = {};
53
+ const primaryKeysObject: Record<string, PrimaryKey> = {};
54
+ const uniqueConstraintObject: Record<string, UniqueConstraint> = {};
55
+
56
+ columns.forEach((column) => {
57
+ const notNull: boolean = column.notNull;
58
+ const sqlTypeLowered = column.getSQLType().toLowerCase();
59
+ const autoIncrement = typeof (column as any).autoIncrement === 'undefined'
60
+ ? false
61
+ : (column as any).autoIncrement;
62
+
63
+ const generated = column.generated;
64
+
65
+ const columnToSet: Column = {
66
+ name: column.name,
67
+ type: column.getSQLType(),
68
+ primaryKey: false,
69
+ // If field is autoincrement it's notNull by default
70
+ // notNull: autoIncrement ? true : notNull,
71
+ notNull,
72
+ autoincrement: autoIncrement,
73
+ onUpdate: (column as any).hasOnUpdateNow,
74
+ generated: generated
75
+ ? {
76
+ as: is(generated.as, SQL)
77
+ ? dialect.sqlToQuery(generated.as as SQL).sql
78
+ : typeof generated.as === 'function'
79
+ ? dialect.sqlToQuery(generated.as() as SQL).sql
80
+ : (generated.as as any),
81
+ type: generated.mode ?? 'stored',
82
+ }
83
+ : undefined,
84
+ };
85
+
86
+ if (column.primary) {
87
+ primaryKeysObject[`${tableName}_${column.name}`] = {
88
+ name: `${tableName}_${column.name}`,
89
+ columns: [column.name],
90
+ };
91
+ }
92
+
93
+ if (column.isUnique) {
94
+ const existingUnique = uniqueConstraintObject[column.uniqueName!];
95
+ if (typeof existingUnique !== 'undefined') {
96
+ console.log(
97
+ `\n${
98
+ withStyle.errorWarning(`We\'ve found duplicated unique constraint names in ${
99
+ chalk.underline.blue(
100
+ tableName,
101
+ )
102
+ } table.
103
+ The unique constraint ${
104
+ chalk.underline.blue(
105
+ column.uniqueName,
106
+ )
107
+ } on the ${
108
+ chalk.underline.blue(
109
+ column.name,
110
+ )
111
+ } column is confilcting with a unique constraint name already defined for ${
112
+ chalk.underline.blue(
113
+ existingUnique.columns.join(','),
114
+ )
115
+ } columns\n`)
116
+ }`,
117
+ );
118
+ process.exit(1);
119
+ }
120
+ uniqueConstraintObject[column.uniqueName!] = {
121
+ name: column.uniqueName!,
122
+ columns: [columnToSet.name],
123
+ };
124
+ }
125
+
126
+ if (column.default !== undefined) {
127
+ if (is(column.default, SQL)) {
128
+ columnToSet.default = sqlToStr(column.default, casing);
129
+ } else {
130
+ if (typeof column.default === 'string') {
131
+ columnToSet.default = `'${column.default}'`;
132
+ } else {
133
+ if (sqlTypeLowered === 'json' || Array.isArray(column.default)) {
134
+ columnToSet.default = `'${JSON.stringify(column.default)}'`;
135
+ } else if (column.default instanceof Date) {
136
+ if (sqlTypeLowered === 'date') {
137
+ columnToSet.default = `'${column.default.toISOString().split('T')[0]}'`;
138
+ } else if (
139
+ sqlTypeLowered.startsWith('datetime')
140
+ || sqlTypeLowered.startsWith('timestamp')
141
+ ) {
142
+ columnToSet.default = `'${
143
+ column.default
144
+ .toISOString()
145
+ .replace('T', ' ')
146
+ .slice(0, 23)
147
+ }'`;
148
+ }
149
+ } else {
150
+ columnToSet.default = column.default;
151
+ }
152
+ }
153
+ // if (['blob', 'text', 'json'].includes(column.getSQLType())) {
154
+ // columnToSet.default = `(${columnToSet.default})`;
155
+ // }
156
+ }
157
+ }
158
+ columnsObject[column.name] = columnToSet;
159
+ });
160
+
161
+ primaryKeys.map((pk: PrimaryKeyORM) => {
162
+ const columnNames = pk.columns.map((c: any) => c.name);
163
+ primaryKeysObject[pk.getName()] = {
164
+ name: pk.getName(),
165
+ columns: columnNames,
166
+ };
167
+
168
+ // all composite pk's should be treated as notNull
169
+ for (const column of pk.columns) {
170
+ columnsObject[column.name].notNull = true;
171
+ }
172
+ });
173
+
174
+ uniqueConstraints?.map((unq) => {
175
+ const columnNames = unq.columns.map((c) => c.name);
176
+
177
+ const name = unq.name ?? uniqueKeyName(table, columnNames);
178
+
179
+ const existingUnique = uniqueConstraintObject[name];
180
+ if (typeof existingUnique !== 'undefined') {
181
+ console.log(
182
+ `\n${
183
+ withStyle.errorWarning(
184
+ `We\'ve found duplicated unique constraint names in ${
185
+ chalk.underline.blue(
186
+ tableName,
187
+ )
188
+ } table. \nThe unique constraint ${
189
+ chalk.underline.blue(
190
+ name,
191
+ )
192
+ } on the ${
193
+ chalk.underline.blue(
194
+ columnNames.join(','),
195
+ )
196
+ } columns is confilcting with a unique constraint name already defined for ${
197
+ chalk.underline.blue(
198
+ existingUnique.columns.join(','),
199
+ )
200
+ } columns\n`,
201
+ )
202
+ }`,
203
+ );
204
+ process.exit(1);
205
+ }
206
+
207
+ uniqueConstraintObject[name] = {
208
+ name: unq.name!,
209
+ columns: columnNames,
210
+ };
211
+ });
212
+
213
+ indexes.forEach((value) => {
214
+ const columns = value.config.columns;
215
+ const name = value.config.name;
216
+
217
+ let indexColumns = columns.map((it) => {
218
+ if (is(it, SQL)) {
219
+ const sql = dialect.sqlToQuery(it, 'indexes').sql;
220
+ if (typeof internal!.indexes![name] === 'undefined') {
221
+ internal!.indexes![name] = {
222
+ columns: {
223
+ [sql]: {
224
+ isExpression: true,
225
+ },
226
+ },
227
+ };
228
+ } else {
229
+ if (typeof internal!.indexes![name]?.columns[sql] === 'undefined') {
230
+ internal!.indexes![name]!.columns[sql] = {
231
+ isExpression: true,
232
+ };
233
+ } else {
234
+ internal!.indexes![name]!.columns[sql]!.isExpression = true;
235
+ }
236
+ }
237
+ return sql;
238
+ } else {
239
+ return `${it.name}`;
240
+ }
241
+ });
242
+
243
+ if (value.config.unique) {
244
+ if (typeof uniqueConstraintObject[name] !== 'undefined') {
245
+ console.log(
246
+ `\n${
247
+ withStyle.errorWarning(
248
+ `We\'ve found duplicated unique constraint names in ${
249
+ chalk.underline.blue(
250
+ tableName,
251
+ )
252
+ } table. \nThe unique index ${
253
+ chalk.underline.blue(
254
+ name,
255
+ )
256
+ } on the ${
257
+ chalk.underline.blue(
258
+ indexColumns.join(','),
259
+ )
260
+ } columns is confilcting with a unique constraint name already defined for ${
261
+ chalk.underline.blue(
262
+ uniqueConstraintObject[name].columns.join(','),
263
+ )
264
+ } columns\n`,
265
+ )
266
+ }`,
267
+ );
268
+ process.exit(1);
269
+ }
270
+ }
271
+
272
+ indexesObject[name] = {
273
+ name,
274
+ columns: indexColumns,
275
+ isUnique: value.config.unique ?? false,
276
+ using: value.config.using,
277
+ algorithm: value.config.algorythm,
278
+ lock: value.config.lock,
279
+ };
280
+ });
281
+
282
+ // only handle tables without schemas
283
+ if (!schema) {
284
+ result[tableName] = {
285
+ name: tableName,
286
+ columns: columnsObject,
287
+ indexes: indexesObject,
288
+ compositePrimaryKeys: primaryKeysObject,
289
+ uniqueConstraints: uniqueConstraintObject,
290
+ };
291
+ }
292
+ }
293
+
294
+ /* for (const view of views) {
295
+ const {
296
+ isExisting,
297
+ name,
298
+ query,
299
+ schema,
300
+ selectedFields,
301
+ algorithm,
302
+ sqlSecurity,
303
+ withCheckOption,
304
+ } = getViewConfig(view);
305
+
306
+ const columnsObject: Record<string, Column> = {};
307
+
308
+ const existingView = resultViews[name];
309
+ if (typeof existingView !== 'undefined') {
310
+ console.log(
311
+ `\n${
312
+ withStyle.errorWarning(
313
+ `We\'ve found duplicated view name across ${
314
+ chalk.underline.blue(
315
+ schema ?? 'public',
316
+ )
317
+ } schema. Please rename your view`,
318
+ )
319
+ }`,
320
+ );
321
+ process.exit(1);
322
+ }
323
+ for (const key in selectedFields) {
324
+ if (is(selectedFields[key], SingleStoreColumn)) {
325
+ const column = selectedFields[key];
326
+
327
+ const notNull: boolean = column.notNull;
328
+ const sqlTypeLowered = column.getSQLType().toLowerCase();
329
+ const autoIncrement = typeof (column as any).autoIncrement === 'undefined'
330
+ ? false
331
+ : (column as any).autoIncrement;
332
+
333
+ const generated = column.generated;
334
+
335
+ const columnToSet: Column = {
336
+ name: column.name,
337
+ type: column.getSQLType(),
338
+ primaryKey: false,
339
+ // If field is autoincrement it's notNull by default
340
+ // notNull: autoIncrement ? true : notNull,
341
+ notNull,
342
+ autoincrement: autoIncrement,
343
+ onUpdate: (column as any).hasOnUpdateNow,
344
+ generated: generated
345
+ ? {
346
+ as: is(generated.as, SQL)
347
+ ? dialect.sqlToQuery(generated.as as SQL).sql
348
+ : typeof generated.as === 'function'
349
+ ? dialect.sqlToQuery(generated.as() as SQL).sql
350
+ : (generated.as as any),
351
+ type: generated.mode ?? 'stored',
352
+ }
353
+ : undefined,
354
+ };
355
+
356
+ if (column.default !== undefined) {
357
+ if (is(column.default, SQL)) {
358
+ columnToSet.default = sqlToStr(column.default, casing);
359
+ } else {
360
+ if (typeof column.default === 'string') {
361
+ columnToSet.default = `'${column.default}'`;
362
+ } else {
363
+ if (sqlTypeLowered === 'json') {
364
+ columnToSet.default = `'${JSON.stringify(column.default)}'`;
365
+ } else if (column.default instanceof Date) {
366
+ if (sqlTypeLowered === 'date') {
367
+ columnToSet.default = `'${column.default.toISOString().split('T')[0]}'`;
368
+ } else if (
369
+ sqlTypeLowered.startsWith('datetime')
370
+ || sqlTypeLowered.startsWith('timestamp')
371
+ ) {
372
+ columnToSet.default = `'${
373
+ column.default
374
+ .toISOString()
375
+ .replace('T', ' ')
376
+ .slice(0, 23)
377
+ }'`;
378
+ }
379
+ } else {
380
+ columnToSet.default = column.default;
381
+ }
382
+ }
383
+ }
384
+ }
385
+ columnsObject[column.name] = columnToSet;
386
+ }
387
+ }
388
+
389
+ resultViews[name] = {
390
+ columns: columnsObject,
391
+ name,
392
+ isExisting,
393
+ definition: isExisting ? undefined : dialect.sqlToQuery(query!).sql,
394
+ withCheckOption,
395
+ algorithm: algorithm ?? 'undefined', // set default values
396
+ sqlSecurity: sqlSecurity ?? 'definer', // set default values
397
+ };
398
+ } */
399
+
400
+ return {
401
+ version: '1',
402
+ dialect: 'singlestore',
403
+ tables: result,
404
+ /* views: resultViews, */
405
+ _meta: {
406
+ tables: {},
407
+ columns: {},
408
+ },
409
+ internal,
410
+ };
411
+ };
412
+
413
+ function clearDefaults(defaultValue: any, collate: string) {
414
+ if (typeof collate === 'undefined' || collate === null) {
415
+ collate = `utf8mb4`;
416
+ }
417
+
418
+ let resultDefault = defaultValue;
419
+ collate = `_${collate}`;
420
+ if (defaultValue.startsWith(collate)) {
421
+ resultDefault = resultDefault
422
+ .substring(collate.length, defaultValue.length)
423
+ .replace(/\\/g, '');
424
+ if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
425
+ return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
426
+ } else {
427
+ return `'${resultDefault}'`;
428
+ }
429
+ } else {
430
+ return `(${resultDefault})`;
431
+ }
432
+ }
433
+
434
+ export const fromDatabase = async (
435
+ db: DB,
436
+ inputSchema: string,
437
+ tablesFilter: (table: string) => boolean = (table) => true,
438
+ progressCallback?: (
439
+ stage: IntrospectStage,
440
+ count: number,
441
+ status: IntrospectStatus,
442
+ ) => void,
443
+ ): Promise<SingleStoreSchemaInternal> => {
444
+ const result: Record<string, Table> = {};
445
+ const internals: SingleStoreKitInternals = { tables: {}, indexes: {} };
446
+
447
+ const columns = await db.query(`select * from information_schema.columns
448
+ where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
449
+ order by table_name, ordinal_position;`);
450
+
451
+ const response = columns as RowDataPacket[];
452
+
453
+ const schemas: string[] = [];
454
+
455
+ let columnsCount = 0;
456
+ let tablesCount = new Set();
457
+ let indexesCount = 0;
458
+ /* let viewsCount = 0; */
459
+
460
+ const idxs = await db.query(
461
+ `select * from INFORMATION_SCHEMA.STATISTICS
462
+ WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`,
463
+ );
464
+
465
+ const idxRows = idxs as RowDataPacket[];
466
+
467
+ for (const column of response) {
468
+ if (!tablesFilter(column['TABLE_NAME'] as string)) continue;
469
+
470
+ columnsCount += 1;
471
+ if (progressCallback) {
472
+ progressCallback('columns', columnsCount, 'fetching');
473
+ }
474
+ const schema: string = column['TABLE_SCHEMA'];
475
+ const tableName = column['TABLE_NAME'];
476
+
477
+ tablesCount.add(`${schema}.${tableName}`);
478
+ if (progressCallback) {
479
+ progressCallback('columns', tablesCount.size, 'fetching');
480
+ }
481
+ const columnName: string = column['COLUMN_NAME'];
482
+ const isNullable = column['IS_NULLABLE'] === 'YES'; // 'YES', 'NO'
483
+ const dataType = column['DATA_TYPE']; // varchar
484
+ const columnType = column['COLUMN_TYPE']; // varchar(256)
485
+ // const columnType = column["DATA_TYPE"];
486
+ const isPrimary = column['COLUMN_KEY'] === 'PRI'; // 'PRI', ''
487
+ let columnDefault: string | null = column['COLUMN_DEFAULT'];
488
+ const collation: string = column['CHARACTER_SET_NAME'];
489
+ const geenratedExpression: string = column['GENERATION_EXPRESSION'];
490
+
491
+ let columnExtra = column['EXTRA'];
492
+ let isAutoincrement = false; // 'auto_increment', ''
493
+ let isDefaultAnExpression = false; // 'auto_increment', ''
494
+
495
+ if (typeof column['EXTRA'] !== 'undefined') {
496
+ columnExtra = column['EXTRA'];
497
+ isAutoincrement = column['EXTRA'] === 'auto_increment'; // 'auto_increment', ''
498
+ isDefaultAnExpression = column['EXTRA'].includes('DEFAULT_GENERATED'); // 'auto_increment', ''
499
+ }
500
+
501
+ // if (isPrimary) {
502
+ // if (typeof tableToPk[tableName] === "undefined") {
503
+ // tableToPk[tableName] = [columnName];
504
+ // } else {
505
+ // tableToPk[tableName].push(columnName);
506
+ // }
507
+ // }
508
+
509
+ if (schema !== inputSchema) {
510
+ schemas.push(schema);
511
+ }
512
+
513
+ const table = result[tableName];
514
+
515
+ // let changedType = columnType.replace("bigint unsigned", "serial")
516
+ let changedType = columnType;
517
+
518
+ if (columnType === 'bigint unsigned' && !isNullable && isAutoincrement) {
519
+ // check unique here
520
+ const uniqueIdx = idxRows.filter(
521
+ (it) =>
522
+ it['COLUMN_NAME'] === columnName
523
+ && it['TABLE_NAME'] === tableName
524
+ && it['NON_UNIQUE'] === 0,
525
+ );
526
+ if (uniqueIdx && uniqueIdx.length === 1) {
527
+ changedType = columnType.replace('bigint unsigned', 'serial');
528
+ }
529
+ }
530
+
531
+ if (
532
+ columnType.startsWith('bigint(')
533
+ || columnType.startsWith('tinyint(')
534
+ || columnType.startsWith('date(')
535
+ || columnType.startsWith('int(')
536
+ || columnType.startsWith('mediumint(')
537
+ || columnType.startsWith('smallint(')
538
+ || columnType.startsWith('text(')
539
+ || columnType.startsWith('time(')
540
+ || columnType.startsWith('year(')
541
+ ) {
542
+ changedType = columnType.replace(/\(\s*[^)]*\)$/, '');
543
+ }
544
+
545
+ if (columnType.includes('decimal(10,0)')) {
546
+ changedType = columnType.replace('decimal(10,0)', 'decimal');
547
+ }
548
+
549
+ if (columnDefault?.endsWith('.')) {
550
+ columnDefault = columnDefault.slice(0, -1);
551
+ }
552
+
553
+ let onUpdate: boolean | undefined = undefined;
554
+ if (
555
+ columnType.startsWith('timestamp')
556
+ && typeof columnExtra !== 'undefined'
557
+ && columnExtra.includes('on update CURRENT_TIMESTAMP')
558
+ ) {
559
+ onUpdate = true;
560
+ }
561
+
562
+ const newColumn: Column = {
563
+ default: columnDefault === null
564
+ ? undefined
565
+ : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault)
566
+ && !['decimal', 'char', 'varchar'].some((type) => columnType.startsWith(type))
567
+ ? Number(columnDefault)
568
+ : isDefaultAnExpression
569
+ ? clearDefaults(columnDefault, collation)
570
+ : columnDefault.startsWith('CURRENT_TIMESTAMP')
571
+ ? 'CURRENT_TIMESTAMP'
572
+ : `'${columnDefault}'`,
573
+ autoincrement: isAutoincrement,
574
+ name: columnName,
575
+ type: changedType,
576
+ primaryKey: false,
577
+ notNull: !isNullable,
578
+ onUpdate,
579
+ generated: geenratedExpression
580
+ ? {
581
+ as: geenratedExpression,
582
+ type: columnExtra === 'VIRTUAL GENERATED' ? 'virtual' : 'stored',
583
+ }
584
+ : undefined,
585
+ };
586
+
587
+ // Set default to internal object
588
+ if (isDefaultAnExpression) {
589
+ if (typeof internals!.tables![tableName] === 'undefined') {
590
+ internals!.tables![tableName] = {
591
+ columns: {
592
+ [columnName]: {
593
+ isDefaultAnExpression: true,
594
+ },
595
+ },
596
+ };
597
+ } else {
598
+ if (
599
+ typeof internals!.tables![tableName]!.columns[columnName]
600
+ === 'undefined'
601
+ ) {
602
+ internals!.tables![tableName]!.columns[columnName] = {
603
+ isDefaultAnExpression: true,
604
+ };
605
+ } else {
606
+ internals!.tables![tableName]!.columns[
607
+ columnName
608
+ ]!.isDefaultAnExpression = true;
609
+ }
610
+ }
611
+ }
612
+
613
+ if (!table) {
614
+ result[tableName] = {
615
+ name: tableName,
616
+ columns: {
617
+ [columnName]: newColumn,
618
+ },
619
+ compositePrimaryKeys: {},
620
+ indexes: {},
621
+ uniqueConstraints: {},
622
+ };
623
+ } else {
624
+ result[tableName]!.columns[columnName] = newColumn;
625
+ }
626
+ }
627
+
628
+ const tablePks = await db.query(
629
+ `SELECT table_name, column_name, ordinal_position
630
+ FROM information_schema.table_constraints t
631
+ LEFT JOIN information_schema.key_column_usage k
632
+ USING(constraint_name,table_schema,table_name)
633
+ WHERE t.constraint_type='UNIQUE'
634
+ and table_name != '__drizzle_migrations'
635
+ AND t.table_schema = '${inputSchema}'
636
+ ORDER BY ordinal_position`,
637
+ );
638
+
639
+ const tableToPk: { [tname: string]: string[] } = {};
640
+
641
+ const tableToPkRows = tablePks as RowDataPacket[];
642
+ for (const tableToPkRow of tableToPkRows) {
643
+ const tableName: string = tableToPkRow['table_name'];
644
+ const columnName: string = tableToPkRow['column_name'];
645
+ const position: string = tableToPkRow['ordinal_position'];
646
+
647
+ if (typeof result[tableName] === 'undefined') {
648
+ continue;
649
+ }
650
+
651
+ if (typeof tableToPk[tableName] === 'undefined') {
652
+ tableToPk[tableName] = [columnName];
653
+ } else {
654
+ tableToPk[tableName].push(columnName);
655
+ }
656
+ }
657
+
658
+ for (const [key, value] of Object.entries(tableToPk)) {
659
+ // if (value.length > 1) {
660
+ result[key].compositePrimaryKeys = {
661
+ [`${key}_${value.join('_')}`]: {
662
+ name: `${key}_${value.join('_')}`,
663
+ columns: value,
664
+ },
665
+ };
666
+ // } else if (value.length === 1) {
667
+ // result[key].columns[value[0]].primaryKey = true;
668
+ // } else {
669
+ // }
670
+ }
671
+ if (progressCallback) {
672
+ progressCallback('columns', columnsCount, 'done');
673
+ progressCallback('tables', tablesCount.size, 'done');
674
+ }
675
+
676
+ for (const idxRow of idxRows) {
677
+ const tableSchema = idxRow['TABLE_SCHEMA'];
678
+ const tableName = idxRow['TABLE_NAME'];
679
+ const constraintName = idxRow['INDEX_NAME'];
680
+ const columnName: string = idxRow['COLUMN_NAME'];
681
+ const isUnique = idxRow['NON_UNIQUE'] === 0;
682
+
683
+ const tableInResult = result[tableName];
684
+ if (typeof tableInResult === 'undefined') continue;
685
+
686
+ // if (tableInResult.columns[columnName].type === "serial") continue;
687
+
688
+ indexesCount += 1;
689
+ if (progressCallback) {
690
+ progressCallback('indexes', indexesCount, 'fetching');
691
+ }
692
+
693
+ if (isUnique) {
694
+ if (
695
+ typeof tableInResult.uniqueConstraints[constraintName] !== 'undefined'
696
+ ) {
697
+ tableInResult.uniqueConstraints[constraintName]!.columns.push(
698
+ columnName,
699
+ );
700
+ } else {
701
+ tableInResult.uniqueConstraints[constraintName] = {
702
+ name: constraintName,
703
+ columns: [columnName],
704
+ };
705
+ }
706
+ }
707
+ }
708
+
709
+ /* const views = await db.query(
710
+ `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`,
711
+ ); */
712
+
713
+ /* const resultViews: Record<string, View> = {}; */
714
+
715
+ /* viewsCount = views.length;
716
+ if (progressCallback) {
717
+ progressCallback('views', viewsCount, 'fetching');
718
+ }
719
+ for await (const view of views) {
720
+ const viewName = view['TABLE_NAME'];
721
+ const definition = view['VIEW_DEFINITION'];
722
+
723
+ const withCheckOption = view['CHECK_OPTION'] === 'NONE'
724
+ ? undefined
725
+ : view['CHECK_OPTION'].toLowerCase();
726
+ const sqlSecurity = view['SECURITY_TYPE'].toLowerCase();
727
+
728
+ const [createSqlStatement] = await db.query(
729
+ `SHOW CREATE VIEW \`${viewName}\`;`,
730
+ );
731
+ const algorithmMatch = createSqlStatement['Create View'].match(/ALGORITHM=([^ ]+)/);
732
+ const algorithm = algorithmMatch
733
+ ? algorithmMatch[1].toLowerCase()
734
+ : undefined;
735
+
736
+ const columns = result[viewName].columns;
737
+ delete result[viewName];
738
+
739
+ resultViews[viewName] = {
740
+ columns: columns,
741
+ isExisting: false,
742
+ name: viewName,
743
+ algorithm,
744
+ definition,
745
+ sqlSecurity,
746
+ withCheckOption,
747
+ };
748
+ } */
749
+
750
+ if (progressCallback) {
751
+ progressCallback('indexes', indexesCount, 'done');
752
+ // progressCallback("enums", 0, "fetching");
753
+ progressCallback('enums', 0, 'done');
754
+ }
755
+
756
+ return {
757
+ version: '1',
758
+ dialect: 'singlestore',
759
+ tables: result,
760
+ /* views: resultViews, */
761
+ _meta: {
762
+ tables: {},
763
+ columns: {},
764
+ },
765
+ internal: internals,
766
+ };
767
+ };