@payloadcms/db-postgres 3.0.0-beta.6 → 3.0.0-beta.60

Sign up to get free protection for your applications and to get access to all the features.
Files changed (303) hide show
  1. package/README.md +1 -1
  2. package/dist/connect.d.ts +1 -1
  3. package/dist/connect.d.ts.map +1 -1
  4. package/dist/connect.js +12 -7
  5. package/dist/connect.js.map +1 -1
  6. package/dist/count.d.ts +3 -0
  7. package/dist/count.d.ts.map +1 -0
  8. package/dist/count.js +41 -0
  9. package/dist/count.js.map +1 -0
  10. package/dist/create.d.ts +1 -1
  11. package/dist/create.d.ts.map +1 -1
  12. package/dist/create.js +4 -6
  13. package/dist/create.js.map +1 -1
  14. package/dist/createGlobal.d.ts +2 -3
  15. package/dist/createGlobal.d.ts.map +1 -1
  16. package/dist/createGlobal.js +4 -6
  17. package/dist/createGlobal.js.map +1 -1
  18. package/dist/createGlobalVersion.d.ts +1 -3
  19. package/dist/createGlobalVersion.d.ts.map +1 -1
  20. package/dist/createGlobalVersion.js +4 -8
  21. package/dist/createGlobalVersion.js.map +1 -1
  22. package/dist/createMigration.d.ts +1 -1
  23. package/dist/createMigration.d.ts.map +1 -1
  24. package/dist/createMigration.js +56 -35
  25. package/dist/createMigration.js.map +1 -1
  26. package/dist/createVersion.d.ts +1 -2
  27. package/dist/createVersion.d.ts.map +1 -1
  28. package/dist/createVersion.js +12 -20
  29. package/dist/createVersion.js.map +1 -1
  30. package/dist/deleteMany.d.ts +1 -1
  31. package/dist/deleteMany.d.ts.map +1 -1
  32. package/dist/deleteMany.js +3 -6
  33. package/dist/deleteMany.js.map +1 -1
  34. package/dist/deleteOne.d.ts +1 -1
  35. package/dist/deleteOne.d.ts.map +1 -1
  36. package/dist/deleteOne.js +5 -8
  37. package/dist/deleteOne.js.map +1 -1
  38. package/dist/deleteVersions.d.ts +1 -1
  39. package/dist/deleteVersions.d.ts.map +1 -1
  40. package/dist/deleteVersions.js +4 -8
  41. package/dist/deleteVersions.js.map +1 -1
  42. package/dist/destroy.d.ts +1 -1
  43. package/dist/destroy.d.ts.map +1 -1
  44. package/dist/destroy.js +11 -7
  45. package/dist/destroy.js.map +1 -1
  46. package/dist/exports/migration-utils.d.ts +2 -0
  47. package/dist/exports/migration-utils.d.ts.map +1 -0
  48. package/dist/exports/migration-utils.js +3 -0
  49. package/dist/exports/migration-utils.js.map +1 -0
  50. package/dist/find/buildFindManyArgs.d.ts +6 -2
  51. package/dist/find/buildFindManyArgs.d.ts.map +1 -1
  52. package/dist/find/buildFindManyArgs.js +4 -3
  53. package/dist/find/buildFindManyArgs.js.map +1 -1
  54. package/dist/find/chainMethods.d.ts.map +1 -1
  55. package/dist/find/chainMethods.js.map +1 -1
  56. package/dist/find/findMany.d.ts +1 -2
  57. package/dist/find/findMany.d.ts.map +1 -1
  58. package/dist/find/findMany.js +6 -17
  59. package/dist/find/findMany.js.map +1 -1
  60. package/dist/find/traverseFields.d.ts +4 -3
  61. package/dist/find/traverseFields.d.ts.map +1 -1
  62. package/dist/find/traverseFields.js +27 -25
  63. package/dist/find/traverseFields.js.map +1 -1
  64. package/dist/find.d.ts +1 -1
  65. package/dist/find.d.ts.map +1 -1
  66. package/dist/find.js +2 -5
  67. package/dist/find.js.map +1 -1
  68. package/dist/findGlobal.d.ts +1 -1
  69. package/dist/findGlobal.d.ts.map +1 -1
  70. package/dist/findGlobal.js +2 -5
  71. package/dist/findGlobal.js.map +1 -1
  72. package/dist/findGlobalVersions.d.ts +1 -1
  73. package/dist/findGlobalVersions.d.ts.map +1 -1
  74. package/dist/findGlobalVersions.js +3 -7
  75. package/dist/findGlobalVersions.js.map +1 -1
  76. package/dist/findOne.d.ts +1 -2
  77. package/dist/findOne.d.ts.map +1 -1
  78. package/dist/findOne.js +2 -5
  79. package/dist/findOne.js.map +1 -1
  80. package/dist/findVersions.d.ts +1 -1
  81. package/dist/findVersions.d.ts.map +1 -1
  82. package/dist/findVersions.js +3 -7
  83. package/dist/findVersions.js.map +1 -1
  84. package/dist/index.d.ts +1 -1
  85. package/dist/index.d.ts.map +1 -1
  86. package/dist/index.js +18 -9
  87. package/dist/index.js.map +1 -1
  88. package/dist/init.d.ts +1 -1
  89. package/dist/init.d.ts.map +1 -1
  90. package/dist/init.js +20 -23
  91. package/dist/init.js.map +1 -1
  92. package/dist/migrate.d.ts.map +1 -1
  93. package/dist/migrate.js +1 -1
  94. package/dist/migrate.js.map +1 -1
  95. package/dist/migrateDown.js +1 -1
  96. package/dist/migrateDown.js.map +1 -1
  97. package/dist/migrateFresh.d.ts.map +1 -1
  98. package/dist/migrateFresh.js +1 -1
  99. package/dist/migrateFresh.js.map +1 -1
  100. package/dist/migrateRefresh.js +1 -1
  101. package/dist/migrateRefresh.js.map +1 -1
  102. package/dist/migrateReset.js +1 -1
  103. package/dist/migrateReset.js.map +1 -1
  104. package/dist/migrateStatus.js +1 -1
  105. package/dist/migrateStatus.js.map +1 -1
  106. package/dist/predefinedMigrations/relationships-v2-v3.d.ts +4 -0
  107. package/dist/predefinedMigrations/relationships-v2-v3.d.ts.map +1 -0
  108. package/dist/predefinedMigrations/relationships-v2-v3.js.map +1 -0
  109. package/dist/predefinedMigrations/relationships-v2-v3.mjs +11 -0
  110. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts +19 -0
  111. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.d.ts.map +1 -0
  112. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js +169 -0
  113. package/dist/predefinedMigrations/v2-v3/fetchAndResave/index.js.map +1 -0
  114. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts +11 -0
  115. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.d.ts.map +1 -0
  116. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js +191 -0
  117. package/dist/predefinedMigrations/v2-v3/fetchAndResave/traverseFields.js.map +1 -0
  118. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts +3 -0
  119. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.d.ts.map +1 -0
  120. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js +56 -0
  121. package/dist/predefinedMigrations/v2-v3/groupUpSQLStatements.js.map +1 -0
  122. package/dist/predefinedMigrations/v2-v3/index.d.ts +23 -0
  123. package/dist/predefinedMigrations/v2-v3/index.d.ts.map +1 -0
  124. package/dist/predefinedMigrations/v2-v3/index.js +211 -0
  125. package/dist/predefinedMigrations/v2-v3/index.js.map +1 -0
  126. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts +19 -0
  127. package/dist/predefinedMigrations/v2-v3/migrateRelationships.d.ts.map +1 -0
  128. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js +57 -0
  129. package/dist/predefinedMigrations/v2-v3/migrateRelationships.js.map +1 -0
  130. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts +22 -0
  131. package/dist/predefinedMigrations/v2-v3/traverseFields.d.ts.map +1 -0
  132. package/dist/predefinedMigrations/v2-v3/traverseFields.js +85 -0
  133. package/dist/predefinedMigrations/v2-v3/traverseFields.js.map +1 -0
  134. package/dist/predefinedMigrations/v2-v3/types.d.ts +9 -0
  135. package/dist/predefinedMigrations/v2-v3/types.d.ts.map +1 -0
  136. package/dist/predefinedMigrations/v2-v3/types.js +6 -0
  137. package/dist/predefinedMigrations/v2-v3/types.js.map +1 -0
  138. package/dist/queries/buildAndOrConditions.d.ts +4 -5
  139. package/dist/queries/buildAndOrConditions.d.ts.map +1 -1
  140. package/dist/queries/buildAndOrConditions.js +1 -2
  141. package/dist/queries/buildAndOrConditions.js.map +1 -1
  142. package/dist/queries/buildQuery.d.ts +2 -3
  143. package/dist/queries/buildQuery.d.ts.map +1 -1
  144. package/dist/queries/buildQuery.js +1 -5
  145. package/dist/queries/buildQuery.js.map +1 -1
  146. package/dist/queries/createJSONQuery/convertPathToJSONTraversal.js.map +1 -1
  147. package/dist/queries/createJSONQuery/formatJSONPathSegment.js.map +1 -1
  148. package/dist/queries/createJSONQuery/index.js.map +1 -1
  149. package/dist/queries/getTableColumnFromPath.d.ts +4 -5
  150. package/dist/queries/getTableColumnFromPath.d.ts.map +1 -1
  151. package/dist/queries/getTableColumnFromPath.js +250 -146
  152. package/dist/queries/getTableColumnFromPath.js.map +1 -1
  153. package/dist/queries/operatorMap.js.map +1 -1
  154. package/dist/queries/parseParams.d.ts +4 -5
  155. package/dist/queries/parseParams.d.ts.map +1 -1
  156. package/dist/queries/parseParams.js +9 -8
  157. package/dist/queries/parseParams.js.map +1 -1
  158. package/dist/queries/sanitizeQueryValue.d.ts +1 -1
  159. package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
  160. package/dist/queries/sanitizeQueryValue.js +2 -3
  161. package/dist/queries/sanitizeQueryValue.js.map +1 -1
  162. package/dist/queries/selectDistinct.d.ts +3 -4
  163. package/dist/queries/selectDistinct.d.ts.map +1 -1
  164. package/dist/queries/selectDistinct.js +3 -14
  165. package/dist/queries/selectDistinct.js.map +1 -1
  166. package/dist/queryDrafts.d.ts +1 -1
  167. package/dist/queryDrafts.d.ts.map +1 -1
  168. package/dist/queryDrafts.js +3 -8
  169. package/dist/queryDrafts.js.map +1 -1
  170. package/dist/schema/build.d.ts +12 -7
  171. package/dist/schema/build.d.ts.map +1 -1
  172. package/dist/schema/build.js +208 -124
  173. package/dist/schema/build.js.map +1 -1
  174. package/dist/schema/createIndex.js.map +1 -1
  175. package/dist/schema/{getTableName.d.ts → createTableName.d.ts} +6 -8
  176. package/dist/schema/createTableName.d.ts.map +1 -0
  177. package/dist/schema/createTableName.js +31 -0
  178. package/dist/schema/createTableName.js.map +1 -0
  179. package/dist/schema/idToUUID.d.ts +1 -1
  180. package/dist/schema/idToUUID.d.ts.map +1 -1
  181. package/dist/schema/idToUUID.js.map +1 -1
  182. package/dist/schema/parentIDColumnMap.js.map +1 -1
  183. package/dist/schema/setColumnID.d.ts +1 -1
  184. package/dist/schema/setColumnID.d.ts.map +1 -1
  185. package/dist/schema/setColumnID.js +2 -2
  186. package/dist/schema/setColumnID.js.map +1 -1
  187. package/dist/schema/traverseFields.d.ts +5 -7
  188. package/dist/schema/traverseFields.d.ts.map +1 -1
  189. package/dist/schema/traverseFields.js +147 -63
  190. package/dist/schema/traverseFields.js.map +1 -1
  191. package/dist/schema/validateExistingBlockIsIdentical.d.ts +3 -2
  192. package/dist/schema/validateExistingBlockIsIdentical.d.ts.map +1 -1
  193. package/dist/schema/validateExistingBlockIsIdentical.js +15 -9
  194. package/dist/schema/validateExistingBlockIsIdentical.js.map +1 -1
  195. package/dist/transactions/beginTransaction.d.ts +1 -1
  196. package/dist/transactions/beginTransaction.d.ts.map +1 -1
  197. package/dist/transactions/beginTransaction.js +4 -0
  198. package/dist/transactions/beginTransaction.js.map +1 -1
  199. package/dist/transactions/commitTransaction.d.ts +1 -1
  200. package/dist/transactions/commitTransaction.d.ts.map +1 -1
  201. package/dist/transactions/commitTransaction.js +1 -0
  202. package/dist/transactions/commitTransaction.js.map +1 -1
  203. package/dist/transactions/rollbackTransaction.d.ts +1 -1
  204. package/dist/transactions/rollbackTransaction.d.ts.map +1 -1
  205. package/dist/transactions/rollbackTransaction.js +5 -4
  206. package/dist/transactions/rollbackTransaction.js.map +1 -1
  207. package/dist/transform/read/hasManyNumber.d.ts +1 -1
  208. package/dist/transform/read/hasManyNumber.d.ts.map +1 -1
  209. package/dist/transform/read/hasManyNumber.js.map +1 -1
  210. package/dist/transform/read/hasManyText.d.ts +1 -1
  211. package/dist/transform/read/hasManyText.d.ts.map +1 -1
  212. package/dist/transform/read/hasManyText.js.map +1 -1
  213. package/dist/transform/read/index.d.ts +4 -3
  214. package/dist/transform/read/index.d.ts.map +1 -1
  215. package/dist/transform/read/index.js +2 -1
  216. package/dist/transform/read/index.js.map +1 -1
  217. package/dist/transform/read/relationship.d.ts +1 -1
  218. package/dist/transform/read/relationship.d.ts.map +1 -1
  219. package/dist/transform/read/relationship.js +0 -4
  220. package/dist/transform/read/relationship.js.map +1 -1
  221. package/dist/transform/read/traverseFields.d.ts +8 -3
  222. package/dist/transform/read/traverseFields.d.ts.map +1 -1
  223. package/dist/transform/read/traverseFields.js +70 -56
  224. package/dist/transform/read/traverseFields.js.map +1 -1
  225. package/dist/transform/write/array.d.ts +1 -1
  226. package/dist/transform/write/array.d.ts.map +1 -1
  227. package/dist/transform/write/array.js.map +1 -1
  228. package/dist/transform/write/blocks.d.ts +1 -1
  229. package/dist/transform/write/blocks.d.ts.map +1 -1
  230. package/dist/transform/write/blocks.js +1 -1
  231. package/dist/transform/write/blocks.js.map +1 -1
  232. package/dist/transform/write/index.d.ts +1 -1
  233. package/dist/transform/write/index.d.ts.map +1 -1
  234. package/dist/transform/write/index.js.map +1 -1
  235. package/dist/transform/write/numbers.js.map +1 -1
  236. package/dist/transform/write/relationships.d.ts +1 -1
  237. package/dist/transform/write/relationships.d.ts.map +1 -1
  238. package/dist/transform/write/relationships.js +1 -1
  239. package/dist/transform/write/relationships.js.map +1 -1
  240. package/dist/transform/write/selects.js.map +1 -1
  241. package/dist/transform/write/texts.js.map +1 -1
  242. package/dist/transform/write/traverseFields.d.ts +1 -1
  243. package/dist/transform/write/traverseFields.d.ts.map +1 -1
  244. package/dist/transform/write/traverseFields.js +23 -6
  245. package/dist/transform/write/traverseFields.js.map +1 -1
  246. package/dist/transform/write/types.js.map +1 -1
  247. package/dist/types.d.ts +5 -7
  248. package/dist/types.d.ts.map +1 -1
  249. package/dist/types.js.map +1 -1
  250. package/dist/update.d.ts +1 -1
  251. package/dist/update.d.ts.map +1 -1
  252. package/dist/update.js +4 -8
  253. package/dist/update.js.map +1 -1
  254. package/dist/updateGlobal.d.ts +2 -3
  255. package/dist/updateGlobal.d.ts.map +1 -1
  256. package/dist/updateGlobal.js +3 -6
  257. package/dist/updateGlobal.js.map +1 -1
  258. package/dist/updateGlobalVersion.d.ts +1 -2
  259. package/dist/updateGlobalVersion.d.ts.map +1 -1
  260. package/dist/updateGlobalVersion.js +4 -8
  261. package/dist/updateGlobalVersion.js.map +1 -1
  262. package/dist/updateVersion.d.ts +1 -2
  263. package/dist/updateVersion.d.ts.map +1 -1
  264. package/dist/updateVersion.js +4 -8
  265. package/dist/updateVersion.js.map +1 -1
  266. package/dist/upsertRow/deleteExistingArrayRows.d.ts.map +1 -1
  267. package/dist/upsertRow/deleteExistingArrayRows.js.map +1 -1
  268. package/dist/upsertRow/deleteExistingRowsByPath.d.ts.map +1 -1
  269. package/dist/upsertRow/deleteExistingRowsByPath.js.map +1 -1
  270. package/dist/upsertRow/index.d.ts +2 -2
  271. package/dist/upsertRow/index.d.ts.map +1 -1
  272. package/dist/upsertRow/index.js +18 -13
  273. package/dist/upsertRow/index.js.map +1 -1
  274. package/dist/upsertRow/insertArrays.d.ts.map +1 -1
  275. package/dist/upsertRow/insertArrays.js +3 -3
  276. package/dist/upsertRow/insertArrays.js.map +1 -1
  277. package/dist/upsertRow/types.d.ts +6 -1
  278. package/dist/upsertRow/types.d.ts.map +1 -1
  279. package/dist/upsertRow/types.js.map +1 -1
  280. package/dist/utilities/appendPrefixToKeys.d.ts.map +1 -1
  281. package/dist/utilities/appendPrefixToKeys.js.map +1 -1
  282. package/dist/utilities/createBlocksMap.d.ts.map +1 -1
  283. package/dist/utilities/createBlocksMap.js.map +1 -1
  284. package/dist/utilities/createMigrationTable.d.ts.map +1 -1
  285. package/dist/utilities/createMigrationTable.js.map +1 -1
  286. package/dist/utilities/createRelationshipMap.d.ts.map +1 -1
  287. package/dist/utilities/createRelationshipMap.js.map +1 -1
  288. package/dist/utilities/hasLocalesTable.d.ts +1 -1
  289. package/dist/utilities/hasLocalesTable.d.ts.map +1 -1
  290. package/dist/utilities/hasLocalesTable.js +1 -1
  291. package/dist/utilities/hasLocalesTable.js.map +1 -1
  292. package/dist/utilities/isArrayOfRows.js.map +1 -1
  293. package/dist/utilities/migrationTableExists.d.ts.map +1 -1
  294. package/dist/utilities/migrationTableExists.js.map +1 -1
  295. package/dist/utilities/parseError.js.map +1 -1
  296. package/dist/utilities/pushDevSchema.d.ts.map +1 -1
  297. package/dist/utilities/pushDevSchema.js +1 -1
  298. package/dist/utilities/pushDevSchema.js.map +1 -1
  299. package/package.json +34 -29
  300. package/dist/schema/getTableName.d.ts.map +0 -1
  301. package/dist/schema/getTableName.js +0 -31
  302. package/dist/schema/getTableName.js.map +0 -1
  303. package/src/index.ts +0 -156
package/README.md CHANGED
@@ -14,7 +14,7 @@ npm install @payloadcms/db-postgres
14
14
  ## Usage
15
15
 
16
16
  ```ts
17
- import { buildConfig } from 'payload/config'
17
+ import { buildConfig } from 'payload'
18
18
  import { postgresAdapter } from '@payloadcms/db-postgres'
19
19
 
20
20
  export default buildConfig({
package/dist/connect.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import type { Connect } from 'payload/database';
1
+ import type { Connect } from 'payload';
2
2
  export declare const connect: Connect;
3
3
  //# sourceMappingURL=connect.d.ts.map
@@ -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":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAW,MAAM,SAAS,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,SAASC,aAAa,QAAQ,+BAA8B;AAE5D,MAAMC,uBAAuB,eAAgB,EAC3CC,OAAO,EACPC,OAAO,EACPC,YAAY,KAAK,EAKlB;IACC,IAAIC;IAEJ,IAAI,CAACD,WAAW;QACdC,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;IACrC,OAAO;QACL,IAAI;YACFF,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;QACrC,EAAE,OAAOC,KAAK;YACZC,WAAW;gBACTN,QAAQO,MAAM,CAACC,IA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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 { Connect, Payload } from 'payload'\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"],"mappings":"AAEA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,OAAO,QAAQ,4BAA2B;AACnD,OAAOC,QAAQ,KAAI;AAInB,SAASC,aAAa,QAAQ,+BAA8B;AAE5D,MAAMC,uBAAuB,eAAgB,EAC3CC,OAAO,EACPC,OAAO,EACPC,YAAY,KAAK,EAKlB;IACC,IAAIC;IAEJ,IAAI,CAACD,WAAW;QACdC,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;IACrC,OAAO;QACL,IAAI;YACFF,SAAS,MAAMH,QAAQI,IAAI,CAACC,OAAO;QACrC,EAAE,OAAOC,KAAK;YACZC,WAAW;gBACTN,QAAQO,MAAM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ACa,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;QACxF,IAAI,OAAO,IAAI,CAACsB,kBAAkB,KAAK,YAAY,IAAI,CAACA,kBAAkB;QAC1ER,QAAQS,IAAI,CAAC;IACf;IAEA,wCAAwC;IACxC,IACET,QAAQC,GAAG,CAACS,QAAQ,KAAK,gBACzBV,QAAQC,GAAG,CAACU,iBAAiB,KAAK,UAClC,IAAI,CAACC,IAAI,KAAK,OACd;QACA,MAAMlC,cAAc,IAAI;IAC1B;IAEA,IAAI,OAAO,IAAI,CAACmC,mBAAmB,KAAK,YAAY,IAAI,CAACA,mBAAmB;AAC9E,EAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Count } from 'payload';
2
+ export declare const count: Count;
3
+ //# sourceMappingURL=count.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"count.d.ts","sourceRoot":"","sources":["../src/count.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAA6B,MAAM,SAAS,CAAA;AAW/D,eAAO,MAAM,KAAK,EAAE,KA0CnB,CAAA"}
package/dist/count.js ADDED
@@ -0,0 +1,41 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import toSnakeCase from 'to-snake-case';
3
+ import { chainMethods } from './find/chainMethods.js';
4
+ import buildQuery from './queries/buildQuery.js';
5
+ export const count = async function count({ collection, locale, req, where: whereArg }) {
6
+ const collectionConfig = this.payload.collections[collection].config;
7
+ const tableName = this.tableNameMap.get(toSnakeCase(collectionConfig.slug));
8
+ const db = this.sessions[await req.transactionID]?.db || this.drizzle;
9
+ const table = this.tables[tableName];
10
+ const { joins, where } = await buildQuery({
11
+ adapter: this,
12
+ fields: collectionConfig.fields,
13
+ locale,
14
+ tableName,
15
+ where: whereArg
16
+ });
17
+ const selectCountMethods = [];
18
+ Object.entries(joins).forEach(([joinTable, condition])=>{
19
+ if (joinTable) {
20
+ selectCountMethods.push({
21
+ args: [
22
+ this.tables[joinTable],
23
+ condition
24
+ ],
25
+ method: 'leftJoin'
26
+ });
27
+ }
28
+ });
29
+ const countResult = await chainMethods({
30
+ methods: selectCountMethods,
31
+ query: db.select({
32
+ count: sql`count
33
+ (DISTINCT ${this.tables[tableName].id})`
34
+ }).from(table).where(where)
35
+ });
36
+ return {
37
+ totalDocs: Number(countResult[0].count)
38
+ };
39
+ };
40
+
41
+ //# sourceMappingURL=count.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/count.ts"],"sourcesContent":["import type { Count, SanitizedCollectionConfig } from 'payload'\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[await 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"],"mappings":"AAEA,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,CAAC,MAAMZ,IAAIa,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IACrE,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"}
package/dist/create.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import type { Create } from 'payload/database';
1
+ import type { Create } from 'payload';
2
2
  export declare const create: Create;
3
3
  //# sourceMappingURL=create.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAO9C,eAAO,MAAM,MAAM,EAAE,MAqBpB,CAAA"}
1
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAQrC,eAAO,MAAM,MAAM,EAAE,MAoBpB,CAAA"}
package/dist/create.js CHANGED
@@ -1,8 +1,9 @@
1
- import { getTableName } from './schema/getTableName.js';
1
+ import toSnakeCase from 'to-snake-case';
2
2
  import { upsertRow } from './upsertRow/index.js';
3
3
  export const create = async function create({ collection: collectionSlug, data, req }) {
4
- const db = this.sessions[req.transactionID]?.db || this.drizzle;
4
+ const db = this.sessions[await req.transactionID]?.db || this.drizzle;
5
5
  const collection = this.payload.collections[collectionSlug].config;
6
+ const tableName = this.tableNameMap.get(toSnakeCase(collection.slug));
6
7
  const result = await upsertRow({
7
8
  adapter: this,
8
9
  data,
@@ -10,10 +11,7 @@ export const create = async function create({ collection: collectionSlug, data,
10
11
  fields: collection.fields,
11
12
  operation: 'create',
12
13
  req,
13
- tableName: getTableName({
14
- adapter: this,
15
- config: collection
16
- })
14
+ tableName
17
15
  });
18
16
  return result;
19
17
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/create.ts"],"sourcesContent":["import type { Create } from 'payload/database'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { getTableName } from './schema/getTableName.js'\nimport { upsertRow } from './upsertRow/index.js'\n\nexport const create: Create = async function create(\n this: PostgresAdapter,\n { collection: collectionSlug, data, req },\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const collection = this.payload.collections[collectionSlug].config\n\n const result = await upsertRow({\n adapter: this,\n data,\n db,\n fields: collection.fields,\n operation: 'create',\n req,\n tableName: getTableName({\n adapter: this,\n config: collection,\n }),\n })\n\n return result\n}\n"],"names":["getTableName","upsertRow","create","collection","collectionSlug","data","req","db","sessions","transactionID","drizzle","payload","collections","config","result","adapter","fields","operation","tableName"],"rangeMappings":";;;;;;;;;;;;;;;;;;","mappings":"AAIA,SAASA,YAAY,QAAQ,2BAA0B;AACvD,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,MAAMC,SAAiB,eAAeA,OAE3C,EAAEC,YAAYC,cAAc,EAAEC,IAAI,EAAEC,GAAG,EAAE;IAEzC,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACF,IAAIG,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMP,aAAa,IAAI,CAACQ,OAAO,CAACC,WAAW,CAACR,eAAe,CAACS,MAAM;IAElE,MAAMC,SAAS,MAAMb,UAAU;QAC7Bc,SAAS,IAAI;QACbV;QACAE;QACAS,QAAQb,WAAWa,MAAM;QACzBC,WAAW;QACXX;QACAY,WAAWlB,aAAa;YACtBe,SAAS,IAAI;YACbF,QAAQV;QACV;IACF;IAEA,OAAOW;AACT,EAAC"}
1
+ {"version":3,"sources":["../src/create.ts"],"sourcesContent":["import type { Create } from 'payload'\n\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { upsertRow } from './upsertRow/index.js'\n\nexport const create: Create = async function create(\n this: PostgresAdapter,\n { collection: collectionSlug, data, req },\n) {\n const db = this.sessions[await 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 const result = await upsertRow({\n adapter: this,\n data,\n db,\n fields: collection.fields,\n operation: 'create',\n req,\n tableName,\n })\n\n return result\n}\n"],"names":["toSnakeCase","upsertRow","create","collection","collectionSlug","data","req","db","sessions","transactionID","drizzle","payload","collections","config","tableName","tableNameMap","get","slug","result","adapter","fields","operation"],"mappings":"AAEA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,MAAMC,SAAiB,eAAeA,OAE3C,EAAEC,YAAYC,cAAc,EAAEC,IAAI,EAAEC,GAAG,EAAE;IAEzC,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAAC,MAAMF,IAAIG,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IACrE,MAAMP,aAAa,IAAI,CAACQ,OAAO,CAACC,WAAW,CAACR,eAAe,CAACS,MAAM;IAElE,MAAMC,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAChB,YAAYG,WAAWc,IAAI;IAEnE,MAAMC,SAAS,MAAMjB,UAAU;QAC7BkB,SAAS,IAAI;QACbd;QACAE;QACAa,QAAQjB,WAAWiB,MAAM;QACzBC,WAAW;QACXf;QACAQ;IACF;IAEA,OAAOI;AACT,EAAC"}
@@ -1,5 +1,4 @@
1
- import type { CreateGlobalArgs } from 'payload/database';
2
- import type { TypeWithID } from 'payload/types';
1
+ import type { CreateGlobalArgs } from 'payload';
3
2
  import type { PostgresAdapter } from './types.js';
4
- export declare function createGlobal<T extends TypeWithID>(this: PostgresAdapter, { slug, data, req }: CreateGlobalArgs): Promise<T>;
3
+ export declare function createGlobal<T extends Record<string, unknown>>(this: PostgresAdapter, { slug, data, req }: CreateGlobalArgs): Promise<T>;
5
4
  //# sourceMappingURL=createGlobal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createGlobal.d.ts","sourceRoot":"","sources":["../src/createGlobal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACxD,OAAO,KAAK,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAA;AAE/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAKjD,wBAAsB,YAAY,CAAC,CAAC,SAAS,UAAU,EACrD,IAAI,EAAE,eAAe,EACrB,EAAE,IAAI,EAAE,IAAI,EAAE,GAA0B,EAAE,EAAE,gBAAgB,GAC3D,OAAO,CAAC,CAAC,CAAC,CAkBZ"}
1
+ {"version":3,"file":"createGlobal.d.ts","sourceRoot":"","sources":["../src/createGlobal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,SAAS,CAAA;AAI/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIjD,wBAAsB,YAAY,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,IAAI,EAAE,eAAe,EACrB,EAAE,IAAI,EAAE,IAAI,EAAE,GAA0B,EAAE,EAAE,gBAAgB,GAC3D,OAAO,CAAC,CAAC,CAAC,CAiBZ"}
@@ -1,8 +1,9 @@
1
- import { getTableName } from './schema/getTableName.js';
1
+ import toSnakeCase from 'to-snake-case';
2
2
  import { upsertRow } from './upsertRow/index.js';
3
3
  export async function createGlobal({ slug, data, req = {} }) {
4
- const db = this.sessions[req.transactionID]?.db || this.drizzle;
4
+ const db = this.sessions[await req.transactionID]?.db || this.drizzle;
5
5
  const globalConfig = this.payload.globals.config.find((config)=>config.slug === slug);
6
+ const tableName = this.tableNameMap.get(toSnakeCase(globalConfig.slug));
6
7
  const result = await upsertRow({
7
8
  adapter: this,
8
9
  data,
@@ -10,10 +11,7 @@ export async function createGlobal({ slug, data, req = {} }) {
10
11
  fields: globalConfig.fields,
11
12
  operation: 'create',
12
13
  req,
13
- tableName: getTableName({
14
- adapter: this,
15
- config: globalConfig
16
- })
14
+ tableName
17
15
  });
18
16
  return result;
19
17
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createGlobal.ts"],"sourcesContent":["import type { CreateGlobalArgs } from 'payload/database'\nimport type { PayloadRequest, TypeWithID } from 'payload/types'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { getTableName } from './schema/getTableName.js'\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createGlobal<T extends TypeWithID>(\n this: PostgresAdapter,\n { slug, data, req = {} as PayloadRequest }: CreateGlobalArgs,\n): Promise<T> {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)\n\n const result = await upsertRow<T>({\n adapter: this,\n data,\n db,\n fields: globalConfig.fields,\n operation: 'create',\n req,\n tableName: getTableName({\n adapter: this,\n config: globalConfig,\n }),\n })\n\n return result\n}\n"],"names":["getTableName","upsertRow","createGlobal","slug","data","req","db","sessions","transactionID","drizzle","globalConfig","payload","globals","config","find","result","adapter","fields","operation","tableName"],"rangeMappings":";;;;;;;;;;;;;;;;;;","mappings":"AAKA,SAASA,YAAY,QAAQ,2BAA0B;AACvD,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,aAEpB,EAAEC,IAAI,EAAEC,IAAI,EAAEC,MAAM,CAAC,CAAmB,EAAoB;IAE5D,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACF,IAAIG,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,eAAe,IAAI,CAACC,OAAO,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAACD,SAAWA,OAAOV,IAAI,KAAKA;IAElF,MAAMY,SAAS,MAAMd,UAAa;QAChCe,SAAS,IAAI;QACbZ;QACAE;QACAW,QAAQP,aAAaO,MAAM;QAC3BC,WAAW;QACXb;QACAc,WAAWnB,aAAa;YACtBgB,SAAS,IAAI;YACbH,QAAQH;QACV;IACF;IAEA,OAAOK;AACT"}
1
+ {"version":3,"sources":["../src/createGlobal.ts"],"sourcesContent":["import type { CreateGlobalArgs, PayloadRequest } from 'payload'\n\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createGlobal<T extends Record<string, unknown>>(\n this: PostgresAdapter,\n { slug, data, req = {} as PayloadRequest }: CreateGlobalArgs,\n): Promise<T> {\n const db = this.sessions[await req.transactionID]?.db || this.drizzle\n const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)\n\n const tableName = this.tableNameMap.get(toSnakeCase(globalConfig.slug))\n\n const result = await upsertRow<T>({\n adapter: this,\n data,\n db,\n fields: globalConfig.fields,\n operation: 'create',\n req,\n tableName,\n })\n\n return result\n}\n"],"names":["toSnakeCase","upsertRow","createGlobal","slug","data","req","db","sessions","transactionID","drizzle","globalConfig","payload","globals","config","find","tableName","tableNameMap","get","result","adapter","fields","operation"],"mappings":"AAEA,OAAOA,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,aAEpB,EAAEC,IAAI,EAAEC,IAAI,EAAEC,MAAM,CAAC,CAAmB,EAAoB;IAE5D,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAAC,MAAMF,IAAIG,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IACrE,MAAMC,eAAe,IAAI,CAACC,OAAO,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAACD,SAAWA,OAAOV,IAAI,KAAKA;IAElF,MAAMY,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAACjB,YAAYU,aAAaP,IAAI;IAErE,MAAMe,SAAS,MAAMjB,UAAa;QAChCkB,SAAS,IAAI;QACbf;QACAE;QACAc,QAAQV,aAAaU,MAAM;QAC3BC,WAAW;QACXhB;QACAU;IACF;IAEA,OAAOG;AACT"}
@@ -1,6 +1,4 @@
1
- import type { TypeWithVersion } from 'payload/database';
2
- import type { TypeWithID } from 'payload/types';
3
- import { type CreateGlobalVersionArgs } from 'payload/database';
1
+ import type { CreateGlobalVersionArgs, TypeWithID, TypeWithVersion } from 'payload';
4
2
  import type { PostgresAdapter } from './types.js';
5
3
  export declare function createGlobalVersion<T extends TypeWithID>(this: PostgresAdapter, { autosave, globalSlug, req, versionData }: CreateGlobalVersionArgs): Promise<TypeWithVersion<T>>;
6
4
  //# sourceMappingURL=createGlobalVersion.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"createGlobalVersion.d.ts","sourceRoot":"","sources":["../src/createGlobalVersion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AACvD,OAAO,KAAK,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAA;AAG/D,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,kBAAkB,CAAA;AAG/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAKjD,wBAAsB,mBAAmB,CAAC,CAAC,SAAS,UAAU,EAC5D,IAAI,EAAE,eAAe,EACrB,EAAE,QAAQ,EAAE,UAAU,EAAE,GAA0B,EAAE,WAAW,EAAE,EAAE,uBAAuB,+BAmC3F"}
1
+ {"version":3,"file":"createGlobalVersion.d.ts","sourceRoot":"","sources":["../src/createGlobalVersion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAkB,UAAU,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAMnG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAIjD,wBAAsB,mBAAmB,CAAC,CAAC,SAAS,UAAU,EAC5D,IAAI,EAAE,eAAe,EACrB,EAAE,QAAQ,EAAE,UAAU,EAAE,GAA0B,EAAE,WAAW,EAAE,EAAE,uBAAuB,+BAgC3F"}
@@ -1,15 +1,11 @@
1
1
  import { sql } from 'drizzle-orm';
2
- import { buildVersionGlobalFields } from 'payload/versions';
3
- import { getTableName } from './schema/getTableName.js';
2
+ import { buildVersionGlobalFields } from 'payload';
3
+ import toSnakeCase from 'to-snake-case';
4
4
  import { upsertRow } from './upsertRow/index.js';
5
5
  export async function createGlobalVersion({ autosave, globalSlug, req = {}, versionData }) {
6
- const db = this.sessions[req.transactionID]?.db || this.drizzle;
6
+ const db = this.sessions[await req.transactionID]?.db || this.drizzle;
7
7
  const global = this.payload.globals.config.find(({ slug })=>slug === globalSlug);
8
- const tableName = getTableName({
9
- adapter: this,
10
- config: global,
11
- versions: true
12
- });
8
+ const tableName = this.tableNameMap.get(`_${toSnakeCase(global.slug)}${this.versionsSuffix}`);
13
9
  const result = await upsertRow({
14
10
  adapter: this,
15
11
  data: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import type { TypeWithVersion } from 'payload/database'\nimport type { PayloadRequest, TypeWithID } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport { type CreateGlobalVersionArgs } from 'payload/database'\nimport { buildVersionGlobalFields } from 'payload/versions'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { getTableName } from './schema/getTableName.js'\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createGlobalVersion<T extends TypeWithID>(\n this: PostgresAdapter,\n { autosave, globalSlug, req = {} as PayloadRequest, versionData }: CreateGlobalVersionArgs,\n) {\n const db = this.sessions[req.transactionID]?.db || this.drizzle\n const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)\n const tableName = getTableName({\n adapter: this,\n config: global,\n versions: true,\n })\n\n const result = await upsertRow<TypeWithVersion<T>>({\n adapter: this,\n data: {\n autosave,\n latest: true,\n version: versionData,\n },\n db,\n fields: buildVersionGlobalFields(global),\n operation: 'create',\n req,\n tableName,\n })\n\n const table = this.tables[tableName]\n\n if (global.versions.drafts) {\n await db.execute(sql`\n UPDATE ${table}\n SET latest = false\n WHERE ${table.id} != ${result.id};\n `)\n }\n\n return result\n}\n"],"names":["sql","buildVersionGlobalFields","getTableName","upsertRow","createGlobalVersion","autosave","globalSlug","req","versionData","db","sessions","transactionID","drizzle","global","payload","globals","config","find","slug","tableName","adapter","versions","result","data","latest","version","fields","operation","table","tables","drafts","execute","id"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AAEjC,SAASC,wBAAwB,QAAQ,mBAAkB;AAI3D,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,oBAEpB,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,MAAM,CAAC,CAAmB,EAAEC,WAAW,EAA2B;IAE1F,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAACH,IAAII,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IAC/D,MAAMC,SAAS,IAAI,CAACC,OAAO,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASZ;IACvE,MAAMa,YAAYjB,aAAa;QAC7BkB,SAAS,IAAI;QACbJ,QAAQH;QACRQ,UAAU;IACZ;IAEA,MAAMC,SAAS,MAAMnB,UAA8B;QACjDiB,SAAS,IAAI;QACbG,MAAM;YACJlB;YACAmB,QAAQ;YACRC,SAASjB;QACX;QACAC;QACAiB,QAAQzB,yBAAyBY;QACjCc,WAAW;QACXpB;QACAY;IACF;IAEA,MAAMS,QAAQ,IAAI,CAACC,MAAM,CAACV,UAAU;IAEpC,IAAIN,OAAOQ,QAAQ,CAACS,MAAM,EAAE;QAC1B,MAAMrB,GAAGsB,OAAO,CAAC/B,GAAG,CAAC;aACZ,EAAE4B,MAAM;;YAET,EAAEA,MAAMI,EAAE,CAAC,IAAI,EAAEV,OAAOU,EAAE,CAAC;IACnC,CAAC;IACH;IAEA,OAAOV;AACT"}
1
+ {"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import type { CreateGlobalVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'\n\nimport { sql } from 'drizzle-orm'\nimport { buildVersionGlobalFields } from 'payload'\nimport toSnakeCase from 'to-snake-case'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { upsertRow } from './upsertRow/index.js'\n\nexport async function createGlobalVersion<T extends TypeWithID>(\n this: PostgresAdapter,\n { autosave, globalSlug, req = {} as PayloadRequest, versionData }: CreateGlobalVersionArgs,\n) {\n const db = this.sessions[await req.transactionID]?.db || this.drizzle\n const global = this.payload.globals.config.find(({ slug }) => slug === globalSlug)\n\n const tableName = this.tableNameMap.get(`_${toSnakeCase(global.slug)}${this.versionsSuffix}`)\n\n const result = await upsertRow<TypeWithVersion<T>>({\n adapter: this,\n data: {\n autosave,\n latest: true,\n version: versionData,\n },\n db,\n fields: buildVersionGlobalFields(global),\n operation: 'create',\n req,\n tableName,\n })\n\n const table = this.tables[tableName]\n\n if (global.versions.drafts) {\n await db.execute(sql`\n UPDATE ${table}\n SET latest = false\n WHERE ${table.id} != ${result.id};\n `)\n }\n\n return result\n}\n"],"names":["sql","buildVersionGlobalFields","toSnakeCase","upsertRow","createGlobalVersion","autosave","globalSlug","req","versionData","db","sessions","transactionID","drizzle","global","payload","globals","config","find","slug","tableName","tableNameMap","get","versionsSuffix","result","adapter","data","latest","version","fields","operation","table","tables","versions","drafts","execute","id"],"mappings":"AAEA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,wBAAwB,QAAQ,UAAS;AAClD,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,oBAEpB,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,MAAM,CAAC,CAAmB,EAAEC,WAAW,EAA2B;IAE1F,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAAC,MAAMH,IAAII,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IACrE,MAAMC,SAAS,IAAI,CAACC,OAAO,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASZ;IAEvE,MAAMa,YAAY,IAAI,CAACC,YAAY,CAACC,GAAG,CAAC,CAAC,CAAC,EAAEnB,YAAYW,OAAOK,IAAI,EAAE,EAAE,IAAI,CAACI,cAAc,CAAC,CAAC;IAE5F,MAAMC,SAAS,MAAMpB,UAA8B;QACjDqB,SAAS,IAAI;QACbC,MAAM;YACJpB;YACAqB,QAAQ;YACRC,SAASnB;QACX;QACAC;QACAmB,QAAQ3B,yBAAyBY;QACjCgB,WAAW;QACXtB;QACAY;IACF;IAEA,MAAMW,QAAQ,IAAI,CAACC,MAAM,CAACZ,UAAU;IAEpC,IAAIN,OAAOmB,QAAQ,CAACC,MAAM,EAAE;QAC1B,MAAMxB,GAAGyB,OAAO,CAAClC,GAAG,CAAC;aACZ,EAAE8B,MAAM;;YAET,EAAEA,MAAMK,EAAE,CAAC,IAAI,EAAEZ,OAAOY,EAAE,CAAC;IACnC,CAAC;IACH;IAEA,OAAOZ;AACT"}
@@ -1,3 +1,3 @@
1
- import type { CreateMigration } from 'payload/database';
1
+ import type { CreateMigration } from 'payload';
2
2
  export declare const createMigration: CreateMigration;
3
3
  //# sourceMappingURL=createMigration.d.ts.map
@@ -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,SAAS,CAAA;AA2CrE,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';
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
  }
71
88
  }
72
89
  // write schema
73
90
  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","ms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AAM,GAAGF,iBAAiBc,KAAK,QAAQC,WACvDd,kBAAkBC,MAAM,GAAGD,mBAAmBa,KAAK,QAAQC;IAG/DhD,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'\n\nimport fs from 'fs'\nimport { createRequire } from 'module'\nimport path from 'path'\nimport { getPredefinedMigration } from 'payload'\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\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 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"],"mappings":"AAAA,yDAAyD,GAIzD,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,SAAQ;AACtC,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,QAAQ,UAAS;AAChD,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;QACRC,QAAQ;QACRJ,SAAS,CAAC;QACVC,QA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C,OAAOA,SAAS,CAAC,mBAAmB,CAAC;IACvC;IAEFe,QAAQkD,MAAM,CAACC,IAAI,CAAC;QAAEC,KAAK,CAAC,qBAAqB,EAAE3B,SAAS,GAAG,CAAC;IAAC;AACnE,EAAC"}
@@ -1,5 +1,4 @@
1
- import type { CreateVersionArgs, TypeWithVersion } from 'payload/database';
2
- import type { TypeWithID } from 'payload/types';
1
+ import type { CreateVersionArgs, TypeWithID, TypeWithVersion } from 'payload';
3
2
  import type { PostgresAdapter } from './types.js';
4
3
  export declare function createVersion<T extends TypeWithID>(this: PostgresAdapter, { autosave, collectionSlug, parent, req, versionData, }: CreateVersionArgs<T>): Promise<TypeWithVersion<T>>;
5
4
  //# sourceMappingURL=createVersion.d.ts.map
@@ -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,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAA;AAK/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAKjD,wBAAsB,aAAa,CAAC,CAAC,SAAS,UAAU,EACtD,IAAI,EAAE,eAAe,EACrB,EACE,QAAQ,EACR,cAAc,EACd,MAAM,EACN,GAA0B,EAC1B,WAAW,GACZ,EAAE,iBAAiB,CAAC,CAAC,CAAC,+BAiDxB"}
1
+ {"version":3,"file":"createVersion.d.ts","sourceRoot":"","sources":["../src/createVersion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAkB,UAAU,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAM7F,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,GAA0B,EAC1B,WAAW,GACZ,EAAE,iBAAiB,CAAC,CAAC,CAAC,+BAsCxB"}
@@ -1,22 +1,23 @@
1
1
  import { sql } from 'drizzle-orm';
2
- import { buildVersionCollectionFields } from 'payload/versions';
3
- import { getTableName } from './schema/getTableName.js';
2
+ import { buildVersionCollectionFields } from 'payload';
3
+ import toSnakeCase from 'to-snake-case';
4
4
  import { upsertRow } from './upsertRow/index.js';
5
5
  export async function createVersion({ autosave, collectionSlug, parent, req = {}, versionData }) {
6
- const db = this.sessions[req.transactionID]?.db || this.drizzle;
6
+ const db = this.sessions[await req.transactionID]?.db || this.drizzle;
7
7
  const collection = this.payload.collections[collectionSlug].config;
8
- const tableName = getTableName({
9
- adapter: this,
10
- config: collection,
11
- versions: true
12
- });
8
+ const defaultTableName = toSnakeCase(collection.slug);
9
+ const tableName = this.tableNameMap.get(`_${defaultTableName}${this.versionsSuffix}`);
10
+ const version = {
11
+ ...versionData
12
+ };
13
+ if (version.id) delete version.id;
13
14
  const result = await upsertRow({
14
15
  adapter: this,
15
16
  data: {
16
17
  autosave,
17
18
  latest: true,
18
19
  parent,
19
- version: versionData
20
+ version
20
21
  },
21
22
  db,
22
23
  fields: buildVersionCollectionFields(collection),
@@ -25,21 +26,12 @@ export async function createVersion({ autosave, collectionSlug, parent, req = {}
25
26
  tableName
26
27
  });
27
28
  const table = this.tables[tableName];
28
- const relationshipsTable = this.tables[getTableName({
29
- adapter: this,
30
- config: collection,
31
- relationships: true,
32
- versions: true
33
- })];
34
29
  if (collection.versions.drafts) {
35
30
  await db.execute(sql`
36
31
  UPDATE ${table}
37
32
  SET latest = false
38
- FROM ${relationshipsTable}
39
- WHERE ${table.id} = ${relationshipsTable.parent}
40
- AND ${relationshipsTable.path} = ${'parent'}
41
- AND ${relationshipsTable[`${collectionSlug}ID`]} = ${parent}
42
- AND ${table.id} != ${result.id};
33
+ WHERE ${table.id} != ${result.id}
34
+ AND ${table.parent} = ${parent}
43
35
  `);
44
36
  }
45
37
  return result;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import type { CreateVersionArgs, TypeWithVersion } from 'payload/database'\nimport type { PayloadRequest, TypeWithID } from 'payload/types'\n\nimport { sql } from 'drizzle-orm'\nimport { buildVersionCollectionFields } from 'payload/versions'\n\nimport type { PostgresAdapter } from './types.js'\n\nimport { getTableName } from './schema/getTableName.js'\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 PayloadRequest,\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 tableName = getTableName({\n adapter: this,\n config: collection,\n versions: true,\n })\n\n const result = await upsertRow<TypeWithVersion<T>>({\n adapter: this,\n data: {\n autosave,\n latest: true,\n parent,\n version: versionData,\n },\n db,\n fields: buildVersionCollectionFields(collection),\n operation: 'create',\n req,\n tableName,\n })\n\n const table = this.tables[tableName]\n const relationshipsTable =\n this.tables[\n getTableName({\n adapter: this,\n config: collection,\n relationships: true,\n versions: true,\n })\n ]\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","getTableName","upsertRow","createVersion","autosave","collectionSlug","parent","req","versionData","db","sessions","transactionID","drizzle","collection","payload","collections","config","tableName","adapter","versions","result","data","latest","version","fields","operation","table","tables","relationshipsTable","relationships","drafts","execute","id","path"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,GAAG,QAAQ,cAAa;AACj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ACnC,CAAC;IACH;IAEA,OAAOZ;AACT"}
1
+ {"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import type { CreateVersionArgs, PayloadRequest, TypeWithID, TypeWithVersion } from 'payload'\n\nimport { sql } from 'drizzle-orm'\nimport { buildVersionCollectionFields } from 'payload'\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 PayloadRequest,\n versionData,\n }: CreateVersionArgs<T>,\n) {\n const db = this.sessions[await 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"],"mappings":"AAEA,SAASA,GAAG,QAAQ,cAAa;AACjC,SAASC,4BAA4B,QAAQ,UAAS;AACtD,OAAOC,iBAAiB,gBAAe;AAIvC,SAASC,SAAS,QAAQ,uBAAsB;AAEhD,OAAO,eAAeC,cAEpB,EACEC,QAAQ,EACRC,cAAc,EACdC,MAAM,EACNC,MAAM,CAAC,CAAmB,EAC1BC,WAAW,EACU;IAEvB,MAAMC,KAAK,IAAI,CAACC,QAAQ,CAAC,MAAMH,IAAII,aAAa,CAAC,EAAEF,MAAM,IAAI,CAACG,OAAO;IACrE,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"}
@@ -1,3 +1,3 @@
1
- import type { DeleteMany } from 'payload/database';
1
+ import type { DeleteMany } from 'payload';
2
2
  export declare const deleteMany: DeleteMany;
3
3
  //# sourceMappingURL=deleteMany.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deleteMany.d.ts","sourceRoot":"","sources":["../src/deleteMany.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAUlD,eAAO,MAAM,UAAU,EAAE,UA6BxB,CAAA"}
1
+ {"version":3,"file":"deleteMany.d.ts","sourceRoot":"","sources":["../src/deleteMany.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAkB,MAAM,SAAS,CAAA;AASzD,eAAO,MAAM,UAAU,EAAE,UA8BxB,CAAA"}