@payloadcms/db-postgres 3.0.0-canary.d894ac7 → 3.0.0-canary.dc8b1fe
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/connect.d.ts.map +1 -1
- package/dist/connect.js +25 -6
- package/dist/connect.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -5
- package/dist/index.js.map +1 -1
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -1
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +3 -1
- package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -1
- package/dist/predefinedMigrations/v2-v3/index.js +2 -2
- package/dist/predefinedMigrations/v2-v3/index.js.map +1 -1
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -1
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +9 -3
- package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -1
- package/dist/types.d.ts +25 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +12 -10
package/dist/connect.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAW,MAAM,SAAS,CAAA;AA6C/C,eAAO,MAAM,OAAO,EAAE,
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAW,MAAM,SAAS,CAAA;AA6C/C,eAAO,MAAM,OAAO,EAAE,OA0ErB,CAAA"}
|
package/dist/connect.js
CHANGED
@@ -8,7 +8,7 @@ const connectWithReconnect = async function({ adapter, payload, reconnect = fals
|
|
8
8
|
} else {
|
9
9
|
try {
|
10
10
|
result = await adapter.pool.connect();
|
11
|
-
} catch (
|
11
|
+
} catch (ignore) {
|
12
12
|
setTimeout(()=>{
|
13
13
|
payload.logger.info('Reconnecting to postgres');
|
14
14
|
void connectWithReconnect({
|
@@ -31,7 +31,7 @@ const connectWithReconnect = async function({ adapter, payload, reconnect = fals
|
|
31
31
|
reconnect: true
|
32
32
|
});
|
33
33
|
}
|
34
|
-
} catch (
|
34
|
+
} catch (ignore) {
|
35
35
|
// swallow error
|
36
36
|
}
|
37
37
|
});
|
@@ -55,7 +55,8 @@ export const connect = async function connect(options = {
|
|
55
55
|
});
|
56
56
|
}
|
57
57
|
const logger = this.logger || false;
|
58
|
-
this.drizzle = drizzle(
|
58
|
+
this.drizzle = drizzle({
|
59
|
+
client: this.pool,
|
59
60
|
logger,
|
60
61
|
schema: this.schema
|
61
62
|
});
|
@@ -69,15 +70,33 @@ export const connect = async function connect(options = {
|
|
69
70
|
}
|
70
71
|
}
|
71
72
|
} catch (err) {
|
72
|
-
|
73
|
-
|
73
|
+
if (err.message?.match(/database .* does not exist/i) && !this.disableCreateDatabase) {
|
74
|
+
// capitalize first char of the err msg
|
75
|
+
this.payload.logger.info(`${err.message.charAt(0).toUpperCase() + err.message.slice(1)}, creating...`);
|
76
|
+
const isCreated = await this.createDatabase();
|
77
|
+
if (isCreated) {
|
78
|
+
await this.connect(options);
|
79
|
+
return;
|
80
|
+
}
|
81
|
+
} else {
|
82
|
+
this.payload.logger.error({
|
83
|
+
err,
|
84
|
+
msg: `Error: cannot connect to Postgres. Details: ${err.message}`
|
85
|
+
});
|
86
|
+
}
|
87
|
+
if (typeof this.rejectInitializing === 'function') {
|
88
|
+
this.rejectInitializing();
|
89
|
+
}
|
74
90
|
process.exit(1);
|
75
91
|
}
|
92
|
+
await this.createExtensions();
|
76
93
|
// Only push schema if not in production
|
77
94
|
if (process.env.NODE_ENV !== 'production' && process.env.PAYLOAD_MIGRATING !== 'true' && this.push !== false) {
|
78
95
|
await pushDevSchema(this);
|
79
96
|
}
|
80
|
-
if (typeof this.resolveInitializing === 'function')
|
97
|
+
if (typeof this.resolveInitializing === 'function') {
|
98
|
+
this.resolveInitializing();
|
99
|
+
}
|
81
100
|
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
|
82
101
|
await this.migrate({
|
83
102
|
migrations: this.prodMigrations
|
package/dist/connect.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { Connect, Payload } from 'payload'\n\nimport { pushDevSchema } from '@payloadcms/drizzle'\nimport { drizzle } from 'drizzle-orm/node-postgres'\nimport pg from 'pg'\n\nimport type { PostgresAdapter } from './types.js'\n\nconst connectWithReconnect = async function ({\n adapter,\n payload,\n reconnect = false,\n}: {\n adapter: PostgresAdapter\n payload: Payload\n reconnect?: boolean\n}) {\n let result\n\n if (!reconnect) {\n result = await adapter.pool.connect()\n } else {\n try {\n result = await adapter.pool.connect()\n } catch (
|
1
|
+
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { Connect, Payload } from 'payload'\n\nimport { pushDevSchema } from '@payloadcms/drizzle'\nimport { drizzle } from 'drizzle-orm/node-postgres'\nimport pg from 'pg'\n\nimport type { PostgresAdapter } from './types.js'\n\nconst connectWithReconnect = async function ({\n adapter,\n payload,\n reconnect = false,\n}: {\n adapter: PostgresAdapter\n payload: Payload\n reconnect?: boolean\n}) {\n let result\n\n if (!reconnect) {\n result = await adapter.pool.connect()\n } else {\n try {\n result = await adapter.pool.connect()\n } catch (ignore) {\n setTimeout(() => {\n payload.logger.info('Reconnecting to postgres')\n void connectWithReconnect({ adapter, payload, reconnect: true })\n }, 1000)\n }\n }\n if (!result) {\n return\n }\n result.prependListener('error', (err) => {\n try {\n if (err.code === 'ECONNRESET') {\n void connectWithReconnect({ adapter, payload, reconnect: true })\n }\n } catch (ignore) {\n // swallow error\n }\n })\n}\n\nexport const connect: Connect = async function connect(\n this: PostgresAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n this.schema = {\n pgSchema: this.pgSchema,\n ...this.tables,\n ...this.relations,\n ...this.enums,\n }\n\n try {\n if (!this.pool) {\n this.pool = new pg.Pool(this.poolOptions)\n await connectWithReconnect({ adapter: this, payload: this.payload })\n }\n\n const logger = this.logger || false\n this.drizzle = drizzle({ client: this.pool, logger, schema: this.schema })\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info(`---- DROPPING TABLES SCHEMA(${this.schemaName || 'public'}) ----`)\n await this.dropDatabase({ adapter: this })\n this.payload.logger.info('---- DROPPED TABLES ----')\n }\n }\n } catch (err) {\n if (err.message?.match(/database .* does not exist/i) && !this.disableCreateDatabase) {\n // capitalize first char of the err msg\n this.payload.logger.info(\n `${err.message.charAt(0).toUpperCase() + err.message.slice(1)}, creating...`,\n )\n const isCreated = await this.createDatabase()\n\n if (isCreated) {\n await this.connect(options)\n return\n }\n } else {\n this.payload.logger.error({\n err,\n msg: `Error: cannot connect to Postgres. Details: ${err.message}`,\n })\n }\n\n if (typeof this.rejectInitializing === 'function') {\n this.rejectInitializing()\n }\n process.exit(1)\n }\n\n await this.createExtensions()\n\n // Only push schema if not in production\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.PAYLOAD_MIGRATING !== 'true' &&\n this.push !== false\n ) {\n await pushDevSchema(this as unknown as DrizzleAdapter)\n }\n\n if (typeof this.resolveInitializing === 'function') {\n this.resolveInitializing()\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations })\n }\n}\n"],"names":["pushDevSchema","drizzle","pg","connectWithReconnect","adapter","payload","reconnect","result","pool","connect","ignore","setTimeout","logger","info","prependListener","err","code","options","hotReload","schema","pgSchema","tables","relations","enums","Pool","poolOptions","client","process","env","PAYLOAD_DROP_DATABASE","schemaName","dropDatabase","message","match","disableCreateDatabase","charAt","toUpperCase","slice","isCreated","createDatabase","error","msg","rejectInitializing","exit","createExtensions","NODE_ENV","PAYLOAD_MIGRATING","push","resolveInitializing","prodMigrations","migrate","migrations"],"mappings":"AAGA,SAASA,aAAa,QAAQ,sBAAqB;AACnD,SAASC,OAAO,QAAQ,4BAA2B;AACnD,OAAOC,QAAQ,KAAI;AAInB,MAAMC,uBAAuB,eAAgB,EAC3CC,OAAO,EACPC,OAAO,EACPC,YAAY,KAAK,EAKlB;IACC,IAAIC;IAEJ,IAAI,CAACD,WAAW;QACdC,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;IACrC,OAAO;QACL,IAAI;YACFF,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;QACrC,EAAE,OAAOC,QAAQ;YACfC,WAAW;gBACTN,QAAQO,MAAM,CAACC,IAAI,CAAC;gBACpB,KAAKV,qBAAqB;oBAAEC;oBAASC;oBAASC,WAAW;gBAAK;YAChE,GAAG;QACL;IACF;IACA,IAAI,CAACC,QAAQ;QACX;IACF;IACAA,OAAOO,eAAe,CAAC,SAAS,CAACC;QAC/B,IAAI;YACF,IAAIA,IAAIC,IAAI,KAAK,cAAc;gBAC7B,KAAKb,qBAAqB;oBAAEC;oBAASC;oBAASC,WAAW;gBAAK;YAChE;QACF,EAAE,OAAOI,QAAQ;QACf,gBAAgB;QAClB;IACF;AACF;AAEA,OAAO,MAAMD,UAAmB,eAAeA,QAE7CQ,UAAU;IACRC,WAAW;AACb,CAAC;IAED,MAAM,EAAEA,SAAS,EAAE,GAAGD;IAEtB,IAAI,CAACE,MAAM,GAAG;QACZC,UAAU,IAAI,CAACA,QAAQ;QACvB,GAAG,IAAI,CAACC,MAAM;QACd,GAAG,IAAI,CAACC,SAAS;QACjB,GAAG,IAAI,CAACC,KAAK;IACf;IAEA,IAAI;QACF,IAAI,CAAC,IAAI,CAACf,IAAI,EAAE;YACd,IAAI,CAACA,IAAI,GAAG,IAAIN,GAAGsB,IAAI,CAAC,IAAI,CAACC,WAAW;YACxC,MAAMtB,qBAAqB;gBAAEC,SAAS,IAAI;gBA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AACC,gBAAgB;IAE3B,wCAAwC;IACxC,IACEjB,QAAQC,GAAG,CAACiB,QAAQ,KAAK,gBACzBlB,QAAQC,GAAG,CAACkB,iBAAiB,KAAK,UAClC,IAAI,CAACC,IAAI,KAAK,OACd;QACA,MAAM/C,cAAc,IAAI;IAC1B;IAEA,IAAI,OAAO,IAAI,CAACgD,mBAAmB,KAAK,YAAY;QAClD,IAAI,CAACA,mBAAmB;IAC1B;IAEA,IAAIrB,QAAQC,GAAG,CAACiB,QAAQ,KAAK,gBAAgB,IAAI,CAACI,cAAc,EAAE;QAChE,MAAM,IAAI,CAACC,OAAO,CAAC;YAAEC,YAAY,IAAI,CAACF,cAAc;QAAC;IACvD;AACF,EAAC"}
|
package/dist/index.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAW,MAAM,SAAS,CAAA;
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAW,MAAM,SAAS,CAAA;AAuD1D,OAAO,KAAK,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIvD,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,kBAAkB,CAAC,eAAe,CAAC,CAyH/E;AAED,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AAClF,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/index.js
CHANGED
@@ -1,7 +1,7 @@
|
|
1
|
-
import { beginTransaction, commitTransaction, count, create, createGlobal, createGlobalVersion, createVersion, deleteMany, deleteOne, deleteVersions, destroy, find, findGlobal, findGlobalVersions, findMigrationDir, findOne, findVersions, migrate, migrateDown, migrateFresh, migrateRefresh, migrateReset, migrateStatus, operatorMap, queryDrafts, rollbackTransaction, updateGlobal, updateGlobalVersion, updateOne, updateVersion } from '@payloadcms/drizzle';
|
2
|
-
import { convertPathToJSONTraversal, countDistinct, createJSONQuery, createMigration, defaultDrizzleSnapshot, deleteWhere, dropDatabase, execute, getMigrationTemplate, init, insert, requireDrizzleKit } from '@payloadcms/drizzle/postgres';
|
1
|
+
import { beginTransaction, commitTransaction, count, countGlobalVersions, countVersions, create, createGlobal, createGlobalVersion, createVersion, deleteMany, deleteOne, deleteVersions, destroy, find, findGlobal, findGlobalVersions, findMigrationDir, findOne, findVersions, migrate, migrateDown, migrateFresh, migrateRefresh, migrateReset, migrateStatus, operatorMap, queryDrafts, rollbackTransaction, updateGlobal, updateGlobalVersion, updateOne, updateVersion } from '@payloadcms/drizzle';
|
2
|
+
import { convertPathToJSONTraversal, countDistinct, createDatabase, createExtensions, createJSONQuery, createMigration, defaultDrizzleSnapshot, deleteWhere, dropDatabase, execute, getMigrationTemplate, init, insert, requireDrizzleKit } from '@payloadcms/drizzle/postgres';
|
3
3
|
import { pgEnum, pgSchema, pgTable } from 'drizzle-orm/pg-core';
|
4
|
-
import { createDatabaseAdapter } from 'payload';
|
4
|
+
import { createDatabaseAdapter, defaultBeginTransaction } from 'payload';
|
5
5
|
import { connect } from './connect.js';
|
6
6
|
export function postgresAdapter(args) {
|
7
7
|
const postgresIDType = args.idType || 'serial';
|
@@ -23,11 +23,21 @@ export function postgresAdapter(args) {
|
|
23
23
|
table: pgTable
|
24
24
|
};
|
25
25
|
}
|
26
|
+
const extensions = (args.extensions ?? []).reduce((acc, name)=>{
|
27
|
+
acc[name] = true;
|
28
|
+
return acc;
|
29
|
+
}, {});
|
26
30
|
return createDatabaseAdapter({
|
27
31
|
name: 'postgres',
|
32
|
+
afterSchemaInit: args.afterSchemaInit ?? [],
|
33
|
+
beforeSchemaInit: args.beforeSchemaInit ?? [],
|
34
|
+
createDatabase,
|
35
|
+
createExtensions,
|
28
36
|
defaultDrizzleSnapshot,
|
37
|
+
disableCreateDatabase: args.disableCreateDatabase ?? false,
|
29
38
|
drizzle: undefined,
|
30
39
|
enums: {},
|
40
|
+
extensions,
|
31
41
|
features: {
|
32
42
|
json: true
|
33
43
|
},
|
@@ -50,15 +60,18 @@ export function postgresAdapter(args) {
|
|
50
60
|
sessions: {},
|
51
61
|
tableNameMap: new Map(),
|
52
62
|
tables: {},
|
63
|
+
tablesFilter: args.tablesFilter,
|
53
64
|
transactionOptions: args.transactionOptions || undefined,
|
54
65
|
versionsSuffix: args.versionsSuffix || '_v',
|
55
66
|
// DatabaseAdapter
|
56
|
-
beginTransaction: args.transactionOptions === false ?
|
67
|
+
beginTransaction: args.transactionOptions === false ? defaultBeginTransaction() : beginTransaction,
|
57
68
|
commitTransaction,
|
58
69
|
connect,
|
59
70
|
convertPathToJSONTraversal,
|
60
71
|
count,
|
61
72
|
countDistinct,
|
73
|
+
countGlobalVersions,
|
74
|
+
countVersions,
|
62
75
|
create,
|
63
76
|
createGlobal,
|
64
77
|
createGlobalVersion,
|
@@ -78,6 +91,7 @@ export function postgresAdapter(args) {
|
|
78
91
|
findGlobalVersions,
|
79
92
|
findOne,
|
80
93
|
findVersions,
|
94
|
+
indexes: new Set(),
|
81
95
|
init,
|
82
96
|
insert,
|
83
97
|
migrate,
|
@@ -87,6 +101,7 @@ export function postgresAdapter(args) {
|
|
87
101
|
migrateReset,
|
88
102
|
migrateStatus,
|
89
103
|
migrationDir,
|
104
|
+
packageName: '@payloadcms/db-postgres',
|
90
105
|
payload,
|
91
106
|
queryDrafts,
|
92
107
|
rejectInitializing,
|
@@ -96,7 +111,8 @@ export function postgresAdapter(args) {
|
|
96
111
|
updateGlobal,
|
97
112
|
updateGlobalVersion,
|
98
113
|
updateOne,
|
99
|
-
updateVersion
|
114
|
+
updateVersion,
|
115
|
+
upsert: updateOne
|
100
116
|
});
|
101
117
|
}
|
102
118
|
return {
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { DatabaseAdapterObj, Payload } from 'payload'\n\nimport {\n beginTransaction,\n commitTransaction,\n count,\n create,\n createGlobal,\n createGlobalVersion,\n createVersion,\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n find,\n findGlobal,\n findGlobalVersions,\n findMigrationDir,\n findOne,\n findVersions,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n operatorMap,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n} from '@payloadcms/drizzle'\nimport {\n convertPathToJSONTraversal,\n countDistinct,\n createJSONQuery,\n createMigration,\n defaultDrizzleSnapshot,\n deleteWhere,\n dropDatabase,\n execute,\n getMigrationTemplate,\n init,\n insert,\n requireDrizzleKit,\n} from '@payloadcms/drizzle/postgres'\nimport { pgEnum, pgSchema, pgTable } from 'drizzle-orm/pg-core'\nimport { createDatabaseAdapter } from 'payload'\n\nimport type { Args, PostgresAdapter } from './types.js'\n\nimport { connect } from './connect.js'\n\nexport function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter> {\n const postgresIDType = args.idType || 'serial'\n const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'\n\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(args.migrationDir)\n let resolveInitializing\n let rejectInitializing\n let adapterSchema: PostgresAdapter['pgSchema']\n\n const initializing = new Promise<void>((res, rej) => {\n resolveInitializing = res\n rejectInitializing = rej\n })\n\n if (args.schemaName) {\n adapterSchema = pgSchema(args.schemaName)\n } else {\n adapterSchema = { enum: pgEnum, table: pgTable }\n }\n\n return createDatabaseAdapter<PostgresAdapter>({\n name: 'postgres',\n defaultDrizzleSnapshot,\n drizzle: undefined,\n enums: {},\n features: {\n json: true,\n },\n fieldConstraints: {},\n getMigrationTemplate,\n idType: postgresIDType,\n initializing,\n localesSuffix: args.localesSuffix || '_locales',\n logger: args.logger,\n operators: operatorMap,\n pgSchema: adapterSchema,\n pool: undefined,\n poolOptions: args.pool,\n prodMigrations: args.prodMigrations,\n push: args.push,\n relations: {},\n relationshipsSuffix: args.relationshipsSuffix || '_rels',\n schema: {},\n schemaName: args.schemaName,\n sessions: {},\n tableNameMap: new Map<string, string>(),\n tables: {},\n transactionOptions: args.transactionOptions || undefined,\n versionsSuffix: args.versionsSuffix || '_v',\n\n // DatabaseAdapter\n beginTransaction
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { DatabaseAdapterObj, Payload } from 'payload'\n\nimport {\n beginTransaction,\n commitTransaction,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createVersion,\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n find,\n findGlobal,\n findGlobalVersions,\n findMigrationDir,\n findOne,\n findVersions,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n operatorMap,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n} from '@payloadcms/drizzle'\nimport {\n convertPathToJSONTraversal,\n countDistinct,\n createDatabase,\n createExtensions,\n createJSONQuery,\n createMigration,\n defaultDrizzleSnapshot,\n deleteWhere,\n dropDatabase,\n execute,\n getMigrationTemplate,\n init,\n insert,\n requireDrizzleKit,\n} from '@payloadcms/drizzle/postgres'\nimport { pgEnum, pgSchema, pgTable } from 'drizzle-orm/pg-core'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { Args, PostgresAdapter } from './types.js'\n\nimport { connect } from './connect.js'\n\nexport function postgresAdapter(args: Args): DatabaseAdapterObj<PostgresAdapter> {\n const postgresIDType = args.idType || 'serial'\n const payloadIDType = postgresIDType === 'serial' ? 'number' : 'text'\n\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(args.migrationDir)\n let resolveInitializing\n let rejectInitializing\n let adapterSchema: PostgresAdapter['pgSchema']\n\n const initializing = new Promise<void>((res, rej) => {\n resolveInitializing = res\n rejectInitializing = rej\n })\n\n if (args.schemaName) {\n adapterSchema = pgSchema(args.schemaName)\n } else {\n adapterSchema = { enum: pgEnum, table: pgTable }\n }\n\n const extensions = (args.extensions ?? []).reduce((acc, name) => {\n acc[name] = true\n return acc\n }, {})\n\n return createDatabaseAdapter<PostgresAdapter>({\n name: 'postgres',\n afterSchemaInit: args.afterSchemaInit ?? [],\n beforeSchemaInit: args.beforeSchemaInit ?? [],\n createDatabase,\n createExtensions,\n defaultDrizzleSnapshot,\n disableCreateDatabase: args.disableCreateDatabase ?? false,\n drizzle: undefined,\n enums: {},\n extensions,\n features: {\n json: true,\n },\n fieldConstraints: {},\n getMigrationTemplate,\n idType: postgresIDType,\n initializing,\n localesSuffix: args.localesSuffix || '_locales',\n logger: args.logger,\n operators: operatorMap,\n pgSchema: adapterSchema,\n pool: undefined,\n poolOptions: args.pool,\n prodMigrations: args.prodMigrations,\n push: args.push,\n relations: {},\n relationshipsSuffix: args.relationshipsSuffix || '_rels',\n schema: {},\n schemaName: args.schemaName,\n sessions: {},\n tableNameMap: new Map<string, string>(),\n tables: {},\n tablesFilter: args.tablesFilter,\n transactionOptions: args.transactionOptions || undefined,\n versionsSuffix: args.versionsSuffix || '_v',\n\n // DatabaseAdapter\n beginTransaction:\n args.transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n commitTransaction,\n connect,\n convertPathToJSONTraversal,\n count,\n countDistinct,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createJSONQuery,\n createMigration,\n createVersion,\n defaultIDType: payloadIDType,\n deleteMany,\n deleteOne,\n deleteVersions,\n deleteWhere,\n destroy,\n dropDatabase,\n execute,\n find,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n indexes: new Set<string>(),\n init,\n insert,\n migrate,\n migrateDown,\n migrateFresh,\n migrateRefresh,\n migrateReset,\n migrateStatus,\n migrationDir,\n packageName: '@payloadcms/db-postgres',\n payload,\n queryDrafts,\n rejectInitializing,\n requireDrizzleKit,\n resolveInitializing,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert: updateOne,\n })\n }\n\n return {\n defaultIDType: payloadIDType,\n init: adapter,\n }\n}\n\nexport type { MigrateDownArgs, MigrateUpArgs } from '@payloadcms/drizzle/postgres'\nexport { sql } from 'drizzle-orm'\n"],"names":["beginTransaction","commitTransaction","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findGlobal","findGlobalVersions","findMigrationDir","findOne","findVersions","migrate","migrateDown","migrateFresh","migrateRefresh","migrateReset","migrateStatus","operatorMap","queryDrafts","rollbackTransaction","updateGlobal","updateGlobalVersion","updateOne","updateVersion","convertPathToJSONTraversal","countDistinct","createDatabase","createExtensions","createJSONQuery","createMigration","defaultDrizzleSnapshot","deleteWhere","dropDatabase","execute","getMigrationTemplate","init","insert","requireDrizzleKit","pgEnum","pgSchema","pgTable","createDatabaseAdapter","defaultBeginTransaction","connect","postgresAdapter","args","postgresIDType","idType","payloadIDType","adapter","payload","migrationDir","resolveInitializing","rejectInitializing","adapterSchema","initializing","Promise","res","rej","schemaName","enum","table","extensions","reduce","acc","name","afterSchemaInit","beforeSchemaInit","disableCreateDatabase","drizzle","undefined","enums","features","json","fieldConstraints","localesSuffix","logger","operators","pool","poolOptions","prodMigrations","push","relations","relationshipsSuffix","schema","sessions","tableNameMap","Map","tables","tablesFilter","transactionOptions","versionsSuffix","defaultIDType","indexes","Set","packageName","upsert","sql"],"mappings":"AAEA,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,KAAK,EACLC,mBAAmB,EACnBC,aAAa,EACbC,MAAM,EACNC,YAAY,EACZC,mBAAmB,EACnBC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,cAAc,EACdC,OAAO,EACPC,IAAI,EACJC,UAAU,EACVC,kBAAkB,EAClBC,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;QACfb,MAAMc;IACR;AACF;AAGA,SAASgD,GAAG,QAAQ,cAAa"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"traverseFields.d.ts","sourceRoot":"","sources":["../../../../src/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAIpC,KAAK,IAAI,GAAG;IACV,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CAChC,CAAA;AAED,eAAO,MAAM,cAAc,wCAAyC,IAAI,
|
1
|
+
{"version":3,"file":"traverseFields.d.ts","sourceRoot":"","sources":["../../../../src/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAIpC,KAAK,IAAI,GAAG;IACV,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;CAChC,CAAA;AAED,eAAO,MAAM,cAAc,wCAAyC,IAAI,SA4MvE,CAAA"}
|
@@ -167,7 +167,9 @@ export const traverseFields = ({ doc, fields, locale, path, rows })=>{
|
|
167
167
|
} else {
|
168
168
|
const matchedRelationship = rows.find((row)=>{
|
169
169
|
const matchesPath = row.path === relationshipPath;
|
170
|
-
if (locale)
|
170
|
+
if (locale) {
|
171
|
+
return matchesPath && locale === row.locale;
|
172
|
+
}
|
171
173
|
return row.path === relationshipPath;
|
172
174
|
});
|
173
175
|
if (matchedRelationship) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../src/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { tabHasName } from 'payload/shared'\n\ntype Args = {\n doc: Record<string, unknown>\n fields: Field[]\n locale?: string\n path: string\n rows: Record<string, unknown>[]\n}\n\nexport const traverseFields = ({ doc, fields, locale, path, rows }: Args) => {\n fields.forEach((field) => {\n switch (field.type) {\n case 'group': {\n const newPath = `${path ? `${path}.` : ''}${field.name}`\n const newDoc = doc?.[field.name]\n\n if (typeof newDoc === 'object' && newDoc !== null) {\n if (field.localized) {\n Object.entries(newDoc).forEach(([locale, localeDoc]) => {\n return traverseFields({\n doc: localeDoc,\n fields: field.fields,\n locale,\n path: newPath,\n rows,\n })\n })\n } else {\n return traverseFields({\n doc: newDoc as Record<string, unknown>,\n fields: field.fields,\n path: newPath,\n rows,\n })\n }\n }\n\n break\n }\n\n case 'row':\n case 'collapsible': {\n return traverseFields({\n doc,\n fields: field.fields,\n path,\n rows,\n })\n }\n\n case 'array': {\n const rowData = doc?.[field.name]\n\n if (field.localized && typeof rowData === 'object' && rowData !== null) {\n Object.entries(rowData).forEach(([locale, localeRows]) => {\n if (Array.isArray(localeRows)) {\n localeRows.forEach((row, i) => {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: field.fields,\n locale,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n })\n }\n })\n }\n\n if (Array.isArray(rowData)) {\n rowData.forEach((row, i) => {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: field.fields,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n })\n }\n\n break\n }\n\n case 'blocks': {\n const rowData = doc?.[field.name]\n\n if (field.localized && typeof rowData === 'object' && rowData !== null) {\n Object.entries(rowData).forEach(([locale, localeRows]) => {\n if (Array.isArray(localeRows)) {\n localeRows.forEach((row, i) => {\n const matchedBlock = field.blocks.find((block) => block.slug === row.blockType)\n\n if (matchedBlock) {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: matchedBlock.fields,\n locale,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n }\n })\n }\n })\n }\n\n if (Array.isArray(rowData)) {\n rowData.forEach((row, i) => {\n const matchedBlock = field.blocks.find((block) => block.slug === row.blockType)\n\n if (matchedBlock) {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: matchedBlock.fields,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n }\n })\n }\n\n break\n }\n\n case 'tabs': {\n return field.tabs.forEach((tab) => {\n if (tabHasName(tab)) {\n const newDoc = doc?.[tab.name]\n const newPath = `${path ? `${path}.` : ''}${tab.name}`\n\n if (typeof newDoc === 'object' && newDoc !== null) {\n if (tab.localized) {\n Object.entries(newDoc).forEach(([locale, localeDoc]) => {\n return traverseFields({\n doc: localeDoc,\n fields: tab.fields,\n locale,\n path: newPath,\n rows,\n })\n })\n } else {\n return traverseFields({\n doc: newDoc as Record<string, unknown>,\n fields: tab.fields,\n path: newPath,\n rows,\n })\n }\n }\n } else {\n traverseFields({\n doc,\n fields: tab.fields,\n path,\n rows,\n })\n }\n })\n }\n\n case 'relationship':\n case 'upload': {\n if (typeof field.relationTo === 'string') {\n if (field.type === 'upload' || !field.hasMany) {\n const relationshipPath = `${path ? `${path}.` : ''}${field.name}`\n\n if (field.localized) {\n const matchedRelationshipsWithLocales = rows.filter(\n (row) => row.path === relationshipPath,\n )\n\n if (matchedRelationshipsWithLocales.length && !doc[field.name]) {\n doc[field.name] = {}\n }\n\n const newDoc = doc[field.name] as Record<string, unknown>\n\n matchedRelationshipsWithLocales.forEach((localeRow) => {\n if (typeof localeRow.locale === 'string') {\n const [, id] = Object.entries(localeRow).find(\n ([key, val]) =>\n val !== null && !['id', 'locale', 'order', 'parent_id', 'path'].includes(key),\n )\n\n newDoc[localeRow.locale] = id\n }\n })\n } else {\n const matchedRelationship = rows.find((row) => {\n const matchesPath = row.path === relationshipPath\n\n if (locale) return matchesPath && locale === row.locale\n\n return row.path === relationshipPath\n })\n\n if (matchedRelationship) {\n const [, id] = Object.entries(matchedRelationship).find(\n ([key, val]) =>\n val !== null && !['id', 'locale', 'order', 'parent_id', 'path'].includes(key),\n )\n\n doc[field.name] = id\n }\n }\n }\n }\n }\n }\n })\n}\n"],"names":["tabHasName","traverseFields","doc","fields","locale","path","rows","forEach","field","type","newPath","name","newDoc","localized","Object","entries","localeDoc","rowData","localeRows","Array","isArray","row","i","matchedBlock","blocks","find","block","slug","blockType","tabs","tab","relationTo","hasMany","relationshipPath","matchedRelationshipsWithLocales","filter","length","localeRow","id","key","val","includes","matchedRelationship","matchesPath"],"mappings":"AAEA,SAASA,UAAU,QAAQ,iBAAgB;AAU3C,OAAO,MAAMC,iBAAiB,CAAC,EAAEC,GAAG,EAAEC,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAQ;IACtEH,OAAOI,OAAO,CAAC,CAACC;QACd,OAAQA,MAAMC,IAAI;YAChB,KAAK;gBAAS;oBACZ,MAAMC,UAAU,CAAC,EAAEL,OAAO,CAAC,EAAEA,KAAK,CAAC,CAAC,GAAG,GAAG,EAAEG,MAAMG,IAAI,CAAC,CAAC;oBACxD,MAAMC,SAASV,KAAK,CAACM,MAAMG,IAAI,CAAC;oBAEhC,IAAI,OAAOC,WAAW,YAAYA,WAAW,MAAM;wBACjD,IAAIJ,MAAMK,SAAS,EAAE;4BACnBC,OAAOC,OAAO,CAACH,QAAQL,OAAO,CAAC,CAAC,CAACH,QAAQY,UAAU;gCACjD,OAAOf,eAAe;oCACpBC,KAAKc;oCACLb,QAAQK,MAAML,MAAM;oCACpBC;oCACAC,MAAMK;oCACNJ;gCACF;4BACF;wBACF,OAAO;4BACL,OAAOL,eAAe;gCACpBC,KAAKU;gCACLT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AAQ,QAAQ,CAAC;gDAAC;gDAAM;gDAAU;gDAAS;gDAAa;6CAAO,CAACC,QAAQ,CAACF;wCAG7E3B,MAAM,CAACyB,UAAUjC,MAAM,CAAC,GAAGkC;oCAC7B;gCACF;4BACF,OAAO;gCACL,MAAMI,sBAAsBpC,KAAKmB,IAAI,CAAC,CAACJ;oCACrC,MAAMsB,cAActB,IAAIhB,IAAI,KAAK4B;oCAEjC,IAAI7B,QAAQ,OAAOuC,eAAevC,WAAWiB,IAAIjB,MAAM;oCAEvD,OAAOiB,IAAIhB,IAAI,KAAK4B;gCACtB;gCAEA,IAAIS,qBAAqB;oCACvB,MAAM,GAAGJ,GAAG,GAAGxB,OAAOC,OAAO,CAAC2B,qBAAqBjB,IAAI,CACrD,CAAC,CAACc,KAAKC,IAAI,GACTA,QAAQ,QAAQ,CAAC;4CAAC;4CAAM;4CAAU;4CAAS;4CAAa;yCAAO,CAACC,QAAQ,CAACF;oCAG7ErC,GAAG,CAACM,MAAMG,IAAI,CAAC,GAAG2B;gCACpB;4BACF;wBACF;oBACF;gBACF;QACF;IACF;AACF,EAAC"}
|
1
|
+
{"version":3,"sources":["../../../../src/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { tabHasName } from 'payload/shared'\n\ntype Args = {\n doc: Record<string, unknown>\n fields: Field[]\n locale?: string\n path: string\n rows: Record<string, unknown>[]\n}\n\nexport const traverseFields = ({ doc, fields, locale, path, rows }: Args) => {\n fields.forEach((field) => {\n switch (field.type) {\n case 'group': {\n const newPath = `${path ? `${path}.` : ''}${field.name}`\n const newDoc = doc?.[field.name]\n\n if (typeof newDoc === 'object' && newDoc !== null) {\n if (field.localized) {\n Object.entries(newDoc).forEach(([locale, localeDoc]) => {\n return traverseFields({\n doc: localeDoc,\n fields: field.fields,\n locale,\n path: newPath,\n rows,\n })\n })\n } else {\n return traverseFields({\n doc: newDoc as Record<string, unknown>,\n fields: field.fields,\n path: newPath,\n rows,\n })\n }\n }\n\n break\n }\n\n case 'row':\n case 'collapsible': {\n return traverseFields({\n doc,\n fields: field.fields,\n path,\n rows,\n })\n }\n\n case 'array': {\n const rowData = doc?.[field.name]\n\n if (field.localized && typeof rowData === 'object' && rowData !== null) {\n Object.entries(rowData).forEach(([locale, localeRows]) => {\n if (Array.isArray(localeRows)) {\n localeRows.forEach((row, i) => {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: field.fields,\n locale,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n })\n }\n })\n }\n\n if (Array.isArray(rowData)) {\n rowData.forEach((row, i) => {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: field.fields,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n })\n }\n\n break\n }\n\n case 'blocks': {\n const rowData = doc?.[field.name]\n\n if (field.localized && typeof rowData === 'object' && rowData !== null) {\n Object.entries(rowData).forEach(([locale, localeRows]) => {\n if (Array.isArray(localeRows)) {\n localeRows.forEach((row, i) => {\n const matchedBlock = field.blocks.find((block) => block.slug === row.blockType)\n\n if (matchedBlock) {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: matchedBlock.fields,\n locale,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n }\n })\n }\n })\n }\n\n if (Array.isArray(rowData)) {\n rowData.forEach((row, i) => {\n const matchedBlock = field.blocks.find((block) => block.slug === row.blockType)\n\n if (matchedBlock) {\n return traverseFields({\n doc: row as Record<string, unknown>,\n fields: matchedBlock.fields,\n path: `${path ? `${path}.` : ''}${field.name}.${i}`,\n rows,\n })\n }\n })\n }\n\n break\n }\n\n case 'tabs': {\n return field.tabs.forEach((tab) => {\n if (tabHasName(tab)) {\n const newDoc = doc?.[tab.name]\n const newPath = `${path ? `${path}.` : ''}${tab.name}`\n\n if (typeof newDoc === 'object' && newDoc !== null) {\n if (tab.localized) {\n Object.entries(newDoc).forEach(([locale, localeDoc]) => {\n return traverseFields({\n doc: localeDoc,\n fields: tab.fields,\n locale,\n path: newPath,\n rows,\n })\n })\n } else {\n return traverseFields({\n doc: newDoc as Record<string, unknown>,\n fields: tab.fields,\n path: newPath,\n rows,\n })\n }\n }\n } else {\n traverseFields({\n doc,\n fields: tab.fields,\n path,\n rows,\n })\n }\n })\n }\n\n case 'relationship':\n case 'upload': {\n if (typeof field.relationTo === 'string') {\n if (field.type === 'upload' || !field.hasMany) {\n const relationshipPath = `${path ? `${path}.` : ''}${field.name}`\n\n if (field.localized) {\n const matchedRelationshipsWithLocales = rows.filter(\n (row) => row.path === relationshipPath,\n )\n\n if (matchedRelationshipsWithLocales.length && !doc[field.name]) {\n doc[field.name] = {}\n }\n\n const newDoc = doc[field.name] as Record<string, unknown>\n\n matchedRelationshipsWithLocales.forEach((localeRow) => {\n if (typeof localeRow.locale === 'string') {\n const [, id] = Object.entries(localeRow).find(\n ([key, val]) =>\n val !== null && !['id', 'locale', 'order', 'parent_id', 'path'].includes(key),\n )\n\n newDoc[localeRow.locale] = id\n }\n })\n } else {\n const matchedRelationship = rows.find((row) => {\n const matchesPath = row.path === relationshipPath\n\n if (locale) {\n return matchesPath && locale === row.locale\n }\n\n return row.path === relationshipPath\n })\n\n if (matchedRelationship) {\n const [, id] = Object.entries(matchedRelationship).find(\n ([key, val]) =>\n val !== null && !['id', 'locale', 'order', 'parent_id', 'path'].includes(key),\n )\n\n doc[field.name] = id\n }\n }\n }\n }\n }\n }\n })\n}\n"],"names":["tabHasName","traverseFields","doc","fields","locale","path","rows","forEach","field","type","newPath","name","newDoc","localized","Object","entries","localeDoc","rowData","localeRows","Array","isArray","row","i","matchedBlock","blocks","find","block","slug","blockType","tabs","tab","relationTo","hasMany","relationshipPath","matchedRelationshipsWithLocales","filter","length","localeRow","id","key","val","includes","matchedRelationship","matchesPath"],"mappings":"AAEA,SAASA,UAAU,QAAQ,iBAAgB;AAU3C,OAAO,MAAMC,iBAAiB,CAAC,EAAEC,GAAG,EAAEC,MAAM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,IAAI,CAAC,GAAG2B;gCACpB;4BACF;wBACF;oBACF;gBACF;QACF;IACF;AACF,EAAC"}
|
@@ -77,7 +77,7 @@ const require = createRequire(import.meta.url);
|
|
77
77
|
});
|
78
78
|
if (collection.versions) {
|
79
79
|
const versionsTableName = adapter.tableNameMap.get(`_${toSnakeCase(collection.slug)}${adapter.versionsSuffix}`);
|
80
|
-
const versionFields = buildVersionCollectionFields(collection);
|
80
|
+
const versionFields = buildVersionCollectionFields(payload.config, collection);
|
81
81
|
const versionPathsToQuery = new Set();
|
82
82
|
traverseFields({
|
83
83
|
adapter,
|
@@ -140,7 +140,7 @@ const require = createRequire(import.meta.url);
|
|
140
140
|
});
|
141
141
|
if (global.versions) {
|
142
142
|
const versionsTableName = adapter.tableNameMap.get(`_${toSnakeCase(global.slug)}${adapter.versionsSuffix}`);
|
143
|
-
const versionFields = buildVersionGlobalFields(global);
|
143
|
+
const versionFields = buildVersionGlobalFields(payload.config, global);
|
144
144
|
const versionPathsToQuery = new Set();
|
145
145
|
traverseFields({
|
146
146
|
adapter,
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/predefinedMigrations/v2-v3/index.ts"],"sourcesContent":["import type { TransactionPg } from '@payloadcms/drizzle/types'\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { Payload, PayloadRequest } from 'payload'\n\nimport { sql } from 'drizzle-orm'\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from '../../types.js'\nimport type { PathsToQuery } from './types.js'\n\nimport { groupUpSQLStatements } from './groupUpSQLStatements.js'\nimport { migrateRelationships } from './migrateRelationships.js'\nimport { traverseFields } from './traverseFields.js'\n\nconst require = createRequire(import.meta.url)\n\ntype Args = {\n debug?: boolean\n payload: Payload\n req?: Partial<PayloadRequest>\n}\n\n/**\n * Moves upload and relationship columns from the join table and into the tables while moving data\n * This is done in the following order:\n * ADD COLUMNs\n * -- manipulate data to move relationships to new columns\n * ADD CONSTRAINTs\n * NOT NULLs\n * DROP TABLEs\n * DROP CONSTRAINTs\n * DROP COLUMNs\n * @param debug\n * @param payload\n * @param req\n */\nexport const migratePostgresV2toV3 = async ({ debug, payload, req }: Args) => {\n const adapter = payload.db as unknown as PostgresAdapter\n const db = adapter.sessions[await req.transactionID].db as TransactionPg\n const dir = payload.db.migrationDir\n\n // get the drizzle migrateUpSQL from drizzle using the last schema\n const { generateDrizzleJson, generateMigration } = require('drizzle-kit/api')\n const drizzleJsonAfter = generateDrizzleJson(adapter.schema)\n\n // Get the previous migration snapshot\n const previousSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json') && !file.endsWith('relationships_v2_v3.json'))\n .sort()\n .reverse()?.[0]\n\n if (!previousSnapshot) {\n throw new Error(\n `No previous migration schema file found! A prior migration from v2 is required to migrate to v3.`,\n )\n }\n\n const drizzleJsonBefore = JSON.parse(\n fs.readFileSync(`${dir}/${previousSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n\n const generatedSQL = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n if (!generatedSQL.length) {\n payload.logger.info(`No schema changes needed.`)\n process.exit(0)\n }\n\n const sqlUpStatements = groupUpSQLStatements(generatedSQL)\n\n const addColumnsStatement = sqlUpStatements.addColumn.join('\\n')\n\n if (debug) {\n payload.logger.info('CREATING NEW RELATIONSHIP COLUMNS')\n payload.logger.info(addColumnsStatement)\n }\n\n await db.execute(sql.raw(addColumnsStatement))\n\n for (const collection of payload.config.collections) {\n const tableName = adapter.tableNameMap.get(toSnakeCase(collection.slug))\n const pathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n collectionSlug: collection.slug,\n columnPrefix: '',\n db,\n disableNotNull: false,\n fields: collection.fields,\n isVersions: false,\n newTableName: tableName,\n parentTableName: tableName,\n path: '',\n pathsToQuery,\n payload,\n rootTableName: tableName,\n })\n\n await migrateRelationships({\n adapter,\n collectionSlug: collection.slug,\n db,\n debug,\n fields: collection.fields,\n isVersions: false,\n pathsToQuery,\n payload,\n req,\n tableName,\n })\n\n if (collection.versions) {\n const versionsTableName = adapter.tableNameMap.get(\n `_${toSnakeCase(collection.slug)}${adapter.versionsSuffix}`,\n )\n const versionFields = buildVersionCollectionFields(collection)\n const versionPathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n collectionSlug: collection.slug,\n columnPrefix: '',\n db,\n disableNotNull: true,\n fields: versionFields,\n isVersions: true,\n newTableName: versionsTableName,\n parentTableName: versionsTableName,\n path: '',\n pathsToQuery: versionPathsToQuery,\n payload,\n rootTableName: versionsTableName,\n })\n\n await migrateRelationships({\n adapter,\n collectionSlug: collection.slug,\n db,\n debug,\n fields: versionFields,\n isVersions: true,\n pathsToQuery: versionPathsToQuery,\n payload,\n req,\n tableName: versionsTableName,\n })\n }\n }\n\n for (const global of payload.config.globals) {\n const tableName = adapter.tableNameMap.get(toSnakeCase(global.slug))\n\n const pathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n columnPrefix: '',\n db,\n disableNotNull: false,\n fields: global.fields,\n globalSlug: global.slug,\n isVersions: false,\n newTableName: tableName,\n parentTableName: tableName,\n path: '',\n pathsToQuery,\n payload,\n rootTableName: tableName,\n })\n\n await migrateRelationships({\n adapter,\n db,\n debug,\n fields: global.fields,\n globalSlug: global.slug,\n isVersions: false,\n pathsToQuery,\n payload,\n req,\n tableName,\n })\n\n if (global.versions) {\n const versionsTableName = adapter.tableNameMap.get(\n `_${toSnakeCase(global.slug)}${adapter.versionsSuffix}`,\n )\n\n const versionFields = buildVersionGlobalFields(global)\n\n const versionPathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n columnPrefix: '',\n db,\n disableNotNull: true,\n fields: versionFields,\n globalSlug: global.slug,\n isVersions: true,\n newTableName: versionsTableName,\n parentTableName: versionsTableName,\n path: '',\n pathsToQuery: versionPathsToQuery,\n payload,\n rootTableName: versionsTableName,\n })\n\n await migrateRelationships({\n adapter,\n db,\n debug,\n fields: versionFields,\n globalSlug: global.slug,\n isVersions: true,\n pathsToQuery: versionPathsToQuery,\n payload,\n req,\n tableName: versionsTableName,\n })\n }\n }\n\n // ADD CONSTRAINT\n const addConstraintsStatement = sqlUpStatements.addConstraint.join('\\n')\n\n if (debug) {\n payload.logger.info('ADDING CONSTRAINTS')\n payload.logger.info(addConstraintsStatement)\n }\n\n await db.execute(sql.raw(addConstraintsStatement))\n\n // NOT NULL\n const notNullStatements = sqlUpStatements.notNull.join('\\n')\n\n if (debug) {\n payload.logger.info('NOT NULL CONSTRAINTS')\n payload.logger.info(notNullStatements)\n }\n\n await db.execute(sql.raw(notNullStatements))\n\n // DROP TABLE\n const dropTablesStatement = sqlUpStatements.dropTable.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING TABLES')\n payload.logger.info(dropTablesStatement)\n }\n\n await db.execute(sql.raw(dropTablesStatement))\n\n // DROP CONSTRAINT\n const dropConstraintsStatement = sqlUpStatements.dropConstraint.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING CONSTRAINTS')\n payload.logger.info(dropConstraintsStatement)\n }\n\n await db.execute(sql.raw(dropConstraintsStatement))\n\n // DROP COLUMN\n const dropColumnsStatement = sqlUpStatements.dropColumn.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING COLUMNS')\n payload.logger.info(dropColumnsStatement)\n }\n\n await db.execute(sql.raw(dropColumnsStatement))\n}\n"],"names":["sql","fs","createRequire","buildVersionCollectionFields","buildVersionGlobalFields","toSnakeCase","groupUpSQLStatements","migrateRelationships","traverseFields","require","url","migratePostgresV2toV3","debug","payload","req","adapter","db","sessions","transactionID","dir","migrationDir","generateDrizzleJson","generateMigration","drizzleJsonAfter","schema","previousSnapshot","readdirSync","filter","file","endsWith","sort","reverse","Error","drizzleJsonBefore","JSON","parse","readFileSync","generatedSQL","length","logger","info","process","exit","sqlUpStatements","addColumnsStatement","addColumn","join","execute","raw","collection","config","collections","tableName","tableNameMap","get","slug","pathsToQuery","Set","collectionSlug","columnPrefix","disableNotNull","fields","isVersions","newTableName","parentTableName","path","rootTableName","versions","versionsTableName","versionsSuffix","versionFields","versionPathsToQuery","global","globals","globalSlug","addConstraintsStatement","addConstraint","notNullStatements","notNull","dropTablesStatement","dropTable","dropConstraintsStatement","dropConstraint","dropColumnsStatement","dropColumn"],"mappings":"AAIA,SAASA,GAAG,QAAQ,cAAa;AACjC,OAAOC,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,SAAQ;AACtC,SAASC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAS;AAChF,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,MAAMC,UAAUP,cAAc,YAAYQ,GAAG;AAQ7C;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,wBAAwB,OAAO,EAAEC,KAAK,EAAEC,OAAO,EAAEC,GAAG,EAAQ;IACvE,MAAMC,UAAUF,QAAQG,EAAE;IAC1B,MAAMA,KAAKD,QAAQE,QAAQ,CAAC,MAAMH,IAAII,aAAa,CAAC,CAACF,EAAE;IACvD,MAAMG,MAAMN,QAAQG,EAAE,CAACI,YAAY;IAEnC,kEAAkE;IAClE,MAAM,EAAEC,mBAAmB,EAAEC,iBAAiB,EAAE,GAAGb,QAAQ;IAC3D,MAAMc,mBAAmBF,oBAAoBN,QAAQS,MAAM;IAE3D,sCAAsC;IACtC,MAAMC,mBAAmBxB,GACtByB,WAAW,CAACP,KACZQ,MAAM,CAAC,CAACC,OAASA,KAAKC,QAAQ,CAAC,YAAY,CAACD,KAAKC,QAAQ,CAAC,6BAC1DC,IAAI,GACJC,OAAO,IAAI,CAAC,EAAE;IAEjB,IAAI,CAACN,kBAAkB;QACrB,MAAM,IAAIO,MACR,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O;QACTC,QAAQ0B,MAAM,CAACC,IAAI,CAAC;QACpB3B,QAAQ0B,MAAM,CAACC,IAAI,CAACyC;IACtB;IAEA,MAAMjE,GAAG+B,OAAO,CAAC/C,IAAIgD,GAAG,CAACiC;IAEzB,cAAc;IACd,MAAME,uBAAuBxC,gBAAgByC,UAAU,CAACtC,IAAI,CAAC;IAE7D,IAAIlC,OAAO;QACTC,QAAQ0B,MAAM,CAACC,IAAI,CAAC;QACpB3B,QAAQ0B,MAAM,CAACC,IAAI,CAAC2C;IACtB;IAEA,MAAMnE,GAAG+B,OAAO,CAAC/C,IAAIgD,GAAG,CAACmC;AAC3B,EAAC"}
|
1
|
+
{"version":3,"sources":["../../../src/predefinedMigrations/v2-v3/index.ts"],"sourcesContent":["import type { TransactionPg } from '@payloadcms/drizzle/types'\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/api'\nimport type { Payload, PayloadRequest } from 'payload'\n\nimport { sql } from 'drizzle-orm'\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from '../../types.js'\nimport type { PathsToQuery } from './types.js'\n\nimport { groupUpSQLStatements } from './groupUpSQLStatements.js'\nimport { migrateRelationships } from './migrateRelationships.js'\nimport { traverseFields } from './traverseFields.js'\n\nconst require = createRequire(import.meta.url)\n\ntype Args = {\n debug?: boolean\n payload: Payload\n req?: Partial<PayloadRequest>\n}\n\n/**\n * Moves upload and relationship columns from the join table and into the tables while moving data\n * This is done in the following order:\n * ADD COLUMNs\n * -- manipulate data to move relationships to new columns\n * ADD CONSTRAINTs\n * NOT NULLs\n * DROP TABLEs\n * DROP CONSTRAINTs\n * DROP COLUMNs\n * @param debug\n * @param payload\n * @param req\n */\nexport const migratePostgresV2toV3 = async ({ debug, payload, req }: Args) => {\n const adapter = payload.db as unknown as PostgresAdapter\n const db = adapter.sessions[await req.transactionID].db as TransactionPg\n const dir = payload.db.migrationDir\n\n // get the drizzle migrateUpSQL from drizzle using the last schema\n const { generateDrizzleJson, generateMigration } = require('drizzle-kit/api')\n const drizzleJsonAfter = generateDrizzleJson(adapter.schema)\n\n // Get the previous migration snapshot\n const previousSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json') && !file.endsWith('relationships_v2_v3.json'))\n .sort()\n .reverse()?.[0]\n\n if (!previousSnapshot) {\n throw new Error(\n `No previous migration schema file found! A prior migration from v2 is required to migrate to v3.`,\n )\n }\n\n const drizzleJsonBefore = JSON.parse(\n fs.readFileSync(`${dir}/${previousSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n\n const generatedSQL = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n\n if (!generatedSQL.length) {\n payload.logger.info(`No schema changes needed.`)\n process.exit(0)\n }\n\n const sqlUpStatements = groupUpSQLStatements(generatedSQL)\n\n const addColumnsStatement = sqlUpStatements.addColumn.join('\\n')\n\n if (debug) {\n payload.logger.info('CREATING NEW RELATIONSHIP COLUMNS')\n payload.logger.info(addColumnsStatement)\n }\n\n await db.execute(sql.raw(addColumnsStatement))\n\n for (const collection of payload.config.collections) {\n const tableName = adapter.tableNameMap.get(toSnakeCase(collection.slug))\n const pathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n collectionSlug: collection.slug,\n columnPrefix: '',\n db,\n disableNotNull: false,\n fields: collection.fields,\n isVersions: false,\n newTableName: tableName,\n parentTableName: tableName,\n path: '',\n pathsToQuery,\n payload,\n rootTableName: tableName,\n })\n\n await migrateRelationships({\n adapter,\n collectionSlug: collection.slug,\n db,\n debug,\n fields: collection.fields,\n isVersions: false,\n pathsToQuery,\n payload,\n req,\n tableName,\n })\n\n if (collection.versions) {\n const versionsTableName = adapter.tableNameMap.get(\n `_${toSnakeCase(collection.slug)}${adapter.versionsSuffix}`,\n )\n const versionFields = buildVersionCollectionFields(payload.config, collection)\n const versionPathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n collectionSlug: collection.slug,\n columnPrefix: '',\n db,\n disableNotNull: true,\n fields: versionFields,\n isVersions: true,\n newTableName: versionsTableName,\n parentTableName: versionsTableName,\n path: '',\n pathsToQuery: versionPathsToQuery,\n payload,\n rootTableName: versionsTableName,\n })\n\n await migrateRelationships({\n adapter,\n collectionSlug: collection.slug,\n db,\n debug,\n fields: versionFields,\n isVersions: true,\n pathsToQuery: versionPathsToQuery,\n payload,\n req,\n tableName: versionsTableName,\n })\n }\n }\n\n for (const global of payload.config.globals) {\n const tableName = adapter.tableNameMap.get(toSnakeCase(global.slug))\n\n const pathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n columnPrefix: '',\n db,\n disableNotNull: false,\n fields: global.fields,\n globalSlug: global.slug,\n isVersions: false,\n newTableName: tableName,\n parentTableName: tableName,\n path: '',\n pathsToQuery,\n payload,\n rootTableName: tableName,\n })\n\n await migrateRelationships({\n adapter,\n db,\n debug,\n fields: global.fields,\n globalSlug: global.slug,\n isVersions: false,\n pathsToQuery,\n payload,\n req,\n tableName,\n })\n\n if (global.versions) {\n const versionsTableName = adapter.tableNameMap.get(\n `_${toSnakeCase(global.slug)}${adapter.versionsSuffix}`,\n )\n\n const versionFields = buildVersionGlobalFields(payload.config, global)\n\n const versionPathsToQuery: PathsToQuery = new Set()\n\n traverseFields({\n adapter,\n columnPrefix: '',\n db,\n disableNotNull: true,\n fields: versionFields,\n globalSlug: global.slug,\n isVersions: true,\n newTableName: versionsTableName,\n parentTableName: versionsTableName,\n path: '',\n pathsToQuery: versionPathsToQuery,\n payload,\n rootTableName: versionsTableName,\n })\n\n await migrateRelationships({\n adapter,\n db,\n debug,\n fields: versionFields,\n globalSlug: global.slug,\n isVersions: true,\n pathsToQuery: versionPathsToQuery,\n payload,\n req,\n tableName: versionsTableName,\n })\n }\n }\n\n // ADD CONSTRAINT\n const addConstraintsStatement = sqlUpStatements.addConstraint.join('\\n')\n\n if (debug) {\n payload.logger.info('ADDING CONSTRAINTS')\n payload.logger.info(addConstraintsStatement)\n }\n\n await db.execute(sql.raw(addConstraintsStatement))\n\n // NOT NULL\n const notNullStatements = sqlUpStatements.notNull.join('\\n')\n\n if (debug) {\n payload.logger.info('NOT NULL CONSTRAINTS')\n payload.logger.info(notNullStatements)\n }\n\n await db.execute(sql.raw(notNullStatements))\n\n // DROP TABLE\n const dropTablesStatement = sqlUpStatements.dropTable.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING TABLES')\n payload.logger.info(dropTablesStatement)\n }\n\n await db.execute(sql.raw(dropTablesStatement))\n\n // DROP CONSTRAINT\n const dropConstraintsStatement = sqlUpStatements.dropConstraint.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING CONSTRAINTS')\n payload.logger.info(dropConstraintsStatement)\n }\n\n await db.execute(sql.raw(dropConstraintsStatement))\n\n // DROP COLUMN\n const dropColumnsStatement = sqlUpStatements.dropColumn.join('\\n')\n\n if (debug) {\n payload.logger.info('DROPPING COLUMNS')\n payload.logger.info(dropColumnsStatement)\n }\n\n await db.execute(sql.raw(dropColumnsStatement))\n}\n"],"names":["sql","fs","createRequire","buildVersionCollectionFields","buildVersionGlobalFields","toSnakeCase","groupUpSQLStatements","migrateRelationships","traverseFields","require","url","migratePostgresV2toV3","debug","payload","req","adapter","db","sessions","transactionID","dir","migrationDir","generateDrizzleJson","generateMigration","drizzleJsonAfter","schema","previousSnapshot","readdirSync","filter","file","endsWith","sort","reverse","Error","drizzleJsonBefore","JSON","parse","readFileSync","generatedSQL","length","logger","info","process","exit","sqlUpStatements","addColumnsStatement","addColumn","join","execute","raw","collection","config","collections","tableName","tableNameMap","get","slug","pathsToQuery","Set","collectionSlug","columnPrefix","disableNotNull","fields","isVersions","newTableName","parentTableName","path","rootTableName","versions","versionsTableName","versionsSuffix","versionFields","versionPathsToQuery","global","globals","globalSlug","addConstraintsStatement","addConstraint","notNullStatements","notNull","dropTablesStatement","dropTable","dropConstraintsStatement","dropConstraint","dropColumn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C;IAE7D,IAAIlC,OAAO;QACTC,QAAQ0B,MAAM,CAACC,IAAI,CAAC;QACpB3B,QAAQ0B,MAAM,CAACC,IAAI,CAAC2C;IACtB;IAEA,MAAMnE,GAAG+B,OAAO,CAAC/C,IAAIgD,GAAG,CAACmC;AAC3B,EAAC"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"migrateRelationships.d.ts","sourceRoot":"","sources":["../../../src/predefinedMigrations/v2-v3/migrateRelationships.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AAC9D,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,KAAK,EAAgB,YAAY,EAAE,MAAM,YAAY,CAAA;AAI5D,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,aAAa,CAAA;IACjB,KAAK,EAAE,OAAO,CAAA;IACd,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,OAAO,CAAA;IACnB,YAAY,EAAE,YAAY,CAAA;IAC1B,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,oBAAoB,mHAY9B,IAAI,
|
1
|
+
{"version":3,"file":"migrateRelationships.d.ts","sourceRoot":"","sources":["../../../src/predefinedMigrations/v2-v3/migrateRelationships.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AAC9D,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,KAAK,EAAgB,YAAY,EAAE,MAAM,YAAY,CAAA;AAI5D,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,eAAe,CAAA;IACxB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,aAAa,CAAA;IACjB,KAAK,EAAE,OAAO,CAAA;IACd,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,OAAO,CAAA;IACnB,YAAY,EAAE,YAAY,CAAA;IAC1B,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,oBAAoB,mHAY9B,IAAI,kBAwEN,CAAA"}
|
@@ -1,7 +1,9 @@
|
|
1
1
|
import { sql } from 'drizzle-orm';
|
2
2
|
import { fetchAndResave } from './fetchAndResave/index.js';
|
3
3
|
export const migrateRelationships = async ({ adapter, collectionSlug, db, debug, fields, globalSlug, isVersions, pathsToQuery, payload, req, tableName })=>{
|
4
|
-
if (pathsToQuery.size === 0)
|
4
|
+
if (pathsToQuery.size === 0) {
|
5
|
+
return;
|
6
|
+
}
|
5
7
|
let offset = 0;
|
6
8
|
let paginationResult;
|
7
9
|
const where = Array.from(pathsToQuery).reduce((statement, path, i)=>{
|
@@ -14,7 +16,9 @@ export const migrateRelationships = async ({ adapter, collectionSlug, db, debug,
|
|
14
16
|
${where} ORDER BY parent_id LIMIT 500 OFFSET ${offset * 500};
|
15
17
|
`;
|
16
18
|
paginationResult = await adapter.drizzle.execute(sql.raw(`${paginationStatement}`));
|
17
|
-
if (paginationResult.rows.length === 0)
|
19
|
+
if (paginationResult.rows.length === 0) {
|
20
|
+
return;
|
21
|
+
}
|
18
22
|
offset += 1;
|
19
23
|
const statement = `SELECT * FROM ${tableName}${adapter.relationshipsSuffix} WHERE
|
20
24
|
(${where}) AND parent_id IN (${paginationResult.rows.map((row)=>row.parent_id).join(', ')});
|
@@ -28,7 +32,9 @@ export const migrateRelationships = async ({ adapter, collectionSlug, db, debug,
|
|
28
32
|
result.rows.forEach((row)=>{
|
29
33
|
const parentID = row.parent_id;
|
30
34
|
if (typeof parentID === 'string' || typeof parentID === 'number') {
|
31
|
-
if (!docsToResave[parentID])
|
35
|
+
if (!docsToResave[parentID]) {
|
36
|
+
docsToResave[parentID] = [];
|
37
|
+
}
|
32
38
|
docsToResave[parentID].push(row);
|
33
39
|
}
|
34
40
|
});
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/predefinedMigrations/v2-v3/migrateRelationships.ts"],"sourcesContent":["import type { TransactionPg } from '@payloadcms/drizzle/types'\nimport type { Field, Payload, PayloadRequest } from 'payload'\n\nimport { sql } from 'drizzle-orm'\n\nimport type { PostgresAdapter } from '../../types.js'\nimport type { DocsToResave, PathsToQuery } from './types.js'\n\nimport { fetchAndResave } from './fetchAndResave/index.js'\n\ntype Args = {\n adapter: PostgresAdapter\n collectionSlug?: string\n db: TransactionPg\n debug: boolean\n fields: Field[]\n globalSlug?: string\n isVersions: boolean\n pathsToQuery: PathsToQuery\n payload: Payload\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\nexport const migrateRelationships = async ({\n adapter,\n collectionSlug,\n db,\n debug,\n fields,\n globalSlug,\n isVersions,\n pathsToQuery,\n payload,\n req,\n tableName,\n}: Args) => {\n if (pathsToQuery.size === 0) return\n\n let offset = 0\n\n let paginationResult\n\n const where = Array.from(pathsToQuery).reduce((statement, path, i) => {\n return (statement += `\n\"${tableName}${adapter.relationshipsSuffix}\".\"path\" LIKE '${path}'${pathsToQuery.size !== i + 1 ? ' OR' : ''}\n`)\n }, '')\n\n while (typeof paginationResult === 'undefined' || paginationResult.rows.length > 0) {\n const paginationStatement = `SELECT DISTINCT parent_id FROM ${tableName}${adapter.relationshipsSuffix} WHERE\n ${where} ORDER BY parent_id LIMIT 500 OFFSET ${offset * 500};\n `\n\n paginationResult = await adapter.drizzle.execute(sql.raw(`${paginationStatement}`))\n\n if (paginationResult.rows.length === 0) return\n\n offset += 1\n\n const statement = `SELECT * FROM ${tableName}${adapter.relationshipsSuffix} WHERE\n (${where}) AND parent_id IN (${paginationResult.rows.map((row) => row.parent_id).join(', ')});\n`\n if (debug) {\n payload.logger.info('FINDING ROWS TO MIGRATE')\n payload.logger.info(statement)\n }\n\n const result = await adapter.drizzle.execute(sql.raw(`${statement}`))\n\n const docsToResave: DocsToResave = {}\n\n result.rows.forEach((row) => {\n const parentID = row.parent_id\n\n if (typeof parentID === 'string' || typeof parentID === 'number') {\n if (!docsToResave[parentID]) docsToResave[parentID] = []\n docsToResave[parentID].push(row)\n }\n })\n\n await fetchAndResave({\n adapter,\n collectionSlug,\n db,\n debug,\n docsToResave,\n fields,\n globalSlug,\n isVersions,\n payload,\n req: req as unknown as PayloadRequest,\n tableName,\n })\n }\n\n const deleteStatement = `DELETE FROM ${tableName}${adapter.relationshipsSuffix} WHERE ${where}`\n if (debug) {\n payload.logger.info('DELETING ROWS')\n payload.logger.info(deleteStatement)\n }\n await db.execute(sql.raw(`${deleteStatement}`))\n}\n"],"names":["sql","fetchAndResave","migrateRelationships","adapter","collectionSlug","db","debug","fields","globalSlug","isVersions","pathsToQuery","payload","req","tableName","size","offset","paginationResult","where","Array","from","reduce","statement","path","i","relationshipsSuffix","rows","length","paginationStatement","drizzle","execute","raw","map","row","parent_id","join","logger","info","result","docsToResave","forEach","parentID","push","deleteStatement"],"mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AAKjC,SAASC,cAAc,QAAQ,4BAA2B;AAgB1D,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,cAAc,EACdC,EAAE,EACFC,KAAK,EACLC,MAAM,EACNC,UAAU,EACVC,UAAU,EACVC,YAAY,EACZC,OAAO,EACPC,GAAG,EACHC,SAAS,EACJ;IACL,IAAIH,aAAaI,IAAI,KAAK,GAAG;
|
1
|
+
{"version":3,"sources":["../../../src/predefinedMigrations/v2-v3/migrateRelationships.ts"],"sourcesContent":["import type { TransactionPg } from '@payloadcms/drizzle/types'\nimport type { Field, Payload, PayloadRequest } from 'payload'\n\nimport { sql } from 'drizzle-orm'\n\nimport type { PostgresAdapter } from '../../types.js'\nimport type { DocsToResave, PathsToQuery } from './types.js'\n\nimport { fetchAndResave } from './fetchAndResave/index.js'\n\ntype Args = {\n adapter: PostgresAdapter\n collectionSlug?: string\n db: TransactionPg\n debug: boolean\n fields: Field[]\n globalSlug?: string\n isVersions: boolean\n pathsToQuery: PathsToQuery\n payload: Payload\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\nexport const migrateRelationships = async ({\n adapter,\n collectionSlug,\n db,\n debug,\n fields,\n globalSlug,\n isVersions,\n pathsToQuery,\n payload,\n req,\n tableName,\n}: Args) => {\n if (pathsToQuery.size === 0) {\n return\n }\n\n let offset = 0\n\n let paginationResult\n\n const where = Array.from(pathsToQuery).reduce((statement, path, i) => {\n return (statement += `\n\"${tableName}${adapter.relationshipsSuffix}\".\"path\" LIKE '${path}'${pathsToQuery.size !== i + 1 ? ' OR' : ''}\n`)\n }, '')\n\n while (typeof paginationResult === 'undefined' || paginationResult.rows.length > 0) {\n const paginationStatement = `SELECT DISTINCT parent_id FROM ${tableName}${adapter.relationshipsSuffix} WHERE\n ${where} ORDER BY parent_id LIMIT 500 OFFSET ${offset * 500};\n `\n\n paginationResult = await adapter.drizzle.execute(sql.raw(`${paginationStatement}`))\n\n if (paginationResult.rows.length === 0) {\n return\n }\n\n offset += 1\n\n const statement = `SELECT * FROM ${tableName}${adapter.relationshipsSuffix} WHERE\n (${where}) AND parent_id IN (${paginationResult.rows.map((row) => row.parent_id).join(', ')});\n`\n if (debug) {\n payload.logger.info('FINDING ROWS TO MIGRATE')\n payload.logger.info(statement)\n }\n\n const result = await adapter.drizzle.execute(sql.raw(`${statement}`))\n\n const docsToResave: DocsToResave = {}\n\n result.rows.forEach((row) => {\n const parentID = row.parent_id\n\n if (typeof parentID === 'string' || typeof parentID === 'number') {\n if (!docsToResave[parentID]) {\n docsToResave[parentID] = []\n }\n docsToResave[parentID].push(row)\n }\n })\n\n await fetchAndResave({\n adapter,\n collectionSlug,\n db,\n debug,\n docsToResave,\n fields,\n globalSlug,\n isVersions,\n payload,\n req: req as unknown as PayloadRequest,\n tableName,\n })\n }\n\n const deleteStatement = `DELETE FROM ${tableName}${adapter.relationshipsSuffix} WHERE ${where}`\n if (debug) {\n payload.logger.info('DELETING ROWS')\n payload.logger.info(deleteStatement)\n }\n await db.execute(sql.raw(`${deleteStatement}`))\n}\n"],"names":["sql","fetchAndResave","migrateRelationships","adapter","collectionSlug","db","debug","fields","globalSlug","isVersions","pathsToQuery","payload","req","tableName","size","offset","paginationResult","where","Array","from","reduce","statement","path","i","relationshipsSuffix","rows","length","paginationStatement","drizzle","execute","raw","map","row","parent_id","join","logger","info","result","docsToResave","forEach","parentID","push","deleteStatement"],"mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AAKjC,SAASC,cAAc,QAAQ,4BAA2B;AAgB1D,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,cAAc,EACdC,EAAE,EACFC,KAAK,EACLC,MAAM,EACNC,UAAU,EACVC,UAAU,EACVC,YAAY,EACZC,OAAO,EACPC,GAAG,EACHC,SAAS,EACJ;IACL,IAAIH,aAAaI,IAAI,KAAK,GAAG;QAC3B;IACF;IAEA,IAAIC,SAAS;IAEb,IAAIC;IAEJ,MAAMC,QAAQC,MAAMC,IAAI,CAACT,cAAcU,MAAM,CAAC,CAACC,WAAWC,MAAMC;QAC9D,OAAQF,aAAa,CAAC;CACzB,EAAER,UAAU,EAAEV,QAAQqB,mBAAmB,CAAC,eAAe,EAAEF,KAAK,CAAC,EAAEZ,aAAaI,IAAI,KAAKS,IAAI,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C;YACAC;YACAE;YACAC,KAAKA;YACLC;QACF;IACF;IAEA,MAAM6B,kBAAkB,CAAC,YAAY,EAAE7B,UAAU,EAAEV,QAAQqB,mBAAmB,CAAC,OAAO,EAAEP,MAAM,CAAC;IAC/F,IAAIX,OAAO;QACTK,QAAQwB,MAAM,CAACC,IAAI,CAAC;QACpBzB,QAAQwB,MAAM,CAACC,IAAI,CAACM;IACtB;IACA,MAAMrC,GAAGwB,OAAO,CAAC7B,IAAI8B,GAAG,CAAC,CAAC,EAAEY,gBAAgB,CAAC;AAC/C,EAAC"}
|
package/dist/types.d.ts
CHANGED
@@ -1,9 +1,27 @@
|
|
1
|
-
import type { BasePostgresAdapter, GenericEnum, MigrateDownArgs, MigrateUpArgs, PostgresDB } from '@payloadcms/drizzle/postgres';
|
1
|
+
import type { BasePostgresAdapter, GenericEnum, MigrateDownArgs, MigrateUpArgs, PostgresDB, PostgresSchemaHook } from '@payloadcms/drizzle/postgres';
|
2
2
|
import type { DrizzleAdapter } from '@payloadcms/drizzle/types';
|
3
3
|
import type { DrizzleConfig } from 'drizzle-orm';
|
4
4
|
import type { PgSchema, PgTableFn, PgTransactionConfig } from 'drizzle-orm/pg-core';
|
5
5
|
import type { Pool, PoolConfig } from 'pg';
|
6
6
|
export type Args = {
|
7
|
+
/**
|
8
|
+
* Transform the schema after it's built.
|
9
|
+
* You can use it to customize the schema with features that aren't supported by Payload.
|
10
|
+
* Examples may include: composite indices, generated columns, vectors
|
11
|
+
*/
|
12
|
+
afterSchemaInit?: PostgresSchemaHook[];
|
13
|
+
/**
|
14
|
+
* Transform the schema before it's built.
|
15
|
+
* You can use it to preserve an existing database schema and if there are any collissions Payload will override them.
|
16
|
+
* To generate Drizzle schema from the database, see [Drizzle Kit introspection](https://orm.drizzle.team/kit-docs/commands#introspect--pull)
|
17
|
+
*/
|
18
|
+
beforeSchemaInit?: PostgresSchemaHook[];
|
19
|
+
/**
|
20
|
+
* Pass `true` to disale auto database creation if it doesn't exist.
|
21
|
+
* @default false
|
22
|
+
*/
|
23
|
+
disableCreateDatabase?: boolean;
|
24
|
+
extensions?: string[];
|
7
25
|
idType?: 'serial' | 'uuid';
|
8
26
|
localesSuffix?: string;
|
9
27
|
logger?: DrizzleConfig['logger'];
|
@@ -21,7 +39,8 @@ export type Args = {
|
|
21
39
|
* @experimental This only works when there are not other tables or enums of the same name in the database under a different schema. Awaiting fix from Drizzle.
|
22
40
|
*/
|
23
41
|
schemaName?: string;
|
24
|
-
|
42
|
+
tablesFilter?: string[];
|
43
|
+
transactionOptions?: false | PgTransactionConfig;
|
25
44
|
versionsSuffix?: string;
|
26
45
|
};
|
27
46
|
export type PostgresAdapter = {
|
@@ -30,9 +49,12 @@ export type PostgresAdapter = {
|
|
30
49
|
} & BasePostgresAdapter;
|
31
50
|
declare module 'payload' {
|
32
51
|
interface DatabaseAdapter extends Omit<Args, 'idType' | 'logger' | 'migrationDir' | 'pool'>, DrizzleAdapter {
|
52
|
+
afterSchemaInit: PostgresSchemaHook[];
|
53
|
+
beforeSchemaInit: PostgresSchemaHook[];
|
33
54
|
beginTransaction: (options?: PgTransactionConfig) => Promise<null | number | string>;
|
34
55
|
drizzle: PostgresDB;
|
35
56
|
enums: Record<string, GenericEnum>;
|
57
|
+
extensions: Record<string, boolean>;
|
36
58
|
/**
|
37
59
|
* An object keyed on each table, with a key value pair where the constraint name is the key, followed by the dot-notation field name
|
38
60
|
* Used for returning properly formed errors from unique fields
|
@@ -59,6 +81,7 @@ declare module 'payload' {
|
|
59
81
|
schema: Record<string, unknown>;
|
60
82
|
schemaName?: Args['schemaName'];
|
61
83
|
tableNameMap: Map<string, string>;
|
84
|
+
tablesFilter?: string[];
|
62
85
|
versionsSuffix?: string;
|
63
86
|
}
|
64
87
|
}
|
package/dist/types.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACn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IAAI,CAAC,MAAM,CAAC,CAAA;QACzB,cAAc,CAAC,EAAE;YACf,IAAI,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;YAC9C,IAAI,EAAE,MAAM,CAAA;YACZ,EAAE,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;SAC3C,EAAE,CAAA;QACH,IAAI,EAAE,OAAO,CAAA;QACb,kBAAkB,EAAE,MAAM,IAAI,CAAA;QAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAA;QAC5B,mBAAmB,EAAE,MAAM,IAAI,CAAA;QAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAC/B,UAAU,CAAC,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QAC/B,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QACjC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;QACvB,cAAc,CAAC,EAAE,MAAM,CAAA;KACxB;CACF"}
|
package/dist/types.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n BasePostgresAdapter,\n GenericEnum,\n MigrateDownArgs,\n MigrateUpArgs,\n PostgresDB,\n} from '@payloadcms/drizzle/postgres'\nimport type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { DrizzleConfig } from 'drizzle-orm'\nimport type { PgSchema, PgTableFn, PgTransactionConfig } from 'drizzle-orm/pg-core'\nimport type { Pool, PoolConfig } from 'pg'\n\nexport type Args = {\n idType?: 'serial' | 'uuid'\n localesSuffix?: string\n logger?: DrizzleConfig['logger']\n migrationDir?: string\n pool: PoolConfig\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n push?: boolean\n relationshipsSuffix?: string\n /**\n * The schema name to use for the database\n * @experimental This only works when there are not other tables or enums of the same name in the database under a different schema. Awaiting fix from Drizzle.\n */\n schemaName?: string\n transactionOptions?:
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n BasePostgresAdapter,\n GenericEnum,\n MigrateDownArgs,\n MigrateUpArgs,\n PostgresDB,\n PostgresSchemaHook,\n} from '@payloadcms/drizzle/postgres'\nimport type { DrizzleAdapter } from '@payloadcms/drizzle/types'\nimport type { DrizzleConfig } from 'drizzle-orm'\nimport type { PgSchema, PgTableFn, PgTransactionConfig } from 'drizzle-orm/pg-core'\nimport type { Pool, PoolConfig } from 'pg'\n\nexport type Args = {\n /**\n * Transform the schema after it's built.\n * You can use it to customize the schema with features that aren't supported by Payload.\n * Examples may include: composite indices, generated columns, vectors\n */\n afterSchemaInit?: PostgresSchemaHook[]\n /**\n * Transform the schema before it's built.\n * You can use it to preserve an existing database schema and if there are any collissions Payload will override them.\n * To generate Drizzle schema from the database, see [Drizzle Kit introspection](https://orm.drizzle.team/kit-docs/commands#introspect--pull)\n */\n beforeSchemaInit?: PostgresSchemaHook[]\n /**\n * Pass `true` to disale auto database creation if it doesn't exist.\n * @default false\n */\n disableCreateDatabase?: boolean\n extensions?: string[]\n idType?: 'serial' | 'uuid'\n localesSuffix?: string\n logger?: DrizzleConfig['logger']\n migrationDir?: string\n pool: PoolConfig\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n push?: boolean\n relationshipsSuffix?: string\n /**\n * The schema name to use for the database\n * @experimental This only works when there are not other tables or enums of the same name in the database under a different schema. Awaiting fix from Drizzle.\n */\n schemaName?: string\n tablesFilter?: string[]\n transactionOptions?: false | PgTransactionConfig\n versionsSuffix?: string\n}\n\nexport type PostgresAdapter = {\n pool: Pool\n poolOptions: PoolConfig\n} & BasePostgresAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<Args, 'idType' | 'logger' | 'migrationDir' | 'pool'>,\n DrizzleAdapter {\n afterSchemaInit: PostgresSchemaHook[]\n\n beforeSchemaInit: PostgresSchemaHook[]\n beginTransaction: (options?: PgTransactionConfig) => Promise<null | number | string>\n drizzle: PostgresDB\n enums: Record<string, GenericEnum>\n extensions: Record<string, boolean>\n /**\n * An object keyed on each table, with a key value pair where the constraint name is the key, followed by the dot-notation field name\n * Used for returning properly formed errors from unique fields\n */\n fieldConstraints: Record<string, Record<string, string>>\n idType: Args['idType']\n initializing: Promise<void>\n localesSuffix?: string\n logger: DrizzleConfig['logger']\n pgSchema?: { table: PgTableFn } | PgSchema\n pool: Pool\n poolOptions: Args['pool']\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n push: boolean\n rejectInitializing: () => void\n relationshipsSuffix?: string\n resolveInitializing: () => void\n schema: Record<string, unknown>\n schemaName?: Args['schemaName']\n tableNameMap: Map<string, string>\n tablesFilter?: string[]\n versionsSuffix?: string\n }\n}\n"],"names":[],"mappings":"AAsDA,WAGuB"}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@payloadcms/db-postgres",
|
3
|
-
"version": "3.0.0-canary.
|
3
|
+
"version": "3.0.0-canary.dc8b1fe",
|
4
4
|
"description": "The officially supported Postgres database adapter for Payload",
|
5
5
|
"homepage": "https://payloadcms.com",
|
6
6
|
"repository": {
|
@@ -35,25 +35,25 @@
|
|
35
35
|
"mock.js"
|
36
36
|
],
|
37
37
|
"dependencies": {
|
38
|
-
"
|
39
|
-
"
|
40
|
-
"drizzle-
|
38
|
+
"@types/pg": "8.10.2",
|
39
|
+
"console-table-printer": "2.12.1",
|
40
|
+
"drizzle-kit": "0.28.0",
|
41
|
+
"drizzle-orm": "0.36.1",
|
41
42
|
"pg": "8.11.3",
|
42
43
|
"prompts": "2.4.2",
|
43
44
|
"to-snake-case": "1.0.0",
|
44
45
|
"uuid": "10.0.0",
|
45
|
-
"@payloadcms/drizzle": "3.0.0-canary.
|
46
|
+
"@payloadcms/drizzle": "3.0.0-canary.dc8b1fe"
|
46
47
|
},
|
47
48
|
"devDependencies": {
|
48
49
|
"@hyrious/esbuild-plugin-commonjs": "^0.2.4",
|
49
|
-
"@types/pg": "8.10.2",
|
50
50
|
"@types/to-snake-case": "1.0.0",
|
51
|
-
"esbuild": "0.23.
|
52
|
-
"
|
53
|
-
"
|
51
|
+
"esbuild": "0.23.1",
|
52
|
+
"@payloadcms/eslint-config": "3.0.0-beta.112",
|
53
|
+
"payload": "3.0.0-canary.dc8b1fe"
|
54
54
|
},
|
55
55
|
"peerDependencies": {
|
56
|
-
"payload": "3.0.0-canary.
|
56
|
+
"payload": "3.0.0-canary.dc8b1fe"
|
57
57
|
},
|
58
58
|
"scripts": {
|
59
59
|
"build": "rimraf .dist && rimraf tsconfig.tsbuildinfo && pnpm build:types && pnpm build:swc && pnpm build:esbuild && pnpm renamePredefinedMigrations",
|
@@ -61,6 +61,8 @@
|
|
61
61
|
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
|
62
62
|
"build:types": "tsc --emitDeclarationOnly --outDir dist",
|
63
63
|
"clean": "rimraf {dist,*.tsbuildinfo}",
|
64
|
+
"lint": "eslint .",
|
65
|
+
"lint:fix": "eslint . --fix",
|
64
66
|
"renamePredefinedMigrations": "node --no-deprecation --import @swc-node/register/esm-register ./scripts/renamePredefinedMigrations.ts"
|
65
67
|
}
|
66
68
|
}
|