orchid-orm 1.67.1 → 1.68.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.
@@ -1,3786 +1,5 @@
1
- import { promptSelect, getSchemaAndTableFromName, getDbTableColumnsChecks, dbColumnToAst, instantiateDbColumn, concatSchemaAndName, encodeColumnDefault, getIndexName, getExcludeName, getConstraintName, tableToAst, getMigrationsSchemaAndTable, getDbStructureTableData, makeDomainsMap, astToMigration, createMigrationInterface, introspectDbSchema, makeStructureToAstCtx, makeFileVersion, writeMigrationFile, migrateAndClose, getDbVersion, migrate, structureToAst, saveMigratedVersion, rakeDbCommands } from 'rake-db';
2
- import { colors, EnumColumn, ArrayColumn, toSnakeCase, getColumnBaseType, deepCompare, RawSql, emptyArray, toArray, getFreeSetAlias, VirtualColumn, getSupportedDefaultPrivileges, exhaustive, toCamelCase, addCode, pluralize, codeToString, emptyObject, getQuerySchema, DomainColumn, UnknownColumn, defaultSchemaConfig, toPascalCase, getImportPath, singleQuote, columnsShapeToCode, pushTableDataCode, quoteObjectKey, pathToLog } from 'pqb/internal';
3
- import path from 'node:path';
4
- import { pathToFileURL } from 'url';
5
- import fs from 'fs/promises';
6
- import typescript from 'typescript';
7
- export * from 'rake-db/node-postgres';
1
+ import { patchRakeDb } from "orchid-orm/migrations";
2
+ export * from "rake-db/node-postgres";
3
+ patchRakeDb();
8
4
 
9
- const compareSqlExpressions = async (tableExpressions, adapter) => {
10
- if (!tableExpressions.length) return;
11
- let id = 1;
12
- for (const { source, compare, handle } of tableExpressions) {
13
- const viewName = `orchidTmpView${id++}`;
14
- const values = [];
15
- const combinedQueries = [
16
- `CREATE TEMPORARY VIEW ${viewName} AS (SELECT ${compare.map(
17
- ({ inDb, inCode }, i) => `${inDb} AS "*inDb-${i}*", ${inCode.map(
18
- (s, j) => `(${typeof s === "string" ? s : s.toSQL({ values })}) "*inCode-${i}-${j}*"`
19
- ).join(", ")}`
20
- ).join(", ")} FROM ${source})`,
21
- `SELECT pg_get_viewdef('${viewName}') v`,
22
- `DROP VIEW ${viewName}`
23
- ].join("; ");
24
- const result = await adapter.query(combinedQueries, values, viewName).then(
25
- (res) => res[1],
26
- async (err) => {
27
- if (err.code !== "42704") {
28
- throw err;
29
- }
30
- }
31
- );
32
- if (!result) {
33
- handle();
34
- return;
35
- }
36
- const match = compareSqlExpressionResult(
37
- result.rows[0].v,
38
- compare[0].inCode
39
- );
40
- handle(match);
41
- }
42
- };
43
- const compareSqlExpressionResult = (resultSql, inCode) => {
44
- let pos = 7;
45
- const rgx = /\s+AS\s+"\*(inDb-\d+|inCode-\d+-\d+)\*",?/g;
46
- let match;
47
- let inDb = "";
48
- let codeI = 0;
49
- const matches = inCode.map(() => true);
50
- while (match = rgx.exec(resultSql)) {
51
- const sql = resultSql.slice(pos, rgx.lastIndex - match[0].length).trim();
52
- const arr = match[1].split("-");
53
- if (arr.length === 2) {
54
- inDb = sql;
55
- codeI = 0;
56
- } else {
57
- if (inDb !== sql && // Comparing `(sql) = sql` and `sql = (sql)` below.
58
- // Could not reproduce this case in integration tests, but it was reported in #494.
59
- !(inDb.startsWith("(") && inDb.endsWith(")") && inDb.slice(1, -1) === sql) && !(sql.startsWith("(") && sql.endsWith(")") && sql.slice(1, -1) === inDb)) {
60
- matches[codeI] = false;
61
- }
62
- codeI++;
63
- }
64
- pos = rgx.lastIndex;
65
- }
66
- const firstMatching = matches.indexOf(true);
67
- return firstMatching === -1 ? void 0 : firstMatching;
68
- };
69
- const promptCreateOrRename = (kind, name, drop, verifying) => {
70
- if (verifying) throw new AbortSignal();
71
- let hintPos = name.length + 4;
72
- for (const from of drop) {
73
- const value = from.length + 8 + name.length;
74
- if (value > hintPos) hintPos = value;
75
- }
76
- let max = 0;
77
- const add = name.length + 3;
78
- for (const name2 of drop) {
79
- if (name2.length + add > max) {
80
- max = name2.length + add;
81
- }
82
- }
83
- const renameMessage = `rename ${kind}`;
84
- return promptSelect({
85
- message: `Create or rename ${colors.blueBold(
86
- name
87
- )} ${kind} from another ${kind}?`,
88
- options: [
89
- `${colors.greenBold("+")} ${name} ${colors.pale(
90
- `create ${kind}`.padStart(
91
- hintPos + renameMessage.length - name.length - 4,
92
- " "
93
- )
94
- )}`,
95
- ...drop.map(
96
- (d) => `${colors.yellowBold("~")} ${d} ${colors.yellowBold(
97
- "=>"
98
- )} ${name} ${colors.pale(
99
- renameMessage.padStart(
100
- hintPos + renameMessage.length - d.length - name.length - 8,
101
- " "
102
- )
103
- )}`
104
- )
105
- ]
106
- });
107
- };
108
- const checkForColumnAddOrDrop = (shape, key) => {
109
- const item = shape[key];
110
- if (item) {
111
- return item && (Array.isArray(item) || item.type === "add" || item.type === "drop");
112
- }
113
- for (const k in shape) {
114
- const item2 = shape[k];
115
- if (Array.isArray(item2) ? item2.some(
116
- (item3) => (item3.type === "add" || item3.type === "drop") && item3.item.data.name === key
117
- ) : (item2.type === "add" || item2.type === "drop") && item2.item.data.name === key) {
118
- return true;
119
- }
120
- }
121
- return false;
122
- };
123
-
124
- const processSchemas = async (ast, dbStructure, {
125
- codeItems: { schemas },
126
- verifying,
127
- internal: { generatorIgnore },
128
- currentSchema
129
- }) => {
130
- const createSchemas = [];
131
- const dropSchemas = [];
132
- for (const schema of schemas) {
133
- if (!dbStructure.schemas.includes(schema)) {
134
- createSchemas.push(schema);
135
- }
136
- }
137
- for (const schema of dbStructure.schemas) {
138
- if (!schemas.has(schema) && schema !== "public" && schema !== currentSchema && !generatorIgnore?.schemas?.includes(schema)) {
139
- dropSchemas.push(schema);
140
- }
141
- }
142
- for (const schema of createSchemas) {
143
- if (dropSchemas.length) {
144
- const i = await promptCreateOrRename(
145
- "schema",
146
- schema,
147
- dropSchemas,
148
- verifying
149
- );
150
- if (i) {
151
- const from = dropSchemas[i - 1];
152
- dropSchemas.splice(i - 1, 1);
153
- renameSchemaInStructures(dbStructure.tables, from, schema);
154
- renameSchemaInStructures(dbStructure.views, from, schema);
155
- renameSchemaInStructures(dbStructure.indexes, from, schema);
156
- renameSchemaInStructures(dbStructure.excludes, from, schema);
157
- renameSchemaInStructures(dbStructure.constraints, from, schema);
158
- renameSchemaInStructures(dbStructure.triggers, from, schema);
159
- renameSchemaInStructures(dbStructure.enums, from, schema);
160
- renameSchemaInStructures(dbStructure.domains, from, schema);
161
- renameSchemaInStructures(dbStructure.collations, from, schema);
162
- for (const table of dbStructure.tables) {
163
- for (const column of table.columns) {
164
- if (column.typeSchema === from) {
165
- column.typeSchema = schema;
166
- }
167
- }
168
- }
169
- ast.push({
170
- type: "renameSchema",
171
- from,
172
- to: schema
173
- });
174
- continue;
175
- }
176
- }
177
- ast.push({
178
- type: "schema",
179
- action: "create",
180
- name: schema
181
- });
182
- }
183
- for (const schema of dropSchemas) {
184
- ast.push({
185
- type: "schema",
186
- action: "drop",
187
- name: schema
188
- });
189
- }
190
- };
191
- const renameSchemaInStructures = (items, from, to) => {
192
- for (const item of items) {
193
- if (item.schemaName === from) {
194
- item.schemaName = to;
195
- }
196
- }
197
- };
198
-
199
- const processExtensions = (ast, dbStructure, {
200
- currentSchema,
201
- internal: { extensions, generatorIgnore }
202
- }) => {
203
- const codeExtensions = extensions?.map((ext) => {
204
- const [schema, name] = getSchemaAndTableFromName(currentSchema, ext.name);
205
- return { schema, name, version: ext.version };
206
- });
207
- for (const dbExt of dbStructure.extensions) {
208
- if (generatorIgnore?.schemas?.includes(dbExt.schemaName) || generatorIgnore?.extensions?.includes(dbExt.name)) {
209
- continue;
210
- }
211
- if (codeExtensions) {
212
- let found = false;
213
- for (let i = 0; i < codeExtensions.length; i++) {
214
- const codeExt = codeExtensions[i];
215
- if (dbExt.name === codeExt.name && dbExt.schemaName === (codeExt.schema ?? currentSchema) && (!codeExt.version || codeExt.version === dbExt.version)) {
216
- found = true;
217
- codeExtensions.splice(i, 1);
218
- break;
219
- }
220
- }
221
- if (found) continue;
222
- }
223
- ast.push({
224
- type: "extension",
225
- action: "drop",
226
- schema: dbExt.schemaName === currentSchema ? void 0 : dbExt.schemaName,
227
- name: dbExt.name,
228
- version: dbExt.version
229
- });
230
- }
231
- if (codeExtensions?.length) {
232
- ast.push(
233
- ...codeExtensions.map((ext) => ({
234
- type: "extension",
235
- action: "create",
236
- ...ext
237
- }))
238
- );
239
- }
240
- };
241
-
242
- const processColumns = async (adapter, config, structureToAstCtx, dbStructure, domainsMap, changeTableData, ast, currentSchema, compareSql, typeCastsCache, verifying) => {
243
- const { dbTable } = changeTableData;
244
- const dbColumns = Object.fromEntries(
245
- dbTable.columns.map((column) => [column.name, column])
246
- );
247
- const { columnsToAdd, columnsToDrop, columnsToChange } = groupColumns(
248
- structureToAstCtx,
249
- dbStructure,
250
- domainsMap,
251
- dbColumns,
252
- changeTableData
253
- );
254
- await addOrRenameColumns(
255
- config,
256
- dbStructure,
257
- changeTableData,
258
- columnsToAdd,
259
- columnsToDrop,
260
- columnsToChange,
261
- verifying
262
- );
263
- await changeColumns(
264
- adapter,
265
- config,
266
- structureToAstCtx,
267
- dbStructure,
268
- domainsMap,
269
- ast,
270
- currentSchema,
271
- dbColumns,
272
- columnsToChange,
273
- compareSql,
274
- changeTableData,
275
- typeCastsCache,
276
- verifying
277
- );
278
- dropColumns(changeTableData, columnsToDrop);
279
- };
280
- const groupColumns = (structureToAstCtx, dbStructure, domainsMap, dbColumns, changeTableData) => {
281
- const columnsToAdd = [];
282
- const columnsToDrop = [];
283
- const columnsToChange = /* @__PURE__ */ new Map();
284
- const columnsToChangeByDbName = /* @__PURE__ */ new Map();
285
- const { codeTable, dbTable, dbTableData } = changeTableData;
286
- const checks = getDbTableColumnsChecks(changeTableData.dbTableData);
287
- for (const key in codeTable.shape) {
288
- const column = codeTable.shape[key];
289
- if (!column.dataType) continue;
290
- const name = column.data.name ?? key;
291
- if (dbColumns[name]) {
292
- columnsToChange.set(key, { key, dbName: name, column });
293
- columnsToChangeByDbName.set(name, true);
294
- } else {
295
- columnsToAdd.push({ key, column });
296
- }
297
- }
298
- for (const name in dbColumns) {
299
- if (columnsToChangeByDbName.has(name)) continue;
300
- const [key, column] = dbColumnToAst(
301
- structureToAstCtx,
302
- dbStructure,
303
- domainsMap,
304
- dbTable.name,
305
- dbColumns[name],
306
- dbTable,
307
- dbTableData,
308
- checks
309
- );
310
- columnsToDrop.push({ key, column });
311
- }
312
- return {
313
- columnsToAdd,
314
- columnsToDrop,
315
- columnsToChange
316
- };
317
- };
318
- const addOrRenameColumns = async (config, dbStructure, {
319
- dbTableData,
320
- schema,
321
- changeTableAst: { name: tableName, shape }
322
- }, columnsToAdd, columnsToDrop, columnsToChange, verifying) => {
323
- for (const { key, column } of columnsToAdd) {
324
- if (columnsToDrop.length) {
325
- const codeName = column.data.name ?? key;
326
- const i = await promptCreateOrRename(
327
- "column",
328
- codeName,
329
- columnsToDrop.map((x) => x.key),
330
- verifying
331
- );
332
- if (i) {
333
- const drop = columnsToDrop[i - 1];
334
- columnsToDrop.splice(i - 1, 1);
335
- const from = drop.column.data.name ?? drop.key;
336
- columnsToChange.set(from, {
337
- key,
338
- dbName: from,
339
- column: column.name(codeName)
340
- });
341
- const to = config.snakeCase ? toSnakeCase(key) : key;
342
- if (dbTableData.primaryKey) {
343
- renameColumn(dbTableData.primaryKey.columns, from, to);
344
- }
345
- for (const index of dbTableData.indexes) {
346
- for (const column2 of index.columns) {
347
- if ("column" in column2 && column2.column === from) {
348
- column2.column = to;
349
- }
350
- }
351
- }
352
- for (const exclude of dbTableData.excludes) {
353
- for (const column2 of exclude.columns) {
354
- if ("column" in column2 && column2.column === from) {
355
- column2.column = to;
356
- }
357
- }
358
- }
359
- for (const c of dbTableData.constraints) {
360
- if (c.check?.columns) {
361
- renameColumn(c.check.columns, from, to);
362
- }
363
- if (c.references) {
364
- renameColumn(c.references.columns, from, to);
365
- }
366
- }
367
- for (const c of dbStructure.constraints) {
368
- if (c.references && c.references.foreignSchema === schema && c.references.foreignTable === tableName) {
369
- renameColumn(c.references.foreignColumns, from, to);
370
- }
371
- }
372
- continue;
373
- }
374
- }
375
- shape[key] = {
376
- type: "add",
377
- item: column
378
- };
379
- }
380
- };
381
- const dropColumns = ({ changeTableAst: { shape } }, columnsToDrop) => {
382
- for (const { key, column } of columnsToDrop) {
383
- shape[key] = {
384
- type: "drop",
385
- item: column
386
- };
387
- }
388
- };
389
- const changeColumns = async (adapter, config, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, dbColumns, columnsToChange, compareSql, changeTableData, typeCastsCache, verifying) => {
390
- for (const [
391
- key,
392
- { key: codeKey, dbName, column: codeColumn }
393
- ] of columnsToChange) {
394
- const dbColumnStructure = dbColumns[dbName];
395
- const dbColumn = instantiateDbColumn(
396
- structureToAstCtx,
397
- dbStructure,
398
- domainsMap,
399
- dbColumnStructure
400
- );
401
- const action = await compareColumns(
402
- adapter,
403
- domainsMap,
404
- ast,
405
- currentSchema,
406
- compareSql,
407
- changeTableData,
408
- typeCastsCache,
409
- verifying,
410
- key,
411
- dbName,
412
- dbColumn,
413
- codeColumn
414
- );
415
- if (action === "change") {
416
- changeColumn(changeTableData, key, dbName, dbColumn, codeColumn);
417
- } else if (action === "recreate") {
418
- changeTableData.changeTableAst.shape[key] = [
419
- {
420
- type: "drop",
421
- item: dbColumn
422
- },
423
- {
424
- type: "add",
425
- item: codeColumn
426
- }
427
- ];
428
- } else if (action !== "recreate") {
429
- const to = codeColumn.data.name ?? codeKey;
430
- if (dbName !== to) {
431
- changeTableData.changeTableAst.shape[config.snakeCase ? dbName === toSnakeCase(codeKey) ? codeKey : dbName : dbName] = {
432
- type: "rename",
433
- name: config.snakeCase ? to === toSnakeCase(codeKey) ? codeKey : to : to
434
- };
435
- }
436
- }
437
- }
438
- };
439
- const compareColumns = async (adapter, domainsMap, ast, currentSchema, compareSql, changeTableData, typeCastsCache, verifying, key, dbName, dbColumn, codeColumn) => {
440
- if (dbColumn instanceof ArrayColumn && codeColumn instanceof ArrayColumn) {
441
- dbColumn = dbColumn.data.item;
442
- codeColumn = codeColumn.data.item;
443
- }
444
- const dbType = getColumnDbType(dbColumn, currentSchema);
445
- const codeType = getColumnDbType(codeColumn, currentSchema);
446
- if (dbType !== codeType) {
447
- const typeCasts = await getTypeCasts(adapter, typeCastsCache);
448
- const dbBaseType = getColumnBaseType(dbColumn, domainsMap, dbType);
449
- const codeBaseType = getColumnBaseType(codeColumn, domainsMap, codeType);
450
- if (!typeCasts.get(dbBaseType)?.has(codeBaseType)) {
451
- if (!(dbColumn instanceof EnumColumn) || !(codeColumn instanceof EnumColumn) || !deepCompare(dbColumn.options, codeColumn.options)) {
452
- if (verifying) throw new AbortSignal();
453
- const tableName = concatSchemaAndName(changeTableData.changeTableAst);
454
- const abort = await promptSelect({
455
- message: `Cannot cast type of ${tableName}'s column ${key} from ${dbType} to ${codeType}`,
456
- options: [
457
- `${colors.yellowBold(
458
- `-/+`
459
- )} recreate the column, existing data will be ${colors.red(
460
- "lost"
461
- )}`,
462
- `write migration manually`
463
- ]
464
- });
465
- if (abort) {
466
- throw new AbortSignal();
467
- }
468
- dbColumn.data.name = codeColumn.data.name;
469
- return "recreate";
470
- }
471
- }
472
- return "change";
473
- }
474
- const dbData = dbColumn.data;
475
- const codeData = codeColumn.data;
476
- for (const key2 of ["isNullable", "comment"]) {
477
- if (dbData[key2] !== codeData[key2]) {
478
- return "change";
479
- }
480
- }
481
- for (const key2 of [
482
- "maxChars",
483
- "collation",
484
- "compression",
485
- "numericPrecision",
486
- "numericScale",
487
- "dateTimePrecision"
488
- ]) {
489
- if (key2 in codeData && dbData[key2] !== codeData[key2]) {
490
- return "change";
491
- }
492
- }
493
- if (dbColumn.data.isOfCustomType) {
494
- const { typmod } = dbColumn.data;
495
- if (typmod !== void 0 && typmod !== -1) {
496
- const i = codeColumn.dataType.indexOf("(");
497
- if (i === -1 || codeColumn.dataType.slice(i + 1, -1) !== `${typmod}`) {
498
- return "change";
499
- }
500
- }
501
- }
502
- if (!deepCompare(
503
- dbData.identity,
504
- codeData.identity ? {
505
- always: false,
506
- start: 1,
507
- increment: 1,
508
- cache: 1,
509
- cycle: false,
510
- ...codeData.identity ?? {}
511
- } : void 0
512
- )) {
513
- return "change";
514
- }
515
- if (dbData.default !== void 0 && codeData.default !== void 0) {
516
- const valuesBeforeLen = compareSql.values.length;
517
- const dbDefault = encodeColumnDefault(
518
- dbData.default,
519
- compareSql.values,
520
- dbColumn
521
- );
522
- const dbValues = compareSql.values.slice(valuesBeforeLen);
523
- const codeDefault = encodeColumnDefault(
524
- codeData.default,
525
- compareSql.values,
526
- codeColumn
527
- );
528
- const codeValues = compareSql.values.slice(valuesBeforeLen);
529
- if (dbValues.length !== codeValues.length || dbValues.length && JSON.stringify(dbValues) !== JSON.stringify(codeValues)) {
530
- compareSql.values.length = valuesBeforeLen;
531
- return "change";
532
- } else if (dbDefault !== codeDefault && dbDefault !== `(${codeDefault})`) {
533
- const change = () => {
534
- changeColumn(changeTableData, key, dbName, dbColumn, codeColumn);
535
- if (!changeTableData.pushedAst) {
536
- changeTableData.pushedAst = true;
537
- ast.push(changeTableData.changeTableAst);
538
- }
539
- };
540
- compareSql.expressions.push({
541
- inDb: dbDefault,
542
- inCode: codeDefault,
543
- change
544
- });
545
- }
546
- }
547
- return;
548
- };
549
- const getTypeCasts = async (adapter, typeCastsCache) => {
550
- let typeCasts = typeCastsCache.value;
551
- if (!typeCasts) {
552
- const { rows } = await adapter.arrays(`SELECT s.typname, t.typname
553
- FROM pg_cast
554
- JOIN pg_type AS s ON s.oid = castsource
555
- JOIN pg_type AS t ON t.oid = casttarget`);
556
- const directTypeCasts = /* @__PURE__ */ new Map();
557
- for (const [source, target] of rows) {
558
- const set = directTypeCasts.get(source);
559
- if (set) {
560
- set.add(target);
561
- } else {
562
- directTypeCasts.set(source, /* @__PURE__ */ new Set([target]));
563
- }
564
- }
565
- typeCasts = /* @__PURE__ */ new Map();
566
- for (const [type, directSet] of directTypeCasts.entries()) {
567
- const set = new Set(directSet);
568
- typeCasts.set(type, set);
569
- for (const subtype of directSet) {
570
- const subset = directTypeCasts.get(subtype);
571
- if (subset) {
572
- for (const type2 of subset) {
573
- set.add(type2);
574
- }
575
- }
576
- }
577
- }
578
- typeCastsCache.value = typeCasts;
579
- }
580
- return typeCasts;
581
- };
582
- const changeColumn = (changeTableData, key, dbName, dbColumn, codeColumn) => {
583
- dbColumn.data.as = codeColumn.data.as = void 0;
584
- const simpleCodeColumn = Object.create(codeColumn);
585
- simpleCodeColumn.data = {
586
- ...codeColumn.data,
587
- primaryKey: void 0,
588
- indexes: void 0,
589
- excludes: void 0,
590
- foreignKeys: void 0,
591
- check: void 0
592
- };
593
- changeTableData.changingColumns[dbName] = {
594
- from: dbColumn,
595
- to: simpleCodeColumn
596
- };
597
- changeTableData.changeTableAst.shape[key] = {
598
- type: "change",
599
- from: { column: dbColumn },
600
- to: { column: simpleCodeColumn }
601
- };
602
- };
603
- const getColumnDbType = (column, currentSchema) => {
604
- if (column instanceof EnumColumn) {
605
- const [schema = currentSchema, name] = getSchemaAndTableFromName(
606
- currentSchema,
607
- column.enumName
608
- );
609
- return `${schema}.${name}`;
610
- } else if (column instanceof ArrayColumn) {
611
- const { item } = column.data;
612
- let type = item instanceof EnumColumn ? item.enumName : item.dataType;
613
- type = type.startsWith(currentSchema + ".") ? type.slice(currentSchema.length + 1) : type;
614
- return type + "[]".repeat(column.data.arrayDims);
615
- } else if (column.data.isOfCustomType) {
616
- let type = column.dataType;
617
- const i = type.indexOf("(");
618
- if (i !== -1) {
619
- type = type.slice(0, i);
620
- }
621
- return type.includes(".") ? type : currentSchema + "." + type;
622
- } else {
623
- return column.dataType;
624
- }
625
- };
626
- const renameColumn = (columns, from, to) => {
627
- for (let i = 0; i < columns.length; i++) {
628
- if (columns[i] === from) {
629
- columns[i] = to;
630
- }
631
- }
632
- };
633
-
634
- const processDomains = async (ast, adapter, domainsMap, dbStructure, {
635
- codeItems: { domains },
636
- structureToAstCtx,
637
- currentSchema,
638
- internal: { generatorIgnore }
639
- }, pendingDbTypes) => {
640
- const codeDomains = [];
641
- if (domains) {
642
- for (const { schemaName, name, column } of domains) {
643
- codeDomains.push(
644
- makeComparableDomain(currentSchema, schemaName, name, column)
645
- );
646
- }
647
- }
648
- const tableExpressions = [];
649
- const holdCodeDomains = /* @__PURE__ */ new Set();
650
- for (const domain of dbStructure.domains) {
651
- if (generatorIgnore?.schemas?.includes(domain.schemaName) || generatorIgnore?.domains?.includes(domain.name)) {
652
- continue;
653
- }
654
- const dbColumn = instantiateDbColumn(
655
- structureToAstCtx,
656
- dbStructure,
657
- domainsMap,
658
- {
659
- // not destructuring `domain` because need to ignore `numericPrecision`, `numericScale`, etc.,
660
- // that are loaded from db, but not defined in the code
661
- schemaName: domain.typeSchema,
662
- tableName: "N/A",
663
- name: domain.name,
664
- typeSchema: domain.typeSchema,
665
- type: domain.type,
666
- arrayDims: domain.arrayDims,
667
- default: domain.default,
668
- isNullable: domain.isNullable,
669
- collate: domain.collate,
670
- maxChars: domain.maxChars,
671
- typmod: -1
672
- }
673
- );
674
- if (domain.checks) {
675
- dbColumn.data.checks = domain.checks.map((check) => ({
676
- sql: new RawSql([[check]])
677
- }));
678
- }
679
- const dbDomain = makeComparableDomain(
680
- currentSchema,
681
- domain.schemaName,
682
- domain.name,
683
- dbColumn
684
- );
685
- const found = codeDomains.filter(
686
- (codeDomain) => deepCompare(dbDomain.compare, codeDomain.compare)
687
- );
688
- if ((domain.default || domain.checks?.length) && found.length) {
689
- for (const codeDomain of found) {
690
- holdCodeDomains.add(codeDomain);
691
- }
692
- const compare = [];
693
- pushCompareDefault(compare, domain, found);
694
- pushCompareChecks(compare, domain, found);
695
- const source = `(VALUES (NULL::${getColumnDbType(
696
- dbColumn,
697
- currentSchema
698
- )})) t(value)`;
699
- tableExpressions.push({
700
- compare,
701
- source,
702
- handle(i) {
703
- const codeDomain = i === void 0 ? void 0 : found[i];
704
- if (!codeDomain) {
705
- ast.push(dropAst(dbDomain));
706
- } else {
707
- holdCodeDomains.delete(codeDomain);
708
- }
709
- }
710
- });
711
- } else if (found.length) {
712
- let i = codeDomains.findIndex(
713
- (codeDomain) => codeDomain.name === dbDomain.name && codeDomain.schemaName === dbDomain.schemaName
714
- );
715
- if (i === -1) {
716
- i = 0;
717
- const first = found[0];
718
- ast.push({
719
- type: "renameType",
720
- kind: "DOMAIN",
721
- fromSchema: dbDomain.schemaName,
722
- from: dbDomain.name,
723
- toSchema: first.schemaName,
724
- to: first.name
725
- });
726
- pendingDbTypes.add(first.schemaName, first.name);
727
- }
728
- codeDomains.splice(i, 1);
729
- } else {
730
- ast.push(dropAst(dbDomain));
731
- }
732
- }
733
- for (const codeDomain of codeDomains) {
734
- if (!holdCodeDomains.has(codeDomain)) {
735
- ast.push(createAst(codeDomain));
736
- pendingDbTypes.add(codeDomain.schemaName, codeDomain.name);
737
- }
738
- }
739
- if (tableExpressions.length) {
740
- await compareSqlExpressions(tableExpressions, adapter);
741
- if (holdCodeDomains.size) {
742
- for (const codeDomain of holdCodeDomains.keys()) {
743
- ast.push(createAst(codeDomain));
744
- pendingDbTypes.add(codeDomain.schemaName, codeDomain.name);
745
- }
746
- }
747
- }
748
- };
749
- const makeComparableDomain = (currentSchema, schemaName, name, column) => {
750
- let arrayDims = 0;
751
- const isNullable = column.data.isNullable ?? false;
752
- let inner = column;
753
- while (inner instanceof ArrayColumn) {
754
- inner = inner.data.item;
755
- arrayDims++;
756
- }
757
- const fullType = getColumnDbType(inner, currentSchema);
758
- const [typeSchema = "pg_catalog", type] = getSchemaAndTableFromName(
759
- currentSchema,
760
- fullType
761
- );
762
- return {
763
- schemaName,
764
- name,
765
- column,
766
- compare: {
767
- type,
768
- typeSchema,
769
- arrayDims,
770
- isNullable,
771
- maxChars: inner.data.maxChars,
772
- numericPrecision: inner.data.numericPrecision,
773
- numericScale: inner.data.numericScale,
774
- dateTimePrecision: inner.data.dateTimePrecision,
775
- collate: column.data.collate,
776
- hasDefault: column.data.default !== void 0,
777
- hasChecks: !!column.data.checks?.length
778
- }
779
- };
780
- };
781
- const pushCompareDefault = (compare, domain, found) => {
782
- if (domain.default) {
783
- compare.push({
784
- inDb: domain.default,
785
- inCode: found.map((codeDomain) => {
786
- const value = codeDomain.column.data.default;
787
- if ("sql" in value) {
788
- return value.sql;
789
- }
790
- return value;
791
- })
792
- });
793
- }
794
- };
795
- const pushCompareChecks = (compare, domain, found) => {
796
- if (domain.checks?.length) {
797
- const inCode = found.flatMap(
798
- (codeDomain) => codeDomain.column.data.checks?.map(
799
- (check) => typeof check === "string" ? check : check.sql
800
- ) || emptyArray
801
- );
802
- compare.push(
803
- ...domain.checks.map((check) => ({
804
- inDb: check,
805
- inCode
806
- }))
807
- );
808
- }
809
- };
810
- const dropAst = (dbDomain) => ({
811
- type: "domain",
812
- action: "drop",
813
- schema: dbDomain.schemaName,
814
- name: dbDomain.name,
815
- baseType: dbDomain.column
816
- });
817
- const createAst = (codeDomain) => ({
818
- type: "domain",
819
- action: "create",
820
- schema: codeDomain.schemaName,
821
- name: codeDomain.name,
822
- baseType: codeDomain.column
823
- });
824
-
825
- const processEnums = async (ast, dbStructure, {
826
- codeItems: { enums },
827
- currentSchema,
828
- verifying,
829
- internal: { generatorIgnore }
830
- }, pendingDbTypes) => {
831
- const createEnums = [];
832
- const dropEnums = [];
833
- for (const [, codeEnum] of enums) {
834
- const { schema = currentSchema, name } = codeEnum;
835
- const dbEnum = dbStructure.enums.find(
836
- (x) => x.schemaName === schema && x.name === name
837
- );
838
- if (!dbEnum) {
839
- createEnums.push(codeEnum);
840
- }
841
- }
842
- for (const dbEnum of dbStructure.enums) {
843
- if (generatorIgnore?.schemas?.includes(dbEnum.schemaName) || generatorIgnore?.enums?.includes(dbEnum.name)) {
844
- continue;
845
- }
846
- const codeEnum = enums.get(`${dbEnum.schemaName}.${dbEnum.name}`);
847
- if (codeEnum) {
848
- changeEnum(ast, dbEnum, codeEnum, pendingDbTypes);
849
- continue;
850
- }
851
- const i = createEnums.findIndex((x) => x.name === dbEnum.name);
852
- if (i !== -1) {
853
- const codeEnum2 = createEnums[i];
854
- createEnums.splice(i, 1);
855
- const fromSchema = dbEnum.schemaName;
856
- const toSchema = codeEnum2.schema ?? currentSchema;
857
- renameColumnsTypeSchema(dbStructure, fromSchema, toSchema);
858
- ast.push({
859
- type: "renameType",
860
- kind: "TYPE",
861
- fromSchema,
862
- from: dbEnum.name,
863
- toSchema,
864
- to: dbEnum.name
865
- });
866
- pendingDbTypes.add(toSchema, dbEnum.name);
867
- changeEnum(ast, dbEnum, codeEnum2, pendingDbTypes);
868
- continue;
869
- }
870
- dropEnums.push(dbEnum);
871
- }
872
- for (const codeEnum of createEnums) {
873
- if (dropEnums.length) {
874
- const i = await promptCreateOrRename(
875
- "enum",
876
- codeEnum.name,
877
- dropEnums.map((x) => x.name),
878
- verifying
879
- );
880
- if (i) {
881
- const dbEnum = dropEnums[i - 1];
882
- dropEnums.splice(i - 1, 1);
883
- const fromSchema = dbEnum.schemaName;
884
- const from = dbEnum.name;
885
- const toSchema = codeEnum.schema ?? currentSchema;
886
- const to = codeEnum.name;
887
- if (fromSchema !== toSchema) {
888
- renameColumnsTypeSchema(dbStructure, fromSchema, toSchema);
889
- }
890
- for (const table of dbStructure.tables) {
891
- for (const column of table.columns) {
892
- if (column.type === from) {
893
- column.type = to;
894
- }
895
- }
896
- }
897
- ast.push({
898
- type: "renameType",
899
- kind: "TYPE",
900
- fromSchema,
901
- from,
902
- toSchema,
903
- to
904
- });
905
- pendingDbTypes.add(toSchema, to);
906
- changeEnum(ast, dbEnum, codeEnum, pendingDbTypes);
907
- continue;
908
- }
909
- }
910
- ast.push({
911
- type: "enum",
912
- action: "create",
913
- ...codeEnum
914
- });
915
- pendingDbTypes.add(codeEnum.schema, codeEnum.name);
916
- }
917
- for (const dbEnum of dropEnums) {
918
- ast.push({
919
- type: "enum",
920
- action: "drop",
921
- schema: dbEnum.schemaName,
922
- name: dbEnum.name,
923
- values: dbEnum.values
924
- });
925
- }
926
- };
927
- const changeEnum = (ast, dbEnum, codeEnum, pendingDbTypes) => {
928
- const { values: dbValues } = dbEnum;
929
- const { values: codeValues, schema, name } = codeEnum;
930
- if (dbValues.length < codeValues.length) {
931
- if (!dbValues.some((value) => !codeValues.includes(value))) {
932
- ast.push({
933
- type: "enumValues",
934
- action: "add",
935
- schema,
936
- name,
937
- values: codeValues.filter((value) => !dbValues.includes(value))
938
- });
939
- pendingDbTypes.add(schema, name);
940
- return;
941
- }
942
- } else if (dbValues.length > codeValues.length) {
943
- if (!codeValues.some((value) => !dbValues.includes(value))) {
944
- ast.push({
945
- type: "enumValues",
946
- action: "drop",
947
- schema,
948
- name,
949
- values: dbValues.filter((value) => !codeValues.includes(value))
950
- });
951
- pendingDbTypes.add(schema, name);
952
- return;
953
- }
954
- } else if (!dbValues.some((value) => !codeValues.includes(value))) {
955
- return;
956
- }
957
- ast.push({
958
- type: "changeEnumValues",
959
- schema,
960
- name,
961
- fromValues: dbValues,
962
- toValues: codeValues
963
- });
964
- pendingDbTypes.add(schema, name);
965
- };
966
- const renameColumnsTypeSchema = (dbStructure, from, to) => {
967
- for (const table of dbStructure.tables) {
968
- for (const column of table.columns) {
969
- if (column.typeSchema === from) {
970
- column.typeSchema = to;
971
- }
972
- }
973
- }
974
- };
975
-
976
- const processPrimaryKey = (config, changeTableData) => {
977
- const { codeTable } = changeTableData;
978
- const columnsPrimaryKey = [];
979
- for (const key in codeTable.shape) {
980
- const column = codeTable.shape[key];
981
- if (column.data.primaryKey) {
982
- columnsPrimaryKey.push({ key, name: column.data.name ?? key });
983
- }
984
- }
985
- changePrimaryKey(config, columnsPrimaryKey, changeTableData);
986
- renamePrimaryKey(changeTableData);
987
- };
988
- const changePrimaryKey = (config, columnsPrimaryKey, {
989
- codeTable,
990
- dbTableData: { primaryKey: dbPrimaryKey },
991
- changeTableAst: { shape, add, drop },
992
- changingColumns
993
- }) => {
994
- const tablePrimaryKey = codeTable.internal.tableData.primaryKey;
995
- const primaryKey = [
996
- .../* @__PURE__ */ new Set([
997
- ...columnsPrimaryKey,
998
- ...(config.snakeCase ? tablePrimaryKey?.columns.map((key) => ({
999
- key,
1000
- name: toSnakeCase(key)
1001
- })) : tablePrimaryKey?.columns.map((key) => ({ key, name: key }))) ?? []
1002
- ])
1003
- ];
1004
- if (dbPrimaryKey && primaryKey.length === dbPrimaryKey.columns.length && !primaryKey.some(
1005
- ({ name }) => !dbPrimaryKey.columns.some((dbName) => name === dbName)
1006
- )) {
1007
- if (primaryKey.length === 1) {
1008
- const { key } = primaryKey[0];
1009
- const changes = shape[key] && toArray(shape[key]);
1010
- if (changes) {
1011
- for (const change of changes) {
1012
- if (change.type !== "change") continue;
1013
- if (change.from.column) {
1014
- change.from.column.data.primaryKey = void 0;
1015
- }
1016
- if (change.to.column) {
1017
- const column = Object.create(change.to.column);
1018
- column.data = { ...column.data, primaryKey: void 0 };
1019
- change.to.column = column;
1020
- }
1021
- }
1022
- }
1023
- }
1024
- return;
1025
- }
1026
- const toDrop = dbPrimaryKey?.columns.filter(
1027
- (key) => !checkForColumnAddOrDrop(shape, key)
1028
- );
1029
- if (toDrop?.length) {
1030
- if (toDrop.length === 1 && changingColumns[toDrop[0]]) {
1031
- const column = changingColumns[toDrop[0]];
1032
- column.from.data.primaryKey = dbPrimaryKey?.name ?? true;
1033
- } else {
1034
- drop.primaryKey = { columns: toDrop, name: dbPrimaryKey?.name };
1035
- }
1036
- }
1037
- const toAdd = primaryKey.filter(
1038
- ({ key }) => !checkForColumnAddOrDrop(shape, key)
1039
- );
1040
- if (toAdd.length) {
1041
- if (toAdd.length === 1 && changingColumns[toAdd[0].name]) {
1042
- const column = changingColumns[toAdd[0].name];
1043
- column.to.data.primaryKey = tablePrimaryKey?.name ?? true;
1044
- } else {
1045
- add.primaryKey = {
1046
- columns: toAdd.map((c) => c.key),
1047
- name: tablePrimaryKey?.name
1048
- };
1049
- }
1050
- }
1051
- };
1052
- const renamePrimaryKey = ({
1053
- codeTable,
1054
- dbTableData: { primaryKey: dbPrimaryKey },
1055
- schema,
1056
- delayedAst
1057
- }) => {
1058
- const tablePrimaryKey = codeTable.internal.tableData.primaryKey;
1059
- if (dbPrimaryKey && tablePrimaryKey && dbPrimaryKey?.name !== tablePrimaryKey?.name) {
1060
- delayedAst.push({
1061
- type: "renameTableItem",
1062
- kind: "CONSTRAINT",
1063
- tableSchema: schema,
1064
- tableName: codeTable.table,
1065
- from: dbPrimaryKey.name ?? `${codeTable.table}_pkey`,
1066
- to: tablePrimaryKey.name ?? `${codeTable}_pkey`
1067
- });
1068
- }
1069
- };
1070
-
1071
- const processIndexesAndExcludes = (config, changeTableData, ast, compareExpressions) => {
1072
- const codeItems = collectCodeIndexes(config, changeTableData);
1073
- const codeComparableItems = collectCodeComparableItems(config, codeItems);
1074
- const skipCodeItems = {
1075
- indexes: /* @__PURE__ */ new Map(),
1076
- excludes: /* @__PURE__ */ new Map()
1077
- };
1078
- const holdCodeItems = {
1079
- indexes: /* @__PURE__ */ new Map(),
1080
- excludes: /* @__PURE__ */ new Map()
1081
- };
1082
- const processParams = {
1083
- config,
1084
- changeTableData,
1085
- codeComparableItems,
1086
- codeItems,
1087
- skipCodeItems,
1088
- holdCodeItems,
1089
- // counter for async SQL comparisons that are in progress
1090
- wait: { indexes: 0, excludes: 0 },
1091
- ast,
1092
- compareExpressions
1093
- };
1094
- processItems(processParams, "indexes");
1095
- processItems(processParams, "excludes");
1096
- addMainItems(
1097
- changeTableData,
1098
- codeItems,
1099
- skipCodeItems,
1100
- holdCodeItems,
1101
- "indexes"
1102
- );
1103
- addMainItems(
1104
- changeTableData,
1105
- codeItems,
1106
- skipCodeItems,
1107
- holdCodeItems,
1108
- "excludes"
1109
- );
1110
- };
1111
- const processItems = ({
1112
- config,
1113
- changeTableData,
1114
- codeComparableItems,
1115
- codeItems,
1116
- skipCodeItems,
1117
- holdCodeItems,
1118
- wait,
1119
- ast,
1120
- compareExpressions
1121
- }, key) => {
1122
- const {
1123
- changeTableAst: { shape }
1124
- } = changeTableData;
1125
- const dbItems = changeTableData.dbTableData[key];
1126
- for (const dbItem of dbItems) {
1127
- const hasAddedOrDroppedColumn = dbItem.columns.some(
1128
- (column) => "column" in column && checkForColumnAddOrDrop(shape, column.column)
1129
- );
1130
- if (hasAddedOrDroppedColumn) continue;
1131
- normalizeItem(dbItem);
1132
- const { found, rename, foundAndHasSql } = findMatchingItem(
1133
- dbItem,
1134
- codeComparableItems,
1135
- codeItems,
1136
- skipCodeItems,
1137
- changeTableData.codeTable.table,
1138
- config,
1139
- key
1140
- );
1141
- const { columns: dbColumns } = dbItem;
1142
- if (!foundAndHasSql) {
1143
- handleItemChange(
1144
- changeTableData,
1145
- dbItem,
1146
- dbColumns,
1147
- found[0],
1148
- rename[0],
1149
- key
1150
- );
1151
- continue;
1152
- }
1153
- for (const codeItem of found) {
1154
- holdCodeItems[key].set(codeItem, true);
1155
- }
1156
- const compare = [];
1157
- for (let i = 0; i < dbItem.columns.length; i++) {
1158
- const column = dbItem.columns[i];
1159
- if (!("expression" in column)) continue;
1160
- compare.push({
1161
- inDb: column.expression,
1162
- inCode: found.map(
1163
- (x) => x.columns[i].expression
1164
- )
1165
- });
1166
- }
1167
- if (dbItem.with) {
1168
- compare.push({
1169
- inDb: dbItem.with,
1170
- inCode: found.map((x) => x.options.with)
1171
- });
1172
- }
1173
- if (dbItem.where) {
1174
- compare.push({
1175
- inDb: dbItem.where,
1176
- inCode: found.map((x) => x.options.where)
1177
- });
1178
- }
1179
- wait[key]++;
1180
- compareExpressions.push({
1181
- compare,
1182
- handle(i) {
1183
- const codeItem = i === void 0 ? void 0 : found[i];
1184
- handleItemChange(
1185
- changeTableData,
1186
- dbItem,
1187
- dbColumns,
1188
- codeItem,
1189
- i === void 0 ? void 0 : rename[i],
1190
- key
1191
- );
1192
- if (codeItem) {
1193
- holdCodeItems[key].delete(codeItem);
1194
- }
1195
- if (!--wait[key] && holdCodeItems[key].size) {
1196
- addItems(changeTableData, [...holdCodeItems[key].keys()], key);
1197
- if (!changeTableData.pushedAst) {
1198
- changeTableData.pushedAst = true;
1199
- ast.push(changeTableData.changeTableAst);
1200
- }
1201
- }
1202
- }
1203
- });
1204
- }
1205
- };
1206
- const collectCodeIndexes = (config, { codeTable, changeTableAst: { shape } }) => {
1207
- const codeItems = { indexes: [], excludes: [] };
1208
- for (const key in codeTable.shape) {
1209
- const column = codeTable.shape[key];
1210
- if (!column.data.indexes && !column.data.excludes) continue;
1211
- const name = column.data.name ?? key;
1212
- if (checkForColumnAddOrDrop(shape, name)) continue;
1213
- pushCodeColumnItems(config, codeItems, key, name, column, "indexes");
1214
- pushCodeColumnItems(config, codeItems, key, name, column, "excludes");
1215
- }
1216
- pushCodeCompositeItems(config, codeTable, codeItems, "indexes");
1217
- pushCodeCompositeItems(config, codeTable, codeItems, "excludes");
1218
- return codeItems;
1219
- };
1220
- const pushCodeColumnItems = (config, codeItems, columnKey, name, column, key) => {
1221
- const items = column.data[key];
1222
- if (!items) return;
1223
- codeItems[key].push(
1224
- ...items.map(
1225
- ({
1226
- options: { collate, opclass, order, weight, ...options },
1227
- with: wi,
1228
- ...index
1229
- }) => {
1230
- const w = key === "excludes" ? wi : void 0;
1231
- return {
1232
- columns: [
1233
- {
1234
- collate,
1235
- opclass,
1236
- order,
1237
- weight,
1238
- column: name,
1239
- with: w
1240
- }
1241
- ],
1242
- ...index,
1243
- options: options.include ? config.snakeCase ? {
1244
- ...options,
1245
- include: toArray(options.include).map(toSnakeCase)
1246
- } : options : options,
1247
- columnKeys: [
1248
- {
1249
- collate,
1250
- opclass,
1251
- order,
1252
- weight,
1253
- column: columnKey,
1254
- with: w
1255
- }
1256
- ],
1257
- includeKeys: options.include
1258
- };
1259
- }
1260
- )
1261
- );
1262
- };
1263
- const pushCodeCompositeItems = (config, codeTable, codeItems, key) => {
1264
- const items = codeTable.internal.tableData[key];
1265
- if (!items) return;
1266
- codeItems[key].push(
1267
- ...items.map((x) => ({
1268
- ...x,
1269
- columns: config.snakeCase ? x.columns.map(
1270
- (c) => "column" in c ? { ...c, column: toSnakeCase(c.column) } : c
1271
- ) : x.columns,
1272
- columnKeys: x.columns,
1273
- options: x.options.include && config.snakeCase ? {
1274
- ...x.options,
1275
- include: toArray(x.options.include).map(toSnakeCase)
1276
- } : x.options,
1277
- includeKeys: x.options.include
1278
- }))
1279
- );
1280
- };
1281
- const collectCodeComparableItems = (config, codeItems) => {
1282
- return {
1283
- indexes: collectCodeComparableItemsType(config, codeItems, "indexes"),
1284
- excludes: collectCodeComparableItemsType(config, codeItems, "excludes")
1285
- };
1286
- };
1287
- const collectCodeComparableItemsType = (config, codeItems, key) => {
1288
- return codeItems[key].map((codeItem) => {
1289
- normalizeItem(codeItem.options);
1290
- return itemToComparable({
1291
- ...codeItem.options,
1292
- include: codeItem.options.include === void 0 ? void 0 : config.snakeCase ? toArray(codeItem.options.include).map(toSnakeCase) : toArray(codeItem.options.include),
1293
- columns: codeItem.columns,
1294
- name: codeItem.options.name,
1295
- columnKeys: codeItem.columnKeys,
1296
- includeKeys: codeItem.includeKeys
1297
- });
1298
- });
1299
- };
1300
- const normalizeItem = (item) => {
1301
- if (item.using) item.using = item.using.toLowerCase();
1302
- if (item.using === "btree") item.using = void 0;
1303
- if (!item.unique) item.unique = void 0;
1304
- if (item.nullsNotDistinct === false) item.nullsNotDistinct = void 0;
1305
- if (item.exclude) {
1306
- for (let i = 0; i < item.columns.length; i++) {
1307
- item.columns[i].with = item.exclude[i];
1308
- }
1309
- }
1310
- };
1311
- const itemToComparable = (index) => {
1312
- let hasExpression = false;
1313
- const columns = index.columns.map((column) => {
1314
- const result = {
1315
- ...column,
1316
- expression: void 0,
1317
- hasExpression: "expression" in column
1318
- };
1319
- if (result.hasExpression) hasExpression = true;
1320
- return result;
1321
- });
1322
- return {
1323
- ...index,
1324
- schemaName: void 0,
1325
- tableName: void 0,
1326
- with: void 0,
1327
- hasWith: !!index.with,
1328
- where: void 0,
1329
- hasWhere: !!index.where,
1330
- columns,
1331
- hasExpression
1332
- };
1333
- };
1334
- const findMatchingItem = (dbItem, codeComparableItems, codeItems, skipCodeItems, tableName, config, key) => {
1335
- const dbComparableItem = itemToComparable(
1336
- key === "indexes" ? dbItem : {
1337
- ...dbItem,
1338
- exclude: void 0,
1339
- columns: dbItem.columns.map((column, i) => ({
1340
- ...column,
1341
- with: dbItem.exclude[i]
1342
- }))
1343
- }
1344
- );
1345
- const { found, rename } = findMatchingItemWithoutSql(
1346
- dbComparableItem,
1347
- codeComparableItems,
1348
- codeItems,
1349
- skipCodeItems,
1350
- tableName,
1351
- config,
1352
- key
1353
- );
1354
- const foundAndHasSql = found.length && checkIfItemHasSql(dbComparableItem);
1355
- return { found, rename, foundAndHasSql };
1356
- };
1357
- const findMatchingItemWithoutSql = (dbItem, codeComparableItems, codeItems, skipCodeItems, tableName, config, key) => {
1358
- const found = [];
1359
- const rename = [];
1360
- const { columns: dbColumns, ...dbItemWithoutColumns } = dbItem;
1361
- for (let i = 0; i < codeComparableItems[key].length; i++) {
1362
- if (skipCodeItems[key].has(i)) continue;
1363
- const { columns: codeColumns, ...codeItem } = codeComparableItems[key][i];
1364
- if (dbColumns.length === codeColumns.length && !dbColumns.some((dbColumn, i2) => !deepCompare(dbColumn, codeColumns[i2]))) {
1365
- let a = dbItemWithoutColumns;
1366
- let b = codeItem;
1367
- const codeName = b.name ?? (key === "indexes" ? getIndexName : getExcludeName)(
1368
- tableName,
1369
- dbColumns
1370
- );
1371
- if (a.name !== b.name) {
1372
- a = { ...a, name: void 0 };
1373
- b = {
1374
- ...b,
1375
- name: void 0,
1376
- columnKeys: void 0,
1377
- includeKeys: void 0
1378
- };
1379
- if (a.language && !b.language) {
1380
- b.language = config.language ?? "english";
1381
- }
1382
- if (deepCompare(a, b)) {
1383
- found.push(codeItems[key][i]);
1384
- rename.push(
1385
- dbItemWithoutColumns.name !== codeName ? codeName : void 0
1386
- );
1387
- }
1388
- } else {
1389
- const {
1390
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1391
- columnKeys,
1392
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1393
- includeKeys,
1394
- ...codeItemWithoutKeys
1395
- } = codeItem;
1396
- if (deepCompare(dbItemWithoutColumns, codeItemWithoutKeys)) {
1397
- found.push(codeItems[key][i]);
1398
- rename.push(void 0);
1399
- }
1400
- }
1401
- if (found.length && !checkIfItemHasSql(codeItem)) {
1402
- skipCodeItems[key].set(i, true);
1403
- }
1404
- }
1405
- }
1406
- return { found, rename };
1407
- };
1408
- const checkIfItemHasSql = (x) => x.hasWith || x.hasWhere || x.hasExpression;
1409
- const handleItemChange = ({
1410
- changeTableAst,
1411
- schema,
1412
- codeTable,
1413
- changingColumns,
1414
- delayedAst
1415
- }, dbItem, dbColumns, found, rename, key) => {
1416
- var _a, _b;
1417
- if (!found) {
1418
- const name = dbItem.name === (key === "indexes" ? getIndexName : getExcludeName)(
1419
- changeTableAst.name,
1420
- dbColumns
1421
- ) ? void 0 : dbItem.name;
1422
- if (dbColumns.length === 1 && "column" in dbColumns[0]) {
1423
- const dbColumn = dbColumns[0];
1424
- const column = changingColumns[dbColumn.column];
1425
- if (column) {
1426
- ((_a = column.from.data)[key] ?? (_a[key] = [])).push({
1427
- options: { ...dbItem, name },
1428
- with: key === "indexes" ? void 0 : dbColumn.with
1429
- });
1430
- return;
1431
- }
1432
- }
1433
- ((_b = changeTableAst.drop)[key] ?? (_b[key] = [])).push({
1434
- columns: dbColumns,
1435
- options: { ...dbItem, name }
1436
- });
1437
- } else if (rename) {
1438
- delayedAst.push({
1439
- type: "renameTableItem",
1440
- kind: key === "indexes" ? "INDEX" : "CONSTRAINT",
1441
- tableSchema: schema,
1442
- tableName: codeTable.table,
1443
- from: dbItem.name,
1444
- to: rename
1445
- });
1446
- }
1447
- };
1448
- const addMainItems = (changeTableData, codeItems, skipCodeItems, holdCodeItems, key) => {
1449
- const itemsToAdd = codeItems[key].filter(
1450
- (item, i) => !skipCodeItems[key].has(i) && !holdCodeItems[key].has(item)
1451
- );
1452
- if (itemsToAdd.length) {
1453
- addItems(
1454
- changeTableData,
1455
- itemsToAdd.map((x) => ({
1456
- ...x,
1457
- columns: x.columnKeys,
1458
- columnNames: x.columns,
1459
- options: x.options.include ? { ...x.options, include: x.includeKeys } : x.options
1460
- })),
1461
- key
1462
- );
1463
- }
1464
- };
1465
- const addItems = ({ changeTableAst, changingColumns }, add, key) => {
1466
- var _a, _b;
1467
- const items = (_a = changeTableAst.add)[key] ?? (_a[key] = []);
1468
- for (const item of add) {
1469
- if (item.columns.length === 1 && "column" in item.columns[0]) {
1470
- const column = changingColumns[(item.columnNames || item.columns)[0].column];
1471
- if (column) {
1472
- ((_b = column.to.data)[key] ?? (_b[key] = [])).push(
1473
- key === "indexes" ? item : {
1474
- ...item,
1475
- with: item.columns[0].with
1476
- }
1477
- );
1478
- continue;
1479
- }
1480
- }
1481
- items.push(item);
1482
- }
1483
- };
1484
-
1485
- const mapMatchToDb = {
1486
- FULL: "f",
1487
- PARTIAL: "p",
1488
- SIMPLE: "s"
1489
- };
1490
- const mapMatchToCode = {};
1491
- for (const key in mapMatchToDb) {
1492
- mapMatchToCode[mapMatchToDb[key]] = key;
1493
- }
1494
- const mapActionToDb = {
1495
- "NO ACTION": "a",
1496
- RESTRICT: "r",
1497
- CASCADE: "c",
1498
- "SET NULL": "n",
1499
- "SET DEFAULT": "d"
1500
- };
1501
- const mapActionToCode = {};
1502
- for (const key in mapActionToDb) {
1503
- mapActionToCode[mapActionToDb[key]] = key;
1504
- }
1505
- const processForeignKeys = (config, ast, changeTables, currentSchema, tableShapes) => {
1506
- var _a, _b;
1507
- for (const changeTableData of changeTables) {
1508
- const codeForeignKeys = collectCodeFkeys(
1509
- config,
1510
- changeTableData,
1511
- currentSchema
1512
- );
1513
- const { codeTable, dbTableData, changeTableAst, schema, changingColumns } = changeTableData;
1514
- const { shape, add, drop } = changeTableAst;
1515
- let changed = false;
1516
- for (const dbConstraint of dbTableData.constraints) {
1517
- const { references: dbReferences } = dbConstraint;
1518
- if (!dbReferences) continue;
1519
- const hasChangedColumn = dbReferences.columns.some(
1520
- (column) => checkForColumnAddOrDrop(shape, column)
1521
- );
1522
- if (hasChangedColumn) continue;
1523
- const foreignShape = tableShapes[`${dbReferences.foreignSchema}.${dbReferences.foreignTable}`];
1524
- const hasForeignChangedColumn = foreignShape && dbReferences.foreignColumns.some((column) => {
1525
- return checkForColumnAddOrDrop(foreignShape, column);
1526
- });
1527
- if (hasForeignChangedColumn) continue;
1528
- let found = false;
1529
- let rename;
1530
- for (let i = 0; i < codeForeignKeys.length; i++) {
1531
- const codeForeignKey = codeForeignKeys[i];
1532
- const codeReferences = codeForeignKey.references;
1533
- if (deepCompare(dbReferences, codeReferences)) {
1534
- found = true;
1535
- codeForeignKeys.splice(i, 1);
1536
- const codeName = codeForeignKey.codeConstraint.name ?? getConstraintName(
1537
- codeTable.table,
1538
- codeForeignKey,
1539
- config.snakeCase
1540
- );
1541
- if (codeName !== dbConstraint.name) {
1542
- rename = codeName;
1543
- }
1544
- }
1545
- }
1546
- if (!found) {
1547
- const foreignKey = dbForeignKeyToCodeForeignKey(
1548
- config,
1549
- dbConstraint,
1550
- dbReferences
1551
- );
1552
- if (dbReferences.columns.length === 1 && changingColumns[dbReferences.columns[0]]) {
1553
- const column = changingColumns[dbReferences.columns[0]];
1554
- ((_a = column.from.data).foreignKeys ?? (_a.foreignKeys = [])).push({
1555
- fnOrTable: foreignKey.references.fnOrTable,
1556
- foreignColumns: foreignKey.references.foreignColumns,
1557
- options: foreignKey.references.options
1558
- });
1559
- } else {
1560
- (drop.constraints ?? (drop.constraints = [])).push(foreignKey);
1561
- }
1562
- changed = true;
1563
- } else if (rename) {
1564
- ast.push({
1565
- type: "renameTableItem",
1566
- kind: "CONSTRAINT",
1567
- tableSchema: schema,
1568
- tableName: codeTable.table,
1569
- from: dbConstraint.name,
1570
- to: rename
1571
- });
1572
- }
1573
- }
1574
- if (codeForeignKeys.length) {
1575
- const constraints = add.constraints ?? (add.constraints = []);
1576
- for (const { codeConstraint, references } of codeForeignKeys) {
1577
- if (references.columns.length === 1 && changingColumns[references.columns[0]]) {
1578
- const column = changingColumns[references.columns[0]];
1579
- ((_b = column.to.data).foreignKeys ?? (_b.foreignKeys = [])).push({
1580
- fnOrTable: references.foreignTable,
1581
- foreignColumns: codeConstraint.references.foreignColumns,
1582
- options: codeConstraint.references.options
1583
- });
1584
- } else {
1585
- constraints.push(codeConstraint);
1586
- }
1587
- }
1588
- changed = true;
1589
- }
1590
- if (changed && !changeTableData.pushedAst) {
1591
- changeTableData.pushedAst = true;
1592
- ast.push(changeTableData.changeTableAst);
1593
- }
1594
- }
1595
- };
1596
- const collectCodeFkeys = (config, { codeTable, changeTableAst: { shape } }, currentSchema) => {
1597
- const codeForeignKeys = [];
1598
- for (const key in codeTable.shape) {
1599
- const column = codeTable.shape[key];
1600
- if (!column.data.foreignKeys) continue;
1601
- const name = column.data.name ?? key;
1602
- if (checkForColumnAddOrDrop(shape, name)) continue;
1603
- codeForeignKeys.push(
1604
- ...column.data.foreignKeys.map((x) => {
1605
- const columns = [name];
1606
- const fnOrTable = fnOrTableToString(x.fnOrTable);
1607
- return parseForeignKey(
1608
- config,
1609
- {
1610
- name: x.options?.name,
1611
- references: {
1612
- columns: [name],
1613
- fnOrTable,
1614
- foreignColumns: x.foreignColumns,
1615
- options: x.options
1616
- }
1617
- },
1618
- {
1619
- columns,
1620
- fnOrTable,
1621
- foreignColumns: x.foreignColumns,
1622
- options: x.options
1623
- },
1624
- currentSchema
1625
- );
1626
- })
1627
- );
1628
- }
1629
- if (codeTable.internal.tableData.constraints) {
1630
- for (const tableConstraint of codeTable.internal.tableData.constraints) {
1631
- const { references: refs } = tableConstraint;
1632
- if (!refs) continue;
1633
- const fnOrTable = fnOrTableToString(refs.fnOrTable);
1634
- codeForeignKeys.push(
1635
- parseForeignKey(
1636
- config,
1637
- {
1638
- ...tableConstraint,
1639
- references: {
1640
- ...refs,
1641
- fnOrTable
1642
- }
1643
- },
1644
- {
1645
- ...refs,
1646
- fnOrTable,
1647
- columns: config.snakeCase ? refs.columns.map(toSnakeCase) : refs.columns,
1648
- foreignColumns: config.snakeCase ? refs.foreignColumns.map(toSnakeCase) : refs.foreignColumns
1649
- },
1650
- currentSchema
1651
- )
1652
- );
1653
- }
1654
- }
1655
- return codeForeignKeys;
1656
- };
1657
- const fnOrTableToString = (fnOrTable) => {
1658
- if (typeof fnOrTable !== "string") {
1659
- const { schema, table } = new (fnOrTable())();
1660
- fnOrTable = concatSchemaAndName({ schema, name: table });
1661
- }
1662
- return fnOrTable;
1663
- };
1664
- const parseForeignKey = (config, codeConstraint, references, currentSchema) => {
1665
- const { fnOrTable, columns, foreignColumns, options } = references;
1666
- const [schema, table] = getSchemaAndTableFromName(currentSchema, fnOrTable);
1667
- return {
1668
- references: {
1669
- foreignSchema: schema ?? currentSchema,
1670
- foreignTable: table,
1671
- columns,
1672
- foreignColumns: config.snakeCase ? foreignColumns.map(toSnakeCase) : foreignColumns,
1673
- match: mapMatchToDb[options?.match || "SIMPLE"],
1674
- onUpdate: mapActionToDb[options?.onUpdate || "NO ACTION"],
1675
- onDelete: mapActionToDb[options?.onDelete || "NO ACTION"]
1676
- },
1677
- codeConstraint
1678
- };
1679
- };
1680
- const dbForeignKeyToCodeForeignKey = (config, dbConstraint, dbReferences) => ({
1681
- name: dbConstraint.name === getConstraintName(
1682
- dbConstraint.tableName,
1683
- { references: dbReferences },
1684
- config.snakeCase
1685
- ) ? void 0 : dbConstraint.name,
1686
- references: {
1687
- columns: dbReferences.columns,
1688
- fnOrTable: `${dbReferences.foreignSchema}.${dbReferences.foreignTable}`,
1689
- foreignColumns: dbReferences.foreignColumns,
1690
- options: {
1691
- match: dbReferences.match === "s" ? void 0 : mapMatchToCode[dbReferences.match],
1692
- onUpdate: dbReferences.onUpdate === "a" ? void 0 : mapActionToCode[dbReferences.onUpdate],
1693
- onDelete: dbReferences.onDelete === "a" ? void 0 : mapActionToCode[dbReferences.onDelete]
1694
- }
1695
- }
1696
- });
1697
-
1698
- const processChecks = (ast, changeTableData, compareExpressions) => {
1699
- const codeChecks = collectCodeChecks(changeTableData);
1700
- const {
1701
- dbTableData,
1702
- changeTableAst: { add, shape }
1703
- } = changeTableData;
1704
- const hasDbChecks = dbTableData.constraints.some((c) => c.check);
1705
- if (!hasDbChecks) {
1706
- if (codeChecks.length) {
1707
- const constraints = add.constraints ?? (add.constraints = []);
1708
- for (const codeCheck of codeChecks) {
1709
- if (!codeCheck.column || !changeTableData.changingColumns[codeCheck.column]) {
1710
- constraints.push({
1711
- check: codeCheck.check.sql,
1712
- name: codeCheck.name
1713
- });
1714
- }
1715
- }
1716
- }
1717
- return;
1718
- }
1719
- let wait = 0;
1720
- const foundCodeChecks = /* @__PURE__ */ new Set();
1721
- for (const dbConstraint of dbTableData.constraints) {
1722
- const { check: dbCheck, name } = dbConstraint;
1723
- if (!dbCheck) continue;
1724
- const hasChangedColumn = dbCheck.columns?.some(
1725
- (column) => checkForColumnAddOrDrop(shape, column)
1726
- );
1727
- if (hasChangedColumn) continue;
1728
- if (codeChecks.length) {
1729
- wait++;
1730
- compareExpressions.push({
1731
- compare: [
1732
- {
1733
- inDb: dbCheck.expression,
1734
- inCode: codeChecks.map(({ check }) => check.sql)
1735
- }
1736
- ],
1737
- handle(i) {
1738
- if (i !== void 0) {
1739
- foundCodeChecks.add(i);
1740
- } else {
1741
- dropCheck(changeTableData, dbCheck, name);
1742
- }
1743
- if (--wait !== 0) return;
1744
- const checksToAdd = [];
1745
- codeChecks.forEach((check, i2) => {
1746
- if (foundCodeChecks.has(i2)) {
1747
- if (!check.column) return;
1748
- const change = changeTableData.changingColumns[check.column];
1749
- if (!change) return;
1750
- const columnChecks = change.to.data.checks;
1751
- if (!columnChecks) return;
1752
- const i3 = columnChecks.indexOf(check.check);
1753
- if (i3 !== -1) {
1754
- columnChecks.splice(i3, 1);
1755
- }
1756
- return;
1757
- }
1758
- checksToAdd.push({
1759
- name: check.name,
1760
- check: check.check.sql
1761
- });
1762
- });
1763
- if (checksToAdd.length) {
1764
- (add.constraints ?? (add.constraints = [])).push(...checksToAdd);
1765
- }
1766
- if (!changeTableData.pushedAst && (changeTableData.changeTableAst.drop.constraints?.length || add.constraints?.length)) {
1767
- changeTableData.pushedAst = true;
1768
- ast.push(changeTableData.changeTableAst);
1769
- }
1770
- }
1771
- });
1772
- } else {
1773
- dropCheck(changeTableData, dbCheck, name);
1774
- }
1775
- }
1776
- };
1777
- const collectCodeChecks = ({
1778
- codeTable,
1779
- changeTableAst: { shape }
1780
- }) => {
1781
- const names = /* @__PURE__ */ new Set();
1782
- const codeChecks = [];
1783
- for (const key in codeTable.shape) {
1784
- const column = codeTable.shape[key];
1785
- if (!column.data.checks) continue;
1786
- const columnName = column.data.name ?? key;
1787
- if (checkForColumnAddOrDrop(shape, columnName)) continue;
1788
- const baseName = `${codeTable.table}_${columnName}_check`;
1789
- codeChecks.push(
1790
- ...column.data.checks.map((check) => {
1791
- const name = check.name || getFreeSetAlias(names, baseName, 1);
1792
- names.add(name);
1793
- return {
1794
- check,
1795
- name,
1796
- column: columnName
1797
- };
1798
- })
1799
- );
1800
- }
1801
- if (codeTable.internal.tableData.constraints) {
1802
- for (const constraint of codeTable.internal.tableData.constraints) {
1803
- const { check } = constraint;
1804
- if (check) {
1805
- const baseName = `${codeTable.table}_check`;
1806
- const name = constraint.name || getFreeSetAlias(names, baseName, 1);
1807
- names.add(name);
1808
- codeChecks.push({
1809
- check: { sql: check, name: constraint.name },
1810
- name
1811
- });
1812
- }
1813
- }
1814
- }
1815
- return codeChecks;
1816
- };
1817
- const dropCheck = ({ changeTableAst: { drop }, changingColumns }, dbCheck, name) => {
1818
- var _a;
1819
- const sql = new RawSql([
1820
- [dbCheck.expression]
1821
- ]);
1822
- if (dbCheck.columns?.length === 1 && changingColumns[dbCheck.columns[0]]) {
1823
- const column = changingColumns[dbCheck.columns[0]];
1824
- column.from.data.name = "i_d";
1825
- ((_a = column.from.data).checks ?? (_a.checks = [])).push({
1826
- name,
1827
- sql
1828
- });
1829
- } else {
1830
- (drop.constraints ?? (drop.constraints = [])).push({
1831
- name,
1832
- check: sql
1833
- });
1834
- }
1835
- };
1836
-
1837
- const processTables = async (ast, domainsMap, adapter, dbStructure, config, {
1838
- structureToAstCtx,
1839
- codeItems: { tables },
1840
- currentSchema,
1841
- internal: { generatorIgnore },
1842
- verifying
1843
- }, pendingDbTypes) => {
1844
- const createTables = collectCreateTables(
1845
- tables,
1846
- dbStructure,
1847
- currentSchema
1848
- );
1849
- const compareSql = { values: [], expressions: [] };
1850
- const tableExpressions = [];
1851
- const { changeTables, changeTableSchemas, dropTables, tableShapes } = collectChangeAndDropTables(
1852
- adapter,
1853
- config,
1854
- tables,
1855
- dbStructure,
1856
- currentSchema,
1857
- createTables,
1858
- generatorIgnore
1859
- );
1860
- applyChangeTableSchemas(changeTableSchemas, currentSchema, ast);
1861
- await applyCreateOrRenameTables(
1862
- dbStructure,
1863
- createTables,
1864
- dropTables,
1865
- changeTables,
1866
- tableShapes,
1867
- currentSchema,
1868
- ast,
1869
- verifying
1870
- );
1871
- await applyChangeTables(
1872
- adapter,
1873
- changeTables,
1874
- structureToAstCtx,
1875
- dbStructure,
1876
- domainsMap,
1877
- ast,
1878
- currentSchema,
1879
- config,
1880
- compareSql,
1881
- tableExpressions,
1882
- verifying,
1883
- pendingDbTypes
1884
- );
1885
- processForeignKeys(config, ast, changeTables, currentSchema, tableShapes);
1886
- await Promise.all([
1887
- applyCompareSql(compareSql, adapter),
1888
- compareSqlExpressions(tableExpressions, adapter)
1889
- ]);
1890
- for (const dbTable of dropTables) {
1891
- ast.push(
1892
- tableToAst(structureToAstCtx, dbStructure, dbTable, "drop", domainsMap)
1893
- );
1894
- }
1895
- };
1896
- const collectCreateTables = (tables, dbStructure, currentSchema) => {
1897
- return tables.reduce((acc, codeTable) => {
1898
- const tableSchema = codeTable.q.schema ?? currentSchema;
1899
- const hasDbTable = dbStructure.tables.some(
1900
- (t) => t.name === codeTable.table && t.schemaName === tableSchema
1901
- );
1902
- if (!hasDbTable) {
1903
- acc.push(codeTable);
1904
- }
1905
- return acc;
1906
- }, []);
1907
- };
1908
- const collectChangeAndDropTables = (adapter, config, tables, dbStructure, currentSchema, createTables, generatorIgnore) => {
1909
- const changeTables = [];
1910
- const changeTableSchemas = [];
1911
- const dropTables = [];
1912
- const tableShapes = {};
1913
- const ignoreTables = generatorIgnore?.tables?.map((name) => {
1914
- const [schema = currentSchema, table] = getSchemaAndTableFromName(
1915
- currentSchema,
1916
- name
1917
- );
1918
- return { schema, table };
1919
- });
1920
- const { schema: migrationsSchema = "public", table: migrationsTable } = getMigrationsSchemaAndTable(adapter, config);
1921
- for (const dbTable of dbStructure.tables) {
1922
- if (dbTable.name === migrationsTable && dbTable.schemaName === migrationsSchema || generatorIgnore?.schemas?.includes(dbTable.schemaName) || ignoreTables?.some(
1923
- ({ schema, table }) => table === dbTable.name && schema === dbTable.schemaName
1924
- ))
1925
- continue;
1926
- const codeTable = tables.find(
1927
- (t) => t.table === dbTable.name && (t.q.schema ?? currentSchema) === dbTable.schemaName
1928
- );
1929
- if (codeTable) {
1930
- addChangeTable(
1931
- dbStructure,
1932
- changeTables,
1933
- tableShapes,
1934
- currentSchema,
1935
- dbTable,
1936
- codeTable
1937
- );
1938
- continue;
1939
- }
1940
- const i = createTables.findIndex((t) => t.table === dbTable.name);
1941
- if (i !== -1) {
1942
- const codeTable2 = createTables[i];
1943
- createTables.splice(i, 1);
1944
- changeTableSchemas.push({ codeTable: codeTable2, dbTable });
1945
- continue;
1946
- }
1947
- dropTables.push(dbTable);
1948
- }
1949
- return { changeTables, changeTableSchemas, dropTables, tableShapes };
1950
- };
1951
- const applyChangeTableSchemas = (changeTableSchemas, currentSchema, ast) => {
1952
- for (const { codeTable, dbTable } of changeTableSchemas) {
1953
- const fromSchema = dbTable.schemaName;
1954
- const toSchema = codeTable.q.schema ?? currentSchema;
1955
- ast.push({
1956
- type: "renameType",
1957
- kind: "TABLE",
1958
- fromSchema,
1959
- from: dbTable.name,
1960
- toSchema,
1961
- to: dbTable.name
1962
- });
1963
- }
1964
- };
1965
- const applyChangeTables = async (adapter, changeTables, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, config, compareSql, tableExpressions, verifying, pendingDbTypes) => {
1966
- const compareExpressions = [];
1967
- const typeCastsCache = {};
1968
- for (const changeTableData of changeTables) {
1969
- compareExpressions.length = 0;
1970
- await processTableChange(
1971
- adapter,
1972
- structureToAstCtx,
1973
- dbStructure,
1974
- domainsMap,
1975
- ast,
1976
- currentSchema,
1977
- config,
1978
- changeTableData,
1979
- compareSql,
1980
- compareExpressions,
1981
- typeCastsCache,
1982
- verifying
1983
- );
1984
- if (compareExpressions.length) {
1985
- const { codeTable } = changeTableData;
1986
- const names = [];
1987
- const types = [];
1988
- for (const key in codeTable.shape) {
1989
- const column = codeTable.shape[key];
1990
- if (!column.dataType) continue;
1991
- const name = column.data.name ?? key;
1992
- const type = getColumnDbTypeForComparison(column, currentSchema);
1993
- if (!pendingDbTypes.set.has(type)) {
1994
- names.push(name);
1995
- types.push(type);
1996
- }
1997
- }
1998
- const tableName = codeTable.table;
1999
- const source = `(VALUES (${types.map((x) => `NULL::${x}`).join(", ")})) "${tableName}"(${names.map((x) => `"${x}"`).join(", ")})`;
2000
- tableExpressions.push(
2001
- ...compareExpressions.map((x) => ({ ...x, source }))
2002
- );
2003
- }
2004
- }
2005
- };
2006
- const getColumnDbTypeForComparison = (column, currentSchema) => {
2007
- if (column instanceof ArrayColumn) {
2008
- return getColumnDbTypeForComparison(column.data.item, currentSchema) + "[]".repeat(column.data.arrayDims);
2009
- }
2010
- let type = column instanceof EnumColumn ? column.enumName : column.dataType;
2011
- const i = type.indexOf("(");
2012
- let append = "";
2013
- if (i !== -1) {
2014
- type = type.slice(0, i);
2015
- append = type.slice(i);
2016
- }
2017
- const j = type.indexOf(".");
2018
- if (j === -1) {
2019
- let result = `"${type}"${append}`;
2020
- if (column.data.isOfCustomType || column instanceof EnumColumn) {
2021
- result = `"${currentSchema}".${result}`;
2022
- }
2023
- return result;
2024
- } else {
2025
- return `"${type.slice(j)}"."${type.slice(0, j)}"${append}`;
2026
- }
2027
- };
2028
- const freezeSqlClock = (sql) => sql.replaceAll("clock_timestamp()", `'0.1ms'::interval + now()`);
2029
- const applyCompareSql = async (compareSql, adapter) => {
2030
- if (compareSql.expressions.length) {
2031
- const {
2032
- rows: [results]
2033
- } = await adapter.arrays(
2034
- "SELECT " + compareSql.expressions.map(
2035
- (x) => `${freezeSqlClock(x.inDb)} = (${x.inCode && freezeSqlClock(x.inCode)})`
2036
- ).join(", "),
2037
- compareSql.values
2038
- );
2039
- for (let i = 0; i < results.length; i++) {
2040
- if (!results[i]) {
2041
- compareSql.expressions[i].change();
2042
- }
2043
- }
2044
- }
2045
- };
2046
- const applyCreateOrRenameTables = async (dbStructure, createTables, dropTables, changeTables, tableShapes, currentSchema, ast, verifying) => {
2047
- for (const codeTable of createTables) {
2048
- if (dropTables.length) {
2049
- const i = await promptCreateOrRename(
2050
- "table",
2051
- codeTable.table,
2052
- dropTables.map((x) => x.name),
2053
- verifying
2054
- );
2055
- if (i) {
2056
- const dbTable = dropTables[i - 1];
2057
- dropTables.splice(i - 1, 1);
2058
- ast.push({
2059
- type: "renameType",
2060
- kind: "TABLE",
2061
- fromSchema: dbTable.schemaName,
2062
- from: dbTable.name,
2063
- toSchema: codeTable.q.schema ?? currentSchema,
2064
- to: codeTable.table
2065
- });
2066
- addChangeTable(
2067
- dbStructure,
2068
- changeTables,
2069
- tableShapes,
2070
- currentSchema,
2071
- dbTable,
2072
- codeTable
2073
- );
2074
- continue;
2075
- }
2076
- }
2077
- ast.push(createTableAst(currentSchema, codeTable));
2078
- }
2079
- };
2080
- const addChangeTable = (dbStructure, changeTables, tableShapes, currentSchema, dbTable, codeTable) => {
2081
- const shape = {};
2082
- const schema = codeTable.q.schema ?? currentSchema;
2083
- changeTables.push({
2084
- codeTable: cloneCodeTableForChange(codeTable),
2085
- dbTable,
2086
- dbTableData: getDbStructureTableData(dbStructure, dbTable),
2087
- schema,
2088
- changeTableAst: {
2089
- type: "changeTable",
2090
- schema,
2091
- name: codeTable.table,
2092
- shape,
2093
- add: {},
2094
- drop: {}
2095
- },
2096
- pushedAst: false,
2097
- changingColumns: {},
2098
- delayedAst: []
2099
- });
2100
- tableShapes[`${schema}.${codeTable.table}`] = shape;
2101
- };
2102
- const cloneCodeTableForChange = (codeTable) => ({
2103
- ...codeTable,
2104
- // codeTable is a class instance and not all props can be cloned with `...`
2105
- table: codeTable.table,
2106
- shape: Object.fromEntries(
2107
- Object.entries(codeTable.shape).map(([key, column]) => {
2108
- const cloned = Object.create(column);
2109
- cloned.data = {
2110
- ...cloned.data,
2111
- checks: cloned.data.checks && [...cloned.data.checks]
2112
- };
2113
- return [key, cloned];
2114
- })
2115
- )
2116
- });
2117
- const createTableAst = (currentSchema, table) => {
2118
- return {
2119
- type: "table",
2120
- action: "create",
2121
- schema: table.q.schema === currentSchema ? void 0 : table.q.schema,
2122
- comment: table.internal.comment,
2123
- name: table.table,
2124
- shape: makeTableShape(table),
2125
- noPrimaryKey: table.internal.noPrimaryKey ? "ignore" : "error",
2126
- ...table.internal.tableData
2127
- };
2128
- };
2129
- const makeTableShape = (table) => {
2130
- const shape = {};
2131
- for (const key in table.shape) {
2132
- const column = table.shape[key];
2133
- if (!(column instanceof VirtualColumn)) {
2134
- shape[key] = column;
2135
- }
2136
- }
2137
- return shape;
2138
- };
2139
- const processTableChange = async (adapter, structureToAstCtx, dbStructure, domainsMap, ast, currentSchema, config, changeTableData, compareSql, compareExpressions, typeCastsCache, verifying) => {
2140
- await processColumns(
2141
- adapter,
2142
- config,
2143
- structureToAstCtx,
2144
- dbStructure,
2145
- domainsMap,
2146
- changeTableData,
2147
- ast,
2148
- currentSchema,
2149
- compareSql,
2150
- typeCastsCache,
2151
- verifying
2152
- );
2153
- processPrimaryKey(config, changeTableData);
2154
- processIndexesAndExcludes(config, changeTableData, ast, compareExpressions);
2155
- processChecks(ast, changeTableData, compareExpressions);
2156
- const { changeTableAst } = changeTableData;
2157
- if (Object.keys(changeTableAst.shape).length || Object.keys(changeTableAst.add).length || Object.keys(changeTableAst.drop).length) {
2158
- changeTableData.pushedAst = true;
2159
- ast.push(changeTableAst);
2160
- }
2161
- if (changeTableData.delayedAst.length) {
2162
- ast.push(...changeTableData.delayedAst);
2163
- }
2164
- };
2165
-
2166
- const defaults = {
2167
- super: false,
2168
- inherit: false,
2169
- createRole: false,
2170
- createDb: false,
2171
- canLogin: false,
2172
- replication: false,
2173
- connLimit: -1,
2174
- bypassRls: false
2175
- };
2176
- const processRoles = async (ast, dbStructure, { verifying, internal: { roles } }) => {
2177
- if (!dbStructure.roles || !roles) return;
2178
- const codeRoles = roles.map((role) => {
2179
- const { defaultPrivileges: _, ...roleWithoutPrivileges } = role;
2180
- return {
2181
- ...defaults,
2182
- ...roleWithoutPrivileges
2183
- };
2184
- });
2185
- const found = /* @__PURE__ */ new Set();
2186
- const dropRoles = [];
2187
- for (const dbRole of dbStructure.roles) {
2188
- const {
2189
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2190
- defaultPrivileges: _,
2191
- ...dbRoleWithoutPrivileges
2192
- } = dbRole;
2193
- const codeRole = codeRoles.find(
2194
- (codeRole2) => dbRole.name === codeRole2.name
2195
- );
2196
- if (codeRole) {
2197
- found.add(dbRole.name);
2198
- if (!deepCompare(dbRoleWithoutPrivileges, codeRole)) {
2199
- ast.push({
2200
- type: "changeRole",
2201
- name: dbRole.name,
2202
- from: dbRoleWithoutPrivileges,
2203
- to: codeRole
2204
- });
2205
- }
2206
- continue;
2207
- }
2208
- dropRoles.push(dbRole);
2209
- }
2210
- for (const codeRole of codeRoles) {
2211
- if (found.has(codeRole.name)) continue;
2212
- if (dropRoles.length) {
2213
- const i = await promptCreateOrRename(
2214
- "table",
2215
- codeRole.name,
2216
- dropRoles.map((x) => x.name),
2217
- verifying
2218
- );
2219
- if (i) {
2220
- const dbRole = dropRoles[i - 1];
2221
- dropRoles.splice(i - 1, 1);
2222
- ast.push(makeRenameOrChangeAst(dbRole, codeRole));
2223
- continue;
2224
- }
2225
- }
2226
- ast.push({
2227
- type: "role",
2228
- action: "create",
2229
- ...codeRole
2230
- });
2231
- }
2232
- for (const dbRole of dropRoles) {
2233
- ast.push({
2234
- type: "role",
2235
- action: "drop",
2236
- ...dbRole
2237
- });
2238
- }
2239
- };
2240
- const makeRenameOrChangeAst = (dbRole, codeRole) => {
2241
- const { name: dbRoleName, ...dbRoleRest } = dbRole;
2242
- const { name: codeRoleName, ...codeRoleRest } = codeRole;
2243
- if (deepCompare(dbRoleRest, codeRoleRest) && dbRoleName !== codeRoleName) {
2244
- return {
2245
- type: "renameRole",
2246
- from: dbRoleName,
2247
- to: codeRoleName
2248
- };
2249
- } else {
2250
- return {
2251
- type: "changeRole",
2252
- name: dbRole.name,
2253
- from: dbRole,
2254
- to: codeRole
2255
- };
2256
- }
2257
- };
2258
-
2259
- const ALL_OBJECT_TYPES = [
2260
- "TABLES",
2261
- "SEQUENCES",
2262
- "FUNCTIONS",
2263
- "TYPES",
2264
- "SCHEMAS",
2265
- "LARGE_OBJECTS"
2266
- ];
2267
- const createAllObjectConfigs = (isGrantable, schema, supportedPrivileges) => {
2268
- let types;
2269
- if (schema) {
2270
- types = ALL_OBJECT_TYPES.filter(
2271
- (t) => t !== "SCHEMAS" && t !== "LARGE_OBJECTS"
2272
- );
2273
- } else {
2274
- types = ALL_OBJECT_TYPES.filter((t) => {
2275
- if (t === "LARGE_OBJECTS") {
2276
- return supportedPrivileges.PRIVILEGES.LARGE_OBJECT !== void 0;
2277
- }
2278
- return true;
2279
- });
2280
- }
2281
- return types.map((object) => ({
2282
- object,
2283
- privilegeConfigs: [{ privilege: "ALL", isGrantable }]
2284
- }));
2285
- };
2286
- const objectTypeToKey = {
2287
- TABLES: "tables",
2288
- SEQUENCES: "sequences",
2289
- FUNCTIONS: "functions",
2290
- TYPES: "types",
2291
- SCHEMAS: "schemas",
2292
- LARGE_OBJECTS: "largeObjects"
2293
- };
2294
- const splitPrivilegeConfigs = (configs) => {
2295
- const regular = [];
2296
- const grantable = [];
2297
- for (const p of configs) {
2298
- if (p.isGrantable) {
2299
- grantable.push(p.privilege);
2300
- } else {
2301
- regular.push(p.privilege);
2302
- }
2303
- }
2304
- return { regular, grantable };
2305
- };
2306
- const createPrivilegeSetting = (regular, grantable) => {
2307
- const setting = {};
2308
- if (regular.length) setting.privileges = regular;
2309
- if (grantable.length) setting.grantablePrivileges = grantable;
2310
- return setting;
2311
- };
2312
- const collapsePrivileges = (privs, newPrivilegeConfigs, expectedPrivs, isGrantable) => {
2313
- const hasAll = privs.some((p) => p.privilege === "ALL");
2314
- const allPresent = hasAll || privs.length > 0 && privs.length === expectedPrivs.length && expectedPrivs.every((priv) => privs.some((p) => p.privilege === priv));
2315
- if (allPresent) {
2316
- newPrivilegeConfigs.push({ privilege: "ALL", isGrantable });
2317
- } else if (privs.length > 0) {
2318
- newPrivilegeConfigs.push(...privs);
2319
- }
2320
- };
2321
- const collapsePrivilegesToAll = (privilege, objectTypeToAllPrivileges) => {
2322
- const collapsedObjectConfigs = privilege.objectConfigs.map(
2323
- (objConfig) => {
2324
- const allPrivileges = objectTypeToAllPrivileges[objConfig.object];
2325
- const expectedPrivs = allPrivileges.filter((p) => p !== "ALL");
2326
- const regularPrivs = [];
2327
- const grantablePrivs = [];
2328
- for (const p of objConfig.privilegeConfigs) {
2329
- if (p.isGrantable) {
2330
- grantablePrivs.push(p);
2331
- } else {
2332
- regularPrivs.push(p);
2333
- }
2334
- }
2335
- const newPrivilegeConfigs = [];
2336
- collapsePrivileges(
2337
- regularPrivs,
2338
- newPrivilegeConfigs,
2339
- expectedPrivs,
2340
- false
2341
- );
2342
- collapsePrivileges(
2343
- grantablePrivs,
2344
- newPrivilegeConfigs,
2345
- expectedPrivs,
2346
- true
2347
- );
2348
- return {
2349
- object: objConfig.object,
2350
- privilegeConfigs: newPrivilegeConfigs
2351
- };
2352
- }
2353
- );
2354
- return {
2355
- owner: privilege.owner,
2356
- grantee: privilege.grantee,
2357
- schema: privilege.schema,
2358
- objectConfigs: collapsedObjectConfigs
2359
- };
2360
- };
2361
- const privilegeConfigsMatch = (a, b, objectType, objectTypeToAllPrivileges) => {
2362
- if (a.privilege === b.privilege && a.isGrantable === b.isGrantable) {
2363
- return true;
2364
- }
2365
- const allPrivileges = objectTypeToAllPrivileges[objectType];
2366
- const expectedPrivs = allPrivileges.filter((p) => p !== "ALL");
2367
- if (a.privilege === "ALL" && a.isGrantable === b.isGrantable) {
2368
- return expectedPrivs.includes(b.privilege);
2369
- }
2370
- if (b.privilege === "ALL" && a.isGrantable === b.isGrantable) {
2371
- return expectedPrivs.includes(a.privilege);
2372
- }
2373
- return false;
2374
- };
2375
- const normalizeRoleName = (name) => {
2376
- if (name.startsWith('"') && name.endsWith('"')) {
2377
- return name.slice(1, -1);
2378
- }
2379
- return name;
2380
- };
2381
- const processPrivilegeConfig = (config, objectType) => {
2382
- if (!config) return;
2383
- const privilegeConfigs = [];
2384
- if (config.privileges) {
2385
- for (const p of config.privileges) {
2386
- privilegeConfigs.push({ privilege: p, isGrantable: false });
2387
- }
2388
- }
2389
- if (config.grantablePrivileges) {
2390
- for (const p of config.grantablePrivileges) {
2391
- privilegeConfigs.push({ privilege: p, isGrantable: true });
2392
- }
2393
- }
2394
- if (privilegeConfigs.length) {
2395
- return { object: objectType, privilegeConfigs };
2396
- }
2397
- return;
2398
- };
2399
- const hasAnyPrivilege = (obj) => {
2400
- if (!obj) return false;
2401
- for (const key of ALL_OBJECT_TYPES) {
2402
- const setting = obj[objectTypeToKey[key]];
2403
- if (setting?.privileges?.length || setting?.grantablePrivileges?.length) {
2404
- return true;
2405
- }
2406
- }
2407
- return false;
2408
- };
2409
- const processDefaultPrivileges = (ast, dbStructure, { internal: { roles } }) => {
2410
- if (!dbStructure.defaultPrivileges || !roles) return;
2411
- const supportedPrivileges = getSupportedDefaultPrivileges(
2412
- dbStructure.version
2413
- );
2414
- const objectTypeToAllPrivileges = {};
2415
- objectTypeToAllPrivileges.TABLES = supportedPrivileges.PRIVILEGES.TABLE;
2416
- objectTypeToAllPrivileges.SEQUENCES = supportedPrivileges.PRIVILEGES.SEQUENCE;
2417
- objectTypeToAllPrivileges.FUNCTIONS = supportedPrivileges.PRIVILEGES.FUNCTION;
2418
- objectTypeToAllPrivileges.TYPES = supportedPrivileges.PRIVILEGES.TYPE;
2419
- objectTypeToAllPrivileges.SCHEMAS = supportedPrivileges.PRIVILEGES.SCHEMA;
2420
- if (supportedPrivileges.PRIVILEGES.LARGE_OBJECT) {
2421
- objectTypeToAllPrivileges.LARGE_OBJECTS = supportedPrivileges.PRIVILEGES.LARGE_OBJECT;
2422
- }
2423
- const codePrivileges = /* @__PURE__ */ new Map();
2424
- for (const role of roles) {
2425
- if (!role.defaultPrivileges) continue;
2426
- for (const privilege of role.defaultPrivileges) {
2427
- const key = `${role.name}.${privilege.schema}`;
2428
- const objectConfigs = [];
2429
- if (privilege.allGrantable) {
2430
- objectConfigs.push(
2431
- ...createAllObjectConfigs(
2432
- true,
2433
- privilege.schema,
2434
- supportedPrivileges
2435
- )
2436
- );
2437
- } else if (privilege.all) {
2438
- objectConfigs.push(
2439
- ...createAllObjectConfigs(
2440
- false,
2441
- privilege.schema,
2442
- supportedPrivileges
2443
- )
2444
- );
2445
- }
2446
- for (const objectType of ALL_OBJECT_TYPES) {
2447
- if (privilege.schema && (objectType === "SCHEMAS" || objectType === "LARGE_OBJECTS")) {
2448
- continue;
2449
- }
2450
- if (objectType === "LARGE_OBJECTS" && !supportedPrivileges.PRIVILEGES.LARGE_OBJECT) {
2451
- continue;
2452
- }
2453
- const key2 = objectTypeToKey[objectType];
2454
- if (key2 in privilege) {
2455
- const config = privilege[key2];
2456
- const processed = processPrivilegeConfig(config, objectType);
2457
- if (processed) {
2458
- const existingIndex = objectConfigs.findIndex(
2459
- (o) => o.object === objectType
2460
- );
2461
- if (existingIndex >= 0) {
2462
- objectConfigs[existingIndex] = processed;
2463
- } else {
2464
- objectConfigs.push(processed);
2465
- }
2466
- }
2467
- }
2468
- }
2469
- if (objectConfigs.length) {
2470
- codePrivileges.set(key, {
2471
- owner: void 0,
2472
- grantee: role.name,
2473
- schema: privilege.schema,
2474
- objectConfigs
2475
- });
2476
- }
2477
- }
2478
- }
2479
- const found = /* @__PURE__ */ new Set();
2480
- for (const dbPrivilege of dbStructure.defaultPrivileges) {
2481
- const grantee = normalizeRoleName(dbPrivilege.grantee);
2482
- if (grantee === "postgres") continue;
2483
- const key = `${grantee}.${dbPrivilege.schema}`;
2484
- const codePrivilege = codePrivileges.get(key);
2485
- if (codePrivilege) {
2486
- found.add(key);
2487
- const grant = {};
2488
- const revoke = {};
2489
- for (const objectType of ALL_OBJECT_TYPES) {
2490
- if (objectType === "LARGE_OBJECTS" && !supportedPrivileges.PRIVILEGES.LARGE_OBJECT) {
2491
- continue;
2492
- }
2493
- const dbObj = dbPrivilege.objectConfigs.find(
2494
- (o) => o.object === objectType
2495
- );
2496
- const codeObj = codePrivilege.objectConfigs.find(
2497
- (o) => o.object === objectType
2498
- );
2499
- const dbPrivs = dbObj?.privilegeConfigs ?? [];
2500
- const codePrivs = codeObj?.privilegeConfigs ?? [];
2501
- const collapsedDbPrivilege = {
2502
- owner: dbPrivilege.owner,
2503
- grantee: dbPrivilege.grantee,
2504
- schema: dbPrivilege.schema,
2505
- objectConfigs: [{ object: objectType, privilegeConfigs: dbPrivs }]
2506
- };
2507
- const collapsedDbObj = collapsePrivilegesToAll(
2508
- collapsedDbPrivilege,
2509
- objectTypeToAllPrivileges
2510
- ).objectConfigs[0];
2511
- const collapsedDbPrivs = collapsedDbObj?.privilegeConfigs ?? [];
2512
- const toGrant = codePrivs.filter(
2513
- (cp) => !collapsedDbPrivs.some(
2514
- (dp) => privilegeConfigsMatch(
2515
- cp,
2516
- dp,
2517
- objectType,
2518
- objectTypeToAllPrivileges
2519
- )
2520
- )
2521
- );
2522
- const toRevoke = dbPrivs.filter(
2523
- (dp) => !codePrivs.some(
2524
- (cp) => privilegeConfigsMatch(
2525
- cp,
2526
- dp,
2527
- objectType,
2528
- objectTypeToAllPrivileges
2529
- )
2530
- )
2531
- );
2532
- if (toGrant.length) {
2533
- const { regular, grantable } = splitPrivilegeConfigs(toGrant);
2534
- const setting = createPrivilegeSetting(regular, grantable);
2535
- if (setting.privileges || setting.grantablePrivileges) {
2536
- grant[objectTypeToKey[objectType]] = setting;
2537
- }
2538
- }
2539
- if (toRevoke.length) {
2540
- const { regular, grantable } = splitPrivilegeConfigs(toRevoke);
2541
- const setting = createPrivilegeSetting(regular, grantable);
2542
- if (setting.privileges || setting.grantablePrivileges) {
2543
- revoke[objectTypeToKey[objectType]] = setting;
2544
- }
2545
- }
2546
- }
2547
- const hasGrant = hasAnyPrivilege(grant);
2548
- const hasRevoke = hasAnyPrivilege(revoke);
2549
- if (hasGrant || hasRevoke) {
2550
- ast.push({
2551
- type: "defaultPrivilege",
2552
- grantee,
2553
- schema: dbPrivilege.schema,
2554
- grant: hasGrant ? grant : void 0,
2555
- revoke: hasRevoke ? revoke : void 0
2556
- });
2557
- }
2558
- } else {
2559
- const revoke = {};
2560
- for (const obj of dbPrivilege.objectConfigs) {
2561
- const { regular, grantable } = splitPrivilegeConfigs(
2562
- obj.privilegeConfigs
2563
- );
2564
- const setting = createPrivilegeSetting(regular, grantable);
2565
- if (setting.privileges || setting.grantablePrivileges) {
2566
- revoke[objectTypeToKey[obj.object]] = setting;
2567
- }
2568
- }
2569
- if (hasAnyPrivilege(revoke)) {
2570
- ast.push({
2571
- type: "defaultPrivilege",
2572
- grantee,
2573
- schema: dbPrivilege.schema,
2574
- revoke
2575
- });
2576
- }
2577
- }
2578
- }
2579
- for (const [key, codePrivilege] of codePrivileges) {
2580
- if (found.has(key)) continue;
2581
- const grant = {};
2582
- for (const obj of codePrivilege.objectConfigs) {
2583
- const { regular, grantable } = splitPrivilegeConfigs(
2584
- obj.privilegeConfigs
2585
- );
2586
- const setting = createPrivilegeSetting(regular, grantable);
2587
- if (setting.privileges || setting.grantablePrivileges) {
2588
- grant[objectTypeToKey[obj.object]] = setting;
2589
- }
2590
- }
2591
- if (hasAnyPrivilege(grant)) {
2592
- ast.push({
2593
- type: "defaultPrivilege",
2594
- grantee: codePrivilege.grantee,
2595
- schema: codePrivilege.schema,
2596
- grant
2597
- });
2598
- }
2599
- }
2600
- };
2601
-
2602
- class PendingDbTypes {
2603
- constructor() {
2604
- this.set = /* @__PURE__ */ new Set();
2605
- }
2606
- add(schemaName = "public", name) {
2607
- this.set.add(`"${schemaName}"."${name}"`);
2608
- }
2609
- }
2610
- const composeMigration = async (adapter, config, ast, dbStructure, params) => {
2611
- const { structureToAstCtx, currentSchema } = params;
2612
- await processRoles(ast, dbStructure, params);
2613
- processDefaultPrivileges(ast, dbStructure, params);
2614
- const domainsMap = makeDomainsMap(structureToAstCtx, dbStructure);
2615
- await processSchemas(ast, dbStructure, params);
2616
- processExtensions(ast, dbStructure, params);
2617
- const pendingDbTypes = new PendingDbTypes();
2618
- await processDomains(
2619
- ast,
2620
- adapter,
2621
- domainsMap,
2622
- dbStructure,
2623
- params,
2624
- pendingDbTypes
2625
- );
2626
- await processEnums(ast, dbStructure, params, pendingDbTypes);
2627
- await processTables(
2628
- ast,
2629
- domainsMap,
2630
- adapter,
2631
- dbStructure,
2632
- config,
2633
- params,
2634
- pendingDbTypes
2635
- );
2636
- return astToMigration(currentSchema, config, ast);
2637
- };
2638
-
2639
- const rollbackErr = new Error("Rollback");
2640
- const verifyMigration = async (adapter, config, migrationCode, generateMigrationParams, roles, defaultPrivileges) => {
2641
- const migrationFn = new Function("change", migrationCode);
2642
- let code;
2643
- try {
2644
- await adapter.transaction(async (trx) => {
2645
- const changeFns = [];
2646
- migrationFn((changeCb) => {
2647
- changeFns.push(changeCb);
2648
- });
2649
- const { log } = config;
2650
- config.log = false;
2651
- const db = createMigrationInterface(trx, true, config).getDb(
2652
- config.columnTypes
2653
- );
2654
- config.log = log;
2655
- for (const changeFn of changeFns) {
2656
- await changeFn(db, true);
2657
- }
2658
- const dbStructure = await introspectDbSchema(trx, {
2659
- roles,
2660
- loadDefaultPrivileges: defaultPrivileges?.loadDefaultPrivileges
2661
- });
2662
- generateMigrationParams.verifying = true;
2663
- try {
2664
- code = await composeMigration(
2665
- trx,
2666
- config,
2667
- [],
2668
- dbStructure,
2669
- generateMigrationParams
2670
- );
2671
- } catch (err) {
2672
- if (err instanceof AbortSignal) {
2673
- code = false;
2674
- throw rollbackErr;
2675
- }
2676
- throw err;
2677
- }
2678
- throw rollbackErr;
2679
- });
2680
- } catch (err) {
2681
- if (err !== rollbackErr) {
2682
- throw err;
2683
- }
2684
- }
2685
- return code;
2686
- };
2687
-
2688
- const report = (ast, config, currentSchema) => {
2689
- if (!config.logger) return;
2690
- const code = [];
2691
- let green, red, yellow, pale;
2692
- if (typeof config.log === "object" && config.log.colors === false) {
2693
- green = red = yellow = pale = (s) => s;
2694
- } else {
2695
- ({ green, red, yellow, pale } = colors);
2696
- }
2697
- for (const a of ast) {
2698
- switch (a.type) {
2699
- case "table": {
2700
- let hasPrimaryKey = !!a.primaryKey;
2701
- const counters = {
2702
- column: 0,
2703
- index: a.indexes?.length ?? 0,
2704
- exclude: a.excludes?.length ?? 0,
2705
- "foreign key": a.constraints?.reduce(
2706
- (sum, c) => c.references ? sum + 1 : sum,
2707
- 0
2708
- ) ?? 0,
2709
- check: a.constraints?.reduce(
2710
- (sum, c) => c.check ? sum + 1 : sum,
2711
- 0
2712
- ) ?? 0
2713
- };
2714
- for (const key in a.shape) {
2715
- counters.column++;
2716
- const column = a.shape[key];
2717
- if (column.data.primaryKey) {
2718
- hasPrimaryKey = true;
2719
- }
2720
- if (column.data.indexes) {
2721
- counters.index += column.data.indexes.length;
2722
- }
2723
- if (column.data.excludes) {
2724
- counters.exclude += column.data.excludes.length;
2725
- }
2726
- if (column.data.foreignKeys) {
2727
- counters["foreign key"] += column.data.foreignKeys.length;
2728
- }
2729
- if (column.data.checks) {
2730
- counters.check += column.data.checks.length;
2731
- }
2732
- }
2733
- const summary = [];
2734
- for (const key in counters) {
2735
- const value = counters[key];
2736
- if (value || key === "column") {
2737
- summary.push(
2738
- `${value} ${pluralize(key, value, key === "index" ? "es" : "s")}`
2739
- );
2740
- }
2741
- }
2742
- if (!hasPrimaryKey) {
2743
- summary.push("no primary key");
2744
- }
2745
- code.push(
2746
- `${a.action === "create" ? green("+ create table") : red("- drop table")} ${dbItemName(a, currentSchema)} (${summary.join(", ")})`
2747
- );
2748
- break;
2749
- }
2750
- case "changeTable": {
2751
- const inner = [];
2752
- const toCodeCtx = {
2753
- t: "t",
2754
- table: a.name,
2755
- currentSchema,
2756
- migration: true,
2757
- snakeCase: config.snakeCase
2758
- };
2759
- for (const key in a.shape) {
2760
- const changes = toArray(a.shape[key]);
2761
- for (const change of changes) {
2762
- if (change.type === "add" || change.type === "drop") {
2763
- const column = change.item;
2764
- const { primaryKey, indexes, excludes, foreignKeys, checks } = column.data;
2765
- inner.push(
2766
- `${change.type === "add" ? green("+ add column") : red("- drop column")} ${key} ${column.data.alias ?? getColumnDbType(column, currentSchema)}${column.data.isNullable ? " nullable" : ""}${primaryKey ? " primary key" : ""}${foreignKeys ? ` references ${foreignKeys.map((fk) => {
2767
- return `${fnOrTableToString(
2768
- fk.fnOrTable
2769
- )}(${fk.foreignColumns.join(", ")})`;
2770
- }).join(", ")}` : ""}${indexes?.length ? indexes.length === 1 ? ", has index" : `, has ${indexes.length} indexes` : ""}${excludes?.length ? excludes.length === 1 ? ", has exclude" : `, has ${excludes.length} excludes` : ""}${checks?.length ? `, checks ${checks.map((check) => check.sql.toSQL({ values: [] })).join(", ")}` : ""}`
2771
- );
2772
- } else if (change.type === "change") {
2773
- let name = change.from.column?.data.name ?? key;
2774
- if (config.snakeCase) name = toCamelCase(name);
2775
- const changes2 = [];
2776
- inner.push(`${yellow("~ change column")} ${name}:`, changes2);
2777
- changes2.push(`${yellow("from")}: `);
2778
- const fromCode = change.from.column?.toCode(toCodeCtx, key);
2779
- if (fromCode) {
2780
- for (const code2 of fromCode) {
2781
- addCode(changes2, code2);
2782
- }
2783
- }
2784
- changes2.push(` ${yellow("to")}: `);
2785
- const toCode = change.to.column?.toCode(toCodeCtx, key);
2786
- if (toCode) {
2787
- for (const code2 of toCode) {
2788
- addCode(changes2, code2);
2789
- }
2790
- }
2791
- } else if (change.type === "rename") {
2792
- inner.push(
2793
- `${yellow("~ rename column")} ${config.snakeCase ? toCamelCase(key) : key} ${yellow("=>")} ${change.name}`
2794
- );
2795
- } else {
2796
- exhaustive(change.type);
2797
- }
2798
- }
2799
- }
2800
- if (a.drop.primaryKey) {
2801
- inner.push(
2802
- `${red(`- drop primary key`)} on (${a.drop.primaryKey.columns.join(
2803
- ", "
2804
- )})`
2805
- );
2806
- }
2807
- if (a.drop.indexes) {
2808
- for (const index of a.drop.indexes) {
2809
- inner.push(
2810
- `${red(
2811
- `- drop${index.options.unique ? " unique" : ""} index`
2812
- )} on (${index.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2813
- );
2814
- }
2815
- }
2816
- if (a.drop.excludes) {
2817
- for (const exclude of a.drop.excludes) {
2818
- inner.push(
2819
- `${red(`- drop exclude`)} on (${exclude.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2820
- );
2821
- }
2822
- }
2823
- if (a.drop.constraints) {
2824
- for (const { references } of a.drop.constraints) {
2825
- if (!references) continue;
2826
- const [schema, name] = getSchemaAndTableFromName(
2827
- currentSchema,
2828
- references.fnOrTable
2829
- );
2830
- inner.push(
2831
- `${red(`- drop foreign key`)} on (${references.columns.join(
2832
- ", "
2833
- )}) to ${dbItemName(
2834
- {
2835
- schema,
2836
- name
2837
- },
2838
- currentSchema
2839
- )}(${references.foreignColumns.join(", ")})`
2840
- );
2841
- }
2842
- for (const { check } of a.drop.constraints) {
2843
- if (!check) continue;
2844
- inner.push(`${red(`- drop check`)} ${check.toSQL({ values: [] })}`);
2845
- }
2846
- }
2847
- if (a.add.primaryKey) {
2848
- inner.push(
2849
- `${green(`+ add primary key`)} on (${a.add.primaryKey.columns.join(
2850
- ", "
2851
- )})`
2852
- );
2853
- }
2854
- if (a.add.indexes) {
2855
- for (const index of a.add.indexes) {
2856
- inner.push(
2857
- `${green(
2858
- `+ add${index.options.unique ? " unique" : ""} index`
2859
- )} on (${index.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2860
- );
2861
- }
2862
- }
2863
- if (a.add.excludes) {
2864
- for (const exclude of a.add.excludes) {
2865
- inner.push(
2866
- `${green(`+ add exclude`)} on (${exclude.columns.map((c) => "column" in c ? c.column : c.expression).join(", ")})`
2867
- );
2868
- }
2869
- }
2870
- if (a.add.constraints) {
2871
- for (const { references } of a.add.constraints) {
2872
- if (!references) continue;
2873
- inner.push(
2874
- `${green(`+ add foreign key`)} on (${references.columns.join(
2875
- ", "
2876
- )}) to ${references.fnOrTable}(${references.foreignColumns.join(", ")})`
2877
- );
2878
- }
2879
- for (const { check } of a.add.constraints) {
2880
- if (!check) continue;
2881
- inner.push(
2882
- `${green(`+ add check`)} ${check.toSQL({ values: [] })}`
2883
- );
2884
- }
2885
- }
2886
- code.push(
2887
- `${yellow("~ change table")} ${dbItemName(a, currentSchema)}${inner.length ? ":" : ""}`
2888
- );
2889
- if (inner.length) {
2890
- code.push(inner);
2891
- }
2892
- break;
2893
- }
2894
- case "schema": {
2895
- code.push(
2896
- `${a.action === "create" ? green("+ create schema") : red("- drop schema")} ${a.name}`
2897
- );
2898
- break;
2899
- }
2900
- case "renameSchema": {
2901
- code.push(
2902
- `${yellow("~ rename schema")} ${a.from} ${yellow("=>")} ${a.to}`
2903
- );
2904
- break;
2905
- }
2906
- case "renameType": {
2907
- code.push(
2908
- `${yellow(
2909
- `~ ${a.fromSchema !== a.toSchema ? a.from !== a.to ? "change schema and rename" : "change schema of" : "rename"} ${a.kind.toLowerCase()}`
2910
- )} ${dbItemName(
2911
- {
2912
- schema: a.fromSchema,
2913
- name: a.from
2914
- },
2915
- currentSchema
2916
- )} ${yellow("=>")} ${dbItemName(
2917
- {
2918
- schema: a.toSchema,
2919
- name: a.to
2920
- },
2921
- currentSchema
2922
- )}`
2923
- );
2924
- break;
2925
- }
2926
- case "extension": {
2927
- code.push(
2928
- `${a.action === "create" ? green("+ create extension") : red("- drop extension")} ${dbItemName(a, currentSchema)}${a.version ? ` ${pale(a.version)}` : ""}`
2929
- );
2930
- break;
2931
- }
2932
- case "enum": {
2933
- code.push(
2934
- `${a.action === "create" ? green("+ create enum") : red("- drop enum")} ${dbItemName(a, currentSchema)}: (${a.values.join(", ")})`
2935
- );
2936
- break;
2937
- }
2938
- case "enumValues": {
2939
- code.push(
2940
- `${a.action === "add" ? green("+ add values to enum") : red("- remove values from enum")} ${dbItemName(a, currentSchema)}: ${a.values.join(", ")}`
2941
- );
2942
- break;
2943
- }
2944
- case "changeEnumValues": {
2945
- if (a.fromValues) {
2946
- code.push(
2947
- `${red("- remove values from enum")} ${dbItemName(
2948
- a,
2949
- currentSchema
2950
- )}: ${a.fromValues.join(", ")}`
2951
- );
2952
- }
2953
- if (a.toValues) {
2954
- code.push(
2955
- `${green("+ add values to enum")} ${dbItemName(
2956
- a,
2957
- currentSchema
2958
- )}: ${a.toValues.join(", ")}`
2959
- );
2960
- }
2961
- break;
2962
- }
2963
- case "domain": {
2964
- code.push(
2965
- `${a.action === "create" ? green("+ create domain") : red("- drop domain")} ${dbItemName(a, currentSchema)}`
2966
- );
2967
- break;
2968
- }
2969
- case "view":
2970
- case "collation":
2971
- case "renameEnumValues":
2972
- case "constraint":
2973
- break;
2974
- case "renameTableItem": {
2975
- code.push(
2976
- `${yellow(`~ rename ${a.kind.toLowerCase()}`)} on table ${dbItemName(
2977
- { schema: a.tableSchema, name: a.tableName },
2978
- currentSchema
2979
- )}: ${a.from} ${yellow("=>")} ${a.to}`
2980
- );
2981
- break;
2982
- }
2983
- case "role":
2984
- code.push(
2985
- `${a.action === "create" ? green("+ create role") : red("- drop role")} ${a.name}`
2986
- );
2987
- break;
2988
- case "renameRole":
2989
- case "changeRole": {
2990
- if (a.type === "renameRole") {
2991
- code.push(
2992
- `${yellow("~ rename role")} ${a.from} ${yellow("=>")} ${a.to}`
2993
- );
2994
- } else {
2995
- code.push(`${yellow("~ change role")} ${a.name}`);
2996
- }
2997
- break;
2998
- }
2999
- case "defaultPrivilege": {
3000
- const mapPrivilege = (p) => p === "ALL" ? "ALL PRIVILEGES" : p;
3001
- const schema = a.schema ? ` in schema ${colors.pale(a.schema)}` : ` ${colors.pale("in all schemas")}`;
3002
- const parts = [];
3003
- if (a.grant) {
3004
- for (const [objType, config2] of Object.entries(a.grant)) {
3005
- if (!config2) continue;
3006
- const type = objType.replace(/([A-Z])/g, " $1").toLowerCase();
3007
- if (config2.privileges?.length) {
3008
- parts.push(
3009
- `${green("+ grant default privileges")} ${config2.privileges.map(mapPrivilege).join(", ")} on ${type} to ${a.grantee}${schema}`
3010
- );
3011
- }
3012
- if (config2.grantablePrivileges?.length) {
3013
- parts.push(
3014
- `${green(
3015
- "+ grant default privileges"
3016
- )} ${config2.grantablePrivileges.map(mapPrivilege).join(", ")} on ${type} with grant option to ${a.grantee}${schema}`
3017
- );
3018
- }
3019
- }
3020
- }
3021
- if (a.revoke) {
3022
- for (const [objType, config2] of Object.entries(a.revoke)) {
3023
- if (!config2) continue;
3024
- const type = objType.replace(/([A-Z])/g, " $1").toLowerCase();
3025
- if (config2.privileges?.length) {
3026
- parts.push(
3027
- `${red("- revoke default privileges")} ${config2.privileges.map(mapPrivilege).join(", ")} on ${type} from ${a.grantee}${schema}`
3028
- );
3029
- }
3030
- if (config2.grantablePrivileges?.length) {
3031
- parts.push(
3032
- `${red(
3033
- "- revoke default privileges"
3034
- )} ${config2.grantablePrivileges.map(mapPrivilege).join(", ")} on ${type} with grant option from ${a.grantee}${schema}`
3035
- );
3036
- }
3037
- }
3038
- }
3039
- if (parts.length) {
3040
- code.push(parts.join("\n"));
3041
- }
3042
- break;
3043
- }
3044
- default:
3045
- exhaustive(a);
3046
- }
3047
- }
3048
- const result = codeToString(code, "", " ");
3049
- config.logger.log(result);
3050
- };
3051
- const dbItemName = ({ schema, name }, currentSchema) => {
3052
- return schema && schema !== currentSchema ? `${schema}.${name}` : name;
3053
- };
3054
-
3055
- class AbortSignal extends Error {
3056
- }
3057
- const generate = async (adapters, config, args, afterPull) => {
3058
- let { dbPath } = config;
3059
- if (!dbPath || !config.baseTable) throw invalidConfig(config);
3060
- if (!adapters.length) throw new Error(`Database options must not be empty`);
3061
- if (!dbPath.endsWith(".ts")) dbPath += ".ts";
3062
- let migrationName = args[0] ?? "generated";
3063
- let up;
3064
- if (migrationName === "up") {
3065
- up = true;
3066
- migrationName = "generated";
3067
- } else {
3068
- up = args[1] === "up";
3069
- }
3070
- if (afterPull) {
3071
- adapters = [afterPull.adapter];
3072
- }
3073
- const db = await getDbFromConfig(config, dbPath);
3074
- const { columnTypes, internal } = db.$qb;
3075
- const rolesDbStructureParam = internal.roles ? internal.managedRolesSql ? { whereSql: internal.managedRolesSql } : emptyObject : void 0;
3076
- const { dbStructure } = await migrateAndPullStructures(
3077
- adapters,
3078
- config,
3079
- rolesDbStructureParam,
3080
- internal.roles ? { loadDefaultPrivileges: true } : void 0,
3081
- afterPull
3082
- );
3083
- const [adapter] = adapters;
3084
- const adapterSchema = adapter.getSchema();
3085
- const currentSchema = (typeof adapterSchema === "function" ? adapterSchema() : adapterSchema) ?? "public";
3086
- const codeItems = await getActualItems(
3087
- db,
3088
- currentSchema,
3089
- internal,
3090
- columnTypes
3091
- );
3092
- const structureToAstCtx = makeStructureToAstCtx(config, currentSchema);
3093
- const generateMigrationParams = {
3094
- structureToAstCtx,
3095
- codeItems,
3096
- currentSchema,
3097
- internal
3098
- };
3099
- const ast = [];
3100
- let migrationCode;
3101
- try {
3102
- migrationCode = await composeMigration(
3103
- adapter,
3104
- config,
3105
- ast,
3106
- dbStructure,
3107
- generateMigrationParams
3108
- );
3109
- } catch (err) {
3110
- if (err instanceof AbortSignal) {
3111
- await closeAdapters(adapters);
3112
- return;
3113
- }
3114
- throw err;
3115
- }
3116
- if (migrationCode && !afterPull) {
3117
- const result = await verifyMigration(
3118
- adapter,
3119
- config,
3120
- migrationCode,
3121
- generateMigrationParams,
3122
- rolesDbStructureParam,
3123
- internal.roles ? { loadDefaultPrivileges: true } : void 0
3124
- );
3125
- if (result !== void 0) {
3126
- throw new Error(
3127
- `Failed to verify generated migration: some of database changes were not applied properly. This is a bug, please open an issue, attach the following migration code:
3128
- ${migrationCode}${result === false ? "" : `
3129
- After applying:
3130
- ${result}`}`
3131
- );
3132
- }
3133
- }
3134
- const { logger } = config;
3135
- if ((!up || !migrationCode) && !afterPull) await closeAdapters(adapters);
3136
- if (!migrationCode) {
3137
- logger?.log("No changes were detected");
3138
- return;
3139
- }
3140
- const version = afterPull?.version ?? await makeFileVersion({}, config);
3141
- const delayLog = [];
3142
- await writeMigrationFile(
3143
- {
3144
- ...config,
3145
- logger: logger ? { ...logger, log: (msg) => delayLog.push(msg) } : logger
3146
- },
3147
- version,
3148
- migrationName,
3149
- migrationCode
3150
- );
3151
- report(ast, config, currentSchema);
3152
- if (logger) {
3153
- for (const msg of delayLog) {
3154
- logger.log(`
3155
- ${msg}`);
3156
- }
3157
- }
3158
- if (up) {
3159
- for (const adapter2 of adapters) {
3160
- await migrateAndClose(adapter2, config);
3161
- }
3162
- } else if (!afterPull) {
3163
- await closeAdapters(adapters);
3164
- }
3165
- };
3166
- const invalidConfig = (config) => new Error(
3167
- `\`${config.dbPath ? "baseTable" : "dbPath"}\` setting must be set in the migrations config for the generator to work`
3168
- );
3169
- const getDbFromConfig = async (config, dbPath) => {
3170
- const module = await config.import(
3171
- pathToFileURL(path.resolve(config.basePath, dbPath)).toString()
3172
- );
3173
- const db = module[config.dbExportedAs ?? "db"];
3174
- if (!db?.$qb) {
3175
- throw new Error(
3176
- `Unable to import OrchidORM instance as ${config.dbExportedAs ?? "db"} from ${config.dbPath}`
3177
- );
3178
- }
3179
- return db;
3180
- };
3181
- const migrateAndPullStructures = async (adapters, config, roles, defaultPrivileges, afterPull) => {
3182
- if (afterPull) {
3183
- const version = await getDbVersion(adapters[0]);
3184
- return {
3185
- dbStructure: {
3186
- version,
3187
- schemas: [],
3188
- tables: [],
3189
- views: [],
3190
- indexes: [],
3191
- excludes: [],
3192
- constraints: [],
3193
- triggers: [],
3194
- extensions: [],
3195
- enums: [],
3196
- domains: [],
3197
- collations: []
3198
- }
3199
- };
3200
- }
3201
- for (const adapter of adapters) {
3202
- await migrate(adapter, config);
3203
- }
3204
- const dbStructures = await Promise.all(
3205
- adapters.map(
3206
- (adapter) => introspectDbSchema(adapter, {
3207
- roles,
3208
- loadDefaultPrivileges: defaultPrivileges?.loadDefaultPrivileges
3209
- })
3210
- )
3211
- );
3212
- const dbStructure = dbStructures[0];
3213
- for (let i = 1; i < dbStructures.length; i++) {
3214
- compareDbStructures(dbStructure, dbStructures[i], i);
3215
- }
3216
- return { dbStructure };
3217
- };
3218
- const compareDbStructures = (a, b, i, path2) => {
3219
- let err;
3220
- if (typeof a !== typeof b) {
3221
- err = true;
3222
- }
3223
- if (!a || typeof a !== "object") {
3224
- if (a !== b) {
3225
- err = true;
3226
- }
3227
- } else {
3228
- if (Array.isArray(a)) {
3229
- for (let n = 0, len = a.length; n < len; n++) {
3230
- compareDbStructures(
3231
- a[n],
3232
- b[n],
3233
- i,
3234
- path2 ? `${path2}[${n}]` : String(n)
3235
- );
3236
- }
3237
- } else {
3238
- for (const key in a) {
3239
- compareDbStructures(
3240
- a[key],
3241
- b[key],
3242
- i,
3243
- path2 ? `${path2}.${key}` : key
3244
- );
3245
- }
3246
- }
3247
- }
3248
- if (err) {
3249
- throw new Error(`${path2} in the db 0 does not match db ${i}`);
3250
- }
3251
- };
3252
- const getActualItems = async (db, currentSchema, internal, columnTypes) => {
3253
- const tableNames = /* @__PURE__ */ new Set();
3254
- const habtmTables = /* @__PURE__ */ new Map();
3255
- const codeItems = {
3256
- schemas: /* @__PURE__ */ new Set(void 0),
3257
- enums: /* @__PURE__ */ new Map(),
3258
- tables: [],
3259
- domains: []
3260
- };
3261
- codeItems.schemas.add(currentSchema);
3262
- const domains = /* @__PURE__ */ new Map();
3263
- for (const key in db) {
3264
- if (key[0] === "$") continue;
3265
- const table = db[key];
3266
- if (!table.table) {
3267
- throw new Error(`Table ${key} is missing table property`);
3268
- }
3269
- const schema = getQuerySchema(table);
3270
- const name = concatSchemaAndName({ schema, name: table.table });
3271
- if (tableNames.has(name)) {
3272
- throw new Error(`Table ${name} is defined more than once`);
3273
- }
3274
- tableNames.add(name);
3275
- if (schema) codeItems.schemas.add(schema);
3276
- codeItems.tables.push({
3277
- table: table.table,
3278
- shape: table.shape,
3279
- internal: table.internal,
3280
- q: {
3281
- schema: getQuerySchema(table)
3282
- }
3283
- });
3284
- for (const key2 in table.relations) {
3285
- const column = table.shape[key2];
3286
- if (column && "joinTable" in column) {
3287
- processHasAndBelongsToManyColumn(column, habtmTables, codeItems);
3288
- }
3289
- }
3290
- for (const key2 in table.shape) {
3291
- const column = table.shape[key2];
3292
- if (column.data.computed) {
3293
- delete table.shape[key2];
3294
- } else if (column instanceof DomainColumn) {
3295
- const [schemaName = currentSchema, name2] = getSchemaAndTableFromName(
3296
- currentSchema,
3297
- column.dataType
3298
- );
3299
- domains.set(column.dataType, {
3300
- schemaName,
3301
- name: name2,
3302
- column: column.data.as ?? new UnknownColumn(defaultSchemaConfig)
3303
- });
3304
- } else {
3305
- const en = column.dataType === "enum" ? column : column instanceof ArrayColumn && column.data.item.dataType === "enum" ? column.data.item : void 0;
3306
- if (en) {
3307
- processEnumColumn(en, currentSchema, codeItems);
3308
- }
3309
- }
3310
- }
3311
- }
3312
- if (internal.extensions) {
3313
- for (const extension of internal.extensions) {
3314
- const [schema] = getSchemaAndTableFromName(currentSchema, extension.name);
3315
- if (schema) codeItems.schemas.add(schema);
3316
- }
3317
- }
3318
- if (internal.domains) {
3319
- for (const key in internal.domains) {
3320
- const [schemaName = currentSchema, name] = getSchemaAndTableFromName(
3321
- currentSchema,
3322
- key
3323
- );
3324
- const column = internal.domains[key](columnTypes);
3325
- domains.set(key, {
3326
- schemaName,
3327
- name,
3328
- column
3329
- });
3330
- }
3331
- }
3332
- for (const domain of domains.values()) {
3333
- codeItems.schemas.add(domain.schemaName);
3334
- codeItems.domains.push(domain);
3335
- }
3336
- if (internal.roles) {
3337
- for (const role of internal.roles) {
3338
- if (role.defaultPrivileges) {
3339
- for (const privilege of role.defaultPrivileges) {
3340
- if (privilege.schema) codeItems.schemas.add(privilege.schema);
3341
- }
3342
- }
3343
- }
3344
- }
3345
- return codeItems;
3346
- };
3347
- const processEnumColumn = (column, currentSchema, codeItems) => {
3348
- const { enumName, options } = column;
3349
- const [schema, name] = getSchemaAndTableFromName(currentSchema, enumName);
3350
- const enumSchema = schema ?? currentSchema;
3351
- codeItems.enums.set(`${enumSchema}.${name}`, {
3352
- schema: enumSchema,
3353
- name,
3354
- values: options
3355
- });
3356
- if (schema) codeItems.schemas.add(schema);
3357
- };
3358
- const processHasAndBelongsToManyColumn = (column, habtmTables, codeItems) => {
3359
- const q = column.joinTable;
3360
- const prev = habtmTables.get(q.table);
3361
- if (prev) {
3362
- for (const key in q.shape) {
3363
- if (q.shape[key].dataType !== prev.shape[key]?.dataType) {
3364
- throw new Error(
3365
- `Column ${key} in ${q.table} in hasAndBelongsToMany relation does not match with the relation on the other side`
3366
- );
3367
- }
3368
- }
3369
- return;
3370
- }
3371
- habtmTables.set(q.table, q);
3372
- const joinTable = Object.create(q);
3373
- const shape = {};
3374
- for (const key in joinTable.shape) {
3375
- const column2 = Object.create(joinTable.shape[key]);
3376
- column2.data = {
3377
- ...column2.data,
3378
- name: column2.data.name ?? key,
3379
- identity: void 0,
3380
- primaryKey: void 0,
3381
- default: void 0
3382
- };
3383
- shape[toCamelCase(key)] = column2;
3384
- }
3385
- joinTable.shape = shape;
3386
- joinTable.internal = {
3387
- ...joinTable.internal,
3388
- tableData: {
3389
- ...joinTable.internal.tableData,
3390
- primaryKey: {
3391
- columns: Object.keys(shape)
3392
- }
3393
- },
3394
- noPrimaryKey: false
3395
- };
3396
- codeItems.tables.push(joinTable);
3397
- return;
3398
- };
3399
- const closeAdapters = (adapters) => {
3400
- return Promise.all(adapters.map((x) => x.close()));
3401
- };
3402
-
3403
- const getTableInfosAndFKeys = (asts, config) => {
3404
- var _a;
3405
- const generateTableTo = config.generateTableTo ?? ((name) => `./tables/${name}.table.ts`);
3406
- const tableInfos = {};
3407
- const fkeys = {};
3408
- for (const ast of asts) {
3409
- if (ast.type === "table") {
3410
- const tableKey = toCamelCase(ast.name);
3411
- const dbTableName = ast.schema ? `${ast.schema}.${ast.name}` : ast.name;
3412
- let tablePath = path.resolve(config.basePath, generateTableTo(tableKey));
3413
- if (!tablePath.endsWith(".ts")) tablePath += ".ts";
3414
- const name = toPascalCase(ast.name);
3415
- const info = {
3416
- dbTableName,
3417
- key: tableKey,
3418
- path: tablePath,
3419
- name,
3420
- className: `${name}Table`
3421
- };
3422
- tableInfos[dbTableName] = info;
3423
- if (ast.constraints) {
3424
- for (const { references } of ast.constraints) {
3425
- if (!references) continue;
3426
- (fkeys[_a = references.fnOrTable] ?? (fkeys[_a] = [])).push({
3427
- table: info,
3428
- references
3429
- });
3430
- }
3431
- }
3432
- }
3433
- }
3434
- return { tableInfos, fkeys };
3435
- };
3436
- const appCodeGenTable = (tableInfos, fkeys, ast, baseTablePath, baseTableExportedAs, currentSchema) => {
3437
- const tableInfo = tableInfos[ast.schema ? `${ast.schema}.${ast.name}` : ast.name];
3438
- const imports = {
3439
- "orchid-orm": "Selectable, Insertable, Updatable",
3440
- [getImportPath(tableInfo.path, baseTablePath)]: baseTableExportedAs
3441
- };
3442
- const props = [];
3443
- if (ast.schema) {
3444
- props.push(`schema = ${singleQuote(ast.schema)};`);
3445
- }
3446
- props.push(`readonly table = ${singleQuote(ast.name)};`);
3447
- if (ast.comment) {
3448
- props.push(`comment = ${singleQuote(ast.comment)};`);
3449
- }
3450
- if (ast.noPrimaryKey === "ignore") {
3451
- props.push("noPrimaryKey = true;");
3452
- }
3453
- const hasTableData = Boolean(
3454
- ast.primaryKey || ast.indexes?.length || ast.excludes?.length || ast.constraints?.length
3455
- );
3456
- const shapeCode = columnsShapeToCode(
3457
- { t: "t", table: ast.name, currentSchema },
3458
- ast.shape
3459
- );
3460
- props.push(
3461
- `columns = this.setColumns(${hasTableData ? "\n " : ""}(t) => ({`,
3462
- hasTableData ? [shapeCode] : shapeCode,
3463
- hasTableData ? " })," : "}));"
3464
- );
3465
- if (hasTableData) {
3466
- props.push(pushTableDataCode([], ast), ");");
3467
- }
3468
- const relations = [];
3469
- const fullTableName = ast.schema ? `${ast.schema}.${ast.name}` : ast.name;
3470
- const belongsTo = fkeys[fullTableName];
3471
- if (belongsTo) {
3472
- for (const { table, references } of belongsTo) {
3473
- imports[getImportPath(tableInfo.path, table.path)] = table.className;
3474
- relations.push(
3475
- `${table.key}: this.belongsTo(() => ${table.className}, {`,
3476
- [
3477
- `columns: [${references.foreignColumns.map(singleQuote).join(", ")}],`,
3478
- `references: [${references.columns.map(singleQuote).join(", ")}],`
3479
- ],
3480
- "}),"
3481
- );
3482
- }
3483
- }
3484
- if (ast.constraints) {
3485
- for (const { references } of ast.constraints) {
3486
- if (!references) continue;
3487
- const table = tableInfos[references.fnOrTable];
3488
- imports[getImportPath(tableInfo.path, table.path)] = table.className;
3489
- relations.push(
3490
- `${table.key}: this.hasMany(() => ${table.className}, {`,
3491
- [
3492
- `columns: [${references.columns.map(singleQuote).join(", ")}],`,
3493
- `references: [${references.foreignColumns.map(singleQuote).join(", ")}],`
3494
- ],
3495
- "}),"
3496
- );
3497
- }
3498
- }
3499
- if (relations.length) {
3500
- props.push("", "relations = {", relations, "};");
3501
- }
3502
- const importsCode = importsToCode(imports);
3503
- const { name, className } = tableInfo;
3504
- const code = [
3505
- `export type ${name} = Selectable<${className}>;
3506
- export type ${name}New = Insertable<${className}>;
3507
- export type ${name}Update = Updatable<${className}>;
3508
-
3509
- export class ${className} extends ${baseTableExportedAs} {`,
3510
- props,
3511
- "}\n"
3512
- ];
3513
- return {
3514
- ...tableInfo,
3515
- content: importsCode + "\n\n" + codeToString(code, "", " ")
3516
- };
3517
- };
3518
- function importsToCode(imports) {
3519
- return Object.entries(imports).map(([from, name]) => `import { ${name} } from '${from}';`).join("\n");
3520
- }
3521
-
3522
- const { createSourceFile, ScriptTarget, SyntaxKind } = typescript;
3523
- const appCodeGenUpdateDbFile = async (dbPath, tables, extensions, domains, currentSchema) => {
3524
- const content = await fs.readFile(dbPath, "utf-8");
3525
- const statements = getTsStatements(content);
3526
- const importName = getOrchidOrmImportName(statements);
3527
- if (!importName) {
3528
- throw new Error(`Main file does not contain import of orchid-orm`);
3529
- }
3530
- const { config, tablesList } = getOrchidOrmArgs(importName, statements);
3531
- const changes = [];
3532
- let replacedConfig;
3533
- if (extensions.length || domains.length) {
3534
- let code = content.slice(config.pos, config.end).trim();
3535
- if (code[0] !== "{") code = `{...${code}}`;
3536
- code = "{\n " + code.slice(1, -1).trim();
3537
- if (!code.endsWith(",")) code += ",";
3538
- if (extensions.length) {
3539
- code += `
3540
- extensions: [${extensions.map(
3541
- (ext) => ext.version ? `{ ${quoteObjectKey(ext.name, false)}: '${ext.version}' }` : singleQuote(ext.name)
3542
- ).join(", ")}],`;
3543
- }
3544
- if (domains.length) {
3545
- code += `
3546
- domains: {
3547
- ${domains.sort((a, b) => a.name > b.name ? 1 : -1).map(
3548
- (ast) => `${quoteObjectKey(
3549
- ast.schema ? `${ast.schema}.${ast.name}` : ast.name,
3550
- false
3551
- )}: (t) => ${ast.baseType.toCode(
3552
- { t: "t", table: ast.name, currentSchema },
3553
- ast.baseType.data.name ?? ""
3554
- )},`
3555
- ).join("\n ")}
3556
- },`;
3557
- }
3558
- replacedConfig = code + "\n}";
3559
- }
3560
- const tablesChanges = makeTablesListChanges(
3561
- content,
3562
- statements,
3563
- tablesList,
3564
- tables,
3565
- dbPath
3566
- );
3567
- if (tablesChanges) {
3568
- addChange(
3569
- content,
3570
- changes,
3571
- tablesChanges.imports.pos,
3572
- tablesChanges.imports.text
3573
- );
3574
- }
3575
- if (replacedConfig) {
3576
- replaceContent(content, changes, config.pos, config.end, replacedConfig);
3577
- }
3578
- if (tablesChanges) {
3579
- addChange(
3580
- content,
3581
- changes,
3582
- tablesChanges.tablesList.pos,
3583
- tablesChanges.tablesList.text
3584
- );
3585
- }
3586
- return applyChanges(content, changes);
3587
- };
3588
- const getTsStatements = (content) => {
3589
- return createSourceFile("file.ts", content, ScriptTarget.Latest, true).statements;
3590
- };
3591
- const getOrchidOrmImportName = (statements) => {
3592
- for (const node of statements) {
3593
- if (node.kind !== SyntaxKind.ImportDeclaration) continue;
3594
- const imp = node;
3595
- const source = imp.moduleSpecifier.getText().slice(1, -1);
3596
- if (source !== "orchid-orm") continue;
3597
- if (!imp.importClause) continue;
3598
- const elements = imp.importClause.namedBindings?.elements;
3599
- for (const element of elements) {
3600
- if (element.name.escapedText === "orchidORM" || element.propertyName && "escapedText" in element.propertyName && element.propertyName.escapedText === "orchidORM") {
3601
- return element.name.escapedText.toString();
3602
- }
3603
- }
3604
- }
3605
- return;
3606
- };
3607
- const makeTablesListChanges = (content, statements, object, tables, dbPath) => {
3608
- const spaces = getTablesListSpaces(content, object);
3609
- let imports = "";
3610
- let tablesList = "";
3611
- const prependComma = object.properties.length && !object.properties.hasTrailingComma;
3612
- const tablesListNewLine = content.slice(object.properties.end, object.end).includes("\n");
3613
- const tablesArr = Object.values(tables);
3614
- for (let i = 0; i < tablesArr.length; i++) {
3615
- const { path, className, key } = tablesArr[i];
3616
- const importPath = getImportPath(dbPath, path);
3617
- imports += `
3618
- import { ${className} } from '${importPath}';`;
3619
- tablesList += `${i === 0 && prependComma ? "," : ""}
3620
- ${spaces} ${key}: ${className},`;
3621
- if (i === tablesArr.length - 1 && !tablesListNewLine) {
3622
- tablesList += `
3623
- ${spaces}`;
3624
- }
3625
- }
3626
- if (!imports.length) return;
3627
- let importPos = 0;
3628
- for (const node of statements) {
3629
- if (node.kind === SyntaxKind.ImportDeclaration) {
3630
- importPos = node.end;
3631
- }
3632
- }
3633
- return {
3634
- imports: { pos: importPos, text: imports },
3635
- tablesList: { pos: object.properties.end, text: tablesList }
3636
- };
3637
- };
3638
- const getTablesListSpaces = (content, object) => {
3639
- const lines = content.slice(0, object.end).split("\n");
3640
- const last = lines[lines.length - 1];
3641
- return last.match(/^\s+/)?.[0] || "";
3642
- };
3643
- const getOrchidOrmArgs = (importName, statements) => {
3644
- for (const v of statements) {
3645
- if (v.kind !== SyntaxKind.VariableStatement) continue;
3646
- for (const node of v.declarationList.declarations) {
3647
- const call = node.initializer;
3648
- if (call?.kind !== SyntaxKind.CallExpression) continue;
3649
- if (call.expression.getText() !== importName) continue;
3650
- if (call.arguments.length !== 2) {
3651
- throw new Error(
3652
- "Invalid number of arguments when initializing orchid orm"
3653
- );
3654
- }
3655
- const object = call.arguments[1];
3656
- if (object?.kind !== SyntaxKind.ObjectLiteralExpression) {
3657
- throw new Error(
3658
- "Second argument of orchidORM must be an object literal"
3659
- );
3660
- }
3661
- return { config: call.arguments[0], tablesList: object };
3662
- }
3663
- }
3664
- throw new Error("List of tables is not found in main file");
3665
- };
3666
- const addChange = (content, changes, at, text, end = at) => {
3667
- if (changes.length === 0) {
3668
- changes.push([0, at], text, [end, content.length]);
3669
- } else {
3670
- const last = changes[changes.length - 1];
3671
- last[1] = at;
3672
- changes.push(text, [end, content.length]);
3673
- }
3674
- };
3675
- const replaceContent = (content, changes, from, to, text) => {
3676
- addChange(content, changes, from, text, to);
3677
- };
3678
- const applyChanges = (content, changes) => {
3679
- return changes.length ? changes.map(
3680
- (item) => typeof item === "string" ? item : content.slice(item[0], item[1])
3681
- ).join("") : content;
3682
- };
3683
-
3684
- const pull = async (adapters, config) => {
3685
- if (!config.dbPath || !config.baseTable) {
3686
- throw new Error(
3687
- `\`${config.dbPath ? "baseTable" : "dbPath"}\` setting must be set in the migrations config for pull command`
3688
- );
3689
- }
3690
- const baseTablePath = config.baseTable.getFilePath();
3691
- const baseTableExportedAs = config.baseTable.exportAs;
3692
- const [adapter] = adapters;
3693
- const adapterSchema = adapter.getSchema();
3694
- const currentSchema = (typeof adapterSchema === "function" ? adapterSchema() : adapterSchema) ?? "public";
3695
- const ctx = makeStructureToAstCtx(config, currentSchema);
3696
- const asts = await structureToAst(ctx, adapter, config);
3697
- const { tableInfos, fkeys } = getTableInfosAndFKeys(asts, config);
3698
- const exclusiveWriteOptions = { flag: "wx" };
3699
- const pendingFileWrites = [];
3700
- const tables = {};
3701
- const extensions = [];
3702
- const domains = [];
3703
- let firstTable;
3704
- for (const ast of asts) {
3705
- switch (ast.type) {
3706
- case "table": {
3707
- const table = appCodeGenTable(
3708
- tableInfos,
3709
- fkeys,
3710
- ast,
3711
- baseTablePath,
3712
- baseTableExportedAs,
3713
- currentSchema
3714
- );
3715
- tables[table.key] = table;
3716
- if (!firstTable) firstTable = table;
3717
- pendingFileWrites.push([
3718
- table.path,
3719
- table.content,
3720
- exclusiveWriteOptions
3721
- ]);
3722
- break;
3723
- }
3724
- case "extension": {
3725
- extensions.push({
3726
- name: ast.schema ? `${ast.schema}.${ast.name}` : ast.name,
3727
- version: ast.version
3728
- });
3729
- break;
3730
- }
3731
- case "domain": {
3732
- domains.push(ast);
3733
- break;
3734
- }
3735
- }
3736
- }
3737
- if (!firstTable && !extensions.length && !domains.length) {
3738
- await adapter.close();
3739
- return;
3740
- }
3741
- let dbPath = path.resolve(config.basePath, config.dbPath);
3742
- if (!dbPath.endsWith(".ts")) dbPath += ".ts";
3743
- const content = await appCodeGenUpdateDbFile(
3744
- dbPath,
3745
- tables,
3746
- extensions,
3747
- domains,
3748
- currentSchema
3749
- );
3750
- if (content) pendingFileWrites.push([dbPath, content]);
3751
- if (firstTable) {
3752
- await fs.mkdir(path.dirname(firstTable.path), { recursive: true });
3753
- }
3754
- await Promise.all(
3755
- pendingFileWrites.map(
3756
- ([path2, content2, options]) => fs.writeFile(path2, content2, options).then(() => {
3757
- config.logger?.log(`Created ${pathToLog(path2)}`);
3758
- })
3759
- )
3760
- );
3761
- const version = await makeFileVersion({}, config);
3762
- await generate(adapters, config, ["pull"], { adapter, version });
3763
- await Promise.all(
3764
- adapters.map(async (adapter2) => {
3765
- const silentAdapter = adapter2;
3766
- silentAdapter.silentArrays = adapter2.arrays;
3767
- await saveMigratedVersion(silentAdapter, version, "pull.ts", config);
3768
- await adapter2.close();
3769
- })
3770
- );
3771
- };
3772
-
3773
- rakeDbCommands.g = rakeDbCommands.generate = {
3774
- run: generate,
3775
- help: "gen migration from OrchidORM tables",
3776
- helpArguments: {
3777
- "no arguments": '"generated" is a default file name',
3778
- "migration-name": "set migration file name",
3779
- up: "auto-apply migration",
3780
- "migration-name up": "with a custom name and apply it"
3781
- },
3782
- helpAfter: "reset"
3783
- };
3784
- rakeDbCommands.pull.run = pull;
3785
- rakeDbCommands.pull.help = "generate ORM tables and a migration for an existing database";
3786
- //# sourceMappingURL=node-postgres.mjs.map
5
+ //# sourceMappingURL=node-postgres.mjs.map