@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,767 +0,0 @@
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
- };