@prisma/orm-target-postgres 8.0.0-rc.18-dev.12 → 8.0.0-rc.18-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/{adapter-Bz0FvaNf.d.mts → adapter-D9TdO1sz.d.mts} +10 -10
  2. package/dist/{adapter-Bz0FvaNf.d.mts.map → adapter-D9TdO1sz.d.mts.map} +1 -1
  3. package/dist/{adapter-ofQbK8p5-DdhE9Pbv.mjs → adapter-HQtZIZ2r-kQG81kJ1.mjs} +3 -3
  4. package/dist/{adapter-ofQbK8p5-DdhE9Pbv.mjs.map → adapter-HQtZIZ2r-kQG81kJ1.mjs.map} +1 -1
  5. package/dist/adapter.d.mts +2 -2
  6. package/dist/adapter.mjs +2 -2
  7. package/dist/adapter__adapter.d.mts +1 -1
  8. package/dist/adapter__adapter.mjs +2 -2
  9. package/dist/adapter__control.d.mts +1 -1
  10. package/dist/adapter__control.mjs +4 -4
  11. package/dist/adapter__control.mjs.map +1 -1
  12. package/dist/adapter__runtime.mjs +3 -3
  13. package/dist/adapter__runtime.mjs.map +1 -1
  14. package/dist/{aggregates-BNxcV7HS.d.mts → aggregates-B-jwhT8T.d.mts} +8 -8
  15. package/dist/{aggregates-BNxcV7HS.d.mts.map → aggregates-B-jwhT8T.d.mts.map} +1 -1
  16. package/dist/{authoring-DOWd8Fpc-BE703X_J.mjs → authoring-BPkERq95-SR5fDsa_.mjs} +3 -3
  17. package/dist/{authoring-DOWd8Fpc-BE703X_J.mjs.map → authoring-BPkERq95-SR5fDsa_.mjs.map} +1 -1
  18. package/dist/autoincrement-widths-D_WhWVXx-D6BupdY2.mjs +58 -0
  19. package/dist/autoincrement-widths-D_WhWVXx-D6BupdY2.mjs.map +1 -0
  20. package/dist/{canonicalize-CQlxSR4D-MnrT5gtW.d.mts → canonicalize-B-xvDOdd-Cnht2N4h.d.mts} +7 -3
  21. package/dist/canonicalize-B-xvDOdd-Cnht2N4h.d.mts.map +1 -0
  22. package/dist/{canonicalize-CrN3u_xM-D4MrOqcB.mjs → canonicalize-RdxoUHao-DK_M6HU-.mjs} +15 -3
  23. package/dist/canonicalize-RdxoUHao-DK_M6HU-.mjs.map +1 -0
  24. package/dist/{contract-contributions-RR2DymD_-B0xeL8RT.mjs → contract-contributions-DC-ACLe5-BtAuL8oB.mjs} +7 -13
  25. package/dist/contract-contributions-DC-ACLe5-BtAuL8oB.mjs.map +1 -0
  26. package/dist/{contract-free-DX6DmaSU.mjs → contract-free-BhaRUqcK.mjs} +2 -2
  27. package/dist/{contract-free-DX6DmaSU.mjs.map → contract-free-BhaRUqcK.mjs.map} +1 -1
  28. package/dist/{contract-free-D-v6WIhk.d.mts → contract-free-D1JEZVpQ.d.mts} +4 -4
  29. package/dist/{contract-free-D-v6WIhk.d.mts.map → contract-free-D1JEZVpQ.d.mts.map} +1 -1
  30. package/dist/{control-B2jgQGkQ.d.mts → control-B6nnypMh.d.mts} +3 -3
  31. package/dist/{control-B2jgQGkQ.d.mts.map → control-B6nnypMh.d.mts.map} +1 -1
  32. package/dist/{control-Ctj_SMkH.mjs → control-Bs7Il_Ju.mjs} +15 -10
  33. package/dist/control-Bs7Il_Ju.mjs.map +1 -0
  34. package/dist/{control-policy-DVEQWEOE-dVbGW9Xq.mjs → control-policy-CQ8hGDrk-jyie0S2j.mjs} +12 -9
  35. package/dist/control-policy-CQ8hGDrk-jyie0S2j.mjs.map +1 -0
  36. package/dist/{ddl-B6lRIezE-BMI5qzD2.mjs → ddl-CU7p3mkk-mKabtlGh.mjs} +164 -33
  37. package/dist/ddl-CU7p3mkk-mKabtlGh.mjs.map +1 -0
  38. package/dist/ddl-D_JWHRzo.d.mts +1 -0
  39. package/dist/{descriptor-meta-642teZF4-CAMY6SnM.mjs → descriptor-meta-CqUL_be_-BkT3aEIm.mjs} +3 -3
  40. package/dist/{descriptor-meta-642teZF4-CAMY6SnM.mjs.map → descriptor-meta-CqUL_be_-BkT3aEIm.mjs.map} +1 -1
  41. package/dist/{descriptor-meta-uNeqfA6R-Rrzkj6Ci.mjs → descriptor-meta-DzC2NwDh-C_D6wtZj.mjs} +3 -3
  42. package/dist/{descriptor-meta-uNeqfA6R-Rrzkj6Ci.mjs.map → descriptor-meta-DzC2NwDh-C_D6wtZj.mjs.map} +1 -1
  43. package/dist/{diff-database-schema-K7Wr3Cso-BkIytT4i.mjs → diff-database-schema-BKkcK7s--BxbpuwVf.mjs} +4 -4
  44. package/dist/{diff-database-schema-K7Wr3Cso-BkIytT4i.mjs.map → diff-database-schema-BKkcK7s--BxbpuwVf.mjs.map} +1 -1
  45. package/dist/{errors-D5sJ0fgp.d.mts → errors-BP-2V2_C.d.mts} +2 -2
  46. package/dist/{errors-D5sJ0fgp.d.mts.map → errors-BP-2V2_C.d.mts.map} +1 -1
  47. package/dist/{indexes-Ccd2ehxq-BaM6od9m.d.mts → indexes-ca4Dxsym-By_PZuYD.d.mts} +13 -4
  48. package/dist/indexes-ca4Dxsym-By_PZuYD.d.mts.map +1 -0
  49. package/dist/{infer-psl-contract-NE6ky6fm-RK7NjZQu.mjs → infer-psl-contract-DgOUfqJq-At4pgf6x.mjs} +3 -3
  50. package/dist/{infer-psl-contract-NE6ky6fm-RK7NjZQu.mjs.map → infer-psl-contract-DgOUfqJq-At4pgf6x.mjs.map} +1 -1
  51. package/dist/{issue-planner-C010eVt6.d.mts → issue-planner-DDhlcfH2.d.mts} +2 -2
  52. package/dist/{issue-planner-C010eVt6.d.mts.map → issue-planner-DDhlcfH2.d.mts.map} +1 -1
  53. package/dist/migration-CbOh59ZJ.mjs.map +1 -1
  54. package/dist/{migration-e6FvcwS2.d.mts → migration-DdE7N4ne.d.mts} +3 -3
  55. package/dist/{migration-e6FvcwS2.d.mts.map → migration-DdE7N4ne.d.mts.map} +1 -1
  56. package/dist/{nodes-h4zPlhED-nduA-ijW.d.mts → nodes-DOXes-fG-BifJqoRd.d.mts} +3 -3
  57. package/dist/{nodes-h4zPlhED-nduA-ijW.d.mts.map → nodes-DOXes-fG-BifJqoRd.d.mts.map} +1 -1
  58. package/dist/op-factory-call-B58Fw5Rz.d.mts +1 -0
  59. package/dist/{op-factory-call-TVvGnrxe-BYM7yGIk.mjs → op-factory-call-BCBPUVFr-CW8l_JKw.mjs} +253 -83
  60. package/dist/op-factory-call-BCBPUVFr-CW8l_JKw.mjs.map +1 -0
  61. package/dist/{op-factory-call-Do9gu48J-CNEnsh3K.d.mts → op-factory-call-COYbR6tp-XukKl6qj.d.mts} +18 -8
  62. package/dist/op-factory-call-COYbR6tp-XukKl6qj.d.mts.map +1 -0
  63. package/dist/{pack-4sJCj0w-.d.mts → pack-D9gjv6Kw.d.mts} +2 -2
  64. package/dist/{pack-4sJCj0w-.d.mts.map → pack-D9gjv6Kw.d.mts.map} +1 -1
  65. package/dist/{planner-Bc3x3nHl.d.mts → planner-Pcd2R46Y.d.mts} +2 -2
  66. package/dist/{planner-Bc3x3nHl.d.mts.map → planner-Pcd2R46Y.d.mts.map} +1 -1
  67. package/dist/{planner-q9c5nQlC-BvjDJEmC.mjs → planner-RhYHAxZm-9qT-aXSU.mjs} +8 -8
  68. package/dist/{planner-q9c5nQlC-BvjDJEmC.mjs.map → planner-RhYHAxZm-9qT-aXSU.mjs.map} +1 -1
  69. package/dist/{planner-ddl-builders-DWMjQBmJ-CjtMnGSN.mjs → planner-ddl-builders-oCsZMJ3b-BTMfg1YV.mjs} +3 -3
  70. package/dist/{planner-ddl-builders-DWMjQBmJ-CjtMnGSN.mjs.map → planner-ddl-builders-oCsZMJ3b-BTMfg1YV.mjs.map} +1 -1
  71. package/dist/{planner-produced-postgres-migration-CzGwh41Q-CoO2N7Ka.mjs → planner-produced-postgres-migration-B3b3MBKL-CxswQFN2.mjs} +4 -4
  72. package/dist/{planner-produced-postgres-migration-CzGwh41Q-CoO2N7Ka.mjs.map → planner-produced-postgres-migration-B3b3MBKL-CxswQFN2.mjs.map} +1 -1
  73. package/dist/planner-produced-postgres-migration-DiBkh1Tj.d.mts +1 -0
  74. package/dist/{planner-produced-postgres-migration-qAKbwI9E-BGte8lXU.d.mts → planner-produced-postgres-migration-eM7nl_4L-DSW4rLOj.d.mts} +3 -3
  75. package/dist/planner-produced-postgres-migration-eM7nl_4L-DSW4rLOj.d.mts.map +1 -0
  76. package/dist/{planner-sql-checks-CX37qDix-Gkq38UQQ.mjs → planner-sql-checks-BV2akIx8-l8qCWzYf.mjs} +32 -8
  77. package/dist/planner-sql-checks-BV2akIx8-l8qCWzYf.mjs.map +1 -0
  78. package/dist/{postgres-contract-view-D_z_HJ5K-BAzRKiIf.mjs → postgres-contract-view-Cei64xbt-BcDzLVah.mjs} +3 -3
  79. package/dist/{postgres-contract-view-D_z_HJ5K-BAzRKiIf.mjs.map → postgres-contract-view-Cei64xbt-BcDzLVah.mjs.map} +1 -1
  80. package/dist/{postgres-migration-DplG05vQ-Cyy1zJjv.mjs → postgres-migration-Bj3MPD7z-Clk_A5s-.mjs} +69 -31
  81. package/dist/postgres-migration-Bj3MPD7z-Clk_A5s-.mjs.map +1 -0
  82. package/dist/{postgres-migration-Btxi7VsD-DdEHax_e.d.mts → postgres-migration-D0TY1HnO-CXuyvNiq.d.mts} +20 -6
  83. package/dist/postgres-migration-D0TY1HnO-CXuyvNiq.d.mts.map +1 -0
  84. package/dist/{prisma7-binding-LcYpTBjP.d.mts → prisma7-binding-Bi4R4axY.d.mts} +2 -2
  85. package/dist/{prisma7-binding-LcYpTBjP.d.mts.map → prisma7-binding-Bi4R4axY.d.mts.map} +1 -1
  86. package/dist/{prisma7-binding-C_-5o7oD.mjs → prisma7-binding-BwBQ58iZ.mjs} +4 -4
  87. package/dist/{prisma7-binding-C_-5o7oD.mjs.map → prisma7-binding-BwBQ58iZ.mjs.map} +1 -1
  88. package/dist/{render-ops-D7WBk4VN-Ba7n9A9L.mjs → render-ops-TAy4wxZ8-FnL41Aq3.mjs} +3 -3
  89. package/dist/{render-ops-D7WBk4VN-Ba7n9A9L.mjs.map → render-ops-TAy4wxZ8-FnL41Aq3.mjs.map} +1 -1
  90. package/dist/{resolve-ddl-schema-BvsUhPsJ-CY5uEwIr.mjs → resolve-ddl-schema-JoXvD4Rv-CzPayApy.mjs} +15 -3
  91. package/dist/resolve-ddl-schema-JoXvD4Rv-CzPayApy.mjs.map +1 -0
  92. package/dist/schema-ir-annotations-DuuYh0gl.d.mts.map +1 -1
  93. package/dist/target.d.mts +17 -17
  94. package/dist/target.mjs +18 -18
  95. package/dist/target__aggregates.d.mts +1 -1
  96. package/dist/target__contract-free.d.mts +1 -1
  97. package/dist/target__contract-free.mjs +2 -2
  98. package/dist/target__control.mjs +3 -3
  99. package/dist/target__ddl.d.mts +3 -3
  100. package/dist/target__diff-database-schema.mjs +1 -1
  101. package/dist/target__errors.d.mts +1 -1
  102. package/dist/target__issue-planner.d.mts +1 -1
  103. package/dist/target__issue-planner.mjs +1 -1
  104. package/dist/target__migration.d.mts +2 -2
  105. package/dist/target__migration.mjs +2 -2
  106. package/dist/target__op-factory-call.d.mts +2 -2
  107. package/dist/target__op-factory-call.mjs +1 -1
  108. package/dist/target__pack.d.mts +1 -1
  109. package/dist/target__pack.mjs +1 -1
  110. package/dist/target__planner-ddl-builders.mjs +1 -1
  111. package/dist/target__planner-produced-postgres-migration.d.mts +2 -2
  112. package/dist/target__planner-produced-postgres-migration.mjs +1 -1
  113. package/dist/target__planner-sql-checks.mjs +1 -1
  114. package/dist/target__planner.d.mts +1 -1
  115. package/dist/target__planner.mjs +2 -2
  116. package/dist/target__prisma7-binding.d.mts +1 -1
  117. package/dist/target__prisma7-binding.mjs +1 -1
  118. package/dist/target__render-ops.mjs +1 -1
  119. package/dist/target__rls-canonicalize.d.mts +2 -2
  120. package/dist/target__rls-canonicalize.mjs +2 -2
  121. package/dist/target__runtime.mjs +2 -2
  122. package/dist/target__runtime.mjs.map +1 -1
  123. package/dist/target__schema-ir-annotations.mjs +1 -1
  124. package/package.json +9 -9
  125. package/dist/autoincrement-widths-DuylBJSq-T8e6pnMZ.mjs +0 -39
  126. package/dist/autoincrement-widths-DuylBJSq-T8e6pnMZ.mjs.map +0 -1
  127. package/dist/canonicalize-CQlxSR4D-MnrT5gtW.d.mts.map +0 -1
  128. package/dist/canonicalize-CrN3u_xM-D4MrOqcB.mjs.map +0 -1
  129. package/dist/contract-contributions-RR2DymD_-B0xeL8RT.mjs.map +0 -1
  130. package/dist/control-Ctj_SMkH.mjs.map +0 -1
  131. package/dist/control-policy-DVEQWEOE-dVbGW9Xq.mjs.map +0 -1
  132. package/dist/ddl-B6lRIezE-BMI5qzD2.mjs.map +0 -1
  133. package/dist/ddl-Da35uGK1.d.mts +0 -1
  134. package/dist/indexes-Ccd2ehxq-BaM6od9m.d.mts.map +0 -1
  135. package/dist/op-factory-call-DFD-usUW.d.mts +0 -1
  136. package/dist/op-factory-call-Do9gu48J-CNEnsh3K.d.mts.map +0 -1
  137. package/dist/op-factory-call-TVvGnrxe-BYM7yGIk.mjs.map +0 -1
  138. package/dist/planner-produced-postgres-migration-Da0CME4J.d.mts +0 -1
  139. package/dist/planner-produced-postgres-migration-qAKbwI9E-BGte8lXU.d.mts.map +0 -1
  140. package/dist/planner-sql-checks-CX37qDix-Gkq38UQQ.mjs.map +0 -1
  141. package/dist/postgres-migration-Btxi7VsD-DdEHax_e.d.mts.map +0 -1
  142. package/dist/postgres-migration-DplG05vQ-Cyy1zJjv.mjs.map +0 -1
  143. package/dist/resolve-ddl-schema-BvsUhPsJ-CY5uEwIr.mjs.map +0 -1
@@ -1,10 +1,11 @@
1
1
  import { s as postgresError } from "./errors-DYyzTYzE-39CV_aMo.mjs";
2
2
  import { i as quoteIdentifier, n as escapeLiteral, o as quoteQualifiedName, s as validateEnumValueLength, t as POSTGRES_QUOTING } from "./sql-utils-Df-nf6eM-Ov1KgjWm.mjs";
3
3
  import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86-Cpp8PTxD.mjs";
4
- import { A as sequenceNameAvailableAst, C as extensionExistsAst, D as noNullValuesAst, E as nativeEnumValueExistsAst, M as tableIsEmptyAst, O as rlsEnabledAst, S as dropType, T as nativeEnumTypeExistsAst, _ as createType, a as alterPolicyRename, b as dropIndex$1, c as columnDefaultSequenceAst, d as columnTypeAst, f as constraintExistsAst, g as createTable, h as createSchema, i as alterIndexRename, j as tableExistsAst, k as rlsPolicyExistsAst, l as columnExistsAst, m as createPolicy, n as addConstraintAction, o as alterTable, p as createIndex$1, r as alterColumnTypeAction, s as columnDefaultAst, t as addColumnAction, u as columnNullabilityAst, v as disableRowLevelSecurity$1, w as indexExistsAst, x as dropPolicy, y as dropDefaultAction } from "./ddl-B6lRIezE-BMI5qzD2.mjs";
5
- import { t as autoincrementWidth } from "./autoincrement-widths-DuylBJSq-T8e6pnMZ.mjs";
4
+ import { A as nativeEnumValueExistsAst, C as dropIndex$1, D as indexDefinitionAst, E as extensionExistsAst, F as rlsPolicyExistsAst, I as sequenceNameAvailableAst, L as sequenceValuesFitAst, M as relationKindAst, N as rlsEnabledAst, O as indexExistsAst, P as rlsPolicyDefinitionAst, R as tableExistsAst, S as dropDefaultAction, T as dropType, _ as createPolicy, a as alterPolicyRename, b as createType, c as columnDefaultSequenceAst, d as columnOwnsSequenceAst, f as columnTypeAst, g as createIndex$1, h as constraintExistsAst, i as alterIndexRename, j as noNullValuesAst, k as nativeEnumTypeExistsAst, l as columnExistsAst, m as constraintDefinitionAst, n as addConstraintAction, o as alterTable, p as columnTypeOidAst, r as alterColumnTypeAction, s as columnDefaultAst, t as addColumnAction, u as columnNullabilityAst, v as createSchema, w as dropPolicy, x as disableRowLevelSecurity$1, y as createTable, z as tableIsEmptyAst } from "./ddl-CU7p3mkk-mKabtlGh.mjs";
5
+ import { i as policyRoleList, t as POLICY_COMMAND_SQL } from "./canonicalize-RdxoUHao-DK_M6HU-.mjs";
6
+ import { r as autoincrementWidthOfPseudoType, t as autoincrementWidth } from "./autoincrement-widths-D_WhWVXx-D6BupdY2.mjs";
6
7
  import { t as postgresObjectName } from "./postgres-object-name-FPikIvOw-BNs44hTu.mjs";
7
- import { r as qualifyTableName, t as alterTypeCheckText } from "./planner-sql-checks-CX37qDix-Gkq38UQQ.mjs";
8
+ import { i as qualifyTableName, r as catalogTypeTextIfReadable, t as alterTypeCheckText } from "./planner-sql-checks-BV2akIx8-l8qCWzYf.mjs";
8
9
  import { t as buildTargetDetails } from "./planner-target-details-CUEF0s90-COTks5yz.mjs";
9
10
  import { DdlColumn, FunctionColumnDefault, LiteralColumnDefault, opaqueSql } from "@prisma/orm-family-sql/relational-core/ast";
10
11
  import { blindCast } from "@prisma/orm-framework/utils/casts";
@@ -17,7 +18,7 @@ import { InternalError, assertNever } from "@prisma/orm-framework/utils/internal
17
18
  import { unfilledPlaceholderOperation } from "@prisma/orm-framework/errors/migration";
18
19
  import { TsExpression, jsonToTsSource, tsObjectSource } from "@prisma/orm-framework/ts-render";
19
20
  import { REFERENTIAL_ACTION_SQL } from "@prisma/orm-family-sql/contract/referential-action-sql";
20
- //#region ../../../3-targets/3-targets/postgres/dist/op-factory-call-TVvGnrxe.mjs
21
+ //#region ../../../3-targets/3-targets/postgres/dist/op-factory-call-BCBPUVFr.mjs
21
22
  /**
22
23
  * Maps a planner schema name to the contract-free DDL builder's optional
23
24
  * `schema` field: the unbound sentinel becomes `undefined` (the builder omits
@@ -57,6 +58,19 @@ async function columnExistsSteps(lowerer, options) {
57
58
  absent: await lowerer.lowerToExecuteRequest(checks.columnAbsent())
58
59
  };
59
60
  }
61
+ /**
62
+ * The postcheck step that the column has the type `type`: by the text `format_type` prints, `checkType`, when the stack's data types read the type, and otherwise by the type's oid, which ignores a type modifier.
63
+ */
64
+ async function columnTypeStep(lowerer, location, type, checkType) {
65
+ const check = await lowerer.lowerToExecuteRequest(checkType === void 0 ? columnTypeOidAst({
66
+ ...location,
67
+ type
68
+ }) : columnTypeAst({
69
+ ...location,
70
+ expectedType: checkType
71
+ }));
72
+ return step(`verify column "${location.column}" has type "${checkType ?? type}"`, check.sql, check.params);
73
+ }
60
74
  async function dropColumn(schemaName, tableName, columnName, lowerer) {
61
75
  const qualified = qualifyTableName(schemaName, tableName);
62
76
  const { present, absent } = await columnExistsSteps(lowerer, {
@@ -103,7 +117,12 @@ async function renameColumn(schemaName, tableName, fromName, toName, lowerer) {
103
117
  }
104
118
  /**
105
119
  * `type` is the new column type as a migration writes it, into the `ALTER COLUMN TYPE` clause.
106
- * `checkType` is the type `format_type` prints for it, which the postcheck compares.
120
+ * `checkType` is the type `format_type` prints for it, which the postcheck compares. `sequence` is
121
+ * the width of the sequence the column owns when it has an `autoincrement()` default: the operation
122
+ * finds that sequence in the catalog and changes it to the new width, refusing first when the
123
+ * sequence has handed out a value past that width. A column whose default reads a sequence it does
124
+ * not own changes type and leaves the sequence alone. The postcheck asks for the type, and for the
125
+ * sequence width when the column owns one.
107
126
  */
108
127
  async function alterColumnType(schemaName, tableName, columnName, options, lowerer, operationClass = "destructive") {
109
128
  const { present } = await columnExistsSteps(lowerer, {
@@ -126,20 +145,61 @@ async function alterColumnType(schemaName, tableName, columnName, options, lower
126
145
  ...ifDefined("using", options.using)
127
146
  })]
128
147
  }));
148
+ const sequenceSteps = await ownedSequenceSteps(lowerer, {
149
+ schema: schemaName,
150
+ table: tableName,
151
+ column: columnName
152
+ }, options.sequenceWidth);
129
153
  return {
130
154
  id: `alterType.${tableName}.${columnName}`,
131
155
  label: `Alter type of "${tableName}"."${columnName}" to ${options.type}`,
132
156
  operationClass,
133
157
  target: targetDetails("column", columnName, schemaName, tableName),
134
- precheck: [step(`ensure column "${columnName}" exists`, present.sql, present.params)],
158
+ precheck: [step(`ensure column "${columnName}" exists`, present.sql, present.params), ...sequenceSteps.precheck],
135
159
  execute: [{
136
- ...step(`alter type of "${columnName}"`, alterType.sql),
160
+ ...step(`alter type of "${columnName}" to ${options.type}`, alterType.sql),
137
161
  ...options.using !== void 0 ? { meta: convertedColumnMeta(tableName, columnName, "conversion") } : operationClass === "destructive" ? { meta: convertedColumnMeta(tableName, columnName, "cast") } : {}
138
- }],
139
- postcheck: [step(`verify column "${columnName}" has type "${options.checkType}"`, typeCheck.sql, typeCheck.params)],
162
+ }, ...sequenceSteps.execute],
163
+ postcheck: [step(`verify column "${columnName}" has type "${options.checkType}"`, typeCheck.sql, typeCheck.params), ...sequenceSteps.postcheck],
140
164
  meta: { warning: "TABLE_REWRITE" }
141
165
  };
142
166
  }
167
+ async function ownedSequenceSteps(lowerer, location, width) {
168
+ if (width === void 0) return {
169
+ precheck: [],
170
+ execute: [],
171
+ postcheck: []
172
+ };
173
+ const { sequenceType, maxValue } = width;
174
+ const fits = await lowerer.lowerToExecuteRequest(sequenceValuesFitAst({
175
+ ...location,
176
+ maxValue
177
+ }));
178
+ const owns = await lowerer.lowerToExecuteRequest(columnOwnsSequenceAst({
179
+ ...location,
180
+ sequenceType,
181
+ orNone: true
182
+ }));
183
+ return {
184
+ precheck: [step(`ensure the sequence column "${location.column}" owns has no value past the ${sequenceType} range`, fits.sql, fits.params)],
185
+ execute: [step(`change the sequence column "${location.column}" owns, if any, to ${sequenceType}`, doBlock(`IF ${ownedSequenceSql(location)} IS NOT NULL THEN ${alterOwnedSequenceTypeStatement(location, sequenceType)} END IF;`))],
186
+ postcheck: [step(`verify the sequence column "${location.column}" owns, if any, is of type ${sequenceType}`, owns.sql, owns.params)]
187
+ };
188
+ }
189
+ /** SQL for the sequence the column owns, as a `regclass`, found at run time. */
190
+ function ownedSequenceSql(location) {
191
+ return `pg_get_serial_sequence('${escapeLiteral(qualifyTableName(location.schema, location.table))}', '${escapeLiteral(location.column)}')::regclass`;
192
+ }
193
+ /** A `DO` block around `body`, quoted with a dollar tag that `body` does not contain. */
194
+ function doBlock(body) {
195
+ let tag = "$prisma$";
196
+ for (let n = 1; body.includes(tag); n += 1) tag = `$prisma${n}$`;
197
+ return `DO ${tag} BEGIN ${body} END ${tag}`;
198
+ }
199
+ /** PL/pgSQL that runs `ALTER SEQUENCE … AS <type>` on the sequence the column owns, whatever its name. */
200
+ function alterOwnedSequenceTypeStatement(location, sequenceType) {
201
+ return `EXECUTE format('ALTER SEQUENCE %s AS ${sequenceType}', ${ownedSequenceSql(location)});`;
202
+ }
143
203
  async function setNotNull(schemaName, tableName, columnName, lowerer) {
144
204
  const qualified = qualifyTableName(schemaName, tableName);
145
205
  const { present } = await columnExistsSteps(lowerer, {
@@ -199,15 +259,11 @@ async function dropNotNull(schemaName, tableName, columnName, lowerer) {
199
259
  * the column's codec first, as every DDL statement that writes a default does. An `autoincrement()`
200
260
  * default attaches a sequence instead ({@link setAutoincrementDefault}).
201
261
  *
202
- * `operationClass` defaults to `'additive'` (setting a default on a column
203
- * that currently has none). The reconciliation planner passes `'widening'`
204
- * when the column already has a different default — policy enforcement
205
- * treats that as a widening change rather than an additive one. A widening
206
- * change has no postcheck: the old default would pass a check for a default,
207
- * and the runner skips an operation whose postcheck already passes. Setting a
208
- * default again is harmless.
262
+ * `operationClass` is `'additive'` when the column has no default yet and `'widening'` when it replaces one; policy enforcement reads it.
263
+ *
264
+ * The operation carries no postcheck. The runner skips an operation whose postchecks already hold before it runs. A check that the column has a default also holds for the old default, so the runner would skip a changed default. A check that compares the value would need the text Postgres stores for the default, predicted at plan time, which is fragile. Instead the run's final schema verification compares the default's value. Running `SET DEFAULT` again on a column that already has that default is harmless.
209
265
  */
210
- async function setDefault(schemaName, tableName, column, lowerer, operationClass = "additive") {
266
+ async function setDefault(schemaName, tableName, column, lowerer, operationClass) {
211
267
  if (column.default === void 0) throw postgresError("CONTRACT.DEFAULT_INVALID", `setDefault on column "${column.name}" of table "${tableName}" has no default. Pass the column with its default, as in col(name, type, { default: lit(value) }) or col(name, type, { default: fn(expression) }).`, { meta: {
212
268
  table: tableName,
213
269
  column: column.name,
@@ -222,11 +278,6 @@ async function setDefault(schemaName, tableName, column, lowerer, operationClass
222
278
  table: tableName,
223
279
  column: columnName
224
280
  });
225
- const hasDefault = operationClass === "additive" ? await lowerer.lowerToExecuteRequest(columnDefaultAst({
226
- schema: schemaName,
227
- table: tableName,
228
- column: columnName
229
- }).defaultPresent()) : void 0;
230
281
  return {
231
282
  id: `setDefault.${tableName}.${columnName}`,
232
283
  label: `Set default on "${tableName}"."${columnName}"`,
@@ -234,16 +285,19 @@ async function setDefault(schemaName, tableName, column, lowerer, operationClass
234
285
  target: targetDetails("column", columnName, schemaName, tableName),
235
286
  precheck: [step(`ensure column "${columnName}" exists`, present.sql, present.params)],
236
287
  execute: [step(`set default on "${columnName}"`, `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} SET ${clause}`)],
237
- postcheck: hasDefault === void 0 ? [] : [step(`verify column "${columnName}" has a default`, hasDefault.sql, hasDefault.params)]
288
+ postcheck: []
238
289
  };
239
290
  }
240
291
  /**
241
- * Gives an existing smallint, integer or bigint column an `autoincrement()` default: creates the
242
- * sequence a SERIAL column of that width would get (or reuses it, since dropping the default leaves
243
- * it in place, retyped to the column's current width), sets the column's default to it, makes the column own it, and starts it past the
244
- * column's largest value so existing rows never collide. The precheck refuses a name another
245
- * relation holds, which `IF NOT EXISTS` would otherwise skip over and then attach. The postcheck asks
246
- * for both the attached sequence and the `nextval(` default, which no earlier default satisfies.
292
+ * Gives an existing smallint, integer or bigint column an `autoincrement()` default. When the column
293
+ * already owns a sequence, whatever its name (dropping the default leaves it in place, and a rename
294
+ * of the table or column does not rename it), the operation reuses it; otherwise it creates the
295
+ * sequence a SERIAL column of that width would get and makes the column own it. It then sets the
296
+ * sequence to the column's width, sets the column's default to it, and starts it past the column's
297
+ * largest value so existing rows never collide. The precheck refuses, when the column owns no
298
+ * sequence, a name another relation holds. The postcheck asks for the attached sequence and the
299
+ * `nextval(` default, which no earlier default satisfies, and that the sequence has the column's
300
+ * width, which a narrower sequence left from before the column was widened does not satisfy.
247
301
  */
248
302
  async function setAutoincrementDefault(schemaName, tableName, column, lowerer, operationClass) {
249
303
  const columnName = column.name;
@@ -255,39 +309,38 @@ async function setAutoincrementDefault(schemaName, tableName, column, lowerer, o
255
309
  } });
256
310
  const qualifiedTable = qualifyTableName(schemaName, tableName);
257
311
  const qualifiedColumn = quoteIdentifier(columnName);
258
- const sequenceName = defaultSequenceName(tableName, columnName);
259
- const qualifiedSequence = qualifyTableName(schemaName, sequenceName);
260
- const sequenceRegclass = `'${escapeLiteral(qualifiedSequence)}'::regclass`;
261
- const { present } = await columnExistsSteps(lowerer, {
312
+ const location = {
262
313
  schema: schemaName,
263
314
  table: tableName,
264
315
  column: columnName
265
- });
316
+ };
317
+ const ownedSequence = ownedSequenceSql(location);
318
+ const sequenceName = defaultSequenceName(tableName, columnName);
319
+ const qualifiedSequence = qualifyTableName(schemaName, sequenceName);
320
+ const { present } = await columnExistsSteps(lowerer, location);
266
321
  const nameAvailable = await lowerer.lowerToExecuteRequest(sequenceNameAvailableAst({
267
- schema: schemaName,
268
- table: tableName,
269
- column: columnName,
322
+ ...location,
270
323
  sequence: sequenceName
271
324
  }));
272
- const attached = await lowerer.lowerToExecuteRequest(columnDefaultSequenceAst({
273
- schema: schemaName,
274
- table: tableName,
275
- column: columnName
325
+ const attached = await lowerer.lowerToExecuteRequest(columnDefaultSequenceAst(location));
326
+ const ownsSequence = await lowerer.lowerToExecuteRequest(columnOwnsSequenceAst({
327
+ ...location,
328
+ sequenceType,
329
+ orNone: false
276
330
  }));
277
331
  return {
278
332
  id: `setDefault.${tableName}.${columnName}`,
279
333
  label: `Set default on "${tableName}"."${columnName}"`,
280
334
  operationClass,
281
335
  target: targetDetails("column", columnName, schemaName, tableName),
282
- precheck: [step(`ensure column "${columnName}" exists`, present.sql, present.params), step(`ensure no relation other than the sequence column "${columnName}" owns is named ${qualifiedSequence} (rename that relation, or write this migration with migration new)`, nameAvailable.sql, nameAvailable.params)],
336
+ precheck: [step(`ensure column "${columnName}" exists`, present.sql, present.params), step(`ensure column "${columnName}" owns a sequence or no relation is named ${qualifiedSequence} (rename that relation, or write this migration with migration new)`, nameAvailable.sql, nameAvailable.params)],
283
337
  execute: [
284
- step(`widen any existing sequence "${sequenceName}" to ${sequenceType}`, `ALTER SEQUENCE IF EXISTS ${qualifiedSequence} AS ${sequenceType}`),
285
- step(`create sequence "${sequenceName}"`, `CREATE SEQUENCE IF NOT EXISTS ${qualifiedSequence} AS ${sequenceType}`),
286
- step(`set default on "${columnName}"`, `ALTER TABLE ${qualifiedTable} ALTER COLUMN ${qualifiedColumn} SET DEFAULT nextval(${sequenceRegclass})`),
287
- step(`attach sequence "${sequenceName}" to "${columnName}"`, `ALTER SEQUENCE ${qualifiedSequence} OWNED BY ${qualifiedTable}.${qualifiedColumn}`),
288
- step(`start sequence "${sequenceName}" past the largest "${columnName}"`, `SELECT setval(${sequenceRegclass}, GREATEST(COALESCE(MAX(${qualifiedColumn}), 0), 0) + 1, false) FROM ${qualifiedTable}`)
338
+ step(`create sequence "${sequenceName}" owned by "${columnName}" unless the column owns one`, doBlock(`IF ${ownedSequence} IS NULL THEN CREATE SEQUENCE ${qualifiedSequence} AS ${sequenceType}; ALTER SEQUENCE ${qualifiedSequence} OWNED BY ${qualifiedTable}.${qualifiedColumn}; END IF;`)),
339
+ step(`change the sequence column "${columnName}" owns to ${sequenceType}`, doBlock(alterOwnedSequenceTypeStatement(location, sequenceType))),
340
+ step(`set default on "${columnName}" to the sequence it owns`, doBlock(`EXECUTE format('ALTER TABLE %s ALTER COLUMN %I SET DEFAULT nextval(%L::regclass)', '${escapeLiteral(qualifiedTable)}', '${escapeLiteral(columnName)}', ${ownedSequence}::text);`)),
341
+ step(`start the sequence column "${columnName}" owns past the largest "${columnName}"`, `SELECT setval(${ownedSequence}, GREATEST(COALESCE(MAX(${qualifiedColumn}), 0), 0) + 1, false) FROM ${qualifiedTable}`)
289
342
  ],
290
- postcheck: [step(`verify column "${columnName}" takes its default from an attached sequence`, attached.sql, attached.params)]
343
+ postcheck: [step(`verify column "${columnName}" takes its default from an attached sequence`, attached.sql, attached.params), step(`verify column "${columnName}" owns a sequence of type ${sequenceType}`, ownsSequence.sql, ownsSequence.params)]
291
344
  };
292
345
  }
293
346
  async function dropDefault(schemaName, tableName, columnName, lowerer) {
@@ -322,7 +375,7 @@ async function dropDefault(schemaName, tableName, columnName, lowerer) {
322
375
  * empty; the execute step lowers the typed `AddColumn` DDL node through the
323
376
  * adapter; postchecks assert the column exists and is NOT NULL.
324
377
  */
325
- async function addRequiredColumnToEmptyTable(schemaName, tableName, column, lowerer) {
378
+ async function addRequiredColumnToEmptyTable(schemaName, tableName, column, checkType, lowerer) {
326
379
  const columnName = column.name;
327
380
  const addColumn = await lowerer.lowerToExecuteRequest(alterTable({
328
381
  ...ifDefined("schema", boundSchema(schemaName)),
@@ -346,6 +399,11 @@ async function addRequiredColumnToEmptyTable(schemaName, tableName, column, lowe
346
399
  column: columnName,
347
400
  nullable: false
348
401
  }));
402
+ const hasType = await columnTypeStep(lowerer, {
403
+ schema: schemaName,
404
+ table: tableName,
405
+ column: columnName
406
+ }, column.type, checkType);
349
407
  return {
350
408
  id: `column.${tableName}.${columnName}`,
351
409
  label: `Add column ${columnName} to ${tableName}`,
@@ -357,7 +415,11 @@ async function addRequiredColumnToEmptyTable(schemaName, tableName, column, lowe
357
415
  meta: requiredColumnMeta(tableName, columnName, "newField")
358
416
  }],
359
417
  execute: [step(`add column "${columnName}"`, addColumn.sql)],
360
- postcheck: [step(`verify column "${columnName}" exists`, present.sql, present.params), step(`verify column "${columnName}" is NOT NULL`, notNullable.sql, notNullable.params)]
418
+ postcheck: [
419
+ step(`verify column "${columnName}" exists`, present.sql, present.params),
420
+ step(`verify column "${columnName}" is NOT NULL`, notNullable.sql, notNullable.params),
421
+ hasType
422
+ ]
361
423
  };
362
424
  }
363
425
  async function constraintCheckSteps(lowerer, options) {
@@ -367,6 +429,20 @@ async function constraintCheckSteps(lowerer, options) {
367
429
  present: await lowerer.lowerToExecuteRequest(checks.constraintPresent())
368
430
  };
369
431
  }
432
+ async function constraintAbsent(lowerer, options) {
433
+ return lowerer.lowerToExecuteRequest(constraintExistsAst(options).constraintAbsent());
434
+ }
435
+ const REFERENTIAL_ACTION_CODE = {
436
+ noAction: "a",
437
+ restrict: "r",
438
+ cascade: "c",
439
+ setNull: "n",
440
+ setDefault: "d"
441
+ };
442
+ async function constraintDefinedStep(lowerer, description, definition) {
443
+ const defined = await lowerer.lowerToExecuteRequest(constraintDefinitionAst(definition));
444
+ return step(description, defined.sql, defined.params);
445
+ }
370
446
  function renderForeignKeySql(schemaName, tableName, fk) {
371
447
  let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
372
448
  ADD CONSTRAINT ${quoteIdentifier(fk.name)}
@@ -387,11 +463,18 @@ REFERENCES ${qualifyTableName(fk.references.schema, fk.references.table)} (${fk.
387
463
  async function addPrimaryKey(schemaName, tableName, constraintName, columns, lowerer) {
388
464
  const qualified = qualifyTableName(schemaName, tableName);
389
465
  const columnList = columns.map(quoteIdentifier).join(", ");
390
- const { absent, present } = await constraintCheckSteps(lowerer, {
466
+ const absent = await constraintAbsent(lowerer, {
391
467
  constraintName,
392
468
  schema: schemaName,
393
469
  table: tableName
394
470
  });
471
+ const defined = await constraintDefinedStep(lowerer, `verify primary key "${constraintName}" exists on (${columns.join(", ")})`, {
472
+ schema: schemaName,
473
+ table: tableName,
474
+ constraintName,
475
+ contype: "p",
476
+ columns
477
+ });
395
478
  return {
396
479
  id: `primaryKey.${tableName}.${constraintName}`,
397
480
  label: `Add primary key on "${tableName}"`,
@@ -399,17 +482,24 @@ async function addPrimaryKey(schemaName, tableName, constraintName, columns, low
399
482
  target: targetDetails("primaryKey", constraintName, schemaName, tableName),
400
483
  precheck: [step(`ensure primary key "${constraintName}" does not exist`, absent.sql, absent.params)],
401
484
  execute: [step(`add primary key "${constraintName}"`, `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteIdentifier(constraintName)} PRIMARY KEY (${columnList})`)],
402
- postcheck: [step(`verify primary key "${constraintName}" exists`, present.sql, present.params)]
485
+ postcheck: [defined]
403
486
  };
404
487
  }
405
488
  async function addUnique(schemaName, tableName, constraintName, columns, lowerer) {
406
489
  const qualified = qualifyTableName(schemaName, tableName);
407
490
  const columnList = columns.map(quoteIdentifier).join(", ");
408
- const { absent, present } = await constraintCheckSteps(lowerer, {
491
+ const absent = await constraintAbsent(lowerer, {
409
492
  constraintName,
410
493
  schema: schemaName,
411
494
  table: tableName
412
495
  });
496
+ const defined = await constraintDefinedStep(lowerer, `verify unique constraint "${constraintName}" exists on (${columns.join(", ")})`, {
497
+ schema: schemaName,
498
+ table: tableName,
499
+ constraintName,
500
+ contype: "u",
501
+ columns
502
+ });
413
503
  return {
414
504
  id: `unique.${tableName}.${constraintName}`,
415
505
  label: `Add unique constraint on "${tableName}" (${columns.join(", ")})`,
@@ -417,15 +507,29 @@ async function addUnique(schemaName, tableName, constraintName, columns, lowerer
417
507
  target: targetDetails("unique", constraintName, schemaName, tableName),
418
508
  precheck: [step(`ensure constraint "${constraintName}" does not exist`, absent.sql, absent.params)],
419
509
  execute: [step(`add unique constraint "${constraintName}"`, `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteIdentifier(constraintName)} UNIQUE (${columnList})`)],
420
- postcheck: [step(`verify constraint "${constraintName}" exists`, present.sql, present.params)]
510
+ postcheck: [defined]
421
511
  };
422
512
  }
423
513
  async function addForeignKey(schemaName, tableName, fk, lowerer) {
424
- const { absent, present } = await constraintCheckSteps(lowerer, {
514
+ const absent = await constraintAbsent(lowerer, {
425
515
  constraintName: fk.name,
426
516
  schema: schemaName,
427
517
  table: tableName
428
518
  });
519
+ const defined = await constraintDefinedStep(lowerer, `verify FK "${fk.name}" exists with the planned columns, referenced table and actions`, {
520
+ schema: schemaName,
521
+ table: tableName,
522
+ constraintName: fk.name,
523
+ contype: "f",
524
+ columns: fk.columns,
525
+ foreignKey: {
526
+ referencedSchema: fk.references.schema,
527
+ referencedTable: fk.references.table,
528
+ referencedColumns: fk.references.columns,
529
+ onDelete: REFERENTIAL_ACTION_CODE[fk.onDelete ?? "noAction"],
530
+ onUpdate: REFERENTIAL_ACTION_CODE[fk.onUpdate ?? "noAction"]
531
+ }
532
+ });
429
533
  return {
430
534
  id: `foreignKey.${tableName}.${fk.name}`,
431
535
  label: `Add foreign key "${fk.name}" on "${tableName}"`,
@@ -433,15 +537,21 @@ async function addForeignKey(schemaName, tableName, fk, lowerer) {
433
537
  target: targetDetails("foreignKey", fk.name, schemaName, tableName),
434
538
  precheck: [step(`ensure FK "${fk.name}" does not exist`, absent.sql, absent.params)],
435
539
  execute: [step(`add FK "${fk.name}"`, renderForeignKeySql(schemaName, tableName, fk))],
436
- postcheck: [step(`verify FK "${fk.name}" exists`, present.sql, present.params)]
540
+ postcheck: [defined]
437
541
  };
438
542
  }
439
543
  async function addCheckConstraint(schemaName, tableName, constraintName, expression, lowerer) {
440
- const { absent, present } = await constraintCheckSteps(lowerer, {
544
+ const absent = await constraintAbsent(lowerer, {
441
545
  constraintName,
442
546
  schema: schemaName,
443
547
  table: tableName
444
548
  });
549
+ const defined = await constraintDefinedStep(lowerer, `verify check constraint "${constraintName}" exists`, {
550
+ schema: schemaName,
551
+ table: tableName,
552
+ constraintName,
553
+ contype: "c"
554
+ });
445
555
  const addCheck = await lowerer.lowerToExecuteRequest(alterTable({
446
556
  ...ifDefined("schema", boundSchema(schemaName)),
447
557
  table: tableName,
@@ -454,7 +564,7 @@ async function addCheckConstraint(schemaName, tableName, constraintName, express
454
564
  target: targetDetails("checkConstraint", constraintName, schemaName, tableName),
455
565
  precheck: [step(`ensure constraint "${constraintName}" does not exist`, absent.sql, absent.params)],
456
566
  execute: [step(`add check constraint "${constraintName}"`, addCheck.sql)],
457
- postcheck: [step(`verify constraint "${constraintName}" exists`, present.sql, present.params)]
567
+ postcheck: [defined]
458
568
  };
459
569
  }
460
570
  const CONSTRAINT_KIND_LABEL = {
@@ -488,7 +598,7 @@ async function renameConstraint(schemaName, tableName, kind, fromName, toName, l
488
598
  target: targetDetails(kind, toName, schemaName, tableName),
489
599
  precheck: [step(`ensure constraint "${fromName}" exists`, from.present.sql, from.present.params), step(`ensure constraint "${toName}" does not exist`, to.absent.sql, to.absent.params)],
490
600
  execute: [step(`rename ${CONSTRAINT_KIND_LABEL[kind]} "${fromName}" to "${toName}"`, `ALTER TABLE ${qualified} RENAME CONSTRAINT ${quoteIdentifier(fromName)} TO ${quoteIdentifier(toName)}`)],
491
- postcheck: [step(`verify constraint "${toName}" exists`, to.present.sql, to.present.params)]
601
+ postcheck: [step(`verify constraint "${toName}" exists`, to.present.sql, to.present.params), step(`verify constraint "${fromName}" no longer exists`, from.absent.sql, from.absent.params)]
492
602
  };
493
603
  }
494
604
  async function dropCheckConstraint(schemaName, tableName, constraintName, lowerer) {
@@ -604,7 +714,16 @@ async function createIndex(schemaName, tableName, indexName, elements, lowerer,
604
714
  where: extras?.where
605
715
  });
606
716
  const execute = await lowerer.lowerToExecuteRequest(ddlNode);
607
- const { present, absent } = await indexExistsSteps(lowerer, schemaName, indexName);
717
+ const absent = await lowerer.lowerToExecuteRequest(indexExistsAst(schemaName, indexName).indexAbsent());
718
+ const defined = await lowerer.lowerToExecuteRequest(indexDefinitionAst({
719
+ schema: schemaName,
720
+ table: tableName,
721
+ index: indexName,
722
+ unique: extras?.unique === true,
723
+ method: extras?.type ?? "btree",
724
+ elements: "columns" in elements ? { columns: elements.columns } : { expression: true },
725
+ hasPredicate: extras?.where !== void 0
726
+ }));
608
727
  return {
609
728
  id: `index.${tableName}.${indexName}`,
610
729
  label: `Create index "${indexName}" on "${tableName}"`,
@@ -612,7 +731,7 @@ async function createIndex(schemaName, tableName, indexName, elements, lowerer,
612
731
  target: targetDetails("index", indexName, schemaName, tableName),
613
732
  precheck: [step(`ensure index "${indexName}" does not exist`, absent.sql, absent.params)],
614
733
  execute: [step(`create index "${indexName}"`, execute.sql, execute.params)],
615
- postcheck: [step(`verify index "${indexName}" exists`, present.sql, present.params)]
734
+ postcheck: [step(`verify index "${indexName}" exists on "${tableName}" with the planned definition`, defined.sql, defined.params)]
616
735
  };
617
736
  }
618
737
  /** `ALTER INDEX … RENAME TO`: `widening`, because a rename keeps every row and value. */
@@ -625,6 +744,7 @@ async function renameIndex(schemaName, tableName, fromName, toName, lowerer) {
625
744
  const fromPresent = await lowerer.lowerToExecuteRequest(fromChecks.indexPresent());
626
745
  const toAbsent = await lowerer.lowerToExecuteRequest(toChecks.indexAbsent());
627
746
  const toPresent = await lowerer.lowerToExecuteRequest(toChecks.indexPresent());
747
+ const fromAbsent = await lowerer.lowerToExecuteRequest(fromChecks.indexAbsent());
628
748
  const ddlNode = alterIndexRename({
629
749
  schema: ddlSchemaOf(schemaName),
630
750
  from: fromName,
@@ -638,7 +758,7 @@ async function renameIndex(schemaName, tableName, fromName, toName, lowerer) {
638
758
  target: targetDetails("index", toName, schemaName, tableName),
639
759
  precheck: [step(`ensure index "${fromName}" exists`, fromPresent.sql, fromPresent.params), step(`ensure index "${toName}" does not exist`, toAbsent.sql, toAbsent.params)],
640
760
  execute: [step(`rename index "${fromName}" to "${toName}"`, execute.sql, execute.params)],
641
- postcheck: [step(`verify index "${toName}" exists`, toPresent.sql, toPresent.params)]
761
+ postcheck: [step(`verify index "${toName}" exists`, toPresent.sql, toPresent.params), step(`verify index "${fromName}" no longer exists`, fromAbsent.sql, fromAbsent.params)]
642
762
  };
643
763
  }
644
764
  async function dropIndex(schemaName, tableName, indexName, lowerer) {
@@ -709,6 +829,11 @@ function validateRoleName(role) {
709
829
  } });
710
830
  return role;
711
831
  }
832
+ /** The roles `pg_policies.roles` lists for a policy created for `roles`: the roles the `TO` clause names, which fold to lower case unquoted. Postgres ignores every other role when the clause names `public`. */
833
+ function catalogPolicyRoles(roles) {
834
+ const named = [...new Set(policyRoleList(roles).map((role) => role.toLowerCase()))];
835
+ return named.includes("public") ? ["public"] : named;
836
+ }
712
837
  async function createRlsPolicy(schemaName, tableName, policy, lowerer) {
713
838
  const validatedRoles = policy.roles.map(validateRoleName);
714
839
  const ddlNode = createPolicy({
@@ -728,7 +853,14 @@ async function createRlsPolicy(schemaName, tableName, policy, lowerer) {
728
853
  });
729
854
  const absent = await lowerer.lowerToExecuteRequest(checks.policyAbsent());
730
855
  const execute = await lowerer.lowerToExecuteRequest(ddlNode);
731
- const present = await lowerer.lowerToExecuteRequest(checks.policyPresent());
856
+ const defined = await lowerer.lowerToExecuteRequest(rlsPolicyDefinitionAst({
857
+ schema: schemaName,
858
+ table: tableName,
859
+ policyName: policy.name,
860
+ command: POLICY_COMMAND_SQL[policy.operation],
861
+ permissive: policy.permissive,
862
+ roles: catalogPolicyRoles(validatedRoles)
863
+ }));
732
864
  return {
733
865
  id: `rlsPolicy.${schemaName}.${tableName}.${policy.name}`,
734
866
  label: `Create RLS policy "${policy.name}" on "${tableName}"`,
@@ -736,7 +868,7 @@ async function createRlsPolicy(schemaName, tableName, policy, lowerer) {
736
868
  target: targetDetails("rlsPolicy", policy.name, schemaName, tableName),
737
869
  precheck: [step(`ensure RLS policy "${policy.name}" does not exist`, absent.sql, absent.params)],
738
870
  execute: [step(`create RLS policy "${policy.name}"`, execute.sql, execute.params)],
739
- postcheck: [step(`verify RLS policy "${policy.name}" exists`, present.sql, present.params)]
871
+ postcheck: [step(`verify RLS policy "${policy.name}" exists with the planned command, roles and permissiveness`, defined.sql, defined.params)]
740
872
  };
741
873
  }
742
874
  async function dropRlsPolicy(schemaName, tableName, policyName, lowerer) {
@@ -816,14 +948,16 @@ async function renameRlsPolicy(schemaName, tableName, oldPolicyName, newPolicyNa
816
948
  const oldPresent = await lowerer.lowerToExecuteRequest(oldChecks.policyPresent());
817
949
  const execute = await lowerer.lowerToExecuteRequest(ddlNode);
818
950
  const newPresent = await lowerer.lowerToExecuteRequest(newChecks.policyPresent());
951
+ const newAbsent = await lowerer.lowerToExecuteRequest(newChecks.policyAbsent());
952
+ const oldAbsent = await lowerer.lowerToExecuteRequest(oldChecks.policyAbsent());
819
953
  return {
820
954
  id: `rlsPolicy.${schemaName}.${tableName}.${oldPolicyName}.rename`,
821
955
  label: `Rename RLS policy "${oldPolicyName}" to "${newPolicyName}" on "${tableName}"`,
822
956
  operationClass: "widening",
823
957
  target: targetDetails("rlsPolicy", newPolicyName, schemaName, tableName),
824
- precheck: [step(`ensure RLS policy "${oldPolicyName}" exists`, oldPresent.sql, oldPresent.params)],
958
+ precheck: [step(`ensure RLS policy "${oldPolicyName}" exists`, oldPresent.sql, oldPresent.params), step(`ensure RLS policy "${newPolicyName}" does not exist`, newAbsent.sql, newAbsent.params)],
825
959
  execute: [step(`rename RLS policy "${oldPolicyName}" to "${newPolicyName}"`, execute.sql, execute.params)],
826
- postcheck: [step(`verify RLS policy "${newPolicyName}" exists`, newPresent.sql, newPresent.params)]
960
+ postcheck: [step(`verify RLS policy "${newPolicyName}" exists`, newPresent.sql, newPresent.params), step(`verify RLS policy "${oldPolicyName}" no longer exists`, oldAbsent.sql, oldAbsent.params)]
827
961
  };
828
962
  }
829
963
  async function dropTable(schemaName, tableName, lowerer) {
@@ -876,7 +1010,7 @@ function buildAddColumnOperationIdentity(schema, tableName, columnName) {
876
1010
  };
877
1011
  }
878
1012
  async function buildAddNotNullColumnWithTemporaryDefaultOperation(options) {
879
- const { schema, tableName, columnName, type, temporaryDefault, lowerer } = options;
1013
+ const { schema, tableName, columnName, type, checkType, temporaryDefault, lowerer } = options;
880
1014
  const ddlColumn = col(columnName, type, {
881
1015
  notNull: true,
882
1016
  default: new FunctionColumnDefault(opaqueSql(temporaryDefault))
@@ -912,6 +1046,11 @@ async function buildAddNotNullColumnWithTemporaryDefaultOperation(options) {
912
1046
  table: tableName,
913
1047
  column: columnName
914
1048
  }).noDefault());
1049
+ const hasType = await columnTypeStep(lowerer, {
1050
+ schema,
1051
+ table: tableName,
1052
+ column: columnName
1053
+ }, type, checkType);
915
1054
  return {
916
1055
  ...buildAddColumnOperationIdentity(schema, tableName, columnName),
917
1056
  operationClass: "additive",
@@ -926,7 +1065,8 @@ async function buildAddNotNullColumnWithTemporaryDefaultOperation(options) {
926
1065
  postcheck: [
927
1066
  step(`verify column "${columnName}" exists`, present.sql, present.params),
928
1067
  step(`verify column "${columnName}" is NOT NULL`, notNullable.sql, notNullable.params),
929
- step(`verify column "${columnName}" has no default after temporary default removal`, noDefault.sql, noDefault.params)
1068
+ step(`verify column "${columnName}" has no default after temporary default removal`, noDefault.sql, noDefault.params),
1069
+ hasType
930
1070
  ]
931
1071
  };
932
1072
  }
@@ -1038,6 +1178,8 @@ function defaultImportSymbols(columns) {
1038
1178
  else if (col.default?.kind === "function") symbols.add("fn");
1039
1179
  return [...symbols];
1040
1180
  }
1181
+ /** `pg_class.relkind` of an ordinary or a partitioned table. */
1182
+ const TABLE_RELATION_KINDS = ["r", "p"];
1041
1183
  var CreateTableCall = class extends PostgresOpFactoryCallNode {
1042
1184
  factoryName = "createTable";
1043
1185
  operationClass = "additive";
@@ -1066,9 +1208,12 @@ var CreateTableCall = class extends PostgresOpFactoryCallNode {
1066
1208
  const statement = await lowerer.lowerToExecuteRequest(ddlNode);
1067
1209
  const schemaName = this.schemaName;
1068
1210
  const tableName = this.tableName;
1069
- const checks = tableExistsAst(schemaName, tableName);
1070
- const absent = await lowerer.lowerToExecuteRequest(checks.tableAbsent());
1071
- const present = await lowerer.lowerToExecuteRequest(checks.tablePresent());
1211
+ const absent = await lowerer.lowerToExecuteRequest(tableExistsAst(schemaName, tableName).tableAbsent());
1212
+ const isTable = await lowerer.lowerToExecuteRequest(relationKindAst({
1213
+ schema: schemaName,
1214
+ name: tableName,
1215
+ kinds: TABLE_RELATION_KINDS
1216
+ }));
1072
1217
  return {
1073
1218
  id: `table.${tableName}`,
1074
1219
  label: `Create table "${tableName}"`,
@@ -1081,7 +1226,7 @@ var CreateTableCall = class extends PostgresOpFactoryCallNode {
1081
1226
  sql: statement.sql,
1082
1227
  params: statement.params ?? []
1083
1228
  }],
1084
- postcheck: [step(`verify table "${tableName}" exists`, present.sql, present.params)]
1229
+ postcheck: [step(`verify table "${tableName}" exists`, isTable.sql, isTable.params)]
1085
1230
  };
1086
1231
  }
1087
1232
  renderTypeScript() {
@@ -1194,12 +1339,15 @@ var AddColumnCall = class extends PostgresOpFactoryCallNode {
1194
1339
  schemaName;
1195
1340
  tableName;
1196
1341
  column;
1342
+ /** The type `format_type` prints for the column, or `undefined` when the stack's data types do not read it. */
1343
+ checkType;
1197
1344
  label;
1198
- constructor(schemaName, tableName, column) {
1345
+ constructor(schemaName, tableName, column, dataTypes) {
1199
1346
  super();
1200
1347
  this.schemaName = schemaName;
1201
1348
  this.tableName = tableName;
1202
1349
  this.column = column;
1350
+ this.checkType = catalogTypeTextIfReadable(column.type, dataTypes);
1203
1351
  this.label = `Add column "${column.name}" to "${tableName}"`;
1204
1352
  this.freeze();
1205
1353
  }
@@ -1214,13 +1362,20 @@ var AddColumnCall = class extends PostgresOpFactoryCallNode {
1214
1362
  const schemaName = this.schemaName;
1215
1363
  const tableName = this.tableName;
1216
1364
  const columnName = this.column.name;
1217
- const colChecks = columnExistsAst({
1365
+ const location = {
1218
1366
  schema: schemaName,
1219
1367
  table: tableName,
1220
1368
  column: columnName
1221
- });
1369
+ };
1370
+ const colChecks = columnExistsAst(location);
1222
1371
  const absent = await lowerer.lowerToExecuteRequest(colChecks.columnAbsent());
1223
1372
  const present = await lowerer.lowerToExecuteRequest(colChecks.columnPresent());
1373
+ const hasType = await columnTypeStep(lowerer, location, this.column.type, this.checkType);
1374
+ const notNullable = this.column.notNull === true || this.column.primaryKey === true ? [await lowerer.lowerToExecuteRequest(columnNullabilityAst({
1375
+ ...location,
1376
+ nullable: false
1377
+ }))] : [];
1378
+ const sequenceDefault = autoincrementWidthOfPseudoType(this.column.type) === void 0 ? [] : [await lowerer.lowerToExecuteRequest(columnDefaultSequenceAst(location))];
1224
1379
  return {
1225
1380
  id: `column.${schemaName}.${tableName}.${columnName}`,
1226
1381
  label: `Add column "${columnName}" to "${tableName}"`,
@@ -1228,7 +1383,12 @@ var AddColumnCall = class extends PostgresOpFactoryCallNode {
1228
1383
  target: targetDetails("column", columnName, schemaName, tableName),
1229
1384
  precheck: [step(`ensure column "${columnName}" is missing`, absent.sql, absent.params)],
1230
1385
  execute: [step(`add column "${columnName}"`, statement.sql)],
1231
- postcheck: [step(`verify column "${columnName}" exists`, present.sql, present.params)]
1386
+ postcheck: [
1387
+ step(`verify column "${columnName}" exists`, present.sql, present.params),
1388
+ hasType,
1389
+ ...notNullable.map((check) => step(`verify column "${columnName}" is NOT NULL`, check.sql, check.params)),
1390
+ ...sequenceDefault.map((check) => step(`verify column "${columnName}" takes its default from an attached sequence`, check.sql, check.params))
1391
+ ]
1232
1392
  };
1233
1393
  }
1234
1394
  renderTypeScript() {
@@ -1346,6 +1506,8 @@ var AlterColumnTypeCall = class extends PostgresOpFactoryCallNode {
1346
1506
  using;
1347
1507
  /** The type `format_type` prints once the alter has run, which the postcheck compares. */
1348
1508
  checkType;
1509
+ /** The width the sequence the column owns takes, when the column has an `autoincrement()` default and an integer type. */
1510
+ sequenceWidth;
1349
1511
  label;
1350
1512
  constructor(input) {
1351
1513
  super();
@@ -1354,6 +1516,7 @@ var AlterColumnTypeCall = class extends PostgresOpFactoryCallNode {
1354
1516
  this.columnName = input.columnName;
1355
1517
  this.type = input.type;
1356
1518
  this.using = input.using;
1519
+ this.sequenceWidth = input.ownsAutoincrementSequence ? autoincrementWidth(input.type) : void 0;
1357
1520
  this.operationClass = input.operationClass ?? this.#defaultClass();
1358
1521
  this.#refuseUnsafeUsing();
1359
1522
  this.checkType = alterTypeCheckText(input.type, input.dataTypes, this.#callText());
@@ -1388,7 +1551,8 @@ var AlterColumnTypeCall = class extends PostgresOpFactoryCallNode {
1388
1551
  return alterColumnType(this.schemaName, this.tableName, this.columnName, {
1389
1552
  type: this.type,
1390
1553
  checkType: this.checkType,
1391
- ...ifDefined("using", sqlOfSlot(this.using))
1554
+ ...ifDefined("using", sqlOfSlot(this.using)),
1555
+ sequenceWidth: this.sequenceWidth
1392
1556
  }, lowerer, this.operationClass);
1393
1557
  }
1394
1558
  renderTypeScript() {
@@ -1482,7 +1646,7 @@ var SetDefaultCall = class extends PostgresOpFactoryCallNode {
1482
1646
  /** The column with the default to set, its type and its codec; the adapter writes the clause. */
1483
1647
  column;
1484
1648
  label;
1485
- constructor(schemaName, tableName, column, operationClass = "additive") {
1649
+ constructor(schemaName, tableName, column, operationClass) {
1486
1650
  super();
1487
1651
  this.schemaName = schemaName;
1488
1652
  this.tableName = tableName;
@@ -1504,7 +1668,6 @@ var SetDefaultCall = class extends PostgresOpFactoryCallNode {
1504
1668
  if (this.schemaName !== UNBOUND_NAMESPACE_ID) opts.push(`schema: ${jsonToTsSource(this.schemaName)}`);
1505
1669
  opts.push(`table: ${jsonToTsSource(this.tableName)}`);
1506
1670
  opts.push(`column: ${renderDdlColumnAsTsCall(this.column, sql)}`);
1507
- if (this.operationClass !== "additive") opts.push(`operationClass: ${jsonToTsSource(this.operationClass)}`);
1508
1671
  return {
1509
1672
  source: `this.setDefault({ ${opts.join(", ")} })`,
1510
1673
  imports: sql.imports()
@@ -1574,19 +1737,22 @@ var AddRequiredColumnToEmptyTableCall = class extends PostgresOpFactoryCallNode
1574
1737
  columnName;
1575
1738
  /** The column's type as a migration writes it. */
1576
1739
  type;
1740
+ /** The type `format_type` prints for `type`, or `undefined` when the stack's data types do not read it. */
1741
+ checkType;
1577
1742
  label;
1578
- constructor(schemaName, tableName, columnName, type) {
1743
+ constructor(schemaName, tableName, columnName, type, dataTypes) {
1579
1744
  super();
1580
1745
  this.schemaName = schemaName;
1581
1746
  this.tableName = tableName;
1582
1747
  this.columnName = columnName;
1583
1748
  this.type = type;
1749
+ this.checkType = catalogTypeTextIfReadable(type, dataTypes);
1584
1750
  this.label = `Add column ${columnName} to ${tableName}`;
1585
1751
  this.freeze();
1586
1752
  }
1587
1753
  async toOp(lowerer) {
1588
1754
  if (lowerer === void 0) throw postgresError("MIGRATION.POSTGRES_CONTROL_STACK_MISSING", `AddRequiredColumnToEmptyTableCall.toOp: a lowerer is required on the Postgres planner path (column "${this.columnName}" on table "${this.tableName}"). Pass the control adapter to createPostgresMigrationPlanner.`, { meta: { factory: "AddRequiredColumnToEmptyTableCall" } });
1589
- return addRequiredColumnToEmptyTable(this.schemaName, this.tableName, col(this.columnName, this.type, { notNull: true }), lowerer);
1755
+ return addRequiredColumnToEmptyTable(this.schemaName, this.tableName, col(this.columnName, this.type, { notNull: true }), this.checkType, lowerer);
1590
1756
  }
1591
1757
  renderTypeScript() {
1592
1758
  return `this.addRequiredColumnToEmptyTable({ ${[...columnCallLocation(this.schemaName, this.tableName, this.columnName), `type: ${jsonToTsSource(this.type)}`].join(", ")} })`;
@@ -1609,14 +1775,17 @@ var AddColumnWithTemporaryDefaultCall = class extends PostgresOpFactoryCallNode
1609
1775
  type;
1610
1776
  /** SQL for the value existing rows take, such as `''` or `0`. */
1611
1777
  temporaryDefault;
1778
+ /** The type `format_type` prints for `type`, or `undefined` when the stack's data types do not read it. */
1779
+ checkType;
1612
1780
  label;
1613
- constructor(schemaName, tableName, columnName, type, temporaryDefault) {
1781
+ constructor(schemaName, tableName, columnName, type, temporaryDefault, dataTypes) {
1614
1782
  super();
1615
1783
  this.schemaName = schemaName;
1616
1784
  this.tableName = tableName;
1617
1785
  this.columnName = columnName;
1618
1786
  this.type = type;
1619
1787
  this.temporaryDefault = temporaryDefault;
1788
+ this.checkType = catalogTypeTextIfReadable(type, dataTypes);
1620
1789
  const refused = checkSqlDefaultText(temporaryDefault);
1621
1790
  if (refused !== void 0) {
1622
1791
  const call = `addColumnWithTemporaryDefault({ ${columnCallLocation(schemaName, tableName, columnName).join(", ")} })`;
@@ -1638,6 +1807,7 @@ var AddColumnWithTemporaryDefaultCall = class extends PostgresOpFactoryCallNode
1638
1807
  tableName: this.tableName,
1639
1808
  columnName: this.columnName,
1640
1809
  type: this.type,
1810
+ checkType: this.checkType,
1641
1811
  temporaryDefault: this.temporaryDefault,
1642
1812
  lowerer
1643
1813
  });
@@ -2430,4 +2600,4 @@ function columnNameOfCall(call) {
2430
2600
  //#endregion
2431
2601
  export { RenameConstraintCall as A, isPostgresOpFactoryCall as B, DropNativeEnumTypeCall as C, EnableRowLevelSecurityCall as D, DropTableCall as E, SetNotNullCall as F, renameTableStatement as H, alterColumnTypeCallText as I, columnNameOfCall as L, RenamePostgresRlsPolicyCall as M, RenameTableCall as N, RawSqlCall as O, SetDefaultCall as P, createExtension as R, DropIndexCall as S, DropPostgresRlsPolicyCall as T, postgresDefaultToDdlColumnDefault as V, DisableRowLevelSecurityCall as _, AddNativeEnumValueCall as a, DropConstraintCall as b, AddUniqueCall as c, CreateIndexCall as d, CreateNativeEnumTypeCall as f, DataTransformCall as g, CreateTableCall as h, AddForeignKeyCall as i, RenameIndexCall as j, RenameColumnCall as k, AlterColumnTypeCall as l, CreateSchemaCall as m, AddColumnCall as n, AddPrimaryKeyCall as o, CreatePostgresRlsPolicyCall as p, AddColumnWithTemporaryDefaultCall as r, AddRequiredColumnToEmptyTableCall as s, AddCheckConstraintCall as t, CreateExtensionCall as u, DropCheckConstraintCall as v, DropNotNullCall as w, DropDefaultCall as x, DropColumnCall as y, installExtension as z };
2432
2602
 
2433
- //# sourceMappingURL=op-factory-call-TVvGnrxe-BYM7yGIk.mjs.map
2603
+ //# sourceMappingURL=op-factory-call-BCBPUVFr-CW8l_JKw.mjs.map