@payloadcms/db-postgres 3.0.0-canary.92e4997 → 3.0.0-canary.c13f9ba

Sign up to get free protection for your applications and to get access to all the features.
Files changed (129) hide show
  1. package/dist/connect.d.ts.map +1 -1
  2. package/dist/connect.js +12 -7
  3. package/dist/connect.js.map +1 -1
  4. package/dist/count.d.ts.map +1 -1
  5. package/dist/count.js +1 -10
  6. package/dist/count.js.map +1 -1
  7. package/dist/createMigration.d.ts.map +1 -1
  8. package/dist/createMigration.js +58 -37
  9. package/dist/createMigration.js.map +1 -1
  10. package/dist/createVersion.d.ts.map +1 -1
  11. package/dist/createVersion.js +2 -6
  12. package/dist/createVersion.js.map +1 -1
  13. package/dist/deleteOne.js +2 -2
  14. package/dist/deleteOne.js.map +1 -1
  15. package/dist/destroy.d.ts.map +1 -1
  16. package/dist/destroy.js +4 -0
  17. package/dist/destroy.js.map +1 -1
  18. package/dist/exports/migration-utils.d.ts +2 -0
  19. package/dist/exports/migration-utils.d.ts.map +1 -0
  20. package/dist/exports/migration-utils.js +3 -0
  21. package/dist/exports/migration-utils.js.map +1 -0
  22. package/dist/find/buildFindManyArgs.d.ts +5 -1
  23. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  24. package/dist/find/buildFindManyArgs.js +2 -1
  25. package/dist/find/buildFindManyArgs.js.map +1 -1
  26. package/dist/find/findMany.d.ts.map +1 -1
  27. package/dist/find/findMany.js +4 -15
  28. package/dist/find/findMany.js.map +1 -1
  29. package/dist/find/traverseFields.d.ts +3 -2
  30. package/dist/find/traverseFields.d.ts.map +1 -1
  31. package/dist/find/traverseFields.js +22 -4
  32. package/dist/find/traverseFields.js.map +1 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +9 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/init.d.ts.map +1 -1
  37. package/dist/init.js +14 -19
  38. package/dist/init.js.map +1 -1
  39. package/dist/predefinedMigrations/relationships-v2-v3.d.ts +4 -0
  40. package/dist/predefinedMigrations/relationships-v2-v3.d.ts.map +1 -0
  41. package/dist/predefinedMigrations/relationships-v2-v3.js.map +1 -0
  42. package/dist/predefinedMigrations/relationships-v2-v3.mjs +11 -0
  43. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts +20 -0
  44. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -0
  45. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js +170 -0
  46. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -0
  47. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts +11 -0
  48. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -0
  49. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +191 -0
  50. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -0
  51. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts +3 -0
  52. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -0
  53. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js +56 -0
  54. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js.map +1 -0
  55. package/dist/predefinedMigrations/v2-v3/index.d.ts +24 -0
  56. package/dist/predefinedMigrations/v2-v3/index.d.ts.map +1 -0
  57. package/dist/predefinedMigrations/v2-v3/index.js +211 -0
  58. package/dist/predefinedMigrations/v2-v3/index.js.map +1 -0
  59. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts +19 -0
  60. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -0
  61. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +57 -0
  62. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -0
  63. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts +23 -0
  64. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -0
  65. package/dist/predefinedMigrations/v2-v3/traverseFields.js +85 -0
  66. package/dist/predefinedMigrations/v2-v3/traverseFields.js.map +1 -0
  67. package/dist/predefinedMigrations/v2-v3/types.d.ts +9 -0
  68. package/dist/predefinedMigrations/v2-v3/types.d.ts.map +1 -0
  69. package/dist/predefinedMigrations/v2-v3/types.js +6 -0
  70. package/dist/predefinedMigrations/v2-v3/types.js.map +1 -0
  71. package/dist/queries/buildAndOrConditions.d.ts +3 -4
  72. package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
  73. package/dist/queries/buildAndOrConditions.js +1 -2
  74. package/dist/queries/buildAndOrConditions.js.map +1 -1
  75. package/dist/queries/buildQuery.d.ts +1 -2
  76. package/dist/queries/buildQuery.d.ts.map +1 -1
  77. package/dist/queries/buildQuery.js +1 -5
  78. package/dist/queries/buildQuery.js.map +1 -1
  79. package/dist/queries/getTableColumnFromPath.d.ts +3 -4
  80. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  81. package/dist/queries/getTableColumnFromPath.js +168 -96
  82. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  83. package/dist/queries/parseParams.d.ts +3 -4
  84. package/dist/queries/parseParams.d.ts.map +1 -1
  85. package/dist/queries/parseParams.js +7 -6
  86. package/dist/queries/parseParams.js.map +1 -1
  87. package/dist/queries/selectDistinct.d.ts +3 -4
  88. package/dist/queries/selectDistinct.d.ts.map +1 -1
  89. package/dist/queries/selectDistinct.js +3 -14
  90. package/dist/queries/selectDistinct.js.map +1 -1
  91. package/dist/schema/build.d.ts +8 -4
  92. package/dist/schema/build.d.ts.map +1 -1
  93. package/dist/schema/build.js +161 -112
  94. package/dist/schema/build.js.map +1 -1
  95. package/dist/schema/traverseFields.d.ts +4 -6
  96. package/dist/schema/traverseFields.d.ts.map +1 -1
  97. package/dist/schema/traverseFields.js +103 -40
  98. package/dist/schema/traverseFields.js.map +1 -1
  99. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  100. package/dist/transactions/beginTransaction.js +4 -0
  101. package/dist/transactions/beginTransaction.js.map +1 -1
  102. package/dist/transform/read/index.d.ts +3 -1
  103. package/dist/transform/read/index.d.ts.map +1 -1
  104. package/dist/transform/read/index.js +2 -1
  105. package/dist/transform/read/index.js.map +1 -1
  106. package/dist/transform/read/relationship.d.ts.map +1 -1
  107. package/dist/transform/read/relationship.js +0 -4
  108. package/dist/transform/read/relationship.js.map +1 -1
  109. package/dist/transform/read/traverseFields.d.ts +6 -1
  110. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  111. package/dist/transform/read/traverseFields.js +69 -55
  112. package/dist/transform/read/traverseFields.js.map +1 -1
  113. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  114. package/dist/transform/write/traverseFields.js +20 -3
  115. package/dist/transform/write/traverseFields.js.map +1 -1
  116. package/dist/types.d.ts +3 -0
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/dist/update.d.ts.map +1 -1
  120. package/dist/update.js +1 -2
  121. package/dist/update.js.map +1 -1
  122. package/dist/upsertRow/index.d.ts +1 -1
  123. package/dist/upsertRow/index.d.ts.map +1 -1
  124. package/dist/upsertRow/index.js +3 -1
  125. package/dist/upsertRow/index.js.map +1 -1
  126. package/dist/upsertRow/types.d.ts +5 -0
  127. package/dist/upsertRow/types.d.ts.map +1 -1
  128. package/dist/upsertRow/types.js.map +1 -1
  129. package/package.json +12 -6
@@ -1 +1 @@
1
- {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AA+C/C,eAAO,MAAM,OAAO,EAAE,OAgDrB,CAAA"}
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AA+C/C,eAAO,MAAM,OAAO,EAAE,OAmDrB,CAAA"}
package/dist/connect.js CHANGED
@@ -47,11 +47,13 @@ export const connect = async function connect(options = {
47
47
  ...this.enums
48
48
  };
49
49
  try {
50
- this.pool = new pg.Pool(this.poolOptions);
51
- await connectWithReconnect({
52
- adapter: this,
53
- payload: this.payload
54
- });
50
+ if (!this.pool) {
51
+ this.pool = new pg.Pool(this.poolOptions);
52
+ await connectWithReconnect({
53
+ adapter: this,
54
+ payload: this.payload
55
+ });
56
+ }
55
57
  const logger = this.logger || false;
56
58
  this.drizzle = drizzle(this.pool, {
57
59
  logger,
@@ -69,11 +71,14 @@ export const connect = async function connect(options = {
69
71
  }
70
72
  } catch (err) {
71
73
  this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err);
74
+ if (typeof this.rejectInitializing === 'function') this.rejectInitializing();
72
75
  process.exit(1);
73
76
  }
74
77
  // Only push schema if not in production
75
- if (process.env.NODE_ENV === 'production' || process.env.PAYLOAD_MIGRATING === 'true' || this.push === false) return;
76
- await pushDevSchema(this);
78
+ if (process.env.NODE_ENV !== 'production' && process.env.PAYLOAD_MIGRATING !== 'true' && this.push !== false) {
79
+ await pushDevSchema(this);
80
+ }
81
+ if (typeof this.resolveInitializing === 'function') this.resolveInitializing();
77
82
  };
78
83
 
79
84
  //# sourceMappingURL=connect.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { Connect } from 'payload/database'\n\nimport { sql } from 'drizzle-orm'\nimport { drizzle } from 'drizzle-orm/node-postgres'\nimport pg from 'pg'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { pushDevSchema } from './utilities/pushDevSchema.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 (err) {\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 (err) {\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 ...this.tables,\n ...this.relations,\n ...this.enums,\n }\n\n try {\n this.pool = new pg.Pool(this.poolOptions)\n await connectWithReconnect({ adapter: this, payload: this.payload })\n\n const logger = this.logger || false\n\n this.drizzle = drizzle(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.drizzle.execute(\n sql.raw(`\n drop schema if exists ${this.schemaName || 'public'} cascade;\n create schema ${this.schemaName || 'public'};\n `),\n )\n this.payload.logger.info('---- DROPPED TABLES ----')\n }\n }\n } catch (err) {\n this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)\n process.exit(1)\n }\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 return\n\n await pushDevSchema(this)\n}\n"],"names":["sql","drizzle","pg","pushDevSchema","connectWithReconnect","adapter","payload","reconnect","result","pool","connect","err","setTimeout","logger","info","prependListener","code","options","hotReload","schema","tables","relations","enums","Pool","poolOptions","process","env","PAYLOAD_DROP_DATABASE","schemaName","execute","raw","error","message","exit","NODE_ENV","PAYLOAD_MIGRATING","push"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,OAAO,QAAQ,4BAA2B;AACnD,OAAOC,QAAQ,KAAI;AAInB,SAAS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AW;YACd,IAAIO,QAAQC,GAAG,CAACC,qBAAqB,KAAK,QAAQ;gBAChD,IAAI,CAACrB,OAAO,CAACO,MAAM,CAACC,IAAI,CAAC,CAAC,4BAA4B,EAAE,IAAI,CAACc,UAAU,IAAI,SAAS,MAAM,CAAC;gBAC3F,MAAM,IAAI,CAAC3B,OAAO,CAAC4B,OAAO,CACxB7B,IAAI8B,GAAG,CAAC,CAAC;gCACa,EAAE,IAAI,CAACF,UAAU,IAAI,SAAS;wBACtC,EAAE,IAAI,CAACA,UAAU,IAAI,SAAS;QAC9C,CAAC;gBAED,IAAI,CAACtB,OAAO,CAACO,MAAM,CAACC,IAAI,CAAC;YAC3B;QACF;IACF,EAAE,OAAOH,KAAK;QACZ,IAAI,CAACL,OAAO,CAACO,MAAM,CAACkB,KAAK,CAAC,CAAC,4CAA4C,EAAEpB,IAAIqB,OAAO,CAAC,CAAC,EAAErB;QACxFc,QAAQQ,IAAI,CAAC;IACf;IAEA,wCAAwC;IACxC,IACER,QAAQC,GAAG,CAACQ,QAAQ,KAAK,gBACzBT,QAAQC,GAAG,CAACS,iBAAiB,KAAK,UAClC,IAAI,CAACC,IAAI,KAAK,OAEd;IAEF,MAAMjC,cAAc,IAAI;AAC1B,EAAC"}
1
+ {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { Connect } from 'payload/database'\n\nimport { sql } from 'drizzle-orm'\nimport { drizzle } from 'drizzle-orm/node-postgres'\nimport pg from 'pg'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { pushDevSchema } from './utilities/pushDevSchema.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 (err) {\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 (err) {\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 ...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(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.drizzle.execute(\n sql.raw(`\n drop schema if exists ${this.schemaName || 'public'} cascade;\n create schema ${this.schemaName || 'public'};\n `),\n )\n this.payload.logger.info('---- DROPPED TABLES ----')\n }\n }\n } catch (err) {\n this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)\n if (typeof this.rejectInitializing === 'function') this.rejectInitializing()\n process.exit(1)\n }\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)\n }\n\n if (typeof this.resolveInitializing === 'function') this.resolveInitializing()\n}\n"],"names":["sql","drizzle","pg","pushDevSchema","connectWithReconnect","adapter","payload","reconnect","result","pool","connect","err","setTimeout","logger","info","prependListener","code","options","hotReload","schema","tables","relations","enums","Pool","poolOptions","process","env","PAYLOAD_DROP_DATABASE","schemaName","execute","raw","error","message","rejectInitializing","exit","NODE_ENV","PAYLOAD_MIGRATING","push","resolveInitializing"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAAA;AAY7C,eAAO,MAAM,KAAK,EAAE,KAiDnB,CAAA"}
1
+ {"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../src/count.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAY7C,eAAO,MAAM,KAAK,EAAE,KA0CnB,CAAA"}
package/dist/count.js CHANGED
@@ -7,7 +7,7 @@ export const count = async function count({ collection, locale, req, where: wher
7
7
  const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug));
8
8
  const db = this.sessions[req.transactionID]?.db || this.drizzle;
9
9
  const table = this.tables[tableName];
10
- const { joinAliases, joins, where } = await buildQuery({
10
+ const { joins, where } = await buildQuery({
11
11
  adapter: this,
12
12
  fields: collectionConfig.fields,
13
13
  locale,
@@ -15,15 +15,6 @@ export const count = async function count({ collection, locale, req, where: wher
15
15
  where: whereArg
16
16
  });
17
17
  const selectCountMethods = [];
18
- joinAliases.forEach(({ condition, table })=>{
19
- selectCountMethods.push({
20
- args: [
21
- table,
22
- condition
23
- ],
24
- method: 'leftJoin'
25
- });
26
- });
27
18
  Object.entries(joins).forEach(([joinTable, condition])=>{
28
19
  if (joinTable) {
29
20
  selectCountMethods.push({
package/dist/count.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/count.ts"],"sourcesContent":["import type { Count } from 'payload/database'\nimport type { SanitizedCollectionConfig } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { ChainedMethods } from './find/chainMethods.js'\nimport type { PostgresAdapter } from './types.js'\n\nimport { chainMethods } from './find/chainMethods.js'\nimport buildQuery from './queries/buildQuery.js'\n\nexport const count: Count = async function count(\n this: PostgresAdapter,\n { collection, locale, req, where: whereArg },\n) {\n const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config\n\n const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug))\n\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const table = this.tables[tableName]\n\n const { joinAliases, joins, where } = await buildQuery({\n adapter: this,\n fields: collectionConfig.fields,\n locale,\n tableName,\n where: whereArg,\n })\n\n const selectCountMethods: ChainedMethods = []\n\n joinAliases.forEach(({ condition, table }) => {\n selectCountMethods.push({\n args: [table, condition],\n method: 'leftJoin',\n })\n })\n\n Object.entries(joins).forEach(([joinTable, condition]) => {\n if (joinTable) {\n selectCountMethods.push({\n args: [this.tables[joinTable], condition],\n method: 'leftJoin',\n })\n }\n })\n\n const countResult = await chainMethods({\n methods: selectCountMethods,\n query: db\n .select({\n count: sql<number>`count\n (DISTINCT ${this.tables[tableName].id})`,\n })\n .from(table)\n .where(where),\n })\n\n return { totalDocs: Number(countResult[0].count) }\n}\n"],"names":["sql","toSnakeCase","chainMethods","buildQuery","count","collection","locale","req","where","whereArg","collectionConfig","payload","collections","config","tableName","tableNameMap","get","slug","db","sessions","transactionID","drizzle","table","tables","joinAliases","joins","adapter","fields","selectCountMethods","forEach","condition","push","args","method","Object","entries","joinTable","countResult","methods","query","select","id","from","totalDocs","Number"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACjC,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,gBAAgB,0BAAyB;AAEhD,OAAO,MAAMC,QAAe,eAAeA,MAEzC,EAAEC,UAAU,EAAEC,MAAM,EAAEC,GAAG,EAAEC,OAAOC,QAAQ,EAAE;IAE5C,MAAMC,mBAA8C,IAAI,CAACC,OAAO,CAACC,WAAW,CAACP,WAAW,CAACQ,MAAM;IAE/F,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAACf,YAAYS,iBAAiBO,IAAI;IAEzE,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACZ,IAAIa,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,QAAQ,IAAI,CAACC,MAAM,CAACT,UAAU;IAEpC,MAAM,EAAEU,WAAW,EAAEC,KAAK,EAAEjB,KAAK,EAAE,GAAG,MAAML,WAAW;QACrDuB,SAAS,IAAI;QACbC,QAAQjB,iBAAiBiB,MAAM;QAC/BrB;QACAQ;QACAN,OAAOC;IACT;IAEA,MAAMmB,qBAAqC,EAAE;IAE7CJ,YAAYK,OAAO,CAAC,CAAC,EAAEC,SAAS,EAAER,KAAK,EAAE;QACvCM,mBAAmBG,IAAI,CAAC;YACtBC,MAAM;gBAACV;gBAAOQ;aAAU;YACxBG,QAAQ;QACV;IACF;IAEAC,OAAOC,OAAO,CAACV,OAAOI,OAAO,CAAC,CAAC,CAACO,WAAWN,UAAU;QACnD,IAAIM,WAAW;YACbR,mBAAmBG,IAAI,CAAC;gBACtBC,MAAM;oBAAC,IAAI,CAACT,MAAM,CAACa,UAAU;oBAAEN;iBAAU;gBACzCG,QAAQ;YACV;QACF;IACF;IAEA,MAAMI,cAAc,MAAMnC,aAAa;QACrCoC,SAASV;QACTW,OAAOrB,GACJsB,MAAM,CAAC;YACNpC,OAAOJ,GAAW,CAAC;sBACL,EAAE,IAAI,CAACuB,MAAM,CAACT,UAAU,CAAC2B,EAAE,CAAC,CAAC,CAAC;QAC9C,GACCC,IAAI,CAACpB,OACLd,KAAK,CAACA;IACX;IAEA,OAAO;QAAEmC,WAAWC,OAAOP,WAAW,CAAC,EAAE,CAACjC,KAAK;IAAE;AACnD,EAAC"}
1
+ {"version":3,"sources":["../src/count.ts"],"sourcesContent":["import type { Count } from 'payload/database'\nimport type { SanitizedCollectionConfig } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { ChainedMethods } from './find/chainMethods.js'\nimport type { PostgresAdapter } from './types.js'\n\nimport { chainMethods } from './find/chainMethods.js'\nimport buildQuery from './queries/buildQuery.js'\n\nexport const count: Count = async function count(\n this: PostgresAdapter,\n { collection, locale, req, where: whereArg },\n) {\n const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config\n\n const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug))\n\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const table = this.tables[tableName]\n\n const { joins, where } = await buildQuery({\n adapter: this,\n fields: collectionConfig.fields,\n locale,\n tableName,\n where: whereArg,\n })\n\n const selectCountMethods: ChainedMethods = []\n\n Object.entries(joins).forEach(([joinTable, condition]) => {\n if (joinTable) {\n selectCountMethods.push({\n args: [this.tables[joinTable], condition],\n method: 'leftJoin',\n })\n }\n })\n\n const countResult = await chainMethods({\n methods: selectCountMethods,\n query: db\n .select({\n count: sql<number>`count\n (DISTINCT ${this.tables[tableName].id})`,\n })\n .from(table)\n .where(where),\n })\n\n return { totalDocs: Number(countResult[0].count) }\n}\n"],"names":["sql","toSnakeCase","chainMethods","buildQuery","count","collection","locale","req","where","whereArg","collectionConfig","payload","collections","config","tableName","tableNameMap","get","slug","db","sessions","transactionID","drizzle","table","tables","joins","adapter","fields","selectCountMethods","Object","entries","forEach","joinTable","condition","push","args","method","countResult","methods","query","select","id","from","totalDocs","Number"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACjC,OAAOC,iBAAiB,gBAAe;AAKvC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,gBAAgB,0BAAyB;AAEhD,OAAO,MAAMC,QAAe,eAAeA,MAEzC,EAAEC,UAAU,EAAEC,MAAM,EAAEC,GAAG,EAAEC,OAAOC,QAAQ,EAAE;IAE5C,MAAMC,mBAA8C,IAAI,CAACC,OAAO,CAACC,WAAW,CAACP,WAAW,CAACQ,MAAM;IAE/F,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAACf,YAAYS,iBAAiBO,IAAI;IAEzE,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACZ,IAAIa,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,QAAQ,IAAI,CAACC,MAAM,CAACT,UAAU;IAEpC,MAAM,EAAEU,KAAK,EAAEhB,KAAK,EAAE,GAAG,MAAML,WAAW;QACxCsB,SAAS,IAAI;QACbC,QAAQhB,iBAAiBgB,MAAM;QAC/BpB;QACAQ;QACAN,OAAOC;IACT;IAEA,MAAMkB,qBAAqC,EAAE;IAE7CC,OAAOC,OAAO,CAACL,OAAOM,OAAO,CAAC,CAAC,CAACC,WAAWC,UAAU;QACnD,IAAID,WAAW;YACbJ,mBAAmBM,IAAI,CAAC;gBACtBC,MAAM;oBAAC,IAAI,CAACX,MAAM,CAACQ,UAAU;oBAAEC;iBAAU;gBACzCG,QAAQ;YACV;QACF;IACF;IAEA,MAAMC,cAAc,MAAMlC,aAAa;QACrCmC,SAASV;QACTW,OAAOpB,GACJqB,MAAM,CAAC;YACNnC,OAAOJ,GAAW,CAAC;sBACL,EAAE,IAAI,CAACuB,MAAM,CAACT,UAAU,CAAC0B,EAAE,CAAC,CAAC,CAAC;QAC9C,GACCC,IAAI,CAACnB,OACLd,KAAK,CAACA;IACX;IAEA,OAAO;QAAEkC,WAAWC,OAAOP,WAAW,CAAC,EAAE,CAAChC,KAAK;IAAE;AACnD,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAqDvD,eAAO,MAAM,eAAe,EAAE,eA4E7B,CAAA"}
1
+ {"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,kBAAkB,CAAA;AA2C9E,eAAO,MAAM,eAAe,EAAE,eA6F7B,CAAA"}
@@ -1,21 +1,18 @@
1
1
  /* eslint-disable no-restricted-syntax, no-await-in-loop */ import fs from 'fs';
2
2
  import { createRequire } from 'module';
3
+ import path from 'path';
4
+ import { getPredefinedMigration } from 'payload/database';
3
5
  import prompts from 'prompts';
6
+ import { fileURLToPath } from 'url';
4
7
  const require = createRequire(import.meta.url);
5
- const migrationTemplate = (upSQL, downSQL)=>`import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
6
-
7
- export async function up({ payload }: MigrateUpArgs): Promise<void> {
8
- ${upSQL ? `await payload.db.drizzle.execute(sql\`
9
-
10
- ${upSQL}\`);
11
- ` : '// Migration code'}
8
+ const migrationTemplate = ({ downSQL, imports, upSQL })=>`import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
9
+ ${imports ? `${imports}\n` : ''}
10
+ export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
11
+ ${upSQL}
12
12
  };
13
13
 
14
- export async function down({ payload }: MigrateDownArgs): Promise<void> {
15
- ${downSQL ? `await payload.db.drizzle.execute(sql\`
16
-
17
- ${downSQL}\`);
18
- ` : '// Migration code'}
14
+ export async function down({ payload, req }: MigrateDownArgs): Promise<void> {
15
+ ${downSQL}
19
16
  };
20
17
  `;
21
18
  const getDefaultDrizzleSnapshot = ()=>({
@@ -32,47 +29,71 @@ const getDefaultDrizzleSnapshot = ()=>({
32
29
  tables: {},
33
30
  version: '5'
34
31
  });
35
- export const createMigration = async function createMigration({ forceAcceptWarning, migrationName, payload }) {
32
+ export const createMigration = async function createMigration({ file, forceAcceptWarning, migrationName, payload }) {
33
+ const filename = fileURLToPath(import.meta.url);
34
+ const dirname = path.dirname(filename);
36
35
  const dir = payload.db.migrationDir;
37
36
  if (!fs.existsSync(dir)) {
38
37
  fs.mkdirSync(dir);
39
38
  }
40
39
  const { generateDrizzleJson, generateMigration } = require('drizzle-kit/payload');
40
+ const drizzleJsonAfter = generateDrizzleJson(this.schema);
41
41
  const [yyymmdd, hhmmss] = new Date().toISOString().split('T');
42
42
  const formattedDate = yyymmdd.replace(/\D/g, '');
43
43
  const formattedTime = hhmmss.split('.')[0].replace(/\D/g, '');
44
+ let imports = '';
45
+ let downSQL;
46
+ let upSQL;
47
+ ({ downSQL, imports, upSQL } = await getPredefinedMigration({
48
+ dirname,
49
+ file,
50
+ migrationName,
51
+ payload
52
+ }));
44
53
  const timestamp = `${formattedDate}_${formattedTime}`;
45
- const fileName = migrationName ? `${timestamp}_${migrationName.replace(/\W/g, '_')}` : `${timestamp}`;
54
+ const name = migrationName || file?.split('/').slice(2).join('/');
55
+ const fileName = `${timestamp}${name ? `_${name.replace(/\W/g, '_')}` : ''}`;
46
56
  const filePath = `${dir}/${fileName}`;
47
57
  let drizzleJsonBefore = getDefaultDrizzleSnapshot();
48
- // Get latest migration snapshot
49
- const latestSnapshot = fs.readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()?.[0];
50
- if (latestSnapshot) {
51
- const latestSnapshotJSON = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'));
52
- drizzleJsonBefore = latestSnapshotJSON;
53
- }
54
- const drizzleJsonAfter = generateDrizzleJson(this.schema);
55
- const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter);
56
- const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore);
57
- if (!sqlStatementsUp.length && !sqlStatementsDown.length && !forceAcceptWarning) {
58
- const { confirm: shouldCreateBlankMigration } = await prompts({
59
- name: 'confirm',
60
- type: 'confirm',
61
- initial: false,
62
- message: 'No schema changes detected. Would you like to create a blank migration file?'
63
- }, {
64
- onCancel: ()=>{
58
+ if (!upSQL) {
59
+ // Get latest migration snapshot
60
+ const latestSnapshot = fs.readdirSync(dir).filter((file)=>file.endsWith('.json')).sort().reverse()?.[0];
61
+ if (latestSnapshot) {
62
+ drizzleJsonBefore = JSON.parse(fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'));
63
+ }
64
+ const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter);
65
+ const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore);
66
+ const sqlExecute = 'await payload.db.drizzle.execute(sql`';
67
+ if (sqlStatementsUp?.length) {
68
+ upSQL = `${sqlExecute}\n ${sqlStatementsUp?.join('\n')}\`)`;
69
+ }
70
+ if (sqlStatementsDown?.length) {
71
+ downSQL = `${sqlExecute}\n ${sqlStatementsDown?.join('\n')}\`)`;
72
+ }
73
+ if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {
74
+ const { confirm: shouldCreateBlankMigration } = await prompts({
75
+ name: 'confirm',
76
+ type: 'confirm',
77
+ initial: false,
78
+ message: 'No schema changes detected. Would you like to create a blank migration file?'
79
+ }, {
80
+ onCancel: ()=>{
81
+ process.exit(0);
82
+ }
83
+ });
84
+ if (!shouldCreateBlankMigration) {
65
85
  process.exit(0);
66
86
  }
67
- });
68
- if (!shouldCreateBlankMigration) {
69
- process.exit(0);
70
87
  }
88
+ // write schema
89
+ fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2));
71
90
  }
72
- // write schema
73
- fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2));
74
91
  // write migration
75
- fs.writeFileSync(`${filePath}.ts`, migrationTemplate(sqlStatementsUp.length ? sqlStatementsUp?.join('\n') : undefined, sqlStatementsDown.length ? sqlStatementsDown?.join('\n') : undefined));
92
+ fs.writeFileSync(`${filePath}.ts`, migrationTemplate({
93
+ downSQL: downSQL || ` // Migration code`,
94
+ imports,
95
+ upSQL: upSQL || ` // Migration code`
96
+ }));
76
97
  payload.logger.info({
77
98
  msg: `Migration created at ${filePath}.ts`
78
99
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["/* eslint-disable no-restricted-syntax, no-await-in-loop */\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/payload'\nimport type { CreateMigration } from 'payload/database'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport prompts from 'prompts'\n\nimport type { PostgresAdapter } from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst migrationTemplate = (\n upSQL?: string,\n downSQL?: string,\n) => `import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'\n\nexport async function up({ payload }: MigrateUpArgs): Promise<void> {\n${\n upSQL\n ? `await payload.db.drizzle.execute(sql\\`\n\n${upSQL}\\`);\n`\n : '// Migration code'\n}\n};\n\nexport async function down({ payload }: MigrateDownArgs): Promise<void> {\n${\n downSQL\n ? `await payload.db.drizzle.execute(sql\\`\n\n${downSQL}\\`);\n`\n : '// Migration code'\n}\n};\n`\n\nconst getDefaultDrizzleSnapshot = (): DrizzleSnapshotJSON => ({\n id: '00000000-0000-0000-0000-000000000000',\n _meta: {\n columns: {},\n schemas: {},\n tables: {},\n },\n dialect: 'pg',\n enums: {},\n prevId: '00000000-0000-0000-0000-00000000000',\n schemas: {},\n tables: {},\n version: '5',\n})\n\nexport const createMigration: CreateMigration = async function createMigration(\n this: PostgresAdapter,\n { forceAcceptWarning, migrationName, payload },\n) {\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n\n const { generateDrizzleJson, generateMigration } = require('drizzle-kit/payload')\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const fileName = migrationName\n ? `${timestamp}_${migrationName.replace(/\\W/g, '_')}`\n : `${timestamp}`\n\n const filePath = `${dir}/${fileName}`\n\n let drizzleJsonBefore = getDefaultDrizzleSnapshot()\n\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n const latestSnapshotJSON = JSON.parse(\n fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n\n drizzleJsonBefore = latestSnapshotJSON\n }\n\n const drizzleJsonAfter = generateDrizzleJson(this.schema)\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n\n if (!sqlStatementsUp.length && !sqlStatementsDown.length && !forceAcceptWarning) {\n const { confirm: shouldCreateBlankMigration } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n if (!shouldCreateBlankMigration) {\n process.exit(0)\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n\n // write migration\n fs.writeFileSync(\n `${filePath}.ts`,\n migrationTemplate(\n sqlStatementsUp.length ? sqlStatementsUp?.join('\\n') : undefined,\n sqlStatementsDown.length ? sqlStatementsDown?.join('\\n') : undefined,\n ),\n )\n payload.logger.info({ msg: `Migration created at ${filePath}.ts` })\n}\n"],"names":["fs","createRequire","prompts","require","url","migrationTemplate","upSQL","downSQL","getDefaultDrizzleSnapshot","id","_meta","columns","schemas","tables","dialect","enums","prevId","version","createMigration","forceAcceptWarning","migrationName","payload","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","fileName","filePath","drizzleJsonBefore","latestSnapshot","readdirSync","filter","file","endsWith","sort","reverse","latestSnapshotJSON","JSON","parse","readFileSync","drizzleJsonAfter","schema","sqlStatementsUp","sqlStatementsDown","length","confirm","shouldCreateBlankMigration","name","type","initial","message","onCancel","process","exit","writeFileSync","stringify","join","undefined","logger","info","msg"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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QAAQiD,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAEjC,SAAS,GAAG,CAAC;IAAC;AACnE,EAAC"}
1
+ {"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["/* eslint-disable no-restricted-syntax, no-await-in-loop */\nimport type { DrizzleSnapshotJSON } from 'drizzle-kit/payload'\nimport type { CreateMigration, MigrationTemplateArgs } from 'payload/database'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { getPredefinedMigration } from 'payload/database'\nimport prompts from 'prompts'\nimport { fileURLToPath } from 'url'\n\nimport type { PostgresAdapter } from './types.js'\n\nconst require = createRequire(import.meta.url)\n\nconst migrationTemplate = ({\n downSQL,\n imports,\n upSQL,\n}: MigrationTemplateArgs): string => `import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'\n${imports ? `${imports}\\n` : ''}\nexport async function up({ payload, req }: MigrateUpArgs): Promise<void> {\n${upSQL}\n};\n\nexport async function down({ payload, req }: MigrateDownArgs): Promise<void> {\n${downSQL}\n};\n`\n\nconst getDefaultDrizzleSnapshot = (): DrizzleSnapshotJSON => ({\n id: '00000000-0000-0000-0000-000000000000',\n _meta: {\n columns: {},\n schemas: {},\n tables: {},\n },\n dialect: 'pg',\n enums: {},\n prevId: '00000000-0000-0000-0000-00000000000',\n schemas: {},\n tables: {},\n version: '5',\n})\n\nexport const createMigration: CreateMigration = async function createMigration(\n this: PostgresAdapter,\n { file, forceAcceptWarning, migrationName, payload },\n) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const { generateDrizzleJson, generateMigration } = require('drizzle-kit/payload')\n const drizzleJsonAfter = generateDrizzleJson(this.schema)\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n const formattedDate = yyymmdd.replace(/\\D/g, '')\n const formattedTime = hhmmss.split('.')[0].replace(/\\D/g, '')\n let imports: string = ''\n let downSQL: string\n let upSQL: string\n ;({ downSQL, imports, upSQL } = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n }))\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const name = migrationName || file?.split('/').slice(2).join('/')\n const fileName = `${timestamp}${name ? `_${name.replace(/\\W/g, '_')}` : ''}`\n\n const filePath = `${dir}/${fileName}`\n\n let drizzleJsonBefore = getDefaultDrizzleSnapshot()\n\n if (!upSQL) {\n // Get latest migration snapshot\n const latestSnapshot = fs\n .readdirSync(dir)\n .filter((file) => file.endsWith('.json'))\n .sort()\n .reverse()?.[0]\n\n if (latestSnapshot) {\n drizzleJsonBefore = JSON.parse(\n fs.readFileSync(`${dir}/${latestSnapshot}`, 'utf8'),\n ) as DrizzleSnapshotJSON\n }\n\n const sqlStatementsUp = await generateMigration(drizzleJsonBefore, drizzleJsonAfter)\n const sqlStatementsDown = await generateMigration(drizzleJsonAfter, drizzleJsonBefore)\n const sqlExecute = 'await payload.db.drizzle.execute(sql`'\n\n if (sqlStatementsUp?.length) {\n upSQL = `${sqlExecute}\\n ${sqlStatementsUp?.join('\\n')}\\`)`\n }\n if (sqlStatementsDown?.length) {\n downSQL = `${sqlExecute}\\n ${sqlStatementsDown?.join('\\n')}\\`)`\n }\n\n if (!upSQL?.length && !downSQL?.length && !forceAcceptWarning) {\n const { confirm: shouldCreateBlankMigration } = await prompts(\n {\n name: 'confirm',\n type: 'confirm',\n initial: false,\n message: 'No schema changes detected. Would you like to create a blank migration file?',\n },\n {\n onCancel: () => {\n process.exit(0)\n },\n },\n )\n\n if (!shouldCreateBlankMigration) {\n process.exit(0)\n }\n }\n\n // write schema\n fs.writeFileSync(`${filePath}.json`, JSON.stringify(drizzleJsonAfter, null, 2))\n }\n\n // write migration\n fs.writeFileSync(\n `${filePath}.ts`,\n migrationTemplate({\n downSQL: downSQL || ` // Migration code`,\n imports,\n upSQL: upSQL || ` // Migration code`,\n }),\n )\n payload.logger.info({ msg: `Migration created at ${filePath}.ts` })\n}\n"],"names":["fs","createRequire","path","getPredefinedMigration","prompts","fileURLToPath","require","url","migrationTemplate","downSQL","imports","upSQL","getDefaultDrizzleSnapshot","id","_meta","columns","schemas","tables","dialect","enums","prevId","version","createMigration","file","forceAcceptWarning","migrationName","payload","filename","dirname","dir","db","migrationDir","existsSync","mkdirSync","generateDrizzleJson","generateMigration","drizzleJsonAfter","schema","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","name","slice","join","fileName","filePath","drizzleJsonBefore","latestSnapshot","readdirSync","filter","endsWith","sort","reverse","JSON","parse","readFileSync","sqlStatementsUp","sqlStatementsDown","sqlExecute","length","confirm","shouldCreateBlankMigration","type","initial","message","onCancel","process","exit","writeFileSync","stringify","logger","info","msg"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,yDAAyD,GAIzD,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,SAAQ;AACtC,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,QAAQ,mBAAkB;AACzD,OAAOC,aAAa,UAAS;AAC7B,SAASC,aAAa,QAAQ,MAAK;AAInC,MAAMC,UAAUL,cAAc,YAAYM,GAAG;AAE7C,MAAMC,oBAAoB,CAAC,EACzBC,OAAO,EACPC,OAAO,EACPC,KAAK,EACiB,GAAa,CAAC;AACtC,EAAED,UAAU,CAAC,EAAEA,QAAQ,EAAE,CAAC,GAAG,GAAG;;AAEhC,EAAEC,MAAM;;;;AAIR,EAAEF,QAAQ;;AAEV,CAAC;AAED,MAAMG,4BAA4B,IAA4B,CAAA;QAC5DC,IAAI;QACJC,OAAO;YACLC,SAAS,CAAC;YACVC,SAAS,CAAC;YACVC,QAAQ,CAAC;QACX;QACAC,SAAS;QACTC,OAAO,CAAC;QAC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A,WAAW,CAAC,mBAAmB,CAAC;QACzCC;QACAC,OAAOA,SAAS,CAAC,mBAAmB,CAAC;IACvC;IAEFe,QAAQkD,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAE3B,SAAS,GAAG,CAAC;IAAC;AACnE,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createVersion.d.ts","sourceRoot":"","sources":["../src/createVersion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAC1E,OAAO,KAAK,EAA0B,UAAU,EAAE,MAAM,eAAe,CAAA;AAMvE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIjD,wBAAsB,aAAa,CAAC,CAAC,SAAS,UAAU,EACtD,IAAI,EAAE,eAAe,EACrB,EACE,QAAQ,EACR,cAAc,EACd,MAAM,EACN,GAAkC,EAClC,WAAW,GACZ,EAAE,iBAAiB,CAAC,CAAC,CAAC,+BA4CxB"}
1
+ {"version":3,"file":"createVersion.d.ts","sourceRoot":"","sources":["../src/createVersion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAC1E,OAAO,KAAK,EAA0B,UAAU,EAAE,MAAM,eAAe,CAAA;AAMvE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIjD,wBAAsB,aAAa,CAAC,CAAC,SAAS,UAAU,EACtD,IAAI,EAAE,eAAe,EACrB,EACE,QAAQ,EACR,cAAc,EACd,MAAM,EACN,GAAkC,EAClC,WAAW,GACZ,EAAE,iBAAiB,CAAC,CAAC,CAAC,+BAsCxB"}
@@ -26,16 +26,12 @@ export async function createVersion({ autosave, collectionSlug, parent, req = {}
26
26
  tableName
27
27
  });
28
28
  const table = this.tables[tableName];
29
- const relationshipsTable = this.tables[`_${defaultTableName}${this.versionsSuffix}${this.relationshipsSuffix}`];
30
29
  if (collection.versions.drafts) {
31
30
  await db.execute(sql`
32
31
  UPDATE ${table}
33
32
  SET latest = false
34
- FROM ${relationshipsTable}
35
- WHERE ${table.id} = ${relationshipsTable.parent}
36
- AND ${relationshipsTable.path} = ${'parent'}
37
- AND ${relationshipsTable[`${collectionSlug}ID`]} = ${parent}
38
- AND ${table.id} != ${result.id};
33
+ WHERE ${table.id} != ${result.id}
34
+ AND ${table.parent} = ${parent}
39
35
  `);
40
36
  }
41
37
  return result;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import type { CreateVersionArgs, TypeWithVersion } from 'payload/database'\nimport type { PayloadRequestWithData, TypeWithID } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport { buildVersionCollectionFields } from 'payload/versions'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createVersion<T extends TypeWithID>(\n this: PostgresAdapter,\n {\n autosave,\n collectionSlug,\n parent,\n req = {} as PayloadRequestWithData,\n versionData,\n }: CreateVersionArgs<T>,\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const collection = this.payload.collections[collectionSlug].config\n const defaultTableName = toSnakeCase(collection.slug)\n\n const tableName = this.tableNameMap.get(`_${defaultTableName}${this.versionsSuffix}`)\n\n const version = { ...versionData }\n if (version.id) delete version.id\n\n const result = await upsertRow<TypeWithVersion<T>>({\n adapter: this,\n data: {\n autosave,\n latest: true,\n parent,\n version,\n },\n db,\n fields: buildVersionCollectionFields(collection),\n operation: 'create',\n req,\n tableName,\n })\n\n const table = this.tables[tableName]\n\n const relationshipsTable =\n this.tables[`_${defaultTableName}${this.versionsSuffix}${this.relationshipsSuffix}`]\n\n if (collection.versions.drafts) {\n await db.execute(sql`\n UPDATE ${table}\n SET latest = false\n FROM ${relationshipsTable}\n WHERE ${table.id} = ${relationshipsTable.parent}\n AND ${relationshipsTable.path} = ${'parent'}\n AND ${relationshipsTable[`${collectionSlug}ID`]} = ${parent}\n AND ${table.id} != ${result.id};\n `)\n }\n\n return result\n}\n"],"names":["sql","buildVersionCollectionFields","toSnakeCase","upsertRow","createVersion","autosave","collectionSlug","parent","req","versionData","db","sessions","transactionID","drizzle","collection","payload","collections","config","defaultTableName","slug","tableName","tableNameMap","get","versionsSuffix","version","id","result","adapter","data","latest","fields","operation","table","tables","relationshipsTable","relationshipsSuffix","versions","drafts","execute","path"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,4BAA4B,QAAQ,mBAAkB;AAC/D,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,cAEpB,EACEC,QAAQ,EACRC,cAAc,EACdC,MAAM,EACNC,MAAM,CAAC,CAA2B,EAClCC,WAAW,EACU;IAEvB,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACH,IAAII,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,aAAa,IAAI,CAACC,OAAO,CAACC,WAAW,CAACV,eAAe,CAACW,MAAM;IAClE,MAAMC,mBAAmBhB,YAAYY,WAAWK,IAAI;IAEpD,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAC,CAAC,CAAC,EAAEJ,iBAAiB,EAAE,IAAI,CAACK,cAAc,CAAC,CAAC;IAEpF,MAAMC,UAAU;QAAE,GAAGf,WAAW;IAAC;IACjC,IAAIe,QAAQC,EAAE,EAAE,OAAOD,QAAQC,EAAE;IAEjC,MAAMC,SAAS,MAAMvB,UAA8B;QACjDwB,SAAS,IAAI;QACbC,MAAM;YACJvB;YACAwB,QAAQ;YACRtB;YACAiB;QACF;QACAd;QACAoB,QAAQ7B,6BAA6Ba;QACrCiB,WAAW;QACXvB;QACAY;IACF;IAEA,MAAMY,QAAQ,IAAI,CAACC,MAAM,CAACb,UAAU;IAEpC,MAAMc,qBACJ,IAAI,CAACD,MAAM,CAAC,CAAC,CAAC,EAAEf,iBAAiB,EAAE,IAAI,CAACK,cAAc,CAAC,EAAE,IAAI,CAACY,mBAAmB,CAAC,CAAC,CAAC;IAEtF,IAAIrB,WAAWsB,QAAQ,CAACC,MAAM,EAAE;QAC9B,MAAM3B,GAAG4B,OAAO,CAACtC,GAAG,CAAC;aACZ,EAAEgC,MAAM;;WAEV,EAAEE,mBAAmB;YACpB,EAAEF,MAAMP,EAAE,CAAC,GAAG,EAAES,mBAAmB3B,MAAM,CAAC;YAC1C,EAAE2B,mBAAmBK,IAAI,CAAC,GAAG,EAAE,SAAS;YACxC,EAAEL,kBAAkB,CAAC,CAAC,EAAE5B,eAAe,EAAE,CAAC,CAAC,CAAC,GAAG,EAAEC,OAAO;YACxD,EAAEyB,MAAMP,EAAE,CAAC,IAAI,EAAEC,OAAOD,EAAE,CAAC;IACnC,CAAC;IACH;IAEA,OAAOC;AACT"}
1
+ {"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import type { CreateVersionArgs, TypeWithVersion } from 'payload/database'\nimport type { PayloadRequestWithData, TypeWithID } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport { buildVersionCollectionFields } from 'payload/versions'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createVersion<T extends TypeWithID>(\n this: PostgresAdapter,\n {\n autosave,\n collectionSlug,\n parent,\n req = {} as PayloadRequestWithData,\n versionData,\n }: CreateVersionArgs<T>,\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const collection = this.payload.collections[collectionSlug].config\n const defaultTableName = toSnakeCase(collection.slug)\n\n const tableName = this.tableNameMap.get(`_${defaultTableName}${this.versionsSuffix}`)\n\n const version = { ...versionData }\n if (version.id) delete version.id\n\n const result = await upsertRow<TypeWithVersion<T>>({\n adapter: this,\n data: {\n autosave,\n latest: true,\n parent,\n version,\n },\n db,\n fields: buildVersionCollectionFields(collection),\n operation: 'create',\n req,\n tableName,\n })\n\n const table = this.tables[tableName]\n\n if (collection.versions.drafts) {\n await db.execute(sql`\n UPDATE ${table}\n SET latest = false\n WHERE ${table.id} != ${result.id}\n AND ${table.parent} = ${parent}\n `)\n }\n\n return result\n}\n"],"names":["sql","buildVersionCollectionFields","toSnakeCase","upsertRow","createVersion","autosave","collectionSlug","parent","req","versionData","db","sessions","transactionID","drizzle","collection","payload","collections","config","defaultTableName","slug","tableName","tableNameMap","get","versionsSuffix","version","id","result","adapter","data","latest","fields","operation","table","tables","versions","drafts","execute"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,4BAA4B,QAAQ,mBAAkB;AAC/D,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,cAEpB,EACEC,QAAQ,EACRC,cAAc,EACdC,MAAM,EACNC,MAAM,CAAC,CAA2B,EAClCC,WAAW,EACU;IAEvB,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACH,IAAII,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,aAAa,IAAI,CAACC,OAAO,CAACC,WAAW,CAACV,eAAe,CAACW,MAAM;IAClE,MAAMC,mBAAmBhB,YAAYY,WAAWK,IAAI;IAEpD,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAC,CAAC,CAAC,EAAEJ,iBAAiB,EAAE,IAAI,CAACK,cAAc,CAAC,CAAC;IAEpF,MAAMC,UAAU;QAAE,GAAGf,WAAW;IAAC;IACjC,IAAIe,QAAQC,EAAE,EAAE,OAAOD,QAAQC,EAAE;IAEjC,MAAMC,SAAS,MAAMvB,UAA8B;QACjDwB,SAAS,IAAI;QACbC,MAAM;YACJvB;YACAwB,QAAQ;YACRtB;YACAiB;QACF;QACAd;QACAoB,QAAQ7B,6BAA6Ba;QACrCiB,WAAW;QACXvB;QACAY;IACF;IAEA,MAAMY,QAAQ,IAAI,CAACC,MAAM,CAACb,UAAU;IAEpC,IAAIN,WAAWoB,QAAQ,CAACC,MAAM,EAAE;QAC9B,MAAMzB,GAAG0B,OAAO,CAACpC,GAAG,CAAC;aACZ,EAAEgC,MAAM;;YAET,EAAEA,MAAMP,EAAE,CAAC,IAAI,EAAEC,OAAOD,EAAE,CAAC;YAC3B,EAAEO,MAAMzB,MAAM,CAAC,GAAG,EAAEA,OAAO;IACnC,CAAC;IACH;IAEA,OAAOmB;AACT"}
package/dist/deleteOne.js CHANGED
@@ -9,7 +9,7 @@ export const deleteOne = async function deleteOne({ collection: collectionSlug,
9
9
  const collection = this.payload.collections[collectionSlug].config;
10
10
  const tableName = this.tableNameMap.get(toSnakeCase(collection.slug));
11
11
  let docToDelete;
12
- const { joinAliases, joins, selectFields, where } = await buildQuery({
12
+ const { joins, selectFields, where } = await buildQuery({
13
13
  adapter: this,
14
14
  fields: collection.fields,
15
15
  locale: req.locale,
@@ -27,7 +27,6 @@ export const deleteOne = async function deleteOne({ collection: collectionSlug,
27
27
  }
28
28
  ],
29
29
  db,
30
- joinAliases,
31
30
  joins,
32
31
  selectFields,
33
32
  tableName,
@@ -48,6 +47,7 @@ export const deleteOne = async function deleteOne({ collection: collectionSlug,
48
47
  docToDelete = await db.query[tableName].findFirst(findManyArgs);
49
48
  }
50
49
  const result = transform({
50
+ adapter: this,
51
51
  config: this.payload.config,
52
52
  data: docToDelete,
53
53
  fields: collection.fields
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deleteOne.ts"],"sourcesContent":["import type { DeleteOne } from 'payload/database'\nimport type { PayloadRequestWithData } from 'payload/types'\n\nimport { eq } from 'drizzle-orm'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { buildFindManyArgs } from './find/buildFindManyArgs.js'\nimport buildQuery from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { transform } from './transform/read/index.js'\n\nexport const deleteOne: DeleteOne = async function deleteOne(\n this: PostgresAdapter,\n { collection: collectionSlug, req = {} as PayloadRequestWithData, where: whereArg },\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const collection = this.payload.collections[collectionSlug].config\n\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n\n let docToDelete: Record<string, unknown>\n\n const { joinAliases, joins, selectFields, where } = await buildQuery({\n adapter: this,\n fields: collection.fields,\n locale: req.locale,\n tableName,\n where: whereArg,\n })\n\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n chainedMethods: [{ args: [1], method: 'limit' }],\n db,\n joinAliases,\n joins,\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n docToDelete = await db.query[tableName].findFirst({\n where: eq(this.tables[tableName].id, selectDistinctResult[0].id),\n })\n } else {\n const findManyArgs = buildFindManyArgs({\n adapter: this,\n depth: 0,\n fields: collection.fields,\n tableName,\n })\n\n findManyArgs.where = where\n\n docToDelete = await db.query[tableName].findFirst(findManyArgs)\n }\n\n const result = transform({\n config: this.payload.config,\n data: docToDelete,\n fields: collection.fields,\n })\n\n await db.delete(this.tables[tableName]).where(eq(this.tables[tableName].id, docToDelete.id))\n\n return result\n}\n"],"names":["eq","toSnakeCase","buildFindManyArgs","buildQuery","selectDistinct","transform","deleteOne","collection","collectionSlug","req","where","whereArg","db","sessions","transactionID","drizzle","payload","collections","config","tableName","tableNameMap","get","slug","docToDelete","joinAliases","joins","selectFields","adapter","fields","locale","selectDistinctResult","chainedMethods","args","method","id","query","findFirst","tables","findManyArgs","depth","result","data","delete"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,EAAE,QAAQ,cAAa;AAChC,OA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qB,MAAM;YACzBT;QACF;QAEAmB,aAAa5B,KAAK,GAAGA;QAErBa,cAAc,MAAMX,GAAGuB,KAAK,CAAChB,UAAU,CAACiB,SAAS,CAACE;IACpD;IAEA,MAAME,SAASnC,UAAU;QACvBa,QAAQ,IAAI,CAACF,OAAO,CAACE,MAAM;QAC3BuB,MAAMlB;QACNK,QAAQrB,WAAWqB,MAAM;IAC3B;IAEA,MAAMhB,GAAG8B,MAAM,CAAC,IAAI,CAACL,MAAM,CAAClB,UAAU,EAAET,KAAK,CAACV,GAAG,IAAI,CAACqC,MAAM,CAAClB,UAAU,CAACe,EAAE,EAAEX,YAAYW,EAAE;IAE1F,OAAOM;AACT,EAAC"}
1
+ {"version":3,"sources":["../src/deleteOne.ts"],"sourcesContent":["import type { DeleteOne } from 'payload/database'\nimport type { PayloadRequestWithData } from 'payload/types'\n\nimport { eq } from 'drizzle-orm'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { buildFindManyArgs } from './find/buildFindManyArgs.js'\nimport buildQuery from './queries/buildQuery.js'\nimport { selectDistinct } from './queries/selectDistinct.js'\nimport { transform } from './transform/read/index.js'\n\nexport const deleteOne: DeleteOne = async function deleteOne(\n this: PostgresAdapter,\n { collection: collectionSlug, req = {} as PayloadRequestWithData, where: whereArg },\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const collection = this.payload.collections[collectionSlug].config\n\n const tableName = this.tableNameMap.get(toSnakeCase(collection.slug))\n\n let docToDelete: Record<string, unknown>\n\n const { joins, selectFields, where } = await buildQuery({\n adapter: this,\n fields: collection.fields,\n locale: req.locale,\n tableName,\n where: whereArg,\n })\n\n const selectDistinctResult = await selectDistinct({\n adapter: this,\n chainedMethods: [{ args: [1], method: 'limit' }],\n db,\n joins,\n selectFields,\n tableName,\n where,\n })\n\n if (selectDistinctResult?.[0]?.id) {\n docToDelete = await db.query[tableName].findFirst({\n where: eq(this.tables[tableName].id, selectDistinctResult[0].id),\n })\n } else {\n const findManyArgs = buildFindManyArgs({\n adapter: this,\n depth: 0,\n fields: collection.fields,\n tableName,\n })\n\n findManyArgs.where = where\n\n docToDelete = await db.query[tableName].findFirst(findManyArgs)\n }\n\n const result = transform({\n adapter: this,\n config: this.payload.config,\n data: docToDelete,\n fields: collection.fields,\n })\n\n await db.delete(this.tables[tableName]).where(eq(this.tables[tableName].id, docToDelete.id))\n\n return result\n}\n"],"names":["eq","toSnakeCase","buildFindManyArgs","buildQuery","selectDistinct","transform","deleteOne","collection","collectionSlug","req","where","whereArg","db","sessions","transactionID","drizzle","payload","collections","config","tableName","tableNameMap","get","slug","docToDelete","joins","selectFields","adapter","fields","locale","selectDistinctResult","chainedMethods","args","method","id","query","findFirst","tables","findManyArgs","depth","result","data","delete"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,EAAE,QAAQ,cAAa;AAChC,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,OAAOC,gBAAgB,0BAAyB;AAChD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,SAAS,QAAQ,4BAA2B;AAErD,OAAO,MAAMC,YAAuB,eAAeA,UAEjD,EAAEC,YAAYC,cAAc,EAAEC,MAAM,CAAC,CAA2B,EAAEC,OAAOC,QAAQ,EAAE;IAEnF,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACJ,IAAIK,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMR,aAAa,IAAI,CAACS,OAAO,CAACC,WAAW,CAACT,eAAe,CAACU,MAAM;IAElE,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAACpB,YAAYM,WAAWe,IAAI;IAEnE,IAAIC;IAEJ,MAAM,EAAEC,KAAK,EAAEC,YAAY,EAAEf,KAAK,EAAE,GAAG,MAAMP,WAAW;QACtDuB,SAAS,IAAI;QACbC,QAAQpB,WAAWoB,MAAM;QACzBC,QAAQnB,IAAImB,MAAM;QAClBT;QACAT,OAAOC;IACT;IAEA,MAAMkB,uBAAuB,MAAMzB,eAAe;QAChDsB,SAAS,IAAI;QACbI,gBAAgB;YAAC;gBAAEC,MAAM;oBAAC;iBAAE;gBAAEC,QAAQ;YAAQ;SAAE;QAChDpB;QACAY;QACAC;QACAN;QACAT;IACF;IAEA,IAAImB,sBAAsB,CAAC,EAAE,EAAEI,IAAI;QACjCV,cAAc,MAAMX,GAAGsB,KAAK,CAACf,UAAU,CAACgB,SAAS,CAAC;YAChDzB,OAAOV,GAAG,IAAI,CAACoC,MAAM,CAACjB,UAAU,CAACc,EAAE,EAAEJ,oBAAoB,CAAC,EAAE,CAACI,EAAE;QACjE;IACF,OAAO;QACL,MAAMI,eAAenC,kBAAkB;YACrCwB,SAAS,IAAI;YACbY,OAAO;YACPX,QAAQpB,WAAWoB,MAAM;YACzBR;QACF;QAEAkB,aAAa3B,KAAK,GAAGA;QAErBa,cAAc,MAAMX,GAAGsB,KAAK,CAACf,UAAU,CAACgB,SAAS,CAACE;IACpD;IAEA,MAAME,SAASlC,UAAU;QACvBqB,SAAS,IAAI;QACbR,QAAQ,IAAI,CAACF,OAAO,CAACE,MAAM;QAC3BsB,MAAMjB;QACNI,QAAQpB,WAAWoB,MAAM;IAC3B;IAEA,MAAMf,GAAG6B,MAAM,CAAC,IAAI,CAACL,MAAM,CAACjB,UAAU,EAAET,KAAK,CAACV,GAAG,IAAI,CAACoC,MAAM,CAACjB,UAAU,CAACc,EAAE,EAAEV,YAAYU,EAAE;IAE1F,OAAOM;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"destroy.d.ts","sourceRoot":"","sources":["../src/destroy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAK/C,eAAO,MAAM,OAAO,EAAE,OAOrB,CAAA"}
1
+ {"version":3,"file":"destroy.d.ts","sourceRoot":"","sources":["../src/destroy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAK/C,eAAO,MAAM,OAAO,EAAE,OAWrB,CAAA"}
package/dist/destroy.js CHANGED
@@ -6,6 +6,10 @@ export const destroy = async function destroy() {
6
6
  this.relations = {};
7
7
  this.fieldConstraints = {};
8
8
  this.drizzle = undefined;
9
+ this.initializing = new Promise((res, rej)=>{
10
+ this.resolveInitializing = res;
11
+ this.rejectInitializing = rej;
12
+ });
9
13
  };
10
14
 
11
15
  //# sourceMappingURL=destroy.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/destroy.ts"],"sourcesContent":["import type { Destroy } from 'payload/database'\n\nimport type { PostgresAdapter } from './types.js'\n\n// eslint-disable-next-line @typescript-eslint/require-await\nexport const destroy: Destroy = async function destroy(this: PostgresAdapter) {\n this.enums = {}\n this.schema = {}\n this.tables = {}\n this.relations = {}\n this.fieldConstraints = {}\n this.drizzle = undefined\n}\n"],"names":["destroy","enums","schema","tables","relations","fieldConstraints","drizzle","undefined"],"rangeMappings":";;;;;;;;","mappings":"AAIA,4DAA4D;AAC5D,OAAO,MAAMA,UAAmB,eAAeA;IAC7C,IAAI,CAACC,KAAK,GAAG,CAAC;IACd,IAAI,CAACC,MAAM,GAAG,CAAC;IACf,IAAI,CAACC,MAAM,GAAG,CAAC;IACf,IAAI,CAACC,SAAS,GAAG,CAAC;IAClB,IAAI,CAACC,gBAAgB,GAAG,CAAC;IACzB,IAAI,CAACC,OAAO,GAAGC;AACjB,EAAC"}
1
+ {"version":3,"sources":["../src/destroy.ts"],"sourcesContent":["import type { Destroy } from 'payload/database'\n\nimport type { PostgresAdapter } from './types.js'\n\n// eslint-disable-next-line @typescript-eslint/require-await\nexport const destroy: Destroy = async function destroy(this: PostgresAdapter) {\n this.enums = {}\n this.schema = {}\n this.tables = {}\n this.relations = {}\n this.fieldConstraints = {}\n this.drizzle = undefined\n this.initializing = new Promise((res, rej) => {\n this.resolveInitializing = res\n this.rejectInitializing = rej\n })\n}\n"],"names":["destroy","enums","schema","tables","relations","fieldConstraints","drizzle","undefined","initializing","Promise","res","rej","resolveInitializing","rejectInitializing"],"rangeMappings":";;;;;;;;;;;;","mappings":"AAIA,4DAA4D;AAC5D,OAAO,MAAMA,UAAmB,eAAeA;IAC7C,IAAI,CAACC,KAAK,GAAG,CAAC;IACd,IAAI,CAACC,MAAM,GAAG,CAAC;IACf,IAAI,CAACC,MAAM,GAAG,CAAC;IACf,IAAI,CAACC,SAAS,GAAG,CAAC;IAClB,IAAI,CAACC,gBAAgB,GAAG,CAAC;IACzB,IAAI,CAACC,OAAO,GAAGC;IACf,IAAI,CAACC,YAAY,GAAG,IAAIC,QAAQ,CAACC,KAAKC;QACpC,IAAI,CAACC,mBAAmB,GAAGF;QAC3B,IAAI,CAACG,kBAAkB,GAAGF;IAC5B;AACF,EAAC"}
@@ -0,0 +1,2 @@
1
+ export { migratePostgresV2toV3 } from '../predefinedMigrations/v2-v3/index.js';
2
+ //# sourceMappingURL=migration-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-utils.d.ts","sourceRoot":"","sources":["../../src/exports/migration-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAA"}
@@ -0,0 +1,3 @@
1
+ export { migratePostgresV2toV3 } from '../predefinedMigrations/v2-v3/index.js';
2
+
3
+ //# sourceMappingURL=migration-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/exports/migration-utils.ts"],"sourcesContent":["export { migratePostgresV2toV3 } from '../predefinedMigrations/v2-v3/index.js'\n"],"names":["migratePostgresV2toV3"],"rangeMappings":"","mappings":"AAAA,SAASA,qBAAqB,QAAQ,yCAAwC"}
@@ -7,7 +7,11 @@ type BuildFindQueryArgs = {
7
7
  fields: Field[];
8
8
  tableName: string;
9
9
  };
10
- export type Result = DBQueryConfig<'many', true, any, any>;
10
+ export type Result = DBQueryConfig<'many', true, any, any> & {
11
+ with?: DBQueryConfig<'many', true, any, any> & {
12
+ _locales?: DBQueryConfig<'many', true, any, any>;
13
+ };
14
+ };
11
15
  export declare const buildFindManyArgs: ({ adapter, depth, fields, tableName, }: BuildFindQueryArgs) => Record<string, unknown>;
12
16
  export {};
13
17
  //# sourceMappingURL=buildFindManyArgs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"buildFindManyArgs.d.ts","sourceRoot":"","sources":["../../src/find/buildFindManyArgs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAA;AAE1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAIlD,KAAK,kBAAkB,GAAG;IACxB,OAAO,EAAE,eAAe,CAAA;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AAI1D,eAAO,MAAM,iBAAiB,2CAK3B,kBAAkB,KAAG,OAAO,MAAM,EAAE,OAAO,CA2D7C,CAAA"}
1
+ {"version":3,"file":"buildFindManyArgs.d.ts","sourceRoot":"","sources":["../../src/find/buildFindManyArgs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAA;AAE1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAIlD,KAAK,kBAAkB,GAAG;IACxB,OAAO,EAAE,eAAe,CAAA;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG;IAC3D,IAAI,CAAC,EAAE,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG;QAC7C,QAAQ,CAAC,EAAE,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;KACjD,CAAA;CACF,CAAA;AAID,eAAO,MAAM,iBAAiB,2CAK3B,kBAAkB,KAAG,OAAO,MAAM,EAAE,OAAO,CA4D7C,CAAA"}
@@ -9,7 +9,8 @@ export const buildFindManyArgs = ({ adapter, depth, fields, tableName })=>{
9
9
  columns: {
10
10
  id: false,
11
11
  _parentID: false
12
- }
12
+ },
13
+ with: {}
13
14
  };
14
15
  if (adapter.tables[`${tableName}_texts`]) {
15
16
  result.with._texts = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { Field } from 'payload/types'\n\nimport type { PostgresAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: PostgresAdapter\n depth: number\n fields: Field[]\n tableName: string\n}\n\nexport type Result = DBQueryConfig<'many', true, any, any>\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n depth,\n fields,\n tableName,\n}: BuildFindQueryArgs): Record<string, unknown> => {\n const result: Result = {\n with: {},\n }\n\n const _locales: Result = {\n columns: {\n id: false,\n _parentID: false,\n },\n }\n\n if (adapter.tables[`${tableName}_texts`]) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`]) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`]) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.localesSuffix}`]) {\n result.with._locales = _locales\n }\n\n traverseFields({\n _locales,\n adapter,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n fields,\n path: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n })\n\n return result\n}\n"],"names":["traverseFields","buildFindManyArgs","adapter","depth","fields","tableName","result","with","_locales","columns","id","_parentID","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_rels","localesSuffix","currentArgs","currentTableName","path","topLevelArgs","topLevelTableName"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAKA,SAASA,cAAc,QAAQ,sBAAqB;AAWpD,mDAAmD;AACnD,+BAA+B;AAC/B,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,SAAS,EACU;IACnB,MAAMC,SAAiB;QACrBC,MAAM,CAAC;IACT;IAEA,MAAMC,WAAmB;QACvBC,SAAS;YACPC,IAAI;YACJC,WAAW;QACb;IACF;IAEA,IAAIT,QAAQU,MAAM,CAAC,CAAC,EAAEP,UAAU,MAAM,CAAC,CAAC,EAAE;QACxCC,OAAOC,IAAI,CAACM,MAAM,GAAG;YACnBJ,SAAS;gBACPC,IAAI;gBACJI,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IAAId,QAAQU,MAAM,CAAC,CAAC,EAAEP,UAAU,QAAQ,CAAC,CAAC,EAAE;QAC1CC,OAAOC,IAAI,CAACY,QAAQ,GAAG;YACrBV,SAAS;gBACPC,IAAI;gBACJI,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IAAId,QAAQU,MAAM,CAAC,CAAC,EAAEP,UAAU,EAAEH,QAAQkB,mBAAmB,CAAC,CAAC,CAAC,EAAE;QAChEd,OAAOC,IAAI,CAACc,KAAK,GAAG;YAClBZ,SAAS;gBACPC,IAAI;gBACJI,QAAQ;YACV;YACAC,SAAS,CAAC,EAAEC,KAAK,EAAE,EAAE,EAAEC,KAAKC,GAAG,EAAE,GAAK;oBAACA,IAAIF;iBAAO;QACpD;IACF;IAEA,IAAId,QAAQU,MAAM,CAAC,CAAC,EAAEP,UAAU,EAAEH,QAAQoB,aAAa,CAAC,CAAC,CAAC,EAAE;QAC1DhB,OAAOC,IAAI,CAACC,QAAQ,GAAGA;IACzB;IAEAR,eAAe;QACbQ;QACAN;QACAqB,aAAajB;QACbkB,kBAAkBnB;QAClBF;QACAC;QACAqB,MAAM;QACNC,cAAcpB;QACdqB,mBAAmBtB;IACrB;IAEA,OAAOC;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/find/buildFindManyArgs.ts"],"sourcesContent":["import type { DBQueryConfig } from 'drizzle-orm'\nimport type { Field } from 'payload/types'\n\nimport type { PostgresAdapter } from '../types.js'\n\nimport { traverseFields } from './traverseFields.js'\n\ntype BuildFindQueryArgs = {\n adapter: PostgresAdapter\n depth: number\n fields: Field[]\n tableName: string\n}\n\nexport type Result = DBQueryConfig<'many', true, any, any> & {\n with?: DBQueryConfig<'many', true, any, any> & {\n _locales?: DBQueryConfig<'many', true, any, any>\n }\n}\n\n// Generate the Drizzle query for findMany based on\n// a collection field structure\nexport const buildFindManyArgs = ({\n adapter,\n depth,\n fields,\n tableName,\n}: BuildFindQueryArgs): Record<string, unknown> => {\n const result: Result = {\n with: {},\n }\n\n const _locales: Result = {\n columns: {\n id: false,\n _parentID: false,\n },\n with: {},\n }\n\n if (adapter.tables[`${tableName}_texts`]) {\n result.with._texts = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}_numbers`]) {\n result.with._numbers = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.relationshipsSuffix}`]) {\n result.with._rels = {\n columns: {\n id: false,\n parent: false,\n },\n orderBy: ({ order }, { asc: ASC }) => [ASC(order)],\n }\n }\n\n if (adapter.tables[`${tableName}${adapter.localesSuffix}`]) {\n result.with._locales = _locales\n }\n\n traverseFields({\n _locales,\n adapter,\n currentArgs: result,\n currentTableName: tableName,\n depth,\n fields,\n path: '',\n topLevelArgs: result,\n topLevelTableName: tableName,\n })\n\n return result\n}\n"],"names":["traverseFields","buildFindManyArgs","adapter","depth","fields","tableName","result","with","_locales","columns","id","_parentID","tables","_texts","parent","orderBy","order","asc","ASC","_numbers","relationshipsSuffix","_rels","localesSuffix","currentArgs","currentTableName","path","topLevelArgs","topLevelTableName"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAKA,SAASA,cAAc,QAAQ,sBAAqB;AAepD,mDAAmD;AACnD,+BAA+B;AAC/B,OAAO,MAAMC,oBAAoB,CAAC,EAChCC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,SAAS,EACU;IACnB,MAAMC,SAAiB;QACrBC,MAAM,CAAC;IACT;IAEA,MAAMC,WAAmB;QACvBC,SAAS;YACPC,IAAI;YACJC,WAAW;QACb;QACAJ,MAAM,CAAC;IACT;IAEA,IAAIL,QAAQU,MAAM,CAAC,CAAC,EAAEP,UAAU,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,KAAK,EAAE,KAAK,EAAsC,MAAM,eAAe,CAAA;AAI9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AASlD,KAAK,IAAI,GAAG,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,GAAG;IACzC,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,QAAQ,iHAYlB,IAAI;;;;;;;;;;;EAgKN,CAAA"}
1
+ {"version":3,"file":"findMany.d.ts","sourceRoot":"","sources":["../../src/find/findMany.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAChD,OAAO,KAAK,EAAE,KAAK,EAAsC,MAAM,eAAe,CAAA;AAI9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AASlD,KAAK,IAAI,GAAG,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,GAAG;IACzC,OAAO,EAAE,eAAe,CAAA;IACxB,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,eAAO,MAAM,QAAQ,iHAYlB,IAAI;;;;;;;;;;;EAsJN,CAAA"}
@@ -13,7 +13,7 @@ export const findMany = async function find({ adapter, fields, limit: limitArg,
13
13
  let hasPrevPage;
14
14
  let hasNextPage;
15
15
  let pagingCounter;
16
- const { joinAliases, joins, orderBy, selectFields, where } = await buildQuery({
16
+ const { joins, orderBy, selectFields, where } = await buildQuery({
17
17
  adapter,
18
18
  fields,
19
19
  locale,
@@ -54,7 +54,6 @@ export const findMany = async function find({ adapter, fields, limit: limitArg,
54
54
  adapter,
55
55
  chainedMethods: selectDistinctMethods,
56
56
  db,
57
- joinAliases,
58
57
  joins,
59
58
  selectFields,
60
59
  tableName,
@@ -94,7 +93,7 @@ export const findMany = async function find({ adapter, fields, limit: limitArg,
94
93
  const findPromise = db.query[tableName].findMany(findManyArgs);
95
94
  if (pagination !== false && (orderedIDs ? orderedIDs?.length <= limit : true)) {
96
95
  const selectCountMethods = [];
97
- joinAliases.forEach(({ condition, table })=>{
96
+ joins.forEach(({ condition, table })=>{
98
97
  selectCountMethods.push({
99
98
  args: [
100
99
  table,
@@ -103,22 +102,11 @@ export const findMany = async function find({ adapter, fields, limit: limitArg,
103
102
  method: 'leftJoin'
104
103
  });
105
104
  });
106
- Object.entries(joins).forEach(([joinTable, condition])=>{
107
- if (joinTable) {
108
- selectCountMethods.push({
109
- args: [
110
- adapter.tables[joinTable],
111
- condition
112
- ],
113
- method: 'leftJoin'
114
- });
115
- }
116
- });
117
105
  const countResult = await chainMethods({
118
106
  methods: selectCountMethods,
119
107
  query: db.select({
120
108
  count: sql`count
121
- (DISTINCT ${adapter.tables[tableName].id})`
109
+ (DISTINCT ${adapter.tables[tableName].id})`
122
110
  }).from(table).where(where)
123
111
  });
124
112
  totalDocs = Number(countResult[0].count);
@@ -141,6 +129,7 @@ export const findMany = async function find({ adapter, fields, limit: limitArg,
141
129
  }
142
130
  const docs = rawDocs.map((data)=>{
143
131
  return transform({
132
+ adapter,
144
133
  config: adapter.payload.config,
145
134
  data,
146
135
  fields