@payloadcms/drizzle 4.0.0-internal.d21c039 → 4.0.0-internal.d3909a9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/exports/postgres.d.ts +1 -0
  2. package/dist/exports/postgres.d.ts.map +1 -1
  3. package/dist/exports/postgres.js +1 -0
  4. package/dist/exports/postgres.js.map +1 -1
  5. package/dist/exports/sqlite.d.ts +1 -0
  6. package/dist/exports/sqlite.d.ts.map +1 -1
  7. package/dist/exports/sqlite.js +1 -0
  8. package/dist/exports/sqlite.js.map +1 -1
  9. package/dist/find/buildPolymorphicJoinQuery.js.map +1 -1
  10. package/dist/index.d.ts +1 -8
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -8
  13. package/dist/index.js.map +1 -1
  14. package/dist/migrate.d.ts.map +1 -1
  15. package/dist/migrate.js +6 -2
  16. package/dist/migrate.js.map +1 -1
  17. package/dist/migrateDown.d.ts.map +1 -1
  18. package/dist/migrateDown.js +5 -2
  19. package/dist/migrateDown.js.map +1 -1
  20. package/dist/migrateFresh.d.ts.map +1 -1
  21. package/dist/migrateFresh.js +5 -2
  22. package/dist/migrateFresh.js.map +1 -1
  23. package/dist/migrateRefresh.d.ts.map +1 -1
  24. package/dist/migrateRefresh.js +6 -2
  25. package/dist/migrateRefresh.js.map +1 -1
  26. package/dist/migrateReset.d.ts.map +1 -1
  27. package/dist/migrateReset.js +6 -2
  28. package/dist/migrateReset.js.map +1 -1
  29. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts +35 -0
  30. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  31. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js +185 -0
  32. package/dist/postgres/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  33. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -1
  34. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js +8 -4
  35. package/dist/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -1
  36. package/dist/schema/build.js +3 -3
  37. package/dist/schema/build.js.map +1 -1
  38. package/dist/sqlite/execute.js.map +1 -1
  39. package/dist/sqlite/insert.d.ts.map +1 -1
  40. package/dist/sqlite/insert.js +4 -1
  41. package/dist/sqlite/insert.js.map +1 -1
  42. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts +15 -0
  43. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.d.ts.map +1 -0
  44. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js +114 -0
  45. package/dist/sqlite/predefinedMigrations/sizes-to-variants/index.js.map +1 -0
  46. package/dist/transform/read/traverseFields.js.map +1 -1
  47. package/dist/types.d.ts.map +1 -1
  48. package/dist/types.js.map +1 -1
  49. package/dist/upsertRow/index.js.map +1 -1
  50. package/dist/utilities/blocksToJsonMigrator.d.ts.map +1 -1
  51. package/dist/utilities/blocksToJsonMigrator.js +6 -17
  52. package/dist/utilities/blocksToJsonMigrator.js.map +1 -1
  53. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts +15 -0
  54. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.d.ts.map +1 -0
  55. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js +110 -0
  56. package/dist/utilities/buildDynamicPredefinedSizesToVariantsMigration.js.map +1 -0
  57. package/dist/utilities/createSchemaGenerator.d.ts.map +1 -1
  58. package/dist/utilities/createSchemaGenerator.js +7 -12
  59. package/dist/utilities/createSchemaGenerator.js.map +1 -1
  60. package/dist/utilities/executeSchemaHooks.js +1 -1
  61. package/dist/utilities/executeSchemaHooks.js.map +1 -1
  62. package/dist/utilities/formatGeneratedFile.d.ts +10 -0
  63. package/dist/utilities/formatGeneratedFile.d.ts.map +1 -0
  64. package/dist/utilities/formatGeneratedFile.js +58 -0
  65. package/dist/utilities/formatGeneratedFile.js.map +1 -0
  66. package/dist/utilities/getSizesToVariantsRenames.d.ts +54 -0
  67. package/dist/utilities/getSizesToVariantsRenames.d.ts.map +1 -0
  68. package/dist/utilities/getSizesToVariantsRenames.js +251 -0
  69. package/dist/utilities/getSizesToVariantsRenames.js.map +1 -0
  70. package/dist/utilities/getTransaction.js.map +1 -1
  71. package/package.json +16 -19
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/migrateReset.ts"],"sourcesContent":["import type { MigrationResult } from 'payload'\n\nimport {\n commitTransaction,\n createLocalReq,\n getMigrations,\n initTransaction,\n killTransaction,\n readMigrationFiles,\n} from 'payload'\n\nimport type { DrizzleAdapter } from './types.js'\n\nimport { getTransaction } from './utilities/getTransaction.js'\nimport { migrationTableExists } from './utilities/migrationTableExists.js'\n\n/**\n * Run all migrate down functions\n */\nexport async function migrateReset(this: DrizzleAdapter): Promise<MigrationResult> {\n const { payload } = this\n const migrationFiles = await readMigrationFiles({ payload })\n\n const { existingMigrations } = await getMigrations({ payload })\n\n if (!existingMigrations?.length) {\n payload.logger.info({ msg: 'No migrations to reset.' })\n return { migrated: [], rolledBack: [] }\n }\n\n const req = await createLocalReq({}, payload)\n\n existingMigrations.reverse()\n const rolledBack: string[] = []\n\n // Rollback all migrations in order\n for (const migration of existingMigrations) {\n const migrationFile = migrationFiles.find((m) => m.name === migration.name)\n try {\n if (!migrationFile) {\n throw new Error(`Migration ${migration.name} not found locally.`)\n }\n\n const start = Date.now()\n payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` })\n await initTransaction(req)\n const db = await getTransaction(this, req)\n await migrationFile.down({ db, payload, req })\n payload.logger.info({\n msg: `Migrated down: ${migrationFile.name} (${Date.now() - start}ms)`,\n })\n\n const tableExists = await migrationTableExists(this, db)\n if (tableExists) {\n await payload.delete({\n id: migration.id,\n collection: 'payload-migrations',\n req,\n })\n }\n\n await commitTransaction(req)\n rolledBack.push(migrationFile.name)\n } catch (err: unknown) {\n let msg = `Error running migration ${migrationFile.name}.`\n\n if (err instanceof Error) {\n msg += ` ${err.message}`\n }\n\n await killTransaction(req)\n payload.logger.error({\n err,\n msg,\n })\n throw err\n }\n }\n\n // Delete dev migration\n\n const tableExists = await migrationTableExists(this)\n if (tableExists) {\n try {\n await payload.delete({\n collection: 'payload-migrations',\n where: {\n batch: {\n equals: -1,\n },\n },\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: 'Error deleting dev migration' })\n throw err\n }\n }\n\n return { migrated: [], rolledBack }\n}\n"],"names":["commitTransaction","createLocalReq","getMigrations","initTransaction","killTransaction","readMigrationFiles","getTransaction","migrationTableExists","migrateReset","payload","migrationFiles","existingMigrations","length","logger","info","msg","migrated","rolledBack","req","reverse","migration","migrationFile","find","m","name","Error","start","Date","now","db","down","tableExists","delete","id","collection","push","err","message","error","where","batch","equals"],"mappings":"AAEA,SACEA,iBAAiB,EACjBC,cAAc,EACdC,aAAa,EACbC,eAAe,EACfC,eAAe,EACfC,kBAAkB,QACb,UAAS;AAIhB,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E;;CAEC,GACD,OAAO,eAAeC;IACpB,MAAM,EAAEC,OAAO,EAAE,GAAG,IAAI;IACxB,MAAMC,iBAAiB,MAAML,mBAAmB;QAAEI;IAAQ;IAE1D,MAAM,EAAEE,kBAAkB,EAAE,GAAG,MAAMT,cAAc;QAAEO;IAAQ;IAE7D,IAAI,CAACE,oBAAoBC,QAAQ;QAC/BH,QAAQI,MAAM,CAACC,IAAI,CAAC;YAAEC,KAAK;QAA0B;QACrD,OAAO;YAAEC,UAAU,EAAE;YAAEC,YAAY,EAAE;QAAC;IACxC;IAEA,MAAMC,MAAM,MAAMjB,eAAe,CAAC,GAAGQ;IAErCE,mBAAmBQ,OAAO;IAC1B,MAAMF,aAAuB,EAAE;IAE/B,mCAAmC;IACnC,KAAK,MAAMG,aAAaT,mBAAoB;QAC1C,MAAMU,gBAAgBX,eAAeY,IAAI,CAAC,CAACC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;gBACnBE,YAAY;gBACZK,OAAO;oBACLC,OAAO;wBACLC,QAAQ,CAAC;oBACX;gBACF;YACF;QACF,EAAE,OAAOL,KAAc;YACrB3B,QAAQI,MAAM,CAACyB,KAAK,CAAC;gBAAEF;gBAAKrB,KAAK;YAA+B;YAChE,MAAMqB;QACR;IACF;IAEA,OAAO;QAAEpB,UAAU,EAAE;QAAEC;IAAW;AACpC"}
1
+ {"version":3,"sources":["../src/migrateReset.ts"],"sourcesContent":["import type { MigrationResult } from 'payload'\n\nimport {\n commitTransaction,\n createPayloadRequest,\n getMigrations,\n initTransaction,\n killTransaction,\n readMigrationFiles,\n} from 'payload'\n\nimport type { DrizzleAdapter } from './types.js'\n\nimport { getTransaction } from './utilities/getTransaction.js'\nimport { migrationTableExists } from './utilities/migrationTableExists.js'\n\n/**\n * Run all migrate down functions\n */\nexport async function migrateReset(this: DrizzleAdapter): Promise<MigrationResult> {\n const { payload } = this\n const migrationFiles = await readMigrationFiles({ payload })\n\n const { existingMigrations } = await getMigrations({ payload })\n\n if (!existingMigrations?.length) {\n payload.logger.info({ msg: 'No migrations to reset.' })\n return { migrated: [], rolledBack: [] }\n }\n\n const req = await createPayloadRequest({ payload })\n\n existingMigrations.reverse()\n const rolledBack: string[] = []\n\n // Rollback all migrations in order\n for (const migration of existingMigrations) {\n const migrationFile = migrationFiles.find((m) => m.name === migration.name)\n try {\n if (!migrationFile) {\n throw new Error(`Migration ${migration.name} not found locally.`)\n }\n\n const start = Date.now()\n payload.logger.info({ msg: `Migrating down: ${migrationFile.name}` })\n await initTransaction(req)\n const db = await getTransaction(this, req)\n await migrationFile.down({ db, payload, req })\n payload.logger.info({\n msg: `Migrated down: ${migrationFile.name} (${Date.now() - start}ms)`,\n })\n\n const tableExists = await migrationTableExists(this, db)\n if (tableExists) {\n await payload.delete({\n id: migration.id,\n collection: 'payload-migrations',\n overrideAccess: true,\n req,\n })\n }\n\n await commitTransaction(req)\n rolledBack.push(migrationFile.name)\n } catch (err: unknown) {\n let msg = `Error running migration ${migrationFile.name}.`\n\n if (err instanceof Error) {\n msg += ` ${err.message}`\n }\n\n await killTransaction(req)\n payload.logger.error({\n err,\n msg,\n })\n throw err\n }\n }\n\n // Delete dev migration\n\n const tableExists = await migrationTableExists(this)\n if (tableExists) {\n try {\n await payload.delete({\n collection: 'payload-migrations',\n overrideAccess: true,\n where: {\n batch: {\n equals: -1,\n },\n },\n })\n } catch (err: unknown) {\n payload.logger.error({ err, msg: 'Error deleting dev migration' })\n throw err\n }\n }\n\n return { migrated: [], rolledBack }\n}\n"],"names":["commitTransaction","createPayloadRequest","getMigrations","initTransaction","killTransaction","readMigrationFiles","getTransaction","migrationTableExists","migrateReset","payload","migrationFiles","existingMigrations","length","logger","info","msg","migrated","rolledBack","req","reverse","migration","migrationFile","find","m","name","Error","start","Date","now","db","down","tableExists","delete","id","collection","overrideAccess","push","err","message","error","where","batch","equals"],"mappings":"AAEA,SACEA,iBAAiB,EACjBC,oBAAoB,EACpBC,aAAa,EACbC,eAAe,EACfC,eAAe,EACfC,kBAAkB,QACb,UAAS;AAIhB,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E;;CAEC,GACD,OAAO,eAAeC;IACpB,MAAM,EAAEC,OAAO,EAAE,GAAG,IAAI;IACxB,MAAMC,iBAAiB,MAAML,mBAAmB;QAAEI;IAAQ;IAE1D,MAAM,EAAEE,kBAAkB,EAAE,GAAG,MAAMT,cAAc;QAAEO;IAAQ;IAE7D,IAAI,CAACE,oBAAoBC,QAAQ;QAC/BH,QAAQI,MAAM,CAACC,IAAI,CAAC;YAAEC,KAAK;QAA0B;QACrD,OAAO;YAAEC,UAAU,EAAE;YAAEC,YAAY,EAAE;QAAC;IACxC;IAEA,MAAMC,MAAM,MAAMjB,qBAAqB;QAAEQ;IAAQ;IAEjDE,mBAAmBQ,OAAO;IAC1B,MAAMF,aAAuB,EAAE;IAE/B,mCAAmC;IACnC,KAAK,MAAMG,a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MxB,qBAAqB,IAAI;IACnD,IAAIwB,aAAa;QACf,IAAI;YACF,MAAMtB,QAAQuB,MAAM,CAAC;gBACnBE,YAAY;gBACZC,gBAAgB;gBAChBK,OAAO;oBACLC,OAAO;wBACLC,QAAQ,CAAC;oBACX;gBACF;YACF;QACF,EAAE,OAAOL,KAAc;YACrB5B,QAAQI,MAAM,CAAC0B,KAAK,CAAC;gBAAEF;gBAAKtB,KAAK;YAA+B;YAChE,MAAMsB;QACR;IACF;IAEA,OAAO;QAAErB,UAAU,EAAE;QAAEC;IAAW;AACpC"}
@@ -0,0 +1,35 @@
1
+ import type { Payload } from 'payload';
2
+ import type { SizesToVariantsDirection, SizesToVariantsIndexRename } from '../../../utilities/getSizesToVariantsRenames.js';
3
+ type ExistingPostgresIndex = {
4
+ columns: string[];
5
+ isPartial: boolean;
6
+ name: string;
7
+ unique: boolean;
8
+ };
9
+ /**
10
+ * Moves every upload collection's stored image sizes between the legacy `sizes_*` columns and
11
+ * `variants_*` (main and versions tables), renaming each column in place so no data is copied,
12
+ * then renames the indexes on those columns to what the current schema expects. Skips columns
13
+ * that are already renamed, so it's safe to re-run.
14
+ */
15
+ export declare function migratePostgresSizesToVariants({ db, direction, payload, }: {
16
+ db: any;
17
+ direction?: SizesToVariantsDirection;
18
+ payload: Payload;
19
+ }): Promise<void>;
20
+ export declare function reservePostgresLegacyIndexName({ existingIndexes, index, reservedRelationNames, }: {
21
+ existingIndexes: ExistingPostgresIndex[];
22
+ index: SizesToVariantsIndexRename;
23
+ reservedRelationNames: Set<string>;
24
+ }): string;
25
+ export declare function resolvePostgresIndexRename({ existingIndexes, index, tableName, }: {
26
+ existingIndexes: ExistingPostgresIndex[];
27
+ index: SizesToVariantsIndexRename;
28
+ tableName: string;
29
+ }): string | undefined;
30
+ export declare function getPostgresSchemaRelationNames({ db, schemaName, }: {
31
+ db: any;
32
+ schemaName: string;
33
+ }): Promise<Set<string>>;
34
+ export {};
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/postgres/predefinedMigrations/sizes-to-variants/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAItC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,iDAAiD,CAAA;AAUxD,KAAK,qBAAqB,GAAG;IAC3B,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,SAAS,EAAE,OAAO,CAAA;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,OAAO,CAAA;CAChB,CAAA;AAED;;;;;GAKG;AACH,wBAAsB,8BAA8B,CAAC,EACnD,EAAE,EACF,SAAgB,EAChB,OAAO,GACR,EAAE;IACD,EAAE,EAAE,GAAG,CAAA;IACP,SAAS,CAAC,EAAE,wBAAwB,CAAA;IACpC,OAAO,EAAE,OAAO,CAAA;CACjB,GAAG,OAAO,CAAC,IAAI,CAAC,CA8EhB;AAED,wBAAgB,8BAA8B,CAAC,EAC7C,eAAe,EACf,KAAK,EACL,qBAAqB,GACtB,EAAE;IACD,eAAe,EAAE,qBAAqB,EAAE,CAAA;IACxC,KAAK,EAAE,0BAA0B,CAAA;IACjC,qBAAqB,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CACnC,GAAG,MAAM,CAgCT;AAED,wBAAgB,0BAA0B,CAAC,EACzC,eAAe,EACf,KAAK,EACL,SAAS,GACV,EAAE;IACD,eAAe,EAAE,qBAAqB,EAAE,CAAA;IACxC,KAAK,EAAE,0BAA0B,CAAA;IACjC,SAAS,EAAE,MAAM,CAAA;CAClB,GAAG,MAAM,GAAG,SAAS,CA2CrB;AAoED,wBAAsB,8BAA8B,CAAC,EACnD,EAAE,EACF,UAAU,GACX,EAAE;IACD,EAAE,EAAE,GAAG,CAAA;IACP,UAAU,EAAE,MAAM,CAAA;CACnB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CASvB"}
@@ -0,0 +1,185 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { assertNoSizesToVariantsColumnCollisions, buildGeneratedLegacyIndexName, getSizesToVariantsRenames, isGeneratedLegacyIndexName } from '../../../utilities/getSizesToVariantsRenames.js';
3
+ /**
4
+ * Moves every upload collection's stored image sizes between the legacy `sizes_*` columns and
5
+ * `variants_*` (main and versions tables), renaming each column in place so no data is copied,
6
+ * then renames the indexes on those columns to what the current schema expects. Skips columns
7
+ * that are already renamed, so it's safe to re-run.
8
+ */ export async function migratePostgresSizesToVariants({ db, direction = 'up', payload }) {
9
+ const adapter = payload.db;
10
+ const schemaName = adapter.schemaName || 'public';
11
+ const plan = getSizesToVariantsRenames({
12
+ adapter,
13
+ direction
14
+ });
15
+ const plannedTables = [];
16
+ for (const tablePlan of plan){
17
+ const existingColumns = await getColumnNames({
18
+ db,
19
+ schemaName,
20
+ tableName: tablePlan.tableName
21
+ });
22
+ assertNoSizesToVariantsColumnCollisions({
23
+ columns: tablePlan.columns,
24
+ existingColumns,
25
+ tableName: tablePlan.tableName
26
+ });
27
+ plannedTables.push({
28
+ ...tablePlan,
29
+ existingColumns
30
+ });
31
+ }
32
+ const reservedRelationNames = direction === 'down' ? await getPostgresSchemaRelationNames({
33
+ db,
34
+ schemaName
35
+ }) : undefined;
36
+ for (const { columns, existingColumns, indexes, tableName } of plannedTables){
37
+ let renamedCount = 0;
38
+ for (const { from, to } of columns){
39
+ if (!existingColumns.has(from) || existingColumns.has(to)) {
40
+ continue;
41
+ }
42
+ await db.execute(sql`
43
+ ALTER TABLE ${sql.identifier(schemaName)}.${sql.identifier(tableName)}
44
+ RENAME COLUMN ${sql.identifier(from)} TO ${sql.identifier(to)}
45
+ `);
46
+ renamedCount++;
47
+ }
48
+ const existingIndexes = await getIndexes({
49
+ db,
50
+ schemaName,
51
+ tableName
52
+ });
53
+ for (const plannedIndex of indexes){
54
+ const index = reservedRelationNames && plannedIndex.legacyNameBase ? {
55
+ ...plannedIndex,
56
+ to: reservePostgresLegacyIndexName({
57
+ existingIndexes,
58
+ index: plannedIndex,
59
+ reservedRelationNames
60
+ })
61
+ } : plannedIndex;
62
+ const existingName = resolvePostgresIndexRename({
63
+ existingIndexes,
64
+ index,
65
+ tableName
66
+ });
67
+ if (!existingName) {
68
+ continue;
69
+ }
70
+ await db.execute(sql`
71
+ ALTER INDEX ${sql.identifier(schemaName)}.${sql.identifier(existingName)}
72
+ RENAME TO ${sql.identifier(index.to)}
73
+ `);
74
+ }
75
+ payload.logger.info({
76
+ msg: `sizes-to-variants (${direction}): renamed ${renamedCount} column(s) on "${tableName}"`
77
+ });
78
+ }
79
+ }
80
+ export function reservePostgresLegacyIndexName({ existingIndexes, index, reservedRelationNames }) {
81
+ const { legacyNameBase } = index;
82
+ if (!legacyNameBase) {
83
+ reservedRelationNames.add(index.to);
84
+ return index.to;
85
+ }
86
+ const existingDestination = existingIndexes.find((existingIndex)=>isCompatiblePostgresIndex({
87
+ existingIndex,
88
+ index
89
+ }) && isGeneratedLegacyIndexName({
90
+ indexName: existingIndex.name,
91
+ legacyNameBase
92
+ }));
93
+ if (existingDestination) {
94
+ reservedRelationNames.add(existingDestination.name);
95
+ return existingDestination.name;
96
+ }
97
+ let number = 0;
98
+ let indexName = buildGeneratedLegacyIndexName(legacyNameBase);
99
+ while(reservedRelationNames.has(indexName)){
100
+ number++;
101
+ indexName = buildGeneratedLegacyIndexName(legacyNameBase, number);
102
+ }
103
+ reservedRelationNames.add(indexName);
104
+ return indexName;
105
+ }
106
+ export function resolvePostgresIndexRename({ existingIndexes, index, tableName }) {
107
+ const destinationIndex = existingIndexes.find(({ name })=>name === index.to);
108
+ if (destinationIndex) {
109
+ if (!isCompatiblePostgresIndex({
110
+ existingIndex: destinationIndex,
111
+ index
112
+ })) {
113
+ throw new Error(`Cannot run the sizes-to-variants migration because index "${index.to}" on table "${tableName}" does not match the expected columns, uniqueness, or predicate.`);
114
+ }
115
+ return undefined;
116
+ }
117
+ let sourceIndex;
118
+ const { legacyNameBase } = index;
119
+ if (index.from) {
120
+ sourceIndex = existingIndexes.find(({ name })=>name === index.from);
121
+ } else if (legacyNameBase) {
122
+ const legacyCandidates = existingIndexes.filter((existingIndex)=>isGeneratedLegacyIndexName({
123
+ indexName: existingIndex.name,
124
+ legacyNameBase
125
+ }));
126
+ sourceIndex = legacyCandidates.find((existingIndex)=>isCompatiblePostgresIndex({
127
+ existingIndex,
128
+ index
129
+ })) ?? legacyCandidates[0];
130
+ }
131
+ if (!sourceIndex) {
132
+ return undefined;
133
+ }
134
+ if (!isCompatiblePostgresIndex({
135
+ existingIndex: sourceIndex,
136
+ index
137
+ })) {
138
+ throw new Error(`Cannot run the sizes-to-variants migration because index "${sourceIndex.name}" on table "${tableName}" does not match the expected columns, uniqueness, or predicate.`);
139
+ }
140
+ return sourceIndex.name === index.to ? undefined : sourceIndex.name;
141
+ }
142
+ function isCompatiblePostgresIndex({ existingIndex, index }) {
143
+ return existingIndex.columns.join(',') === index.columns.join(',') && existingIndex.unique === index.unique && !existingIndex.isPartial;
144
+ }
145
+ async function getColumnNames({ db, schemaName, tableName }) {
146
+ const result = await db.execute(sql`
147
+ SELECT column_name FROM information_schema.columns
148
+ WHERE table_schema = ${schemaName} AND table_name = ${tableName}
149
+ `);
150
+ return new Set(result.rows.map((row)=>row.column_name));
151
+ }
152
+ async function getIndexes({ db, schemaName, tableName }) {
153
+ const result = await db.execute(sql`
154
+ SELECT
155
+ i.relname AS name,
156
+ array_agg(a.attname::text ORDER BY k.ord) AS columns,
157
+ ix.indisunique AS is_unique,
158
+ ix.indpred IS NOT NULL AS is_partial
159
+ FROM pg_index ix
160
+ JOIN pg_class t ON t.oid = ix.indrelid
161
+ JOIN pg_namespace n ON n.oid = t.relnamespace
162
+ JOIN pg_class i ON i.oid = ix.indexrelid
163
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
164
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
165
+ WHERE n.nspname = ${schemaName} AND t.relname = ${tableName}
166
+ GROUP BY i.relname, ix.indisunique, (ix.indpred IS NOT NULL)
167
+ `);
168
+ return result.rows.map((row)=>({
169
+ name: row.name,
170
+ columns: row.columns,
171
+ isPartial: row.is_partial,
172
+ unique: row.is_unique
173
+ }));
174
+ }
175
+ export async function getPostgresSchemaRelationNames({ db, schemaName }) {
176
+ const result = await db.execute(sql`
177
+ SELECT c.relname AS name
178
+ FROM pg_class c
179
+ JOIN pg_namespace n ON n.oid = c.relnamespace
180
+ WHERE n.nspname = ${schemaName}
181
+ `);
182
+ return new Set(result.rows.map((row)=>row.name));
183
+ }
184
+
185
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/postgres/predefinedMigrations/sizes-to-variants/index.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { sql } from 'drizzle-orm'\n\nimport type {\n SizesToVariantsDirection,\n SizesToVariantsIndexRename,\n} from '../../../utilities/getSizesToVariantsRenames.js'\nimport type { BasePostgresAdapter } from '../../types.js'\n\nimport {\n assertNoSizesToVariantsColumnCollisions,\n buildGeneratedLegacyIndexName,\n getSizesToVariantsRenames,\n isGeneratedLegacyIndexName,\n} from '../../../utilities/getSizesToVariantsRenames.js'\n\ntype ExistingPostgresIndex = {\n columns: string[]\n isPartial: boolean\n name: string\n unique: boolean\n}\n\n/**\n * Moves every upload collection's stored image sizes between the legacy `sizes_*` columns and\n * `variants_*` (main and versions tables), renaming each column in place so no data is copied,\n * then renames the indexes on those columns to what the current schema expects. Skips columns\n * that are already renamed, so it's safe to re-run.\n */\nexport async function migratePostgresSizesToVariants({\n db,\n direction = 'up',\n payload,\n}: {\n db: any\n direction?: SizesToVariantsDirection\n payload: Payload\n}): Promise<void> {\n const adapter = payload.db as unknown as BasePostgresAdapter\n const schemaName = adapter.schemaName || 'public'\n const plan = getSizesToVariantsRenames({ adapter, direction })\n const plannedTables: Array<\n (typeof plan)[number] & {\n existingColumns: Set<string>\n }\n > = []\n\n for (const tablePlan of plan) {\n const existingColumns = await getColumnNames({\n db,\n schemaName,\n tableName: tablePlan.tableName,\n })\n\n assertNoSizesToVariantsColumnCollisions({\n columns: tablePlan.columns,\n existingColumns,\n tableName: tablePlan.tableName,\n })\n\n plannedTables.push({ ...tablePlan, existingColumns })\n }\n\n const reservedRelationNames =\n direction === 'down' ? await getPostgresSchemaRelationNames({ db, schemaName }) : undefined\n\n for (const { columns, existingColumns, indexes, tableName } of plannedTables) {\n let renamedCount = 0\n\n for (const { from, to } of columns) {\n if (!existingColumns.has(from) || existingColumns.has(to)) {\n continue\n }\n\n await db.execute(sql`\n ALTER TABLE ${sql.identifier(schemaName)}.${sql.identifier(tableName)}\n RENAME COLUMN ${sql.identifier(from)} TO ${sql.identifier(to)}\n `)\n renamedCount++\n }\n\n const existingIndexes = await getIndexes({ db, schemaName, tableName })\n\n for (const plannedIndex of indexes) {\n const index =\n reservedRelationNames && plannedIndex.legacyNameBase\n ? {\n ...plannedIndex,\n to: reservePostgresLegacyIndexName({\n existingIndexes,\n index: plannedIndex,\n reservedRelationNames,\n }),\n }\n : plannedIndex\n const existingName = resolvePostgresIndexRename({\n existingIndexes,\n index,\n tableName,\n })\n\n if (!existingName) {\n continue\n }\n\n await db.execute(sql`\n ALTER INDEX ${sql.identifier(schemaName)}.${sql.identifier(existingName)}\n RENAME TO ${sql.identifier(index.to)}\n `)\n }\n\n payload.logger.info({\n msg: `sizes-to-variants (${direction}): renamed ${renamedCount} column(s) on \"${tableName}\"`,\n })\n }\n}\n\nexport function reservePostgresLegacyIndexName({\n existingIndexes,\n index,\n reservedRelationNames,\n}: {\n existingIndexes: ExistingPostgresIndex[]\n index: SizesToVariantsIndexRename\n reservedRelationNames: Set<string>\n}): string {\n const { legacyNameBase } = index\n\n if (!legacyNameBase) {\n reservedRelationNames.add(index.to)\n return index.to\n }\n\n const existingDestination = existingIndexes.find(\n (existingIndex) =>\n isCompatiblePostgresIndex({ existingIndex, index }) &&\n isGeneratedLegacyIndexName({\n indexName: existingIndex.name,\n legacyNameBase,\n }),\n )\n\n if (existingDestination) {\n reservedRelationNames.add(existingDestination.name)\n return existingDestination.name\n }\n\n let number = 0\n let indexName = buildGeneratedLegacyIndexName(legacyNameBase)\n\n while (reservedRelationNames.has(indexName)) {\n number++\n indexName = buildGeneratedLegacyIndexName(legacyNameBase, number)\n }\n\n reservedRelationNames.add(indexName)\n return indexName\n}\n\nexport function resolvePostgresIndexRename({\n existingIndexes,\n index,\n tableName,\n}: {\n existingIndexes: ExistingPostgresIndex[]\n index: SizesToVariantsIndexRename\n tableName: string\n}): string | undefined {\n const destinationIndex = existingIndexes.find(({ name }) => name === index.to)\n\n if (destinationIndex) {\n if (!isCompatiblePostgresIndex({ existingIndex: destinationIndex, index })) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because index \"${index.to}\" on table \"${tableName}\" does not match the expected columns, uniqueness, or predicate.`,\n )\n }\n\n return undefined\n }\n\n let sourceIndex: ExistingPostgresIndex | undefined\n const { legacyNameBase } = index\n\n if (index.from) {\n sourceIndex = existingIndexes.find(({ name }) => name === index.from)\n } else if (legacyNameBase) {\n const legacyCandidates = existingIndexes.filter((existingIndex) =>\n isGeneratedLegacyIndexName({\n indexName: existingIndex.name,\n legacyNameBase,\n }),\n )\n\n sourceIndex =\n legacyCandidates.find((existingIndex) =>\n isCompatiblePostgresIndex({ existingIndex, index }),\n ) ?? legacyCandidates[0]\n }\n\n if (!sourceIndex) {\n return undefined\n }\n\n if (!isCompatiblePostgresIndex({ existingIndex: sourceIndex, index })) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because index \"${sourceIndex.name}\" on table \"${tableName}\" does not match the expected columns, uniqueness, or predicate.`,\n )\n }\n\n return sourceIndex.name === index.to ? undefined : sourceIndex.name\n}\n\nfunction isCompatiblePostgresIndex({\n existingIndex,\n index,\n}: {\n existingIndex: ExistingPostgresIndex\n index: SizesToVariantsIndexRename\n}): boolean {\n return (\n existingIndex.columns.join(',') === index.columns.join(',') &&\n existingIndex.unique === index.unique &&\n !existingIndex.isPartial\n )\n}\n\nasync function getColumnNames({\n db,\n schemaName,\n tableName,\n}: {\n db: any\n schemaName: string\n tableName: string\n}): Promise<Set<string>> {\n const result = await db.execute(sql`\n SELECT column_name FROM information_schema.columns\n WHERE table_schema = ${schemaName} AND table_name = ${tableName}\n `)\n\n return new Set(result.rows.map((row: { column_name: string }) => row.column_name))\n}\n\nasync function getIndexes({\n db,\n schemaName,\n tableName,\n}: {\n db: any\n schemaName: string\n tableName: string\n}): Promise<ExistingPostgresIndex[]> {\n const result = await db.execute(sql`\n SELECT\n i.relname AS name,\n array_agg(a.attname::text ORDER BY k.ord) AS columns,\n ix.indisunique AS is_unique,\n ix.indpred IS NOT NULL AS is_partial\n FROM pg_index ix\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n JOIN pg_class i ON i.oid = ix.indexrelid\n CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum\n WHERE n.nspname = ${schemaName} AND t.relname = ${tableName}\n GROUP BY i.relname, ix.indisunique, (ix.indpred IS NOT NULL)\n `)\n\n return result.rows.map(\n (row: { columns: string[]; is_partial: boolean; is_unique: boolean; name: string }) => ({\n name: row.name,\n columns: row.columns,\n isPartial: row.is_partial,\n unique: row.is_unique,\n }),\n )\n}\n\nexport async function getPostgresSchemaRelationNames({\n db,\n schemaName,\n}: {\n db: any\n schemaName: string\n}): Promise<Set<string>> {\n const result = await db.execute(sql`\n SELECT c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${schemaName}\n `)\n\n return new Set(result.rows.map((row: { name: string }) => row.name))\n}\n"],"names":["sql","assertNoSizesToVariantsColumnCollisions","buildGeneratedLegacyIndexName","getSizesToVariantsRenames","isGeneratedLegacyIndexName","migratePostgresSizesToVariants","db","direction","payload","adapter","schemaName","plan","plannedTables","tablePlan","existingColumns","getColumnNames","tableName","columns","push","reservedRelationNames","getPostgresSchemaRelationNames","undefined","indexes","renamedCount","from","to","has","execute","identifier","existingIndexes","getIndexes","plannedIndex","index","legacyNameBase","reservePostgresLegacyIndexName","existingName","resolvePostgresIndexRename","logger","info","msg","add","existingDestination","find","existingIndex","isCompatiblePostgresIndex","indexName","name","number","destinationIndex","Error","sourceIndex","legacyCandidates","filter","join","unique","isPartial","result","Set","rows","map","row","column_name","is_partial","is_unique"],"mappings":"AAEA,SAASA,GAAG,QAAQ,cAAa;AAQjC,SACEC,uCAAuC,EACvCC,6BAA6B,EAC7BC,yBAAyB,EACzBC,0BAA0B,QACrB,kDAAiD;AASxD;;;;;CAKC,GACD,OAAO,eAAeC,+BAA+B,EACnDC,EAAE,EACFC,YAAY,IAAI,EAChBC,OAAO,EAKR;IACC,MAAMC,UAAUD,QAAQF,EAAE;IAC1B,MAAMI,aAAaD,QAAQC,UAAU,IAAI;IACzC,MAAMC,OAAOR,0BAA0B;QAAEM;QAASF;IAAU;IAC5D,MAAMK,gBAIF,EAAE;IAEN,KAAK,MAAMC,aAAaF,KAAM;QAC5B,MAAMG,kBAAkB,MAAMC,eAAe;YAC3CT;YACAI;YACAM,WAAWH,UAAUG,SAAS;QAChC;QAEAf,wCAAwC;YACtCgB,SAASJ,UAAUI,OAAO;YAC1BH;YACAE,WAAWH,UAAUG,SAAS;QAChC;QAEAJ,cAAcM,IAAI,CAAC;YAAE,GAAGL,SAAS;YAAEC;QAAgB;IACrD;IAEA,MAAMK,wBACJZ,cAAc,SAAS,MAAMa,+BAA+B;QAAEd;QAAII;IAAW,KAAKW;IAEpF,KAAK,MAAM,EAAEJ,OAAO,EAAEH,eAAe,EAAEQ,OAAO,EAAEN,SAAS,EAAE,IAAIJ,cAAe;QAC5E,IAAIW,eAAe;QAEnB,KAAK,MAAM,EAAEC,IAAI,EAAEC,EAAE,EAAE,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O,eAAe3C,+BAA+B,EACnDd,EAAE,EACFI,UAAU,EAIX;IACC,MAAM8C,SAAS,MAAMlD,GAAGqB,OAAO,CAAC3B,GAAG,CAAC;;;;sBAIhB,EAAEU,WAAW;EACjC,CAAC;IAED,OAAO,IAAI+C,IAAID,OAAOE,IAAI,CAACC,GAAG,CAAC,CAACC,MAA0BA,IAAId,IAAI;AACpE"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAEtE,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAK/C,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,mBAAmB,CAAA;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,UAAU,CAAA;IACd,KAAK,EAAE,OAAO,CAAA;IACd,YAAY,EAAE,YAAY,CAAA;IAC1B,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,OAAO,CAAA;IACnB,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,cAAc,mHAYxB,IAAI,kBA4MN,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAEtE,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAK/C,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,mBAAmB,CAAA;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,EAAE,EAAE,UAAU,CAAA;IACd,KAAK,EAAE,OAAO,CAAA;IACd,YAAY,EAAE,YAAY,CAAA;IAC1B,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,EAAE,OAAO,CAAA;IACnB,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAC7B,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,cAAc,mHAYxB,IAAI,kBAgNN,CAAA"}
@@ -13,7 +13,8 @@ export const fetchAndResave = async ({ adapter, collectionSlug, db, debug, docsT
13
13
  fallbackLocale: null,
14
14
  locale: 'all',
15
15
  req,
16
- showHiddenFields: true
16
+ showHiddenFields: true,
17
+ overrideAccess: true
17
18
  });
18
19
  if (debug) {
19
20
  payload.logger.info(`The collection "${collectionConfig.slug}" version with ID ${id} will be migrated`);
@@ -52,7 +53,8 @@ export const fetchAndResave = async ({ adapter, collectionSlug, db, debug, docsT
52
53
  fallbackLocale: null,
53
54
  locale: 'all',
54
55
  req,
55
- showHiddenFields: true
56
+ showHiddenFields: true,
57
+ overrideAccess: true
56
58
  });
57
59
  if (debug) {
58
60
  payload.logger.info(`The collection "${collectionConfig.slug}" with ID ${doc.id} will be migrated`);
@@ -97,7 +99,8 @@ export const fetchAndResave = async ({ adapter, collectionSlug, db, debug, docsT
97
99
  limit: 0,
98
100
  locale: 'all',
99
101
  req,
100
- showHiddenFields: true
102
+ showHiddenFields: true,
103
+ overrideAccess: true
101
104
  });
102
105
  if (debug) {
103
106
  payload.logger.info(`${docs.length} global "${globalSlug}" versions will be migrated`);
@@ -137,7 +140,8 @@ export const fetchAndResave = async ({ adapter, collectionSlug, db, debug, docsT
137
140
  fallbackLocale: null,
138
141
  locale: 'all',
139
142
  req,
140
- showHiddenFields: true
143
+ showHiddenFields: true,
144
+ overrideAccess: true
141
145
  });
142
146
  traverseFields({
143
147
  doc,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts"],"sourcesContent":["import type { FlattenedField, Payload, PayloadRequest } from 'payload'\n\nimport type { BasePostgresAdapter, PostgresDB } from '../../../types.js'\nimport type { DocsToResave } from '../types.js'\n\nimport { upsertRow } from '../../../../upsertRow/index.js'\nimport { traverseFields } from './traverseFields.js'\n\ntype Args = {\n adapter: BasePostgresAdapter\n collectionSlug?: string\n db: PostgresDB\n debug: boolean\n docsToResave: DocsToResave\n fields: FlattenedField[]\n globalSlug?: string\n isVersions: boolean\n payload: Payload\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\nexport const fetchAndResave = async ({\n adapter,\n collectionSlug,\n db,\n debug,\n docsToResave,\n fields,\n globalSlug,\n isVersions,\n payload,\n req,\n tableName,\n}: Args) => {\n for (const [id, rows] of Object.entries(docsToResave)) {\n if (collectionSlug) {\n const collectionConfig = payload.collections[collectionSlug].config\n\n if (collectionConfig) {\n if (isVersions) {\n const doc = await payload.findVersionByID({\n id,\n collection: collectionSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n })\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" version with ID ${id} will be migrated`,\n )\n }\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n collectionSlug,\n data: doc,\n db,\n fields,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(\n `\"${collectionConfig.slug}\" version with ID ${doc.id} FAILED TO MIGRATE`,\n )\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `\"${collectionConfig.slug}\" version with ID ${doc.id} migrated successfully!`,\n )\n }\n } else {\n const doc = await payload.findByID({\n id,\n collection: collectionSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n })\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} will be migrated`,\n )\n }\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n collectionSlug,\n data: doc,\n db,\n fields,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} has FAILED TO MIGRATE`,\n )\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} has migrated successfully!`,\n )\n }\n }\n }\n }\n\n if (globalSlug) {\n const globalConfig = payload.config.globals?.find((global) => global.slug === globalSlug)\n\n if (globalConfig) {\n if (isVersions) {\n const { docs } = await payload.findGlobalVersions({\n slug: globalSlug,\n depth: 0,\n fallbackLocale: null,\n limit: 0,\n locale: 'all',\n req,\n showHiddenFields: true,\n })\n\n if (debug) {\n payload.logger.info(`${docs.length} global \"${globalSlug}\" versions will be migrated`)\n }\n\n for (const doc of docs) {\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n data: doc,\n db,\n fields,\n globalSlug,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(`\"${globalSlug}\" version with ID ${doc.id} FAILED TO MIGRATE`)\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `\"${globalSlug}\" version with ID ${doc.id} migrated successfully!`,\n )\n }\n }\n } else {\n const doc = await payload.findGlobal({\n slug: globalSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n })\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n adapter,\n data: doc,\n db,\n fields,\n globalSlug,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(`The global \"${globalSlug}\" has FAILED TO MIGRATE`)\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(`The global \"${globalSlug}\" has migrated successfully!`)\n }\n }\n }\n }\n }\n}\n"],"names":["upsertRow","traverseFields","fetchAndResave","adapter","collectionSlug","db","debug","docsToResave","fields","globalSlug","isVersions","payload","req","tableName","id","rows","Object","entries","collectionConfig","collections","config","doc","findVersionByID","collection","depth","fallbackLocale","locale","showHiddenFields","logger","info","slug","path","data","ignoreResult","operation","err","error","findByID","globalConfig","globals","find","global","docs","findGlobalVersions","limit","length","findGlobal"],"mappings":"AAKA,SAASA,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,cAAc,QAAQ,sBAAqB;AAgBpD,OAAO,MAAMC,iBAAiB,OAAO,EACnCC,OAAO,EACPC,cAAc,EACdC,EAAE,EACFC,KAAK,EACLC,YAAY,EACZC,MAAM,EACNC,UAAU,EACVC,UAAU,EACVC,OAAO,EACPC,GAAG,EACHC,SAAS,EACJ;IACL,KAAK,MAAM,CAACC,IAAIC,KAAK,IAAIC,OAAOC,OAAO,CAACV,cAAe;QACrD,IAAIH,gBAAgB;YAClB,MAAMc,mBAAmBP,QAAQQ,WAAW,CAACf,eAAe,CAACgB,MAAM;YAEnE,IAAIF,kBAAkB;gBACpB,IAAIR,YAAY;oBACd,MAAMW,MAAM,MAAMV,QAAQW,eAAe,CAAC;wBACxCR;wBACAS,YAAYnB;wBACZoB,OAAO;wBACPC,gBAAgB;wBAChBC,QAAQ;wBACRd;wBACAe,kBAAkB;oBACpB;oBAEA,IAAIrB,OAAO;wBACTK,QAAQiB,MAAM,CAACC,IAAI,CACjB,CAAC,gBAAgB,EAAEX,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AEpB,WAAW,kBAAkB,EAAEY,IAAIP,EAAE,CAAC,uBAAuB,CAAC;wBAEtE;oBACF;gBACF,OAAO;oBACL,MAAMO,MAAM,MAAMV,QAAQmC,UAAU,CAAC;wBACnChB,MAAMrB;wBACNe,OAAO;wBACPC,gBAAgB;wBAChBC,QAAQ;wBACRd;wBACAe,kBAAkB;oBACpB;oBAEA1B,eAAe;wBACboB;wBACAb;wBACAuB,MAAM;wBACNhB;oBACF;oBAEA,IAAI;wBACF,MAAMf,UAAU;4BACdG;4BACA6B,MAAMX;4BACNhB;4BACAG;4BACAC;4BACAwB,cAAc;4BACdC,WAAW;4BACXtB;4BACAC;wBACF;oBACF,EAAE,OAAOsB,KAAK;wBACZxB,QAAQiB,MAAM,CAACQ,KAAK,CAAC,CAAC,YAAY,EAAE3B,WAAW,uBAAuB,CAAC;wBAEvE,MAAM0B;oBACR;oBAEA,IAAI7B,OAAO;wBACTK,QAAQiB,MAAM,CAACC,IAAI,CAAC,CAAC,YAAY,EAAEpB,WAAW,4BAA4B,CAAC;oBAC7E;gBACF;YACF;QACF;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../src/postgres/predefinedMigrations/v2-v3/fetchAndResave/index.ts"],"sourcesContent":["import type { FlattenedField, Payload, PayloadRequest } from 'payload'\n\nimport type { BasePostgresAdapter, PostgresDB } from '../../../types.js'\nimport type { DocsToResave } from '../types.js'\n\nimport { upsertRow } from '../../../../upsertRow/index.js'\nimport { traverseFields } from './traverseFields.js'\n\ntype Args = {\n adapter: BasePostgresAdapter\n collectionSlug?: string\n db: PostgresDB\n debug: boolean\n docsToResave: DocsToResave\n fields: FlattenedField[]\n globalSlug?: string\n isVersions: boolean\n payload: Payload\n req?: Partial<PayloadRequest>\n tableName: string\n}\n\nexport const fetchAndResave = async ({\n adapter,\n collectionSlug,\n db,\n debug,\n docsToResave,\n fields,\n globalSlug,\n isVersions,\n payload,\n req,\n tableName,\n}: Args) => {\n for (const [id, rows] of Object.entries(docsToResave)) {\n if (collectionSlug) {\n const collectionConfig = payload.collections[collectionSlug].config\n\n if (collectionConfig) {\n if (isVersions) {\n const doc = await payload.findVersionByID({\n id,\n collection: collectionSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n overrideAccess: true,\n })\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" version with ID ${id} will be migrated`,\n )\n }\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n collectionSlug,\n data: doc,\n db,\n fields,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(\n `\"${collectionConfig.slug}\" version with ID ${doc.id} FAILED TO MIGRATE`,\n )\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `\"${collectionConfig.slug}\" version with ID ${doc.id} migrated successfully!`,\n )\n }\n } else {\n const doc = await payload.findByID({\n id,\n collection: collectionSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n overrideAccess: true,\n })\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} will be migrated`,\n )\n }\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n collectionSlug,\n data: doc,\n db,\n fields,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} has FAILED TO MIGRATE`,\n )\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `The collection \"${collectionConfig.slug}\" with ID ${doc.id} has migrated successfully!`,\n )\n }\n }\n }\n }\n\n if (globalSlug) {\n const globalConfig = payload.config.globals?.find((global) => global.slug === globalSlug)\n\n if (globalConfig) {\n if (isVersions) {\n const { docs } = await payload.findGlobalVersions({\n slug: globalSlug,\n depth: 0,\n fallbackLocale: null,\n limit: 0,\n locale: 'all',\n req,\n showHiddenFields: true,\n overrideAccess: true,\n })\n\n if (debug) {\n payload.logger.info(`${docs.length} global \"${globalSlug}\" versions will be migrated`)\n }\n\n for (const doc of docs) {\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n id: doc.id,\n adapter,\n data: doc,\n db,\n fields,\n globalSlug,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(`\"${globalSlug}\" version with ID ${doc.id} FAILED TO MIGRATE`)\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(\n `\"${globalSlug}\" version with ID ${doc.id} migrated successfully!`,\n )\n }\n }\n } else {\n const doc = await payload.findGlobal({\n slug: globalSlug,\n depth: 0,\n fallbackLocale: null,\n locale: 'all',\n req,\n showHiddenFields: true,\n overrideAccess: true,\n })\n\n traverseFields({\n doc,\n fields,\n path: '',\n rows,\n })\n\n try {\n await upsertRow({\n adapter,\n data: doc,\n db,\n fields,\n globalSlug,\n ignoreResult: true,\n operation: 'update',\n req,\n tableName,\n })\n } catch (err) {\n payload.logger.error(`The global \"${globalSlug}\" has FAILED TO MIGRATE`)\n\n throw err\n }\n\n if (debug) {\n payload.logger.info(`The global \"${globalSlug}\" has migrated successfully!`)\n }\n }\n }\n }\n }\n}\n"],"names":["upsertRow","traverseFields","fetchAndResave","adapter","collectionSlug","db","debug","docsToResave","fields","globalSlug","isVersions","payload","req","tableName","id","rows","Object","entries","collectionConfig","collections","config","doc","findVersionByID","collection","depth","fallbackLocale","locale","showHiddenFields","overrideAccess","logger","info","slug","path","data","ignoreResult","operation","err","error","findByID","globalConfig","globals","find","global","docs","findGlobalVersions","limit","length","findGlobal"],"mappings":"AAKA,SAASA,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,cAAc,QAAQ,sBAAqB;AAgBpD,OAAO,MAAMC,iBAAiB,OAAO,EACnCC,OAAO,EACPC,cAAc,EACdC,EAAE,EAC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AW,4BAA4B,CAAC;oBAC7E;gBACF;YACF;QACF;IACF;AACF,EAAC"}
@@ -110,13 +110,13 @@ export const buildTable = ({ adapter, baseColumns = {}, baseForeignKeys = {}, ba
110
110
  };
111
111
  localesIndexes._localeParent = {
112
112
  name: buildIndexName({
113
- name: `${localeTableName}_locale_parent_id_unique`,
113
+ name: `${localeTableName}_parent_id_locale_unique`,
114
114
  adapter,
115
115
  appendSuffix: false
116
116
  }),
117
117
  on: [
118
- '_locale',
119
- '_parentID'
118
+ '_parentID',
119
+ '_locale'
120
120
  ],
121
121
  unique: true
122
122
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema/build.ts"],"sourcesContent":["import type { FlattenedField, SanitizedCompoundIndex } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type {\n DrizzleAdapter,\n IDType,\n RawColumn,\n RawForeignKey,\n RawIndex,\n RawRelation,\n RawTable,\n RelationMap,\n SetColumnID,\n} from '../types.js'\n\nimport { createTableName } from '../createTableName.js'\nimport { buildForeignKeyName } from '../utilities/buildForeignKeyName.js'\nimport { buildIndexName } from '../utilities/buildIndexName.js'\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport { traverseFields } from './traverseFields.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n baseColumns?: Record<string, RawColumn>\n /**\n * After table is created, run these functions to add extra config to the table\n * ie. indexes, multiple columns, etc\n */\n baseForeignKeys?: Record<string, RawForeignKey>\n /**\n * After table is created, run these functions to add extra config to the table\n * ie. indexes, multiple columns, etc\n */\n baseIndexes?: Record<string, RawIndex>\n blocksTableNameMap: Record<string, number>\n buildNumbers?: boolean\n buildRelationships?: boolean\n compoundIndexes?: SanitizedCompoundIndex[]\n disableNotNull: boolean\n disableRelsTableUnique?: boolean\n disableUnique: boolean\n fields: FlattenedField[]\n parentIsLocalized: boolean\n rootRelationships?: Set<string>\n rootRelationsToBuild?: RelationMap\n rootTableIDColType?: IDType\n rootTableName?: string\n rootUniqueRelationships?: Set<string>\n setColumnID: SetColumnID\n tableName: string\n timestamps?: boolean\n versions: boolean\n /**\n * Tracks whether or not this table is built\n * from the result of a localized array or block field at some point\n */\n withinLocalizedArrayOrBlock?: boolean\n}\n\ntype Result = {\n hasLocalizedManyNumberField: boolean\n hasLocalizedManyTextField: boolean\n hasLocalizedRelationshipField: boolean\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n relationsToBuild: RelationMap\n}\n\nexport const buildTable = ({\n adapter,\n baseColumns = {},\n baseForeignKeys = {},\n baseIndexes = {},\n blocksTableNameMap,\n compoundIndexes,\n disableNotNull,\n disableRelsTableUnique = false,\n disableUnique = false,\n fields,\n parentIsLocalized,\n rootRelationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName: incomingRootTableName,\n rootUniqueRelationships,\n setColumnID,\n tableName,\n timestamps,\n versions,\n withinLocalizedArrayOrBlock,\n}: Args): Result => {\n const isRoot = !incomingRootTableName\n const rootTableName = incomingRootTableName || tableName\n const columns: Record<string, RawColumn> = baseColumns\n const indexes: Record<string, RawIndex> = baseIndexes\n\n const localesColumns: Record<string, RawColumn> = {}\n const localesIndexes: Record<string, RawIndex> = {}\n let localesTable: RawTable\n let textsTable: RawTable\n let numbersTable: RawTable\n\n // Relationships to the base collection\n const relationships: Set<string> = rootRelationships || new Set()\n\n // Unique relationships to the base collection\n const uniqueRelationships: Set<string> = rootUniqueRelationships || new Set()\n\n let relationshipsTable: RawTable\n\n // Drizzle relations\n const relationsToBuild: RelationMap = new Map()\n\n const idColType: IDType = setColumnID({ adapter, columns, fields })\n\n const {\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n } = traverseFields({\n adapter,\n blocksTableNameMap,\n columns,\n disableNotNull,\n disableRelsTableUnique,\n disableUnique,\n fields,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: tableName,\n parentIsLocalized,\n parentTableName: tableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild: rootRelationsToBuild || relationsToBuild,\n rootTableIDColType: rootTableIDColType || idColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock,\n })\n\n // split the relationsToBuild by localized and non-localized\n const localizedRelations = new Map()\n const nonLocalizedRelations = new Map()\n\n relationsToBuild.forEach(({ type, localized, relationName, target }, key) => {\n const map = localized ? localizedRelations : nonLocalizedRelations\n map.set(key, { type, relationName, target })\n })\n\n if (timestamps) {\n columns.createdAt = {\n name: 'created_at',\n type: 'timestamp',\n defaultNow: true,\n mode: 'string',\n notNull: true,\n precision: 3,\n withTimezone: true,\n }\n\n columns.updatedAt = {\n name: 'updated_at',\n type: 'timestamp',\n defaultNow: true,\n mode: 'string',\n notNull: true,\n precision: 3,\n withTimezone: true,\n }\n }\n\n const table: RawTable = {\n name: tableName,\n columns,\n foreignKeys: baseForeignKeys,\n indexes,\n }\n\n adapter.rawTables[tableName] = table\n\n if (hasLocalizedField || localizedRelations.size) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n adapter.rawTables[localeTableName] = localesTable\n\n localesColumns.id = {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n }\n\n localesColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n localesColumns._parentID = {\n name: '_parent_id',\n type: idColType,\n notNull: true,\n }\n\n localesIndexes._localeParent = {\n name: buildIndexName({\n name: `${localeTableName}_locale_parent_id_unique`,\n adapter,\n appendSuffix: false,\n }),\n on: ['_locale', '_parentID'],\n unique: true,\n }\n\n localesTable = {\n name: localeTableName,\n columns: localesColumns,\n foreignKeys: {\n _parentIdFk: {\n name: buildForeignKeyName({ name: `${localeTableName}_parent_id`, adapter }),\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: localesIndexes,\n }\n\n adapter.rawTables[localeTableName] = localesTable\n\n const localeRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: localeTableName,\n },\n ],\n references: ['id'],\n relationName: '_locales',\n to: tableName,\n },\n }\n\n localizedRelations.forEach(({ type, target }, key) => {\n if (type === 'one') {\n localeRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: localeTableName,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n if (type === 'many') {\n localeRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n adapter.rawRelations[localeTableName] = localeRelations\n }\n\n if (compoundIndexes) {\n for (const index of compoundIndexes) {\n let someLocalized: boolean | null = null\n const columns: string[] = []\n\n const getTableToUse = () => {\n if (someLocalized) {\n return localesTable\n }\n\n return table\n }\n\n for (const { path, pathHasLocalized } of index.fields) {\n if (someLocalized === null) {\n someLocalized = pathHasLocalized\n }\n\n if (someLocalized !== pathHasLocalized) {\n throw new InvalidConfiguration(\n `Compound indexes within localized and non localized fields are not supported in SQL. Expected ${path} to be ${someLocalized ? 'non' : ''} localized.`,\n )\n }\n\n const columnPath = path.replaceAll('.', '_')\n\n if (!getTableToUse().columns[columnPath]) {\n throw new InvalidConfiguration(\n `Column ${columnPath} for compound index on ${path} was not found in the ${getTableToUse().name} table.`,\n )\n }\n\n columns.push(columnPath)\n }\n\n if (someLocalized) {\n columns.push('_locale')\n }\n\n let name = columns.join('_')\n // truncate against the limit, buildIndexName will handle collisions\n if (name.length > 63) {\n name = 'compound_index'\n }\n\n const indexName = buildIndexName({ name, adapter })\n\n getTableToUse().indexes[indexName] = {\n name: indexName,\n on: columns,\n unique: disableUnique ? false : index.unique,\n }\n }\n }\n\n if (isRoot) {\n if (hasManyTextField) {\n const textsTableName = `${rootTableName}_texts`\n adapter.rawTables[textsTableName] = textsTable\n\n const columns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n\n notNull: true,\n },\n text: {\n name: 'text',\n type: 'varchar',\n },\n }\n\n if (hasLocalizedManyTextField) {\n columns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const textsTableIndexes: Record<string, RawIndex> = {\n orderParentIdx: {\n name: buildIndexName({\n name: `${textsTableName}_order_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['order', 'parent'],\n },\n }\n\n if (hasManyTextField === 'index') {\n textsTableIndexes.text_idx = {\n name: buildIndexName({ name: `${textsTableName}_text`, adapter }),\n on: 'text',\n }\n }\n\n if (hasLocalizedManyTextField) {\n textsTableIndexes.localeParent = {\n name: buildIndexName({\n name: `${textsTableName}_locale_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['locale', 'parent'],\n }\n }\n\n textsTable = {\n name: textsTableName,\n columns,\n foreignKeys: {\n parentFk: {\n name: buildForeignKeyName({ name: `${textsTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: textsTableIndexes,\n }\n\n adapter.rawTables[textsTableName] = textsTable\n\n adapter.rawRelations[textsTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: textsTableName,\n },\n ],\n references: ['id'],\n relationName: '_texts',\n to: tableName,\n },\n }\n }\n\n if (hasManyNumberField) {\n const numbersTableName = `${rootTableName}_numbers`\n adapter.rawTables[numbersTableName] = numbersTable\n const columns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n number: {\n name: 'number',\n type: 'numeric',\n },\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n notNull: true,\n },\n }\n\n if (hasLocalizedManyNumberField) {\n columns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const numbersTableIndexes: Record<string, RawIndex> = {\n orderParentIdx: {\n name: buildIndexName({ name: `${numbersTableName}_order_parent`, adapter }),\n on: ['order', 'parent'],\n },\n }\n\n if (hasManyNumberField === 'index') {\n numbersTableIndexes.numberIdx = {\n name: buildIndexName({ name: `${numbersTableName}_number`, adapter }),\n on: 'number',\n }\n }\n\n if (hasLocalizedManyNumberField) {\n numbersTableIndexes.localeParent = {\n name: buildIndexName({\n name: `${numbersTableName}_locale_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['locale', 'parent'],\n }\n }\n\n numbersTable = {\n name: numbersTableName,\n columns,\n foreignKeys: {\n parentFk: {\n name: buildForeignKeyName({ name: `${numbersTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: numbersTableIndexes,\n }\n\n adapter.rawTables[numbersTableName] = numbersTable\n\n adapter.rawRelations[numbersTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: numbersTableName,\n },\n ],\n references: ['id'],\n relationName: '_numbers',\n to: tableName,\n },\n }\n }\n\n if (relationships.size) {\n const relationshipColumns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n order: {\n name: 'order',\n type: 'integer',\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n notNull: true,\n },\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipColumns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n const relationshipIndexes: Record<string, RawIndex> = {\n order: {\n name: buildIndexName({ name: `${relationshipsTableName}_order`, adapter }),\n on: 'order',\n },\n parentIdx: {\n name: buildIndexName({ name: `${relationshipsTableName}_parent`, adapter }),\n on: 'parent',\n },\n pathIdx: {\n name: buildIndexName({ name: `${relationshipsTableName}_path`, adapter }),\n on: 'path',\n },\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipIndexes.localeIdx = {\n name: buildIndexName({ name: `${relationshipsTableName}_locale`, adapter }),\n on: 'locale',\n }\n }\n\n const relationshipForeignKeys: Record<string, RawForeignKey> = {\n parentFk: {\n name: buildForeignKeyName({ name: `${relationshipsTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n relationships.forEach((relationTo) => {\n const relationshipConfig = adapter.payload.collections[relationTo].config\n const formattedRelationTo = createTableName({\n adapter,\n config: relationshipConfig,\n throwValidationError: true,\n })\n let colType: 'integer' | 'numeric' | 'uuid' | 'varchar' = isUUIDType(adapter.idType)\n ? 'uuid'\n : 'integer'\n const relatedCollectionCustomIDType =\n adapter.payload.collections[relationshipConfig.slug]?.customIDType\n\n if (relatedCollectionCustomIDType === 'number') {\n colType = 'numeric'\n }\n if (relatedCollectionCustomIDType === 'text') {\n colType = 'varchar'\n }\n\n const colName = `${relationTo}ID`\n\n relationshipColumns[colName] = {\n name: `${formattedRelationTo}_id`,\n type: colType,\n }\n\n relationshipForeignKeys[`${relationTo}IdFk`] = {\n name: buildForeignKeyName({\n name: `${relationshipsTableName}_${toSnakeCase(relationTo)}`,\n adapter,\n }),\n columns: [colName],\n foreignColumns: [\n {\n name: 'id',\n table: formattedRelationTo,\n },\n ],\n onDelete: 'cascade',\n }\n\n const indexColumns = [colName]\n\n const unique = !disableUnique && uniqueRelationships.has(relationTo)\n\n if (unique) {\n indexColumns.push('path')\n }\n if (hasLocalizedRelationshipField) {\n indexColumns.push('locale')\n }\n\n const indexName = buildIndexName({\n name: `${relationshipsTableName}_${formattedRelationTo}_id`,\n adapter,\n })\n\n relationshipIndexes[indexName] = {\n name: indexName,\n on: indexColumns,\n unique,\n }\n })\n\n relationshipsTable = {\n name: relationshipsTableName,\n columns: relationshipColumns,\n foreignKeys: relationshipForeignKeys,\n indexes: relationshipIndexes,\n }\n\n adapter.rawTables[relationshipsTableName] = relationshipsTable\n\n const relationshipsTableRelations: Record<string, RawRelation> = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: relationshipsTableName,\n },\n ],\n references: ['id'],\n relationName: '_rels',\n to: tableName,\n },\n }\n\n relationships.forEach((relationTo) => {\n const relatedTableName = createTableName({\n adapter,\n config: adapter.payload.collections[relationTo].config,\n throwValidationError: true,\n })\n const idColumnName = `${relationTo}ID`\n\n relationshipsTableRelations[idColumnName] = {\n type: 'one',\n fields: [\n {\n name: idColumnName,\n table: relationshipsTableName,\n },\n ],\n references: ['id'],\n relationName: relationTo,\n to: relatedTableName,\n }\n })\n adapter.rawRelations[relationshipsTableName] = relationshipsTableRelations\n }\n }\n\n const tableRelations: Record<string, RawRelation> = {}\n\n nonLocalizedRelations.forEach(({ type, relationName, target }, key) => {\n if (type === 'one') {\n tableRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: tableName,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n if (type === 'many') {\n tableRelations[key] = {\n type: 'many',\n relationName: relationName || key,\n to: target,\n }\n }\n })\n\n if (hasLocalizedField) {\n tableRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: localesTable.name,\n }\n }\n\n if (isRoot && textsTable) {\n tableRelations._texts = {\n type: 'many',\n relationName: '_texts',\n to: textsTable.name,\n }\n }\n\n if (isRoot && numbersTable) {\n tableRelations._numbers = {\n type: 'many',\n relationName: '_numbers',\n to: numbersTable.name,\n }\n }\n\n if (relationships.size && relationshipsTable) {\n tableRelations._rels = {\n type: 'many',\n relationName: '_rels',\n to: relationshipsTable.name,\n }\n }\n\n adapter.rawRelations[tableName] = tableRelations\n\n return {\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n relationsToBuild,\n }\n}\n"],"names":["InvalidConfiguration","toSnakeCase","createTableName","buildForeignKeyName","buildIndexName","isUUIDType","traverseFields","buildTable","adapter","baseColumns","baseForeignKeys","baseIndexes","blocksTableNameMap","compoundIndexes","disableNotNull","disableRelsTableUnique","disableUnique","fields","parentIsLocalized","rootRelationships","rootRelationsToBuild","rootTableIDColType","rootTableName","incomingRootTableName","rootUniqueRelationships","setColumnID","tableName","timestamps","versions","withinLocalizedArrayOrBlock","isRoot","columns","indexes","localesColumns","localesIndexes","localesTable","textsTable","numbersTable","relationships","Set","uniqueRelationships","relationshipsTable","relationsToBuild","Map","idColType","hasLocalizedField","hasLocalizedManyNumberField","hasLocalizedManyTextField","hasLocalizedRelationshipField","hasManyNumberField","hasManyTextField","newTableName","parentTableName","localizedRelations","nonLocalizedRelations","forEach","type","localized","relationName","target","key","map","set","createdAt","name","defaultNow","mode","notNull","precision","withTimezone","updatedAt","table","foreignKeys","rawTables","size","localeTableName","localesSuffix","id","primaryKey","_locale","locale","_parentID","_localeParent","appendSuffix","on","unique","_parentIdFk","foreignColumns","onDelete","localeRelations","references","to","rawRelations","index","someLocalized","getTableToUse","path","pathHasLocalized","columnPath","replaceAll","push","join","length","indexName","textsTableName","order","parent","text","textsTableIndexes","orderParentIdx","text_idx","localeParent","parentFk","numbersTableName","number","numbersTableIndexes","numberIdx","relationshipColumns","relationshipsTableName","relationshipsSuffix","relationshipIndexes","parentIdx","pathIdx","localeIdx","relationshipForeignKeys","relationTo","relationshipConfig","payload","collections","config","formattedRelationTo","throwValidationError","colType","idType","relatedCollectionCustomIDType","slug","customIDType","colName","indexColumns","has","relationshipsTableRelations","relatedTableName","idColumnName","tableRelations","_locales","_texts","_numbers","_rels"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAS;AAC9C,OAAOC,iBAAiB,gBAAe;AAcvC,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,mBAAmB,QA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mBuB,IAAI;QAC7B;IACF;IAEAxD,QAAQoF,YAAY,CAAClE,UAAU,GAAGqH;IAElC,OAAO;QACLjG;QACAC;QACAC;QACAC;QACAC;QACAR;IACF;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/schema/build.ts"],"sourcesContent":["import type { FlattenedField, SanitizedCompoundIndex } from 'payload'\n\nimport { InvalidConfiguration } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type {\n DrizzleAdapter,\n IDType,\n RawColumn,\n RawForeignKey,\n RawIndex,\n RawRelation,\n RawTable,\n RelationMap,\n SetColumnID,\n} from '../types.js'\n\nimport { createTableName } from '../createTableName.js'\nimport { buildForeignKeyName } from '../utilities/buildForeignKeyName.js'\nimport { buildIndexName } from '../utilities/buildIndexName.js'\nimport { isUUIDType } from '../utilities/isUUIDType.js'\nimport { traverseFields } from './traverseFields.js'\n\ntype Args = {\n adapter: DrizzleAdapter\n baseColumns?: Record<string, RawColumn>\n /**\n * After table is created, run these functions to add extra config to the table\n * ie. indexes, multiple columns, etc\n */\n baseForeignKeys?: Record<string, RawForeignKey>\n /**\n * After table is created, run these functions to add extra config to the table\n * ie. indexes, multiple columns, etc\n */\n baseIndexes?: Record<string, RawIndex>\n blocksTableNameMap: Record<string, number>\n buildNumbers?: boolean\n buildRelationships?: boolean\n compoundIndexes?: SanitizedCompoundIndex[]\n disableNotNull: boolean\n disableRelsTableUnique?: boolean\n disableUnique: boolean\n fields: FlattenedField[]\n parentIsLocalized: boolean\n rootRelationships?: Set<string>\n rootRelationsToBuild?: RelationMap\n rootTableIDColType?: IDType\n rootTableName?: string\n rootUniqueRelationships?: Set<string>\n setColumnID: SetColumnID\n tableName: string\n timestamps?: boolean\n versions: boolean\n /**\n * Tracks whether or not this table is built\n * from the result of a localized array or block field at some point\n */\n withinLocalizedArrayOrBlock?: boolean\n}\n\ntype Result = {\n hasLocalizedManyNumberField: boolean\n hasLocalizedManyTextField: boolean\n hasLocalizedRelationshipField: boolean\n hasManyNumberField: 'index' | boolean\n hasManyTextField: 'index' | boolean\n relationsToBuild: RelationMap\n}\n\nexport const buildTable = ({\n adapter,\n baseColumns = {},\n baseForeignKeys = {},\n baseIndexes = {},\n blocksTableNameMap,\n compoundIndexes,\n disableNotNull,\n disableRelsTableUnique = false,\n disableUnique = false,\n fields,\n parentIsLocalized,\n rootRelationships,\n rootRelationsToBuild,\n rootTableIDColType,\n rootTableName: incomingRootTableName,\n rootUniqueRelationships,\n setColumnID,\n tableName,\n timestamps,\n versions,\n withinLocalizedArrayOrBlock,\n}: Args): Result => {\n const isRoot = !incomingRootTableName\n const rootTableName = incomingRootTableName || tableName\n const columns: Record<string, RawColumn> = baseColumns\n const indexes: Record<string, RawIndex> = baseIndexes\n\n const localesColumns: Record<string, RawColumn> = {}\n const localesIndexes: Record<string, RawIndex> = {}\n let localesTable: RawTable\n let textsTable: RawTable\n let numbersTable: RawTable\n\n // Relationships to the base collection\n const relationships: Set<string> = rootRelationships || new Set()\n\n // Unique relationships to the base collection\n const uniqueRelationships: Set<string> = rootUniqueRelationships || new Set()\n\n let relationshipsTable: RawTable\n\n // Drizzle relations\n const relationsToBuild: RelationMap = new Map()\n\n const idColType: IDType = setColumnID({ adapter, columns, fields })\n\n const {\n hasLocalizedField,\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n } = traverseFields({\n adapter,\n blocksTableNameMap,\n columns,\n disableNotNull,\n disableRelsTableUnique,\n disableUnique,\n fields,\n indexes,\n localesColumns,\n localesIndexes,\n newTableName: tableName,\n parentIsLocalized,\n parentTableName: tableName,\n relationships,\n relationsToBuild,\n rootRelationsToBuild: rootRelationsToBuild || relationsToBuild,\n rootTableIDColType: rootTableIDColType || idColType,\n rootTableName,\n setColumnID,\n uniqueRelationships,\n versions,\n withinLocalizedArrayOrBlock,\n })\n\n // split the relationsToBuild by localized and non-localized\n const localizedRelations = new Map()\n const nonLocalizedRelations = new Map()\n\n relationsToBuild.forEach(({ type, localized, relationName, target }, key) => {\n const map = localized ? localizedRelations : nonLocalizedRelations\n map.set(key, { type, relationName, target })\n })\n\n if (timestamps) {\n columns.createdAt = {\n name: 'created_at',\n type: 'timestamp',\n defaultNow: true,\n mode: 'string',\n notNull: true,\n precision: 3,\n withTimezone: true,\n }\n\n columns.updatedAt = {\n name: 'updated_at',\n type: 'timestamp',\n defaultNow: true,\n mode: 'string',\n notNull: true,\n precision: 3,\n withTimezone: true,\n }\n }\n\n const table: RawTable = {\n name: tableName,\n columns,\n foreignKeys: baseForeignKeys,\n indexes,\n }\n\n adapter.rawTables[tableName] = table\n\n if (hasLocalizedField || localizedRelations.size) {\n const localeTableName = `${tableName}${adapter.localesSuffix}`\n adapter.rawTables[localeTableName] = localesTable\n\n localesColumns.id = {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n }\n\n localesColumns._locale = {\n name: '_locale',\n type: 'enum',\n locale: true,\n notNull: true,\n }\n\n localesColumns._parentID = {\n name: '_parent_id',\n type: idColType,\n notNull: true,\n }\n\n localesIndexes._localeParent = {\n name: buildIndexName({\n name: `${localeTableName}_parent_id_locale_unique`,\n adapter,\n appendSuffix: false,\n }),\n on: ['_parentID', '_locale'],\n unique: true,\n }\n\n localesTable = {\n name: localeTableName,\n columns: localesColumns,\n foreignKeys: {\n _parentIdFk: {\n name: buildForeignKeyName({ name: `${localeTableName}_parent_id`, adapter }),\n columns: ['_parentID'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: localesIndexes,\n }\n\n adapter.rawTables[localeTableName] = localesTable\n\n const localeRelations: Record<string, RawRelation> = {\n _parentID: {\n type: 'one',\n fields: [\n {\n name: '_parentID',\n table: localeTableName,\n },\n ],\n references: ['id'],\n relationName: '_locales',\n to: tableName,\n },\n }\n\n localizedRelations.forEach(({ type, target }, key) => {\n if (type === 'one') {\n localeRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: localeTableName,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n if (type === 'many') {\n localeRelations[key] = {\n type: 'many',\n relationName: key,\n to: target,\n }\n }\n })\n adapter.rawRelations[localeTableName] = localeRelations\n }\n\n if (compoundIndexes) {\n for (const index of compoundIndexes) {\n let someLocalized: boolean | null = null\n const columns: string[] = []\n\n const getTableToUse = () => {\n if (someLocalized) {\n return localesTable\n }\n\n return table\n }\n\n for (const { path, pathHasLocalized } of index.fields) {\n if (someLocalized === null) {\n someLocalized = pathHasLocalized\n }\n\n if (someLocalized !== pathHasLocalized) {\n throw new InvalidConfiguration(\n `Compound indexes within localized and non localized fields are not supported in SQL. Expected ${path} to be ${someLocalized ? 'non' : ''} localized.`,\n )\n }\n\n const columnPath = path.replaceAll('.', '_')\n\n if (!getTableToUse().columns[columnPath]) {\n throw new InvalidConfiguration(\n `Column ${columnPath} for compound index on ${path} was not found in the ${getTableToUse().name} table.`,\n )\n }\n\n columns.push(columnPath)\n }\n\n if (someLocalized) {\n columns.push('_locale')\n }\n\n let name = columns.join('_')\n // truncate against the limit, buildIndexName will handle collisions\n if (name.length > 63) {\n name = 'compound_index'\n }\n\n const indexName = buildIndexName({ name, adapter })\n\n getTableToUse().indexes[indexName] = {\n name: indexName,\n on: columns,\n unique: disableUnique ? false : index.unique,\n }\n }\n }\n\n if (isRoot) {\n if (hasManyTextField) {\n const textsTableName = `${rootTableName}_texts`\n adapter.rawTables[textsTableName] = textsTable\n\n const columns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n\n notNull: true,\n },\n text: {\n name: 'text',\n type: 'varchar',\n },\n }\n\n if (hasLocalizedManyTextField) {\n columns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const textsTableIndexes: Record<string, RawIndex> = {\n orderParentIdx: {\n name: buildIndexName({\n name: `${textsTableName}_order_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['order', 'parent'],\n },\n }\n\n if (hasManyTextField === 'index') {\n textsTableIndexes.text_idx = {\n name: buildIndexName({ name: `${textsTableName}_text`, adapter }),\n on: 'text',\n }\n }\n\n if (hasLocalizedManyTextField) {\n textsTableIndexes.localeParent = {\n name: buildIndexName({\n name: `${textsTableName}_locale_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['locale', 'parent'],\n }\n }\n\n textsTable = {\n name: textsTableName,\n columns,\n foreignKeys: {\n parentFk: {\n name: buildForeignKeyName({ name: `${textsTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: textsTableIndexes,\n }\n\n adapter.rawTables[textsTableName] = textsTable\n\n adapter.rawRelations[textsTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: textsTableName,\n },\n ],\n references: ['id'],\n relationName: '_texts',\n to: tableName,\n },\n }\n }\n\n if (hasManyNumberField) {\n const numbersTableName = `${rootTableName}_numbers`\n adapter.rawTables[numbersTableName] = numbersTable\n const columns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n number: {\n name: 'number',\n type: 'numeric',\n },\n order: {\n name: 'order',\n type: 'integer',\n notNull: true,\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n notNull: true,\n },\n }\n\n if (hasLocalizedManyNumberField) {\n columns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const numbersTableIndexes: Record<string, RawIndex> = {\n orderParentIdx: {\n name: buildIndexName({ name: `${numbersTableName}_order_parent`, adapter }),\n on: ['order', 'parent'],\n },\n }\n\n if (hasManyNumberField === 'index') {\n numbersTableIndexes.numberIdx = {\n name: buildIndexName({ name: `${numbersTableName}_number`, adapter }),\n on: 'number',\n }\n }\n\n if (hasLocalizedManyNumberField) {\n numbersTableIndexes.localeParent = {\n name: buildIndexName({\n name: `${numbersTableName}_locale_parent`,\n adapter,\n appendSuffix: false,\n }),\n on: ['locale', 'parent'],\n }\n }\n\n numbersTable = {\n name: numbersTableName,\n columns,\n foreignKeys: {\n parentFk: {\n name: buildForeignKeyName({ name: `${numbersTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n },\n indexes: numbersTableIndexes,\n }\n\n adapter.rawTables[numbersTableName] = numbersTable\n\n adapter.rawRelations[numbersTableName] = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: numbersTableName,\n },\n ],\n references: ['id'],\n relationName: '_numbers',\n to: tableName,\n },\n }\n }\n\n if (relationships.size) {\n const relationshipColumns: Record<string, RawColumn> = {\n id: {\n name: 'id',\n type: 'serial',\n primaryKey: true,\n },\n order: {\n name: 'order',\n type: 'integer',\n },\n parent: {\n name: 'parent_id',\n type: idColType,\n notNull: true,\n },\n path: {\n name: 'path',\n type: 'varchar',\n notNull: true,\n },\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipColumns.locale = {\n name: 'locale',\n type: 'enum',\n locale: true,\n }\n }\n\n const relationshipsTableName = `${tableName}${adapter.relationshipsSuffix}`\n\n const relationshipIndexes: Record<string, RawIndex> = {\n order: {\n name: buildIndexName({ name: `${relationshipsTableName}_order`, adapter }),\n on: 'order',\n },\n parentIdx: {\n name: buildIndexName({ name: `${relationshipsTableName}_parent`, adapter }),\n on: 'parent',\n },\n pathIdx: {\n name: buildIndexName({ name: `${relationshipsTableName}_path`, adapter }),\n on: 'path',\n },\n }\n\n if (hasLocalizedRelationshipField) {\n relationshipIndexes.localeIdx = {\n name: buildIndexName({ name: `${relationshipsTableName}_locale`, adapter }),\n on: 'locale',\n }\n }\n\n const relationshipForeignKeys: Record<string, RawForeignKey> = {\n parentFk: {\n name: buildForeignKeyName({ name: `${relationshipsTableName}_parent`, adapter }),\n columns: ['parent'],\n foreignColumns: [\n {\n name: 'id',\n table: tableName,\n },\n ],\n onDelete: 'cascade',\n },\n }\n\n relationships.forEach((relationTo) => {\n const relationshipConfig = adapter.payload.collections[relationTo].config\n const formattedRelationTo = createTableName({\n adapter,\n config: relationshipConfig,\n throwValidationError: true,\n })\n let colType: 'integer' | 'numeric' | 'uuid' | 'varchar' = isUUIDType(adapter.idType)\n ? 'uuid'\n : 'integer'\n const relatedCollectionCustomIDType =\n adapter.payload.collections[relationshipConfig.slug]?.customIDType\n\n if (relatedCollectionCustomIDType === 'number') {\n colType = 'numeric'\n }\n if (relatedCollectionCustomIDType === 'text') {\n colType = 'varchar'\n }\n\n const colName = `${relationTo}ID`\n\n relationshipColumns[colName] = {\n name: `${formattedRelationTo}_id`,\n type: colType,\n }\n\n relationshipForeignKeys[`${relationTo}IdFk`] = {\n name: buildForeignKeyName({\n name: `${relationshipsTableName}_${toSnakeCase(relationTo)}`,\n adapter,\n }),\n columns: [colName],\n foreignColumns: [\n {\n name: 'id',\n table: formattedRelationTo,\n },\n ],\n onDelete: 'cascade',\n }\n\n const indexColumns = [colName]\n\n const unique = !disableUnique && uniqueRelationships.has(relationTo)\n\n if (unique) {\n indexColumns.push('path')\n }\n if (hasLocalizedRelationshipField) {\n indexColumns.push('locale')\n }\n\n const indexName = buildIndexName({\n name: `${relationshipsTableName}_${formattedRelationTo}_id`,\n adapter,\n })\n\n relationshipIndexes[indexName] = {\n name: indexName,\n on: indexColumns,\n unique,\n }\n })\n\n relationshipsTable = {\n name: relationshipsTableName,\n columns: relationshipColumns,\n foreignKeys: relationshipForeignKeys,\n indexes: relationshipIndexes,\n }\n\n adapter.rawTables[relationshipsTableName] = relationshipsTable\n\n const relationshipsTableRelations: Record<string, RawRelation> = {\n parent: {\n type: 'one',\n fields: [\n {\n name: 'parent',\n table: relationshipsTableName,\n },\n ],\n references: ['id'],\n relationName: '_rels',\n to: tableName,\n },\n }\n\n relationships.forEach((relationTo) => {\n const relatedTableName = createTableName({\n adapter,\n config: adapter.payload.collections[relationTo].config,\n throwValidationError: true,\n })\n const idColumnName = `${relationTo}ID`\n\n relationshipsTableRelations[idColumnName] = {\n type: 'one',\n fields: [\n {\n name: idColumnName,\n table: relationshipsTableName,\n },\n ],\n references: ['id'],\n relationName: relationTo,\n to: relatedTableName,\n }\n })\n adapter.rawRelations[relationshipsTableName] = relationshipsTableRelations\n }\n }\n\n const tableRelations: Record<string, RawRelation> = {}\n\n nonLocalizedRelations.forEach(({ type, relationName, target }, key) => {\n if (type === 'one') {\n tableRelations[key] = {\n type: 'one',\n fields: [\n {\n name: key,\n table: tableName,\n },\n ],\n references: ['id'],\n relationName: key,\n to: target,\n }\n }\n if (type === 'many') {\n tableRelations[key] = {\n type: 'many',\n relationName: relationName || key,\n to: target,\n }\n }\n })\n\n if (hasLocalizedField) {\n tableRelations._locales = {\n type: 'many',\n relationName: '_locales',\n to: localesTable.name,\n }\n }\n\n if (isRoot && textsTable) {\n tableRelations._texts = {\n type: 'many',\n relationName: '_texts',\n to: textsTable.name,\n }\n }\n\n if (isRoot && numbersTable) {\n tableRelations._numbers = {\n type: 'many',\n relationName: '_numbers',\n to: numbersTable.name,\n }\n }\n\n if (relationships.size && relationshipsTable) {\n tableRelations._rels = {\n type: 'many',\n relationName: '_rels',\n to: relationshipsTable.name,\n }\n }\n\n adapter.rawRelations[tableName] = tableRelations\n\n return {\n hasLocalizedManyNumberField,\n hasLocalizedManyTextField,\n hasLocalizedRelationshipField,\n hasManyNumberField,\n hasManyTextField,\n relationsToBuild,\n }\n}\n"],"names":["InvalidConfiguration","toSnakeCase","createTableName","buildForeignKeyName","buildIndexName","isUUIDType","traverseFields","buildTable","adapter","baseColumns","baseForeignKeys","baseIndexes","blocksTableNameMap","compoundIndexes","disableNotNull","disableRelsTableUnique","disableUnique","fields","parentIsLocalized","rootRelationships","rootRelationsToBuild","rootTableIDColType","rootTableName","incomingRootTableName","rootUniqueRelationships","setColumnID","tableName","timestamps","versions","withinLocalizedArrayOrBlock","isRoot","columns","indexes","localesColumns","localesIndexes","localesTable","textsTable","numbersTable","relationships","Set","uniqueRelationships","relationshipsTable","relationsToBuild","Map","idColType","hasLocalizedField","hasLocalizedManyNumberField","hasLocalizedManyTextField","hasLocalizedRelationshipField","hasManyNumberField","hasManyTextField","newTableName","parentTableName","localizedRelations","nonLocalizedRelations","forEach","type","localized","relationName","target","key","map","set","createdAt","name","defaultNow","mode","notNull","precision","withTimezone","updatedAt","table","foreignKeys","rawTables","size","localeTableName","localesSuffix","id","primaryKey","_locale","locale","_parentID","_localeParent","appendSuffix","on","unique","_parentIdFk","foreignColumns","onDelete","localeRelations","references","to","rawRelations","index","someLocalized","getTableToUse","path","pathHasLocalized","columnPath","replaceAll","push","join","length","indexName","textsTableName","order","parent","text","textsTableIndexes","orderParentIdx","text_idx","localeParent","parentFk","numbersTableName","number","numbersTableIndexes","numberIdx","relationshipColumns","relationshipsTableName","relationshipsSuffix","relationshipIndexes","parentIdx","pathIdx","localeIdx","relationshipForeignKeys","relationTo","relationshipConfig","payload","collections","config","formattedRelationTo","throwValidationError","colType","idType","relatedCollectionCustomIDType","slug","customIDType","colName","indexColumns","has","relationshipsTableRelations","relatedTableName","idColumnName","tableRelations","_locales","_texts","_numbers","_rels"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAS;AAC9C,OAAOC,iBAAiB,gBAAe;AAcvC,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,UAAU,QAAQ,6BAA4B;AACvD,SAASC,cAAc,QAAQ,sBAAqB;AAiDpD,OAAO,MAAMC,aAAa,CAAC,EACzBC,OAAO,EACPC,cAAc,CAAC,CAAC,EAChBC,kBAAkB,CAAC,CAAC,EACpBC,cAAc,CAAC,CAAC,EAChBC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,CAAC0B,uBAAuB,GAAGsB;QACjD;IACF;IAEA,MAAMG,iBAA8C,CAAC;IAErDzF,sBAAsBC,OAAO,CAAC,CAAC,EAAEC,IAAI,EAAEE,YAAY,EAAEC,MAAM,EAAE,EAAEC;QAC7D,IAAIJ,SAAS,OAAO;YAClBuF,cAAc,CAACnF,IAAI,GAAG;gBACpBJ,MAAM;gBACNvC,QAAQ;oBACN;wBACE+C,MAAMJ;wBACNW,OAAO7C;oBACT;iBACD;gBACDgE,YAAY;oBAAC;iBAAK;gBAClBhC,cAAcE;gBACd+B,IAAIhC;YACN;QACF;QACA,IAAIH,SAAS,QAAQ;YACnBuF,cAAc,CAACnF,IAAI,GAAG;gBACpBJ,MAAM;gBACNE,cAAcA,gBAAgBE;gBAC9B+B,IAAIhC;YACN;QACF;IACF;IAEA,IAAId,mBAAmB;QACrBkG,eAAeC,QAAQ,GAAG;YACxBxF,MAAM;YACNE,cAAc;YACdiC,IAAIxD,aAAa6B,IAAI;QACvB;IACF;IAEA,IAAIlC,UAAUM,YAAY;QACxB2G,eAAeE,MAAM,GAAG;YACtBzF,MAAM;YACNE,cAAc;YACdiC,IAAIvD,WAAW4B,IAAI;QACrB;IACF;IAEA,IAAIlC,UAAUO,cAAc;QAC1B0G,eAAeG,QAAQ,GAAG;YACxB1F,MAAM;YACNE,cAAc;YACdiC,IAAItD,aAAa2B,IAAI;QACvB;IACF;IAEA,IAAI1B,cAAcoC,IAAI,IAAIjC,oBAAoB;QAC5CsG,eAAeI,KAAK,GAAG;YACrB3F,MAAM;YACNE,cAAc;YACdiC,IAAIlD,mBAAmBuB,IAAI;QAC7B;IACF;IAEAxD,QAAQoF,YAAY,CAAClE,UAAU,GAAGqH;IAElC,OAAO;QACLjG;QACAC;QACAC;QACAC;QACAC;QACAR;IACF;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sqlite/execute.ts"],"sourcesContent":["import { sql } from 'drizzle-orm'\n\nimport type { Execute } from './types.js'\n\nexport const execute: Execute<any> = function execute({ db, drizzle, raw, sql: statement }) {\n const executeFrom = (db ?? drizzle)\n\n if (raw) {\n const result = executeFrom.run(sql.raw(raw))\n return result\n } else {\n const result = executeFrom.run(statement)\n return result\n }\n}\n"],"names":["sql","execute","db","drizzle","raw","statement","executeFrom","result","run"],"mappings":"AAAA,SAASA,GAAG,QAAQ,cAAa;AAIjC,OAAO,MAAMC,UAAwB,SAASA,QAAQ,EAAEC,EAAE,EAAEC,OAAO,EAAEC,GAAG,EAAEJ,KAAKK,SAAS,EAAE;IACxF,MAAMC,cAAeJ,MAAMC;IAE3B,IAAIC,KAAK;QACP,MAAMG,SAASD,YAAYE,GAAG,CAACR,IAAII,GAAG,CAACA;QACvC,OAAOG;IACT,OAAO;QACL,MAAMA,SAASD,YAAYE,GAAG,CAACH;QAC/B,OAAOE;IACT;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/sqlite/execute.ts"],"sourcesContent":["import { sql } from 'drizzle-orm'\n\nimport type { Execute } from './types.js'\n\nexport const execute: Execute<any> = function execute({ db, drizzle, raw, sql: statement }) {\n const executeFrom = db ?? drizzle\n\n if (raw) {\n const result = executeFrom.run(sql.raw(raw))\n return result\n } else {\n const result = executeFrom.run(statement)\n return result\n }\n}\n"],"names":["sql","execute","db","drizzle","raw","statement","executeFrom","result","run"],"mappings":"AAAA,SAASA,GAAG,QAAQ,cAAa;AAIjC,OAAO,MAAMC,UAAwB,SAASA,QAAQ,EAAEC,EAAE,EAAEC,OAAO,EAAEC,GAAG,EAAEJ,KAAKK,SAAS,EAAE;IACxF,MAAMC,cAAcJ,MAAMC;IAE1B,IAAIC,KAAK;QACP,MAAMG,SAASD,YAAYE,GAAG,CAACR,IAAII,GAAG,CAACA;QACvC,OAAOG;IACT,OAAO;QACL,MAAMA,SAASD,YAAYE,GAAG,CAACH;QAC/B,OAAOE;IACT;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../src/sqlite/insert.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAqB,MAAM,EAAE,MAAM,YAAY,CAAA;AAE3D,eAAO,MAAM,MAAM,EAAE,MAkCpB,CAAA"}
1
+ {"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../src/sqlite/insert.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAqB,MAAM,EAAE,MAAM,YAAY,CAAA;AAE3D,eAAO,MAAM,MAAM,EAAE,MAoCpB,CAAA"}
@@ -1,9 +1,12 @@
1
+ import { getTableColumns } from 'drizzle-orm';
1
2
  export const insert = async function({ db, onConflictDoUpdate, tableName, values }) {
2
3
  const table = this.tables[tableName];
3
4
  // Batch insert if limitedBoundParameters: true
4
5
  if (this.limitedBoundParameters && Array.isArray(values)) {
5
6
  const results = [];
6
- const colsPerRow = Object.keys(values[0]).length;
7
+ // Drizzle emits a value for every table column per row, not just the keys present on the row —
8
+ // omitted columns fall back to their default / defaultFn, which is also a bound parameter
9
+ const colsPerRow = Math.max(1, Object.keys(getTableColumns(table)).length);
7
10
  const maxParams = 100;
8
11
  const maxRowsPerBatch = Math.max(1, Math.floor(maxParams / colsPerRow));
9
12
  for(let i = 0; i < values.length; i += maxRowsPerBatch){