postgrelize 0.0.0-stage → 1.0.0

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 (308) hide show
  1. package/CHANGELOG.md +269 -0
  2. package/LICENSE +21 -0
  3. package/README.md +131 -2
  4. package/dist/associations/association-accessors.d.ts +21 -0
  5. package/dist/associations/association-key-types.d.ts +44 -0
  6. package/dist/associations/association-keys.d.ts +98 -0
  7. package/dist/associations/association-lookup.d.ts +26 -0
  8. package/dist/associations/association-shape.d.ts +25 -0
  9. package/dist/associations/association.d.ts +95 -0
  10. package/dist/associations/belongs-to-many.d.ts +86 -0
  11. package/dist/associations/belongs-to.d.ts +45 -0
  12. package/dist/associations/has-many.d.ts +79 -0
  13. package/dist/associations/has-one.d.ts +44 -0
  14. package/dist/associations/include-assembler.d.ts +21 -0
  15. package/dist/associations/include-columns.d.ts +24 -0
  16. package/dist/associations/include-joins.d.ts +17 -0
  17. package/dist/associations/include-loader.d.ts +48 -0
  18. package/dist/associations/include-order.d.ts +22 -0
  19. package/dist/associations/include-query-builder.d.ts +54 -0
  20. package/dist/associations/include-resolver.d.ts +29 -0
  21. package/dist/associations/include-rows.d.ts +47 -0
  22. package/dist/associations/include-sub-query.d.ts +35 -0
  23. package/dist/associations/include.d.ts +112 -0
  24. package/dist/associations/junction-keys.d.ts +23 -0
  25. package/dist/associations/nested-creator.d.ts +44 -0
  26. package/dist/associations/nested-saver.d.ts +30 -0
  27. package/dist/associations/owner-keys.d.ts +34 -0
  28. package/dist/associations/separate-include-loader.d.ts +24 -0
  29. package/dist/associations/types.d.ts +139 -0
  30. package/dist/connection/connection-config.d.ts +33 -0
  31. package/dist/connection/connection-manager.d.ts +65 -0
  32. package/dist/connection/connection-types.d.ts +21 -0
  33. package/dist/connection/copy-from-stdin.d.ts +52 -0
  34. package/dist/connection/copy-runner.d.ts +30 -0
  35. package/dist/connection/copy-to-stdout.d.ts +49 -0
  36. package/dist/connection/copy.d.ts +22 -0
  37. package/dist/connection/notifications.d.ts +28 -0
  38. package/dist/connection/options.d.ts +158 -0
  39. package/dist/connection/query-logger.d.ts +41 -0
  40. package/dist/connection/replica-router.d.ts +20 -0
  41. package/dist/connection/statement-cache.d.ts +36 -0
  42. package/dist/connection/statement-timeout.d.ts +22 -0
  43. package/dist/data-types/abstract-data-type.d.ts +58 -0
  44. package/dist/data-types/array-literal-parser.d.ts +17 -0
  45. package/dist/data-types/array-type.d.ts +18 -0
  46. package/dist/data-types/bit-type.d.ts +14 -0
  47. package/dist/data-types/blob-type.d.ts +12 -0
  48. package/dist/data-types/char-type.d.ts +12 -0
  49. package/dist/data-types/composite-fields.d.ts +26 -0
  50. package/dist/data-types/composite-type.d.ts +32 -0
  51. package/dist/data-types/data-types.d.ts +172 -0
  52. package/dist/data-types/date-type.d.ts +14 -0
  53. package/dist/data-types/decimal-type.d.ts +13 -0
  54. package/dist/data-types/default-value-generator.d.ts +15 -0
  55. package/dist/data-types/enum-type.d.ts +19 -0
  56. package/dist/data-types/ewkb-reader.d.ts +18 -0
  57. package/dist/data-types/ewkb-writer.d.ts +17 -0
  58. package/dist/data-types/float-type.d.ts +12 -0
  59. package/dist/data-types/geometric-text.d.ts +65 -0
  60. package/dist/data-types/geometric-type.d.ts +46 -0
  61. package/dist/data-types/hstore-type.d.ts +16 -0
  62. package/dist/data-types/integer-type.d.ts +24 -0
  63. package/dist/data-types/json-type.d.ts +16 -0
  64. package/dist/data-types/multirange-type.d.ts +19 -0
  65. package/dist/data-types/range-type.d.ts +28 -0
  66. package/dist/data-types/record-text.d.ts +29 -0
  67. package/dist/data-types/scalar-type.d.ts +13 -0
  68. package/dist/data-types/spatial-type.d.ts +20 -0
  69. package/dist/data-types/string-type.d.ts +12 -0
  70. package/dist/data-types/text-type.d.ts +12 -0
  71. package/dist/data-types/timestamp-type.d.ts +15 -0
  72. package/dist/data-types/virtual-type.d.ts +15 -0
  73. package/dist/data-types/wall-clock.d.ts +14 -0
  74. package/dist/ddl/column-ddl.d.ts +73 -0
  75. package/dist/ddl/constraint-ddl.d.ts +30 -0
  76. package/dist/ddl/ddl-generator.d.ts +181 -0
  77. package/dist/ddl/ddl-guards.d.ts +60 -0
  78. package/dist/ddl/ddl-types.d.ts +193 -0
  79. package/dist/ddl/enum-ddl.d.ts +42 -0
  80. package/dist/ddl/extension-ddl.d.ts +57 -0
  81. package/dist/ddl/function-ddl.d.ts +98 -0
  82. package/dist/ddl/index-ddl.d.ts +29 -0
  83. package/dist/ddl/index-element-ddl.d.ts +19 -0
  84. package/dist/ddl/partition-ddl.d.ts +88 -0
  85. package/dist/ddl/partition-types.d.ts +94 -0
  86. package/dist/ddl/policy-ddl.d.ts +137 -0
  87. package/dist/ddl/routine-guards.d.ts +63 -0
  88. package/dist/ddl/sequence-ddl.d.ts +103 -0
  89. package/dist/ddl/sql-literal.d.ts +61 -0
  90. package/dist/ddl/table-ddl.d.ts +35 -0
  91. package/dist/ddl/trigger-ddl.d.ts +81 -0
  92. package/dist/ddl/view-ddl.d.ts +122 -0
  93. package/dist/decorators/association-applier.d.ts +18 -0
  94. package/dist/decorators/association-decorators.d.ts +72 -0
  95. package/dist/decorators/column-decorators.d.ts +147 -0
  96. package/dist/decorators/decorator-factory.d.ts +45 -0
  97. package/dist/decorators/decorator-signature.d.ts +26 -0
  98. package/dist/decorators/decorator-types.d.ts +24 -0
  99. package/dist/decorators/foreign-key-decorator.d.ts +21 -0
  100. package/dist/decorators/hook-decorators.d.ts +393 -0
  101. package/dist/decorators/init-arguments.d.ts +29 -0
  102. package/dist/decorators/model-decorators.d.ts +18 -0
  103. package/dist/decorators/model-metadata.d.ts +70 -0
  104. package/dist/decorators/table-decorators.d.ts +43 -0
  105. package/dist/decorators/timestamp-decorators.d.ts +38 -0
  106. package/dist/errors/base-error.d.ts +40 -0
  107. package/dist/errors/connection-errors.d.ts +152 -0
  108. package/dist/errors/database-errors.d.ts +152 -0
  109. package/dist/errors/errors.d.ts +5 -0
  110. package/dist/errors/map-pg-error.d.ts +27 -0
  111. package/dist/errors/misc-errors.d.ts +188 -0
  112. package/dist/errors/validation-errors.d.ts +117 -0
  113. package/dist/exports-core.d.ts +15 -0
  114. package/dist/exports-decorators.d.ts +8 -0
  115. package/dist/exports-errors.d.ts +2 -0
  116. package/dist/exports-model.d.ts +21 -0
  117. package/dist/exports-schema.d.ts +19 -0
  118. package/dist/expressions/call-expressions.d.ts +54 -0
  119. package/dist/expressions/condition-expressions.d.ts +51 -0
  120. package/dist/expressions/expression.d.ts +52 -0
  121. package/dist/expressions/jsonpath-helpers.d.ts +37 -0
  122. package/dist/expressions/methods.d.ts +188 -0
  123. package/dist/expressions/op.d.ts +182 -0
  124. package/dist/expressions/query-expressions.d.ts +110 -0
  125. package/dist/expressions/row-expressions.d.ts +35 -0
  126. package/dist/expressions/search-helpers.d.ts +138 -0
  127. package/dist/expressions/trigram-helpers.d.ts +40 -0
  128. package/dist/hooks/hooks.d.ts +125 -0
  129. package/dist/index.cjs +20461 -0
  130. package/dist/index.cjs.map +1 -0
  131. package/dist/index.d.ts +5 -0
  132. package/dist/index.js +20332 -0
  133. package/dist/index.js.map +1 -0
  134. package/dist/model/attribute-columns.d.ts +85 -0
  135. package/dist/model/attribute-normalizer.d.ts +42 -0
  136. package/dist/model/attribute-options.d.ts +121 -0
  137. package/dist/model/bulk-insert-builder.d.ts +24 -0
  138. package/dist/model/bulk-options.d.ts +173 -0
  139. package/dist/model/copy-options.d.ts +51 -0
  140. package/dist/model/cte-builder.d.ts +134 -0
  141. package/dist/model/definition-normalizer.d.ts +26 -0
  142. package/dist/model/delete-query-builder.d.ts +42 -0
  143. package/dist/model/find-options.d.ts +144 -0
  144. package/dist/model/find-query-builder.d.ts +38 -0
  145. package/dist/model/insert-query-builder.d.ts +41 -0
  146. package/dist/model/instance-destroyer.d.ts +44 -0
  147. package/dist/model/instance-lifecycle-services.d.ts +61 -0
  148. package/dist/model/instance-lifecycle.d.ts +128 -0
  149. package/dist/model/instance-saver.d.ts +25 -0
  150. package/dist/model/instance-state.d.ts +48 -0
  151. package/dist/model/instance-validation.d.ts +35 -0
  152. package/dist/model/instance-values.d.ts +80 -0
  153. package/dist/model/instance-writer.d.ts +59 -0
  154. package/dist/model/join-source-builder.d.ts +25 -0
  155. package/dist/model/lateral-keys-builder.d.ts +25 -0
  156. package/dist/model/merge-action-builder.d.ts +31 -0
  157. package/dist/model/merge-options.d.ts +72 -0
  158. package/dist/model/merge-query-builder.d.ts +29 -0
  159. package/dist/model/merge-source-builder.d.ts +22 -0
  160. package/dist/model/mixins/model-aggregates.d.ts +69 -0
  161. package/dist/model/mixins/model-associations.d.ts +73 -0
  162. package/dist/model/mixins/model-constructor.d.ts +7 -0
  163. package/dist/model/mixins/model-finders.d.ts +124 -0
  164. package/dist/model/mixins/model-hooks.d.ts +138 -0
  165. package/dist/model/mixins/model-postgres.d.ts +198 -0
  166. package/dist/model/mixins/model-schema-binding.d.ts +36 -0
  167. package/dist/model/mixins/model-schema.d.ts +55 -0
  168. package/dist/model/mixins/model-scopes.d.ts +57 -0
  169. package/dist/model/mixins/model-writers.d.ts +175 -0
  170. package/dist/model/mixins/named-hooks.d.ts +28 -0
  171. package/dist/model/model-accessors.d.ts +22 -0
  172. package/dist/model/model-base.d.ts +83 -0
  173. package/dist/model/model-definition.d.ts +130 -0
  174. package/dist/model/model-instance-persistence.d.ts +132 -0
  175. package/dist/model/model-instance-values.d.ts +154 -0
  176. package/dist/model/model-operations.d.ts +22 -0
  177. package/dist/model/model-registry.d.ts +139 -0
  178. package/dist/model/model-services.d.ts +46 -0
  179. package/dist/model/model-state.d.ts +60 -0
  180. package/dist/model/model-values.d.ts +86 -0
  181. package/dist/model/model.d.ts +560 -0
  182. package/dist/model/on-conflict-builder.d.ts +111 -0
  183. package/dist/model/operations/bulk-create-operation.d.ts +40 -0
  184. package/dist/model/operations/copy-from-source.d.ts +51 -0
  185. package/dist/model/operations/copy-operation.d.ts +54 -0
  186. package/dist/model/operations/count-operation.d.ts +52 -0
  187. package/dist/model/operations/create-operation.d.ts +31 -0
  188. package/dist/model/operations/destroy-operation.d.ts +65 -0
  189. package/dist/model/operations/find-cursor.d.ts +23 -0
  190. package/dist/model/operations/find-lookups.d.ts +89 -0
  191. package/dist/model/operations/find-operation.d.ts +47 -0
  192. package/dist/model/operations/increment-operation.d.ts +40 -0
  193. package/dist/model/operations/insert-operation.d.ts +71 -0
  194. package/dist/model/operations/merge-operation.d.ts +56 -0
  195. package/dist/model/operations/model-operation.d.ts +33 -0
  196. package/dist/model/operations/update-operation.d.ts +45 -0
  197. package/dist/model/operations/upsert-operation.d.ts +39 -0
  198. package/dist/model/options.d.ts +103 -0
  199. package/dist/model/returning-old.d.ts +52 -0
  200. package/dist/model/row-mapper.d.ts +78 -0
  201. package/dist/model/row-plan.d.ts +31 -0
  202. package/dist/model/runtime.d.ts +54 -0
  203. package/dist/model/scope-registry.d.ts +81 -0
  204. package/dist/model/select-aggregates.d.ts +37 -0
  205. package/dist/model/select-lock.d.ts +13 -0
  206. package/dist/model/select-options.d.ts +92 -0
  207. package/dist/model/select-query-builder.d.ts +73 -0
  208. package/dist/model/select-targets.d.ts +77 -0
  209. package/dist/model/source-option-builder.d.ts +23 -0
  210. package/dist/model/source-options.d.ts +108 -0
  211. package/dist/model/statement-builder.d.ts +77 -0
  212. package/dist/model/statement-services.d.ts +2 -0
  213. package/dist/model/sync-hooks.d.ts +18 -0
  214. package/dist/model/table-sample-builder.d.ts +13 -0
  215. package/dist/model/types.d.ts +85 -0
  216. package/dist/model/unnest-insert-builder.d.ts +24 -0
  217. package/dist/model/update-query-builder.d.ts +39 -0
  218. package/dist/model/v6-conflict-builder.d.ts +37 -0
  219. package/dist/model/value-cloner.d.ts +17 -0
  220. package/dist/model/values-writer.d.ts +12 -0
  221. package/dist/model/where-options.d.ts +164 -0
  222. package/dist/model/write-options.d.ts +160 -0
  223. package/dist/model/written-rows.d.ts +56 -0
  224. package/dist/query/query-result-shaper.d.ts +91 -0
  225. package/dist/query/raw-query.d.ts +27 -0
  226. package/dist/query-interface/alter-planner.d.ts +40 -0
  227. package/dist/query-interface/bulk-data.d.ts +44 -0
  228. package/dist/query-interface/column-commands.d.ts +52 -0
  229. package/dist/query-interface/column-describer.d.ts +17 -0
  230. package/dist/query-interface/enum-commands.d.ts +36 -0
  231. package/dist/query-interface/index-commands.d.ts +57 -0
  232. package/dist/query-interface/model-tables.d.ts +58 -0
  233. package/dist/query-interface/object-commands.d.ts +71 -0
  234. package/dist/query-interface/partition-commands.d.ts +43 -0
  235. package/dist/query-interface/policy-commands.d.ts +54 -0
  236. package/dist/query-interface/query-interface-objects.d.ts +108 -0
  237. package/dist/query-interface/query-interface-partitions.d.ts +66 -0
  238. package/dist/query-interface/query-interface-policies.d.ts +86 -0
  239. package/dist/query-interface/query-interface-routines.d.ts +120 -0
  240. package/dist/query-interface/query-interface-tables.d.ts +179 -0
  241. package/dist/query-interface/query-interface-types.d.ts +62 -0
  242. package/dist/query-interface/query-interface-views.d.ts +84 -0
  243. package/dist/query-interface/query-interface.d.ts +256 -0
  244. package/dist/query-interface/routine-commands.d.ts +71 -0
  245. package/dist/query-interface/schema-synchronizer.d.ts +99 -0
  246. package/dist/query-interface/statement-runner.d.ts +40 -0
  247. package/dist/query-interface/sync-planner.d.ts +26 -0
  248. package/dist/query-interface/table-commands.d.ts +63 -0
  249. package/dist/query-interface/table-introspector.d.ts +58 -0
  250. package/dist/query-interface/view-commands.d.ts +47 -0
  251. package/dist/sequelize/sequelize-base.d.ts +196 -0
  252. package/dist/sequelize/sequelize-constructor.d.ts +7 -0
  253. package/dist/sequelize/sequelize-hooks.d.ts +86 -0
  254. package/dist/sequelize/sequelize-internals.d.ts +87 -0
  255. package/dist/sequelize/sequelize-notifications.d.ts +66 -0
  256. package/dist/sequelize/sequelize-schema.d.ts +106 -0
  257. package/dist/sequelize/sequelize-transactions.d.ts +96 -0
  258. package/dist/sequelize.d.ts +790 -0
  259. package/dist/sql/ast-clauses.d.ts +137 -0
  260. package/dist/sql/ast-expressions.d.ts +88 -0
  261. package/dist/sql/ast-statements.d.ts +80 -0
  262. package/dist/sql/ast.d.ts +21 -0
  263. package/dist/sql/compile.d.ts +21 -0
  264. package/dist/sql/dml-compiler.d.ts +54 -0
  265. package/dist/sql/expression-compiler.d.ts +56 -0
  266. package/dist/sql/from-compiler.d.ts +39 -0
  267. package/dist/sql/identifier-quoter.d.ts +15 -0
  268. package/dist/sql/merge-compiler.d.ts +20 -0
  269. package/dist/sql/order.d.ts +15 -0
  270. package/dist/sql/query-compiler.d.ts +45 -0
  271. package/dist/sql/sql-chunks.d.ts +50 -0
  272. package/dist/sql/with-compiler.d.ts +19 -0
  273. package/dist/transaction/advisory-locks.d.ts +28 -0
  274. package/dist/transaction/transaction-constants.d.ts +35 -0
  275. package/dist/transaction/transaction-runner.d.ts +60 -0
  276. package/dist/transaction/transaction-starter.d.ts +25 -0
  277. package/dist/transaction/transaction-statements.d.ts +28 -0
  278. package/dist/transaction/transaction.d.ts +198 -0
  279. package/dist/validation/attribute-validators.d.ts +23 -0
  280. package/dist/validation/builtin-attribute-validator.d.ts +19 -0
  281. package/dist/validation/builtin-validators.d.ts +16 -0
  282. package/dist/validation/core-validator.d.ts +16 -0
  283. package/dist/validation/custom-validators.d.ts +13 -0
  284. package/dist/validation/instance-validator.d.ts +25 -0
  285. package/dist/validation/schema-items.d.ts +22 -0
  286. package/dist/validation/standard-schema-validator.d.ts +30 -0
  287. package/dist/validation/standard-schema.d.ts +39 -0
  288. package/dist/validation/types.d.ts +36 -0
  289. package/dist/validation/validation-target.d.ts +13 -0
  290. package/dist/where/comparison-compiler.d.ts +27 -0
  291. package/dist/where/condition-compiler.d.ts +18 -0
  292. package/dist/where/operand-resolver.d.ts +10 -0
  293. package/dist/where/operator-allowlist.d.ts +14 -0
  294. package/dist/where/where-support.d.ts +52 -0
  295. package/dist/where/where.d.ts +46 -0
  296. package/dist/where/window-compiler.d.ts +14 -0
  297. package/llm/USAGE.md +423 -0
  298. package/package.json +102 -4
  299. package/skills/postgrelize/SKILL.md +57 -0
  300. package/skills/postgrelize/reference/associations.md +108 -0
  301. package/skills/postgrelize/reference/errors.md +37 -0
  302. package/skills/postgrelize/reference/migrating-from-sequelize.md +15 -0
  303. package/skills/postgrelize/reference/postgresql-features.md +157 -0
  304. package/skills/postgrelize/reference/querying.md +111 -0
  305. package/skills/postgrelize/reference/schema.md +135 -0
  306. package/skills/postgrelize/reference/security.md +34 -0
  307. package/skills/postgrelize/reference/transactions-and-sessions.md +122 -0
  308. package/skills/postgrelize/reference/writing.md +198 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["wallClock","quoter","HAS_Z","HAS_SRID","TYPE_NAME","contains","values","col","quoter","isPlainObject","accessors","registry","ast","ast","ast","ast","ast","ast","ast","ast","ast","ast","attributeColumns","selects","field","ast","attributeColumns","field","ast","attributeColumns","ast","ast","registry","registry","modelValues","toArray","extensions","ast","ast","ast","compiler","ast","ast","ast","ast","guards","noContext","sqlLiteral","guards","guards","elements","identity","sqlLiteral","sqlLiteral","guards","elements","identity","sqlLiteral","guards","sqlLiteral","sqlLiteral","partitions","guards","ddl","ast","registry","sqlCompiler","registry","__setFunctionName","sqlCompiler","registry","registry","ownerKeys","BelongsTo","registry","registry","BelongsToMany","keys","ownerKeys","HasMany","HasOne","registry","BelongsTo","HasOne","HasMany","BelongsToMany","registry","ddl","sqlLiteral","ddl","sqlLiteral","registry","sqlLiteral","identity","ddl","sqlLiteral","ddl","sqlLiteral","ddl","sqlLiteral","sqlLiteral","KINDS","sqlLiteral","guards","sqlLiteral","sqlLiteral","sqlLiteral","sqlLiteral","guards","sqlLiteral","guards","sqlLiteral","PgClient"],"sources":["../src/data-types/abstract-data-type.ts","../src/data-types/array-literal-parser.ts","../src/data-types/array-type.ts","../src/data-types/bit-type.ts","../src/data-types/blob-type.ts","../src/data-types/char-type.ts","../src/sql/identifier-quoter.ts","../src/data-types/wall-clock.ts","../src/data-types/composite-fields.ts","../src/data-types/record-text.ts","../src/data-types/composite-type.ts","../src/data-types/date-type.ts","../src/data-types/decimal-type.ts","../src/data-types/default-value-generator.ts","../src/data-types/enum-type.ts","../src/data-types/float-type.ts","../src/data-types/geometric-text.ts","../src/data-types/geometric-type.ts","../src/data-types/hstore-type.ts","../src/data-types/integer-type.ts","../src/data-types/json-type.ts","../src/data-types/range-type.ts","../src/data-types/multirange-type.ts","../src/data-types/scalar-type.ts","../src/data-types/ewkb-reader.ts","../src/data-types/ewkb-writer.ts","../src/data-types/spatial-type.ts","../src/data-types/string-type.ts","../src/data-types/text-type.ts","../src/data-types/timestamp-type.ts","../src/data-types/virtual-type.ts","../src/data-types/data-types.ts","../src/expressions/expression.ts","../src/expressions/call-expressions.ts","../src/expressions/condition-expressions.ts","../src/expressions/query-expressions.ts","../src/expressions/row-expressions.ts","../src/expressions/methods.ts","../src/expressions/op.ts","../src/sql/sql-chunks.ts","../src/sql/dml-compiler.ts","../src/sql/merge-compiler.ts","../src/sql/with-compiler.ts","../src/sql/from-compiler.ts","../src/sql/expression-compiler.ts","../src/sql/query-compiler.ts","../src/sql/compile.ts","../src/model/instance-state.ts","../src/model/model-accessors.ts","../src/hooks/hooks.ts","../src/model/attribute-normalizer.ts","../src/model/definition-normalizer.ts","../src/model/model-definition.ts","../src/model/runtime.ts","../src/model/values-writer.ts","../src/model/scope-registry.ts","../src/model/model-state.ts","../src/model/model-registry.ts","../src/associations/include-rows.ts","../src/associations/include-assembler.ts","../src/sql/ast.ts","../src/where/operator-allowlist.ts","../src/where/where-support.ts","../src/where/comparison-compiler.ts","../src/where/condition-compiler.ts","../src/where/operand-resolver.ts","../src/sql/order.ts","../src/where/window-compiler.ts","../src/where/where.ts","../src/model/attribute-columns.ts","../src/associations/separate-include-loader.ts","../src/associations/include-loader.ts","../src/model/table-sample-builder.ts","../src/transaction/advisory-locks.ts","../src/transaction/transaction-constants.ts","../src/transaction/transaction-statements.ts","../src/transaction/transaction.ts","../src/model/select-lock.ts","../src/model/select-aggregates.ts","../src/model/select-targets.ts","../src/model/select-query-builder.ts","../src/associations/include-columns.ts","../src/associations/include-joins.ts","../src/associations/include-order.ts","../src/associations/include-sub-query.ts","../src/associations/include-query-builder.ts","../src/errors/base-error.ts","../src/errors/validation-errors.ts","../src/errors/database-errors.ts","../src/errors/connection-errors.ts","../src/errors/misc-errors.ts","../src/associations/association-lookup.ts","../src/associations/include-resolver.ts","../src/model/model-values.ts","../src/associations/nested-saver.ts","../src/associations/nested-creator.ts","../src/validation/builtin-validators.ts","../src/validation/builtin-attribute-validator.ts","../src/validation/custom-validators.ts","../src/validation/standard-schema-validator.ts","../src/validation/schema-items.ts","../src/validation/attribute-validators.ts","../src/validation/core-validator.ts","../src/validation/instance-validator.ts","../src/model/cte-builder.ts","../src/model/delete-query-builder.ts","../src/model/lateral-keys-builder.ts","../src/model/find-query-builder.ts","../src/model/insert-query-builder.ts","../src/model/instance-destroyer.ts","../src/model/instance-writer.ts","../src/model/instance-saver.ts","../src/model/instance-validation.ts","../src/model/instance-lifecycle.ts","../src/model/sync-hooks.ts","../src/model/instance-values.ts","../src/ddl/sql-literal.ts","../src/model/source-option-builder.ts","../src/model/join-source-builder.ts","../src/model/v6-conflict-builder.ts","../src/model/on-conflict-builder.ts","../src/model/returning-old.ts","../src/model/row-plan.ts","../src/model/row-mapper.ts","../src/model/update-query-builder.ts","../src/model/value-cloner.ts","../src/model/merge-action-builder.ts","../src/ddl/ddl-types.ts","../src/ddl/ddl-guards.ts","../src/ddl/column-ddl.ts","../src/ddl/index-element-ddl.ts","../src/ddl/constraint-ddl.ts","../src/ddl/enum-ddl.ts","../src/ddl/index-ddl.ts","../src/ddl/partition-types.ts","../src/ddl/partition-ddl.ts","../src/ddl/table-ddl.ts","../src/ddl/ddl-generator.ts","../src/model/merge-source-builder.ts","../src/model/merge-query-builder.ts","../src/model/written-rows.ts","../src/model/model-services.ts","../src/model/model-base.ts","../src/model/model-instance-persistence.ts","../src/model/model-instance-values.ts","../src/connection/copy-from-stdin.ts","../src/connection/copy-to-stdout.ts","../src/connection/copy.ts","../src/model/operations/model-operation.ts","../src/model/operations/bulk-create-operation.ts","../src/model/operations/copy-from-source.ts","../src/model/operations/copy-operation.ts","../src/model/operations/count-operation.ts","../src/model/operations/create-operation.ts","../src/model/operations/destroy-operation.ts","../src/model/operations/find-cursor.ts","../src/model/operations/find-lookups.ts","../src/model/operations/find-operation.ts","../src/model/operations/increment-operation.ts","../src/model/operations/insert-operation.ts","../src/model/bulk-insert-builder.ts","../src/model/unnest-insert-builder.ts","../src/model/operations/merge-operation.ts","../src/model/operations/update-operation.ts","../src/model/operations/upsert-operation.ts","../src/model/model-operations.ts","../src/model/mixins/model-aggregates.ts","../src/associations/association-accessors.ts","../src/associations/association-shape.ts","../src/associations/association.ts","../src/associations/association-keys.ts","../src/associations/owner-keys.ts","../src/associations/belongs-to.ts","../src/associations/junction-keys.ts","../src/associations/belongs-to-many.ts","../src/associations/has-many.ts","../src/associations/has-one.ts","../src/model/mixins/model-associations.ts","../src/model/mixins/model-finders.ts","../src/model/mixins/named-hooks.ts","../src/model/mixins/model-hooks.ts","../src/model/statement-builder.ts","../src/model/statement-services.ts","../src/model/mixins/model-postgres.ts","../src/query-interface/alter-planner.ts","../src/query-interface/model-tables.ts","../src/query-interface/sync-planner.ts","../src/query-interface/schema-synchronizer.ts","../src/model/mixins/model-schema.ts","../src/model/mixins/model-schema-binding.ts","../src/model/mixins/model-scopes.ts","../src/model/mixins/model-writers.ts","../src/model/model.ts","../src/query/query-result-shaper.ts","../src/decorators/model-metadata.ts","../src/decorators/association-applier.ts","../src/decorators/init-arguments.ts","../src/decorators/model-decorators.ts","../src/connection/connection-config.ts","../src/query/raw-query.ts","../src/query-interface/bulk-data.ts","../src/query-interface/column-commands.ts","../src/query-interface/enum-commands.ts","../src/query-interface/index-commands.ts","../src/query-interface/partition-commands.ts","../src/ddl/policy-ddl.ts","../src/query-interface/policy-commands.ts","../src/ddl/extension-ddl.ts","../src/ddl/sequence-ddl.ts","../src/query-interface/object-commands.ts","../src/query-interface/statement-runner.ts","../src/query-interface/table-commands.ts","../src/query-interface/column-describer.ts","../src/query-interface/table-introspector.ts","../src/query-interface/query-interface-tables.ts","../src/query-interface/query-interface-objects.ts","../src/ddl/routine-guards.ts","../src/ddl/function-ddl.ts","../src/ddl/trigger-ddl.ts","../src/query-interface/routine-commands.ts","../src/query-interface/query-interface-routines.ts","../src/ddl/view-ddl.ts","../src/query-interface/view-commands.ts","../src/query-interface/query-interface-views.ts","../src/query-interface/query-interface-policies.ts","../src/query-interface/query-interface-partitions.ts","../src/query-interface/query-interface.ts","../src/connection/copy-runner.ts","../src/connection/replica-router.ts","../src/connection/statement-timeout.ts","../src/connection/statement-cache.ts","../src/connection/connection-manager.ts","../src/connection/notifications.ts","../src/connection/query-logger.ts","../src/errors/map-pg-error.ts","../src/transaction/transaction-runner.ts","../src/transaction/transaction-starter.ts","../src/sequelize/sequelize-internals.ts","../src/sequelize/sequelize-base.ts","../src/sequelize/sequelize-hooks.ts","../src/sequelize/sequelize-notifications.ts","../src/sequelize/sequelize-schema.ts","../src/sequelize/sequelize-transactions.ts","../src/sequelize.ts","../src/expressions/jsonpath-helpers.ts","../src/expressions/search-helpers.ts","../src/expressions/trigram-helpers.ts","../src/decorators/decorator-signature.ts","../src/decorators/decorator-factory.ts","../src/decorators/association-decorators.ts","../src/decorators/column-decorators.ts","../src/decorators/foreign-key-decorator.ts","../src/decorators/hook-decorators.ts","../src/decorators/table-decorators.ts","../src/decorators/timestamp-decorators.ts"],"sourcesContent":["/**\n * Description of a column type: its SQL type and conversions between JavaScript values and the\n * values sent to / received from PostgreSQL.\n */\nexport type DataType = Readonly<{\n /** Sequelize v6 type key, e.g. `'STRING'`. */\n key: string;\n /** PostgreSQL column type, e.g. `'VARCHAR(255)'`. */\n sqlType: string;\n /** True for `JSON` and `JSONB`; enables nested JSON where conditions. */\n isJson?: boolean;\n /** True for `VIRTUAL`: the attribute is not stored in the database. */\n isVirtual?: boolean;\n /** Element type for `ARRAY` and `RANGE`. */\n subtype?: DataType;\n /** Allowed values for `ENUM`. */\n values?: readonly string[];\n /** SQL type that `where` parameters of this type are cast to (types PostgreSQL cannot infer from an untyped parameter). */\n bindCast?: string;\n /** Converts a value read from the driver into the attribute value. */\n parse?: (value: unknown) => unknown;\n /** Converts an attribute value into a driver parameter. */\n serialize?: (value: unknown) => unknown;\n}>;\n\n/** A data type used as is (`DataTypes.INTEGER`) or after calling it (`DataTypes.STRING(64)`). */\nexport type DataTypeInput = DataType | ((...args: never[]) => DataType);\n\n/**\n * Base of the built-in data type classes. Conversions (`parse`, `serialize`) are own function\n * properties, present only on types that convert values, so they can be read and called detached.\n *\n * @internal\n */\nexport abstract class AbstractDataType implements DataType {\n /** Sequelize v6 type key, e.g. `'STRING'`. */\n readonly key: string;\n /** PostgreSQL column type, e.g. `'VARCHAR(255)'`. */\n readonly sqlType: string;\n\n /**\n * @param key - Sequelize v6 type key.\n * @param sqlType - PostgreSQL column type.\n */\n constructor(key: string, sqlType: string) {\n this.key = key;\n this.sqlType = sqlType;\n }\n\n /**\n * Validates a numeric type parameter (length, precision, scale, srid) before it reaches SQL.\n *\n * @param name - Parameter name for the error message.\n * @param value - Parameter value.\n * @returns The value.\n */\n protected static integer(name: string, value: number): number {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(`${name} must be a non-negative integer, got ${String(value)}`);\n }\n return value;\n }\n\n /**\n * Resolves a data type given bare or called (`DataTypes.STRING` / `DataTypes.STRING(64)`).\n *\n * @param input - Data type or callable data type.\n * @returns The data type; a callable type carries the properties of its default form.\n */\n static from(input: DataTypeInput): DataType {\n return typeof input === 'function' ? (input as unknown as DataType) : input;\n }\n}\n","type Parsed = readonly (string | null | Parsed)[];\n\ntype State = Readonly<{ items: Parsed; index: number }>;\n\ntype Token = Readonly<{ value: string; index: number }>;\n\n/**\n * Parses PostgreSQL array literals (`{a,\"b c\",NULL}`, nested) into strings and nulls.\n *\n * @internal\n */\nexport class ArrayLiteralParser {\n /**\n * Parses an array literal.\n *\n * @param text - Array literal as returned by the driver.\n * @returns Elements (strings, `null`s and nested arrays); empty when `text` is not an array.\n */\n parse(text: string): Parsed {\n const open = text.indexOf('{');\n return open === -1 ? [] : this.#list(text, open + 1).items;\n }\n\n #unquoted(text: string, start: number): Token {\n const end = text.slice(start).search(/[,}]/);\n const stop = end === -1 ? text.length : start + end;\n return { value: text.slice(start, stop).trim(), index: stop };\n }\n\n #quoted(text: string, start: number): Token {\n const read = (index: number, value: string): Token =>\n text[index] === '\\\\'\n ? read(index + 2, value + (text[index + 1] ?? ''))\n : text[index] === '\"' || index >= text.length\n ? { value, index: index + 1 }\n : read(index + 1, value + text[index]);\n return read(start + 1, '');\n }\n\n #list(text: string, start: number): State {\n return this.#step(text, { items: [], index: start });\n }\n\n #step(text: string, state: State): State {\n const char = text[state.index];\n if (char === undefined || char === '}') {\n return { items: state.items, index: state.index + 1 };\n }\n if (char === ',' || char === ' ') {\n return this.#step(text, { ...state, index: state.index + 1 });\n }\n return this.#step(text, this.#element(text, state, char));\n }\n\n #element(text: string, state: State, char: string): State {\n if (char === '{') {\n const nested = this.#list(text, state.index + 1);\n return { items: [...state.items, nested.items], index: nested.index };\n }\n if (char === '\"') {\n const item = this.#quoted(text, state.index);\n return { items: [...state.items, item.value], index: item.index };\n }\n const item = this.#unquoted(text, state.index);\n return {\n items: [...state.items, item.value.toUpperCase() === 'NULL' ? null : item.value],\n index: item.index,\n };\n }\n}\n","import { AbstractDataType, type DataType, type DataTypeInput } from './abstract-data-type.ts';\nimport { ArrayLiteralParser } from './array-literal-parser.ts';\n\nconst arrayLiteral = new ArrayLiteralParser();\n\n/**\n * `type[]` (`DataTypes.ARRAY(DataTypes.TEXT)`).\n *\n * @internal\n */\nexport class ArrayType extends AbstractDataType {\n /** Element type. */\n readonly subtype: DataType;\n /** Converts a driver array literal into an array of strings. */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' ? arrayLiteral.parse(value) : value;\n /** Serializes every element; present only when the element type serializes values. */\n declare readonly serialize?: (value: unknown) => unknown;\n\n /**\n * @param subtype - Element type.\n */\n constructor(subtype: DataTypeInput) {\n const element = AbstractDataType.from(subtype);\n super('ARRAY', `${element.sqlType}[]`);\n this.subtype = element;\n if (element.serialize !== undefined) {\n this.serialize = (value: unknown) =>\n Array.isArray(value) ? value.map((item) => element.serialize?.(item)) : value;\n }\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `BIT(length)` / `BIT VARYING(length)` (`DataTypes.BIT`, `DataTypes.VARBIT`); values are strings\n * of `0` and `1`.\n *\n * @internal\n */\nexport class BitType extends AbstractDataType {\n /**\n * @param key - `'BIT'` or `'VARBIT'`.\n * @param length - Number of bits; `BIT` defaults to 1, `VARBIT` to unlimited.\n */\n constructor(key: 'BIT' | 'VARBIT', length?: number) {\n const sqlName = key === 'BIT' ? 'BIT' : 'BIT VARYING';\n super(\n key,\n length === undefined\n ? sqlName\n : `${sqlName}(${AbstractDataType.integer(`${key} length`, length)})`,\n );\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `BYTEA` (`DataTypes.BLOB`).\n *\n * @internal\n */\nexport class BlobType extends AbstractDataType {\n /**\n * @param _size - MySQL size; accepted for compatibility and ignored.\n */\n constructor(_size?: 'tiny' | 'medium' | 'long') {\n super('BLOB', 'BYTEA');\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `CHAR(length)` (`DataTypes.CHAR`).\n *\n * @internal\n */\nexport class CharType extends AbstractDataType {\n /**\n * @param length - Fixed length; default 255.\n */\n constructor(length = 255) {\n super('CHAR', `CHAR(${AbstractDataType.integer('CHAR length', length)})`);\n Object.freeze(this);\n }\n}\n","const LIMIT = 4096;\n\n/**\n * Quotes SQL identifiers (`\"name\"`, embedded quotes doubled). The quoted form of a name never\n * changes and the same few table and column names are quoted for every statement, so results are\n * remembered; the memo stops growing at a fixed size, so arbitrary user aliases cannot exhaust memory.\n */\nexport class IdentifierQuoter {\n readonly #quoted = new Map<string, string>();\n\n /**\n * Quotes an identifier.\n *\n * @param name - Identifier.\n * @returns `\"name\"` with embedded quotes doubled.\n */\n quote(name: string): string {\n const known = this.#quoted.get(name);\n if (known !== undefined) {\n return known;\n }\n const quoted = `\"${name.replaceAll('\"', '\"\"')}\"`;\n if (this.#quoted.size < LIMIT) {\n this.#quoted.set(name, quoted);\n }\n return quoted;\n }\n}\n","const pad = (value: number, width = 2): string => String(value).padStart(width, '0');\n\n/**\n * Formats dates as local wall-clock text, the stored form of `TIMESTAMP WITHOUT TIME ZONE`.\n *\n * @internal\n */\nexport class WallClock {\n /**\n * Formats a date in the process time zone.\n *\n * @param date - Date to format.\n * @returns `YYYY-MM-DD HH:MM:SS.mmm`.\n */\n format(date: Date): string {\n const day = `${pad(date.getFullYear(), 4)}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n return `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`;\n }\n}\n","import type { DataType } from './abstract-data-type.ts';\nimport { WallClock } from './wall-clock.ts';\n\nconst NUMERIC = new Set(['INTEGER', 'SMALLINT', 'TINYINT', 'MEDIUMINT', 'FLOAT', 'REAL', 'DOUBLE']);\nconst wallClock = new WallClock();\n\n/**\n * Converts single composite fields between JavaScript values and field text.\n *\n * @internal\n */\nexport class CompositeFields {\n /**\n * Converts field text read from a record into the field's value.\n *\n * @param field - Field type.\n * @param text - Field text, or `null` for NULL.\n * @returns The value.\n */\n fromText(field: DataType, text: string | null): unknown {\n if (text === null) {\n return null;\n }\n if (field.parse !== undefined) {\n return field.parse(text);\n }\n if (NUMERIC.has(field.key)) {\n return Number(text);\n }\n return this.#byKey(field.key, text);\n }\n\n /**\n * Converts a field value into field text.\n *\n * @param field - Field type.\n * @param value - Value; `null` / `undefined` are NULL.\n * @returns Field text, or `null` for NULL.\n * @throws Error for array values (not supported inside composites).\n */\n toText(field: DataType, value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n const converted = field.serialize === undefined ? value : field.serialize(value);\n if (field.isJson === true) {\n return JSON.stringify(value);\n }\n if (Array.isArray(converted)) {\n throw new Error('Composite fields do not support array values');\n }\n return this.#text(field, converted);\n }\n\n #byKey(key: string, text: string): unknown {\n switch (key) {\n case 'BOOLEAN':\n return text === 't';\n case 'DATE':\n return new Date(text);\n case 'BLOB':\n return Buffer.from(text.slice(2), 'hex');\n default:\n return key === 'JSON' || key === 'JSONB' ? JSON.parse(text) : text;\n }\n }\n\n #text(field: DataType, value: unknown): string {\n if (value instanceof Date) {\n return field.key === 'TIMESTAMP' ? wallClock.format(value) : value.toISOString();\n }\n if (typeof value === 'boolean') {\n return value ? 't' : 'f';\n }\n if (Buffer.isBuffer(value)) {\n return `\\\\x${value.toString('hex')}`;\n }\n return typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n}\n","const SPECIAL = /[\\s\"\\\\(),]/;\n\n/**\n * Reads and writes the text form of a composite value, `(1,\"a b\",)`.\n *\n * @internal\n */\nexport class RecordText {\n /**\n * Splits record text into field texts.\n *\n * @param text - Record text, e.g. `(1,\"say \"\"hi\"\"\",)`.\n * @returns One entry per field; `null` for an empty (NULL) field.\n */\n parse(text: string): (string | null)[] {\n const fields: (string | null)[] = [];\n const body = text.slice(1, -1);\n let index = 0;\n for (;;) {\n const [value, next] = body.startsWith('\"', index)\n ? this.#quoted(body, index + 1)\n : this.#plain(body, index);\n fields.push(value);\n if (next >= body.length) {\n return fields;\n }\n index = next + 1;\n }\n }\n\n /**\n * Writes field texts as record text.\n *\n * @param fields - Field texts; `null` is written as an empty field.\n * @returns Record text.\n */\n format(fields: readonly (string | null)[]): string {\n return `(${fields.map((field) => this.quote(field)).join(',')})`;\n }\n\n /**\n * Quotes one field when it needs it.\n *\n * @param field - Field text or `null`.\n * @returns Field text for use inside a record or array literal.\n */\n quote(field: string | null): string {\n if (field === null) {\n return '';\n }\n return field === '' || SPECIAL.test(field)\n ? `\"${field.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\"\"')}\"`\n : field;\n }\n\n #plain(body: string, from: number): [string | null, number] {\n const end = body.indexOf(',', from);\n const stop = end === -1 ? body.length : end;\n return [from === stop ? null : body.slice(from, stop), stop];\n }\n\n #quoted(body: string, from: number): [string, number] {\n let value = '';\n let index = from;\n while (index < body.length) {\n const char = body[index] ?? '';\n if (char === '\"' && body[index + 1] === '\"') {\n value += '\"';\n index += 2;\n } else if (char === '\"') {\n return [value, index + 1];\n } else {\n value += char === '\\\\' ? (body[++index] ?? '') : char;\n index += 1;\n }\n }\n return [value, index];\n }\n}\n","import { IdentifierQuoter } from '../sql/identifier-quoter.ts';\nimport { AbstractDataType, type DataType, type DataTypeInput } from './abstract-data-type.ts';\nimport { CompositeFields } from './composite-fields.ts';\nimport { RecordText } from './record-text.ts';\n\nconst quoter = new IdentifierQuoter();\nconst records = new RecordText();\nconst fieldCodec = new CompositeFields();\n\n/** Value of a composite column: an object keyed by field name. */\nexport type CompositeValue = Readonly<Record<string, unknown>>;\n\n/**\n * Composite type (`DataTypes.COMPOSITE('address', { street: DataTypes.TEXT, zip: DataTypes.INTEGER })`);\n * values are objects keyed by field name.\n *\n * @internal\n */\nexport class CompositeType extends AbstractDataType {\n /** SQL type that `where` parameters are cast to. */\n readonly bindCast: string;\n /** Field types by name, in declaration order. */\n readonly fields: Readonly<Record<string, DataType>>;\n /** Converts driver record text into an object. */\n readonly parse = (value: unknown): unknown => this.#parse(value);\n /** Converts an object into record text bound as one parameter. */\n readonly serialize = (value: unknown): unknown => this.#serialize(value);\n readonly #names: readonly string[];\n readonly #name: string;\n\n /**\n * @param name - Name of the composite type (quoted as one identifier).\n * @param fields - Field types by field name.\n * @throws Error when there are no fields.\n */\n constructor(name: string, fields: Readonly<Record<string, DataTypeInput>>) {\n const names = Object.keys(fields);\n if (names.length === 0) {\n throw new Error('COMPOSITE needs at least one field');\n }\n super('COMPOSITE', quoter.quote(name));\n this.bindCast = this.sqlType;\n this.#name = name;\n this.#names = names;\n this.fields = Object.fromEntries(\n names.map((field) => [field, AbstractDataType.from(fields[field] as DataTypeInput)]),\n );\n Object.freeze(this);\n }\n\n /**\n * SQL that creates the type; run it once with `sequelize.query()` before `sync()`.\n *\n * @returns `CREATE TYPE \"name\" AS (\"field\" TYPE, …)` with quoted names.\n */\n createSql(): string {\n const columns = this.#names.map(\n (field) => `${quoter.quote(field)} ${this.fields[field]?.sqlType ?? ''}`,\n );\n return `CREATE TYPE ${quoter.quote(this.#name)} AS (${columns.join(', ')})`;\n }\n\n #serialize(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return value;\n }\n const source = value as CompositeValue;\n return records.format(\n this.#names.map((field) => fieldCodec.toText(this.fields[field] as DataType, source[field])),\n );\n }\n\n #parse(value: unknown): unknown {\n if (typeof value !== 'string' || !value.startsWith('(')) {\n return value;\n }\n const texts = records.parse(value);\n return Object.fromEntries(\n this.#names.map((field, index) => [\n field,\n fieldCodec.fromText(this.fields[field] as DataType, texts[index] ?? null),\n ]),\n );\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `TIMESTAMP WITH TIME ZONE` (`DataTypes.DATE`); values are `Date` objects.\n *\n * @internal\n */\nexport class DateType extends AbstractDataType {\n /** Converts a driver string into a `Date`. */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' ? new Date(value) : value;\n\n /**\n * @param fsp - Fractional seconds precision.\n */\n constructor(fsp?: number) {\n super(\n 'DATE',\n fsp === undefined\n ? 'TIMESTAMP WITH TIME ZONE'\n : `TIMESTAMP(${AbstractDataType.integer('DATE precision', fsp)}) WITH TIME ZONE`,\n );\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `DECIMAL(precision, scale)` (`DataTypes.DECIMAL`, `DataTypes.NUMBER`); values are strings.\n *\n * @internal\n */\nexport class DecimalType extends AbstractDataType {\n /**\n * @param digits - Precision.\n * @param scale - Scale.\n */\n constructor(digits?: number, scale?: number) {\n super(\n 'DECIMAL',\n digits === undefined\n ? 'DECIMAL'\n : `DECIMAL(${[digits, scale]\n .filter((n) => n !== undefined)\n .map((n) => AbstractDataType.integer('DECIMAL precision and scale', n))\n .join(',')})`,\n );\n Object.freeze(this);\n }\n}\n","/**\n * Default value marker (`DataTypes.NOW`, `DataTypes.UUIDV4`): generates a value on the client when a\n * row is built.\n */\nexport class DefaultValueGenerator {\n /** Sequelize v6 type key, e.g. `'UUIDV4'`. */\n readonly key: string;\n /** Produces the default value. */\n readonly generate: () => unknown;\n\n /**\n * @param key - Sequelize v6 type key.\n * @param generate - Produces the default value.\n */\n constructor(key: string, generate: () => unknown) {\n this.key = key;\n this.generate = generate;\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/** Arguments of `DataTypes.ENUM`: values, arrays of values or `{ values }`. */\ntype EnumArgument = string | readonly string[] | Readonly<{ values: readonly string[] }>;\n\n/**\n * Enumerated values (`DataTypes.ENUM`).\n *\n * @internal\n */\nexport class EnumType extends AbstractDataType {\n /** Allowed values. */\n readonly values: readonly string[];\n\n /**\n * @param args - Values, arrays of values or `{ values }`, in any combination.\n */\n constructor(...args: readonly EnumArgument[]) {\n super('ENUM', 'ENUM');\n this.values = args.flatMap((arg) =>\n typeof arg === 'string'\n ? [arg]\n : Array.isArray(arg)\n ? arg\n : (arg as Readonly<{ values: readonly string[] }>).values,\n );\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `FLOAT(precision)` (`DataTypes.FLOAT`).\n *\n * @internal\n */\nexport class FloatType extends AbstractDataType {\n /**\n * @param digits - Precision.\n */\n constructor(digits?: number) {\n super(\n 'FLOAT',\n digits === undefined\n ? 'FLOAT'\n : `FLOAT(${AbstractDataType.integer('FLOAT precision', digits)})`,\n );\n Object.freeze(this);\n }\n}\n","/** A `point` value. */\nexport type GeoPoint = Readonly<{\n /** Horizontal coordinate. */\n x: number;\n /** Vertical coordinate. */\n y: number;\n}>;\n\nconst NUMBER = /-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?|-?Infinity|NaN/gi;\n\n/**\n * Reads and writes the text form of geometric values.\n *\n * @internal\n */\nexport class GeometricText {\n /**\n * Extracts the numbers of a geometric literal, e.g. `((1,2),(3,4))` → `[1, 2, 3, 4]`.\n *\n * @param text - Literal returned by PostgreSQL.\n * @returns Numbers in order of appearance.\n */\n numbers(text: string): number[] {\n return (text.match(NUMBER) ?? []).map(Number);\n }\n\n /**\n * Groups numbers into points.\n *\n * @param values - Flat coordinates.\n * @returns One point per pair.\n */\n points(values: readonly number[]): GeoPoint[] {\n const result: GeoPoint[] = [];\n for (let index = 0; index + 1 < values.length; index += 2) {\n result.push({ x: values[index] ?? 0, y: values[index + 1] ?? 0 });\n }\n return result;\n }\n\n /**\n * Validates a coordinate before it is formatted.\n *\n * @param value - Coordinate.\n * @returns The value as text.\n * @throws Error when the value is not a finite number.\n */\n number(value: unknown): string {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`Geometric coordinates must be finite numbers, got ${String(value)}`);\n }\n return String(value);\n }\n\n /**\n * Formats a point as `(x,y)`.\n *\n * @param value - Point-like value.\n * @returns Point text.\n */\n point(value: unknown): string {\n const point = this.#object(value);\n return `(${this.number(point['x'])},${this.number(point['y'])})`;\n }\n\n /**\n * Formats a list of points as `(x,y),(x,y)`.\n *\n * @param value - Array of points.\n * @returns Comma-joined point text.\n */\n list(value: unknown): string {\n if (!Array.isArray(value)) {\n throw new Error('Expected an array of points');\n }\n return value.map((item) => this.point(item)).join(',');\n }\n\n /**\n * Formats a pair of points (`lseg`, `box`).\n *\n * @param value - Array of exactly two points.\n * @returns Comma-joined point text.\n */\n pair(value: unknown): string {\n if (!Array.isArray(value) || value.length !== 2) {\n throw new Error('Expected an array of two points');\n }\n return this.list(value);\n }\n\n #object(value: unknown): Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n throw new Error(`Expected an object, got ${String(value)}`);\n }\n return value as Record<string, unknown>;\n }\n\n /**\n * Narrows a value to an object for field access.\n *\n * @param value - Value to check.\n * @returns The value as a record.\n */\n fields(value: unknown): Record<string, unknown> {\n return this.#object(value);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\nimport { GeometricText, type GeoPoint } from './geometric-text.ts';\n\n/** Keys of the geometric data types. */\nexport type GeometricKey = 'POINT' | 'LINE' | 'LSEG' | 'BOX' | 'PATH' | 'POLYGON' | 'CIRCLE';\n\n/** `path` value: `closed` paths are written `( … )`, open ones `[ … ]`. */\nexport type GeoPath = Readonly<{\n /** Vertices in order. */\n points: readonly GeoPoint[];\n /** True for a closed path. */\n closed: boolean;\n}>;\n/** `line` value: the line `a·x + b·y + c = 0`. */\nexport type GeoLine = Readonly<{\n /** Coefficient of `x`. */\n a: number;\n /** Coefficient of `y`. */\n b: number;\n /** Constant term. */\n c: number;\n}>;\n/** `circle` value: center and radius. */\nexport type GeoCircle = Readonly<{\n /** Center x. */\n x: number;\n /** Center y. */\n y: number;\n /** Radius. */\n radius: number;\n}>;\n\ntype Codec = Readonly<{\n parse: (numbers: number[], text: string) => unknown;\n format: (value: unknown) => string;\n}>;\n\nconst text = new GeometricText();\n\nconst CODECS: Readonly<Record<GeometricKey, Codec>> = {\n POINT: {\n parse: (n) => text.points(n)[0],\n format: (value) => text.point(value),\n },\n LINE: {\n parse: ([a = 0, b = 0, c = 0]) => ({ a, b, c }),\n format: (value) => {\n const line = text.fields(value);\n return `{${text.number(line['a'])},${text.number(line['b'])},${text.number(line['c'])}}`;\n },\n },\n LSEG: {\n parse: (n) => text.points(n),\n format: (value) => `[${text.pair(value)}]`,\n },\n BOX: {\n parse: (n) => text.points(n),\n format: (value) => text.pair(value),\n },\n PATH: {\n parse: (n, literal) => ({ points: text.points(n), closed: !literal.startsWith('[') }),\n format: (value) => {\n const path = text.fields(value);\n const points = text.list(path['points']);\n return path['closed'] === false ? `[${points}]` : `(${points})`;\n },\n },\n POLYGON: {\n parse: (n) => text.points(n),\n format: (value) => `(${text.list(value)})`,\n },\n CIRCLE: {\n parse: ([x = 0, y = 0, radius = 0]) => ({ x, y, radius }),\n format: (value) => {\n const circle = text.fields(value);\n return `<${text.point(circle)},${text.number(circle['radius'])}>`;\n },\n },\n};\n\n/**\n * Geometric types (`DataTypes.POINT`, `LINE`, `LSEG`, `BOX`, `PATH`, `POLYGON`, `CIRCLE`); values\n * are plain objects and arrays of points.\n *\n * @internal\n */\nexport class GeometricType extends AbstractDataType {\n /** Converts a driver literal into the value shape; non-text values are kept. */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' ? CODECS[this.#key].parse(text.numbers(value), value.trim()) : value;\n /** Converts a value into a literal bound as one parameter; text and `null` are kept. */\n readonly serialize = (value: unknown): unknown =>\n value === null || value === undefined || typeof value === 'string'\n ? value\n : CODECS[this.#key].format(value);\n readonly #key: GeometricKey;\n\n /**\n * @param key - Geometric type key; also the SQL type name.\n */\n constructor(key: GeometricKey) {\n super(key, key);\n this.#key = key;\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/** Key/value pairs of an `HSTORE` column: values are strings, or `null` for SQL `NULL`. */\nexport type HstoreValue = Readonly<Record<string, string | null>>;\n\nconst PAIR = /\"((?:[^\"\\\\]|\\\\.)*)\"\\s*=>\\s*(?:NULL|\"((?:[^\"\\\\]|\\\\.)*)\")/g;\n\n/**\n * `HSTORE` (`DataTypes.HSTORE`); values are plain objects, like Sequelize v6 with `pg-hstore`.\n *\n * @internal\n */\nexport class HstoreType extends AbstractDataType {\n /** Converts hstore text into an object; values are strings or `null`. */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' ? HstoreType.#parse(value) : value;\n /** Converts an object into hstore text; non-object values (e.g. hstore text) are kept. */\n readonly serialize = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n ? HstoreType.#serialize(value)\n : value;\n\n constructor() {\n super('HSTORE', 'HSTORE');\n Object.freeze(this);\n }\n\n static #quote(text: string): string {\n return `\"${text.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`;\n }\n\n static #unquote(text: string): string {\n return text.replaceAll(/\\\\(.)/g, '$1');\n }\n\n static #text(value: unknown): string {\n return typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n static #serialize(value: object): string {\n return Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .map(\n ([key, item]) =>\n `${HstoreType.#quote(key)}=>${item === null ? 'NULL' : HstoreType.#quote(HstoreType.#text(item))}`,\n )\n .join(',');\n }\n\n static #parse(text: string): Record<string, string | null> {\n const result: Record<string, string | null> = {};\n for (const match of text.matchAll(PAIR)) {\n result[HstoreType.#unquote(match[1] ?? '')] =\n match[2] === undefined ? null : HstoreType.#unquote(match[2]);\n }\n return result;\n }\n}\n","import { AbstractDataType, type DataType } from './abstract-data-type.ts';\n\n/** Integer type with Sequelize v6 MySQL-only modifiers kept as no-ops for compatibility. */\nexport type IntegerDataType = DataType &\n Readonly<{\n /** No-op in PostgreSQL, kept for Sequelize v6 compatibility. */\n UNSIGNED: IntegerDataType;\n /** No-op in PostgreSQL, kept for Sequelize v6 compatibility. */\n ZEROFILL: IntegerDataType;\n }>;\n\n/**\n * Integer types (`INTEGER`, `BIGINT`, `SMALLINT`, ...).\n *\n * @internal\n */\nexport class IntegerType extends AbstractDataType implements IntegerDataType {\n /**\n * @param key - Sequelize v6 type key.\n * @param sqlType - PostgreSQL column type.\n */\n constructor(key: string, sqlType: string) {\n super(key, sqlType);\n Object.freeze(this);\n }\n\n /** No-op in PostgreSQL, kept for Sequelize v6 compatibility. */\n get UNSIGNED(): this {\n return this;\n }\n\n /** No-op in PostgreSQL, kept for Sequelize v6 compatibility. */\n get ZEROFILL(): this {\n return this;\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `JSON` / `JSONB`; values are serialized to JSON text.\n *\n * @internal\n */\nexport class JsonType extends AbstractDataType {\n /** Enables nested JSON where conditions. */\n readonly isJson = true;\n /** Converts a value into JSON text (`null` / `undefined` are kept). */\n readonly serialize = (value: unknown): unknown =>\n value === null || value === undefined ? value : JSON.stringify(value);\n\n /**\n * @param key - `'JSON'` or `'JSONB'` (also the SQL type).\n */\n constructor(key: 'JSON' | 'JSONB') {\n super(key, key);\n Object.freeze(this);\n }\n}\n","import { AbstractDataType, type DataType, type DataTypeInput } from './abstract-data-type.ts';\nimport { WallClock } from './wall-clock.ts';\n\nconst wallClock = new WallClock();\n\n/** Range bound as returned by Sequelize v6 for `RANGE` attributes. */\nexport type RangeBound<T> = Readonly<{\n /** Bound value; `null` for an unbounded side. */\n value: T | null;\n /** Whether the bound itself is part of the range. */\n inclusive: boolean;\n}>;\n\nconst RANGE_SQL_TYPES: Readonly<Record<string, string>> = {\n INTEGER: 'INT4RANGE',\n BIGINT: 'INT8RANGE',\n DECIMAL: 'NUMRANGE',\n TIMESTAMP: 'TSRANGE',\n DATE: 'TSTZRANGE',\n DATEONLY: 'DATERANGE',\n};\n\nconst RANGE_PATTERN = /^([[(])\"?(.*?)\"?,\"?(.*?)\"?([\\])])$/;\n\n/**\n * Range type (`DataTypes.RANGE(DataTypes.INTEGER)` → `INT4RANGE`); values are\n * `[lower, upper]` pairs of {@link RangeBound}s, like Sequelize v6.\n *\n * @internal\n */\nexport class RangeType extends AbstractDataType {\n /** Element type. */\n readonly subtype: DataType;\n /** Converts a driver range literal into a pair of bounds (`[]` for `empty`). */\n readonly parse = (value: unknown): unknown => this.#parse(value);\n /** Converts a pair of values or bounds into a range literal. */\n readonly serialize = (value: unknown): unknown => this.#serialize(value);\n readonly #parseBound: ((value: unknown) => unknown) | undefined;\n\n /**\n * @param subtype - Element type: `INTEGER`, `BIGINT`, `DECIMAL`, `TIMESTAMP`, `DATE` or `DATEONLY`.\n * @throws Error for any other element type.\n */\n constructor(subtype: DataTypeInput) {\n const element = AbstractDataType.from(subtype);\n const sqlType = RANGE_SQL_TYPES[element.key];\n if (sqlType === undefined) {\n throw new Error(`RANGE does not support subtype ${element.key}`);\n }\n super('RANGE', sqlType);\n this.subtype = element;\n this.#parseBound =\n element.key === 'INTEGER' || element.key === 'BIGINT'\n ? (raw) => (typeof raw === 'string' ? Number.parseInt(raw, 10) : raw)\n : element.parse;\n Object.freeze(this);\n }\n\n #serialize(value: unknown): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n if (value.length === 0) {\n return 'empty';\n }\n const lower = this.#toBound(value[0], true);\n const upper = this.#toBound(value[1], false);\n return `${lower.inclusive ? '[' : '('}${this.#formatBound(lower)},${this.#formatBound(upper)}${upper.inclusive ? ']' : ')'}`;\n }\n\n #toBound(bound: unknown, inclusive: boolean): RangeBound<unknown> {\n return typeof bound === 'object' && bound !== null && 'value' in bound && 'inclusive' in bound\n ? (bound as RangeBound<unknown>)\n : { value: bound ?? null, inclusive };\n }\n\n #formatBound(bound: RangeBound<unknown>): string {\n if (bound.value instanceof Date) {\n return this.subtype.key === 'TIMESTAMP'\n ? wallClock.format(bound.value)\n : bound.value.toISOString();\n }\n return bound.value === null ? '' : String(bound.value);\n }\n\n #parse(value: unknown): unknown {\n if (typeof value !== 'string') {\n return value;\n }\n if (value === 'empty') {\n return [];\n }\n const match = RANGE_PATTERN.exec(value);\n if (match === null) {\n return value;\n }\n const [, open, low = '', high = '', close] = match;\n return [\n { value: this.#parseBoundValue(low), inclusive: open === '[' },\n { value: this.#parseBoundValue(high), inclusive: close === ']' },\n ];\n }\n\n #parseBoundValue(raw: string): unknown {\n return raw === '' ? null : this.#parseBound === undefined ? raw : this.#parseBound(raw);\n }\n}\n","import { AbstractDataType, type DataTypeInput } from './abstract-data-type.ts';\nimport { RangeType } from './range-type.ts';\n\nconst MULTIRANGE_SQL_TYPES: Readonly<Record<string, string>> = {\n INT4RANGE: 'INT4MULTIRANGE',\n INT8RANGE: 'INT8MULTIRANGE',\n NUMRANGE: 'NUMMULTIRANGE',\n TSRANGE: 'TSMULTIRANGE',\n TSTZRANGE: 'TSTZMULTIRANGE',\n DATERANGE: 'DATEMULTIRANGE',\n};\n\n/**\n * Multirange type (`DataTypes.MULTIRANGE(DataTypes.INTEGER)` → `INT4MULTIRANGE`, PostgreSQL 14+);\n * values are arrays of ranges, each a `[lower, upper]` pair like {@link RangeType} values.\n *\n * @internal\n */\nexport class MultirangeType extends AbstractDataType {\n /** Converts a driver multirange literal into an array of ranges (`[]` for `{}`). */\n readonly parse = (value: unknown): unknown => this.#parse(value);\n /** Converts an array of ranges into a multirange literal. */\n readonly serialize = (value: unknown): unknown => this.#serialize(value);\n readonly #range: RangeType;\n\n /**\n * @param subtype - Element type: `INTEGER`, `BIGINT`, `DECIMAL`, `TIMESTAMP`, `DATE` or `DATEONLY`.\n * @throws Error for any other element type.\n */\n constructor(subtype: DataTypeInput) {\n const range = new RangeType(subtype);\n super('MULTIRANGE', MULTIRANGE_SQL_TYPES[range.sqlType] ?? range.sqlType);\n this.#range = range;\n Object.freeze(this);\n }\n\n #serialize(value: unknown): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n return `{${value.map((range) => String(this.#range.serialize(range))).join(',')}}`;\n }\n\n #parse(value: unknown): unknown {\n if (typeof value !== 'string' || !value.startsWith('{')) {\n return value;\n }\n return MultirangeType.#split(value.slice(1, -1)).map((text) => this.#range.parse(text));\n }\n\n /** Splits at the commas that are outside brackets and quotes. */\n static #split(body: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let quoted = false;\n let start = 0;\n for (const [index, char] of [...body].entries()) {\n quoted = char === '\"' ? !quoted : quoted;\n depth += quoted ? 0 : '[('.includes(char) ? 1 : '])'.includes(char) ? -1 : 0;\n if (char === ',' && depth === 0 && !quoted) {\n parts.push(body.slice(start, index));\n start = index + 1;\n }\n }\n return body === '' ? [] : [...parts, body.slice(start)];\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * Type without parameters or value conversions (`BOOLEAN`, `UUID`, `INET`, ...).\n *\n * @internal\n */\nexport class ScalarType extends AbstractDataType {\n /**\n * @param key - Sequelize v6 type key.\n * @param sqlType - PostgreSQL column type.\n */\n constructor(key: string, sqlType: string) {\n super(key, sqlType);\n Object.freeze(this);\n }\n}\n","/** GeoJSON geometry as produced by the EWKB reader. */\nexport type GeoJsonGeometry = Readonly<Record<string, unknown>>;\n\nconst HAS_Z = 0x80000000;\nconst HAS_M = 0x40000000;\nconst HAS_SRID = 0x20000000;\n\nclass Cursor {\n little = true;\n offset = 0;\n readonly #bytes: Buffer;\n\n constructor(bytes: Buffer) {\n this.#bytes = bytes;\n }\n\n byte(): number {\n return this.#bytes.readUInt8(this.offset++);\n }\n\n uint32(): number {\n const value = this.little\n ? this.#bytes.readUInt32LE(this.offset)\n : this.#bytes.readUInt32BE(this.offset);\n this.offset += 4;\n return value;\n }\n\n float64(): number {\n const value = this.little\n ? this.#bytes.readDoubleLE(this.offset)\n : this.#bytes.readDoubleBE(this.offset);\n this.offset += 8;\n return value;\n }\n}\n\ntype Header = Readonly<{ type: number; z: boolean; m: boolean; srid: number | undefined }>;\n\n/**\n * Reads hex-encoded EWKB (what PostGIS sends for `geometry` and `geography`) into GeoJSON.\n *\n * @internal\n */\nexport class EwkbReader {\n /**\n * Parses hex EWKB.\n *\n * @param hex - Hex string of an EWKB geometry.\n * @returns GeoJSON geometry; `crs` is set (`EPSG:<srid>`) when the EWKB carries an SRID, like v6.\n * @throws Error for a geometry type this reader does not support (curves, TIN, …).\n */\n parse(hex: string): GeoJsonGeometry {\n const cursor = new Cursor(Buffer.from(hex, 'hex'));\n const header = this.#header(cursor);\n const geometry = this.#geometry(cursor, header);\n return header.srid === undefined\n ? geometry\n : { ...geometry, crs: { type: 'name', properties: { name: `EPSG:${header.srid}` } } };\n }\n\n #header(cursor: Cursor): Header {\n cursor.little = cursor.byte() === 1;\n const raw = cursor.uint32();\n const srid = (raw & HAS_SRID) === 0 ? undefined : cursor.uint32();\n return { type: raw & 0xff, z: (raw & HAS_Z) !== 0, m: (raw & HAS_M) !== 0, srid };\n }\n\n #geometry(cursor: Cursor, header: Header): GeoJsonGeometry {\n const names = [\n '',\n 'Point',\n 'LineString',\n 'Polygon',\n 'MultiPoint',\n 'MultiLineString',\n 'MultiPolygon',\n 'GeometryCollection',\n ];\n const type = names[header.type];\n if (type === undefined || type === '') {\n throw new Error(`Unsupported EWKB geometry type ${header.type}`);\n }\n if (header.type === 7) {\n return { type, geometries: this.#members(cursor) };\n }\n return { type, coordinates: this.#coordinates(cursor, header) };\n }\n\n #coordinates(cursor: Cursor, header: Header): unknown {\n switch (header.type) {\n case 1:\n return this.#position(cursor, header);\n case 2:\n return this.#list(cursor, () => this.#position(cursor, header));\n case 3:\n return this.#list(cursor, () => this.#list(cursor, () => this.#position(cursor, header)));\n default:\n return this.#members(cursor).map((member) => member['coordinates']);\n }\n }\n\n #members(cursor: Cursor): GeoJsonGeometry[] {\n return this.#list(cursor, () => {\n const header = this.#header(cursor);\n return this.#geometry(cursor, header);\n });\n }\n\n #list<T>(cursor: Cursor, item: () => T): T[] {\n const count = cursor.uint32();\n return Array.from({ length: count }, item);\n }\n\n #position(cursor: Cursor, header: Header): number[] {\n const position = [cursor.float64(), cursor.float64()];\n if (header.z) {\n position.push(cursor.float64());\n }\n if (header.m) {\n cursor.float64();\n }\n return Number.isNaN(position[0]) ? [] : position;\n }\n}\n","const HAS_Z = 0x80000000;\nconst HAS_SRID = 0x20000000;\nconst DEFAULT_SRID = 4326;\n\nconst TYPE_CODES: Readonly<Record<string, number>> = {\n Point: 1,\n LineString: 2,\n Polygon: 3,\n MultiPoint: 4,\n MultiLineString: 5,\n MultiPolygon: 6,\n GeometryCollection: 7,\n};\n\ntype Geometry = Readonly<Record<string, unknown>>;\n\n/**\n * Writes GeoJSON as hex-encoded EWKB, which `geometry` and `geography` accept as text input, so a\n * value is one bound parameter.\n *\n * @internal\n */\nexport class EwkbWriter {\n readonly #parts: Buffer[] = [];\n\n /**\n * Converts a GeoJSON geometry to hex EWKB.\n *\n * @param value - GeoJSON geometry object; `crs` (`EPSG:<srid>`) sets the SRID, default 4326.\n * @returns Hex EWKB.\n * @throws Error for an unknown geometry type or malformed coordinates.\n */\n write(value: unknown): string {\n const geometry = this.#object(value);\n const z = this.#hasZ(geometry);\n this.#geometry(geometry, z, this.#srid(geometry));\n return Buffer.concat(this.#parts.splice(0)).toString('hex');\n }\n\n #object(value: unknown): Geometry {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('Expected a GeoJSON geometry object');\n }\n return value as Geometry;\n }\n\n #srid(geometry: Geometry): number {\n const crs = geometry['crs'] as { properties?: { name?: unknown } } | undefined;\n const name = crs?.properties?.name;\n const match = typeof name === 'string' ? /EPSG:+(\\d+)$/.exec(name) : null;\n return match === null ? DEFAULT_SRID : Number(match[1]);\n }\n\n #hasZ(geometry: Geometry): boolean {\n let node: unknown = geometry['coordinates'] ?? (geometry['geometries'] as unknown[])?.[0];\n while (Array.isArray(node) && typeof node[0] !== 'number' && node.length > 0) {\n node = node[0];\n }\n if (node !== null && typeof node === 'object' && !Array.isArray(node)) {\n return this.#hasZ(node as Geometry);\n }\n return Array.isArray(node) && node.length === 3;\n }\n\n #geometry(geometry: Geometry, z: boolean, srid?: number): void {\n const code = TYPE_CODES[String(geometry['type'])];\n if (code === undefined) {\n throw new Error(`Unsupported GeoJSON geometry type ${String(geometry['type'])}`);\n }\n this.#parts.push(\n Buffer.from([1]),\n this.#uint32((code | (z ? HAS_Z : 0) | (srid === undefined ? 0 : HAS_SRID)) >>> 0),\n );\n if (srid !== undefined) {\n this.#parts.push(this.#uint32(srid));\n }\n this.#body(code, geometry, z);\n }\n\n #body(code: number, geometry: Geometry, z: boolean): void {\n if (code === 7) {\n this.#items(geometry['geometries'], (member) => this.#geometry(this.#object(member), z));\n } else if (code === 1) {\n this.#position(geometry['coordinates'], z);\n } else if (code === 2) {\n this.#items(geometry['coordinates'], (position) => this.#position(position, z));\n } else if (code === 3) {\n this.#items(geometry['coordinates'], (ring) =>\n this.#items(ring, (position) => this.#position(position, z)),\n );\n } else {\n this.#items(geometry['coordinates'], (member) =>\n this.#geometry({ type: String(geometry['type']).slice(5), coordinates: member }, z),\n );\n }\n }\n\n #items(value: unknown, write: (item: unknown) => void): void {\n if (!Array.isArray(value)) {\n throw new TypeError('GeoJSON coordinates must be arrays');\n }\n this.#parts.push(this.#uint32(value.length));\n value.forEach(write);\n }\n\n #position(value: unknown, z: boolean): void {\n const valid = Array.isArray(value) && value.length === (z ? 3 : 2);\n if (!valid || !value.every((item) => typeof item === 'number' && Number.isFinite(item))) {\n throw new Error('GeoJSON positions must be arrays of finite numbers of equal length');\n }\n for (const coordinate of value as number[]) {\n const bytes = Buffer.alloc(8);\n bytes.writeDoubleLE(coordinate);\n this.#parts.push(bytes);\n }\n }\n\n #uint32(value: number): Buffer {\n const bytes = Buffer.alloc(4);\n bytes.writeUInt32LE(value);\n return bytes;\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\nimport { EwkbReader } from './ewkb-reader.ts';\nimport { EwkbWriter } from './ewkb-writer.ts';\n\nconst HEX_EWKB = /^(?:[0-9a-fA-F]{2})+$/;\n\n/**\n * PostGIS `GEOMETRY(type, srid)` / `GEOGRAPHY(type, srid)`; values are GeoJSON geometry objects\n * (reading hex EWKB, writing hex EWKB), like Sequelize v6.\n *\n * @internal\n */\nexport class SpatialType extends AbstractDataType {\n /** Converts hex EWKB into GeoJSON; other values (WKT, objects) are kept. */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' && HEX_EWKB.test(value) ? new EwkbReader().parse(value) : value;\n /** Converts a GeoJSON object into hex EWKB bound as one parameter; text is kept. */\n readonly serialize = (value: unknown): unknown =>\n typeof value === 'object' && value !== null ? new EwkbWriter().write(value) : value;\n\n static #shape(shape: string): string {\n if (!/^[A-Za-z][A-Za-z0-9]*$/.test(shape)) {\n throw new Error(`Invalid spatial type: ${shape}`);\n }\n return shape;\n }\n\n /**\n * @param key - `'GEOMETRY'` or `'GEOGRAPHY'` (also the SQL type name).\n * @param shape - Geometry type, e.g. `'POINT'`.\n * @param srid - Spatial reference id.\n */\n constructor(key: 'GEOMETRY' | 'GEOGRAPHY', shape?: string, srid?: number) {\n super(\n key,\n shape === undefined\n ? key\n : `${key}(${SpatialType.#shape(shape)}${srid === undefined ? '' : `,${AbstractDataType.integer(`${key} srid`, srid)}`})`,\n );\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `VARCHAR(length)` (`DataTypes.STRING`).\n *\n * @internal\n */\nexport class StringType extends AbstractDataType {\n /**\n * @param length - Maximum length; default 255.\n */\n constructor(length = 255) {\n super('STRING', `VARCHAR(${AbstractDataType.integer('STRING length', length)})`);\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `TEXT` (`DataTypes.TEXT`).\n *\n * @internal\n */\nexport class TextType extends AbstractDataType {\n /**\n * @param _size - MySQL size; accepted for compatibility and ignored.\n */\n constructor(_size?: 'tiny' | 'medium' | 'long') {\n super('TEXT', 'TEXT');\n Object.freeze(this);\n }\n}\n","import { AbstractDataType } from './abstract-data-type.ts';\n\n/**\n * `TIMESTAMP WITHOUT TIME ZONE` (`DataTypes.TIMESTAMP`); values are `Date` objects whose local\n * wall-clock time is the stored time.\n *\n * @internal\n */\nexport class TimestampType extends AbstractDataType {\n /** Converts a driver string into a `Date` (local time). */\n readonly parse = (value: unknown): unknown =>\n typeof value === 'string' ? new Date(value) : value;\n\n /**\n * @param fsp - Fractional seconds precision.\n */\n constructor(fsp?: number) {\n super(\n 'TIMESTAMP',\n fsp === undefined\n ? 'TIMESTAMP WITHOUT TIME ZONE'\n : `TIMESTAMP(${AbstractDataType.integer('TIMESTAMP precision', fsp)}) WITHOUT TIME ZONE`,\n );\n Object.freeze(this);\n }\n}\n","import { AbstractDataType, type DataTypeInput } from './abstract-data-type.ts';\n\n/**\n * Attribute that is not stored in the database (`DataTypes.VIRTUAL`).\n *\n * @internal\n */\nexport class VirtualType extends AbstractDataType {\n /** The attribute is not stored in the database. */\n readonly isVirtual = true;\n\n /**\n * @param returnType - Type of the computed value.\n * @param _fields - Dependency fields; accepted for compatibility and ignored.\n */\n constructor(returnType?: DataTypeInput, _fields?: readonly string[]) {\n super(\n 'VIRTUAL',\n returnType === undefined ? 'VIRTUAL' : AbstractDataType.from(returnType).sqlType,\n );\n Object.freeze(this);\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { DataType, DataTypeInput } from './abstract-data-type.ts';\nimport { ArrayType } from './array-type.ts';\nimport { BitType } from './bit-type.ts';\nimport { BlobType } from './blob-type.ts';\nimport { CharType } from './char-type.ts';\nimport { CompositeType } from './composite-type.ts';\nimport { DateType } from './date-type.ts';\nimport { DecimalType } from './decimal-type.ts';\nimport { DefaultValueGenerator } from './default-value-generator.ts';\nimport { EnumType } from './enum-type.ts';\nimport { FloatType } from './float-type.ts';\nimport { GeometricType } from './geometric-type.ts';\nimport { HstoreType } from './hstore-type.ts';\nimport { IntegerType } from './integer-type.ts';\nimport { JsonType } from './json-type.ts';\nimport { MultirangeType } from './multirange-type.ts';\nimport { RangeType } from './range-type.ts';\nimport { ScalarType } from './scalar-type.ts';\nimport { SpatialType } from './spatial-type.ts';\nimport { StringType } from './string-type.ts';\nimport { TextType } from './text-type.ts';\nimport { TimestampType } from './timestamp-type.ts';\nimport { VirtualType } from './virtual-type.ts';\n\nexport type { DataType, DataTypeInput } from './abstract-data-type.ts';\nexport type { GeoCircle, GeoLine, GeoPath } from './geometric-type.ts';\nexport type { GeoPoint } from './geometric-text.ts';\nexport type { CompositeValue } from './composite-type.ts';\nexport type { HstoreValue } from './hstore-type.ts';\nexport type { IntegerDataType } from './integer-type.ts';\nexport type { RangeBound } from './range-type.ts';\nexport type { DefaultValueGenerator } from './default-value-generator.ts';\n\n/** Makes a type usable both bare and called, like `DataTypes.STRING` and `DataTypes.STRING(64)`. */\nconst callable = <A extends unknown[], T extends DataType>(\n build: (...args: A) => T,\n bare: T,\n): ((...args: A) => T) & T => Object.freeze(Object.assign((...args: A) => build(...args), bare));\n\nconst INTEGER = new IntegerType('INTEGER', 'INTEGER');\n\n/**\n * Column types, API-compatible with Sequelize v6 `DataTypes` for PostgreSQL.\n *\n * `BIGINT` and `DECIMAL` values are returned as strings (like Sequelize v6) to avoid precision loss.\n *\n * @example\n * ```ts\n * User.init({ id: { type: DataTypes.BIGINT, primaryKey: true }, name: DataTypes.STRING(64) }, { sequelize });\n * ```\n */\nexport const DataTypes = {\n /** `VARCHAR(length)`, default length 255. */\n STRING: callable((length?: number) => new StringType(length), new StringType()),\n /** `CHAR(length)`, default length 255. */\n CHAR: callable((length?: number) => new CharType(length), new CharType()),\n /** `TEXT`. The size argument is accepted for compatibility and ignored. */\n TEXT: callable((size?: 'tiny' | 'medium' | 'long') => new TextType(size), new TextType()),\n /** `CITEXT` (case-insensitive text, requires the `citext` extension). */\n CITEXT: new ScalarType('CITEXT', 'CITEXT'),\n /** `INTEGER`. */\n INTEGER,\n /** `SMALLINT`. */\n SMALLINT: new IntegerType('SMALLINT', 'SMALLINT'),\n /** Mapped to `SMALLINT` (PostgreSQL has no `TINYINT`). */\n TINYINT: new IntegerType('TINYINT', 'SMALLINT'),\n /** Mapped to `INTEGER` (PostgreSQL has no `MEDIUMINT`). */\n MEDIUMINT: new IntegerType('MEDIUMINT', 'INTEGER'),\n /** `BIGINT`; values are returned as strings. */\n BIGINT: new IntegerType('BIGINT', 'BIGINT'),\n /** `FLOAT(precision)`. */\n FLOAT: callable((digits?: number) => new FloatType(digits), new FloatType()),\n /** `REAL`. */\n REAL: new ScalarType('REAL', 'REAL'),\n /** `DOUBLE PRECISION`. */\n DOUBLE: new ScalarType('DOUBLE', 'DOUBLE PRECISION'),\n /** `DECIMAL(precision, scale)`; values are returned as strings. */\n DECIMAL: callable(\n (digits?: number, scale?: number) => new DecimalType(digits, scale),\n new DecimalType(),\n ),\n /** Alias of `DECIMAL`. */\n NUMBER: callable(\n (digits?: number, scale?: number) => new DecimalType(digits, scale),\n new DecimalType(),\n ),\n /** `BOOLEAN`. */\n BOOLEAN: new ScalarType('BOOLEAN', 'BOOLEAN'),\n /** `TIMESTAMP WITH TIME ZONE`; values are `Date` objects. */\n DATE: callable((fsp?: number) => new DateType(fsp), new DateType()),\n /**\n * `TIMESTAMP WITHOUT TIME ZONE`; values are `Date` objects whose local wall-clock time is the\n * stored time. PostgreSQL extension.\n */\n TIMESTAMP: callable((fsp?: number) => new TimestampType(fsp), new TimestampType()),\n /** `DATE`; values are `'YYYY-MM-DD'` strings. */\n DATEONLY: new ScalarType('DATEONLY', 'DATE'),\n /** `TIME`. */\n TIME: new ScalarType('TIME', 'TIME'),\n /** `INTERVAL`; values are PostgreSQL interval strings (e.g. `'1 day 02:00:00'`). PostgreSQL extension. */\n INTERVAL: new ScalarType('INTERVAL', 'INTERVAL'),\n /** `JSON`. */\n JSON: new JsonType('JSON'),\n /** `JSONB`. */\n JSONB: new JsonType('JSONB'),\n /** `BYTEA`; values are `Buffer`s. */\n BLOB: callable((size?: 'tiny' | 'medium' | 'long') => new BlobType(size), new BlobType()),\n /** `UUID`. */\n UUID: new ScalarType('UUID', 'UUID'),\n /**\n * `HSTORE` (requires the `hstore` extension); values are objects of string (or `null`) values,\n * like Sequelize v6.\n */\n HSTORE: new HstoreType(),\n /**\n * `LTREE` label path (requires the `ltree` extension); values are strings like `'Top.Science'`.\n * PostgreSQL extension.\n */\n LTREE: new ScalarType('LTREE', 'LTREE'),\n /**\n * `MONEY`; values are strings formatted by the server's `lc_monetary` (e.g. `'$12.50'`); numbers\n * are accepted on write. PostgreSQL extension.\n */\n MONEY: new ScalarType('MONEY', 'MONEY'),\n /** `XML`; values are XML text. PostgreSQL extension. */\n XML: new ScalarType('XML', 'XML'),\n /** `BIT(length)`, default length 1; values are strings of `0` and `1`. PostgreSQL extension. */\n BIT: callable((length?: number) => new BitType('BIT', length), new BitType('BIT')),\n /**\n * `BIT VARYING(length)`, unlimited without a length; values are strings of `0` and `1`.\n * PostgreSQL extension.\n */\n VARBIT: callable((length?: number) => new BitType('VARBIT', length), new BitType('VARBIT')),\n /** `INET`. */\n INET: new ScalarType('INET', 'INET'),\n /** `CIDR`. */\n CIDR: new ScalarType('CIDR', 'CIDR'),\n /** `MACADDR`. */\n MACADDR: new ScalarType('MACADDR', 'MACADDR'),\n /** `MACADDR8` (EUI-64 address). PostgreSQL extension. */\n MACADDR8: new ScalarType('MACADDR8', 'MACADDR8'),\n /** `TSQUERY`; values are full-text query strings. PostgreSQL extension. */\n TSQUERY: new ScalarType('TSQUERY', 'TSQUERY'),\n /** `TSVECTOR`. */\n TSVECTOR: new ScalarType('TSVECTOR', 'TSVECTOR'),\n /** `POINT`; values are `{ x, y }`. PostgreSQL extension. */\n POINT: new GeometricType('POINT'),\n /** `LINE` (`a·x + b·y + c = 0`); values are `{ a, b, c }`. PostgreSQL extension. */\n LINE: new GeometricType('LINE'),\n /** `LSEG` line segment; values are `[start, end]` points. PostgreSQL extension. */\n LSEG: new GeometricType('LSEG'),\n /** `BOX`; values are `[corner, corner]` points (the server returns the upper right first). PostgreSQL extension. */\n BOX: new GeometricType('BOX'),\n /** `PATH`; values are `{ points, closed }`. PostgreSQL extension. */\n PATH: new GeometricType('PATH'),\n /** `POLYGON`; values are arrays of `{ x, y }` points. PostgreSQL extension. */\n POLYGON: new GeometricType('POLYGON'),\n /** `CIRCLE`; values are `{ x, y, radius }`. PostgreSQL extension. */\n CIRCLE: new GeometricType('CIRCLE'),\n /** PostGIS `GEOMETRY(type, srid)`. */\n GEOMETRY: callable(\n (geometryType?: string, srid?: number) => new SpatialType('GEOMETRY', geometryType, srid),\n new SpatialType('GEOMETRY'),\n ),\n /** PostGIS `GEOGRAPHY(type, srid)`. */\n GEOGRAPHY: callable(\n (geographyType?: string, srid?: number) => new SpatialType('GEOGRAPHY', geographyType, srid),\n new SpatialType('GEOGRAPHY'),\n ),\n /** `type[]`, e.g. `DataTypes.ARRAY(DataTypes.TEXT)`. */\n ARRAY: (subtype: DataTypeInput): ArrayType => new ArrayType(subtype),\n /** Range type, e.g. `DataTypes.RANGE(DataTypes.INTEGER)` → `INT4RANGE`. */\n RANGE: callable(\n (subtype: DataTypeInput = INTEGER) => new RangeType(subtype),\n new RangeType(INTEGER),\n ),\n /**\n * Multirange type (PostgreSQL 14+), e.g. `DataTypes.MULTIRANGE(DataTypes.INTEGER)` →\n * `INT4MULTIRANGE`; values are arrays of `[lower, upper]` ranges. PostgreSQL extension.\n */\n MULTIRANGE: callable(\n (subtype: DataTypeInput = INTEGER) => new MultirangeType(subtype),\n new MultirangeType(INTEGER),\n ),\n /**\n * Composite type, e.g. `DataTypes.COMPOSITE('address', { street: DataTypes.TEXT, zip: DataTypes.INTEGER })`;\n * values are objects keyed by field name. Create the type first with `createSql()`. PostgreSQL extension.\n */\n COMPOSITE: (name: string, fields: Readonly<Record<string, DataTypeInput>>): CompositeType =>\n new CompositeType(name, fields),\n /** Enumerated values: `DataTypes.ENUM('a', 'b')` or `DataTypes.ENUM({ values: ['a', 'b'] })`. */\n ENUM: (\n ...args: readonly (string | readonly string[] | Readonly<{ values: readonly string[] }>)[]\n ): EnumType => new EnumType(...args),\n /** Attribute that is not stored in the database (computed by getters/setters). */\n VIRTUAL: callable(\n (returnType?: DataTypeInput, fields?: readonly string[]) => new VirtualType(returnType, fields),\n new VirtualType(),\n ),\n /** Default value: current timestamp. */\n NOW: new DefaultValueGenerator('NOW', () => new Date()),\n /** Default value: random UUID v4 generated on the client. */\n UUIDV4: new DefaultValueGenerator('UUIDV4', () => randomUUID()),\n} as const;\n","import type { Cast, Col, Fn } from './call-expressions.ts';\nimport type { Excluded, Json, Where } from './condition-expressions.ts';\nimport type { Literal } from './methods.ts';\nimport type { Exists, Subquery } from './query-expressions.ts';\nimport type { Over, Tuple } from './row-expressions.ts';\n\n/**\n * Operations over every expression class (double dispatch through {@link SqlExpression.accept}).\n *\n * @internal\n */\nexport interface SqlExpressionVisitor<R> {\n /** Visits a {@link Literal}. */\n visitLiteral(expression: Literal): R;\n /** Visits a {@link Fn}. */\n visitFn(expression: Fn): R;\n /** Visits a {@link Col}. */\n visitCol(expression: Col): R;\n /** Visits a {@link Cast}. */\n visitCast(expression: Cast): R;\n /** Visits a {@link Json}. */\n visitJson(expression: Json): R;\n /** Visits a {@link Where}. */\n visitWhere(expression: Where): R;\n /** Visits a {@link Excluded}. */\n visitExcluded(expression: Excluded): R;\n /** Visits a {@link Subquery}. */\n visitSubquery(expression: Subquery): R;\n /** Visits a {@link Exists}. */\n visitExists(expression: Exists): R;\n /** Visits a {@link Over}. */\n visitOver(expression: Over): R;\n /** Visits a {@link Tuple}. */\n visitTuple(expression: Tuple): R;\n}\n\n// Shared through the global symbol registry so that expressions built by another copy of the\n// package (e.g. the CommonJS build next to the ES module build) are still recognised.\nconst KIND: unique symbol = Symbol.for('postgrelize.expression') as never;\n\n/**\n * Any expression builder accepted where Sequelize v6 accepts a `SequelizeMethod`. Instances are\n * immutable.\n */\nexport abstract class SqlExpression {\n /** @internal Expression kind; set by every concrete class. */\n static readonly kind: string = 'SqlExpression';\n\n constructor() {\n Object.defineProperty(this, KIND, { value: (new.target as typeof SqlExpression).kind });\n }\n\n /**\n * `instanceof` by kind tag instead of prototype chain, so it works across package copies.\n *\n * @param value - Value to test.\n * @returns True when `value` is an expression of this class (any expression for the base class).\n */\n static [Symbol.hasInstance](value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const kind = (value as { [KIND]?: unknown })[KIND];\n return typeof kind === 'string' && (this === SqlExpression || this.kind === kind);\n }\n\n /** @internal Dispatches to the visitor method of the concrete expression class. */\n abstract accept<R>(visitor: SqlExpressionVisitor<R>): R;\n}\n","import { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\n\nconst FUNCTION_NAME = /^[A-Za-z_][\\w$]*(?:\\.[A-Za-z_][\\w$]*)?$/;\n\nconst TYPE_NAME = /^[A-Za-z_][\\w ]*(?:\\(\\s*\\d+\\s*(?:,\\s*\\d+\\s*)?\\))?(?:\\[\\])*$/;\n\n/** SQL function call. Created by {@link fn}. */\nexport class Fn extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Fn';\n /** Function name. */\n readonly fn: string;\n /** Arguments. */\n readonly args: readonly unknown[];\n\n /**\n * @param fn - Function name; must be a plain or schema-qualified identifier.\n * @param args - Arguments.\n */\n constructor(fn: string, args: readonly unknown[]) {\n super();\n this.fn = Fn.validName(fn);\n this.args = args;\n Object.freeze(this);\n }\n\n /**\n * Checks that a function name is a plain or schema-qualified identifier.\n *\n * @internal\n */\n static validName(name: string): string {\n if (typeof name !== 'string' || !FUNCTION_NAME.test(name)) {\n throw new Error(`Invalid function name: ${String(name)}`);\n }\n return name;\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitFn(this);\n }\n}\n\n/** Column reference. Created by {@link col}. */\nexport class Col extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Col';\n /** Column name or path. */\n readonly col: string | readonly string[];\n\n /**\n * @param col - Column name or path.\n */\n constructor(col: string | readonly string[]) {\n super();\n this.col = col;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitCol(this);\n }\n}\n\n/** Type cast `CAST(value AS type)`. Created by {@link cast}. */\nexport class Cast extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Cast';\n /** Value or expression to cast. */\n readonly val: unknown;\n /** Target type. */\n readonly type: string;\n /** Kept for Sequelize v6 compatibility. */\n readonly json: boolean = false;\n\n /**\n * @param val - Value or expression to cast.\n * @param type - PostgreSQL type name.\n */\n constructor(val: unknown, type: string) {\n super();\n if (!TYPE_NAME.test(type.trim())) {\n throw new Error(`Invalid cast type: ${type}`);\n }\n this.val = val;\n this.type = type.trim();\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitCast(this);\n }\n}\n","import { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\n\n/** JSON path access or JSON conditions. Created by {@link json}. */\nexport class Json extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Json';\n /** Dot-separated path starting with the attribute name. */\n readonly path?: string;\n /** Conditions object. */\n readonly conditions?: object;\n /** Value compared with the path (`undefined`: no comparison). */\n readonly value?: unknown;\n\n /**\n * @param conditionsOrPath - Dot-separated path or conditions object.\n * @param value - Value compared with the path.\n */\n constructor(conditionsOrPath: string | object, value?: unknown) {\n super();\n if (typeof conditionsOrPath === 'string') {\n this.path = conditionsOrPath;\n this.value = value;\n } else {\n this.conditions = conditionsOrPath;\n }\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitJson(this);\n }\n}\n\n/** Comparison of an arbitrary expression with a value. Created by {@link where}. */\nexport class Where extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Where';\n /** Left-hand expression. */\n readonly attribute: unknown;\n /** Comparison operator. */\n readonly comparator: string | symbol;\n /** Right-hand value. */\n readonly logic: unknown;\n\n /**\n * @param attribute - Left-hand expression.\n * @param comparator - Comparison operator.\n * @param logic - Right-hand value.\n */\n constructor(attribute: unknown, comparator: string | symbol, logic: unknown) {\n super();\n this.attribute = attribute;\n this.comparator = comparator;\n this.logic = logic;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitWhere(this);\n }\n}\n\n/** Reference to a column of the row proposed for insertion in `ON CONFLICT DO UPDATE`. Created by {@link excluded}. */\nexport class Excluded extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Excluded';\n /** Attribute name. */\n readonly column: string;\n\n /**\n * @param column - Attribute name.\n */\n constructor(column: string) {\n super();\n this.column = column;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitExcluded(this);\n }\n}\n","import type { ModifyingNode, QueryNode, SetOperator } from '../sql/ast.ts';\nimport { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\n\n/**\n * Options of {@link Subquery.union}, {@link Subquery.intersect} and {@link Subquery.except}.\n *\n * @example\n * ```ts\n * const opts: SetOperationOptions = { all: true };\n * const rows = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }), opts);\n * ```\n */\nexport type SetOperationOptions = Readonly<{\n /**\n * Keep duplicate rows (`UNION ALL`, `INTERSECT ALL`, `EXCEPT ALL`).\n *\n * @defaultValue false\n */\n all?: boolean;\n}>;\n\n/**\n * SELECT embedded in another statement. Created by `Model.subquery()`, or by combining subqueries\n * with a set operation. PostgreSQL extension.\n */\nexport class Subquery extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Subquery';\n /** Builds the query AST (called when the outer statement is compiled). */\n readonly build: () => QueryNode;\n\n /**\n * @param build - Builds the query AST.\n */\n constructor(build: () => QueryNode) {\n super();\n this.build = build;\n Object.freeze(this);\n }\n\n /**\n * Rows of this query or of `other`, without duplicates unless `all` is set (`UNION`).\n *\n * Both queries must select the same number of columns of compatible types. Use the result\n * wherever a subquery fits: `source`, `with`, `Op.in`, `insertFrom`, `merge`.\n *\n * @param other - Query to combine with.\n * @param options - `all` keeps duplicates.\n * @returns Combined subquery.\n * @example\n * ```ts\n * const ids = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }));\n * const users = await User.findAll({ where: { id: { [Op.in]: ids } } });\n * ```\n */\n union(other: Subquery, options?: SetOperationOptions): Subquery {\n return this.#combine('UNION', other, options);\n }\n\n /**\n * Rows that are in both this query and `other` (`INTERSECT`).\n *\n * @param other - Query to intersect with.\n * @param options - `all` keeps duplicates.\n * @returns Combined subquery.\n * @example\n * ```ts\n * const both = Post.subquery({ attributes: ['userId'] }).intersect(Task.subquery({ attributes: ['userId'] }));\n * ```\n */\n intersect(other: Subquery, options?: SetOperationOptions): Subquery {\n return this.#combine('INTERSECT', other, options);\n }\n\n /**\n * Rows of this query that are not in `other` (`EXCEPT`).\n *\n * @param other - Query whose rows are removed.\n * @param options - `all` keeps duplicates.\n * @returns Combined subquery.\n * @example\n * ```ts\n * const quiet = User.subquery({ attributes: ['id'] }).except(Post.subquery({ attributes: ['userId'] }));\n * ```\n */\n except(other: Subquery, options?: SetOperationOptions): Subquery {\n return this.#combine('EXCEPT', other, options);\n }\n\n #combine(op: SetOperator, other: Subquery, options: SetOperationOptions | undefined): Subquery {\n return new Subquery(() => ({\n kind: 'setop',\n op,\n all: options?.all === true,\n left: this.build(),\n right: other.build(),\n }));\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitSubquery(this);\n }\n}\n\n/** `EXISTS (subquery)` / `NOT EXISTS (subquery)`. Created by {@link exists} / {@link notExists}. */\nexport class Exists extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Exists';\n /** The wrapped `SELECT` that `EXISTS` tests for rows. */\n readonly subquery: Subquery;\n /** `NOT EXISTS`. */\n readonly negated: boolean;\n\n /**\n * @param subquery - Subquery.\n * @param negated - `NOT EXISTS`.\n */\n constructor(subquery: Subquery, negated: boolean) {\n super();\n this.subquery = subquery;\n this.negated = negated;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitExists(this);\n }\n}\n\n/**\n * INSERT, UPDATE or DELETE statement for a data-modifying CTE. Created by `Model.insertStatement()`,\n * `Model.updateStatement()` and `Model.deleteStatement()`; not executed on its own. PostgreSQL extension.\n *\n * @example\n * ```ts\n * const moved = Task.deleteStatement({ where: { done: true }, returning: true });\n * const rows = await Task.findAll({ with: { moved }, source: 'moved' });\n * ```\n */\nexport class WriteStatement {\n /** Builds the statement AST (called when the outer statement is compiled). */\n readonly build: () => ModifyingNode;\n\n /**\n * @param build - Builds the statement AST.\n */\n constructor(build: () => ModifyingNode) {\n this.build = build;\n Object.freeze(this);\n }\n}\n","import type { Fn } from './call-expressions.ts';\nimport { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\nimport type { Literal } from './methods.ts';\n\n/** Window function call `fn OVER (...)`. Created by {@link over}. */\nexport class Over extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Over';\n /** Window function, e.g. `fn('row_number')`. */\n readonly fn: Fn | Literal;\n /** `PARTITION BY` attributes or expressions. */\n readonly partitionBy: readonly unknown[];\n /** `ORDER BY` items: attribute, `[attribute, direction]` or expression. */\n readonly orderBy: readonly unknown[];\n\n /**\n * @param fn - Window function.\n * @param partitionBy - `PARTITION BY` items.\n * @param orderBy - `ORDER BY` items.\n */\n constructor(fn: Fn | Literal, partitionBy: readonly unknown[], orderBy: readonly unknown[]) {\n super();\n this.fn = fn;\n this.partitionBy = partitionBy;\n this.orderBy = orderBy;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitOver(this);\n }\n}\n\n/** Row constructor `(a, b, ...)` for row comparisons. Created by {@link tuple}. */\nexport class Tuple extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Tuple';\n /** Row items. */\n readonly items: readonly unknown[];\n\n /**\n * @param items - Row items.\n */\n constructor(items: readonly unknown[]) {\n super();\n this.items = items;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitTuple(this);\n }\n}\n","import { Cast, Col, Fn } from './call-expressions.ts';\nimport { Excluded, Json, Where } from './condition-expressions.ts';\nimport { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\nimport { Exists, type Subquery } from './query-expressions.ts';\nimport { Over, Tuple } from './row-expressions.ts';\n\nexport { Cast, Col, Fn } from './call-expressions.ts';\nexport { Excluded, Json, Where } from './condition-expressions.ts';\nexport { SqlExpression, type SqlExpressionVisitor } from './expression.ts';\nexport { Exists, Subquery, WriteStatement, type SetOperationOptions } from './query-expressions.ts';\nexport { Over, Tuple } from './row-expressions.ts';\n\n// Kept in the module of the factories: a second copy of this module (another package build) then\n// has its own class, which the cross-copy instance check tests rely on.\n/** Raw SQL fragment inserted into a query as-is. Created by {@link literal}. */\nexport class Literal extends SqlExpression {\n /** @internal */\n static override readonly kind = 'Literal';\n /** SQL text. */\n readonly val: string;\n\n /**\n * @param val - SQL text.\n */\n constructor(val: string) {\n super();\n this.val = val;\n Object.freeze(this);\n }\n\n /** @internal */\n accept<R>(visitor: SqlExpressionVisitor<R>): R {\n return visitor.visitLiteral(this);\n }\n}\n\n/**\n * Creates a raw SQL fragment. The text is not escaped — never pass user input.\n *\n * @param val - SQL text.\n * @returns Literal expression.\n * @example\n * ```ts\n * await Post.findAll({ order: [literal('\"createdAt\" DESC NULLS LAST')] });\n * ```\n */\nexport const literal = (val: string): Literal => new Literal(val);\n\n/**\n * Creates an SQL function call. Arguments are bound as parameters unless they are expressions.\n *\n * @param name - Function name, e.g. `'lower'`.\n * @param args - Function arguments.\n * @returns Function call expression.\n * @example\n * ```ts\n * await User.findAll({ where: where(fn('lower', col('email')), 'a@b.c') });\n * ```\n */\nexport const fn = (name: string, ...args: readonly unknown[]): Fn => new Fn(name, args);\n\n/**\n * Creates a column reference. Dots separate table and column: `'user.id'`.\n *\n * @param name - Column name, optionally prefixed with a table alias.\n * @returns Column expression.\n * @example\n * ```ts\n * await Post.findAll({ attributes: [[fn('count', col('Post.id')), 'total']], group: [col('Post.userId')] });\n * ```\n */\nexport const col = (name: string): Col => new Col(name);\n\n/**\n * Creates a type cast `CAST(value AS type)`.\n *\n * @param val - Value or expression to cast.\n * @param type - PostgreSQL type name, e.g. `'integer'`.\n * @returns Cast expression.\n * @example\n * ```ts\n * await Product.findAll({ attributes: [[cast(col('price'), 'integer'), 'rounded']] });\n * ```\n */\nexport const cast = (val: unknown, type: string): Cast => new Cast(val, type);\n\n/**\n * Accesses a JSON(B) value by path (`json('meta.a.b')`) or builds JSON conditions\n * (`json({ meta: { a: 1 } })`).\n *\n * @param conditionsOrPath - Dot-separated path, starting with the attribute name, or a conditions object.\n * @param value - Value to compare with when a path is given.\n * @returns JSON expression.\n * @example\n * ```ts\n * await User.findAll({ where: json('meta.address.city', 'Berlin') });\n * await User.findAll({ where: json({ meta: { active: true } }) });\n * ```\n */\nexport const json = (conditionsOrPath: string | object, value?: unknown): Json =>\n new Json(conditionsOrPath, value);\n\n/** Call signatures of {@link where}. */\nexport type WhereFactory = {\n /**\n * @param attribute - Left-hand expression.\n * @param logic - Right-hand value or condition object, compared with `=`.\n */\n (attribute: unknown, logic: unknown): Where;\n /**\n * @param attribute - Left-hand expression.\n * @param comparator - `Op.*` symbol or SQL operator string such as `'>='`.\n * @param logic - Right-hand value.\n */\n (attribute: unknown, comparator: string | symbol, logic: unknown): Where;\n};\n\n/**\n * Compares an expression with a value: `where(fn('lower', col('name')), 'bob')` or\n * `where(col('age'), Op.gt, 18)`.\n *\n * @returns Where expression.\n * @example\n * ```ts\n * await User.findAll({ where: where(fn('lower', col('name')), 'bob') });\n * await User.findAll({ where: where(col('age'), Op.gt, 18) });\n * ```\n */\nexport const where: WhereFactory = (\n attribute: unknown,\n ...rest: readonly [unknown] | readonly [string | symbol, unknown]\n): Where =>\n rest.length === 1 ? new Where(attribute, '=', rest[0]) : new Where(attribute, rest[0], rest[1]);\n\n/**\n * References the value proposed for insertion (`EXCLUDED.\"column\"`) inside an `onConflict`\n * update. PostgreSQL extension.\n *\n * @param attribute - Model attribute name.\n * @returns Excluded column expression.\n * @example\n * ```ts\n * const rows = [{ key: 'home', hits: 1 }];\n * await Product.bulkCreate(rows, {\n * onConflict: { target: ['key'], action: { update: { hits: excluded('hits') } } },\n * });\n * ```\n */\nexport const excluded = (attribute: string): Excluded => new Excluded(attribute);\n\n/**\n * `EXISTS (subquery)`. PostgreSQL extension.\n *\n * @param subquery - Subquery from `Model.subquery()`.\n * @returns Condition usable as `where`.\n * @example\n * ```ts\n * await User.findAll({ where: exists(Post.subquery({ where: { userId: col('User.id') } })) });\n * ```\n */\nexport const exists = (subquery: Subquery): Exists => new Exists(subquery, false);\n\n/**\n * `NOT EXISTS (subquery)`. PostgreSQL extension.\n *\n * @param subquery - Subquery from `Model.subquery()`.\n * @returns Condition usable as `where`.\n * @example\n * ```ts\n * await User.findAll({ where: notExists(Post.subquery({ where: { userId: col('User.id') } })) });\n * ```\n */\nexport const notExists = (subquery: Subquery): Exists => new Exists(subquery, true);\n\n/**\n * Window definition of {@link over}.\n *\n * @example\n * ```ts\n * const window: WindowOptions = { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] };\n * ```\n */\nexport type WindowOptions = Readonly<{\n /** `PARTITION BY` attributes or expressions. */\n partitionBy?: readonly unknown[];\n /** `ORDER BY` items: attribute, `[attribute, direction]` or expression. */\n orderBy?: readonly unknown[];\n}>;\n\n/**\n * Window function call: `over(fn('row_number'), { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] })`.\n * PostgreSQL extension.\n *\n * @param windowFunction - Function call, e.g. `fn('rank')`.\n * @param window - Partition and order.\n * @returns Expression usable in `attributes` and `order`.\n * @example\n * ```ts\n * await Post.findAll({\n * attributes: ['id', [over(fn('row_number'), { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] }), 'rank']],\n * });\n * ```\n */\nexport const over = (windowFunction: Fn | Literal, window: WindowOptions = {}): Over =>\n new Over(windowFunction, window.partitionBy ?? [], window.orderBy ?? []);\n\n/**\n * Row constructor for row comparisons: `where(tuple(col('createdAt'), col('id')), Op.lt, tuple(date, id))`.\n * PostgreSQL extension.\n *\n * @param items - Row items (values or expressions).\n * @returns Row expression.\n * @example\n * ```ts\n * const cursor = new Date();\n * await Post.findAll({ where: where(tuple(col('createdAt'), col('id')), Op.lt, tuple(cursor, 100)) });\n * ```\n */\nexport const tuple = (...items: readonly unknown[]): Tuple => new Tuple(items);\n","const eq: unique symbol = Symbol.for('eq');\nconst ne: unique symbol = Symbol.for('ne');\nconst gte: unique symbol = Symbol.for('gte');\nconst gt: unique symbol = Symbol.for('gt');\nconst lte: unique symbol = Symbol.for('lte');\nconst lt: unique symbol = Symbol.for('lt');\nconst not: unique symbol = Symbol.for('not');\nconst is: unique symbol = Symbol.for('is');\nconst inOp: unique symbol = Symbol.for('in');\nconst notIn: unique symbol = Symbol.for('notIn');\nconst like: unique symbol = Symbol.for('like');\nconst notLike: unique symbol = Symbol.for('notLike');\nconst iLike: unique symbol = Symbol.for('iLike');\nconst notILike: unique symbol = Symbol.for('notILike');\nconst startsWith: unique symbol = Symbol.for('startsWith');\nconst endsWith: unique symbol = Symbol.for('endsWith');\nconst substring: unique symbol = Symbol.for('substring');\nconst regexp: unique symbol = Symbol.for('regexp');\nconst notRegexp: unique symbol = Symbol.for('notRegexp');\nconst iRegexp: unique symbol = Symbol.for('iRegexp');\nconst notIRegexp: unique symbol = Symbol.for('notIRegexp');\nconst between: unique symbol = Symbol.for('between');\nconst notBetween: unique symbol = Symbol.for('notBetween');\nconst overlap: unique symbol = Symbol.for('overlap');\nconst contains: unique symbol = Symbol.for('contains');\nconst contained: unique symbol = Symbol.for('contained');\nconst adjacent: unique symbol = Symbol.for('adjacent');\nconst strictLeft: unique symbol = Symbol.for('strictLeft');\nconst strictRight: unique symbol = Symbol.for('strictRight');\nconst noExtendRight: unique symbol = Symbol.for('noExtendRight');\nconst noExtendLeft: unique symbol = Symbol.for('noExtendLeft');\nconst and: unique symbol = Symbol.for('and');\nconst or: unique symbol = Symbol.for('or');\nconst any: unique symbol = Symbol.for('any');\nconst all: unique symbol = Symbol.for('all');\nconst values: unique symbol = Symbol.for('values');\nconst col: unique symbol = Symbol.for('col');\nconst placeholder: unique symbol = Symbol.for('placeholder');\nconst join: unique symbol = Symbol.for('join');\nconst match: unique symbol = Symbol.for('match');\nconst isDistinctFrom: unique symbol = Symbol.for('postgrelize.isDistinctFrom');\nconst isNotDistinctFrom: unique symbol = Symbol.for('postgrelize.isNotDistinctFrom');\nconst hasKey: unique symbol = Symbol.for('postgrelize.hasKey');\nconst hasAnyKeys: unique symbol = Symbol.for('postgrelize.hasAnyKeys');\nconst hasAllKeys: unique symbol = Symbol.for('postgrelize.hasAllKeys');\nconst similarTo: unique symbol = Symbol.for('postgrelize.similarTo');\nconst notSimilarTo: unique symbol = Symbol.for('postgrelize.notSimilarTo');\nconst jsonPathExists: unique symbol = Symbol.for('postgrelize.jsonPathExists');\nconst containedOrEqual: unique symbol = Symbol.for('postgrelize.containedOrEqual');\nconst containsOrEqual: unique symbol = Symbol.for('postgrelize.containsOrEqual');\nconst trigramSimilar: unique symbol = Symbol.for('postgrelize.trigramSimilar');\nconst trigramWordSimilar: unique symbol = Symbol.for('postgrelize.trigramWordSimilar');\nconst trigramStrictWordSimilar: unique symbol = Symbol.for('postgrelize.trigramStrictWordSimilar');\nconst trigramHasSimilarWord: unique symbol = Symbol.for('postgrelize.trigramHasSimilarWord');\nconst trigramHasSimilarStrictWord: unique symbol = Symbol.for(\n 'postgrelize.trigramHasSimilarStrictWord',\n);\n\n/**\n * Query operators for `where` clauses.\n *\n * Symbols are created with `Symbol.for(name)` exactly like Sequelize v6, so operators imported\n * from `sequelize` and from `postgrelize` are interchangeable. Operators marked \"PostgreSQL\n * extension\" do not exist in Sequelize v6.\n *\n * @example\n * ```ts\n * await User.findAll({ where: { age: { [Op.gte]: 18 }, name: { [Op.iLike]: 'a%' } } });\n * ```\n */\nexport const Op = {\n /** `= value`; `IS NULL` when the value is `null`. */\n eq,\n /** `<> value`; `IS NOT NULL` when the value is `null`. */\n ne,\n /** `>= value`. */\n gte,\n /** `> value`. */\n gt,\n /** `<= value`. */\n lte,\n /** `< value`. */\n lt,\n /** `IS NOT value` for `null`/booleans, otherwise negates a nested condition. */\n not,\n /** `IS value`, for `null`, `true` or `false`. */\n is,\n /** `IN (...)`; long lists compile to `= ANY($n)`. */\n in: inOp,\n /** `NOT IN (...)`; long lists compile to `<> ALL($n)`. */\n notIn,\n /** `LIKE pattern`. */\n like,\n /** `NOT LIKE pattern`. */\n notLike,\n /** `ILIKE pattern`. */\n iLike,\n /** `NOT ILIKE pattern`. */\n notILike,\n /** `LIKE 'value%'`. */\n startsWith,\n /** `LIKE '%value'`. */\n endsWith,\n /** `LIKE '%value%'`. */\n substring,\n /** `~ pattern` (POSIX regular expression). */\n regexp,\n /** `!~ pattern`. */\n notRegexp,\n /** `~* pattern` (case-insensitive regular expression). */\n iRegexp,\n /** `!~* pattern`. */\n notIRegexp,\n /** `BETWEEN a AND b`, value is `[a, b]`. */\n between,\n /** `NOT BETWEEN a AND b`, value is `[a, b]`. */\n notBetween,\n /** `&&` — arrays or ranges overlap. */\n overlap,\n /** `@>` — array, range or jsonb contains the value. */\n contains,\n /** `<@` — array, range or jsonb is contained by the value. */\n contained,\n /** `-|-` — ranges are adjacent. */\n adjacent,\n /** `<<` — range is strictly left of the value. */\n strictLeft,\n /** `>>` — range is strictly right of the value. */\n strictRight,\n /** `&<` — range does not extend to the right of the value. */\n noExtendRight,\n /** `&>` — range does not extend to the left of the value. */\n noExtendLeft,\n /** Logical AND of nested conditions. */\n and,\n /** Logical OR of nested conditions. */\n or,\n /** `ANY (ARRAY[...])`, combined with a comparison operator. */\n any,\n /** `ALL (ARRAY[...])`, combined with a comparison operator. */\n all,\n /** `VALUES (...)` list for `Op.any` / `Op.all`. */\n values,\n /** Compares with another column, value is a column reference such as `'user.id'`. */\n col,\n /** Reserved by Sequelize v6 for internal use. */\n placeholder,\n /** Reserved by Sequelize v6 for internal use. */\n join,\n /** `@@` — tsvector matches tsquery. */\n match,\n /** `IS DISTINCT FROM value` (null-safe `<>`). PostgreSQL extension. */\n isDistinctFrom,\n /** `IS NOT DISTINCT FROM value` (null-safe `=`). PostgreSQL extension. */\n isNotDistinctFrom,\n /** jsonb `?` — top-level key exists. PostgreSQL extension. */\n hasKey,\n /** jsonb `?|` — any of the keys exist. PostgreSQL extension. */\n hasAnyKeys,\n /** jsonb `?&` — all of the keys exist. PostgreSQL extension. */\n hasAllKeys,\n /** `SIMILAR TO pattern` (SQL regular expression). PostgreSQL extension. */\n similarTo,\n /** `NOT SIMILAR TO pattern`. PostgreSQL extension. */\n notSimilarTo,\n /** jsonb `@?` — the jsonpath returns any item; the value is a jsonpath string. PostgreSQL extension. */\n jsonPathExists,\n /** `<<=` — inet/cidr subnet is contained within or equals the value. PostgreSQL extension. */\n containedOrEqual,\n /** `>>=` — inet/cidr subnet contains or equals the value. PostgreSQL extension. */\n containsOrEqual,\n /** `%` — `pg_trgm` trigram similarity above `pg_trgm.similarity_threshold`. PostgreSQL extension. */\n trigramSimilar,\n /** `<%` — `pg_trgm`: the column is similar to a part of the value (word similarity above the threshold). PostgreSQL extension. */\n trigramWordSimilar,\n /** `<<%` — `pg_trgm`: the column is strictly similar to a word of the value. PostgreSQL extension. */\n trigramStrictWordSimilar,\n /** `%>` — `pg_trgm`: the column has a part similar to the value (commutator of `<%`). PostgreSQL extension. */\n trigramHasSimilarWord,\n /** `%>>` — `pg_trgm`: the column has a strictly similar word of the value. PostgreSQL extension. */\n trigramHasSimilarStrictWord,\n} as const;\n\n/** Union of all operator symbols in {@link Op}. */\nexport type OpSymbol = (typeof Op)[keyof typeof Op];\n","import type { TableRef } from './ast.ts';\nimport { IdentifierQuoter } from './identifier-quoter.ts';\n\nconst quoter = new IdentifierQuoter();\n\n/** Bound value inside a chunk list; the same chunk object maps to the same `$n`. */\nexport type ParamChunk = Readonly<{ param: unknown }>;\n/** SQL text or a bound value. */\nexport type Chunk = string | ParamChunk;\n/** Chunk list rendered by `SqlCompiler.finalize`. */\nexport type Chunks = readonly Chunk[];\n\n/** Shared chunk helpers of the SQL compilers: quoting, wrapping, joining and table references. */\nexport class ChunkBuilder {\n /** Quotes an identifier: `\"name\"`, doubling embedded quotes. */\n protected readonly quote = (name: string): string => quoter.quote(name);\n\n /**\n * Joins chunk lists with a separator.\n *\n * @param parts - Chunk lists.\n * @param separator - SQL text between the lists.\n * @returns Joined chunks.\n */\n protected joinAll(parts: readonly Chunks[], separator: string): Chunks {\n const joined: Chunk[] = [];\n for (const [index, part] of parts.entries()) {\n if (index > 0) {\n joined.push(separator);\n }\n for (const chunk of part) {\n joined.push(chunk);\n }\n }\n return joined;\n }\n\n /**\n * Wraps chunks in parentheses.\n *\n * @param chunks - Chunks.\n * @returns `(chunks)`.\n */\n protected wrap(chunks: Chunks): Chunks {\n return ['(', ...chunks, ')'];\n }\n\n /**\n * Parenthesized quoted column list.\n *\n * @param columns - Column names.\n * @returns `(\"a\", \"b\")`.\n */\n protected columnList(columns: readonly string[]): Chunks {\n return this.wrap([columns.map(this.quote).join(', ')]);\n }\n\n /**\n * Quoted table reference with an optional alias.\n *\n * @param table - Table reference.\n * @returns `\"schema\".\"name\" AS \"alias\"`.\n */\n protected tableRef(table: TableRef): Chunks {\n return [\n [table.schema, table.name]\n .filter((part): part is string => part !== undefined)\n .map(this.quote)\n .join('.'),\n ...(table.alias === undefined || table.alias === table.name\n ? []\n : [` AS ${this.quote(table.alias)}`]),\n ];\n }\n\n /**\n * Exhaustiveness guard of node switches.\n *\n * @param value - Unhandled node.\n * @throws Error always.\n */\n protected unexpected(value: never): never {\n throw new Error(`Unexpected AST node: ${JSON.stringify(value)}`);\n }\n}\n","import type {\n ConflictTarget,\n DeleteNode,\n ExprNode,\n InsertNode,\n OnConflictNode,\n SetItem,\n TruncateNode,\n UpdateNode,\n} from './ast.ts';\nimport type { ExpressionCompiler } from './expression-compiler.ts';\nimport type { QueryCompiler } from './query-compiler.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles INSERT, UPDATE, DELETE and TRUNCATE statements and their shared clauses. */\nexport class DmlCompiler extends ChunkBuilder {\n readonly #query: QueryCompiler;\n readonly #expr: ExpressionCompiler;\n readonly #setItem = (item: SetItem): Chunks => [\n `${this.quote(item.column)} = `,\n ...this.#expr.expression(item.value),\n ];\n\n /**\n * @param query - SELECT compiler; its expression compiler is shared.\n */\n constructor(query: QueryCompiler) {\n super();\n this.#query = query;\n this.#expr = query.expr;\n }\n\n /**\n * Compiles an INSERT statement.\n *\n * @param node - INSERT node.\n * @returns Chunks.\n */\n insert(node: InsertNode): Chunks {\n return [\n 'INSERT INTO ',\n ...this.tableRef(node.table),\n ...this.#insertValues(node),\n ...(node.onConflict === undefined ? [] : this.#onConflict(node.onConflict)),\n ...this.returning(node.returning, node.returningOld),\n ];\n }\n\n /**\n * Compiles an UPDATE statement.\n *\n * @param node - UPDATE node.\n * @returns Chunks.\n */\n update(node: UpdateNode): Chunks {\n return [\n 'UPDATE ',\n ...this.tableRef(node.table),\n ' SET ',\n ...this.setList(node.set),\n ...(node.from === undefined || node.from.length === 0\n ? []\n : [' FROM ', ...this.#query.fromList(node.from)]),\n ...this.#expr.where(node.where),\n ...this.returning(node.returning, node.returningOld),\n ];\n }\n\n /**\n * Compiles a DELETE statement.\n *\n * @param node - DELETE node.\n * @returns Chunks.\n */\n delete(node: DeleteNode): Chunks {\n return [\n 'DELETE FROM ',\n ...this.tableRef(node.table),\n ...(node.using === undefined || node.using.length === 0\n ? []\n : [' USING ', ...this.#query.fromList(node.using)]),\n ...this.#expr.where(node.where),\n ...this.returning(node.returning),\n ];\n }\n\n /**\n * Compiles a TRUNCATE statement.\n *\n * @param node - TRUNCATE node.\n * @returns Chunks.\n */\n truncate(node: TruncateNode): Chunks {\n return [\n 'TRUNCATE ',\n ...this.tableRef(node.table),\n node.restartIdentity === true ? ' RESTART IDENTITY' : '',\n node.cascade === true ? ' CASCADE' : '',\n ];\n }\n\n /**\n * Comma-separated `\"column\" = value` items.\n *\n * @param items - SET items.\n * @returns Chunks.\n */\n setList(items: readonly SetItem[]): Chunks {\n return this.joinAll(items.map(this.#setItem), ', ');\n }\n\n /**\n * Optional RETURNING clause.\n *\n * @param items - Returned expressions.\n * @param oldAlias - Alias of the pre-statement row (`WITH (OLD AS ...)`).\n * @returns Chunks, or nothing.\n */\n returning(items: readonly ExprNode[] | undefined, oldAlias?: string): Chunks {\n return items === undefined || items.length === 0\n ? []\n : [\n ' RETURNING ',\n oldAlias === undefined ? '' : `WITH (OLD AS ${this.quote(oldAlias)}) `,\n ...this.#expr.exprList(items),\n ];\n }\n\n #insertValues(node: InsertNode): Chunks {\n return node.select !== undefined\n ? [' ', ...this.columnList(node.columns), ' ', ...this.#query.query(node.select)]\n : node.columns.length === 0\n ? [' DEFAULT VALUES']\n : [\n ' ',\n ...this.columnList(node.columns),\n node.overriding === undefined\n ? ''\n : ` OVERRIDING ${node.overriding === 'system' ? 'SYSTEM' : 'USER'} VALUE`,\n ' VALUES ',\n ...this.#expr.rows(node.rows),\n ];\n }\n\n #conflictTarget(target: ConflictTarget): Chunks {\n return target.kind === 'constraint'\n ? [` ON CONSTRAINT ${this.quote(target.name)}`]\n : [' ', ...this.wrap(this.#expr.exprList(target.items)), ...this.#expr.where(target.where)];\n }\n\n #onConflict(node: OnConflictNode): Chunks {\n return [\n ' ON CONFLICT',\n ...(node.target === undefined ? [] : this.#conflictTarget(node.target)),\n ...(node.action.kind === 'nothing'\n ? [' DO NOTHING']\n : [\n ' DO UPDATE SET ',\n ...this.setList(node.action.set),\n ...this.#expr.where(node.action.where),\n ]),\n ];\n }\n}\n","import type { MergeAction, MergeNode, MergeWhen } from './ast.ts';\nimport type { DmlCompiler } from './dml-compiler.ts';\nimport type { ExpressionCompiler } from './expression-compiler.ts';\nimport type { QueryCompiler } from './query-compiler.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles MERGE statements. */\nexport class MergeCompiler extends ChunkBuilder {\n readonly #query: QueryCompiler;\n readonly #expr: ExpressionCompiler;\n readonly #dml: DmlCompiler;\n readonly #whenClause = (clause: MergeWhen): Chunks => this.#when(clause);\n\n /**\n * @param query - SELECT compiler; its expression compiler is shared.\n * @param dml - SET and RETURNING clauses.\n */\n constructor(query: QueryCompiler, dml: DmlCompiler) {\n super();\n this.#query = query;\n this.#expr = query.expr;\n this.#dml = dml;\n }\n\n /**\n * Compiles a MERGE statement.\n *\n * @param node - MERGE node.\n * @returns Chunks.\n */\n merge(node: MergeNode): Chunks {\n return [\n 'MERGE INTO ',\n ...this.tableRef(node.table),\n ' USING ',\n ...this.#source(node.source),\n ' ON ',\n ...this.#expr.expression(node.on),\n ...node.when.flatMap(this.#whenClause),\n ...this.#dml.returning(node.returning, node.returningOld),\n ];\n }\n\n #source(source: MergeNode['source']): Chunks {\n return source.kind === 'query'\n ? [...this.wrap(this.#query.query(source.query)), ` AS ${this.quote(source.alias)}`]\n : [\n ...this.wrap(['VALUES ', ...this.#expr.rows(source.rows)]),\n ` AS ${this.quote(source.alias)} `,\n ...this.columnList(source.columns),\n ];\n }\n\n #when(clause: MergeWhen): Chunks {\n return [\n ` WHEN ${clause.match}`,\n ...(clause.condition === undefined\n ? []\n : [' AND ', ...this.#expr.expression(clause.condition)]),\n ' THEN ',\n ...this.#action(clause.action),\n ];\n }\n\n #action(action: MergeAction): Chunks {\n switch (action.kind) {\n case 'update':\n return ['UPDATE SET ', ...this.#dml.setList(action.set)];\n case 'delete':\n return ['DELETE'];\n case 'nothing':\n return ['DO NOTHING'];\n case 'insert':\n return this.#insert(action);\n default:\n return this.unexpected(action);\n }\n }\n\n #insert(action: Extract<MergeAction, Readonly<{ kind: 'insert' }>>): Chunks {\n return action.columns.length === 0\n ? ['INSERT DEFAULT VALUES']\n : [\n 'INSERT ',\n ...this.columnList(action.columns),\n ' VALUES ',\n ...this.wrap(this.#expr.exprList(action.values)),\n ];\n }\n}\n","import type { CteCycle, CteNode, CteSearch, ModifyingNode, QueryNode, WithClause } from './ast.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles a CTE body: a query, or a data-modifying statement. */\nexport type CteBodyCompiler = (node: QueryNode | ModifyingNode) => Chunks;\n\n/** Compiles `WITH [RECURSIVE]` clauses with `MATERIALIZED`, `SEARCH` and `CYCLE`. */\nexport class WithCompiler extends ChunkBuilder {\n readonly #body: CteBodyCompiler;\n\n /**\n * @param body - Compiler of CTE bodies.\n */\n constructor(body: CteBodyCompiler) {\n super();\n this.#body = body;\n }\n\n /**\n * Compiles a WITH clause.\n *\n * @param clause - WITH clause.\n * @returns `WITH ... ` including the trailing space.\n */\n with(clause: WithClause): Chunks {\n return [\n clause.recursive ? 'WITH RECURSIVE ' : 'WITH ',\n ...this.joinAll(\n clause.ctes.map((cte) => this.#cte(cte)),\n ', ',\n ),\n ' ',\n ];\n }\n\n #cte(cte: CteNode): Chunks {\n return [\n `${this.quote(cte.name)} AS `,\n cte.materialized === undefined\n ? ''\n : cte.materialized\n ? 'MATERIALIZED '\n : 'NOT MATERIALIZED ',\n ...this.wrap(this.#body(cte.query)),\n this.#search(cte.search),\n this.#cycle(cte.cycle),\n ];\n }\n\n #search(search: CteSearch | undefined): string {\n return search === undefined\n ? ''\n : ` SEARCH ${search.mode} FIRST BY ${search.by.map(this.quote).join(', ')} SET ${this.quote(search.set)}`;\n }\n\n #cycle(cycle: CteCycle | undefined): string {\n return cycle === undefined\n ? ''\n : ` CYCLE ${cycle.columns.map(this.quote).join(', ')} SET ${this.quote(cycle.set)} USING ${this.quote(cycle.using)}`;\n }\n}\n","import type {\n FunctionSource,\n JsonTableColumn,\n JsonTableSource,\n TableRef,\n TableSample,\n ValuesSource,\n} from './ast.ts';\nimport type { ExpressionCompiler } from './expression-compiler.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles the FROM sources other than tables and subqueries: VALUES, functions, JSON_TABLE, TABLESAMPLE. */\nexport class FromCompiler extends ChunkBuilder {\n readonly #expr: ExpressionCompiler;\n\n /**\n * @param expr - Expression compiler of the arguments.\n */\n constructor(expr: ExpressionCompiler) {\n super();\n this.#expr = expr;\n }\n\n /**\n * A table with its optional sampling clause.\n *\n * @param table - Table reference.\n * @returns Chunks.\n */\n table(table: TableRef): Chunks {\n return [...this.tableRef(table), ...this.#sample(table.sample)];\n }\n\n /**\n * `(VALUES ...) AS alias(columns)`.\n *\n * @param source - VALUES source.\n * @returns Chunks.\n */\n values(source: ValuesSource): Chunks {\n return [\n ...this.wrap(['VALUES ', ...this.#expr.rows(source.values)]),\n ` AS ${this.quote(source.alias)}`,\n ...this.columnList(source.columns),\n ];\n }\n\n /**\n * Set-returning function call.\n *\n * @param source - Function source.\n * @returns Chunks.\n */\n function(source: FunctionSource): Chunks {\n return [\n source.function.map(this.quote).join('.'),\n ...this.wrap(this.#expr.exprList(source.args)),\n source.ordinality === undefined ? '' : ' WITH ORDINALITY',\n ` AS ${this.quote(source.alias)}`,\n ...(source.columns === undefined ? [] : this.columnList(source.columns)),\n ];\n }\n\n /**\n * `JSON_TABLE(...)`.\n *\n * @param source - JSON_TABLE source.\n * @returns Chunks.\n */\n jsonTable(source: JsonTableSource): Chunks {\n const { doc, path, columns } = source.jsonTable;\n return [\n 'JSON_TABLE(',\n ...this.#expr.expression(doc),\n `, ${path} COLUMNS (${columns.map((column) => this.#column(column)).join(', ')})) AS ${this.quote(source.alias)}`,\n ];\n }\n\n #column(column: JsonTableColumn): string {\n if (column.kind === 'ordinality') {\n return `${this.quote(column.name)} FOR ORDINALITY`;\n }\n const exists = column.kind === 'exists' ? ' EXISTS' : '';\n const path = column.path === undefined ? '' : ` PATH ${column.path}`;\n return `${this.quote(column.name)} ${column.type}${exists}${path}`;\n }\n\n #sample(sample: TableSample | undefined): Chunks {\n return sample === undefined\n ? []\n : [\n ` TABLESAMPLE ${sample.method} `,\n ...this.wrap(this.#expr.expression(sample.percent)),\n ...(sample.seed === undefined\n ? []\n : [' REPEATABLE ', ...this.wrap(this.#expr.expression(sample.seed))]),\n ];\n }\n}\n","import type {\n BetweenNode,\n BinaryNode,\n ExprNode,\n FnNode,\n LogicalNode,\n OrderNode,\n OverNode,\n QueryNode,\n} from './ast.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles SELECT statements nested in expressions (subqueries). */\nexport type SubqueryCompiler = Readonly<{ query(node: QueryNode): Chunks }>;\n\n// Dispatch is split in three switches to keep each short; the last one has the `never` check.\ntype CompoundNode = Exclude<\n ExprNode,\n Readonly<{ kind: 'param' | 'raw' | 'ident' | 'binary' | 'and' | 'or' | 'list' }>\n>;\ntype StructuralNode = Exclude<\n CompoundNode,\n Readonly<{ kind: 'star' | 'fn' | 'cast' | 'prefix' | 'postfix' | 'between' }>\n>;\n\n/** Compiles expression nodes, ORDER BY items and WHERE clauses into chunks. */\nexport class ExpressionCompiler extends ChunkBuilder {\n readonly #queries: SubqueryCompiler;\n readonly #expr = (node: ExprNode): Chunks => this.expression(node);\n readonly #orderItem = (node: OrderNode): Chunks => this.order(node);\n readonly #row = (row: readonly ExprNode[]): Chunks => this.wrap(this.exprList(row));\n\n /**\n * @param queries - Compiler of subqueries.\n */\n constructor(queries: SubqueryCompiler) {\n super();\n this.#queries = queries;\n }\n\n /**\n * Compiles an expression.\n *\n * @param node - Expression node.\n * @returns Chunks.\n */\n expression(node: ExprNode): Chunks {\n switch (node.kind) {\n case 'param':\n return [{ param: node.value }];\n case 'raw':\n return [node.sql];\n case 'ident':\n return [node.path.map(this.quote).join('.')];\n case 'binary':\n return this.#binary(node);\n case 'and':\n case 'or':\n return this.#logical(node);\n case 'list':\n return this.wrap(this.exprList(node.items));\n default:\n return this.#compound(node);\n }\n }\n\n /**\n * Comma-separated expressions.\n *\n * @param items - Expressions.\n * @returns `a, b`.\n */\n exprList(items: readonly ExprNode[]): Chunks {\n return this.joinAll(items.map(this.#expr), ', ');\n }\n\n /**\n * Comma-separated parenthesized rows.\n *\n * @param rows - Rows of expressions.\n * @returns `(a, b), (c, d)`.\n */\n rows(rows: readonly (readonly ExprNode[])[]): Chunks {\n return this.joinAll(rows.map(this.#row), ', ');\n }\n\n /**\n * Comma-separated ORDER BY items.\n *\n * @param items - Order items.\n * @returns `a ASC, b DESC NULLS LAST`.\n */\n orderList(items: readonly OrderNode[]): Chunks {\n return this.joinAll(items.map(this.#orderItem), ', ');\n }\n\n /**\n * One ORDER BY item.\n *\n * @param node - Order item.\n * @returns `expr ASC NULLS FIRST`.\n */\n order(node: OrderNode): Chunks {\n return [\n ...this.expression(node.expr),\n ...(node.direction === undefined ? [] : [` ${node.direction}`]),\n ...(node.nulls === undefined ? [] : [` NULLS ${node.nulls}`]),\n ];\n }\n\n /**\n * Optional WHERE clause.\n *\n * @param node - Condition.\n * @returns ` WHERE cond`, or nothing.\n */\n where(node: ExprNode | undefined): Chunks {\n return node === undefined ? [] : [' WHERE ', ...this.expression(node)];\n }\n\n #compound(node: CompoundNode): Chunks {\n switch (node.kind) {\n case 'star':\n return [node.table === undefined ? '*' : `${this.quote(node.table)}.*`];\n case 'fn':\n return this.#fn(node);\n case 'cast':\n return ['CAST(', ...this.expression(node.expr), ` AS ${node.type})`];\n case 'prefix':\n return [`${node.op} `, ...this.expression(node.expr)];\n case 'postfix':\n return [...this.expression(node.expr), ` ${node.op}`];\n case 'between':\n return this.#between(node);\n default:\n return this.#structural(node);\n }\n }\n\n #structural(node: StructuralNode): Chunks {\n switch (node.kind) {\n case 'excluded':\n return [`EXCLUDED.${this.quote(node.column)}`];\n case 'subquery':\n return this.wrap(this.#queries.query(node.query));\n case 'alias':\n return [...this.expression(node.expr), ` AS ${this.quote(node.alias)}`];\n case 'over':\n return this.#over(node);\n case 'values':\n return ['VALUES ', ...this.rows(node.rows)];\n default:\n return this.unexpected(node);\n }\n }\n\n #binary(node: BinaryNode): Chunks {\n return [...this.expression(node.left), ` ${node.op} `, ...this.expression(node.right)];\n }\n\n #logical(node: LogicalNode): Chunks {\n return node.items.length === 0\n ? [node.kind === 'and' ? 'TRUE' : 'FALSE']\n : node.items.length === 1 && node.items[0] !== undefined\n ? this.expression(node.items[0])\n : this.wrap(this.joinAll(node.items.map(this.#expr), ` ${node.kind.toUpperCase()} `));\n }\n\n #fn(node: FnNode): Chunks {\n return [\n `${node.name}(`,\n ...(node.distinct === true ? ['DISTINCT '] : []),\n ...this.exprList(node.args),\n ')',\n ];\n }\n\n #between(node: BetweenNode): Chunks {\n return [\n ...this.expression(node.expr),\n node.negated ? ' NOT BETWEEN ' : ' BETWEEN ',\n ...this.expression(node.low),\n ' AND ',\n ...this.expression(node.high),\n ];\n }\n\n #over(node: OverNode): Chunks {\n return [...this.expression(node.expr), ' OVER (', ...this.#window(node), ')'];\n }\n\n #window(node: OverNode): Chunks {\n return this.joinAll(\n [\n ...(node.partitionBy.length === 0\n ? []\n : [['PARTITION BY ', ...this.exprList(node.partitionBy)]]),\n ...(node.orderBy.length === 0 ? [] : [['ORDER BY ', ...this.orderList(node.orderBy)]]),\n ],\n ' ',\n );\n }\n}\n","import type {\n FromItem,\n JoinNode,\n LockNode,\n QueryNode,\n SelectNode,\n SetOperationNode,\n} from './ast.ts';\nimport { WithCompiler, type CteBodyCompiler } from './with-compiler.ts';\nimport { FromCompiler } from './from-compiler.ts';\nimport { ExpressionCompiler } from './expression-compiler.ts';\nimport { ChunkBuilder, type Chunks } from './sql-chunks.ts';\n\n/** Compiles SELECT statements with their FROM, JOIN, WITH and locking clauses. */\nexport class QueryCompiler extends ChunkBuilder {\n /** Expression compiler that compiles subqueries through this compiler. */\n readonly expr: ExpressionCompiler;\n readonly #sources: FromCompiler;\n readonly #with: WithCompiler;\n #modifying: CteBodyCompiler = (node) => this.unexpected(node as never);\n readonly #fromItem = (from: FromItem): Chunks => this.from(from);\n readonly #joinClause = (node: JoinNode): Chunks => this.#join(node);\n\n constructor() {\n super();\n this.expr = new ExpressionCompiler(this);\n this.#sources = new FromCompiler(this.expr);\n this.#with = new WithCompiler((node) => this.#cteBody(node));\n }\n\n /**\n * Compiles a SELECT statement.\n *\n * @param node - SELECT node.\n * @returns Chunks.\n */\n select(node: SelectNode): Chunks {\n return [...this.#selectHead(node), ...this.#selectTail(node)];\n }\n\n /**\n * Compiles a query expression: a SELECT or a set operation.\n *\n * @param node - Query node.\n * @returns Chunks.\n */\n query(node: QueryNode): Chunks {\n return node.kind === 'setop' ? this.#setOperation(node) : this.select(node);\n }\n\n /**\n * Sets the compiler of data-modifying CTE bodies (which live in the DML compiler).\n *\n * @param compile - Compiler of INSERT / UPDATE / DELETE statements.\n */\n useModifying(compile: CteBodyCompiler): void {\n this.#modifying = compile;\n }\n\n /**\n * One FROM source: a table or an aliased subquery.\n *\n * @param from - FROM source.\n * @returns Chunks.\n */\n from(from: FromItem): Chunks {\n if ('subquery' in from) {\n return [\n from.lateral === true ? 'LATERAL ' : '',\n ...this.wrap(this.query(from.subquery)),\n ` AS ${this.quote(from.alias)}`,\n ];\n }\n if ('values' in from) {\n return this.#sources.values(from);\n }\n if ('function' in from) {\n return this.#sources.function(from);\n }\n return 'jsonTable' in from ? this.#sources.jsonTable(from) : this.#sources.table(from);\n }\n\n /**\n * Comma-separated FROM sources.\n *\n * @param items - FROM sources.\n * @returns Chunks.\n */\n fromList(items: readonly FromItem[]): Chunks {\n return this.joinAll(items.map(this.#fromItem), ', ');\n }\n\n #selectHead(node: SelectNode): Chunks {\n const distinctOn = node.distinctOn ?? [];\n return [\n ...(node.with === undefined ? [] : this.#with.with(node.with)),\n node.distinct === true || distinctOn.length > 0 ? 'SELECT DISTINCT ' : 'SELECT ',\n ...(distinctOn.length === 0\n ? []\n : ['ON ', ...this.wrap(this.expr.exprList(distinctOn)), ' ']),\n ...this.expr.exprList(node.columns),\n ' FROM ',\n ...this.from(node.from),\n ...(node.joins ?? []).flatMap(this.#joinClause),\n ...(node.extraFrom ?? []).flatMap((item) => [', ', ...this.from(item)]),\n ];\n }\n\n #selectTail(node: SelectNode): Chunks {\n return [\n ...this.expr.where(node.where),\n ...(node.groupBy === undefined || node.groupBy.length === 0\n ? []\n : [' GROUP BY ', ...this.expr.exprList(node.groupBy)]),\n ...(node.having === undefined ? [] : [' HAVING ', ...this.expr.expression(node.having)]),\n ...(node.orderBy === undefined || node.orderBy.length === 0\n ? []\n : [' ORDER BY ', ...this.expr.orderList(node.orderBy)]),\n ...(node.limit === undefined || node.withTies === true\n ? []\n : [' LIMIT ', { param: node.limit }]),\n ...(node.offset === undefined ? [] : [' OFFSET ', { param: node.offset }]),\n ...(node.limit === undefined || node.withTies !== true\n ? []\n : [' FETCH FIRST ', { param: node.limit }, ' ROWS WITH TIES']),\n ...(node.lock === undefined ? [] : [this.#lock(node.lock)]),\n ];\n }\n\n #join(node: JoinNode): Chunks {\n return [\n ` ${node.type} JOIN `,\n ...this.from(node.table),\n ' ON ',\n ...this.expr.expression(node.on),\n ];\n }\n\n #lock(node: LockNode): string {\n return [\n ` FOR ${node.strength}`,\n node.of === undefined || node.of.length === 0\n ? ''\n : ` OF ${node.of.map(this.quote).join(', ')}`,\n node.wait === undefined ? '' : ` ${node.wait}`,\n ].join('');\n }\n\n #setOperation(node: SetOperationNode): Chunks {\n return [\n ...this.#operand(node.left),\n ` ${node.op}${node.all ? ' ALL' : ''} `,\n ...this.#operand(node.right),\n ];\n }\n\n // Parentheses only where the grammar needs them, so plain operands keep their text.\n #operand(node: QueryNode): Chunks {\n const needsParens =\n node.kind === 'setop' ||\n (node.orderBy?.length ?? 0) > 0 ||\n node.limit !== undefined ||\n node.offset !== undefined ||\n node.lock !== undefined ||\n node.with !== undefined;\n return needsParens ? this.wrap(this.query(node)) : this.select(node);\n }\n\n #cteBody(node: Parameters<CteBodyCompiler>[0]): Chunks {\n return node.kind === 'select' || node.kind === 'setop'\n ? this.query(node)\n : this.#modifying(node);\n }\n}\n","import type { ExprNode, StatementNode } from './ast.ts';\nimport { DmlCompiler } from './dml-compiler.ts';\nimport { IdentifierQuoter } from './identifier-quoter.ts';\nimport { MergeCompiler } from './merge-compiler.ts';\nimport { QueryCompiler } from './query-compiler.ts';\nimport type { Chunks, ParamChunk } from './sql-chunks.ts';\n\nexport type { Chunk, Chunks, ParamChunk } from './sql-chunks.ts';\n\n/** Parameterized SQL text with its bound values. */\nexport type CompiledQuery = Readonly<{ text: string; values: readonly unknown[] }>;\n\nconst quoter = new IdentifierQuoter();\n\nconst assertNever = (value: never): never => {\n throw new Error(`Unexpected AST node: ${JSON.stringify(value)}`);\n};\n\n/** Compiles SQL AST nodes into parameterized text with `$n` placeholders. Stateless. */\nexport class SqlCompiler {\n readonly #query = new QueryCompiler();\n readonly #dml = new DmlCompiler(this.#query);\n readonly #merge = new MergeCompiler(this.#query, this.#dml);\n\n constructor() {\n this.#query.useModifying((node) => this.#statement(node));\n }\n\n /** Quotes an identifier: `\"name\"`, doubling embedded quotes. */\n static quoteIdent(name: string): string {\n return quoter.quote(name);\n }\n\n /** Compiles a statement. */\n compile(node: StatementNode): CompiledQuery {\n return this.finalize(this.#statement(node));\n }\n\n /** Compiles a standalone expression. */\n compileExpr(node: ExprNode): CompiledQuery {\n return this.finalize(this.#query.expr.expression(node));\n }\n\n /** Joins chunks into text, numbering distinct parameter chunks `$1`, `$2`, ... */\n finalize(chunks: Chunks): CompiledQuery {\n const positions = new Map<ParamChunk, number>();\n const values: unknown[] = [];\n let text = '';\n for (const chunk of chunks) {\n if (typeof chunk === 'string') {\n text += chunk;\n continue;\n }\n let position = positions.get(chunk);\n if (position === undefined) {\n values.push(chunk.param);\n position = values.length;\n positions.set(chunk, position);\n }\n text += `$${position}`;\n }\n return { text, values };\n }\n\n #statement(node: StatementNode): Chunks {\n switch (node.kind) {\n case 'select':\n return this.#query.select(node);\n case 'setop':\n return this.#query.query(node);\n case 'insert':\n return this.#dml.insert(node);\n case 'update':\n return this.#dml.update(node);\n case 'delete':\n return this.#dml.delete(node);\n case 'truncate':\n return this.#dml.truncate(node);\n case 'merge':\n return this.#merge.merge(node);\n default:\n return assertNever(node);\n }\n }\n}\n","import type { IncludeNode } from '../associations/include.ts';\n\nconst UNCHANGED: ReadonlySet<string> = new Set();\nconst NO_INCLUDES: readonly IncludeNode[] = [];\n// A symbol-keyed own property: invisible to attribute enumeration, JSON and the instance type.\nconst STATE = Symbol('postgrelize.instanceState');\n\n/**\n * Internal state of one model instance: changed attribute names, the include tree it was built\n * with, and the write metadata exposed as `wasInserted` / `oldValues`. Stored under a private symbol\n * (no attribute-like member, no private field that would break mixin declaration types).\n */\nexport class InstanceState {\n /**\n * Creates the state of a new instance.\n *\n * @param instance - Model instance.\n */\n static attach(instance: object): void {\n (instance as Record<symbol, InstanceState>)[STATE] = new InstanceState();\n }\n\n /**\n * State of an instance.\n *\n * @param instance - Model instance.\n * @returns Its state.\n */\n static of(instance: object): InstanceState {\n return (instance as Record<symbol, InstanceState>)[STATE] as InstanceState;\n }\n\n /**\n * Whether a value is a model instance (has a state).\n *\n * @param value - Any value.\n * @returns True for model instances.\n */\n static has(value: unknown): boolean {\n return typeof value === 'object' && value !== null && STATE in value;\n }\n\n /**\n * Changed attribute names. The set belongs to this instance and grows in place; readers copy it\n * (`[...changed]`) when they need a snapshot.\n */\n changed: ReadonlySet<string> = UNCHANGED;\n /** Include tree of a nested build. */\n includes: readonly IncludeNode[] = NO_INCLUDES;\n /** Whether the row was inserted (`true`) or updated (`false`) by an `ON CONFLICT` write. */\n wasInserted: boolean | undefined = undefined;\n /** Pre-statement values from `returningOld`, `null` for inserted rows. */\n oldValues: Readonly<Record<string, unknown>> | null | undefined = undefined;\n\n /**\n * Marks an attribute as changed or unchanged.\n *\n * @param name - Attribute name.\n * @param changed - Changed flag.\n */\n mark(name: string, changed: boolean): void {\n if (!changed) {\n (this.changed as Set<string>).delete(name);\n } else if (this.changed === UNCHANGED) {\n this.changed = new Set([name]);\n } else {\n (this.changed as Set<string>).add(name);\n }\n }\n\n /** Forgets all changes (after a load or save). */\n reset(): void {\n this.changed = UNCHANGED;\n }\n}\n","import type { ModelDefinition } from './model-definition.ts';\n\ntype AttributeHost = Readonly<{\n get: (name: string) => unknown;\n set: (name: string, value: unknown) => unknown;\n}>;\n\ntype AssociationHost = Readonly<{ dataValues: Record<string, unknown> }>;\n\n/**\n * Installs `instance.<attribute>` and `instance.<alias>` accessors on model prototypes.\n *\n * @internal\n */\nexport class ModelAccessors {\n /**\n * Defines `instance.<attribute>` getters / setters on the model prototype (once per attribute).\n *\n * @param prototype - Model prototype.\n * @param definition - Model definition.\n */\n defineAttributes(prototype: object, definition: ModelDefinition): void {\n [...definition.attributes.keys()]\n .filter((name) => !Object.prototype.hasOwnProperty.call(prototype, name))\n .forEach((name) =>\n Object.defineProperty(prototype, name, {\n configurable: true,\n enumerable: false,\n get(this: AttributeHost) {\n return this.get(name);\n },\n set(this: AttributeHost, value: unknown) {\n this.set(name, value);\n },\n }),\n );\n }\n\n /**\n * Defines `instance.<alias>` for an association, holding included / nested instances.\n *\n * @param prototype - Model prototype.\n * @param alias - Association alias.\n */\n defineAssociation(prototype: object, alias: string): void {\n if (Object.prototype.hasOwnProperty.call(prototype, alias)) {\n return;\n }\n Object.defineProperty(prototype, alias, {\n configurable: true,\n enumerable: false,\n get(this: AssociationHost) {\n return this.dataValues[alias];\n },\n set(this: AssociationHost, value: unknown) {\n this.dataValues[alias] = value;\n },\n });\n }\n}\n","/**\n * Hook names accepted by `addHook` (Sequelize v6). Model lifecycle hooks, `beforeConnect` and the sync hooks\n * (`beforeBulkSync`, `afterBulkSync`, `beforeSync`, `afterSync`) run; the other connection / define hooks are accepted\n * and not run yet.\n */\nexport const HOOK_TYPES = [\n 'beforeValidate',\n 'afterValidate',\n 'validationFailed',\n 'beforeCreate',\n 'afterCreate',\n 'beforeUpdate',\n 'afterUpdate',\n 'beforeSave',\n 'afterSave',\n 'beforeDestroy',\n 'afterDestroy',\n 'beforeRestore',\n 'afterRestore',\n 'beforeUpsert',\n 'afterUpsert',\n 'beforeBulkCreate',\n 'afterBulkCreate',\n 'beforeBulkUpdate',\n 'afterBulkUpdate',\n 'beforeBulkDestroy',\n 'afterBulkDestroy',\n 'beforeBulkRestore',\n 'afterBulkRestore',\n 'beforeFind',\n 'beforeFindAfterExpandIncludeAll',\n 'beforeFindAfterOptions',\n 'afterFind',\n 'beforeCount',\n 'beforeConnect',\n 'afterConnect',\n 'beforeDisconnect',\n 'afterDisconnect',\n 'beforePoolAcquire',\n 'afterPoolAcquire',\n 'beforeQuery',\n 'afterQuery',\n 'beforeSync',\n 'afterSync',\n 'beforeBulkSync',\n 'afterBulkSync',\n 'beforeDefine',\n 'afterDefine',\n 'beforeInit',\n 'afterInit',\n 'beforeAssociate',\n 'afterAssociate',\n] as const;\n\n/** One of {@link HOOK_TYPES}. */\nexport type HookType = (typeof HOOK_TYPES)[number];\n\n/** Hook function. May be async; its return value is ignored. Receives the model class as `this`. */\nexport type HookFunction = (...args: never[]) => unknown;\n\n/** Registered hook: a function, optionally named so it can be removed by name. */\nexport type Hook = Readonly<{\n /** Hook name, used by `removeHook`. */\n name?: string;\n /** Hook function. */\n fn: HookFunction;\n}>;\n\n/** Hooks passed in `init({ hooks })` / `define({ hooks })`: one function or a list per hook type. */\nexport type HooksOption = Partial<\n Readonly<Record<HookType, HookFunction | readonly HookFunction[]>>\n>;\n\nconst PROXIES: Partial<Readonly<Record<HookType, readonly HookType[]>>> = {\n beforeSave: ['beforeUpdate', 'beforeCreate', 'beforeSave'],\n afterSave: ['afterUpdate', 'afterCreate', 'afterSave'],\n};\n\nconst HOOK_SET: ReadonlySet<string> = new Set(HOOK_TYPES);\n\n/** Result when no hook is registered: nothing to wait for, no promise chain to build. */\nconst NO_HOOKS_RAN: Promise<void> = Promise.resolve();\n\n/**\n * Immutable registry of hooks by type: `add` and `remove` return a new registry, so a model or `Sequelize`\n * instance replaces its registry on change.\n */\nexport class HookRegistry {\n /** Registry without hooks. */\n static readonly EMPTY: HookRegistry = new HookRegistry(new Map());\n\n readonly #hooks: ReadonlyMap<HookType, readonly Hook[]>;\n\n private constructor(hooks: ReadonlyMap<HookType, readonly Hook[]>) {\n this.#hooks = hooks;\n }\n\n /**\n * Builds a registry from the `hooks` option.\n *\n * @param option - One function or a list per hook type.\n * @param base - Registry the hooks are added to.\n * @returns Registry with the hooks of `base`, then those of `option`.\n */\n static fromOption(\n option: HooksOption | undefined,\n base: HookRegistry = HookRegistry.EMPTY,\n ): HookRegistry {\n return Object.entries(option ?? {}).reduce<HookRegistry>(\n (registry, [type, value]) =>\n (Array.isArray(value) ? value : [value]).reduce<HookRegistry>(\n (next, fn: HookFunction) => next.add(type, fn),\n registry,\n ),\n base,\n );\n }\n\n /**\n * Runs hooks of `type` from each registry in order (model hooks first, then Sequelize-level hooks).\n *\n * @param registries - Registries in run order.\n * @param type - Hook type.\n * @param context - `this` of the hook functions.\n * @param args - Hook arguments.\n * @returns Resolves when all hooks finished.\n */\n static runAll(\n registries: readonly HookRegistry[],\n type: HookType,\n context: unknown,\n ...args: readonly unknown[]\n ): Promise<void> {\n const hooks: Hook[] = [];\n for (const registry of registries) {\n const own = registry.#hooks.get(type);\n if (own !== undefined) {\n hooks.push(...own);\n }\n }\n return hooks.length === 0 ? NO_HOOKS_RAN : HookRegistry.#runInOrder(hooks, context, args);\n }\n\n static async #runInOrder(\n hooks: readonly Hook[],\n context: unknown,\n args: readonly unknown[],\n ): Promise<void> {\n for (const hook of hooks) {\n // oxlint-disable-next-line no-await-in-loop -- hooks of one type run one after another.\n await (hook.fn as (...callArgs: unknown[]) => unknown).apply(context, args as unknown[]);\n }\n }\n\n /**\n * Returns a registry with `fn` added (to the proxied types for `beforeSave` / `afterSave`, like v6).\n *\n * @param type - Hook type.\n * @param fn - Hook function.\n * @param name - Name to remove the hook by.\n * @returns New registry; the receiver is not modified.\n * @throws Error for an unknown hook type.\n *\n * @example\n * ```ts\n * let registry!: HookRegistry;\n * const next = registry.add('beforeCreate', () => {}, 'audit');\n * next.has('beforeCreate');\n * ```\n */\n add(type: string, fn: HookFunction, name?: string): HookRegistry {\n const hook: Hook = name === undefined ? { fn } : { name, fn };\n const types = HookRegistry.#targets(type);\n return new HookRegistry(\n new Map([\n ...this.#hooks,\n ...types.map((target) => [target, [...(this.#hooks.get(target) ?? []), hook]] as const),\n ]),\n );\n }\n\n /**\n * Returns a registry without hooks matching `nameOrFn`.\n *\n * @param type - Hook type.\n * @param nameOrFn - Hook name or function; all hooks of the type when omitted.\n * @returns New registry; the receiver is not modified.\n * @throws Error for an unknown hook type.\n *\n * @example\n * ```ts\n * let registry!: HookRegistry;\n * const next = registry.remove('beforeCreate', 'audit');\n * next.has('beforeCreate');\n * ```\n */\n remove(type: string, nameOrFn?: string | HookFunction): HookRegistry {\n const types = HookRegistry.#targets(type);\n const keep = (hook: Hook): boolean =>\n nameOrFn !== undefined &&\n (typeof nameOrFn === 'string' ? hook.name !== nameOrFn : hook.fn !== nameOrFn);\n return new HookRegistry(\n new Map([\n ...this.#hooks,\n ...types.map((target) => [target, (this.#hooks.get(target) ?? []).filter(keep)] as const),\n ]),\n );\n }\n\n /**\n * Checks whether the registry has hooks of the type.\n *\n * @param type - Hook type.\n * @returns True when at least one hook exists.\n * @throws Error for an unknown hook type.\n *\n * @example\n * ```ts\n * let registry!: HookRegistry;\n * if (registry.has('afterCreate')) {\n * console.log('afterCreate hooks registered');\n * }\n * ```\n */\n has(type: string): boolean {\n return (this.#hooks.get(HookRegistry.#assertHookType(type)) ?? []).length > 0;\n }\n\n /**\n * Like {@link HookRegistry.has}, but `undefined` for a type that never had a hook (what\n * Sequelize v6 `hasHook` returns).\n *\n * @param type - Hook type.\n * @returns Whether hooks exist, `undefined` when none was ever added.\n * @throws Error for an unknown hook type.\n * @example\n * ```ts\n * let registry!: HookRegistry;\n * const known = registry.hasOrUndefined('beforeCreate'); // undefined until a hook was added\n * ```\n */\n hasOrUndefined(type: string): boolean | undefined {\n const hooks = this.#hooks.get(HookRegistry.#assertHookType(type));\n return hooks === undefined ? undefined : hooks.length > 0;\n }\n\n /**\n * Runs the hooks of `type` in registration order.\n *\n * @param type - Hook type.\n * @param context - `this` of the hook functions.\n * @param args - Hook arguments.\n * @returns Resolves when all hooks finished; a rejecting hook stops the chain.\n *\n * @example\n * ```ts\n * let registry!: HookRegistry;\n * await registry.run('beforeCreate', User, { name: 'Ann' }, {});\n * ```\n */\n run(type: HookType, context: unknown, ...args: readonly unknown[]): Promise<void> {\n return HookRegistry.runAll([this], type, context, ...args);\n }\n\n static #targets(type: string): readonly HookType[] {\n const hookType = HookRegistry.#assertHookType(type);\n return PROXIES[hookType] ?? [hookType];\n }\n\n static #assertHookType(type: string): HookType {\n if (!HOOK_SET.has(type)) {\n throw new Error(`${type} is not a valid hook type`);\n }\n return type as HookType;\n }\n}\n","import inflection from 'inflection';\nimport { AbstractDataType } from '../data-types/abstract-data-type.ts';\nimport type { DataTypeInput } from '../data-types/data-types.ts';\nimport type { AttributeDefinition, AttributeOptions } from './attribute-options.ts';\n\n/**\n * Normalizes declared attributes (`Model.init` input) into attribute definitions.\n *\n * @internal\n */\nexport class AttributeNormalizer {\n /**\n * Normalizes one attribute: column name, data type instance, `allowNull` default.\n *\n * @param name - Attribute name.\n * @param input - Data type or column options.\n * @param underscored - Derive the column name in snake case.\n * @returns Frozen attribute definition.\n */\n attribute(\n name: string,\n input: DataTypeInput | AttributeOptions,\n underscored: boolean,\n ): AttributeDefinition {\n const options: AttributeOptions = this.isOptions(input) ? input : { type: input };\n const { type, field, ...rest } = options;\n return Object.freeze({\n ...rest,\n fieldName: name,\n field: field ?? this.underscoredIf(name, underscored),\n type: AbstractDataType.from(type),\n allowNull: options.allowNull ?? options.primaryKey !== true,\n ...(options.identity === undefined ? {} : { autoIncrement: true }),\n });\n }\n\n /**\n * Whether a declared attribute is given as column options rather than as a bare type.\n *\n * @param value - Declared attribute.\n * @returns True for column options.\n */\n isOptions(value: DataTypeInput | AttributeOptions): value is AttributeOptions {\n return typeof value === 'object' && 'type' in value && typeof value.type !== 'string';\n }\n\n /**\n * Snake-cases a name when `underscored` is set.\n *\n * @param name - Name.\n * @param underscored - `underscored` option.\n * @returns The name.\n */\n underscoredIf(name: string, underscored: boolean): string {\n return underscored ? inflection.underscore(name) : name;\n }\n\n /**\n * Unique keys from attribute `unique` options.\n *\n * @param tableName - Table name (prefix of default key names).\n * @param list - Normalized attributes in definition order.\n * @returns Key name → attribute names (in definition order).\n */\n uniqueKeys(\n tableName: string,\n list: readonly AttributeDefinition[],\n ): ReadonlyMap<string, readonly string[]> {\n const named = list.flatMap((attribute) => {\n const name = this.#uniqueKeyName(tableName, attribute);\n return name === undefined ? [] : [[name, attribute.fieldName] as const];\n });\n return new Map(\n [...new Set(named.map(([name]) => name))].map((name) => [\n name,\n named.filter(([key]) => key === name).map(([, attribute]) => attribute),\n ]),\n );\n }\n\n #uniqueKeyName(tableName: string, attribute: AttributeDefinition): string | undefined {\n const { unique } = attribute;\n return unique === undefined || unique === false\n ? undefined\n : typeof unique === 'string'\n ? unique\n : typeof unique === 'object' && unique.name !== undefined\n ? unique.name\n : `${tableName}_${attribute.fieldName}_unique`;\n }\n}\n","import inflection from 'inflection';\nimport type { ModelDefaults } from '../connection/options.ts';\nimport { DataTypes } from '../data-types/data-types.ts';\nimport { AttributeNormalizer } from './attribute-normalizer.ts';\nimport type { AttributeDefinition, ModelAttributes } from './attribute-options.ts';\nimport type { DefinitionOptions, ModelDefinitionFields } from './model-definition.ts';\n\ntype SpecialAttributes = Readonly<{\n createdAt: string | undefined;\n updatedAt: string | undefined;\n deletedAt: string | undefined;\n version: string | undefined;\n}>;\n\nconst attributes = new AttributeNormalizer();\n\n/**\n * Normalizes `Model.init` arguments into the fields of a model definition, applying Sequelize v6\n * defaults (table name, automatic primary key, timestamps, paranoid, version, unique keys).\n *\n * @internal\n */\nexport class DefinitionNormalizer {\n readonly #attributes: ModelAttributes;\n readonly #associationAttributes: ModelAttributes;\n readonly #options: DefinitionOptions;\n readonly #name: string;\n readonly #underscored: boolean;\n readonly #tableName: string;\n\n /**\n * @param className - Class name (default model name).\n * @param declared - Declared attributes.\n * @param options - Model options.\n * @param defaults - `define` defaults of the Sequelize instance.\n * @param associationAttributes - Attributes added by associations (foreign keys).\n */\n constructor(\n className: string,\n declared: ModelAttributes,\n options: DefinitionOptions,\n defaults: ModelDefaults,\n associationAttributes: ModelAttributes,\n ) {\n this.#attributes = declared;\n this.#associationAttributes = associationAttributes;\n this.#options = { timestamps: true, ...defaults, ...options };\n this.#name = this.#options.modelName ?? className;\n this.#underscored = this.#options.underscored === true;\n this.#tableName =\n this.#options.tableName ??\n (this.#options.freezeTableName === true\n ? this.#name\n : attributes.underscoredIf(inflection.pluralize(this.#name), this.#underscored));\n }\n\n /**\n * Normalized definition fields.\n *\n * @returns The fields.\n */\n fields(): ModelDefinitionFields {\n const special = this.#specialAttributes();\n const normalized = this.#normalizedAttributes(special);\n const list = [...normalized.values()];\n return {\n name: this.#name,\n tableName: this.#tableName,\n schema: this.#options.schema,\n attributes: normalized,\n fieldToAttribute: new Map(list.map((attribute) => [attribute.field, attribute.fieldName])),\n primaryKeys: list\n .filter((attribute) => attribute.primaryKey === true)\n .map((attribute) => attribute.fieldName),\n ...special,\n uniqueKeys: attributes.uniqueKeys(this.#tableName, list),\n options: this.#options,\n };\n }\n\n #specialAttributes(): SpecialAttributes {\n const options = this.#options;\n const timestamps = options.timestamps === true;\n return {\n createdAt: timestamps ? this.#timestampName(options.createdAt, 'createdAt') : undefined,\n updatedAt: timestamps ? this.#timestampName(options.updatedAt, 'updatedAt') : undefined,\n deletedAt:\n timestamps && options.paranoid === true\n ? this.#timestampName(options.deletedAt, 'deletedAt')\n : undefined,\n version:\n options.version === undefined || options.version === false\n ? undefined\n : typeof options.version === 'string'\n ? options.version\n : 'version',\n };\n }\n\n #timestampName(option: string | boolean | undefined, fallback: string): string | undefined {\n return option === false ? undefined : typeof option === 'string' ? option : fallback;\n }\n\n #normalizedAttributes(special: SpecialAttributes): Map<string, AttributeDefinition> {\n const withAssociations: ModelAttributes = {\n ...this.#associationAttributes,\n ...this.#attributes,\n };\n const generated = new Set([\n ...Object.keys(this.#autoPrimaryKey(withAssociations)),\n special.createdAt,\n special.updatedAt,\n special.deletedAt,\n special.version,\n ]);\n const all: ModelAttributes = {\n ...this.#autoPrimaryKey(withAssociations),\n ...this.#attributes,\n ...this.#undeclared(this.#timestampAttributes(special)),\n ...this.#undeclared(this.#associationAttributes),\n };\n return new Map(Object.entries(all).map(([name, input]) => this.#entry(name, input, generated)));\n }\n\n #entry(\n name: string,\n input: ModelAttributes[string],\n generated: ReadonlySet<string | undefined>,\n ): readonly [string, AttributeDefinition] {\n const definition = attributes.attribute(name, input, this.#underscored);\n return [\n name,\n generated.has(name) && !(name in this.#attributes)\n ? Object.freeze({ ...definition, _autoGenerated: true })\n : definition,\n ];\n }\n\n #undeclared(added: ModelAttributes): ModelAttributes {\n return Object.fromEntries(Object.entries(added).filter(([key]) => !(key in this.#attributes)));\n }\n\n #autoPrimaryKey(declared: ModelAttributes): ModelAttributes {\n const entries = Object.values(declared);\n if (entries.some((value) => attributes.isOptions(value) && value.primaryKey === true)) {\n return {};\n }\n if ('id' in declared) {\n throw new Error(\n `A column called 'id' was added to the attributes of '${this.#tableName}' but not marked with 'primaryKey: true'`,\n );\n }\n return {\n id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },\n };\n }\n\n #timestampAttributes({\n createdAt,\n updatedAt,\n deletedAt,\n version,\n }: SpecialAttributes): ModelAttributes {\n return Object.fromEntries([\n ...[createdAt, updatedAt]\n .filter((name): name is string => name !== undefined)\n .map((name) => [name, { type: DataTypes.DATE, allowNull: false }] as const),\n ...(deletedAt === undefined ? [] : [[deletedAt, { type: DataTypes.DATE }] as const]),\n ...(version === undefined\n ? []\n : [[version, { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }] as const]),\n ]);\n }\n}\n","import type { ModelDefaults } from '../connection/options.ts';\nimport type { DataTypeInput } from '../data-types/data-types.ts';\nimport type { IndexOptions } from '../ddl/ddl-generator.ts';\nimport { AttributeNormalizer } from './attribute-normalizer.ts';\nimport type {\n AttributeDefinition,\n AttributeOptions,\n ModelAttributes,\n} from './attribute-options.ts';\nimport { DefinitionNormalizer } from './definition-normalizer.ts';\n\nexport type {\n AttributeDefinition,\n AttributeOptions,\n GeneratedColumn,\n ModelAttributes,\n ReferencedTable,\n ReferenceOptions,\n UniqueOptions,\n} from './attribute-options.ts';\n\nconst attributeNormalizer = new AttributeNormalizer();\n\n/**\n * Table-level model options shared by `Model.init` and `sequelize.define`.\n *\n * Extends the model defaults (`paranoid`, `timestamps`, `schema`, ...).\n *\n * @example\n * ```ts\n * const opts: DefinitionOptions = {\n * modelName: 'Invoice',\n * tableName: 'invoices',\n * timestamps: true,\n * paranoid: true,\n * version: true,\n * indexes: [{ fields: ['number'], unique: true }],\n * };\n * ```\n */\nexport type DefinitionOptions = ModelDefaults &\n Readonly<{\n /** Model name. Defaults to the class name. */\n modelName?: string;\n /** Table name. Defaults to the pluralized model name. */\n tableName?: string;\n /** Separator between schema and table that `getTableName` reports (PostgreSQL always uses `.` in SQL). */\n schemaDelimiter?: string;\n /** Name of the created-at attribute, or `false` to disable it.\n * @defaultValue 'createdAt' */\n createdAt?: string | boolean;\n /** Name of the updated-at attribute, or `false` to disable it.\n * @defaultValue 'updatedAt' */\n updatedAt?: string | boolean;\n /** Name of the deleted-at attribute of paranoid models.\n * @defaultValue 'deletedAt' */\n deletedAt?: string | boolean;\n /** Optimistic locking: `true` adds a `version` attribute, a string names it. */\n version?: boolean | string;\n /** Indexes created by `sync()`. */\n indexes?: readonly IndexOptions[];\n /** Table comment. */\n comment?: string;\n /** `CREATE UNLOGGED TABLE` on `sync`: faster writes, no WAL, emptied after a crash, not replicated. */\n unlogged?: boolean;\n /** `CREATE TEMPORARY TABLE` on `sync`: lives as long as the database session; cannot have a `schema`. See {@link QueryInterface.createTable}. */\n temporary?: boolean;\n }>;\n\n/** Normalized fields of a {@link ModelDefinition}. */\nexport type ModelDefinitionFields = Readonly<{\n /** Model name. */\n name: string;\n /** Table name. */\n tableName: string;\n /** Table schema. */\n schema: string | undefined;\n /** Normalized attributes by attribute name. */\n attributes: ReadonlyMap<string, AttributeDefinition>;\n /** Attribute name by column name. */\n fieldToAttribute: ReadonlyMap<string, string>;\n /** Primary key attribute names. */\n primaryKeys: readonly string[];\n /** Created-at attribute. */\n createdAt: string | undefined;\n /** Updated-at attribute. */\n updatedAt: string | undefined;\n /** Deleted-at attribute when the model is paranoid. */\n deletedAt: string | undefined;\n /** Version attribute when optimistic locking is enabled. */\n version: string | undefined;\n /** Unique keys from attribute `unique` options: key name → attribute names (in definition order). */\n uniqueKeys: ReadonlyMap<string, readonly string[]>;\n /** Model options after defaults were applied. */\n options: DefinitionOptions;\n}>;\n\n/**\n * Immutable normalized model definition: table, attributes, keys, timestamps and options of a\n * model, built from `Model.init` arguments with Sequelize v6 defaults by {@link ModelDefinition.normalize}.\n */\nexport class ModelDefinition {\n /** Model name. */\n readonly name: string;\n /** Table name. */\n readonly tableName: string;\n /** Table schema. */\n readonly schema: string | undefined;\n /** Normalized attributes by attribute name. */\n readonly attributes: ReadonlyMap<string, AttributeDefinition>;\n /** Attribute name by column name. */\n readonly fieldToAttribute: ReadonlyMap<string, string>;\n /** Primary key attribute names. */\n readonly primaryKeys: readonly string[];\n /** Created-at attribute. */\n readonly createdAt: string | undefined;\n /** Updated-at attribute. */\n readonly updatedAt: string | undefined;\n /** Deleted-at attribute when the model is paranoid. */\n readonly deletedAt: string | undefined;\n /** Version attribute when optimistic locking is enabled. */\n readonly version: string | undefined;\n /** Unique keys from attribute `unique` options: key name → attribute names (in definition order). */\n readonly uniqueKeys: ReadonlyMap<string, readonly string[]>;\n /** Model options after defaults were applied. */\n readonly options: DefinitionOptions;\n\n /**\n * @param fields - Normalized fields; the instance is frozen.\n */\n constructor(fields: ModelDefinitionFields) {\n this.name = fields.name;\n this.tableName = fields.tableName;\n this.schema = fields.schema;\n this.attributes = fields.attributes;\n this.fieldToAttribute = fields.fieldToAttribute;\n this.primaryKeys = fields.primaryKeys;\n this.createdAt = fields.createdAt;\n this.updatedAt = fields.updatedAt;\n this.deletedAt = fields.deletedAt;\n this.version = fields.version;\n this.uniqueKeys = fields.uniqueKeys;\n this.options = fields.options;\n Object.freeze(this);\n }\n\n /**\n * Normalizes one attribute: column name, data type instance, `allowNull` default.\n *\n * @param name - Attribute name.\n * @param input - Data type or column options.\n * @param underscored - Derive the column name in snake case.\n * @returns Frozen attribute definition.\n */\n static attribute(\n name: string,\n input: DataTypeInput | AttributeOptions,\n underscored: boolean,\n ): AttributeDefinition {\n return attributeNormalizer.attribute(name, input, underscored);\n }\n\n /**\n * Normalizes `Model.init` arguments into an immutable definition, applying Sequelize v6 defaults.\n *\n * @param className - Class name (default model name).\n * @param attributes - Declared attributes.\n * @param options - Model options.\n * @param defaults - `define` defaults of the Sequelize instance.\n * @param associationAttributes - Attributes added by associations (foreign keys).\n * @returns The definition.\n */\n static normalize(\n className: string,\n attributes: ModelAttributes,\n options: DefinitionOptions,\n defaults: ModelDefaults = {},\n associationAttributes: ModelAttributes = {},\n ): ModelDefinition {\n return new ModelDefinition(\n new DefinitionNormalizer(\n className,\n attributes,\n options,\n defaults,\n associationAttributes,\n ).fields(),\n );\n }\n}\n","import type { QueryResult } from '../connection/connection-manager.ts';\nimport type { LoggingFunction, ModelDefaults } from '../connection/options.ts';\nimport type { CompiledQuery } from '../sql/compile.ts';\nimport type { HookRegistry } from '../hooks/hooks.ts';\nimport type { QueryInterface } from '../query-interface/query-interface.ts';\nimport type { Transaction, TransactionOptions } from '../transaction/transaction.ts';\n\n/** Options common to every query issued by a model. */\nexport type QueryOptionsBase = Readonly<{\n /** Transaction to run in; `null` forces running outside the CLS transaction. */\n transaction?: Transaction | null;\n /** SQL logger for this query, or `false`. */\n logging?: LoggingFunction | false;\n /** Pass query duration to the logger. */\n benchmark?: boolean;\n /**\n * `statement_timeout` for this query only, in milliseconds (non-negative integer; `0` disables it).\n * PostgreSQL cancels the statement with a `DatabaseError` (code `57014`) when it runs longer.\n * Outside a transaction the query runs in its own short transaction; inside one the previous\n * timeout is restored afterwards. PostgreSQL extension.\n */\n statementTimeout?: number;\n /** Force the writer even for SELECTs when read replicas are configured. */\n useMaster?: boolean;\n}>;\n\n/** Services a `Sequelize` instance provides to its models. */\nexport type ModelRuntime = Readonly<{\n execute: (\n query: CompiledQuery,\n options: QueryOptionsBase,\n kind?: 'read' | 'write',\n ) => Promise<QueryResult>;\n transaction: <T>(\n run: (transaction: Transaction) => Promise<T>,\n parent?: Transaction | null,\n ) => Promise<T>;\n register: (name: string, model: object) => void;\n /** Defines a model through the owning Sequelize instance (used for implicit through models). */\n defineModel: (\n name: string,\n attributes: Readonly<Record<string, unknown>>,\n options: Readonly<Record<string, unknown>>,\n ) => object;\n /** Schema API of the owning Sequelize instance. */\n queryInterface: () => QueryInterface;\n /** Streams encoded lines into `COPY ... FROM STDIN`. */\n copyFrom: (\n text: string,\n lines: AsyncIterable<string>,\n options: QueryOptionsBase,\n ) => Promise<number>;\n /** Streams `COPY ... TO STDOUT` output. */\n copyTo: (\n text: string,\n options: QueryOptionsBase,\n kind?: 'read' | 'write',\n ) => AsyncGenerator<Buffer, void, undefined>;\n /** Starts an unmanaged transaction. */\n beginTransaction: (options?: TransactionOptions) => Promise<Transaction>;\n /** `server_version_num` of the database (cached). */\n serverVersion: () => Promise<number>;\n /** Registered models by name. */\n models: () => Readonly<Record<string, object>>;\n hooks: () => HookRegistry;\n defaults: ModelDefaults;\n inAsAnyThreshold: number | undefined;\n}>;\n\n/** @internal */\nexport const runtimeKey: unique symbol = Symbol('postgrelize.runtime');\n\n/** Owner of the internal model services: the `Sequelize` instance. */\n// An interface (not a type alias) so declaration files reference it by name instead of inlining\n// the internal symbol key.\nexport interface RuntimeOwner {\n /** Internal services used by models. */\n readonly [runtimeKey]: ModelRuntime;\n}\n","/** Writes attribute values into plain objects built from driver rows. */\nexport class ValuesWriter {\n /**\n * Sets a value as an own property. A column called `__proto__` stays an own property, like it\n * does with `Object.fromEntries`, instead of replacing the object's prototype.\n *\n * @param values - Target object.\n * @param name - Property name.\n * @param value - Property value.\n */\n set(values: Record<string, unknown>, name: string, value: unknown): void {\n if (name === '__proto__') {\n Object.defineProperty(values, name, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n } else {\n values[name] = value;\n }\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { Op } from '../expressions/op.ts';\nimport { ValuesWriter } from './values-writer.ts';\n\nconst writer = new ValuesWriter();\n\n/**\n * Find options stored in a scope (`where`, `attributes`, `order`, `limit`, ...).\n *\n * @example\n * ```ts\n * const scope: ScopeOptions = { where: { active: true }, order: [['createdAt', 'DESC']], limit: 100 };\n * User.init({ name: DataTypes.STRING }, { sequelize, defaultScope: scope });\n * ```\n */\nexport type ScopeOptions = Readonly<Record<string, unknown>>;\n\n/** Scope definition: options, or a function of arguments returning options. */\nexport type ScopeDefinition = ScopeOptions | ((...args: never[]) => ScopeOptions);\n\n/** Scope selector for `Model.scope()`: a name, `{ method: [name, ...args] }`, or inline options. */\nexport type ScopeSelector = string | ScopeMethodSelector | ScopeOptions | null;\n\n/** `{ method: [name, ...args] }` — calls a function scope with arguments. */\nexport type ScopeMethodSelector = Readonly<{\n /** Scope function name, or `[name, ...args]`. */\n method: string | readonly [string, ...unknown[]];\n}>;\n\n/** `whereMergeStrategy` model option: overwrite same keys (v6 default) or combine with `Op.and`. */\nexport type WhereMergeStrategy = 'overwrite' | 'and';\n\nconst isPlainObject = (value: unknown): value is Readonly<Record<string | symbol, unknown>> =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof SqlExpression);\n\nconst union = (left: readonly unknown[], right: readonly unknown[]): readonly unknown[] => [\n ...left,\n ...right.filter((item) => !left.includes(item)),\n];\n\nconst asCondition = (value: unknown): unknown =>\n value instanceof SqlExpression ? { [Op.and]: value } : value;\n\nconst mergeWhere = (left: unknown, right: unknown, strategy: WhereMergeStrategy): unknown => {\n if (left === undefined) {\n return right;\n }\n if (right === undefined) {\n return left;\n }\n if (strategy === 'and') {\n return { [Op.and]: [left, right] };\n }\n const source = asCondition(right);\n return isPlainObject(left) && isPlainObject(source) ? { ...left, ...source } : source;\n};\n\nconst mergeAttributes = (left: unknown, right: unknown): unknown =>\n isPlainObject(left) && isPlainObject(right)\n ? Object.fromEntries(\n [...new Set([...Object.keys(left), ...Object.keys(right)])].map((key) => {\n const a = left[key];\n const b = right[key];\n return [key, Array.isArray(a) && Array.isArray(b) ? union(a, b) : (b ?? a)];\n }),\n )\n : (right ?? left);\n\nconst mergeValue = (\n key: string,\n left: unknown,\n right: unknown,\n strategy: WhereMergeStrategy,\n): unknown => {\n if (key === 'where' || key === 'having') {\n return mergeWhere(left, right, strategy);\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n return union(left, right);\n }\n if (key === 'attributes') {\n return mergeAttributes(left, right);\n }\n return right === undefined ? left : right;\n};\n\n/**\n * Scopes of a model (default scope, named scopes, `whereMergeStrategy`) and the Sequelize v6\n * option merging rules used to apply them. Immutable: {@link ScopeRegistry.with} returns a new registry.\n */\nexport class ScopeRegistry {\n /** Default scope (`{}` when none). */\n readonly defaultScope: ScopeOptions;\n /** Named scopes. */\n readonly scopes: ReadonlyMap<string, ScopeDefinition>;\n /** How `where` / `having` of merged options combine. */\n readonly whereMergeStrategy: WhereMergeStrategy;\n\n /**\n * @param defaultScope - Default scope of the model.\n * @param scopes - Named scopes.\n * @param whereMergeStrategy - `'overwrite'` (default) or `'and'`.\n */\n constructor(\n defaultScope: ScopeOptions | undefined,\n scopes:\n | Readonly<Record<string, ScopeDefinition>>\n | ReadonlyMap<string, ScopeDefinition>\n | undefined,\n whereMergeStrategy: WhereMergeStrategy | undefined,\n ) {\n this.defaultScope = defaultScope ?? {};\n this.scopes = scopes instanceof Map ? scopes : new Map(Object.entries(scopes ?? {}));\n this.whereMergeStrategy = whereMergeStrategy ?? 'overwrite';\n }\n\n /**\n * Merges find options like Sequelize v6 `_assignOptions`: `where` / `having` keys of `right`\n * overwrite `left` (or are AND-ed with `whereMergeStrategy: 'and'`), arrays are unioned, other\n * keys of `right` win.\n *\n * @param left - Base options.\n * @param right - Options applied on top.\n * @returns Merged options.\n */\n merge(left: ScopeOptions, right: ScopeOptions): ScopeOptions {\n const strategy = this.whereMergeStrategy;\n const merged: Record<string, unknown> = {};\n for (const key of [...Object.keys(left), ...Object.keys(right)]) {\n if (!Object.hasOwn(merged, key)) {\n writer.set(merged, key, mergeValue(key, left[key], right[key], strategy));\n }\n }\n return merged;\n }\n\n /**\n * Resolves and merges the selected scopes in order (later scopes win).\n *\n * @param selectors - Scope names, `{ method: [name, ...args] }`, inline options or `null`.\n * @returns Merged scope options.\n * @throws Error for unknown scopes.\n */\n resolve(selectors: readonly ScopeSelector[]): ScopeOptions {\n return selectors\n .map((selector) => this.#resolveOne(selector))\n .reduce<ScopeOptions>((merged, scope) => this.merge(merged, scope), {});\n }\n\n /**\n * Applies a resolved scope to query options; the query options win (Sequelize v6 `_injectScope`).\n *\n * @param scope - Resolved scope.\n * @param options - Query options.\n * @returns Merged options.\n */\n inject<T extends ScopeOptions>(scope: ScopeOptions, options: T): T {\n return this.merge(scope, options) as T;\n }\n\n /**\n * Whether a scope with this name exists (`'defaultScope'`: whether it is not empty).\n *\n * @param name - Scope name.\n * @returns True when defined.\n */\n has(name: string): boolean {\n return name === 'defaultScope'\n ? Object.keys(this.defaultScope).length > 0\n : this.scopes.has(name);\n }\n\n /**\n * Registry with a scope added or replaced (`'defaultScope'` replaces the default scope).\n *\n * @param name - Scope name.\n * @param scope - Options or a function returning options.\n * @returns New registry.\n */\n with(name: string, scope: ScopeDefinition): ScopeRegistry {\n return name === 'defaultScope'\n ? new ScopeRegistry(scope as ScopeOptions, this.scopes, this.whereMergeStrategy)\n : new ScopeRegistry(\n this.defaultScope,\n new Map([...this.scopes, [name, scope]]),\n this.whereMergeStrategy,\n );\n }\n\n #resolveOne(selector: ScopeSelector): ScopeOptions {\n if (selector === null) {\n return {};\n }\n if (typeof selector === 'string') {\n return this.#resolveNamed(selector);\n }\n if ('method' in selector) {\n return this.#resolveMethod(selector as ScopeMethodSelector);\n }\n return selector;\n }\n\n #resolveNamed(selector: string): ScopeOptions {\n if (selector === 'defaultScope') {\n return this.defaultScope;\n }\n const scope = this.scopes.get(selector);\n if (scope === undefined) {\n throw new Error(`Invalid scope ${selector} called.`);\n }\n if (typeof scope === 'function') {\n throw new Error(\n `Scope \"${selector}\" is a function; use { method: ['${selector}', ...args] }`,\n );\n }\n return scope;\n }\n\n #resolveMethod(selector: ScopeMethodSelector): ScopeOptions {\n const method: readonly unknown[] = Array.isArray(selector.method)\n ? selector.method\n : [selector.method];\n const [name = '', ...args] = method as readonly string[];\n const scope = this.scopes.get(name);\n if (typeof scope !== 'function') {\n throw new Error(`Invalid scope ${name} called.`);\n }\n return (scope as (...scopeArgs: unknown[]) => ScopeOptions)(...args);\n }\n}\n","import { HookRegistry } from '../hooks/hooks.ts';\nimport type { StandardSchemaV1 } from '../validation/standard-schema.ts';\nimport type { ModelValidatorFunction } from '../validation/types.ts';\nimport {\n ModelDefinition,\n type DefinitionOptions,\n type ModelAttributes,\n} from './model-definition.ts';\nimport type { InitOptions } from './options.ts';\nimport { runtimeKey, type ModelRuntime } from './runtime.ts';\nimport { ScopeRegistry } from './scope-registry.ts';\n\n/** Internal state of an initialized model class. */\nexport type ModelState = Readonly<{\n definition: ModelDefinition;\n runtime: ModelRuntime;\n hooks: HookRegistry;\n scopes: ScopeRegistry;\n validators: Readonly<Record<string, ModelValidatorFunction>>;\n schema: StandardSchemaV1 | undefined;\n /** `init` input, kept to rebuild the definition when associations add attributes. */\n input: Readonly<{\n className: string;\n attributes: ModelAttributes;\n options: DefinitionOptions;\n extra: ModelAttributes;\n }>;\n /** Associations by alias. */\n associations: ReadonlyMap<string, unknown>;\n}>;\n\n/**\n * Builds the state of a model class from `Model.init` arguments, and rebuilds it when\n * associations add attributes.\n *\n * @internal\n */\nexport class ModelStateFactory {\n /**\n * State of a model class just initialized by `Model.init`.\n *\n * @param className - Class name (default model name).\n * @param attributes - Attribute definitions.\n * @param options - Model options, including the `sequelize` instance.\n * @returns The state.\n */\n create(className: string, attributes: ModelAttributes, options: InitOptions): ModelState {\n const {\n sequelize,\n hooks,\n defaultScope,\n scopes,\n whereMergeStrategy,\n validate,\n validationSchema,\n ...definitionOptions\n } = options;\n const runtime = sequelize[runtimeKey];\n return {\n ...this.#definitionState(className, attributes, definitionOptions, runtime),\n hooks: HookRegistry.fromOption(hooks, HookRegistry.fromOption(runtime.defaults.hooks)),\n scopes: new ScopeRegistry(defaultScope, scopes, whereMergeStrategy),\n validators: validate ?? {},\n schema: validationSchema,\n };\n }\n\n /**\n * State with the definition rebuilt from the `init` input plus attributes of associations.\n *\n * @param state - Current state.\n * @param attributes - Added attributes (foreign keys).\n * @returns The new state.\n */\n withAssociationAttributes(state: ModelState, attributes: ModelAttributes): ModelState {\n const extra = { ...state.input.extra, ...attributes };\n return {\n ...state,\n input: { ...state.input, extra },\n definition: ModelDefinition.normalize(\n state.input.className,\n state.input.attributes,\n state.input.options,\n state.runtime.defaults,\n extra,\n ),\n };\n }\n\n /**\n * State of a schema-bound copy of a model: the definition is rebuilt with the schema.\n *\n * @param state - State of the model the copy extends.\n * @param schema - Schema name.\n * @param delimiter - Separator reported by `getTableName`, `.` when not given.\n * @returns The new state.\n */\n withSchema(state: ModelState, schema: string, delimiter: string | undefined): ModelState {\n const options = {\n ...state.input.options,\n schema,\n ...(delimiter === undefined ? {} : { schemaDelimiter: delimiter }),\n };\n return this.withAssociationAttributes({ ...state, input: { ...state.input, options } }, {});\n }\n\n #definitionState(\n className: string,\n attributes: ModelAttributes,\n options: DefinitionOptions,\n runtime: ModelRuntime,\n ): Pick<ModelState, 'definition' | 'runtime' | 'input' | 'associations'> {\n return {\n definition: ModelDefinition.normalize(className, attributes, options, runtime.defaults),\n runtime,\n input: { className, attributes, options, extra: {} },\n associations: new Map(),\n };\n }\n}\n","import type { HookFunction, HookType } from '../hooks/hooks.ts';\nimport type { ModelAttributes, ModelDefinition } from './model-definition.ts';\nimport { ModelAccessors } from './model-accessors.ts';\nimport { ModelStateFactory, type ModelState } from './model-state.ts';\nimport type { InitOptions } from './options.ts';\nimport type { RuntimeOwner } from './runtime.ts';\nimport type { ScopeDefinition, ScopeOptions, ScopeSelector } from './scope-registry.ts';\n\nexport type { ModelState } from './model-state.ts';\n\nconst NOT_INITIALIZED = 'Model is not initialized. Call Model.init() or sequelize.define() first.';\n\nconst states = new WeakMap<object, ModelState>();\nconst selections = new WeakMap<object, readonly ScopeSelector[]>();\nconst owners = new WeakMap<object, RuntimeOwner>();\nconst accessors = new ModelAccessors();\nconst factory = new ModelStateFactory();\n\n/**\n * Per-class state of models: definition, runtime, hooks, scopes, validators and associations of\n * each initialized model class (shared by its scoped subclasses), the scopes selected by\n * `Model.scope()`, and the attribute / association accessors installed on model prototypes.\n * Instances share one store, so they can be created wherever needed.\n */\nexport class ModelRegistry {\n /**\n * Initializes a model class (`Model.init`): normalizes the definition, stores the state,\n * installs attribute accessors and registers the model in `sequelize.models`.\n *\n * @param model - Model class.\n * @param attributes - Attribute definitions.\n * @param options - Model options, including the `sequelize` instance.\n */\n init(\n model: Readonly<{ name: string; prototype: object }>,\n attributes: ModelAttributes,\n options: InitOptions,\n ): void {\n const state = factory.create(model.name, attributes, options);\n states.set(model, state);\n owners.set(model, options.sequelize);\n this.defineAttributeAccessors(model.prototype, state.definition);\n state.runtime.register(state.definition.name, model);\n }\n\n /**\n * State of a model class or of a scoped subclass of it.\n *\n * @param model - Model class.\n * @returns The state.\n * @throws Error when the model is not initialized.\n */\n state(model: object): ModelState {\n const base = this.#owner(model);\n const state = base === undefined ? undefined : states.get(base);\n if (state === undefined) {\n throw new Error(NOT_INITIALIZED);\n }\n return state;\n }\n\n /**\n * Normalized definition of a model class.\n *\n * @param model - Model class.\n * @returns The definition.\n */\n definition(model: object): ModelDefinition {\n return this.state(model).definition;\n }\n\n /**\n * Replaces the state of the model that owns `model` (scoped subclasses share it).\n *\n * @param model - Model class.\n * @param change - Computes the new state from the current one.\n */\n update(model: object, change: (state: ModelState) => ModelState): void {\n const base = this.#owner(model);\n if (base === undefined) {\n throw new Error(NOT_INITIALIZED);\n }\n states.set(base, change(this.state(base)));\n }\n\n /**\n * `Sequelize` instance given to `Model.init` for exactly this class.\n *\n * @param model - Model class.\n * @returns The instance, or `undefined`.\n */\n sequelizeOf(model: object): RuntimeOwner | undefined {\n return owners.get(model);\n }\n\n /**\n * Adds a hook to a model.\n *\n * @param model - Model class.\n * @param type - Hook type.\n * @param nameOrFn - Hook name or function.\n * @param fn - Hook function when a name is given.\n */\n addHook(\n model: object,\n type: HookType,\n nameOrFn: string | HookFunction,\n fn: HookFunction | undefined,\n ): void {\n this.update(model, (state) => ({\n ...state,\n hooks:\n typeof nameOrFn === 'string'\n ? state.hooks.add(type, fn ?? this.#missingHook(), nameOrFn)\n : state.hooks.add(type, nameOrFn),\n }));\n }\n\n /**\n * Removes hooks of a model by name or function.\n *\n * @param model - Model class.\n * @param type - Hook type.\n * @param nameOrFn - Hook name or function; all hooks of the type when omitted.\n */\n removeHook(model: object, type: HookType, nameOrFn: string | HookFunction | undefined): void {\n this.update(model, (state) => ({ ...state, hooks: state.hooks.remove(type, nameOrFn) }));\n }\n\n /**\n * Adds a named scope (or replaces the default scope with name `'defaultScope'`).\n *\n * @param model - Model class.\n * @param name - Scope name.\n * @param scope - Options or a function returning options.\n * @param override - Replace an existing scope.\n * @throws Error when the scope exists and `override` is not set.\n */\n addScope(model: object, name: string, scope: ScopeDefinition, override: boolean): void {\n if (this.state(model).scopes.has(name) && !override) {\n throw new Error(\n `The scope ${name} already exists. Pass { override: true } as options to silence this error`,\n );\n }\n this.update(model, (state) => ({ ...state, scopes: state.scopes.with(name, scope) }));\n }\n\n /**\n * Marks `scoped` (a subclass of `model`) as using the given scopes, checking that they resolve.\n *\n * @param model - Model class whose scopes are used.\n * @param scoped - Scoped subclass.\n * @param selectors - Selected scopes.\n */\n selectScopes(model: object, scoped: object, selectors: readonly ScopeSelector[]): void {\n this.state(model).scopes.resolve(selectors);\n selections.set(scoped, selectors);\n }\n\n /**\n * Gives `bound` (a subclass of `model`) its own state bound to a schema, and the scope\n * selection of `model`.\n *\n * @param model - Model class the copy extends.\n * @param bound - Schema-bound subclass.\n * @param schema - Schema name.\n * @param delimiter - Separator reported by `getTableName`.\n */\n bindSchema(model: object, bound: object, schema: string, delimiter: string | undefined): void {\n states.set(bound, factory.withSchema(this.state(model), schema, delimiter));\n const owner = owners.get(this.#owner(model) as object);\n if (owner !== undefined) {\n owners.set(bound, owner);\n }\n const selected = selections.get(model);\n if (selected !== undefined) {\n selections.set(bound, selected);\n }\n }\n\n /**\n * Scope options in effect for `model`: its selected scopes, or the default scope.\n *\n * @param model - Model class.\n * @returns Scope options.\n */\n activeScope(model: object): ScopeOptions {\n const state = this.state(model);\n const selected = selections.get(model);\n return selected === undefined ? state.scopes.defaultScope : state.scopes.resolve(selected);\n }\n\n /**\n * Query options with the active scope of `model` applied (query options win).\n *\n * @param model - Model class.\n * @param options - Query options.\n * @returns Merged options.\n */\n scoped<T extends ScopeOptions>(model: object, options: T): T {\n const { scopes } = this.state(model);\n const selected = selections.get(model);\n return scopes.inject(\n selected === undefined ? scopes.defaultScope : scopes.resolve(selected),\n options,\n );\n }\n\n /**\n * Defines `instance.<attribute>` getters / setters on the model prototype (once per attribute).\n *\n * @param prototype - Model prototype.\n * @param definition - Model definition.\n */\n defineAttributeAccessors(prototype: object, definition: ModelDefinition): void {\n accessors.defineAttributes(prototype, definition);\n }\n\n /**\n * Defines `instance.<alias>` for an association, holding included / nested instances (Sequelize v6).\n *\n * @param prototype - Model prototype.\n * @param alias - Association alias.\n */\n defineAssociationAccessor(prototype: object, alias: string): void {\n accessors.defineAssociation(prototype, alias);\n }\n\n /**\n * Rebuilds the definition of `model` with attributes contributed by associations.\n *\n * @param model - Model class.\n * @param attributes - Added attributes (foreign keys).\n * @returns The new definition.\n */\n addAssociationAttributes(model: object, attributes: ModelAttributes): ModelDefinition {\n this.update(model, (state) => factory.withAssociationAttributes(state, attributes));\n const { definition } = this.state(model);\n this.defineAttributeAccessors((model as { prototype: object }).prototype, definition);\n return definition;\n }\n\n #owner(model: object | null): object | undefined {\n return model === null\n ? undefined\n : states.has(model)\n ? model\n : this.#owner(Object.getPrototypeOf(model) as object | null);\n }\n\n #missingHook(): never {\n throw new Error('addHook: hook function is required');\n }\n}\n","import type { AttributeDefinition, ModelDefinition } from '../model/model-definition.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport { ValuesWriter } from '../model/values-writer.ts';\nimport type { IncludeNode } from './include.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\n/** Result row keyed by column alias (`Posts.title` for included columns). */\nexport type IncludeRow = Readonly<Record<string, unknown>>;\n\n/** Builds an instance of `model` from loaded values. */\nexport type InstanceBuilder = (model: Model, values: Readonly<Record<string, unknown>>) => AnyModel;\n\n/** Reads and parses the values of included models out of joined result rows. */\nexport class IncludeRows {\n readonly #writer = new ValuesWriter();\n // Which attribute of an include a result column belongs to depends on its name only, so it is\n // worked out once per column name instead of once per row.\n readonly #directNames = new Map<string, Map<string, string | null>>();\n readonly #rawAttributes = new WeakMap<\n readonly IncludeNode[],\n Map<string, AttributeDefinition | null>\n >();\n\n /**\n * Value parsed with an attribute's data type.\n *\n * @param attribute - Attribute definition, if known.\n * @param value - Raw value.\n * @returns Parsed value (`null` / `undefined` are kept).\n */\n parseValue(attribute: AttributeDefinition | undefined, value: unknown): unknown {\n return value === null || value === undefined || attribute?.type.parse === undefined\n ? value\n : attribute.type.parse(value);\n }\n\n /**\n * Values of the columns directly under `path` (`Posts.title` → `title`), parsed.\n *\n * @param definition - Definition of the included model.\n * @param row - Joined row.\n * @param path - Result path of the include.\n * @returns Attribute values.\n */\n valuesAt(definition: ModelDefinition, row: IncludeRow, path: string): Record<string, unknown> {\n const names = this.#namesUnder(path);\n const values: Record<string, unknown> = {};\n for (const key of Object.keys(row)) {\n const name = names.get(key) ?? this.#direct(names, path, key);\n if (name !== null) {\n this.#writer.set(values, name, this.parseValue(definition.attributes.get(name), row[key]));\n }\n }\n return values;\n }\n\n /**\n * Identity of an instance for de-duplication: its primary key, else all values.\n *\n * @param definition - Model definition.\n * @param values - Attribute values.\n * @returns Identity, or `undefined` when every value is `null` (no row joined).\n */\n identity(\n definition: ModelDefinition,\n values: Readonly<Record<string, unknown>>,\n ): string | number | undefined {\n if (Object.values(values).every((value) => value === null || value === undefined)) {\n return undefined;\n }\n const keys = definition.primaryKeys;\n if (keys.length === 0 || !keys.every((key) => key in values)) {\n return JSON.stringify(Object.entries(values));\n }\n const single = keys.length === 1 ? values[keys[0] as string] : undefined;\n return typeof single === 'number' ? single : JSON.stringify(keys.map((key) => values[key]));\n }\n\n /**\n * Parses a joined raw row: included keys are parsed with the included model's data types.\n *\n * @param includes - Include tree.\n * @param row - Joined row.\n * @param parseMain - Parses a row with the main model's data types; must return a new object.\n * @returns Parsed row.\n */\n parseRaw(\n includes: readonly IncludeNode[],\n row: IncludeRow,\n parseMain: (row: IncludeRow) => Readonly<Record<string, unknown>>,\n ): Record<string, unknown> {\n const parsed = parseMain(row) as Record<string, unknown>;\n const attributes = this.#attributesOf(includes);\n for (const key of Object.keys(parsed)) {\n const attribute = attributes.get(key) ?? this.#rawAttribute(includes, attributes, key);\n if (attribute !== null) {\n parsed[key] = this.parseValue(attribute, parsed[key]);\n }\n }\n return parsed;\n }\n\n #namesUnder(path: string): Map<string, string | null> {\n let names = this.#directNames.get(path);\n if (names === undefined) {\n names = new Map();\n this.#directNames.set(path, names);\n }\n return names;\n }\n\n #direct(names: Map<string, string | null>, path: string, key: string): string | null {\n const rest = key.startsWith(`${path}.`) ? key.slice(path.length + 1) : null;\n const name = rest !== null && !rest.includes('.') ? rest : null;\n names.set(key, name);\n return name;\n }\n\n #attributesOf(includes: readonly IncludeNode[]): Map<string, AttributeDefinition | null> {\n let attributes = this.#rawAttributes.get(includes);\n if (attributes === undefined) {\n attributes = new Map();\n this.#rawAttributes.set(includes, attributes);\n }\n return attributes;\n }\n\n #rawAttribute(\n includes: readonly IncludeNode[],\n attributes: Map<string, AttributeDefinition | null>,\n key: string,\n ): AttributeDefinition | null {\n const dot = key.lastIndexOf('.');\n const attribute =\n dot < 0\n ? null\n : (this.#definitionAt(this.#flatten(includes), key.slice(0, dot))?.attributes.get(\n key.slice(dot + 1),\n ) ?? null);\n attributes.set(key, attribute);\n return attribute;\n }\n\n #definitionAt(all: readonly IncludeNode[], path: string): ModelDefinition | undefined {\n return (\n all.find((candidate) => candidate.path === path)?.definition ??\n all.find((candidate) => candidate.through?.path === path)?.through?.definition\n );\n }\n\n #flatten(list: readonly IncludeNode[]): readonly IncludeNode[] {\n return list.flatMap((node) => [node, ...this.#flatten(node.children)]);\n }\n}\n","import { ModelRegistry } from '../model/model-registry.ts';\nimport type { ModelDefinition } from '../model/model-definition.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { IncludeNode } from './include.ts';\nimport { ValuesWriter } from '../model/values-writer.ts';\nimport { IncludeRows, type IncludeRow, type InstanceBuilder } from './include-rows.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\ntype Values = Record<string, unknown>;\ntype Group = Readonly<{ values: Values; rows: IncludeRow[] }>;\n\n/** Groups joined result rows into instance trees (Sequelize v6 de-duplication by primary key). */\nexport class IncludeAssembler {\n readonly #rows = new IncludeRows();\n readonly #writer = new ValuesWriter();\n\n /**\n * Groups joined rows into instance trees.\n *\n * @param model - Main model.\n * @param includes - Include tree.\n * @param rows - Joined rows.\n * @param parseMain - Parses a row with the main model's data types.\n * @param build - Builds an instance from loaded values.\n * @returns Main instances with the included instances attached.\n */\n assemble(\n model: Model,\n includes: readonly IncludeNode[],\n rows: readonly IncludeRow[],\n parseMain: (row: IncludeRow) => Readonly<Record<string, unknown>>,\n build: InstanceBuilder,\n ): readonly Instance[] {\n const mainKeys = (row: IncludeRow): Values => this.#mainValues(parseMain(row));\n const groups = this.#groupMain(registry.state(model).definition, rows, mainKeys);\n return [...groups.values()].map((group) => {\n const instance = build(model, group.values);\n this.#attachChildren(instance, includes, group.rows, build);\n return instance;\n });\n }\n\n #mainValues(parsed: Readonly<Record<string, unknown>>): Values {\n const values: Values = {};\n for (const key of Object.keys(parsed)) {\n if (!key.includes('.')) {\n this.#writer.set(values, key, parsed[key]);\n }\n }\n return values;\n }\n\n #groupMain(\n definition: ModelDefinition,\n rows: readonly IncludeRow[],\n mainKeys: (row: IncludeRow) => Values,\n ): Map<string | number, Group> {\n const groups = new Map<string | number, Group>();\n for (const [index, row] of rows.entries()) {\n const values = mainKeys(row);\n const key = this.#rows.identity(definition, values) ?? `row:${index}`;\n const group = groups.get(key);\n if (group === undefined) {\n groups.set(key, { values, rows: [row] });\n } else {\n group.rows.push(row);\n }\n }\n return groups;\n }\n\n #groupNode(node: IncludeNode, rows: readonly IncludeRow[]): Map<string | number, Group> {\n return rows.reduce<Map<string | number, Group>>((acc, row) => {\n const values = this.#rows.valuesAt(node.definition, row, node.path);\n const key = this.#rows.identity(node.definition, values);\n const group = key === undefined ? undefined : acc.get(key);\n if (key !== undefined && group === undefined) {\n acc.set(key, { values, rows: [row] });\n } else {\n group?.rows.push(row);\n }\n return acc;\n }, new Map());\n }\n\n #attachChildren(\n parent: Instance,\n nodes: readonly IncludeNode[],\n rows: readonly IncludeRow[],\n build: InstanceBuilder,\n ): void {\n nodes\n .filter((node) => !node.separate)\n .forEach((node) => {\n const children = [...this.#groupNode(node, rows).values()].map((group) =>\n this.#child(node, group, build),\n );\n (parent.dataValues as Values)[node.as] = node.association.isMultiAssociation\n ? children\n : (children[0] ?? null);\n });\n }\n\n #child(node: IncludeNode, group: Group, build: InstanceBuilder): Instance {\n const child = build(node.model, group.values);\n this.#attachThrough(child, node, group.rows[0] ?? {}, build);\n this.#attachChildren(child, node.children, group.rows, build);\n return child;\n }\n\n #attachThrough(\n child: Instance,\n node: IncludeNode,\n row: IncludeRow,\n build: InstanceBuilder,\n ): void {\n const { through } = node;\n const values =\n through === undefined ? {} : this.#rows.valuesAt(through.definition, row, through.path);\n if (through !== undefined && Object.keys(values).length > 0) {\n (child.dataValues as Values)[through.definition.name] = build(through.model, values);\n }\n }\n}\n","import type {\n BinaryNode,\n ExprNode,\n FnNode,\n IdentNode,\n LogicalNode,\n ParamNode,\n RawNode,\n} from './ast-expressions.ts';\n\nexport type * from './ast-expressions.ts';\nexport type * from './ast-clauses.ts';\nexport type * from './ast-statements.ts';\n\n/** Factories for the most common AST nodes. Stateless; nodes are plain immutable data. */\nexport class SqlAst {\n /** Bound parameter (`$n`). */\n param(value: unknown): ParamNode {\n return { kind: 'param', value };\n }\n\n /** Raw SQL text inserted as-is. */\n raw(sql: string): RawNode {\n return { kind: 'raw', sql };\n }\n\n /** Quoted identifier path, e.g. `\"table\".\"column\"`. */\n ident(...path: readonly string[]): IdentNode {\n return { kind: 'ident', path };\n }\n\n /** Binary operation `left op right`. */\n binary(op: string, left: ExprNode, right: ExprNode): BinaryNode {\n return { kind: 'binary', op, left, right };\n }\n\n /** Conjunction of the items (`TRUE` when empty). */\n and(items: readonly ExprNode[]): LogicalNode {\n return { kind: 'and', items };\n }\n\n /** Disjunction of the items (`FALSE` when empty). */\n or(items: readonly ExprNode[]): LogicalNode {\n return { kind: 'or', items };\n }\n\n /** Function call `name(args)`. */\n fnCall(name: string, args: readonly ExprNode[]): FnNode {\n return { kind: 'fn', name, args };\n }\n}\n","import { Op } from '../expressions/op.ts';\n\nconst ALLOWED_CAST_TYPES: ReadonlySet<string> = new Set([\n 'integer',\n 'int',\n 'smallint',\n 'bigint',\n 'float',\n 'real',\n 'double precision',\n 'decimal',\n 'numeric',\n 'boolean',\n 'text',\n 'char',\n 'varchar',\n 'date',\n 'timestamp',\n 'timestamptz',\n 'json',\n 'jsonb',\n 'uuid',\n]);\n\n/** Checks a `attribute::type` cast against the allowlist. */\nexport const validCastType = (type: string): string => {\n if (!ALLOWED_CAST_TYPES.has(type.trim().toLowerCase())) {\n throw new Error(`Invalid cast type: ${type}`);\n }\n return type;\n};\n\nconst SQL_COMPARATOR =\n /^(?:[=<>!~*@&|?#+\\-/%^]{1,3}|(?:NOT\\s+)?(?:I?LIKE|IN|SIMILAR\\s+TO)|IS(?:\\s+NOT)?(?:\\s+DISTINCT\\s+FROM)?)$/i;\n\n/** Checks the string comparator of `where(attr, comparator, value)` against the allowlist. */\nexport const validComparator = (comparator: string): string => {\n if (!SQL_COMPARATOR.test(comparator.trim()) || /--|\\/\\*|\\*\\//.test(comparator)) {\n throw new Error(`Invalid comparator: ${comparator}`);\n }\n return comparator.trim();\n};\n\n/** Operators compiled to a binary SQL operator. */\nexport const binaryOps: ReadonlyMap<symbol, string> = new Map<symbol, string>([\n [Op.gt, '>'],\n [Op.gte, '>='],\n [Op.lt, '<'],\n [Op.lte, '<='],\n [Op.like, 'LIKE'],\n [Op.notLike, 'NOT LIKE'],\n [Op.iLike, 'ILIKE'],\n [Op.notILike, 'NOT ILIKE'],\n [Op.regexp, '~'],\n [Op.notRegexp, '!~'],\n [Op.iRegexp, '~*'],\n [Op.notIRegexp, '!~*'],\n [Op.overlap, '&&'],\n [Op.contains, '@>'],\n [Op.contained, '<@'],\n [Op.adjacent, '-|-'],\n [Op.strictLeft, '<<'],\n [Op.strictRight, '>>'],\n [Op.noExtendRight, '&<'],\n [Op.noExtendLeft, '&>'],\n [Op.match, '@@'],\n [Op.isDistinctFrom, 'IS DISTINCT FROM'],\n [Op.isNotDistinctFrom, 'IS NOT DISTINCT FROM'],\n [Op.hasKey, '?'],\n [Op.hasAnyKeys, '?|'],\n [Op.hasAllKeys, '?&'],\n [Op.similarTo, 'SIMILAR TO'],\n [Op.notSimilarTo, 'NOT SIMILAR TO'],\n [Op.jsonPathExists, '@?'],\n [Op.containedOrEqual, '<<='],\n [Op.containsOrEqual, '>>='],\n [Op.trigramSimilar, '%'],\n [Op.trigramWordSimilar, '<%'],\n [Op.trigramStrictWordSimilar, '<<%'],\n [Op.trigramHasSimilarWord, '%>'],\n [Op.trigramHasSimilarStrictWord, '%>>'],\n]);\n\n/** jsonb key existence and jsonpath operators; their values are never serialized as JSON. */\nexport const KEY_OPERATORS: ReadonlySet<symbol> = new Set([\n Op.jsonPathExists,\n Op.hasKey,\n Op.hasAnyKeys,\n Op.hasAllKeys,\n]);\n\n/** Containment operators (jsonb when applied to a JSON path). */\nexport const CONTAINMENT_OPERATORS: ReadonlySet<symbol> = new Set([Op.contains, Op.contained]);\n\n/** Families of the operators that are not plain binary SQL operators. */\nexport type OperatorFamily = 'equality' | 'membership' | 'pattern' | 'logical' | 'quantifier';\n\n/** Operator family of every non-binary operator. */\nexport const operatorFamilies: ReadonlyMap<symbol, OperatorFamily> = new Map<\n symbol,\n OperatorFamily\n>([\n [Op.eq, 'equality'],\n [Op.ne, 'equality'],\n [Op.is, 'equality'],\n [Op.not, 'equality'],\n [Op.col, 'equality'],\n [Op.in, 'membership'],\n [Op.notIn, 'membership'],\n [Op.between, 'membership'],\n [Op.notBetween, 'membership'],\n [Op.startsWith, 'pattern'],\n [Op.endsWith, 'pattern'],\n [Op.substring, 'pattern'],\n [Op.and, 'logical'],\n [Op.or, 'logical'],\n [Op.any, 'quantifier'],\n [Op.all, 'quantifier'],\n]);\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { SqlAst, type ExprNode } from '../sql/ast.ts';\n\n/** Attribute facts the where compiler needs; supplied by the model layer. */\nexport type AttributeRef = Readonly<{\n field: string;\n isJson?: boolean;\n castType?: string;\n serialize?: (value: unknown) => unknown;\n}>;\n\n/** Attribute resolver and options injected into a `WhereCompiler`. */\nexport type WhereContext = Readonly<{\n tableAlias?: string;\n resolve: (attribute: string) => AttributeRef | undefined;\n inAsAnyThreshold?: number;\n /** Allows `excluded()` (only inside `ON CONFLICT DO UPDATE`). */\n allowExcluded?: boolean;\n}>;\n\n/** JSON(B) column and the key path read from it. */\nexport type JsonAccess = Readonly<{ base: ExprNode; path: readonly string[] }>;\n\n/** Left-hand side of a condition: the AST node plus the attribute or JSON path it came from. */\nexport type Operand = Readonly<{ node: ExprNode; ref?: AttributeRef; json?: JsonAccess }>;\n\n/** Plain conditions object of a `where` value. */\nexport type Conditions = Readonly<Record<string | symbol, unknown>>;\n\n/** Where context plus value conversion (implemented by `WhereCompiler`). */\nexport type ExprConverter = Readonly<{\n context: WhereContext;\n toExpr(value: unknown, ref?: AttributeRef): ExprNode;\n}>;\n\nconst ast = new SqlAst();\n\n/** True for a plain conditions object (not an array, date, buffer or expression). */\nexport const isPlainObject = (value: unknown): value is Conditions =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !Buffer.isBuffer(value) &&\n !(value instanceof SqlExpression);\n\n/** String and symbol keys of an object. */\nexport const ownKeys = (value: object): readonly (string | symbol)[] => Reflect.ownKeys(value);\n\n/** True for an `Op.*` key. */\nexport const isOpKey = (key: string | symbol): key is symbol => typeof key === 'symbol';\n\n/** True when a conditions object has at least one `Op.*` key. */\nexport const hasOpKeys = (value: Conditions): boolean => ownKeys(value).some(isOpKey);\n\n/** Dot-separated column path (or `*`) as an AST node. */\nexport const columnPath = (path: string): ExprNode =>\n path === '*' ? { kind: 'star' } : ast.ident(...path.split('.'));\n\n/** Applies the attribute serializer, when there is one. */\nexport const serializeWith = (ref: AttributeRef | undefined, value: unknown): unknown =>\n ref?.serialize === undefined ? value : ref.serialize(value);\n\n// The path is bound as a text[] parameter, so keys with `,`, `\"` or a backslash need no escaping.\n/** Text value at the path of a JSON column (`#>>`). */\nexport const jsonOperand = (json: JsonAccess): Operand => ({\n node: ast.binary('#>>', json.base, ast.param(json.path)),\n json,\n});\n\n/** jsonb value at the path of a JSON operand (`#>`), for jsonb operators. */\nexport const jsonbAt = (json: JsonAccess): ExprNode =>\n ast.binary('#>', json.base, ast.param(json.path));\n\n/** Wraps an operand in a cast when a type is given. */\nexport const withCast = (operand: Operand, type: string | undefined): Operand =>\n type === undefined ? operand : { node: { kind: 'cast', expr: operand.node, type } };\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { Op } from '../expressions/op.ts';\nimport { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport { CONTAINMENT_OPERATORS } from './operator-allowlist.ts';\nimport {\n isPlainObject,\n jsonbAt,\n serializeWith,\n withCast,\n type ExprConverter,\n type JsonAccess,\n type Operand,\n} from './where-support.ts';\n\nconst ast = new SqlAst();\n\nconst DEFAULT_IN_AS_ANY_THRESHOLD = 100;\n\nconst jsonCastFor = (value: unknown): string | undefined =>\n typeof value === 'number'\n ? 'double precision'\n : typeof value === 'boolean'\n ? 'boolean'\n : undefined;\n\nconst quantifierOf = (value: unknown): 'ANY' | 'ALL' | undefined =>\n isPlainObject(value)\n ? Op.any in value\n ? 'ANY'\n : Op.all in value\n ? 'ALL'\n : undefined\n : undefined;\n\nconst likePattern = (prefix: string, value: unknown, suffix: string): unknown =>\n value instanceof SqlExpression ? value : `${prefix}${String(value)}${suffix}`;\n\nconst pairOf = (value: unknown): readonly [unknown, unknown] => {\n if (!Array.isArray(value) || value.length !== 2) {\n throw new Error('Op.between / Op.notBetween expects an array of two values');\n }\n return [value[0], value[1]];\n};\n\n/** `IS NULL` / `IS NOT NULL`. */\nexport const nullCheck = (left: Operand, negated: boolean): ExprNode => ({\n kind: 'postfix',\n op: negated ? 'IS NOT NULL' : 'IS NULL',\n expr: left.node,\n});\n\n/** True for the values accepted by `Op.is`. */\nexport const isNullOrBoolean = (value: unknown): value is boolean | null =>\n value === null || typeof value === 'boolean';\n\n/** `IS [NOT] NULL|TRUE|FALSE`. */\nexport const isCheck = (left: Operand, value: boolean | null, negated: boolean): ExprNode => ({\n kind: 'postfix',\n op: `${negated ? 'IS NOT' : 'IS'} ${value === null ? 'NULL' : String(value).toUpperCase()}`,\n expr: left.node,\n});\n\n/** `Op.is`: `IS NULL|TRUE|FALSE`. */\nexport const isOperator = (left: Operand, value: unknown): ExprNode => {\n if (!isNullOrBoolean(value)) {\n throw new Error('Op.is expects null, true or false');\n }\n return isCheck(left, value, false);\n};\n\n/**\n * Value comparisons: binary operators with `ANY` / `ALL` quantifiers, `IN` lists (as `= ANY` above\n * the threshold), `BETWEEN`, the `LIKE` shortcuts and jsonb operators on JSON paths.\n */\nexport class ComparisonCompiler {\n /** `left <sqlOp> value`, with `ANY` / `ALL` quantifiers and JSON value casts. */\n comparison(compiler: ExprConverter, sqlOp: string, left: Operand, value: unknown): ExprNode {\n const quantifier = quantifierOf(value);\n if (quantifier !== undefined && isPlainObject(value)) {\n const items = value[quantifier === 'ANY' ? Op.any : Op.all];\n return ast.binary(\n sqlOp,\n left.node,\n ast.fnCall(quantifier, [this.#quantifiedOperand(compiler, left, items)]),\n );\n }\n const operand = left.json === undefined ? left : withCast(left, jsonCastFor(value));\n return ast.binary(sqlOp, operand.node, this.#valueNode(compiler, left, value));\n }\n\n /** `Op.startsWith` / `Op.endsWith` / `Op.substring` as `LIKE`. */\n pattern(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {\n const prefix = op === Op.startsWith ? '' : '%';\n const suffix = op === Op.endsWith ? '' : '%';\n return this.comparison(compiler, 'LIKE', left, likePattern(prefix, value, suffix));\n }\n\n /** `[NOT] IN`; empty lists become `FALSE` / `TRUE`, long lists `= ANY($n)` / `<> ALL($n)`. */\n inList(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {\n if (value instanceof SqlExpression) {\n return ast.binary(negated ? 'NOT IN' : 'IN', left.node, compiler.toExpr(value));\n }\n const items: readonly unknown[] = Array.isArray(value) ? value : [value];\n if (items.length === 0) {\n return ast.raw(negated ? 'TRUE' : 'FALSE');\n }\n if (items.length > (compiler.context.inAsAnyThreshold ?? DEFAULT_IN_AS_ANY_THRESHOLD)) {\n return this.#inAsArray(left, items, negated);\n }\n return ast.binary(negated ? 'NOT IN' : 'IN', left.node, {\n kind: 'list',\n items: items.map((item) => compiler.toExpr(item, left.ref)),\n });\n }\n\n /** `[NOT] BETWEEN low AND high`. */\n between(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {\n const [low, high] = pairOf(value);\n return {\n kind: 'between',\n expr: left.node,\n low: compiler.toExpr(low, left.ref),\n high: compiler.toExpr(high, left.ref),\n negated,\n };\n }\n\n /** jsonb key existence / containment operator on the jsonb value at a JSON path (`#>`). */\n jsonb(\n compiler: ExprConverter,\n sqlOp: string,\n op: symbol,\n json: JsonAccess,\n value: unknown,\n ): ExprNode {\n return ast.binary(\n sqlOp,\n jsonbAt(json),\n CONTAINMENT_OPERATORS.has(op) && !(value instanceof SqlExpression)\n ? ast.param(JSON.stringify(value))\n : compiler.toExpr(value),\n );\n }\n\n #inAsArray(left: Operand, items: readonly unknown[], negated: boolean): ExprNode {\n return ast.binary(\n negated ? '<>' : '=',\n left.node,\n ast.fnCall(negated ? 'ALL' : 'ANY', [\n ast.param(items.map((item) => serializeWith(left.ref, item))),\n ]),\n );\n }\n\n #valueNode(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {\n return left.json !== undefined && !(value instanceof SqlExpression)\n ? ast.param(\n typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value),\n )\n : compiler.toExpr(value, left.ref);\n }\n\n #quantifiedOperand(compiler: ExprConverter, left: Operand, items: unknown): ExprNode {\n return isPlainObject(items) && Array.isArray(items[Op.values])\n ? {\n kind: 'values',\n rows: (items[Op.values] as readonly unknown[]).map((item) => [\n compiler.toExpr(item, left.ref),\n ]),\n }\n : ast.param(\n Array.isArray(items) ? items.map((item) => serializeWith(left.ref, item)) : items,\n );\n }\n}\n","import { Op } from '../expressions/op.ts';\nimport { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport {\n isCheck,\n isNullOrBoolean,\n isOperator,\n nullCheck,\n type ComparisonCompiler,\n} from './comparison-compiler.ts';\nimport {\n binaryOps,\n CONTAINMENT_OPERATORS,\n KEY_OPERATORS,\n operatorFamilies,\n} from './operator-allowlist.ts';\nimport {\n columnPath,\n hasOpKeys,\n isOpKey,\n isPlainObject,\n jsonOperand,\n ownKeys,\n type Conditions,\n type ExprConverter,\n type JsonAccess,\n type Operand,\n} from './where-support.ts';\n\nconst ast = new SqlAst();\n\n/**\n * Compiles the value of one attribute condition (`{ attr: value }`): plain values, `Op.*` objects,\n * nested JSON conditions and the logical combinators applied to the same attribute.\n */\nexport class ConditionCompiler {\n readonly #comparisons: ComparisonCompiler;\n\n /**\n * @param comparisons - Value comparisons.\n */\n constructor(comparisons: ComparisonCompiler) {\n this.#comparisons = comparisons;\n }\n\n /** Condition of `left` against a where value (plain value, array, `Op.*` object, JSON object). */\n condition(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {\n if (isPlainObject(value)) {\n if (hasOpKeys(value)) {\n return ast.and(\n ownKeys(value)\n .filter(isOpKey)\n .map((op) => this.operator(compiler, op, left, value[op])),\n );\n }\n if (left.ref?.isJson === true || left.json !== undefined) {\n return this.#jsonNested(compiler, left, value);\n }\n }\n if (Array.isArray(value) && left.ref?.isJson !== true) {\n return this.#comparisons.inList(compiler, left, value, false);\n }\n return this.#equals(compiler, left, value, false);\n }\n\n /** Applies one `Op.*` operator; only operators of the allowlist are accepted. */\n operator(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {\n const sqlOp = binaryOps.get(op);\n if (sqlOp !== undefined) {\n return this.#binaryOperator(compiler, sqlOp, op, left, value);\n }\n switch (operatorFamilies.get(op)) {\n case 'equality':\n return this.#equality(compiler, op, left, value);\n case 'membership':\n return this.#membership(compiler, op, left, value);\n case 'pattern':\n return this.#comparisons.pattern(compiler, op, left, value);\n case 'logical':\n return this.#logical(compiler, op, left, value);\n case 'quantifier':\n return this.#comparisons.comparison(compiler, '=', left, { [op]: value });\n default:\n throw new Error(`Unsupported operator: ${String(op)}`);\n }\n }\n\n #binaryOperator(\n compiler: ExprConverter,\n sqlOp: string,\n op: symbol,\n left: Operand,\n value: unknown,\n ): ExprNode {\n if (left.json !== undefined && (KEY_OPERATORS.has(op) || CONTAINMENT_OPERATORS.has(op))) {\n return this.#comparisons.jsonb(compiler, sqlOp, op, left.json, value);\n }\n const operand = KEY_OPERATORS.has(op) ? { node: left.node } : left;\n return this.#comparisons.comparison(compiler, sqlOp, operand, value);\n }\n\n #equals(compiler: ExprConverter, left: Operand, value: unknown, negated: boolean): ExprNode {\n return value === null\n ? nullCheck(left, negated)\n : this.#comparisons.comparison(compiler, negated ? '<>' : '=', left, value);\n }\n\n #equality(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {\n switch (op) {\n case Op.eq:\n return this.#equals(compiler, left, value, false);\n case Op.ne:\n return this.#equals(compiler, left, value, true);\n case Op.is:\n return isOperator(left, value);\n case Op.not:\n return this.#negation(compiler, left, value);\n default:\n return ast.binary('=', left.node, columnPath(String(value)));\n }\n }\n\n #membership(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {\n switch (op) {\n case Op.in:\n return this.#comparisons.inList(compiler, left, value, false);\n case Op.notIn:\n return this.#comparisons.inList(compiler, left, value, true);\n case Op.between:\n return this.#comparisons.between(compiler, left, value, false);\n default:\n return this.#comparisons.between(compiler, left, value, true);\n }\n }\n\n #logical(compiler: ExprConverter, op: symbol, left: Operand, value: unknown): ExprNode {\n const items = (Array.isArray(value) ? value : [value]).map((item: unknown) =>\n this.condition(compiler, left, item),\n );\n return op === Op.and ? ast.and(items) : ast.or(items);\n }\n\n #negation(compiler: ExprConverter, left: Operand, value: unknown): ExprNode {\n return isNullOrBoolean(value)\n ? isCheck(left, value, true)\n : isPlainObject(value)\n ? { kind: 'prefix', op: 'NOT', expr: this.condition(compiler, left, value) }\n : this.#comparisons.comparison(compiler, '<>', left, value);\n }\n\n #jsonNested(compiler: ExprConverter, left: Operand, value: Conditions): ExprNode {\n const access: JsonAccess = left.json ?? { base: left.node, path: [] };\n return ast.and(\n Object.entries(value).map(([key, nested]) =>\n this.condition(\n compiler,\n jsonOperand({ base: access.base, path: [...access.path, key] }),\n nested,\n ),\n ),\n );\n }\n}\n","import { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport { validCastType } from './operator-allowlist.ts';\nimport {\n columnPath,\n jsonOperand,\n withCast,\n type Operand,\n type WhereContext,\n} from './where-support.ts';\n\nconst ast = new SqlAst();\n\n/**\n * Resolves a where key into its left-hand operand: `$table.column$` paths, attribute names mapped\n * to columns, `attr.a.b` JSON paths and `attr::type` casts.\n */\nexport class OperandResolver {\n /** Operand of a where key. */\n operand(context: WhereContext, key: string): Operand {\n if (key.startsWith('$') && key.endsWith('$')) {\n return { node: columnPath(key.slice(1, -1)) };\n }\n const [name = key, castType] = key.split('::');\n const [attribute = name, ...path] = name.split('.');\n const ref = context.resolve(attribute);\n const column = this.#column(context, ref?.field ?? attribute);\n const operand: Operand =\n path.length > 0\n ? jsonOperand({ base: column, path })\n : ref === undefined\n ? { node: column }\n : { node: column, ref };\n return withCast(operand, castType === undefined ? undefined : validCastType(castType));\n }\n\n #column(context: WhereContext, field: string): ExprNode {\n const tableAlias = context.tableAlias;\n return tableAlias === undefined ? ast.ident(field) : ast.ident(tableAlias, field);\n }\n}\n","import type { OrderNode } from './ast.ts';\n\ntype Direction = NonNullable<OrderNode['direction']>;\ntype Nulls = NonNullable<OrderNode['nulls']>;\n\n/** Order direction (`ASC`, `DESC NULLS LAST`, ...) from an allowlist; spreads into an order node. */\nexport class OrderDirection {\n /** `ASC` / `DESC`; absent when only the nulls order is given. */\n declare readonly direction?: Direction;\n /** `NULLS FIRST` / `NULLS LAST`; absent when not given. */\n declare readonly nulls?: Nulls;\n\n static readonly #allowed: ReadonlyMap<string, OrderDirection> = new Map([\n ['ASC', new OrderDirection('ASC')],\n ['DESC', new OrderDirection('DESC')],\n ['ASC NULLS FIRST', new OrderDirection('ASC', 'FIRST')],\n ['ASC NULLS LAST', new OrderDirection('ASC', 'LAST')],\n ['DESC NULLS FIRST', new OrderDirection('DESC', 'FIRST')],\n ['DESC NULLS LAST', new OrderDirection('DESC', 'LAST')],\n ['NULLS FIRST', new OrderDirection(undefined, 'FIRST')],\n ['NULLS LAST', new OrderDirection(undefined, 'LAST')],\n ]);\n\n private constructor(direction?: Direction, nulls?: Nulls) {\n if (direction !== undefined) {\n this.direction = direction;\n }\n if (nulls !== undefined) {\n this.nulls = nulls;\n }\n Object.freeze(this);\n }\n\n /** Parses an order direction from the allowlist; throws for anything else. */\n static parse(value: unknown): OrderDirection {\n const direction = OrderDirection.#allowed.get(String(value).trim().toUpperCase());\n if (direction === undefined) {\n throw new Error(`Invalid order direction: ${String(value)}`);\n }\n return direction;\n }\n}\n","import type { Over } from '../expressions/methods.ts';\nimport type { ExprNode, OrderNode } from '../sql/ast.ts';\nimport { OrderDirection } from '../sql/order.ts';\nimport type { OperandResolver } from './operand-resolver.ts';\nimport type { ExprConverter } from './where-support.ts';\n\n/** Compiles window function calls (`over()`): `PARTITION BY` and `ORDER BY` items. */\nexport class WindowCompiler {\n readonly #operands: OperandResolver;\n\n /**\n * @param operands - Resolves attribute names.\n */\n constructor(operands: OperandResolver) {\n this.#operands = operands;\n }\n\n /** `fn OVER (PARTITION BY ... ORDER BY ...)`. */\n over(compiler: ExprConverter, value: Over): ExprNode {\n return {\n kind: 'over',\n expr: compiler.toExpr(value.fn),\n partitionBy: value.partitionBy.map((item) => this.#target(compiler, item)),\n orderBy: value.orderBy.map((item) => this.#order(compiler, item)),\n };\n }\n\n #target(compiler: ExprConverter, item: unknown): ExprNode {\n return typeof item === 'string'\n ? this.#operands.operand(compiler.context, item).node\n : compiler.toExpr(item);\n }\n\n #order(compiler: ExprConverter, item: unknown): OrderNode {\n if (Array.isArray(item)) {\n const [target, direction]: readonly unknown[] = item;\n return {\n expr: this.#target(compiler, target),\n ...(direction === undefined ? {} : OrderDirection.parse(direction)),\n };\n }\n return { expr: this.#target(compiler, item) };\n }\n}\n","import { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport {\n SqlExpression,\n type Cast,\n type Col,\n type Excluded,\n type Exists,\n type Fn,\n type Json,\n type Literal,\n type Over,\n type SqlExpressionVisitor,\n type Subquery,\n type Tuple,\n type Where,\n} from '../expressions/methods.ts';\nimport { Op } from '../expressions/op.ts';\nimport { ComparisonCompiler } from './comparison-compiler.ts';\nimport { ConditionCompiler } from './condition-compiler.ts';\nimport { OperandResolver } from './operand-resolver.ts';\nimport { validComparator } from './operator-allowlist.ts';\nimport { WindowCompiler } from './window-compiler.ts';\nimport {\n columnPath,\n isOpKey,\n isPlainObject,\n ownKeys,\n serializeWith,\n type AttributeRef,\n type Operand,\n type WhereContext,\n} from './where-support.ts';\n\nexport type { AttributeRef, WhereContext } from './where-support.ts';\n\nconst ast = new SqlAst();\n\nconst splitConditions = (value: unknown): readonly unknown[] =>\n Array.isArray(value)\n ? value\n : isPlainObject(value)\n ? ownKeys(value).map((key) => ({ [key]: value[key] }))\n : [value];\n\n// The collaborators are stateless (the compiler is passed in) and shared by every compiler: a\n// compiler is created per query, so it allocates nothing beyond itself.\nconst operands = new OperandResolver();\nconst conditions = new ConditionCompiler(new ComparisonCompiler());\nconst windows = new WindowCompiler(operands);\n\n/**\n * Compiles Sequelize v6 `where` / `having` values and expression builders into AST nodes.\n * Attribute names are resolved through the injected {@link WhereContext}; one instance can be\n * reused for any number of conditions over the same context.\n */\nexport class WhereCompiler implements SqlExpressionVisitor<ExprNode> {\n /** Attribute resolver, table alias and options. */\n readonly context: WhereContext;\n\n /**\n * @param context - Attribute resolver, table alias and options.\n */\n constructor(context: WhereContext) {\n this.context = context;\n }\n\n /** True when a where value has no conditions. */\n static isEmpty(where: unknown): boolean {\n return (\n where === undefined ||\n where === null ||\n (isPlainObject(where) && ownKeys(where).length === 0) ||\n (Array.isArray(where) && where.length === 0)\n );\n }\n\n /** Compiles a Sequelize v6 `where` value (object, array or expression) into an AST condition. */\n compile(where: unknown): ExprNode {\n if (where instanceof SqlExpression) {\n return where.accept(this);\n }\n if (Array.isArray(where)) {\n return ast.and(where.map((item: unknown) => this.compile(item)));\n }\n if (!isPlainObject(where)) {\n throw new Error(`Invalid where value: ${String(where)}`);\n }\n return ast.and(\n ownKeys(where).map((key) =>\n isOpKey(key)\n ? this.#topLevelOperator(key, where[key])\n : conditions.condition(this, operands.operand(this.context, key), where[key]),\n ),\n );\n }\n\n /** Converts an expression builder or a plain value (bound as a parameter) into an AST node. */\n toExpr(value: unknown, ref?: AttributeRef): ExprNode {\n if (value instanceof SqlExpression) {\n return value.accept(this);\n }\n const param = ast.param(serializeWith(ref, value));\n return ref?.castType === undefined ? param : { kind: 'cast', expr: param, type: ref.castType };\n }\n\n /** @internal */\n visitLiteral(value: Literal): ExprNode {\n return ast.raw(value.val);\n }\n\n /** @internal */\n visitFn(value: Fn): ExprNode {\n return ast.fnCall(\n value.fn,\n value.args.map((arg) => this.toExpr(arg)),\n );\n }\n\n /** @internal */\n visitCol(value: Col): ExprNode {\n return typeof value.col === 'string' ? columnPath(value.col) : ast.ident(...value.col);\n }\n\n /** @internal */\n visitCast(value: Cast): ExprNode {\n return { kind: 'cast', expr: this.toExpr(value.val), type: value.type };\n }\n\n /** @internal */\n visitJson(value: Json): ExprNode {\n if (value.conditions !== undefined) {\n return this.compile(value.conditions);\n }\n const accessor = operands.operand(this.context, value.path ?? '').node;\n return value.value === undefined ? accessor : ast.binary('=', accessor, ast.param(value.value));\n }\n\n /** @internal */\n visitWhere(value: Where): ExprNode {\n const left: Operand = { node: this.toExpr(value.attribute) };\n if (typeof value.comparator === 'symbol') {\n return conditions.operator(this, value.comparator, left, value.logic);\n }\n return value.comparator === '='\n ? conditions.condition(this, left, value.logic)\n : ast.binary(validComparator(value.comparator), left.node, this.toExpr(value.logic));\n }\n\n /** @internal */\n visitSubquery(value: Subquery): ExprNode {\n return { kind: 'subquery', query: value.build() };\n }\n\n /** @internal */\n visitExists(value: Exists): ExprNode {\n return {\n kind: 'prefix',\n op: value.negated ? 'NOT EXISTS' : 'EXISTS',\n expr: { kind: 'subquery', query: value.subquery.build() },\n };\n }\n\n /** @internal */\n visitTuple(value: Tuple): ExprNode {\n return { kind: 'list', items: value.items.map((item) => this.toExpr(item)) };\n }\n\n /** @internal */\n visitOver(value: Over): ExprNode {\n return windows.over(this, value);\n }\n\n /** @internal */\n visitExcluded(value: Excluded): ExprNode {\n if (this.context.allowExcluded !== true) {\n throw new Error('excluded() can only be used inside onConflict');\n }\n return { kind: 'excluded', column: this.context.resolve(value.column)?.field ?? value.column };\n }\n\n #topLevelOperator(op: symbol, value: unknown): ExprNode {\n switch (op) {\n case Op.and:\n return ast.and(splitConditions(value).map((item) => this.compile(item)));\n case Op.or:\n return ast.or(splitConditions(value).map((item) => this.compile(item)));\n case Op.not:\n return { kind: 'prefix', op: 'NOT', expr: this.compile(value) };\n default:\n throw new Error(`Invalid top-level where operator: ${String(op)}`);\n }\n }\n}\n","import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';\nimport { Op } from '../expressions/op.ts';\nimport { SqlAst, type ExprNode, type SetItem, type TableRef } from '../sql/ast.ts';\nimport { WhereCompiler, type AttributeRef } from '../where/where.ts';\nimport type { AttributeDefinition, ModelDefinition } from './model-definition.ts';\n\nconst ast = new SqlAst();\n\nconst attributeRef = (attribute: AttributeDefinition): AttributeRef => ({\n field: attribute.field,\n ...(attribute.type.isJson === true ? { isJson: true } : {}),\n ...(attribute.type.bindCast === undefined ? {} : { castType: attribute.type.bindCast }),\n ...(attribute.type.serialize === undefined ? {} : { serialize: attribute.type.serialize }),\n});\n\n/**\n * Maps model attributes to SQL pieces shared by the statement builders: table reference, where\n * compiler resolving attribute names, stored columns, bound column values, SET items, RETURNING\n * lists, primary-key and paranoid conditions.\n */\nexport class AttributeColumns {\n /**\n * Table reference of the model.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @returns Table reference.\n */\n table(definition: ModelDefinition, alias?: string): TableRef {\n return {\n name: definition.tableName,\n ...(definition.schema === undefined ? {} : { schema: definition.schema }),\n ...(alias === undefined ? {} : { alias }),\n };\n }\n\n /**\n * Where compiler resolving attribute names of the model.\n *\n * @param definition - Model definition.\n * @param alias - Table alias used to qualify columns.\n * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.\n * @returns Where compiler.\n */\n whereCompiler(\n definition: ModelDefinition,\n alias: string | undefined,\n inAsAnyThreshold?: number,\n ): WhereCompiler {\n return new WhereCompiler({\n ...(alias === undefined ? {} : { tableAlias: alias }),\n ...(inAsAnyThreshold === undefined ? {} : { inAsAnyThreshold }),\n resolve: (name) => {\n const attribute = definition.attributes.get(name);\n return attribute === undefined ? undefined : attributeRef(attribute);\n },\n });\n }\n\n /**\n * Compiles a `where` / `having` option; empty conditions give `undefined`.\n *\n * @param where - Condition.\n * @param ctx - Where compiler of the model.\n * @returns Expression or `undefined`.\n */\n where(where: unknown, ctx: WhereCompiler): ExprNode | undefined {\n return WhereCompiler.isEmpty(where) ? undefined : ctx.compile(where);\n }\n\n /**\n * Attributes stored in the table (not virtual).\n *\n * @param definition - Model definition.\n * @returns Stored attributes in definition order.\n */\n stored(definition: ModelDefinition): readonly AttributeDefinition[] {\n return [...definition.attributes.values()].filter(\n (attribute) => attribute.type.isVirtual !== true,\n );\n }\n\n /**\n * Column value for INSERT / UPDATE: bound parameter, expression, or generated default.\n *\n * @param attribute - Attribute of the column (`undefined` for unknown names).\n * @param value - Value or expression.\n * @param ctx - Where compiler of the model.\n * @returns Value expression.\n */\n value(attribute: AttributeDefinition | undefined, value: unknown, ctx: WhereCompiler): ExprNode {\n return value instanceof DefaultValueGenerator\n ? ast.param(value.generate())\n : ctx.toExpr(value, attribute === undefined ? undefined : attributeRef(attribute));\n }\n\n /**\n * SET items from attribute-keyed values (`undefined` values and generated columns are skipped).\n *\n * @param definition - Model definition.\n * @param values - Values by attribute name.\n * @param ctx - Where compiler used for expressions.\n * @returns SET items.\n */\n setItems(\n definition: ModelDefinition,\n values: Readonly<Record<string, unknown>>,\n ctx: WhereCompiler = this.whereCompiler(definition, undefined),\n ): readonly SetItem[] {\n return Object.entries(values)\n .filter(\n ([name, value]) =>\n value !== undefined && definition.attributes.get(name)?.generated === undefined,\n )\n .map(([name, value]) => {\n const attribute = definition.attributes.get(name);\n return { column: attribute?.field ?? name, value: this.value(attribute, value, ctx) };\n });\n }\n\n /**\n * RETURNING list: all stored columns aliased to attribute names.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @returns Column list.\n */\n returningAll(definition: ModelDefinition, alias?: string): readonly ExprNode[] {\n return this.stored(definition).map((attribute) => {\n const column =\n alias === undefined ? ast.ident(attribute.field) : ast.ident(alias, attribute.field);\n return attribute.field === attribute.fieldName && alias === undefined\n ? column\n : { kind: 'alias', expr: column, alias: attribute.fieldName };\n });\n }\n\n /**\n * Primary-key where object for an instance.\n *\n * @param definition - Model definition.\n * @param values - Instance values.\n * @returns `{ [primaryKey]: value }`.\n */\n primaryKeyWhere(\n definition: ModelDefinition,\n values: Readonly<Record<string, unknown>>,\n ): Readonly<Record<string, unknown>> {\n return Object.fromEntries(definition.primaryKeys.map((name) => [name, values[name]]));\n }\n\n /**\n * Adds `deletedAt IS NULL` to `where` for paranoid models unless `paranoid: false`.\n *\n * @param definition - Model definition.\n * @param where - Condition.\n * @param paranoid - `paranoid` option.\n * @returns Condition.\n */\n paranoid(definition: ModelDefinition, where: unknown, paranoid: boolean | undefined): unknown {\n if (definition.deletedAt === undefined || paranoid === false) {\n return where;\n }\n const notDeleted = { [definition.deletedAt]: null };\n return where === undefined || where === null ? notDeleted : { [Op.and]: [notDeleted, where] };\n }\n}\n","import { Op } from '../expressions/op.ts';\nimport type { AnyModel } from '../model/options.ts';\nimport { AttributeColumns } from '../model/attribute-columns.ts';\nimport type { IncludeNode } from './include.ts';\nimport type { IncludeResolver } from './include-resolver.ts';\n\nconst columns = new AttributeColumns();\n\ntype Instance = AnyModel;\ntype Values = Record<string, unknown>;\ntype FindOptions = Readonly<Record<string, unknown>>;\n\n/** Loads `separate: true` includes with one extra query each. */\nexport class SeparateIncludeLoader {\n readonly #resolver: IncludeResolver;\n\n /**\n * @param resolver - Converts include nodes back to options for the separate queries.\n */\n constructor(resolver: IncludeResolver) {\n this.#resolver = resolver;\n }\n\n /**\n * Loads `separate: true` includes with one extra query each and attaches them, keeping at most\n * `limit` rows per parent.\n *\n * @param parents - Instances the includes belong to.\n * @param includes - Include tree.\n * @param options - Find options (`transaction` is passed on).\n * @returns Resolves when all separate includes are attached.\n */\n async load(\n parents: readonly Instance[],\n includes: readonly IncludeNode[],\n options: FindOptions,\n ): Promise<void> {\n await Promise.all(includes.map((node) => this.#loadNode(parents, node, options)));\n }\n\n async #loadNode(\n parents: readonly Instance[],\n node: IncludeNode,\n options: FindOptions,\n ): Promise<void> {\n if (!node.separate) {\n await this.load(this.#loaded(parents, node), node.children, options);\n return;\n }\n const keys = [...new Set(parents.map((parent) => parent.get(node.association.sourceKey)))];\n const rows = (await node.model.findAll(\n this.#query(node, keys, options) as never,\n )) as Instance[];\n parents.forEach((parent) => this.#attach(parent, node, rows));\n }\n\n #loaded(parents: readonly Instance[], node: IncludeNode): Instance[] {\n return parents.flatMap((parent) => {\n const value = (parent.dataValues as Values)[node.as];\n return Array.isArray(value)\n ? (value as Instance[])\n : value === null || value === undefined\n ? []\n : [value as Instance];\n });\n }\n\n #query(node: IncludeNode, keys: readonly unknown[], options: FindOptions): Values {\n return {\n ...(options['transaction'] === undefined ? {} : { transaction: options['transaction'] }),\n ...this.#scope(node, keys),\n attributes:\n node.attributes ?? columns.stored(node.definition).map((attribute) => attribute.fieldName),\n ...(node.order === undefined ? {} : { order: node.order }),\n ...(node.children.length === 0\n ? {}\n : { include: node.children.map((child) => this.#resolver.toOptions(child)) }),\n paranoid: node.paranoid,\n };\n }\n\n #scope(node: IncludeNode, keys: readonly unknown[]): Values {\n const own = node.where === undefined ? [] : [node.where];\n if (!node.lateral) {\n return { where: { [Op.and]: [{ [node.association.foreignKey]: keys }, ...own] } };\n }\n if (node.limit === undefined || node.children.length > 0) {\n throw new Error('A lateral include needs a limit and no nested includes');\n }\n return {\n ...(own.length === 0 ? {} : { where: { [Op.and]: own } }),\n limit: node.limit,\n lateralKeys: { attribute: node.association.foreignKey, values: keys },\n };\n }\n\n #attach(parent: Instance, node: IncludeNode, rows: readonly Instance[]): void {\n const own = rows.filter(\n (row) => row.get(node.association.foreignKey) === parent.get(node.association.sourceKey),\n );\n (parent.dataValues as Values)[node.as] =\n node.limit === undefined ? own : own.slice(0, node.limit);\n }\n}\n","import type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { IncludeNode } from './include.ts';\nimport { IncludeAssembler } from './include-assembler.ts';\nimport type { IncludeResolver } from './include-resolver.ts';\nimport { IncludeRows, type IncludeRow, type InstanceBuilder } from './include-rows.ts';\nimport { SeparateIncludeLoader } from './separate-include-loader.ts';\n\nexport type { IncludeRow, InstanceBuilder } from './include-rows.ts';\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\n\n/**\n * Turns joined result rows into instance trees (Sequelize v6 de-duplication by primary key),\n * parses raw joined rows, and loads `separate: true` includes with one extra query each.\n */\nexport class IncludeLoader {\n readonly #assembler = new IncludeAssembler();\n readonly #rows = new IncludeRows();\n readonly #separate: SeparateIncludeLoader;\n\n /**\n * @param resolver - Converts include nodes back to options for the separate queries.\n */\n constructor(resolver: IncludeResolver) {\n this.#separate = new SeparateIncludeLoader(resolver);\n }\n\n /**\n * Groups joined rows into instance trees.\n *\n * @param model - Main model.\n * @param includes - Include tree.\n * @param rows - Joined rows.\n * @param parseMain - Parses a row with the main model's data types.\n * @param build - Builds an instance from loaded values.\n * @returns Main instances with the included instances attached.\n */\n assemble(\n model: Model,\n includes: readonly IncludeNode[],\n rows: readonly IncludeRow[],\n parseMain: (row: IncludeRow) => Readonly<Record<string, unknown>>,\n build: InstanceBuilder,\n ): readonly Instance[] {\n return this.#assembler.assemble(model, includes, rows, parseMain, build);\n }\n\n /**\n * Parses a joined raw row: included keys are parsed with the included model's data types.\n *\n * @param includes - Include tree.\n * @param row - Joined row.\n * @param parseMain - Parses a row with the main model's data types.\n * @returns Parsed row.\n */\n parseRawRow(\n includes: readonly IncludeNode[],\n row: IncludeRow,\n parseMain: (row: IncludeRow) => Readonly<Record<string, unknown>>,\n ): Record<string, unknown> {\n return this.#rows.parseRaw(includes, row, parseMain);\n }\n\n /**\n * Loads `separate: true` includes with one extra query each and attaches them, keeping at most\n * `limit` rows per parent.\n *\n * @param parents - Instances the includes belong to.\n * @param includes - Include tree.\n * @param options - Find options (`transaction` is passed on).\n * @returns Resolves when all separate includes are attached.\n */\n loadSeparate(\n parents: readonly Instance[],\n includes: readonly IncludeNode[],\n options: Readonly<Record<string, unknown>>,\n ): Promise<void> {\n return this.#separate.load(parents, includes, options);\n }\n}\n","import type { TableSample } from '../sql/ast.ts';\nimport { SqlAst } from '../sql/ast.ts';\nimport type { TableSampleOptions } from './source-options.ts';\n\nconst ast = new SqlAst();\nconst METHODS: ReadonlySet<string> = new Set(['BERNOULLI', 'SYSTEM']);\n\n/** Validates `sample` options and converts them to a `TABLESAMPLE` clause. */\nexport class TableSampleBuilder {\n /**\n * Builds the sampling clause.\n *\n * @param sample - Sample options.\n * @returns `TABLESAMPLE` node with bound percent and seed.\n * @throws Error for an unknown method, a percent outside 0–100, or a non-finite seed.\n */\n build(sample: TableSampleOptions): TableSample {\n const method = String(sample.method).toUpperCase();\n if (!METHODS.has(method)) {\n throw new Error(`Invalid TABLESAMPLE method: ${String(sample.method)}`);\n }\n if (!Number.isFinite(sample.percent) || sample.percent < 0 || sample.percent > 100) {\n throw new Error('TABLESAMPLE percent must be a number from 0 to 100');\n }\n if (sample.seed !== undefined && !Number.isFinite(sample.seed)) {\n throw new Error('TABLESAMPLE seed must be a finite number');\n }\n return {\n method: method as TableSample['method'],\n percent: ast.param(sample.percent),\n ...(sample.seed === undefined ? {} : { seed: ast.param(sample.seed) }),\n };\n }\n}\n","import type { ConnectionManager, ExecuteOptions } from '../connection/connection-manager.ts';\n\n/** Advisory lock key: a 64-bit integer, or a string hashed by PostgreSQL. */\nexport type AdvisoryLockKey = number | bigint | string;\n\n/** Transaction-level advisory locks taken on the connection of one transaction. */\nexport class AdvisoryLocks {\n readonly #connections: ConnectionManager;\n readonly #executeOptions: () => ExecuteOptions;\n\n /**\n * @param connections - Connection manager running the lock statements.\n * @param executeOptions - Execute options bound to the owning transaction.\n */\n constructor(connections: ConnectionManager, executeOptions: () => ExecuteOptions) {\n this.#connections = connections;\n this.#executeOptions = executeOptions;\n }\n\n /**\n * Waits for and takes the lock.\n *\n * @param key - Lock key.\n * @param shared - Take a shared lock.\n * @returns Resolves when the lock is held.\n */\n async lock(key: AdvisoryLockKey, shared: boolean): Promise<void> {\n await this.#connections.execute(\n AdvisoryLocks.#query(shared ? 'pg_advisory_xact_lock_shared' : 'pg_advisory_xact_lock', key),\n this.#executeOptions(),\n );\n }\n\n /**\n * Tries to take the lock without waiting.\n *\n * @param key - Lock key.\n * @param shared - Take a shared lock.\n * @returns True when the lock was acquired.\n */\n async tryLock(key: AdvisoryLockKey, shared: boolean): Promise<boolean> {\n const fn = shared ? 'pg_try_advisory_xact_lock_shared' : 'pg_try_advisory_xact_lock';\n const result = await this.#connections.execute(\n AdvisoryLocks.#query(fn, key, 'locked'),\n this.#executeOptions(),\n );\n return result.rows[0]?.['locked'] === true;\n }\n\n static #query(fn: string, key: AdvisoryLockKey, alias = 'lock') {\n return {\n text:\n typeof key === 'string'\n ? `SELECT ${fn}(hashtextextended($1, 0)) AS \"${alias}\"`\n : `SELECT ${fn}($1::bigint) AS \"${alias}\"`,\n values: [typeof key === 'string' ? key : String(key)],\n };\n }\n}\n","/** Transaction isolation levels (Sequelize v6 `Transaction.ISOLATION_LEVELS`). */\nexport const ISOLATION_LEVELS = {\n /** `READ UNCOMMITTED` (behaves as `READ COMMITTED` in PostgreSQL). */\n READ_UNCOMMITTED: 'READ UNCOMMITTED',\n /** `READ COMMITTED` (PostgreSQL default). */\n READ_COMMITTED: 'READ COMMITTED',\n /** `REPEATABLE READ`. */\n REPEATABLE_READ: 'REPEATABLE READ',\n /** `SERIALIZABLE`. */\n SERIALIZABLE: 'SERIALIZABLE',\n} as const;\n\n/** One of {@link ISOLATION_LEVELS}. */\nexport type IsolationLevel = (typeof ISOLATION_LEVELS)[keyof typeof ISOLATION_LEVELS];\n\n/** Row lock strengths for `findAll({ lock })` (Sequelize v6 `Transaction.LOCK`). */\nexport const LOCK = {\n /** `FOR UPDATE`. */\n UPDATE: 'UPDATE',\n /** `FOR SHARE`. */\n SHARE: 'SHARE',\n /** `FOR KEY SHARE`. */\n KEY_SHARE: 'KEY SHARE',\n /** `FOR NO KEY UPDATE`. */\n NO_KEY_UPDATE: 'NO KEY UPDATE',\n} as const;\n\n/** One of {@link LOCK}. */\nexport type LockStrength = (typeof LOCK)[keyof typeof LOCK];\n\n/** Transaction types; accepted for Sequelize v6 compatibility and ignored by PostgreSQL. */\nexport const TRANSACTION_TYPES = {\n /** SQLite-only, ignored. */\n DEFERRED: 'DEFERRED',\n /** SQLite-only, ignored. */\n IMMEDIATE: 'IMMEDIATE',\n /** SQLite-only, ignored. */\n EXCLUSIVE: 'EXCLUSIVE',\n} as const;\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { ISOLATION_LEVELS, type IsolationLevel } from './transaction-constants.ts';\n\n/** SQL statements that start and finish a transaction, or a savepoint when it is nested. */\nexport class TransactionStatements {\n readonly #savepoint: string | undefined;\n\n /**\n * @param id - Transaction id, quoted as the savepoint name.\n * @param nested - Whether the transaction is a savepoint inside a parent transaction.\n */\n constructor(id: string, nested: boolean) {\n this.#savepoint = nested ? SqlCompiler.quoteIdent(id) : undefined;\n }\n\n /**\n * @param options - Isolation level, access mode and deferrable mode of a top-level transaction.\n * @returns `START TRANSACTION …`, or `SAVEPOINT …` when nested.\n * @throws Error for an isolation level outside the allowlist or a non-boolean `deferrable`.\n */\n begin(\n options: Readonly<{\n isolationLevel?: IsolationLevel;\n readOnly?: boolean;\n deferrable?: boolean;\n }>,\n ): string {\n if (this.#savepoint !== undefined) {\n return `SAVEPOINT ${this.#savepoint}`;\n }\n return `START TRANSACTION${TransactionStatements.#modes(options)}`;\n }\n\n static #modes(\n options: Readonly<{\n isolationLevel?: IsolationLevel;\n readOnly?: boolean;\n deferrable?: boolean;\n }>,\n ): string {\n if (\n options.isolationLevel !== undefined &&\n !(Object.values(ISOLATION_LEVELS) as string[]).includes(options.isolationLevel)\n ) {\n throw new Error(`Invalid isolation level: ${String(options.isolationLevel)}`);\n }\n return [\n options.isolationLevel === undefined ? '' : ` ISOLATION LEVEL ${options.isolationLevel}`,\n options.readOnly === true ? ' READ ONLY' : '',\n TransactionStatements.#deferrable(options.deferrable),\n ].join('');\n }\n\n static #deferrable(deferrable: unknown): string {\n if (deferrable !== undefined && typeof deferrable !== 'boolean') {\n throw new Error(`Invalid deferrable option: ${String(deferrable)}`);\n }\n return deferrable === undefined ? '' : deferrable ? ' DEFERRABLE' : ' NOT DEFERRABLE';\n }\n\n /**\n * @returns `COMMIT`, or `RELEASE SAVEPOINT …` when nested.\n */\n commit(): string {\n return this.#savepoint === undefined ? 'COMMIT' : `RELEASE SAVEPOINT ${this.#savepoint}`;\n }\n\n /**\n * @returns `ROLLBACK`, or `ROLLBACK TO SAVEPOINT …` when nested.\n */\n rollback(): string {\n return this.#savepoint === undefined ? 'ROLLBACK' : `ROLLBACK TO SAVEPOINT ${this.#savepoint}`;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n Client,\n ConnectionManager,\n ExecuteOptions,\n} from '../connection/connection-manager.ts';\nimport type { LoggingFunction } from '../connection/options.ts';\nimport { AdvisoryLocks, type AdvisoryLockKey } from './advisory-locks.ts';\nimport { TransactionStatements } from './transaction-statements.ts';\nimport {\n ISOLATION_LEVELS,\n LOCK,\n TRANSACTION_TYPES,\n type IsolationLevel,\n} from './transaction-constants.ts';\n\nexport { ISOLATION_LEVELS, LOCK, TRANSACTION_TYPES } from './transaction-constants.ts';\nexport type { AdvisoryLockKey } from './advisory-locks.ts';\nexport type { IsolationLevel, LockStrength } from './transaction-constants.ts';\n\n/**\n * Options of `sequelize.transaction()`.\n *\n * All fields are optional.\n *\n * @example\n * ```ts\n * const options: TransactionOptions = {\n * isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,\n * readOnly: true,\n * deferrable: true,\n * settings: { 'app.user_id': '42', statement_timeout: '5s' },\n * };\n * const t = await sequelize.transaction(options);\n * await t.commit();\n * ```\n */\nexport type TransactionOptions = Readonly<{\n /** Isolation level of a new transaction. */\n isolationLevel?: IsolationLevel;\n /** Accepted for compatibility, ignored. */\n type?: (typeof TRANSACTION_TYPES)[keyof typeof TRANSACTION_TYPES];\n /** Start `READ ONLY`. PostgreSQL extension. */\n readOnly?: boolean;\n /**\n * Start `DEFERRABLE` (`true`) or `NOT DEFERRABLE` (`false`). PostgreSQL honours it only for\n * `SERIALIZABLE READ ONLY` transactions: a deferrable one waits for a safe snapshot and then runs\n * without serialization failures. Ignored for savepoints. PostgreSQL extension.\n */\n deferrable?: boolean;\n /** Parent transaction: the new transaction becomes a savepoint inside it. */\n transaction?: Transaction | null;\n /**\n * Session settings applied with `SET LOCAL` semantics (`set_config(name, value, true)`), e.g.\n * `{ 'app.user_id': '42', statement_timeout: '5s' }` for row-level security. PostgreSQL extension.\n */\n settings?: Readonly<Record<string, string | number | boolean>>;\n /** SQL logger for transaction statements. */\n logging?: LoggingFunction | false;\n}>;\n\n/**\n * Handle of an open database transaction or savepoint (Sequelize v6 `Transaction`).\n *\n * Obtain one from `sequelize.transaction()` and pass it to queries with the `transaction` option.\n * Unmanaged transactions must be finished with {@link Transaction.commit} or\n * {@link Transaction.rollback}; the connection is released to the pool when that happens.\n *\n * @example\n * ```ts\n * const t = await sequelize.transaction();\n * try {\n * const created = await User.create({ name: 'Ann' }, { transaction: t });\n * await Post.create({ title: 'Hi', userId: created.id }, { transaction: t });\n * await t.commit();\n * } catch (e) {\n * await t.rollback();\n * throw e;\n * }\n * ```\n */\nexport class Transaction {\n /** Values for the `isolationLevel` option, e.g. `SERIALIZABLE` or `READ_COMMITTED`. */\n static readonly ISOLATION_LEVELS = ISOLATION_LEVELS;\n /** Row lock strengths. */\n static readonly LOCK = LOCK;\n /** Transaction types (ignored by PostgreSQL). */\n static readonly TYPES = TRANSACTION_TYPES;\n\n /** Unique id, used in SQL logs and as savepoint name. */\n readonly id: string = randomUUID();\n /** Options the transaction was started with. */\n readonly options: TransactionOptions;\n /** Parent transaction when this one is a savepoint. */\n readonly parent: Transaction | undefined;\n /** `'commit'` or `'rollback'` once the transaction is finished. */\n finished: 'commit' | 'rollback' | undefined;\n\n readonly #connections: ConnectionManager;\n readonly #advisoryLocks: AdvisoryLocks;\n readonly #statements: TransactionStatements;\n #client: Client | undefined;\n #afterCommit: readonly ((transaction: Transaction) => unknown)[] = [];\n\n /**\n * Creates an unstarted transaction; use `sequelize.transaction()` instead of calling this directly.\n *\n * @param connections - Connection manager of the owning `Sequelize` instance.\n * @param options - Transaction options.\n */\n constructor(connections: ConnectionManager, options: TransactionOptions = {}) {\n this.#connections = connections;\n this.#advisoryLocks = new AdvisoryLocks(connections, () => this.executeOptions());\n this.options = options;\n this.parent = options.transaction ?? undefined;\n this.#statements = new TransactionStatements(this.id, this.parent !== undefined);\n }\n\n /** Row lock strengths (instance alias of {@link Transaction.LOCK}). */\n get LOCK(): typeof LOCK {\n return LOCK;\n }\n\n /** @internal */\n get client(): Client {\n const client = this.#client ?? this.parent?.client;\n if (client === undefined) {\n throw new Error('Transaction has not started');\n }\n return client;\n }\n\n /** @internal */\n executeOptions(): ExecuteOptions {\n return {\n client: this.client,\n transactionId: this.id,\n ...(this.options.logging === undefined ? {} : { logging: this.options.logging }),\n };\n }\n\n /** @internal */\n async begin(): Promise<this> {\n if (this.parent === undefined) {\n this.#client = await this.#connections.acquire();\n }\n try {\n await this.#run(this.#statements.begin(this.options));\n await this.#applySettings();\n } catch (error) {\n await this.#abortBegin();\n throw error;\n }\n return this;\n }\n\n /**\n * Commits the transaction (or releases the savepoint) and runs `afterCommit` hooks.\n *\n * @returns Resolves when committed and all `afterCommit` hooks have run.\n * @throws Error when the transaction is already finished.\n *\n * @example\n * ```ts\n * const t = await sequelize.transaction();\n * await User.create({ name: 'Ann' }, { transaction: t });\n * await t.commit();\n * ```\n */\n async commit(): Promise<void> {\n this.#assertActive('commit');\n try {\n await this.#run(this.#statements.commit());\n this.finished = 'commit';\n } finally {\n this.#release();\n }\n await this.#afterCommit.reduce<Promise<unknown>>(\n (previous, hook) => previous.then(() => hook(this)),\n Promise.resolve(),\n );\n }\n\n /**\n * Rolls the transaction back (or rolls back to the savepoint).\n *\n * @returns Resolves when rolled back.\n * @throws Error when the transaction is already finished.\n *\n * @example\n * ```ts\n * const t = await sequelize.transaction();\n * try {\n * await User.create({ name: 'Ann' }, { transaction: t });\n * await t.commit();\n * } catch (e) {\n * await t.rollback();\n * }\n * ```\n */\n async rollback(): Promise<void> {\n this.#assertActive('rollback');\n try {\n await this.#run(this.#statements.rollback());\n this.finished = 'rollback';\n } finally {\n this.#release();\n }\n }\n\n /**\n * Takes a transaction-level advisory lock (`pg_advisory_xact_lock`), waiting until it is free.\n * The lock is released on commit or rollback. PostgreSQL extension.\n *\n * @param key - Integer key, or a string hashed with `hashtextextended`.\n * @param options - `shared: true` for a shared lock.\n * @returns Resolves when the lock is held.\n *\n * @example\n * ```ts\n * await sequelize.transaction(async (t) => {\n * await t.advisoryLock('invoice-42');\n * await Invoice.update({ status: 'sent' }, { where: { id: 42 }, transaction: t });\n * });\n * ```\n */\n async advisoryLock(\n key: AdvisoryLockKey,\n options: Readonly<{ shared?: boolean }> = {},\n ): Promise<void> {\n await this.#advisoryLocks.lock(key, options.shared === true);\n }\n\n /**\n * Tries to take a transaction-level advisory lock without waiting. PostgreSQL extension.\n *\n * @param key - Integer key, or a string hashed with `hashtextextended`.\n * @param options - `shared: true` for a shared lock.\n * @returns True when the lock was acquired.\n *\n * @example\n * ```ts\n * await sequelize.transaction(async (t) => {\n * if (await t.tryAdvisoryLock(42, { shared: true })) {\n * await Task.findAll({ transaction: t });\n * }\n * });\n * ```\n */\n async tryAdvisoryLock(\n key: AdvisoryLockKey,\n options: Readonly<{ shared?: boolean }> = {},\n ): Promise<boolean> {\n return this.#advisoryLocks.tryLock(key, options.shared === true);\n }\n\n /**\n * Registers a callback run after a successful commit.\n *\n * @param hook - Callback receiving this transaction; hooks run in registration order after the\n * transaction is committed and are awaited by `commit()`. They never run after a rollback.\n *\n * @example\n * ```ts\n * await sequelize.transaction(async (t) => {\n * t.afterCommit(() => console.log('committed, safe to notify'));\n * await User.create({ name: 'Ann' }, { transaction: t });\n * });\n * ```\n */\n afterCommit(hook: (transaction: Transaction) => unknown): void {\n this.#afterCommit = [...this.#afterCommit, hook];\n }\n\n async #applySettings(): Promise<void> {\n await Object.entries(this.options.settings ?? {}).reduce<Promise<unknown>>(\n (previous, [name, value]) =>\n previous.then(() =>\n this.#connections.execute(\n { text: 'SELECT set_config($1, $2, true)', values: [name, String(value)] },\n this.executeOptions(),\n ),\n ),\n Promise.resolve(),\n );\n }\n\n async #abortBegin(): Promise<void> {\n if (this.parent === undefined) {\n // Never return a connection inside an open (possibly aborted) transaction to the pool.\n await this.#run(this.#statements.rollback()).catch(() => undefined);\n this.#release();\n }\n }\n\n #assertActive(action: string): void {\n if (this.finished !== undefined) {\n throw new Error(\n `Transaction cannot be ${action === 'commit' ? 'committed' : 'rolled back'} because it has been finished with state: ${this.finished}`,\n );\n }\n }\n\n async #run(sql: string): Promise<void> {\n await this.#connections.execute({ text: sql, values: [] }, this.executeOptions());\n }\n\n #release(): void {\n if (this.parent === undefined && this.#client !== undefined) {\n this.#client.release();\n this.#client = undefined;\n }\n }\n}\n","import type { LockNode } from '../sql/ast.ts';\nimport { LOCK } from '../transaction/transaction.ts';\nimport type { SelectOptions } from './select-options.ts';\n\nconst LOCK_STRENGTHS: ReadonlySet<string> = new Set(Object.values(LOCK));\n\n// Sequelize v6 emits FOR UPDATE for any lock level it does not know.\nconst lockStrength = (level: unknown): LockNode['strength'] =>\n typeof level === 'string' && LOCK_STRENGTHS.has(level)\n ? (level as LockNode['strength'])\n : LOCK.UPDATE;\n\nconst lockOf = (options: SelectOptions): LockNode | undefined => {\n if (options.lock === undefined || options.lock === false) {\n return undefined;\n }\n if (options.skipLocked === true && options.noWait === true) {\n throw new Error('skipLocked and noWait cannot be used together');\n }\n const wait =\n options.skipLocked === true ? 'SKIP LOCKED' : options.noWait === true ? 'NOWAIT' : undefined;\n const base: LockNode =\n options.lock === true\n ? { strength: 'UPDATE' }\n : typeof options.lock === 'string'\n ? { strength: lockStrength(options.lock) }\n : {\n strength: lockStrength(options.lock.level),\n ...(options.lock.of === undefined ? {} : { of: [options.lock.of.name] }),\n };\n return wait === undefined ? base : { ...base, wait };\n};\n\n/** Resolves the `lock`, `skipLocked` and `noWait` options into a row-lock clause. */\nexport class SelectLock {\n /**\n * Row-lock clause of the options.\n *\n * @param options - Select options.\n * @returns Lock node, or `undefined` without a lock.\n * @throws Error when `skipLocked` and `noWait` are both set.\n */\n of(options: SelectOptions): LockNode | undefined {\n return lockOf(options);\n }\n}\n","import { Fn } from '../expressions/methods.ts';\nimport { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { SelectOptions } from './select-options.ts';\nimport type { SelectTargets } from './select-targets.ts';\n\nconst ast = new SqlAst();\n\nconst aggregateColumn = (\n name: string,\n target: ExprNode,\n distinct: boolean | undefined,\n alias: string,\n): ExprNode => ({\n kind: 'alias',\n expr: {\n kind: 'fn',\n name,\n args: [target],\n ...(distinct === true ? { distinct: true } : {}),\n },\n alias,\n});\n\n/** Selected columns of `count()` and `aggregate()`: the grouped columns and the aggregate. */\nexport class SelectAggregates {\n readonly #columns: AttributeColumns;\n readonly #targets: SelectTargets;\n\n /**\n * @param columns - Attribute to column mapping.\n * @param targets - Converts attribute names and expressions.\n */\n constructor(columns: AttributeColumns, targets: SelectTargets) {\n this.#columns = columns;\n this.#targets = targets;\n }\n\n /**\n * Columns of `SELECT count(...) AS \"count\"`.\n *\n * @param definition - Model definition.\n * @param options - Select options with `col` / `distinct`.\n * @returns Group columns followed by the count.\n */\n count(\n definition: ModelDefinition,\n options: SelectOptions & Readonly<{ col?: string; distinct?: boolean }>,\n ): readonly ExprNode[] {\n const alias = definition.name;\n const count = aggregateColumn(\n 'count',\n this.#countTarget(definition, options),\n options.distinct,\n 'count',\n );\n const ctx = this.#columns.whereCompiler(definition, alias);\n return [...this.#targets.list(definition, alias, ctx, options.group), count];\n }\n\n /**\n * Columns of `SELECT fn(field) AS \"fn\"`.\n *\n * @param definition - Model definition.\n * @param field - Attribute name or `'*'`.\n * @param aggregateFunction - Aggregate function name.\n * @param options - Select options with `distinct`.\n * @returns Group columns followed by the aggregate.\n */\n aggregate(\n definition: ModelDefinition,\n field: string,\n aggregateFunction: string,\n options: SelectOptions & Readonly<{ distinct?: boolean }>,\n ): readonly ExprNode[] {\n const alias = definition.name;\n const ctx = this.#columns.whereCompiler(definition, alias);\n const target =\n field === '*'\n ? ({ kind: 'star' } as const)\n : this.#targets.target(definition, alias, ctx, field);\n const column = aggregateColumn(\n Fn.validName(aggregateFunction),\n target,\n options.distinct,\n aggregateFunction,\n );\n return [...this.#targets.list(definition, alias, ctx, options.group), column];\n }\n\n #countTarget(\n definition: ModelDefinition,\n options: Readonly<{ col?: string; distinct?: boolean }>,\n ): ExprNode {\n const alias = definition.name;\n if (options.col !== undefined) {\n const ctx = this.#columns.whereCompiler(definition, alias);\n return this.#targets.target(definition, alias, ctx, options.col);\n }\n return options.distinct === true\n ? ast.ident(\n alias,\n definition.attributes.get(definition.primaryKeys[0] ?? 'id')?.field ?? 'id',\n )\n : { kind: 'star' };\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { SqlAst, type ExprNode, type OrderNode } from '../sql/ast.ts';\nimport { OrderDirection } from '../sql/order.ts';\nimport type { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { AttributeSpec, FindAttributeOptions, Order } from './select-options.ts';\n\nconst ast = new SqlAst();\n\nconst invalidOrder = (): never => {\n throw new Error('Order must be type of array or instance of a valid sequelize method.');\n};\n\n/**\n * Converts the attribute and expression lists of finders into SELECT expressions: `attributes`,\n * `order`, `group` and `distinctOn` items, including `'jsonAttr.a.b'` paths.\n */\nexport class SelectTargets {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Selected columns for the `attributes` option.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param attributes - `attributes` option.\n * @returns Column expressions.\n */\n columns(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n attributes: FindAttributeOptions | undefined,\n ): readonly ExprNode[] {\n if (attributes === undefined || !Array.isArray(attributes)) {\n return this.#specColumns(definition, alias, ctx, (attributes ?? {}) as AttributeSpec);\n }\n return (attributes as readonly (string | readonly [unknown, string])[]).map((item) =>\n this.#attributeItem(definition, alias, ctx, item),\n );\n }\n\n /**\n * One `order` item.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param item - Attribute name, `[target, direction]` or expression.\n * @returns Order node.\n */\n orderItem(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n item: unknown,\n ): OrderNode {\n if (Array.isArray(item)) {\n const [target, direction]: readonly unknown[] = item;\n return {\n expr: this.target(definition, alias, ctx, target),\n ...(direction === undefined ? {} : OrderDirection.parse(direction)),\n };\n }\n return { expr: this.target(definition, alias, ctx, item) };\n }\n\n /**\n * Expression of an attribute name, `'jsonAttr.a.b'` path, `'table.column'` or expression.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param target - Attribute name or expression.\n * @returns Expression.\n */\n target(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n target: unknown,\n ): ExprNode {\n return typeof target === 'string'\n ? definition.attributes.has(target)\n ? ast.ident(alias, definition.attributes.get(target)?.field ?? target)\n : (this.#jsonPathOrder(definition, alias, target) ?? ast.ident(...target.split('.')))\n : ctx.toExpr(target);\n }\n\n /**\n * `ORDER BY` items of the `order` option.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param order - `order` option.\n * @returns Order nodes.\n * @throws Error for an order that is neither a list nor an expression.\n */\n orderBy(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n order: Order,\n ): readonly OrderNode[] {\n return order === undefined || order === null\n ? []\n : Array.isArray(order)\n ? order.map((item: unknown) => this.orderItem(definition, alias, ctx, item))\n : order instanceof SqlExpression\n ? [{ expr: ctx.toExpr(order) }]\n : invalidOrder();\n }\n\n /**\n * Expressions of a `group` or `distinctOn` option (one item or a list).\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param items - Attribute names or expressions.\n * @returns Expressions.\n */\n list(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n items: unknown,\n ): readonly ExprNode[] {\n return items === undefined\n ? []\n : (Array.isArray(items) ? items : [items]).map((item: unknown) =>\n this.target(definition, alias, ctx, item),\n );\n }\n\n /**\n * Expressions of the `distinctOn` option.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param items - Attribute names or expressions.\n * @returns Expressions.\n */\n distinctOn(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n items: readonly unknown[] | undefined,\n ): readonly ExprNode[] {\n return (items ?? []).map((item) => this.target(definition, alias, ctx, item));\n }\n\n #specColumns(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n spec: AttributeSpec,\n ): readonly ExprNode[] {\n const all = this.#columns.stored(definition).map((attribute) => attribute.fieldName);\n const excluded = new Set(spec.exclude ?? []);\n return [\n ...all\n .filter((name) => !excluded.has(name))\n .map((name) => SelectTargets.#columnFor(definition, alias, name)),\n ...(spec.include ?? []).map((item) => this.#attributeItem(definition, alias, ctx, item)),\n ];\n }\n\n #attributeItem(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n item: string | readonly [unknown, string],\n ): ExprNode {\n if (typeof item === 'string') {\n return SelectTargets.#columnFor(definition, alias, item);\n }\n const [source, name] = item;\n const expr =\n typeof source === 'string'\n ? ast.ident(alias, definition.attributes.get(source)?.field ?? source)\n : ctx.toExpr(source);\n return { kind: 'alias', expr, alias: name };\n }\n\n /** `'jsonAttr.a.b'` orders by the jsonb value at that path (numbers sort numerically). */\n #jsonPathOrder(definition: ModelDefinition, alias: string, target: string): ExprNode | undefined {\n const [name = '', ...path] = target.split('.');\n const attribute = definition.attributes.get(name);\n return attribute === undefined ||\n path.length === 0 ||\n (attribute.type.key !== 'JSON' && attribute.type.key !== 'JSONB')\n ? undefined\n : ast.binary(\n '#>',\n attribute.type.key === 'JSON'\n ? { kind: 'cast', expr: ast.ident(alias, attribute.field), type: 'JSONB' }\n : ast.ident(alias, attribute.field),\n ast.param(path),\n );\n }\n\n static #columnFor(definition: ModelDefinition, alias: string, name: string): ExprNode {\n const attribute = definition.attributes.get(name);\n const column = ast.ident(alias, attribute?.field ?? name);\n return attribute === undefined || attribute.field === name\n ? column\n : { kind: 'alias', expr: column, alias: name };\n }\n}\n","import type { ExprNode, FromItem, OrderNode, SelectNode, TableRef } from '../sql/ast.ts';\nimport type { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport { TableSampleBuilder } from './table-sample-builder.ts';\nimport { SelectLock } from './select-lock.ts';\nimport { SelectAggregates } from './select-aggregates.ts';\nimport type { FindAttributeOptions, SelectOptions } from './select-options.ts';\nimport { SelectTargets } from './select-targets.ts';\n\nexport type {\n AttributeSpec,\n FindAttributeOptions,\n LockOption,\n LockTarget,\n Order,\n OrderItem,\n SelectOptions,\n} from './select-options.ts';\n\nconst definedNumber = (value: number | null | undefined): number | undefined =>\n value === null || value === undefined ? undefined : value;\n\n/**\n * Builds SELECT statements of finders: columns from `attributes`, `where` / `having`, `order`,\n * `group`, `distinctOn`, `limit` / `offset`, row locks, and the `count()` / `aggregate()` forms.\n */\nexport class SelectQueryBuilder {\n readonly #columns: AttributeColumns;\n readonly #targets: SelectTargets;\n readonly #aggregates: SelectAggregates;\n readonly #locks = new SelectLock();\n readonly #samples = new TableSampleBuilder();\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n this.#targets = new SelectTargets(columns);\n this.#aggregates = new SelectAggregates(columns, this.#targets);\n }\n\n /**\n * Builds a SELECT for `findAll`-style options.\n *\n * @param definition - Model definition.\n * @param options - Select options.\n * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.\n * @param columnsOverride - Selected columns instead of `attributes`.\n * @param aliasOverride - Table alias instead of the model name.\n * @returns SELECT node.\n */\n build(\n definition: ModelDefinition,\n options: SelectOptions,\n inAsAnyThreshold?: number,\n columnsOverride?: readonly ExprNode[],\n aliasOverride?: string,\n ): SelectNode {\n const alias = aliasOverride ?? definition.name;\n const ctx = this.#columns.whereCompiler(definition, alias, inAsAnyThreshold);\n const clauses = this.#clauses(definition, alias, ctx, options);\n return {\n kind: 'select',\n ...SelectQueryBuilder.#sources(options),\n columns: columnsOverride ?? this.columns(definition, alias, ctx, options.attributes),\n from: this.#from(this.#columns.table(definition, alias), alias, options),\n ...clauses,\n orderBy: this.#targets.orderBy(definition, alias, ctx, options.order),\n ...SelectQueryBuilder.#window(options),\n };\n }\n\n /**\n * Builds `SELECT count(...) AS \"count\"` for `count()`.\n *\n * @param definition - Model definition.\n * @param options - Select options with `col` / `distinct`.\n * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.\n * @returns SELECT node.\n */\n count(\n definition: ModelDefinition,\n options: SelectOptions & Readonly<{ col?: string; distinct?: boolean }>,\n inAsAnyThreshold?: number,\n ): SelectNode {\n const columns = this.#aggregates.count(definition, options);\n const { order: _order, limit: _limit, offset: _offset, lock: _lock, ...rest } = options;\n return this.build(definition, rest, inAsAnyThreshold, columns);\n }\n\n /**\n * Builds `SELECT fn(field) AS \"fn\"` for `aggregate()`.\n *\n * @param definition - Model definition.\n * @param field - Attribute name or `'*'`.\n * @param aggregateFunction - Aggregate function name.\n * @param options - Select options with `distinct`.\n * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.\n * @returns SELECT node.\n */\n aggregate(\n definition: ModelDefinition,\n field: string,\n aggregateFunction: string,\n options: SelectOptions & Readonly<{ distinct?: boolean }>,\n inAsAnyThreshold?: number,\n ): SelectNode {\n const columns = this.#aggregates.aggregate(definition, field, aggregateFunction, options);\n const { order: _order, limit: _limit, offset: _offset, ...rest } = options;\n return this.build(definition, rest, inAsAnyThreshold, columns);\n }\n\n /**\n * Selected columns for the `attributes` option.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param attributes - `attributes` option.\n * @returns Column expressions.\n */\n columns(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n attributes: FindAttributeOptions | undefined,\n ): readonly ExprNode[] {\n return this.#targets.columns(definition, alias, ctx, attributes);\n }\n\n /**\n * One `order` item.\n *\n * @param definition - Model definition.\n * @param alias - Table alias.\n * @param ctx - Where compiler of the model.\n * @param item - Attribute name, `[target, direction]` or expression.\n * @returns Order node.\n */\n orderItem(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n item: unknown,\n ): OrderNode {\n return this.#targets.orderItem(definition, alias, ctx, item);\n }\n\n #clauses(\n definition: ModelDefinition,\n alias: string,\n ctx: WhereCompiler,\n options: SelectOptions,\n ): Partial<SelectNode> {\n const where = this.#columns.where(options.where, ctx);\n const having = this.#columns.where(options.having, ctx);\n const lock = this.#locks.of(options);\n const group = this.#targets.list(definition, alias, ctx, options.group);\n const distinctOn = this.#targets.distinctOn(definition, alias, ctx, options.distinctOn);\n return {\n ...(distinctOn.length === 0 ? {} : { distinctOn }),\n ...(where === undefined ? {} : { where }),\n ...(group.length === 0 ? {} : { groupBy: group }),\n ...(having === undefined ? {} : { having }),\n ...(lock === undefined ? {} : { lock }),\n };\n }\n\n #from(table: TableRef, alias: string, options: SelectOptions): FromItem {\n if (options.fromQuery !== undefined) {\n return { subquery: options.fromQuery, alias };\n }\n return options.sample === undefined\n ? table\n : { ...table, sample: this.#samples.build(options.sample) };\n }\n\n static #sources(options: SelectOptions): Partial<SelectNode> {\n return {\n ...(options.withClause === undefined ? {} : { with: options.withClause }),\n ...(options.extraFrom === undefined || options.extraFrom.length === 0\n ? {}\n : { extraFrom: options.extraFrom }),\n };\n }\n\n static #window(options: SelectOptions): Partial<SelectNode> {\n const limit = definedNumber(options.limit);\n const offset = definedNumber(options.offset);\n if (options.withTies === true && limit === undefined) {\n throw new Error('withTies requires a limit');\n }\n return {\n ...(limit === undefined ? {} : { limit }),\n ...(options.withTies === true ? { withTies: true } : {}),\n ...(offset === undefined ? {} : { offset }),\n };\n }\n}\n","import type { ModelDefinition } from '../model/model-definition.ts';\nimport { AttributeColumns } from '../model/attribute-columns.ts';\nimport { SelectQueryBuilder, type FindAttributeOptions } from '../model/select-query-builder.ts';\nimport { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport type { IncludeNode } from './include.ts';\n\nconst ast = new SqlAst();\nconst attributeColumns = new AttributeColumns();\nconst selects = new SelectQueryBuilder(attributeColumns);\n\nconst field = (definition: ModelDefinition, name: string): string =>\n definition.attributes.get(name)?.field ?? name;\n\nconst parentKey = (node: IncludeNode): string =>\n node.association.associationType === 'BelongsTo'\n ? node.association.foreignKey\n : node.association.sourceKey;\n\nconst selectsField = (column: ExprNode, name: string, fieldName: string): boolean =>\n column.kind === 'star' ||\n (column.kind === 'ident' && column.path.at(-1) === fieldName) ||\n (column.kind === 'alias' && column.alias === name);\n\n/** Columns an include adds to the SELECT, aliased by result path (`Posts.title`). */\nexport class IncludeColumns {\n /**\n * Prefixed columns of an include, its junction and its nested includes.\n *\n * @param node - Include node.\n * @returns Aliased column expressions.\n */\n columns(node: IncludeNode): readonly ExprNode[] {\n const { through } = node;\n return [\n ...this.#prefixed(node.definition, node.alias, node.path, node.attributes),\n ...(through === undefined\n ? []\n : this.#prefixed(through.definition, through.alias, through.path, through.attributes)),\n ...node.children.filter((child) => !child.separate).flatMap((child) => this.columns(child)),\n ];\n }\n\n /**\n * Join keys of the main table that the subquery must expose for the outer joins.\n *\n * @param definition - Main model definition.\n * @param alias - Main table alias.\n * @param columns - Columns already selected.\n * @param joined - Joined includes.\n * @returns Missing key columns.\n */\n missingKeys(\n definition: ModelDefinition,\n alias: string,\n columns: readonly ExprNode[],\n joined: readonly IncludeNode[],\n ): readonly ExprNode[] {\n return [...new Set(joined.map(parentKey))]\n .filter(\n (name) => !columns.some((column) => selectsField(column, name, field(definition, name))),\n )\n .map((name) => ast.ident(alias, field(definition, name)));\n }\n\n #prefixed(\n definition: ModelDefinition,\n alias: string,\n path: string,\n attributes: FindAttributeOptions | undefined,\n ): readonly ExprNode[] {\n return selects\n .columns(definition, alias, attributeColumns.whereCompiler(definition, alias), attributes)\n .map((column) => {\n const expr = column.kind === 'alias' ? column.expr : column;\n return { kind: 'alias', expr, alias: `${path}.${this.#name(definition, column)}` } as const;\n });\n }\n\n #name(definition: ModelDefinition, column: ExprNode): string {\n return column.kind === 'alias'\n ? column.alias\n : column.kind === 'ident'\n ? (definition.fieldToAttribute.get(column.path.at(-1) ?? '') ?? column.path.at(-1) ?? '')\n : '';\n }\n}\n","import type { ModelDefinition } from '../model/model-definition.ts';\nimport { AttributeColumns } from '../model/attribute-columns.ts';\nimport { SqlAst, type ExprNode, type JoinNode } from '../sql/ast.ts';\nimport type { IncludeNode } from './include.ts';\n\nconst ast = new SqlAst();\nconst attributeColumns = new AttributeColumns();\n\ntype Through = NonNullable<IncludeNode['through']>;\n\nconst defined = (part: ExprNode | undefined): part is ExprNode => part !== undefined;\n\n/** Column name of an attribute (the attribute name when it has no explicit field). */\nconst field = (definition: ModelDefinition, name: string): string =>\n definition.attributes.get(name)?.field ?? name;\n\n/** Builds the JOIN nodes of an include and its nested includes. */\nexport class IncludeJoins {\n /**\n * Joins of an include: the target table, or junction then target for belongsToMany, followed by\n * the joins of the nested (non-separate) includes.\n *\n * @param parent - Definition of the parent model.\n * @param parentAlias - Table alias of the parent.\n * @param node - Include node.\n * @returns Join nodes.\n */\n joins(parent: ModelDefinition, parentAlias: string, node: IncludeNode): readonly JoinNode[] {\n return node.through === undefined\n ? this.#direct(parent, parentAlias, node)\n : this.#viaJunction(parent, parentAlias, node, node.through);\n }\n\n #type(node: IncludeNode): JoinNode['type'] {\n return node.right ? 'RIGHT OUTER' : node.required ? 'INNER' : 'LEFT OUTER';\n }\n\n #direct(parent: ModelDefinition, parentAlias: string, node: IncludeNode): readonly JoinNode[] {\n return [\n {\n type: this.#type(node),\n table: attributeColumns.table(node.definition, node.alias),\n on: ast.and([this.#onClause(parent, parentAlias, node), ...this.#extra(node)]),\n },\n ...this.#childJoins(node),\n ];\n }\n\n #viaJunction(\n parent: ModelDefinition,\n parentAlias: string,\n node: IncludeNode,\n through: Through,\n ): readonly JoinNode[] {\n return [\n {\n type: this.#type(node),\n table: attributeColumns.table(through.definition, through.alias),\n on: ast.and(this.#junctionCondition(parent, parentAlias, node, through)),\n },\n this.#targetJoin(node, through),\n ...this.#childJoins(node),\n ];\n }\n\n #targetJoin(node: IncludeNode, through: Through): JoinNode {\n return {\n type: this.#type(node),\n table: attributeColumns.table(node.definition, node.alias),\n on: ast.and([\n ast.binary(\n '=',\n ast.ident(node.alias, field(node.definition, node.association.targetKey)),\n ast.ident(through.alias, field(through.definition, node.association.otherKey ?? '')),\n ),\n ...this.#extra(node),\n ]),\n };\n }\n\n #junctionCondition(\n parent: ModelDefinition,\n parentAlias: string,\n node: IncludeNode,\n through: Through,\n ): readonly ExprNode[] {\n return [\n ast.binary(\n '=',\n ast.ident(parentAlias, field(parent, node.association.sourceKey)),\n ast.ident(through.alias, field(through.definition, node.association.foreignKey)),\n ),\n attributeColumns.where(\n through.where,\n attributeColumns.whereCompiler(through.definition, through.alias),\n ),\n this.#scopeCondition(through.definition, through.alias, node.association.through?.scope),\n ].filter(defined);\n }\n\n #childJoins(node: IncludeNode): readonly JoinNode[] {\n return node.children\n .filter((child) => !child.separate)\n .flatMap((child) => this.joins(node.definition, node.alias, child));\n }\n\n #extra(node: IncludeNode): readonly ExprNode[] {\n return [\n this.#condition(node.definition, node.alias, node.where, node.paranoid),\n this.#scopeCondition(node.definition, node.alias, node.association.scope),\n ].filter(defined);\n }\n\n #condition(\n definition: ModelDefinition,\n alias: string,\n where: unknown,\n paranoid: boolean,\n ): ExprNode | undefined {\n const condition = attributeColumns.where(\n where,\n attributeColumns.whereCompiler(definition, alias),\n );\n const notDeleted = paranoid ? this.#notDeleted(definition, alias) : undefined;\n const parts = [condition, notDeleted].filter(defined);\n return parts.length === 0 ? undefined : ast.and(parts);\n }\n\n #notDeleted(definition: ModelDefinition, alias: string): ExprNode | undefined {\n return definition.deletedAt === undefined\n ? undefined\n : ({\n kind: 'postfix',\n op: 'IS NULL',\n expr: ast.ident(alias, field(definition, definition.deletedAt)),\n } as const);\n }\n\n #scopeCondition(\n definition: ModelDefinition,\n alias: string,\n scope: Readonly<Record<string, unknown>> | undefined,\n ): ExprNode | undefined {\n return scope === undefined\n ? undefined\n : attributeColumns.where(scope, attributeColumns.whereCompiler(definition, alias));\n }\n\n #onClause(parent: ModelDefinition, parentAlias: string, node: IncludeNode): ExprNode {\n const { association } = node;\n return association.associationType === 'BelongsTo'\n ? ast.binary(\n '=',\n ast.ident(parentAlias, field(parent, association.foreignKey)),\n ast.ident(node.alias, field(node.definition, association.targetKey)),\n )\n : ast.binary(\n '=',\n ast.ident(parentAlias, field(parent, association.sourceKey)),\n ast.ident(node.alias, field(node.definition, association.foreignKey)),\n );\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport type { ModelDefinition } from '../model/model-definition.ts';\nimport { AttributeColumns } from '../model/attribute-columns.ts';\nimport { SelectQueryBuilder } from '../model/select-query-builder.ts';\nimport { SqlAst, type OrderNode } from '../sql/ast.ts';\nimport { OrderDirection } from '../sql/order.ts';\nimport type { IncludeNode, IncludeOptions } from './include.ts';\n\nconst ast = new SqlAst();\nconst attributeColumns = new AttributeColumns();\nconst selects = new SelectQueryBuilder(attributeColumns);\n\ntype WhereContext = ReturnType<AttributeColumns['whereCompiler']>;\n\n/** ORDER BY nodes: all of them, and those that belong inside the main-table subquery. */\nexport type OrderNodes = Readonly<{ all: readonly OrderNode[]; main: readonly OrderNode[] }>;\n\nconst field = (definition: ModelDefinition, name: string): string =>\n definition.attributes.get(name)?.field ?? name;\n\n/** Resolves `order` items that reference an include (`[Include, 'attr', 'DESC']`). */\nexport class IncludeOrder {\n /**\n * Order nodes of a find, resolving items that go through includes.\n *\n * @param definition - Main model definition.\n * @param includes - Joined includes.\n * @param order - `order` option.\n * @param mainAlias - Main table alias.\n * @returns All order nodes and the ones for the subquery.\n */\n nodes(\n definition: ModelDefinition,\n includes: readonly IncludeNode[],\n order: unknown,\n mainAlias: string,\n ): OrderNodes {\n if (order === undefined || order === null) {\n return { all: [], main: [] };\n }\n const ctx = attributeColumns.whereCompiler(definition, mainAlias);\n const items: readonly unknown[] = Array.isArray(order) ? order : [order];\n const resolved = items.map((item) => this.#resolve(definition, includes, item, mainAlias, ctx));\n return {\n all: resolved.map((entry) => entry.node),\n main: resolved.filter((entry) => entry.main).map((entry) => entry.node),\n };\n }\n\n #resolve(\n definition: ModelDefinition,\n includes: readonly IncludeNode[],\n item: unknown,\n mainAlias: string,\n ctx: WhereContext,\n ): Readonly<{ node: OrderNode; main: boolean }> {\n const viaInclude = this.#viaInclude(includes, item);\n if (viaInclude !== undefined) {\n return { node: viaInclude, main: false };\n }\n const node =\n item instanceof SqlExpression\n ? { expr: attributeColumns.where(item, ctx) ?? ast.raw('1') }\n : selects.orderItem(definition, mainAlias, ctx, item);\n return { node, main: true };\n }\n\n #viaInclude(includes: readonly IncludeNode[], item: unknown): OrderNode | undefined {\n const throughInclude =\n Array.isArray(item) &&\n (item.length > 2 ||\n (item.length === 2 && typeof item[0] !== 'string' && !(item[0] instanceof SqlExpression)));\n return throughInclude ? this.#includeOrder(includes, item as readonly unknown[]) : undefined;\n }\n\n #hasDirection(item: readonly unknown[]): boolean {\n const last = item[item.length - 1];\n if (typeof last !== 'string') {\n return false;\n }\n try {\n OrderDirection.parse(last);\n return true;\n } catch {\n return false;\n }\n }\n\n #includeOrder(includes: readonly IncludeNode[], item: readonly unknown[]): OrderNode | undefined {\n const hasDirection = this.#hasDirection(item);\n const parts = hasDirection ? item.slice(0, -1) : item;\n const attribute = parts.at(-1);\n const references = parts.slice(0, -1);\n if (references.length === 0 || typeof attribute !== 'string') {\n return undefined;\n }\n const node = this.#walk(includes, references);\n return node === undefined\n ? undefined\n : {\n expr: ast.ident(node.alias, field(node.definition, attribute)),\n ...(hasDirection ? OrderDirection.parse(item[item.length - 1]) : {}),\n };\n }\n\n #walk(includes: readonly IncludeNode[], references: readonly unknown[]): IncludeNode | undefined {\n return references.reduce<Readonly<{ nodes: readonly IncludeNode[]; node?: IncludeNode }>>(\n (acc, reference) => {\n const found = this.#find(acc.nodes, reference);\n return { nodes: found?.children ?? [], node: found };\n },\n { nodes: includes },\n ).node;\n }\n\n #find(nodes: readonly IncludeNode[], reference: unknown): IncludeNode | undefined {\n return nodes.find((node) => this.#matches(node, reference));\n }\n\n #matches(node: IncludeNode, reference: unknown): boolean {\n if (typeof reference === 'string') {\n return node.as === reference;\n }\n if (typeof reference === 'function') {\n return node.model === reference;\n }\n if (typeof reference !== 'object' || reference === null || !('model' in reference)) {\n return false;\n }\n const options = reference as IncludeOptions;\n return node.model === options.model && (options.as === undefined || node.as === options.as);\n }\n}\n","import type { ModelDefinition } from '../model/model-definition.ts';\nimport { SqlAst, type ExprNode, type SelectNode } from '../sql/ast.ts';\nimport type { IncludeNode } from './include.ts';\nimport type { IncludeJoins } from './include-joins.ts';\n\nconst ast = new SqlAst();\n\nconst isMulti = (node: IncludeNode): boolean => node.association.isMultiAssociation;\n\nconst aliasesOf = (nodes: readonly IncludeNode[]): readonly string[] =>\n nodes.flatMap((node) => [node.alias, ...aliasesOf(node.children)]);\n\n/** True when a condition references a joined include (`$Include.attr$`) as a table. */\nconst referencesIncludes = (\n where: ExprNode | undefined,\n includes: readonly IncludeNode[],\n): boolean => {\n if (where === undefined) {\n return false;\n }\n const text = JSON.stringify(where);\n return aliasesOf(includes).some((alias) => text.includes(`\"path\":[${JSON.stringify(alias)},`));\n};\n\n/** Decides the v6 sub-query form of a find with includes and builds its `EXISTS` filters. */\nexport class IncludeSubQuery {\n readonly #joins: IncludeJoins;\n\n /**\n * @param joins - Builds the joins the `EXISTS` filters are made of.\n */\n constructor(joins: IncludeJoins) {\n this.#joins = joins;\n }\n\n /**\n * Whether `limit`/`offset` must go into a subquery of the main table (v6 rules). A top-level\n * `where` that references a joined include cannot run inside that subquery, so it disables it.\n *\n * @param includes - Joined includes.\n * @param options - Limit / offset / subQuery of the find.\n * @param where - Compiled top-level condition.\n * @returns True for the sub-query form.\n */\n needsSubQuery(\n includes: readonly IncludeNode[],\n options: Readonly<{ limit?: number | null; offset?: number | null; subQuery?: boolean }>,\n where?: ExprNode,\n ): boolean {\n return (\n options.subQuery !== false &&\n !referencesIncludes(where, includes) &&\n ((options.limit !== undefined && options.limit !== null) ||\n (options.offset !== undefined && options.offset !== null)) &&\n includes.some(\n (node) =>\n !node.separate && (isMulti(node) || node.children.some((child) => isMulti(child))),\n )\n );\n }\n\n /**\n * `EXISTS` condition that keeps the rows of the main table having a matching required include.\n *\n * @param parent - Main model definition.\n * @param parentAlias - Main table alias.\n * @param node - Required include.\n * @returns Condition.\n */\n existsFilter(parent: ModelDefinition, parentAlias: string, node: IncludeNode): ExprNode {\n const joins = this.#joins.joins(parent, parentAlias, {\n ...node,\n children: node.children.filter((child) => child.required),\n required: true,\n });\n const [first, ...rest] = joins;\n if (first === undefined) {\n return ast.raw('TRUE');\n }\n const query: SelectNode = {\n kind: 'select',\n columns: [ast.raw('1')],\n from: first.table,\n ...(rest.length === 0 ? {} : { joins: rest }),\n where: first.on,\n };\n return { kind: 'prefix', op: 'EXISTS', expr: { kind: 'subquery', query } };\n }\n}\n","import type { ModelDefinition } from '../model/model-definition.ts';\nimport { SqlAst, type ExprNode, type JoinNode, type SelectNode } from '../sql/ast.ts';\nimport type { IncludeNode } from './include.ts';\nimport { IncludeColumns } from './include-columns.ts';\nimport { IncludeJoins } from './include-joins.ts';\nimport { IncludeOrder, type OrderNodes } from './include-order.ts';\nimport { IncludeSubQuery } from './include-sub-query.ts';\n\nconst ast = new SqlAst();\n\n/** Options of the main query that affect the include joins. */\nexport type IncludeQueryOptions = Readonly<{\n /** `order` option (may reference includes). */\n order?: unknown;\n /** `limit` option. */\n limit?: number | null;\n /** `offset` option. */\n offset?: number | null;\n /** `subQuery: false` disables the sub-query form. */\n subQuery?: boolean;\n}>;\n\ntype Parts = Readonly<{\n definition: ModelDefinition;\n alias: string;\n base: SelectNode;\n joined: readonly IncludeNode[];\n order: OrderNodes;\n}>;\n\n/**\n * Adds include joins, columns and ordering to a SELECT of the main model (ADR-009): decides the\n * v6 sub-query form for `limit` with multi includes, turns required includes into `EXISTS`\n * filters there, and builds the joins of `count` with includes.\n */\nexport class IncludeQueryBuilder {\n readonly #joins = new IncludeJoins();\n readonly #columns = new IncludeColumns();\n readonly #order = new IncludeOrder();\n readonly #subQuery = new IncludeSubQuery(this.#joins);\n\n /**\n * Adds joins, include columns and include ordering to a SELECT built for the main model.\n *\n * @param definition - Main model definition.\n * @param base - SELECT of the main model.\n * @param includes - Include tree.\n * @param options - Order / limit / offset / subQuery of the find.\n * @returns SELECT with the includes.\n */\n build(\n definition: ModelDefinition,\n base: SelectNode,\n includes: readonly IncludeNode[],\n options: IncludeQueryOptions,\n ): SelectNode {\n const alias = definition.name;\n const joined = includes.filter((node) => !node.separate);\n const order = this.#order.nodes(definition, joined, options.order, alias);\n const parts = { definition, alias, base, joined, order };\n return this.needsSubQuery(joined, options, base.where)\n ? this.#subQueryForm(parts)\n : {\n ...base,\n columns: [...base.columns, ...joined.flatMap((node) => this.#columns.columns(node))],\n joins: this.#joinsOf(parts),\n orderBy: order.all,\n };\n }\n\n /**\n * Whether `limit`/`offset` must go into a subquery of the main table (v6 rules). A top-level\n * `where` that references a joined include cannot run inside that subquery, so it disables it.\n *\n * @param includes - Joined includes.\n * @param options - Limit / offset / subQuery of the find.\n * @param where - Compiled top-level condition.\n * @returns True for the sub-query form.\n */\n needsSubQuery(\n includes: readonly IncludeNode[],\n options: Readonly<{ limit?: number | null; offset?: number | null; subQuery?: boolean }>,\n where?: ExprNode,\n ): boolean {\n return this.#subQuery.needsSubQuery(includes, options, where);\n }\n\n /**\n * Joins for `count` with includes (no include columns).\n *\n * @param definition - Main model definition.\n * @param includes - Include tree.\n * @returns Join nodes.\n */\n countJoins(definition: ModelDefinition, includes: readonly IncludeNode[]): readonly JoinNode[] {\n return includes\n .filter((node) => !node.separate)\n .flatMap((node) => this.#joins.joins(definition, definition.name, node));\n }\n\n #joinsOf(parts: Parts): readonly JoinNode[] {\n return parts.joined.flatMap((node) => this.#joins.joins(parts.definition, parts.alias, node));\n }\n\n #innerSelect(parts: Parts): SelectNode {\n const { definition, alias, base, joined, order } = parts;\n const filters = joined\n .filter((node) => node.required)\n .map((node) => this.#subQuery.existsFilter(definition, alias, node));\n const missing = this.#columns.missingKeys(definition, alias, base.columns, joined);\n return {\n ...base,\n columns: [...base.columns, ...missing],\n ...(base.where === undefined && filters.length === 0\n ? {}\n : { where: ast.and([...(base.where === undefined ? [] : [base.where]), ...filters]) }),\n orderBy: order.main,\n };\n }\n\n #subQueryForm(parts: Parts): SelectNode {\n const { alias, base, joined, order } = parts;\n return {\n kind: 'select',\n columns: [\n { kind: 'star', table: alias },\n ...joined.flatMap((node) => this.#columns.columns(node)),\n ],\n from: { subquery: this.#innerSelect(parts), alias },\n joins: this.#joinsOf(parts),\n orderBy: order.all,\n ...(base.lock === undefined ? {} : { lock: base.lock }),\n };\n }\n}\n","/** Driver error object as produced by `pg` (a subset of its fields). */\nexport type DriverError = Error &\n Readonly<{\n /** SQLSTATE or Node.js error code. */\n code?: string;\n /** Error detail reported by PostgreSQL. */\n detail?: string;\n /** Table the error refers to. */\n table?: string;\n /** Constraint the error refers to. */\n constraint?: string;\n /** Schema the error refers to. */\n schema?: string;\n /** Column the error refers to. */\n column?: string;\n }>;\n\n/**\n * Root of the error hierarchy, so one `instanceof` check catches every error postgrelize throws (Sequelize v6 `BaseError`).\n *\n * Programmer mistakes (such as committing a finished transaction) still throw a plain `Error`.\n *\n * @example\n * ```ts\n * try {\n * await User.findOne({ where: { id: 1 }, rejectOnEmpty: true });\n * } catch (e) {\n * if (e instanceof BaseError) {\n * console.error(e.name, e.message);\n * }\n * }\n * ```\n */\nexport class BaseError extends Error {\n /**\n * Creates the error and sets `name` to `'SequelizeBaseError'`.\n *\n * @param message - Error message.\n * @param options - Standard error options (`cause`).\n */\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'SequelizeBaseError';\n }\n}\n","import { BaseError, type DriverError } from './base-error.ts';\nimport type { ConstraintErrorOptions } from './database-errors.ts';\n\n/** Origin of a validation error item. */\nexport type ValidationErrorItemOrigin = 'CORE' | 'DB' | 'FUNCTION';\n\nconst ORIGIN_BY_TYPE: Readonly<Record<string, ValidationErrorItemOrigin>> = {\n 'notnull violation': 'CORE',\n 'string violation': 'CORE',\n 'unique violation': 'DB',\n 'validation error': 'FUNCTION',\n};\n\nconst ORIGINS: ReadonlySet<string> = new Set(['CORE', 'DB', 'FUNCTION']);\n\nconst classify = (\n type: string | null | undefined,\n): Readonly<{ origin: ValidationErrorItemOrigin | null; type: string | null }> => {\n const origin =\n type === undefined || type === null ? undefined : ORIGIN_BY_TYPE[type.toLowerCase().trim()];\n return {\n origin:\n type !== undefined && type !== null && ORIGINS.has(type)\n ? (type as ValidationErrorItemOrigin)\n : (origin ?? null),\n type: origin === undefined ? null : (type ?? null),\n };\n};\n\n/**\n * Describes a single failed validation: which attribute, which value and which validator (Sequelize v6 `ValidationErrorItem`).\n *\n * `origin` is derived from `type`: `'CORE'` for not-null and string violations, `'DB'` for unique violations, `'FUNCTION'` for custom validators.\n *\n * @example\n * ```ts\n * try {\n * await User.create({ email: 'not-an-email' });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * for (const item of e.errors) {\n * console.error(item.path, item.validatorKey, item.value, item.origin);\n * }\n * }\n * }\n * ```\n */\nexport class ValidationErrorItem {\n /** Human-readable message. */\n readonly message: string;\n /** Validation type, e.g. `'unique violation'`, `'notNull Violation'`, `'Validation error'`. */\n declare readonly type: string | null;\n /** Attribute name (or model validator name). */\n readonly path: string | null;\n /** Offending value. */\n readonly value: unknown;\n /** Where the error was raised, derived from `type`. */\n declare readonly origin: ValidationErrorItemOrigin | null;\n /** Instance being validated. */\n readonly instance: object | null;\n /** Validator key, e.g. `'not_unique'`, `'is_null'`, `'isEmail'`. */\n readonly validatorKey: string | null;\n /** Built-in validator name. */\n readonly validatorName: string | null;\n /** Built-in validator arguments. */\n readonly validatorArgs: readonly unknown[];\n\n /**\n * Creates an item; `path`, `instance`, `validatorKey` and `validatorName` default to `null`, `validatorArgs` to `[]`, and `value` to `null` when `undefined`.\n *\n * @param message - Human-readable message.\n * @param type - Validation type or origin.\n * @param path - Attribute name.\n * @param value - Offending value.\n * @param instance - Instance being validated.\n * @param validatorKey - Validator key.\n * @param validatorName - Built-in validator name.\n * @param validatorArgs - Built-in validator arguments.\n */\n constructor(\n message: string,\n type?: string | null,\n path?: string | null,\n value?: unknown,\n instance?: object | null,\n validatorKey?: string | null,\n validatorName?: string | null,\n validatorArgs?: readonly unknown[],\n ) {\n this.message = message;\n this.path = path ?? null;\n this.value = value === undefined ? null : value;\n this.instance = instance ?? null;\n this.validatorKey = validatorKey ?? null;\n this.validatorName = validatorName ?? null;\n this.validatorArgs = validatorArgs ?? [];\n Object.assign(this, classify(type));\n }\n}\n\n/**\n * Thrown when a model instance fails validation, carrying one item per failed rule (Sequelize v6 `ValidationError`).\n *\n * Raised by `create`, `save`, `update`, `build(...).validate()` and similar before any SQL is sent. Not-null, unique and validator failures all end up in `errors`.\n *\n * @example\n * ```ts\n * try {\n * await User.create({ email: 'not-an-email' });\n * } catch (e) {\n * if (e instanceof ValidationError) {\n * console.error(e.errors.map((item) => `${item.path}: ${item.message}`));\n * }\n * }\n * ```\n */\nexport class ValidationError extends BaseError {\n /** Individual validation failures. */\n readonly errors: readonly ValidationErrorItem[];\n\n /**\n * Creates the error from a message and its items.\n *\n * @param message - Error message; when empty it is built from the items like Sequelize v6.\n * @param errors - Individual validation failures.\n */\n constructor(message: string | null | undefined, errors: readonly ValidationErrorItem[] = []) {\n super(\n message !== null && message !== undefined && message !== ''\n ? message\n : errors.length > 0\n ? errors.map((item) => `${item.type ?? item.origin ?? ''}: ${item.message}`).join(',\\n')\n : 'Validation Error',\n );\n this.name = 'SequelizeValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Thrown when PostgreSQL reports a unique violation (SQLSTATE `23505`); a {@link ValidationError} subclass like in Sequelize v6.\n *\n * `fields` maps the unique columns to the offending values (parsed from the PostgreSQL detail) and `errors` has one `not_unique` item per column.\n *\n * @example\n * ```ts\n * try {\n * await User.create({ email: 'taken@example.com' });\n * } catch (e) {\n * if (e instanceof UniqueConstraintError) {\n * console.error(e.fields, e.errors[0]?.message);\n * }\n * }\n * ```\n */\nexport class UniqueConstraintError extends ValidationError {\n /** Original driver error. */\n readonly parent: DriverError;\n /** Original driver error (alias of `parent`). */\n readonly original: DriverError;\n /** Executed SQL text. */\n readonly sql: string;\n /** Unique columns mapped to offending values. */\n readonly fields: Readonly<Record<string, string>>;\n\n /**\n * Builds the error; the message defaults to `Validation error`.\n *\n * @param options - Driver error, fields and validation items.\n */\n constructor(\n options: Omit<ConstraintErrorOptions, 'fields'> &\n Readonly<{\n fields?: Readonly<Record<string, string>>;\n errors?: readonly ValidationErrorItem[];\n }>,\n ) {\n super(options.message ?? 'Validation error', options.errors);\n this.name = 'SequelizeUniqueConstraintError';\n this.parent = options.parent;\n this.original = options.parent;\n this.sql = options.sql ?? '';\n this.fields = options.fields ?? {};\n }\n}\n","import { BaseError, type DriverError } from './base-error.ts';\n\n/** Context attached to errors raised while executing SQL. */\nexport type QueryErrorContext = Readonly<{\n /** Executed SQL text. */\n sql?: string;\n /** Bound parameter values. */\n parameters?: readonly unknown[];\n}>;\n\n/**\n * Error returned by PostgreSQL while executing a query (Sequelize v6 `DatabaseError`).\n *\n * Any driver error without a more specific mapping becomes a `DatabaseError`; `sql` and `parameters` describe the failed statement and `parent.code` holds the SQLSTATE.\n *\n * @example\n * ```ts\n * try {\n * await sequelize.query('SELECT * FROM missing_table');\n * } catch (e) {\n * if (e instanceof DatabaseError) {\n * console.error(e.parent.code, e.sql, e.parameters);\n * }\n * }\n * ```\n */\nexport class DatabaseError extends BaseError {\n /** Original driver error. */\n readonly parent: DriverError;\n /** Original driver error (alias of `parent`). */\n readonly original: DriverError;\n /** Executed SQL text. */\n readonly sql: string;\n /** Bound parameter values. */\n readonly parameters: readonly unknown[];\n\n /**\n * Wraps a driver error together with the statement that failed.\n *\n * @param parent - Original driver error.\n * @param context - Executed SQL and parameters; `sql` defaults to `''` and `parameters` to `[]`.\n */\n constructor(parent: DriverError, context: QueryErrorContext = {}) {\n super(parent.message, { cause: parent });\n this.name = 'SequelizeDatabaseError';\n this.parent = parent;\n this.original = parent;\n this.sql = context.sql ?? '';\n this.parameters = context.parameters ?? [];\n }\n}\n\n/**\n * Query cancelled by PostgreSQL, e.g. because `statement_timeout` elapsed (SQLSTATE `57014`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.query('SELECT pg_sleep(10)');\n * } catch (e) {\n * if (e instanceof TimeoutError) {\n * console.error('query was cancelled:', e.sql);\n * }\n * }\n * ```\n */\nexport class TimeoutError extends DatabaseError {\n /**\n * Wraps a driver error together with the statement that failed.\n *\n * @param parent - Original driver error.\n * @param context - Executed SQL and parameters.\n */\n constructor(parent: DriverError, context?: QueryErrorContext) {\n super(parent, context);\n this.name = 'SequelizeTimeoutError';\n }\n}\n\n/**\n * Input of the constraint error constructors: the driver error plus what PostgreSQL reported about the constraint.\n *\n * @example\n * ```ts\n * const options: ConstraintErrorOptions = {\n * parent: Object.assign(new Error('violates foreign key constraint'), { code: '23503' }),\n * fields: ['userId'],\n * table: 'posts',\n * constraint: 'posts_userId_fkey',\n * sql: 'INSERT INTO \"posts\" (\"userId\") VALUES ($1)',\n * parameters: [42],\n * };\n * const error = new ForeignKeyConstraintError(options);\n * ```\n */\nexport type ConstraintErrorOptions = QueryErrorContext &\n Readonly<{\n /** Original driver error. */\n parent: DriverError;\n /** Constraint columns mapped to offending values. */\n fields?: Readonly<Record<string, string>> | readonly string[];\n /** Table name. */\n table?: string;\n /** Constraint name. */\n constraint?: string;\n /** Error message, defaults to the driver message. */\n message?: string;\n }>;\n\n/**\n * Thrown when a write references a missing row or removes a row that is still referenced (SQLSTATE `23503`).\n *\n * `fields` lists the referencing columns (parsed from the PostgreSQL detail), `table` the table and `index` the constraint name.\n *\n * @example\n * ```ts\n * try {\n * await Post.create({ title: 'Hello', userId: 999999 });\n * } catch (e) {\n * if (e instanceof ForeignKeyConstraintError) {\n * console.error(e.table, e.fields, e.index);\n * }\n * }\n * ```\n */\nexport class ForeignKeyConstraintError extends DatabaseError {\n /** Referencing columns. */\n readonly fields: readonly string[];\n /** Table name. */\n readonly table: string | undefined;\n /** Constraint name. */\n readonly index: string | undefined;\n\n /**\n * Builds the error from the constraint details; an object `fields` is reduced to its keys.\n *\n * @param options - Driver error, fields and context.\n */\n constructor(options: ConstraintErrorOptions) {\n super(options.parent, options);\n this.name = 'SequelizeForeignKeyConstraintError';\n this.fields = Array.isArray(options.fields)\n ? options.fields\n : Object.keys(options.fields ?? {});\n this.table = options.table;\n this.index = options.constraint;\n }\n}\n\n/**\n * Thrown when a row conflicts with an exclusion constraint, e.g. overlapping ranges (SQLSTATE `23P01`). PostgreSQL-specific; v6 has no such class.\n *\n * `constraint` is the constraint name, `fields` the columns parsed from the PostgreSQL detail and `table` the table.\n *\n * @example\n * ```ts\n * try {\n * await Task.create({ room: 'A', during: [new Date('2026-01-01'), new Date('2026-01-02')] });\n * } catch (e) {\n * if (e instanceof ExclusionConstraintError) {\n * console.error(e.constraint, e.fields);\n * }\n * }\n * ```\n */\nexport class ExclusionConstraintError extends DatabaseError {\n /** Constraint name. */\n readonly constraint: string | undefined;\n /** Constraint columns. */\n readonly fields: readonly string[];\n /** Table name. */\n readonly table: string | undefined;\n\n /**\n * Builds the error from the constraint details; an object `fields` is reduced to its keys.\n *\n * @param options - Driver error, fields and context.\n */\n constructor(options: ConstraintErrorOptions) {\n super(options.parent, options);\n this.name = 'SequelizeExclusionConstraintError';\n this.constraint = options.constraint;\n this.fields = Array.isArray(options.fields)\n ? options.fields\n : Object.keys(options.fields ?? {});\n this.table = options.table;\n }\n}\n","import { BaseError } from './base-error.ts';\n\n/**\n * Failure to reach or authenticate against PostgreSQL (Sequelize v6 `ConnectionError`).\n *\n * Thrown when connecting fails and for driver errors with an unmapped `08xxx` SQLSTATE. The subclasses below narrow the cause; `parent` and `original` hold the driver error.\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof ConnectionError) {\n * console.error('cannot connect:', e.parent.message);\n * }\n * }\n * ```\n */\nexport class ConnectionError extends BaseError {\n /** Original driver error. */\n readonly parent: Error;\n /** Original driver error (alias of `parent`). */\n readonly original: Error;\n\n /**\n * Wraps a driver error; the message and `cause` are taken from it.\n *\n * @param parent - Original driver error.\n */\n constructor(parent: Error) {\n super(parent.message, { cause: parent });\n this.name = 'SequelizeConnectionError';\n this.parent = parent;\n this.original = parent;\n }\n}\n\nconst connectionError = (name: string): typeof ConnectionError =>\n class extends ConnectionError {\n constructor(parent: Error) {\n super(parent);\n this.name = name;\n }\n };\n\n/**\n * Thrown when the server refuses the connection (`ECONNREFUSED`), typically because PostgreSQL is not running on that host and port.\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof ConnectionRefusedError) {\n * console.error('database is down');\n * }\n * }\n * ```\n */\nexport class ConnectionRefusedError extends connectionError('SequelizeConnectionRefusedError') {}\n/**\n * Thrown when PostgreSQL rejects the credentials (SQLSTATE `28P01` or `28000`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof AccessDeniedError) {\n * console.error('check username and password');\n * }\n * }\n * ```\n */\nexport class AccessDeniedError extends connectionError('SequelizeAccessDeniedError') {}\n/**\n * Thrown when the host name cannot be resolved (`ENOTFOUND` or `EAI_AGAIN`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof HostNotFoundError) {\n * console.error('unknown database host');\n * }\n * }\n * ```\n */\nexport class HostNotFoundError extends connectionError('SequelizeHostNotFoundError') {}\n/**\n * Thrown when no route to the host exists (`EHOSTUNREACH`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof HostNotReachableError) {\n * console.error('database host is unreachable');\n * }\n * }\n * ```\n */\nexport class HostNotReachableError extends connectionError('SequelizeHostNotReachableError') {}\n/**\n * Thrown when the connection parameters are rejected by the network layer (`EINVAL`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof InvalidConnectionError) {\n * console.error('check host and port settings');\n * }\n * }\n * ```\n */\nexport class InvalidConnectionError extends connectionError('SequelizeInvalidConnectionError') {}\n/**\n * Thrown when the TCP connection to the server times out (`ETIMEDOUT`).\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (e) {\n * if (e instanceof ConnectionTimedOutError) {\n * console.error('database did not answer in time');\n * }\n * }\n * ```\n */\nexport class ConnectionTimedOutError extends connectionError('SequelizeConnectionTimedOutError') {}\n/**\n * Thrown when no pooled connection became free within `pool.acquire` milliseconds (default 60000).\n *\n * Raise `pool.max` or shorten the transactions that hold connections.\n * See {@link PoolOptions}.\n *\n * @example\n * ```ts\n * try {\n * await User.findAll();\n * } catch (e) {\n * if (e instanceof ConnectionAcquireTimeoutError) {\n * console.error('pool exhausted');\n * }\n * }\n * ```\n */\nexport class ConnectionAcquireTimeoutError extends connectionError(\n 'SequelizeConnectionAcquireTimeoutError',\n) {}\n","import { BaseError } from './base-error.ts';\n\n/**\n * Thrown when saving an instance of a model with `version: true` updates no row because another writer changed it first (optimistic locking).\n *\n * The failed update is not retried; reload the instance and apply the change again.\n *\n * @example\n * ```ts\n * const user = await User.findByPk(1);\n * try {\n * await user!.update({ name: 'New name' });\n * } catch (e) {\n * if (e instanceof OptimisticLockError) {\n * console.error(e.modelName, e.where);\n * }\n * }\n * ```\n */\nexport class OptimisticLockError extends BaseError {\n /** Name of the model whose row was stale; `undefined` when not given. */\n readonly modelName: string | undefined;\n /** Primary key values of the row. */\n readonly where: unknown;\n /** Expected version values. */\n readonly values: unknown;\n\n /**\n * Builds the error; the message defaults to `Attempting to update a stale model instance: <modelName>`.\n *\n * @param options - Model name, values and where of the failed update.\n */\n constructor(\n options: Readonly<{\n message?: string;\n modelName?: string;\n values?: unknown;\n where?: unknown;\n }> = {},\n ) {\n super(\n options.message ?? `Attempting to update a stale model instance: ${options.modelName ?? ''}`,\n );\n this.name = 'SequelizeOptimisticLockError';\n this.modelName = options.modelName;\n this.values = options.values;\n this.where = options.where;\n }\n}\n\n/**\n * Failure of one record in a bulk operation, carrying the offending record.\n *\n * Collected into an {@link AggregateError} by `bulkCreate` with `validate: true`.\n *\n * @example\n * ```ts\n * try {\n * await User.bulkCreate([{ email: 'not-an-email' }], { validate: true });\n * } catch (e) {\n * if (e instanceof AggregateError) {\n * for (const item of e.errors) {\n * if (item instanceof BulkRecordError) {\n * console.error(item.record, item.errors.message);\n * }\n * }\n * }\n * }\n * ```\n */\nexport class BulkRecordError extends BaseError {\n /** Underlying error. */\n readonly errors: Error;\n /** Record that failed. */\n readonly record: object;\n\n /**\n * Wraps the validation error of one record; the message is copied from it.\n *\n * @param error - Underlying error.\n * @param record - Record that failed.\n */\n constructor(error: Error, record: object) {\n super(error.message);\n this.name = 'SequelizeBulkRecordError';\n this.errors = error;\n this.record = record;\n }\n}\n\n/**\n * Bundles the errors of one bulk operation into a single error (Sequelize v6 `AggregateError`).\n *\n * `bulkCreate` with `validate: true` validates every record and throws this error with one {@link BulkRecordError} per invalid record. The message joins the messages of all errors with newlines.\n *\n * @example\n * ```ts\n * try {\n * await User.bulkCreate([{ email: 'a' }, { email: 'b' }], { validate: true });\n * } catch (e) {\n * if (e instanceof AggregateError) {\n * console.error(`${e.errors.length} records failed`);\n * }\n * }\n * ```\n */\nexport class AggregateError extends BaseError {\n /** Collected errors. */\n readonly errors: readonly Error[];\n\n /**\n * Creates the error from the collected errors.\n *\n * @param errors - Collected errors.\n */\n constructor(errors: readonly Error[]) {\n super(errors.map((error) => error.message).join('\\n'));\n this.name = 'AggregateError';\n this.errors = errors;\n }\n}\n\n/**\n * Thrown by finders called with `rejectOnEmpty: true` when no row matches.\n *\n * Pass an `Error` instance as `rejectOnEmpty` to throw it instead of this class.\n *\n * @example\n * ```ts\n * try {\n * await User.findOne({ where: { email: 'nobody@example.com' }, rejectOnEmpty: true });\n * } catch (e) {\n * if (e instanceof EmptyResultError) {\n * console.error('no such user');\n * }\n * }\n * ```\n */\nexport class EmptyResultError extends BaseError {\n /**\n * Creates the error.\n *\n * @param message - Error message.\n */\n constructor(message?: string) {\n super(message);\n this.name = 'SequelizeEmptyResultError';\n }\n}\n\n/**\n * Thrown when an instance method is used on an instance in the wrong state, e.g. `reload()` for a row that no longer exists.\n *\n * @example\n * ```ts\n * try {\n * await user.destroy();\n * await user.reload();\n * } catch (e) {\n * if (e instanceof InstanceError) {\n * console.error(e.message);\n * }\n * }\n * ```\n */\nexport class InstanceError extends BaseError {\n /**\n * Creates the error.\n *\n * @param message - Error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'SequelizeInstanceError';\n }\n}\n\n/**\n * Thrown when an `include` names a model that is not associated with the queried model.\n *\n * @example\n * ```ts\n * try {\n * await User.findAll({ include: [Tag] });\n * } catch (e) {\n * if (e instanceof EagerLoadingError) {\n * console.error(e.message);\n * }\n * }\n * ```\n */\nexport class EagerLoadingError extends BaseError {\n /**\n * Creates the error.\n *\n * @param message - Error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'SequelizeEagerLoadingError';\n }\n}\n\n/**\n * Thrown when an association is defined incorrectly, e.g. two associations of one model share an alias.\n *\n * @example\n * ```ts\n * try {\n * User.hasMany(Post, { as: 'items' });\n * User.hasMany(Task, { as: 'items' });\n * } catch (e) {\n * if (e instanceof AssociationError) {\n * console.error(e.message);\n * }\n * }\n * ```\n */\nexport class AssociationError extends BaseError {\n /**\n * Creates the error.\n *\n * @param message - Error message.\n */\n constructor(message: string) {\n super(message);\n this.name = 'SequelizeAssociationError';\n }\n}\n","import { EagerLoadingError } from '../errors/errors.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport type { IncludeOptions } from './include.ts';\nimport type { Association } from './types.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\n\n/** Finds the association an include entry refers to, by object, alias or target model. */\nexport class AssociationLookup {\n /**\n * Replaces `{ all: true }` entries with one entry per association of `source`.\n *\n * @param source - Model the includes are resolved on.\n * @param items - Include entries.\n * @returns Include entries without `all`.\n */\n expandAll(source: Model, items: readonly IncludeOptions[]): readonly IncludeOptions[] {\n return items.flatMap((item): readonly IncludeOptions[] =>\n item.all === true\n ? [...this.#associationsOf(source).values()].map((association): IncludeOptions => ({\n association,\n }))\n : [item],\n );\n }\n\n /**\n * Association an include entry refers to.\n *\n * @param source - Model the include is resolved on.\n * @param item - Include entry.\n * @returns The association.\n * @throws EagerLoadingError when the target model is not associated to `source`.\n */\n resolve(source: Model, item: IncludeOptions): Association {\n if (item.association !== undefined) {\n return this.#byAssociation(source, item.association);\n }\n return item.as === undefined\n ? this.#byModel(source, item)\n : this.#byAlias(source, item.as, item);\n }\n\n #associationsOf(model: Model): ReadonlyMap<string, Association> {\n return registry.state(model).associations as ReadonlyMap<string, Association>;\n }\n\n #nameOf(model: Model): string {\n return registry.state(model).definition.name;\n }\n\n #sameModel(left: Model, right: Model): boolean {\n return registry.state(left) === registry.state(right);\n }\n\n #byAssociation(source: Model, given: Association | string): Association {\n const association = typeof given === 'string' ? this.#associationsOf(source).get(given) : given;\n if (association === undefined) {\n throw new Error(\n `Association with alias \"${String(given)}\" does not exist on ${this.#nameOf(source)}`,\n );\n }\n return association;\n }\n\n #aliases(source: Model, item: IncludeOptions): readonly string[] {\n const { model } = item;\n return [...this.#associationsOf(source).values()]\n .filter((association) => model === undefined || this.#sameModel(association.target, model))\n .map((association) => association.as);\n }\n\n #byAlias(source: Model, alias: string, item: IncludeOptions): Association {\n const association = this.#associationsOf(source).get(alias);\n if (\n association === undefined ||\n (item.model !== undefined && !this.#sameModel(association.target, item.model))\n ) {\n const targetName = item.model === undefined ? alias : this.#nameOf(item.model);\n throw new EagerLoadingError(\n `${targetName} is associated to ${this.#nameOf(source)} using an alias. You've included an alias (${alias}), but it does not match the alias(es) defined in your association (${this.#aliases(source, item).join(', ')}).`,\n );\n }\n return association;\n }\n\n #byModel(source: Model, item: IncludeOptions): Association {\n const candidates = [...this.#associationsOf(source).values()].filter(\n (association) => item.model !== undefined && this.#sameModel(association.target, item.model),\n );\n const targetName = item.model === undefined ? '?' : this.#nameOf(item.model);\n if (candidates.length === 0) {\n throw new EagerLoadingError(`${targetName} is not associated to ${this.#nameOf(source)}!`);\n }\n if (candidates.length > 1) {\n throw new EagerLoadingError(\n `${targetName} is associated to ${this.#nameOf(source)} multiple times. To identify the correct association, you must use the 'as' keyword to specify the alias of the association you want to include.`,\n );\n }\n return candidates[0] as Association;\n }\n}\n","import type { AnyModel, ModelStatic } from '../model/options.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport type { IncludeNode, IncludeOption, IncludeOptions } from './include.ts';\nimport { AssociationLookup } from './association-lookup.ts';\nimport type { Association } from './types.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\ntype Position = Readonly<{ alias: string; path: string }>;\ntype BaseNode = Omit<IncludeNode, 'alias' | 'path' | 'through' | 'children'>;\n\nconst isModel = (value: unknown): value is Model => typeof value === 'function';\n\nconst toOptions = (item: Model | string | IncludeOptions): IncludeOptions =>\n isModel(item) ? { model: item } : typeof item === 'string' ? { association: item } : item;\n\n/**\n * Normalizes the `include` option into an include tree: resolves associations by model, alias or\n * association object, expands `{ all: true }` and injects the scope of the included model.\n */\nexport class IncludeResolver {\n readonly #lookup = new AssociationLookup();\n\n /**\n * Normalizes the `include` option of `source` into an include tree.\n *\n * @param source - Model the includes are resolved on.\n * @param option - `include` option.\n * @param parentAlias - Table alias of the parent include (`''` for the main model).\n * @param parentPath - Result path of the parent include (`''` for the main model).\n * @returns Include nodes.\n * @throws EagerLoadingError when a model is not associated to `source`.\n */\n normalize(\n source: Model,\n option: IncludeOption | undefined,\n parentAlias = '',\n parentPath = '',\n ): readonly IncludeNode[] {\n if (option === undefined) {\n return [];\n }\n const items = this.#lookup.expandAll(\n source,\n (Array.isArray(option) ? option : [option]).map(toOptions),\n );\n const parent = { alias: parentAlias, path: parentPath };\n return items.map((item) => this.#node(source, item, parent));\n }\n\n /**\n * Converts an include node back to include options.\n *\n * @param node - Include node.\n * @returns Include options resolving to the same node.\n */\n toOptions(node: IncludeNode): IncludeOptions {\n return {\n association: node.association,\n required: node.required,\n separate: node.separate,\n lateral: node.lateral,\n paranoid: node.paranoid,\n ...(node.where === undefined ? {} : { where: node.where }),\n ...(node.attributes === undefined ? {} : { attributes: node.attributes }),\n ...(node.children.length === 0\n ? {}\n : { include: node.children.map((child) => this.toOptions(child)) }),\n };\n }\n\n #node(source: Model, unscoped: IncludeOptions, parent: Position): IncludeNode {\n const association = this.#lookup.resolve(source, unscoped);\n const item = this.#withTargetScope(unscoped, association.target);\n const position = {\n alias: parent.alias === '' ? association.as : `${parent.alias}->${association.as}`,\n path: parent.path === '' ? association.as : `${parent.path}.${association.as}`,\n };\n return {\n ...this.#base(association, item),\n ...position,\n through: this.#through(association, item, position),\n children: this.normalize(association.target, item.include, position.alias, position.path),\n };\n }\n\n #base(association: Association, item: IncludeOptions): BaseNode {\n return {\n association,\n model: association.target,\n definition: registry.state(association.target).definition,\n as: association.as,\n where: item.where,\n required: item.required ?? item.where !== undefined,\n right: item.right === true,\n attributes: item.attributes,\n separate: item.separate === true && association.associationType === 'HasMany',\n lateral: item.lateral === true,\n paranoid: item.paranoid !== false,\n order: item.order,\n limit: item.limit,\n };\n }\n\n #through(\n association: Association,\n item: IncludeOptions,\n position: Position,\n ): IncludeNode['through'] {\n if (association.through === undefined) {\n return undefined;\n }\n const { model } = association.through;\n const definition = registry.state(model).definition;\n return {\n model,\n definition,\n alias: `${position.alias}->${definition.name}`,\n path: `${position.path}.${definition.name}`,\n attributes: item.through?.attributes,\n where: item.through?.where,\n };\n }\n\n /**\n * Merges the scope of the included model into the include options like Sequelize v6\n * `_injectScope`: a scoped class given as `model` brings its scopes, otherwise the target's\n * default scope applies. Include options win.\n */\n #withTargetScope(item: IncludeOptions, target: Model): IncludeOptions {\n const scoped = item.model ?? target;\n return registry\n .state(scoped)\n .scopes.inject(\n registry.activeScope(scoped),\n item as Readonly<Record<string, unknown>>,\n ) as IncludeOptions;\n }\n}\n","import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';\nimport { SqlExpression } from '../expressions/methods.ts';\nimport type { AttributeDefinition, ModelDefinition } from './model-definition.ts';\nimport type { AttributeAmounts, Values } from './options.ts';\nimport type { QueryOptionsBase } from './runtime.ts';\n\n/**\n * Attribute value rules of model operations: change detection, defaults, timestamps, field\n * selection, increment amounts, values taken from `where`, and the query options passed on to\n * nested queries.\n */\nexport class ModelValues {\n /**\n * Whether two attribute values are equal (dates by time, objects by JSON).\n *\n * @param left - First value.\n * @param right - Second value.\n * @returns True when equal.\n */\n isEqual(left: unknown, right: unknown): boolean {\n return left instanceof Date && right instanceof Date\n ? left.getTime() === right.getTime()\n : typeof left === 'object' && left !== null && typeof right === 'object' && right !== null\n ? JSON.stringify(left) === JSON.stringify(right)\n : left === right;\n }\n\n /**\n * Values of a new instance: attribute defaults and `null` primary keys.\n *\n * @param definition - Model definition.\n * @returns Initial values.\n */\n initial(definition: ModelDefinition): Values {\n return Object.fromEntries([\n ...[...definition.attributes.values()]\n .filter((attribute) => attribute.defaultValue !== undefined)\n .map((attribute) => [attribute.fieldName, this.#defaultValueOf(attribute)] as const),\n ...definition.primaryKeys\n .filter((name) => definition.attributes.get(name)?.defaultValue === undefined)\n .map((name) => [name, null] as const),\n ]);\n }\n\n /**\n * Amount per attribute of `increment` / `decrement`.\n *\n * @param fields - Attribute name(s), or a map of attribute to amount.\n * @param by - Amount for names.\n * @returns Amount per attribute.\n */\n amounts(fields: AttributeAmounts<Values>, by: number): Readonly<Record<string, number>> {\n return typeof fields === 'string'\n ? { [fields]: by }\n : Array.isArray(fields)\n ? Object.fromEntries(fields.map((name: string) => [name, by]))\n : (fields as Readonly<Record<string, number>>);\n }\n\n /**\n * Values restricted to `fields` (all values when `fields` is not given).\n *\n * @param values - Values.\n * @param fields - Attribute names.\n * @returns Picked values.\n */\n pick(values: Values, fields: readonly string[] | undefined): Values {\n return fields === undefined\n ? values\n : Object.fromEntries(Object.entries(values).filter(([key]) => fields.includes(key)));\n }\n\n /**\n * Explicit `fields` of `save` / `create` extended like v6: `updatedAt` and the version\n * attribute (when anything is written), and for an INSERT `createdAt` and primary keys that\n * have a default.\n *\n * @param definition - Model definition.\n * @param fields - Fields as given, or `undefined`.\n * @param creating - Whether the row is inserted.\n * @returns Fields to write (`undefined` when none were given).\n */\n saveFields(\n definition: ModelDefinition,\n fields: readonly string[] | undefined,\n creating: boolean,\n ): readonly string[] | undefined {\n if (fields === undefined) {\n return undefined;\n }\n const keys = definition.primaryKeys.filter(\n (name) => definition.attributes.get(name)?.defaultValue !== undefined,\n );\n const extra = [\n ...(fields.length > 0 ? [definition.updatedAt, definition.version] : []),\n ...(creating ? [definition.createdAt] : []),\n ].filter((name): name is string => name !== undefined);\n return [...new Set([...(creating ? keys : []), ...fields, ...extra])];\n }\n\n /**\n * Explicit `fields` of `bulkCreate` extended with the timestamp attributes, like v6.\n *\n * @param definition - Model definition.\n * @param fields - Fields as given, or `undefined`.\n * @returns Fields to write (`undefined` when none were given).\n */\n bulkFields(\n definition: ModelDefinition,\n fields: readonly string[] | undefined,\n ): readonly string[] | undefined {\n return fields === undefined\n ? undefined\n : [\n ...new Set([\n ...fields,\n ...[definition.createdAt, definition.updatedAt].filter(\n (name): name is string => name !== undefined,\n ),\n ]),\n ];\n }\n\n /**\n * Query options passed on to nested queries: `transaction`, `logging`, `benchmark`.\n *\n * @param options - Options of the outer call.\n * @returns Query options.\n */\n queryOptions(options: QueryOptionsBase): QueryOptionsBase {\n return {\n ...(options.transaction === undefined ? {} : { transaction: options.transaction }),\n ...(options.logging === undefined ? {} : { logging: options.logging }),\n ...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),\n };\n }\n\n /**\n * Sets `createdAt` (on creation, when empty) and `updatedAt` (unless `silent`).\n *\n * @param definition - Model definition.\n * @param values - Values.\n * @param now - Timestamp.\n * @param creating - Whether the row is inserted.\n * @param silent - `silent` option.\n * @returns Values with timestamps.\n */\n withTimestamps(\n definition: ModelDefinition,\n values: Values,\n now: Date,\n creating: boolean,\n silent: boolean,\n ): Values {\n const { createdAt, updatedAt } = definition;\n const setCreatedAt =\n creating &&\n createdAt !== undefined &&\n (values[createdAt] === undefined || values[createdAt] === null);\n return {\n ...values,\n ...(setCreatedAt ? { [createdAt]: now } : {}),\n ...(updatedAt !== undefined && (!silent || creating)\n ? { [updatedAt]: this.#updatedAt(values[updatedAt], now, creating, silent) }\n : {}),\n };\n }\n\n #updatedAt(current: unknown, now: Date, creating: boolean, silent: boolean): unknown {\n return creating && current instanceof Date && silent ? current : now;\n }\n\n /**\n * Plain values of a `where` object (used as defaults by `findOrCreate` / `findOrBuild`).\n *\n * @param where - Condition.\n * @returns Attribute values compared with `=`.\n */\n fromWhere(where: unknown): Values {\n return typeof where === 'object' &&\n where !== null &&\n !Array.isArray(where) &&\n !(where instanceof SqlExpression)\n ? Object.fromEntries(\n Object.entries(where).filter(\n ([, value]) => typeof value !== 'object' || value === null || value instanceof Date,\n ),\n )\n : {};\n }\n\n #defaultValueOf(attribute: AttributeDefinition): unknown {\n return attribute.defaultValue instanceof DefaultValueGenerator\n ? attribute.defaultValue.generate()\n : attribute.defaultValue instanceof SqlExpression\n ? attribute.defaultValue\n : structuredClone(attribute.defaultValue);\n }\n}\n","import type { AnyModel, SaveOptions, Values } from '../model/options.ts';\nimport { ModelValues } from '../model/model-values.ts';\nimport type { IncludeNode } from './include.ts';\n\n/** Tells model instances apart from plain values (injected to avoid importing `Model`). */\nexport type InstanceCheck = (value: unknown) => value is AnyModel;\n\nconst modelValues = new ModelValues();\n\nconst toArray = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : [value]);\n\n/** Saves the nested instances of a nested creation, in the order Sequelize v6 does. */\nexport class NestedSaver {\n readonly #isInstance: InstanceCheck;\n\n /**\n * @param isInstance - Checks whether a value is a model instance.\n */\n constructor(isInstance: InstanceCheck) {\n this.#isInstance = isInstance;\n }\n\n /**\n * Saves nested belongsTo parents and sets the foreign keys on the instance.\n *\n * @param instance - Instance being created.\n * @param includes - Include tree of the instance.\n * @param options - Save options (query options are passed on).\n * @returns Resolves when the parents are saved.\n */\n async saveBelongsTo(\n instance: AnyModel,\n includes: readonly IncludeNode[],\n options: SaveOptions,\n ): Promise<void> {\n await includes\n .filter((node) => node.association.associationType === 'BelongsTo')\n .reduce<Promise<unknown>>(\n (previous, node) => previous.then(() => this.#saveParent(instance, node, options)),\n Promise.resolve(),\n );\n }\n\n /**\n * Saves nested hasOne / hasMany / belongsToMany children after the instance, one at a time.\n *\n * @param instance - Saved instance.\n * @param includes - Include tree of the instance.\n * @param options - Save options (query options are passed on).\n * @returns Resolves when the children are saved.\n */\n async saveChildren(\n instance: AnyModel,\n includes: readonly IncludeNode[],\n options: SaveOptions,\n ): Promise<void> {\n const pairs = includes\n .filter((node) => node.association.associationType !== 'BelongsTo')\n .flatMap((node) =>\n this.#nestedInstances(instance, node).map((child) => [node, child] as const),\n );\n await pairs.reduce<Promise<unknown>>(\n (previous, [node, child]) =>\n previous.then(() => this.#saveChild(instance, node, child, options)),\n Promise.resolve(),\n );\n }\n\n #nestedInstances(instance: AnyModel, node: IncludeNode): readonly AnyModel[] {\n return toArray((instance.dataValues as Values)[node.as]).filter(this.#isInstance);\n }\n\n #throughValues(child: AnyModel, node: IncludeNode): Values {\n const value =\n node.through === undefined\n ? undefined\n : (child.dataValues as Values)[node.through.definition.name];\n return this.#isInstance(value)\n ? (value.get({ plain: true }) as Values)\n : typeof value === 'object' && value !== null\n ? (value as Values)\n : {};\n }\n\n async #saveParent(instance: AnyModel, node: IncludeNode, options: SaveOptions): Promise<void> {\n const [parent] = this.#nestedInstances(instance, node);\n if (parent !== undefined) {\n await parent.save(modelValues.queryOptions(options));\n instance.set(node.association.foreignKey, parent.get(node.association.targetKey));\n }\n }\n\n async #saveChild(\n instance: AnyModel,\n node: IncludeNode,\n child: AnyModel,\n options: SaveOptions,\n ): Promise<void> {\n const { association } = node;\n const childOptions = modelValues.queryOptions(options);\n if (association.associationType === 'BelongsToMany' && association.through !== undefined) {\n await child.save(childOptions);\n await this.#saveJunction(instance, node, child, childOptions);\n return;\n }\n child.set({\n ...association.scope,\n [association.foreignKey]: instance.get(association.sourceKey),\n });\n await child.save(childOptions);\n }\n\n async #saveJunction(\n instance: AnyModel,\n node: IncludeNode,\n child: AnyModel,\n childOptions: ReturnType<ModelValues['queryOptions']>,\n ): Promise<void> {\n const { association } = node;\n await association.through?.model.create(\n {\n ...this.#throughValues(child, node),\n ...association.through.scope,\n [association.foreignKey]: instance.get(association.sourceKey),\n [association.otherKey ?? '']: child.get(association.targetKey),\n } as never,\n childOptions as never,\n );\n }\n}\n","import type { AnyModel, SaveOptions, Values } from '../model/options.ts';\nimport type { IncludeNode } from './include.ts';\nimport type { IncludeResolver } from './include-resolver.ts';\nimport { NestedSaver, type InstanceCheck } from './nested-saver.ts';\n\nexport type { InstanceCheck } from './nested-saver.ts';\n\nconst toArray = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : [value]);\n\n/**\n * Nested creation (`Model.create(values, { include })`, Sequelize v6): builds nested instances\n * from the values, saves belongsTo parents before the instance and hasOne / hasMany /\n * belongsToMany children (with their junction rows) after it.\n */\nexport class NestedCreator {\n readonly #resolver: IncludeResolver;\n readonly #isInstance: InstanceCheck;\n readonly #saver: NestedSaver;\n\n /**\n * @param resolver - Converts include nodes back to options for the nested builds.\n * @param isInstance - Checks whether a value is a model instance.\n */\n constructor(resolver: IncludeResolver, isInstance: InstanceCheck) {\n this.#resolver = resolver;\n this.#isInstance = isInstance;\n this.#saver = new NestedSaver(isInstance);\n }\n\n /**\n * Builds the nested instance(s) of an include from the given values; instances are kept.\n *\n * @param node - Include node.\n * @param value - Values (a list for multi associations), an instance, or `null`.\n * @returns Nested instance(s), or `null`.\n */\n build(node: IncludeNode, value: unknown): unknown {\n const build = (item: unknown): unknown => this.#buildOne(node, item);\n return value === null\n ? null\n : node.association.isMultiAssociation\n ? toArray(value).map(build)\n : build(value);\n }\n\n /**\n * Saves nested belongsTo parents and sets the foreign keys on the instance.\n *\n * @param instance - Instance being created.\n * @param includes - Include tree of the instance.\n * @param options - Save options (query options are passed on).\n * @returns Resolves when the parents are saved.\n */\n saveBelongsTo(\n instance: AnyModel,\n includes: readonly IncludeNode[],\n options: SaveOptions,\n ): Promise<void> {\n return this.#saver.saveBelongsTo(instance, includes, options);\n }\n\n /**\n * Saves nested hasOne / hasMany / belongsToMany children after the instance, one at a time.\n *\n * @param instance - Saved instance.\n * @param includes - Include tree of the instance.\n * @param options - Save options (query options are passed on).\n * @returns Resolves when the children are saved.\n */\n saveChildren(\n instance: AnyModel,\n includes: readonly IncludeNode[],\n options: SaveOptions,\n ): Promise<void> {\n return this.#saver.saveChildren(instance, includes, options);\n }\n\n #buildOne(node: IncludeNode, item: unknown): unknown {\n if (this.#isInstance(item)) {\n return item;\n }\n const child = new node.model(\n item as Values,\n node.children.length === 0\n ? {}\n : { include: node.children.map((nested) => this.#resolver.toOptions(nested)) },\n );\n this.#attachThrough(child, node, item);\n return child;\n }\n\n #attachThrough(child: AnyModel, node: IncludeNode, item: unknown): void {\n const through = node.association.through?.model;\n const throughName = node.through?.definition.name;\n if (\n through !== undefined &&\n throughName !== undefined &&\n typeof item === 'object' &&\n item !== null &&\n throughName in item\n ) {\n const throughValue = (item as Values)[throughName];\n (child.dataValues as Values)[throughName] = this.#isInstance(throughValue)\n ? throughValue\n : new through(throughValue as Values);\n }\n }\n}\n","import validatorJs from 'validator';\n\n/** Built-in validator: value as a string, then the validator arguments. */\nexport type ValidatorFunction = (value: string, ...args: readonly unknown[]) => boolean;\n\nconst regex = (value: string, pattern: unknown, modifiers?: unknown): boolean =>\n (pattern instanceof RegExp\n ? pattern\n : new RegExp(String(pattern), modifiers === undefined ? undefined : String(modifiers))\n ).test(value);\n\nconst contains = (value: string, element: unknown): boolean =>\n typeof element === 'string' && element !== '' && value.includes(element);\n\nconst builtin = validatorJs as unknown as Readonly<Record<string, ValidatorFunction>>;\n\n/** Sequelize v6 additions on top of validator.js (`utils/validator-extras`). */\nconst extensions: Readonly<Record<string, ValidatorFunction>> = {\n notEmpty: (value) => !/^[\\s\\t\\r\\n]*$/.test(value),\n len: (value, min, max) =>\n validatorJs.isLength(value, {\n min: Number(min ?? 0),\n ...(max === undefined ? {} : { max: Number(max) }),\n }),\n isUrl: (value) => validatorJs.isURL(value),\n isIPv6: (value) => validatorJs.isIP(value, 6),\n isIPv4: (value) => validatorJs.isIP(value, 4),\n notIn: (value, values) => !validatorJs.isIn(value, values as string[]),\n regex: (value, pattern, modifiers) => regex(value, pattern, modifiers),\n notRegex: (value, pattern, modifiers) => !regex(value, pattern, modifiers),\n is: (value, pattern, modifiers) => regex(value, pattern, modifiers),\n not: (value, pattern, modifiers) => !regex(value, pattern, modifiers),\n isDecimal: (value) =>\n value !== '' && /^(?:-?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][+-]?(?:[0-9]+))?$/.test(value),\n min: (value, limit) => {\n const number = Number.parseFloat(value);\n return Number.isNaN(number) || number >= Number(limit);\n },\n max: (value, limit) => {\n const number = Number.parseFloat(value);\n return Number.isNaN(number) || number <= Number(limit);\n },\n contains,\n notContains: (value, element) => !contains(value, element),\n isNull: (value) => validatorJs.isEmpty(value),\n isDate: (value) => !Number.isNaN(Date.parse(value)),\n};\n\n/**\n * Sequelize v6 built-in attribute validators: validator.js functions plus the v6 additions.\n *\n * @internal\n */\nexport class BuiltinValidators {\n /**\n * Finds a built-in validator by its Sequelize v6 name.\n *\n * @param name - Validator name, e.g. `'isEmail'` or `'len'`.\n * @returns The validator (called with the value as a string and the arguments), or `undefined`.\n */\n find(name: string): ValidatorFunction | undefined {\n return extensions[name] ?? (typeof builtin[name] === 'function' ? builtin[name] : undefined);\n }\n}\n","import { ValidationErrorItem } from '../errors/errors.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport { BuiltinValidators } from './builtin-validators.ts';\nimport type { ValidationTarget } from './validation-target.ts';\n\nconst builtinValidators = new BuiltinValidators();\n\n/** Runs one built-in (validator.js) validator option of an attribute. */\nexport class BuiltinAttributeValidator {\n /**\n * Validates a non-null attribute value.\n *\n * @param target - Instance being validated.\n * @param attribute - Attribute definition.\n * @param name - Validator name, e.g. `isEmail`.\n * @param test - Validator option: `false`, arguments, or `{ args, msg }`.\n * @param value - Current value of the attribute.\n * @returns The failure, or `undefined` when the value passed or the validator is disabled.\n * @remarks An unknown validator name fails with `Invalid validator function: <name>`, like v6.\n */\n run(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n name: string,\n test: unknown,\n value: unknown,\n ): ValidationErrorItem | undefined {\n if (test === false) {\n return undefined;\n }\n const field = attribute.fieldName;\n if (name !== 'isImmutable' && builtinValidators.find(name) === undefined) {\n return this.#unknown(target, field, name, value);\n }\n const normalized = BuiltinAttributeValidator.#normalize(name, test);\n const args = BuiltinAttributeValidator.#args(normalized, name, field, target);\n return BuiltinAttributeValidator.#passes(target, field, name, args, value)\n ? undefined\n : BuiltinAttributeValidator.#failure(target, field, name, normalized, args, value);\n }\n\n #unknown(\n target: ValidationTarget,\n field: string,\n name: string,\n value: unknown,\n ): ValidationErrorItem {\n return new ValidationErrorItem(\n `Invalid validator function: ${name}`,\n 'Validation error',\n field,\n value,\n target.instance,\n );\n }\n\n static #failure(\n target: ValidationTarget,\n field: string,\n name: string,\n test: unknown,\n args: readonly unknown[],\n value: unknown,\n ): ValidationErrorItem {\n return new ValidationErrorItem(\n BuiltinAttributeValidator.#message(test) ?? `Validation ${name} on ${field} failed`,\n 'Validation error',\n field,\n value,\n target.instance,\n name,\n name,\n args,\n );\n }\n\n static #passes(\n target: ValidationTarget,\n field: string,\n name: string,\n args: readonly unknown[],\n value: unknown,\n ): boolean {\n if (name === 'isImmutable') {\n return target.isNewRecord || target.values[field] === target.previous[field];\n }\n return builtinValidators.find(name)?.(String(value), ...args) ?? false;\n }\n\n static #normalize(name: string, test: unknown): unknown {\n if (!['isUrl', 'isURL', 'isEmail'].includes(name)) {\n return test;\n }\n const msg = BuiltinAttributeValidator.#message(test);\n return msg === undefined ? {} : { msg };\n }\n\n static #message(test: unknown): string | undefined {\n return typeof test === 'object' && test !== null && 'msg' in test\n ? String((test as { msg: unknown }).msg)\n : undefined;\n }\n\n static #args(\n test: unknown,\n name: string,\n field: string,\n target: ValidationTarget,\n ): readonly unknown[] {\n const raw =\n typeof test === 'object' && test !== null && 'args' in test\n ? (test as { args: unknown }).args\n : test;\n if (Array.isArray(raw)) {\n return raw;\n }\n if (name === 'isImmutable') {\n return [raw, field, target];\n }\n return BuiltinAttributeValidator.#takesNoArgs(raw, name) ? [] : [raw];\n }\n\n static #takesNoArgs(raw: unknown, name: string): boolean {\n return (\n (typeof raw !== 'string' && ['isAlpha', 'isAlphanumeric', 'isMobilePhone'].includes(name)) ||\n name === 'isIP'\n );\n }\n}\n","import { promisify } from 'node:util';\n\n/** Runs user-supplied validator functions (sync, async or callback style). */\nexport class CustomValidators {\n /**\n * Calls a validator with the instance as `this`.\n *\n * @param instance - Instance being validated.\n * @param fn - Validator function; with one parameter more than `args` it is callback style.\n * @param args - Arguments passed before the callback.\n * @returns The failure message, or `undefined` when the validator passed.\n */\n async failure(\n instance: object,\n fn: unknown,\n args: readonly unknown[],\n ): Promise<string | undefined> {\n try {\n await this.#call(instance, fn, args);\n return undefined;\n } catch (error) {\n return CustomValidators.#messageOf(error);\n }\n }\n\n async #call(instance: object, validator: unknown, args: readonly unknown[]): Promise<void> {\n const fn = validator as (...callArgs: unknown[]) => unknown;\n if (fn.length === args.length + 1) {\n await promisify(fn.bind(instance, ...args))();\n return;\n }\n await fn.apply(instance, [...args]);\n }\n\n static #messageOf(error: unknown): string {\n return error instanceof Error\n ? error.message\n : typeof error === 'string' && error !== ''\n ? error\n : 'Validation error';\n }\n}\n","import type { StandardSchemaPathSegment, StandardSchemaV1 } from './standard-schema.ts';\n\n/** Problem found by a Standard Schema, with a dotted path. */\nexport type StandardSchemaFailure = Readonly<{ message: string; path: string | undefined }>;\n\n/**\n * Validates values with [Standard Schema v1](https://standardschema.dev) schemas (zod, valibot,\n * arktype, ...).\n *\n * @internal\n */\nexport class StandardSchemaValidator {\n /**\n * Checks whether a value is a Standard Schema.\n *\n * @param value - Value to test.\n * @returns True when `value` has a `~standard.validate` function.\n */\n isSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === 'object' &&\n value !== null &&\n '~standard' in value &&\n typeof (value as StandardSchemaV1)['~standard'].validate === 'function'\n );\n }\n\n /**\n * Validates a value.\n *\n * @param schema - Schema to validate against.\n * @param value - Value to validate.\n * @returns Issues with dotted paths (empty when valid).\n */\n async issues(\n schema: StandardSchemaV1,\n value: unknown,\n ): Promise<readonly StandardSchemaFailure[]> {\n const result = await schema['~standard'].validate(value);\n return (result.issues ?? []).map((issue) => ({\n message: issue.message,\n path:\n issue.path === undefined || issue.path.length === 0\n ? undefined\n : issue.path.map((segment) => this.#segmentKey(segment)).join('.'),\n }));\n }\n\n #segmentKey(segment: PropertyKey | StandardSchemaPathSegment): string {\n return String(typeof segment === 'object' ? segment.key : segment);\n }\n}\n","import { ValidationErrorItem } from '../errors/errors.ts';\nimport type { StandardSchemaV1 } from './standard-schema.ts';\nimport { StandardSchemaValidator } from './standard-schema-validator.ts';\nimport type { ValidationTarget } from './validation-target.ts';\n\n/** Turns the issues of a Standard Schema into validation error items. */\nexport class SchemaItems {\n readonly #schemas = new StandardSchemaValidator();\n\n /**\n * @param test - Value to check.\n * @returns Whether `test` is a Standard Schema.\n */\n isSchema(test: unknown): test is StandardSchemaV1 {\n return this.#schemas.isSchema(test);\n }\n\n /**\n * Validates a value against a schema.\n *\n * @param target - Instance being validated.\n * @param schema - Standard Schema.\n * @param value - Value to validate.\n * @param path - Attribute the schema belongs to; `undefined` for a model schema.\n * @returns One item per schema issue.\n */\n async items(\n target: ValidationTarget,\n schema: StandardSchemaV1,\n value: unknown,\n path: string | undefined,\n ): Promise<readonly ValidationErrorItem[]> {\n return (await this.#schemas.issues(schema, value)).map(\n (issue) =>\n new ValidationErrorItem(\n issue.message,\n 'Validation error',\n SchemaItems.#issuePath(path, issue.path),\n value,\n target.instance,\n 'schema',\n ),\n );\n }\n\n static #issuePath(path: string | undefined, issuePath: string | undefined): string | null {\n if (path === undefined) {\n return issuePath ?? null;\n }\n return issuePath === undefined ? path : `${path}.${issuePath}`;\n }\n}\n","import { ValidationErrorItem } from '../errors/errors.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport { BuiltinAttributeValidator } from './builtin-attribute-validator.ts';\nimport { CustomValidators } from './custom-validators.ts';\nimport { SchemaItems } from './schema-items.ts';\nimport type { StandardSchemaV1 } from './standard-schema.ts';\nimport type { AttributeValidateOptions } from './types.ts';\nimport type { ValidationTarget } from './validation-target.ts';\n\nconst NO_ITEMS: Promise<readonly ValidationErrorItem[]> = Promise.resolve([]);\n\n/** Runs the `validate` options of one attribute: built-in, custom and Standard Schema validators. */\nexport class AttributeValidators {\n readonly #builtin = new BuiltinAttributeValidator();\n readonly #custom = new CustomValidators();\n readonly #schema = new SchemaItems();\n\n /**\n * Validates one attribute value (`notNull` is checked elsewhere).\n *\n * @param target - Instance being validated.\n * @param attribute - Attribute definition.\n * @param value - Current value of the attribute.\n * @returns Failures of all validators of the attribute.\n */\n items(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n value: unknown,\n ): Promise<readonly ValidationErrorItem[]> {\n if ((value === null || value === undefined) && attribute.allowNull === false) {\n return NO_ITEMS;\n }\n const tests = AttributeValidators.#tests(attribute);\n return tests.length === 0 ? NO_ITEMS : this.#run(target, attribute, tests, value);\n }\n\n /**\n * Whether the attribute has validators to run (everything in `validate` except `notNull`).\n *\n * @param attribute - Attribute definition.\n * @returns True when {@link AttributeValidators.items} can report failures.\n */\n hasValidators(attribute: AttributeDefinition): boolean {\n return AttributeValidators.#tests(attribute).length > 0;\n }\n\n static #tests(attribute: AttributeDefinition): readonly (readonly [string, unknown])[] {\n const validate = attribute.validate as AttributeValidateOptions | undefined;\n return validate === undefined\n ? []\n : Object.entries(validate).filter(([name]) => name !== 'notNull');\n }\n\n async #run(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n tests: readonly (readonly [string, unknown])[],\n value: unknown,\n ): Promise<readonly ValidationErrorItem[]> {\n const results = await Promise.all(\n tests.map(([name, test]) => this.#validatorItems(target, attribute, name, test, value)),\n );\n return results.flat();\n }\n\n async #validatorItems(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n name: string,\n test: unknown,\n value: unknown,\n ): Promise<readonly ValidationErrorItem[]> {\n if (name === 'schema' && this.#schema.isSchema(test)) {\n return this.#schemaItems(target, attribute.fieldName, test, value);\n }\n if (typeof test === 'function') {\n return this.#customItems(target, attribute, name, test, value);\n }\n return this.#builtinItems(target, attribute, name, test, value);\n }\n\n #schemaItems(\n target: ValidationTarget,\n path: string,\n schema: StandardSchemaV1,\n value: unknown,\n ): Promise<readonly ValidationErrorItem[]> {\n return value === undefined\n ? Promise.resolve([])\n : this.#schema.items(target, schema, value, path);\n }\n\n async #customItems(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n name: string,\n fn: unknown,\n value: unknown,\n ): Promise<readonly ValidationErrorItem[]> {\n const message = await this.#custom.failure(target.instance, fn, [value]);\n const { instance } = target;\n const { fieldName } = attribute;\n return message === undefined\n ? []\n : [new ValidationErrorItem(message, 'Validation error', fieldName, value, instance, name)];\n }\n\n #builtinItems(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n name: string,\n test: unknown,\n value: unknown,\n ): readonly ValidationErrorItem[] {\n if (value === null || value === undefined) {\n return [];\n }\n const item = this.#builtin.run(target, attribute, name, test, value);\n return item === undefined ? [] : [item];\n }\n}\n","import { ValidationErrorItem } from '../errors/errors.ts';\nimport { SqlExpression } from '../expressions/methods.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport type { AttributeValidateOptions } from './types.ts';\nimport type { ValidationTarget } from './validation-target.ts';\n\nconst STRING_TYPES: ReadonlySet<string> = new Set(['STRING', 'TEXT', 'CITEXT', 'CHAR']);\n\n/** Checks the checks Sequelize v6 always runs: `allowNull` and string attributes holding objects. */\nexport class CoreValidator {\n /**\n * Validates one attribute value.\n *\n * @param target - Instance being validated.\n * @param attribute - Attribute definition.\n * @param value - Current value of the attribute.\n * @returns Failures; empty for auto-generated attributes and valid values.\n */\n items(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n value: unknown,\n ): readonly ValidationErrorItem[] {\n if (attribute._autoGenerated === true || attribute.autoIncrement === true) {\n return [];\n }\n const item =\n this.#notNull(target, attribute, value) ?? this.#notString(target, attribute, value);\n return item === undefined ? [] : [item];\n }\n\n #notNull(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n value: unknown,\n ): ValidationErrorItem | undefined {\n if (attribute.allowNull !== false || (value !== null && value !== undefined)) {\n return undefined;\n }\n const message = CoreValidator.#notNullMessage(target, attribute);\n return new ValidationErrorItem(\n message,\n 'notNull Violation',\n attribute.fieldName,\n value,\n target.instance,\n 'is_null',\n );\n }\n\n static #notNullMessage(target: ValidationTarget, attribute: AttributeDefinition): string {\n const notNull = (attribute.validate as AttributeValidateOptions | undefined)?.notNull;\n return typeof notNull === 'object' && notNull.msg !== undefined\n ? notNull.msg\n : `${target.definition.name}.${attribute.fieldName} cannot be null`;\n }\n\n #notString(\n target: ValidationTarget,\n attribute: AttributeDefinition,\n value: unknown,\n ): ValidationErrorItem | undefined {\n if (!STRING_TYPES.has(attribute.type.key) || !CoreValidator.#isStructured(value)) {\n return undefined;\n }\n return new ValidationErrorItem(\n `${attribute.fieldName} cannot be an array or an object`,\n 'string violation',\n attribute.fieldName,\n value,\n target.instance,\n 'not_a_string',\n );\n }\n\n static #isStructured(value: unknown): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Buffer.isBuffer(value) &&\n !(value instanceof SqlExpression)\n );\n }\n}\n","import { ValidationErrorItem } from '../errors/errors.ts';\nimport { SqlExpression } from '../expressions/methods.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport { AttributeValidators } from './attribute-validators.ts';\nimport { CoreValidator } from './core-validator.ts';\nimport { CustomValidators } from './custom-validators.ts';\nimport type { StandardSchemaV1 } from './standard-schema.ts';\nimport { SchemaItems } from './schema-items.ts';\nimport type { ModelValidatorFunction } from './types.ts';\nimport type { ValidationScope, ValidationTarget } from './validation-target.ts';\n\nexport type { ValidationScope, ValidationTarget } from './validation-target.ts';\n\n/**\n * Validates instances like Sequelize v6 `InstanceValidator` (without hooks): `notNull`, string\n * values, built-in (validator.js) and custom attribute validators, Standard Schemas and model\n * validators. Expressions (`literal`, `fn`, ...) are not validated.\n *\n * @internal\n */\nexport class InstanceValidator {\n readonly #core = new CoreValidator();\n readonly #attributes = new AttributeValidators();\n readonly #schema = new SchemaItems();\n readonly #custom = new CustomValidators();\n\n /**\n * Validates an instance and returns all failures.\n *\n * @param target - Instance, its definition and values.\n * @param scope - Attributes and model validators to skip.\n * @param modelValidators - Model-level validators (`validate` model option).\n * @param modelSchema - Standard Schema of the whole model (`schema` model option).\n * @returns Failures; empty when the instance is valid.\n */\n async validate(\n target: ValidationTarget,\n scope: ValidationScope,\n modelValidators: Readonly<Record<string, ModelValidatorFunction>> = {},\n modelSchema?: StandardSchemaV1,\n ): Promise<readonly ValidationErrorItem[]> {\n const attributes = this.#checked(target, scope);\n const coreErrors = this.#coreItems(target, attributes);\n const [attributeErrors, modelErrors, schemaIssues] = await Promise.all([\n this.#attributeItems(target, attributes),\n this.#modelValidatorItems(target, modelValidators, scope),\n this.#modelSchemaItems(target, modelSchema),\n ]);\n return [...coreErrors, ...attributeErrors, ...modelErrors, ...schemaIssues];\n }\n\n #checked(target: ValidationTarget, scope: ValidationScope): readonly AttributeDefinition[] {\n return [...target.definition.attributes.values()].filter(\n (attribute) =>\n !scope.skip.has(attribute.fieldName) &&\n !(target.values[attribute.fieldName] instanceof SqlExpression),\n );\n }\n\n #coreItems(\n target: ValidationTarget,\n attributes: readonly AttributeDefinition[],\n ): readonly ValidationErrorItem[] {\n return attributes.flatMap((attribute) =>\n this.#core.items(target, attribute, target.values[attribute.fieldName]),\n );\n }\n\n async #attributeItems(\n target: ValidationTarget,\n attributes: readonly AttributeDefinition[],\n ): Promise<readonly ValidationErrorItem[]> {\n const results = await Promise.all(\n attributes\n .filter((attribute) => this.#attributes.hasValidators(attribute))\n .map((attribute) =>\n this.#attributes.items(target, attribute, target.values[attribute.fieldName]),\n ),\n );\n return results.flat();\n }\n\n #modelSchemaItems(\n target: ValidationTarget,\n schema: StandardSchemaV1 | undefined,\n ): Promise<readonly ValidationErrorItem[]> {\n return schema === undefined\n ? Promise.resolve([])\n : this.#schema.items(target, schema, this.#plainValues(target), undefined);\n }\n\n async #modelValidatorItems(\n target: ValidationTarget,\n validators: Readonly<Record<string, ModelValidatorFunction>>,\n scope: ValidationScope,\n ): Promise<readonly ValidationErrorItem[]> {\n const results = await Promise.all(\n Object.entries(validators)\n .filter(([name]) => !scope.skip.has(name))\n .map(([name, fn]) => this.#modelItems(target, name, fn)),\n );\n return results.flat();\n }\n\n async #modelItems(\n target: ValidationTarget,\n name: string,\n fn: ModelValidatorFunction,\n ): Promise<readonly ValidationErrorItem[]> {\n const message = await this.#custom.failure(target.instance, fn, []);\n return message === undefined\n ? []\n : [new ValidationErrorItem(message, 'Validation error', name, null, target.instance, name)];\n }\n\n #plainValues(target: ValidationTarget): Readonly<Record<string, unknown>> {\n return Object.fromEntries(\n [...target.definition.attributes.keys()].map((name) => [name, target.values[name]]),\n );\n }\n}\n","import { Subquery, WriteStatement } from '../expressions/methods.ts';\nimport type { CteNode, FromItem, QueryNode, SelectNode, WithClause } from '../sql/ast.ts';\nimport type { JoinSourceBuilder, JoinSources } from './join-source-builder.ts';\nimport { ModelDefinition } from './model-definition.ts';\n\n/**\n * Common table expression of the `with` option. PostgreSQL extension.\n *\n * @example\n * ```ts\n * const cte: CteDefinition = {\n * query: Task.subquery({ attributes: ['id'], where: { parentId: null } }),\n * unionAll: true,\n * materialized: false,\n * };\n * ```\n */\nexport type CteDefinition = Readonly<{\n /** Non-recursive part, or a data-modifying statement with `returning` (never with `recursive`). */\n query: Subquery | WriteStatement;\n /** Recursive part (makes the whole clause `WITH RECURSIVE`); reference the CTE through `from`. */\n recursive?: Subquery;\n /** `UNION ALL` (default) or `UNION` between `query` and `recursive`. */\n unionAll?: boolean;\n /** `MATERIALIZED` / `NOT MATERIALIZED` hint. */\n materialized?: boolean;\n /** `SEARCH … FIRST BY … SET …`: adds a column that orders the rows breadth or depth first. Needs `recursive`. */\n search?: CteSearchOptions;\n /** `CYCLE … SET … [USING …]`: marks rows that revisit a key, and stops the recursion there. Needs `recursive`. */\n cycle?: CteCycleOptions;\n}>;\n\n/**\n * `search` of a recursive CTE definition.\n *\n * @example\n * ```ts\n * const search: CteSearchOptions = { by: ['id'], mode: 'breadth', set: 'ordercol' };\n * ```\n */\nexport type CteSearchOptions = Readonly<{\n /** Columns of the CTE that define the order. */\n by: readonly string[];\n /** Traversal order.\n * @defaultValue 'depth' */\n mode?: 'breadth' | 'depth';\n /** Name of the added ordering column. */\n set: string;\n}>;\n\n/**\n * `cycle` of a recursive CTE definition.\n *\n * @example\n * ```ts\n * const cycle: CteCycleOptions = { columns: ['id'], set: 'is_cycle', using: 'path' };\n * ```\n */\nexport type CteCycleOptions = Readonly<{\n /** Columns that identify a visited row. */\n columns: readonly string[];\n /** Name of the added boolean column that is true on the row that closes a cycle. */\n set: string;\n /** Name of the added array column with the path of visited keys (required: PostgreSQL 16 and 17 need it). */\n using: string;\n}>;\n\n/** `with` option: CTEs by name. */\nexport type WithOption = Readonly<Record<string, Subquery | WriteStatement | CteDefinition>>;\n\n/**\n * CTE-related find options. PostgreSQL extension.\n *\n * Combined into {@link FindOptions} and {@link CountOptions}.\n *\n * @example\n * ```ts\n * const opts: CteFindOptions = {\n * with: { recent: { query: Post.subquery({ where: { published: true } }) } },\n * source: 'recent',\n * };\n * ```\n */\nexport type CteFindOptions = Readonly<{\n /** Common table expressions (`WITH [RECURSIVE] ...`). */\n with?: WithOption;\n /**\n * Read model rows from this relation instead of the model table: a CTE or table name, or a\n * subquery such as a set operation (`a.union(b)`), aliased with the model name. Columns are\n * named like the attributes.\n */\n source?: string | Subquery;\n /** Extra relations (`FROM \"Model\", \"alias\"`), keyed by alias; correlate them in `where`. */\n from?: JoinSources;\n}>;\n\nconst isDefinition = (value: Subquery | WriteStatement | CteDefinition): value is CteDefinition =>\n 'query' in value;\n\n/**\n * Resolves the CTE-related find options (PostgreSQL extension): the `WITH [RECURSIVE]` clause,\n * extra FROM relations, and the definition used when rows come from a `source` relation.\n */\nexport class CteBuilder {\n readonly #joins: JoinSourceBuilder;\n\n /**\n * @param joins - Converts `from` relations into FROM items.\n */\n constructor(joins: JoinSourceBuilder) {\n this.#joins = joins;\n }\n\n /**\n * Builds the `WITH` clause of the `with` option.\n *\n * @param option - CTEs by name.\n * @returns WITH clause, or `undefined` without CTEs.\n */\n withClause(option: WithOption | undefined): WithClause | undefined {\n const entries = Object.entries(option ?? {});\n if (entries.length === 0) {\n return undefined;\n }\n const ctes = entries.map(([name, value]) => CteBuilder.#cte(name, value));\n return {\n recursive: entries.some(([, value]) => isDefinition(value) && value.recursive !== undefined),\n ctes,\n };\n }\n\n /**\n * Definition used when rows come from `source`: same attributes, columns named like attributes.\n *\n * @param definition - Model definition.\n * @param source - `source` option.\n * @returns The definition itself without `source`.\n */\n sourceDefinition(\n definition: ModelDefinition,\n source: string | Subquery | undefined,\n ): ModelDefinition {\n return source === undefined\n ? definition\n : new ModelDefinition({\n ...definition,\n tableName: typeof source === 'string' ? source : definition.tableName,\n schema: undefined,\n attributes: new Map(\n [...definition.attributes].map(([name, attribute]) => [\n name,\n { ...attribute, field: name },\n ]),\n ),\n fieldToAttribute: new Map([...definition.attributes.keys()].map((name) => [name, name])),\n });\n }\n\n /**\n * Resolved CTE options for the select builder.\n *\n * @param options - Find options.\n * @returns `withClause` / `extraFrom` when present.\n */\n selectOptions(options: CteFindOptions): Readonly<{\n withClause?: WithClause;\n extraFrom?: readonly FromItem[];\n fromQuery?: QueryNode;\n }> {\n const withClause = this.withClause(options.with);\n const extraFrom = this.#joins.build(options.from);\n return {\n ...(withClause === undefined ? {} : { withClause }),\n ...(extraFrom.length === 0 ? {} : { extraFrom }),\n ...(options.source instanceof Subquery ? { fromQuery: options.source.build() } : {}),\n };\n }\n\n /**\n * Route of a statement: `'write'` when a CTE modifies data, so it never goes to a replica.\n *\n * @param select - Built SELECT.\n * @returns `'read'` or `'write'`.\n */\n route(select: SelectNode): 'read' | 'write' {\n const modifying = select.with?.ctes.some(\n (cte) => cte.query.kind !== 'select' && cte.query.kind !== 'setop',\n );\n return modifying === true ? 'write' : 'read';\n }\n\n static #cte(name: string, value: Subquery | WriteStatement | CteDefinition): CteNode {\n const cte: CteDefinition = isDefinition(value) ? value : { query: value };\n return {\n name,\n query: CteBuilder.#body(name, cte),\n ...(cte.materialized === undefined ? {} : { materialized: cte.materialized }),\n ...CteBuilder.#extras(name, cte),\n };\n }\n\n static #body(name: string, cte: CteDefinition): CteNode['query'] {\n const base = cte.query.build();\n if (cte.query instanceof WriteStatement) {\n if (cte.recursive !== undefined) {\n throw new Error(`CTE \"${name}\": a data-modifying statement cannot be recursive`);\n }\n return base;\n }\n return cte.recursive === undefined\n ? base\n : {\n kind: 'setop',\n op: 'UNION',\n left: base as QueryNode,\n right: cte.recursive.build(),\n all: cte.unionAll !== false,\n };\n }\n\n static #extras(name: string, cte: CteDefinition): Pick<CteNode, 'search' | 'cycle'> {\n if ((cte.search !== undefined || cte.cycle !== undefined) && cte.recursive === undefined) {\n throw new Error(`CTE \"${name}\": search and cycle need a recursive part`);\n }\n const mode = (cte.search?.mode ?? 'depth').toUpperCase();\n if (mode !== 'DEPTH' && mode !== 'BREADTH') {\n throw new Error(`Invalid CTE search mode: ${String(cte.search?.mode)}`);\n }\n return {\n ...(cte.search === undefined\n ? {}\n : { search: { mode, by: cte.search.by, set: cte.search.set } }),\n ...(cte.cycle === undefined ? {} : { cycle: cte.cycle }),\n };\n }\n}\n","import {\n SqlAst,\n type DeleteNode,\n type ExprNode,\n type FromItem,\n type TruncateNode,\n} from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\n\nconst ast = new SqlAst();\n\n/** Options of {@link DeleteQueryBuilder.build}. */\nexport type DeleteBuildOptions = Readonly<{\n /** Return all stored columns. */\n returning?: boolean;\n /** Lists at least this long compile to `= ANY($n)`. */\n inAsAnyThreshold?: number;\n /** Delete at most this many rows (`ctid IN (SELECT ... LIMIT n)`). */\n limit?: number;\n /** Extra relations (`DELETE ... USING`); the table is then aliased with the model name. */\n using?: readonly FromItem[];\n}>;\n\n/** Builds DELETE and TRUNCATE statements of a model table. */\nexport class DeleteQueryBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Builds a DELETE.\n *\n * @param definition - Model definition.\n * @param where - Condition.\n * @param options - RETURNING, `= ANY` threshold, LIMIT, USING relations.\n * @returns DELETE node.\n */\n build(definition: ModelDefinition, where: unknown, options: DeleteBuildOptions = {}): DeleteNode {\n const alias =\n options.using === undefined || options.using.length === 0 ? undefined : definition.name;\n const ctx = this.#columns.whereCompiler(definition, alias, options.inAsAnyThreshold);\n const limited = this.#limited(definition, this.#columns.where(where, ctx), options.limit);\n return {\n kind: 'delete',\n table: this.#columns.table(definition, alias),\n ...(alias === undefined ? {} : { using: options.using }),\n ...(limited === undefined ? {} : { where: limited }),\n ...(options.returning === true\n ? { returning: this.#columns.returningAll(definition, alias) }\n : {}),\n };\n }\n\n /**\n * Builds `TRUNCATE`.\n *\n * @param definition - Model definition.\n * @param options - `cascade`, `restartIdentity`.\n * @returns TRUNCATE node.\n */\n truncate(\n definition: ModelDefinition,\n options: Readonly<{ cascade?: boolean; restartIdentity?: boolean }>,\n ): TruncateNode {\n return {\n kind: 'truncate',\n table: {\n name: definition.tableName,\n ...(definition.schema === undefined ? {} : { schema: definition.schema }),\n },\n ...(options.cascade === true ? { cascade: true } : {}),\n ...(options.restartIdentity === true ? { restartIdentity: true } : {}),\n };\n }\n\n #limited(\n definition: ModelDefinition,\n condition: ExprNode | undefined,\n limit: number | undefined,\n ): ExprNode | undefined {\n return limit === undefined\n ? condition\n : ast.binary('IN', ast.raw('ctid'), {\n kind: 'subquery',\n query: {\n kind: 'select',\n columns: [ast.raw('ctid')],\n from: this.#columns.table(definition),\n ...(condition === undefined ? {} : { where: condition }),\n limit,\n },\n });\n }\n}\n","import {\n SqlAst,\n type ExprNode,\n type FunctionSource,\n type JoinNode,\n type SelectNode,\n} from '../sql/ast.ts';\nimport type { ModelDefinition } from './model-definition.ts';\n\nconst ast = new SqlAst();\n\n/** Parent keys of a top-N-per-parent read: child rows whose `attribute` equals one of `values`. */\nexport type LateralKeys = Readonly<{ attribute: string; values: readonly unknown[] }>;\n\n/**\n * Wraps the per-parent query in `FROM unnest(keys) JOIN LATERAL (query) ON TRUE`, so that `limit`\n * and `order` of the query apply to each key separately.\n */\nexport class LateralKeysBuilder {\n /**\n * Builds the outer SELECT.\n *\n * @param definition - Definition of the child model.\n * @param inner - Per-parent SELECT (with `limit` and `order`) without the key condition.\n * @param keys - Parent keys and the child attribute they match.\n * @param alias - Alias of the child rows.\n * @returns SELECT of every child row, grouped by key in key order.\n * @throws Error when the key attribute is not a stored attribute.\n */\n build(\n definition: ModelDefinition,\n inner: SelectNode,\n keys: LateralKeys,\n alias: string,\n ): SelectNode {\n const attribute = definition.attributes.get(keys.attribute);\n if (attribute === undefined) {\n throw new Error(`Unknown attribute for a lateral include: ${keys.attribute}`);\n }\n const where = LateralKeysBuilder.#where(inner, alias, attribute.field);\n return {\n kind: 'select',\n columns: [{ kind: 'star', table: alias }],\n from: LateralKeysBuilder.#keys(keys, attribute.type.sqlType),\n joins: [LateralKeysBuilder.#join({ ...inner, where }, alias)],\n orderBy: [{ expr: ast.ident('keys', 'position') }, ...(inner.orderBy ?? [])],\n };\n }\n\n static #join(inner: SelectNode, alias: string): JoinNode {\n return {\n type: 'INNER',\n table: { subquery: inner, alias, lateral: true },\n on: ast.raw('TRUE'),\n };\n }\n\n static #where(inner: SelectNode, alias: string, field: string): ExprNode {\n const correlated = ast.binary('=', ast.ident(alias, field), ast.ident('keys', 'key'));\n return inner.where === undefined ? correlated : ast.and([correlated, inner.where]);\n }\n\n static #keys(keys: LateralKeys, sqlType: string): FunctionSource {\n return {\n function: ['unnest'],\n args: [{ kind: 'cast', expr: ast.param(keys.values), type: `${sqlType}[]` }],\n alias: 'keys',\n columns: ['key', 'position'],\n ordinality: 'position',\n };\n }\n}\n","import type { IncludeNode } from '../associations/include.ts';\nimport type { IncludeQueryBuilder } from '../associations/include-query-builder.ts';\nimport type { SelectNode } from '../sql/ast.ts';\nimport { LateralKeysBuilder, type LateralKeys } from './lateral-keys-builder.ts';\nimport type { CteBuilder } from './cte-builder.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { FindOptions } from './options.ts';\nimport type { SelectOptions, SelectQueryBuilder } from './select-query-builder.ts';\n\n/**\n * Builds the SELECT of a finder from resolved find options: the `source` / `with` / `from` CTE\n * options and the joins of includes (whose ordering is applied by the include builder).\n */\nexport class FindQueryBuilder {\n readonly #selects: SelectQueryBuilder;\n readonly #cte: CteBuilder;\n readonly #includes: IncludeQueryBuilder;\n readonly #laterals = new LateralKeysBuilder();\n\n /**\n * @param selects - SELECT builder.\n * @param cte - CTE options.\n * @param includes - Include joins.\n */\n constructor(selects: SelectQueryBuilder, cte: CteBuilder, includes: IncludeQueryBuilder) {\n this.#selects = selects;\n this.#cte = cte;\n this.#includes = includes;\n }\n\n /**\n * Builds the SELECT of resolved find options (scope and paranoid filter already applied).\n *\n * @param definition - Model definition.\n * @param query - Find options.\n * @param includes - Normalized include tree.\n * @param inAsAnyThreshold - Lists at least this long compile to `= ANY($n)`.\n * @param alias - Table alias instead of the model name.\n * @returns SELECT node.\n */\n build(\n definition: ModelDefinition,\n query: FindOptions,\n includes: readonly IncludeNode[],\n inAsAnyThreshold: number | undefined,\n alias?: string,\n ): SelectNode {\n if (query.lateralKeys !== undefined) {\n return this.#lateral(definition, query, inAsAnyThreshold, alias);\n }\n const base = this.#base(definition, query, includes.length > 0, inAsAnyThreshold, alias);\n return includes.length === 0 ? base : this.#includes.build(definition, base, includes, query);\n }\n\n /**\n * Route of the built SELECT: the writer when a CTE modifies data.\n *\n * @param select - Built SELECT.\n * @returns `'read'` or `'write'`.\n */\n route(select: SelectNode): 'read' | 'write' {\n return this.#cte.route(select);\n }\n\n #base(\n definition: ModelDefinition,\n query: FindOptions,\n joined: boolean,\n inAsAnyThreshold: number | undefined,\n alias: string | undefined,\n ): SelectNode {\n return this.#selects.build(\n this.#cte.sourceDefinition(definition, query.source),\n {\n ...(joined ? { ...query, order: undefined } : query),\n ...this.#cte.selectOptions(query),\n } as SelectOptions,\n inAsAnyThreshold,\n undefined,\n alias,\n );\n }\n\n #lateral(\n definition: ModelDefinition,\n query: FindOptions,\n inAsAnyThreshold: number | undefined,\n alias: string | undefined,\n ): SelectNode {\n const name = alias ?? definition.name;\n const inner = this.#selects.build(\n definition,\n query as SelectOptions,\n inAsAnyThreshold,\n undefined,\n name,\n );\n return this.#laterals.build(definition, inner, query.lateralKeys as LateralKeys, name);\n }\n}\n","import {\n SqlAst,\n type ExprNode,\n type InsertNode,\n type OnConflictNode,\n type QueryNode,\n} from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { AttributeDefinition, ModelDefinition } from './model-definition.ts';\n\nconst ast = new SqlAst();\n\nconst isAutoIncrementEmpty = (\n attribute: AttributeDefinition | undefined,\n value: unknown,\n): boolean => attribute?.autoIncrement === true && (value === null || value === undefined);\n\n/** Options of {@link InsertQueryBuilder.build}. */\nexport type InsertBuildOptions = Readonly<{\n /** `true`: all stored columns; a list: these expressions. */\n returning?: boolean | readonly ExprNode[];\n /** `ON CONFLICT` clause. */\n onConflict?: OnConflictNode;\n /** `OVERRIDING { SYSTEM | USER } VALUE`. */\n overriding?: 'system' | 'user';\n}>;\n\n/** Builds INSERT statements: multi-row `VALUES` from attribute-keyed rows, or `INSERT ... SELECT`. */\nexport class InsertQueryBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Builds a multi-row INSERT from attribute-keyed rows. Columns no row provides are left out;\n * missing values and empty auto-increment keys are written as `DEFAULT`.\n *\n * @param definition - Model definition.\n * @param rows - Values by attribute name.\n * @param options - RETURNING, ON CONFLICT, OVERRIDING.\n * @returns INSERT node.\n */\n build(\n definition: ModelDefinition,\n rows: readonly Readonly<Record<string, unknown>>[],\n options: InsertBuildOptions = {},\n ): InsertNode {\n const attributes = this.#insertable(definition, rows);\n const returning = this.#returning(definition, options.returning);\n return {\n kind: 'insert',\n table: this.#columns.table(\n definition,\n options.onConflict === undefined ? undefined : definition.name,\n ),\n columns: attributes.map((name) => definition.attributes.get(name)?.field ?? name),\n rows: this.#rows(definition, rows, attributes),\n ...(options.onConflict === undefined ? {} : { onConflict: options.onConflict }),\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n ...(returning === undefined ? {} : { returning }),\n };\n }\n\n /**\n * Builds `INSERT INTO ... (columns) SELECT ...`.\n *\n * @param definition - Model definition.\n * @param columns - Target attribute names.\n * @param select - Source query.\n * @param onConflict - `ON CONFLICT` clause.\n * @param returning - RETURNING list.\n * @returns INSERT node.\n */\n fromSelect(\n definition: ModelDefinition,\n columns: readonly string[],\n select: QueryNode,\n onConflict: OnConflictNode | undefined,\n returning: readonly ExprNode[],\n ): InsertNode {\n return {\n kind: 'insert' as const,\n table: this.#columns.table(\n definition,\n onConflict === undefined ? undefined : definition.name,\n ),\n columns: columns.map((name) => definition.attributes.get(name)?.field ?? name),\n rows: [],\n select,\n ...(onConflict === undefined ? {} : { onConflict }),\n returning,\n };\n }\n\n #insertable(\n definition: ModelDefinition,\n rows: readonly Readonly<Record<string, unknown>>[],\n ): readonly string[] {\n return this.#columns\n .stored(definition)\n .filter((attribute) => attribute.generated === undefined)\n .map((attribute) => attribute.fieldName)\n .filter((name) => rows.some((row) => row[name] !== undefined))\n .filter(\n (name) =>\n !rows.every((row) => isAutoIncrementEmpty(definition.attributes.get(name), row[name])),\n );\n }\n\n #returning(\n definition: ModelDefinition,\n returning: InsertBuildOptions['returning'],\n ): readonly ExprNode[] | undefined {\n return returning === true\n ? this.#columns.returningAll(definition)\n : returning === false\n ? undefined\n : returning;\n }\n\n #rows(\n definition: ModelDefinition,\n rows: readonly Readonly<Record<string, unknown>>[],\n attributes: readonly string[],\n ): readonly (readonly ExprNode[])[] {\n const ctx = this.#columns.whereCompiler(definition, undefined);\n return rows.map((row) =>\n attributes.map((name) => {\n const attribute = definition.attributes.get(name);\n const value = row[name];\n return value === undefined || isAutoIncrementEmpty(attribute, value)\n ? ast.raw('DEFAULT')\n : this.#columns.value(attribute, value, ctx);\n }),\n );\n }\n}\n","import type { InstanceLifecycleServices } from './instance-lifecycle-services.ts';\nimport type { InstanceLifecycle } from './instance-lifecycle.ts';\nimport type { ModelState } from './model-registry.ts';\nimport type { AnyModel, InstanceDestroyOptions, MutableOptions, Values } from './options.ts';\nimport type { QueryOptionsBase } from './runtime.ts';\n\n/**\n * Instance `destroy` (DELETE, or soft delete of paranoid models), `restore` and `isSoftDeleted`.\n *\n * @internal\n */\nexport class InstanceDestroyer {\n readonly #services: InstanceLifecycleServices;\n readonly #lifecycle: InstanceLifecycle;\n\n /**\n * @param services - Collaborators.\n * @param lifecycle - Hook runner.\n */\n constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {\n this.#services = services;\n this.#lifecycle = lifecycle;\n }\n\n /**\n * Deletes the row of an instance (sets `deletedAt` for paranoid models unless `force`).\n *\n * @param instance - Instance.\n * @param options - Destroy options.\n * @returns Resolves when deleted.\n */\n async destroy(instance: AnyModel, options: InstanceDestroyOptions): Promise<void> {\n const model = instance.constructor;\n const state = this.#services.registry.state(model);\n const opts: MutableOptions = { hooks: true, force: false, ...options };\n if (opts['hooks'] === true) {\n await this.#lifecycle.runHooks(model, 'beforeDestroy', instance, opts);\n }\n const { deletedAt } = state.definition;\n await (deletedAt !== undefined && opts['force'] !== true\n ? this.#softDelete(instance, deletedAt, options)\n : this.#deleteRow(instance, state, options));\n if (opts['hooks'] === true) {\n await this.#lifecycle.runHooks(model, 'afterDestroy', instance, opts);\n }\n }\n\n /**\n * Restores a soft-deleted instance of a paranoid model.\n *\n * @param instance - Instance.\n * @param options - Query options; `hooks: false` skips restore hooks.\n * @returns Resolves when restored.\n * @throws Error when the model is not paranoid.\n */\n async restore(\n instance: AnyModel,\n options: QueryOptionsBase & Readonly<{ hooks?: boolean }>,\n ): Promise<void> {\n const model = instance.constructor;\n const deletedAt = this.#deletedAt(model);\n const hooks = options.hooks !== false;\n if (hooks) {\n await this.#lifecycle.runHooks(model, 'beforeRestore', instance, options);\n }\n instance.setDataValue(deletedAt, null);\n await instance.save({ ...this.#services.values.queryOptions(options), hooks: false });\n if (hooks) {\n await this.#lifecycle.runHooks(model, 'afterRestore', instance, options);\n }\n }\n\n /**\n * Whether an instance of a paranoid model is soft-deleted.\n *\n * @param instance - Instance.\n * @returns True when `deletedAt` is set.\n * @throws Error when the model is not paranoid.\n */\n isSoftDeleted(instance: AnyModel): boolean {\n const value = (instance.dataValues as Values)[this.#deletedAt(instance.constructor)];\n return value !== null && value !== undefined;\n }\n\n #deletedAt(model: object): string {\n const { definition } = this.#services.registry.state(model);\n if (definition.deletedAt === undefined) {\n throw new Error('Model is not paranoid');\n }\n return definition.deletedAt;\n }\n\n async #softDelete(\n instance: AnyModel,\n deletedAt: string,\n options: InstanceDestroyOptions,\n ): Promise<void> {\n instance.setDataValue(deletedAt, new Date());\n await instance.save({ ...this.#services.values.queryOptions(options), hooks: false });\n }\n\n async #deleteRow(\n instance: AnyModel,\n { definition, runtime }: ModelState,\n options: InstanceDestroyOptions,\n ): Promise<void> {\n const { compiler, deletes, columns } = this.#services;\n await runtime.execute(\n compiler.compile(\n deletes.build(\n definition,\n columns.primaryKeyWhere(definition, instance.dataValues as Values),\n ),\n ),\n options,\n );\n }\n}\n","import type { QueryResult } from '../connection/connection-manager.ts';\nimport { OptimisticLockError } from '../errors/errors.ts';\nimport type { InstanceLifecycleServices } from './instance-lifecycle-services.ts';\nimport type { InstanceLifecycle } from './instance-lifecycle.ts';\nimport type { InstanceState } from './instance-state.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { AnyModel, MutableOptions, SaveOptions, Values } from './options.ts';\nimport type { ModelRuntime } from './runtime.ts';\n\n/** @internal State of one `save` call. */\nexport type SaveContext = Readonly<{\n /** Model class. */\n model: object;\n /** Model definition. */\n definition: ModelDefinition;\n /** Runtime of the model. */\n runtime: ModelRuntime;\n /** Instance state. */\n state: InstanceState;\n /** Options passed to hooks (which may change them). */\n opts: MutableOptions;\n /** Options as given. */\n options: SaveOptions;\n /** Whether the instance is inserted. */\n isNew: boolean;\n /** `fields` option. */\n explicitFields: readonly string[] | undefined;\n}>;\n\n/**\n * SQL step of `instance.save()`: INSERT of a new instance (with nested associations) or UPDATE of\n * changed attributes with optimistic locking, then the returned row is applied to the instance.\n *\n * @internal\n */\nexport class InstanceWriter {\n readonly #services: InstanceLifecycleServices;\n readonly #lifecycle: InstanceLifecycle;\n\n /**\n * @param services - Collaborators.\n * @param lifecycle - Row refresh.\n */\n constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {\n this.#services = services;\n this.#lifecycle = lifecycle;\n }\n\n /**\n * Inserts a new instance, saving `belongsTo` parents before and children after it.\n *\n * @param instance - Instance.\n * @param context - Save state.\n * @param now - Timestamp of the write.\n * @returns Resolves when written.\n */\n async insert(instance: AnyModel, context: SaveContext, now: Date): Promise<void> {\n const { nested } = this.#services;\n await nested.saveBelongsTo(instance, context.state.includes, context.options);\n const result = await this.#insertRow(context, this.#insertValues(instance, context, now));\n this.#lifecycle.refresh(instance, context.definition, result.rows[0]);\n await nested.saveChildren(instance, context.state.includes, context.options);\n }\n\n /**\n * Updates the given attributes of a loaded instance (and its version).\n *\n * @param instance - Instance.\n * @param context - Save state.\n * @param fields - Attributes to write.\n * @param now - Timestamp of the write.\n * @returns Resolves when written.\n * @throws OptimisticLockError when the version no longer matches.\n */\n async update(\n instance: AnyModel,\n context: SaveContext,\n fields: readonly string[],\n now: Date,\n ): Promise<void> {\n const { definition } = context;\n const changes = this.#changes(instance, context, fields, now);\n const previous = instance._previousDataValues as Values;\n const where = this.#updateWhere(definition, previous);\n const set = this.#updateSet(definition, previous, changes);\n const result = await this.#updateRow(context, set, where);\n if (definition.version !== undefined && result.rowCount === 0) {\n throw new OptimisticLockError({ modelName: definition.name, values: set, where });\n }\n this.#lifecycle.refresh(instance, definition, result.rows[0]);\n }\n\n #updateRow(\n { definition, options, runtime }: SaveContext,\n set: Values,\n where: Values,\n ): Promise<QueryResult> {\n const { compiler, updates, columns } = this.#services;\n return runtime.execute(\n compiler.compile(\n updates.build(definition, columns.setItems(definition, set), where, { returning: true }),\n ),\n options,\n );\n }\n\n #insertValues(instance: AnyModel, context: SaveContext, now: Date): Values {\n const rules = this.#services.values;\n const silent = context.opts['silent'] === true;\n return rules.pick(\n rules.withTimestamps(context.definition, instance.dataValues as Values, now, true, silent),\n context.explicitFields,\n );\n }\n\n #insertRow({ definition, options, runtime }: SaveContext, values: Values): Promise<QueryResult> {\n const { compiler, inserts } = this.#services;\n return runtime.execute(\n compiler.compile(\n inserts.build(definition, [values], {\n returning: true,\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n }),\n ),\n options,\n );\n }\n\n #changes(instance: AnyModel, context: SaveContext, fields: readonly string[], now: Date): Values {\n const { version } = context.definition;\n const current = instance.dataValues as Values;\n return this.#services.values.withTimestamps(\n context.definition,\n Object.fromEntries(\n fields.filter((name) => name !== version).map((name) => [name, current[name]]),\n ),\n now,\n false,\n context.opts['silent'] === true,\n );\n }\n\n #updateWhere(definition: ModelDefinition, previous: Values): Values {\n const { version } = definition;\n return {\n ...this.#services.columns.primaryKeyWhere(definition, previous),\n ...(version === undefined ? {} : { [version]: previous[version] }),\n };\n }\n\n #updateSet(definition: ModelDefinition, previous: Values, changes: Values): Values {\n const { version } = definition;\n return version === undefined\n ? changes\n : { ...changes, [version]: Number(previous[version] ?? 0) + 1 };\n }\n}\n","import type { HookType } from '../hooks/hooks.ts';\nimport type { InstanceLifecycleServices } from './instance-lifecycle-services.ts';\nimport type { InstanceLifecycle } from './instance-lifecycle.ts';\nimport { InstanceState } from './instance-state.ts';\nimport { InstanceWriter, type SaveContext } from './instance-writer.ts';\nimport type { AnyModel, SaveOptions } from './options.ts';\n\n/**\n * `instance.save()`: validation, `beforeCreate` / `beforeUpdate` hooks (with re-validation of\n * attributes the hooks changed), the INSERT or UPDATE, then the `after` hooks.\n *\n * @internal\n */\nexport class InstanceSaver {\n readonly #services: InstanceLifecycleServices;\n readonly #lifecycle: InstanceLifecycle;\n readonly #writer: InstanceWriter;\n\n /**\n * @param services - Collaborators.\n * @param lifecycle - Hook runner and row refresh.\n */\n constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {\n this.#services = services;\n this.#lifecycle = lifecycle;\n this.#writer = new InstanceWriter(services, lifecycle);\n }\n\n /**\n * Inserts the instance if new, otherwise updates its changed attributes.\n *\n * @param instance - Instance.\n * @param options - Save options.\n * @returns The instance with values returned by the database.\n */\n async save<I extends AnyModel>(instance: I, options: SaveOptions): Promise<I> {\n const context = this.#context(instance, options);\n const fields =\n context.explicitFields ??\n (context.isNew ? this.#attributes(context) : this.#changed(context));\n if (!context.isNew && fields.length === 0) {\n return instance;\n }\n const hookFields = await this.#prepare(instance, context, fields);\n const now = new Date();\n await (context.isNew\n ? this.#writer.insert(instance, context, now)\n : this.#writer.update(instance, context, hookFields, now));\n if (context.opts['hooks'] === true) {\n await this.#hook(instance, context, 'afterCreate', 'afterUpdate');\n }\n return instance;\n }\n\n #context(instance: AnyModel, options: SaveOptions): SaveContext {\n const model = instance.constructor;\n const { definition, runtime } = this.#services.registry.state(model);\n return {\n model,\n definition,\n runtime,\n state: InstanceState.of(instance),\n opts: { hooks: true, validate: true, ...options },\n options,\n isNew: instance.isNewRecord,\n explicitFields: this.#services.values.saveFields(\n definition,\n options.fields as readonly string[] | undefined,\n instance.isNewRecord,\n ),\n };\n }\n\n #attributes(context: SaveContext): readonly string[] {\n return [...context.definition.attributes.keys()];\n }\n\n #changed({ state, definition }: SaveContext): readonly string[] {\n return [...state.changed].filter((name) => definition.attributes.has(name));\n }\n\n #hook(\n instance: AnyModel,\n context: SaveContext,\n create: HookType,\n update: HookType,\n ): Promise<void> {\n const type = context.isNew ? create : update;\n return this.#lifecycle.runHooks(context.model, type, instance, context.opts);\n }\n\n async #prepare(\n instance: AnyModel,\n context: SaveContext,\n fields: readonly string[],\n ): Promise<readonly string[]> {\n const { opts } = context;\n if (opts['validate'] === true) {\n await instance.validate({ hooks: opts['hooks'] === true, fields });\n }\n if (opts['hooks'] !== true) {\n return fields;\n }\n const before = this.#changed(context);\n await this.#hook(instance, context, 'beforeCreate', 'beforeUpdate');\n if (context.explicitFields !== undefined || context.isNew) {\n return fields;\n }\n return this.#addChanged(instance, context, fields, before);\n }\n\n /** Adds attributes changed by `beforeUpdate` hooks to the saved fields, validating them. */\n async #addChanged(\n instance: AnyModel,\n context: SaveContext,\n fields: readonly string[],\n before: readonly string[],\n ): Promise<readonly string[]> {\n const added = this.#changed(context).filter((name) => !before.includes(name));\n if (context.opts['validate'] === true) {\n await instance.validate({\n hooks: context.opts['hooks'] === true,\n skip: this.#attributes(context).filter((name) => !added.includes(name)),\n });\n }\n return [...fields, ...added];\n }\n}\n","import { AggregateError, BulkRecordError, ValidationError } from '../errors/errors.ts';\nimport type { ValidationErrorItem } from '../errors/errors.ts';\nimport type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';\nimport type { InstanceLifecycle } from './instance-lifecycle.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { ModelState } from './model-registry.ts';\nimport type { AnyModel } from './options.ts';\n\n/**\n * Instance validation with `beforeValidate` / `afterValidate` / `validationFailed` hooks, and the\n * validation of bulk writes.\n *\n * @internal\n */\nexport class InstanceValidation {\n readonly #services: InstanceLifecycleServices;\n readonly #lifecycle: InstanceLifecycle;\n\n /**\n * @param services - Collaborators.\n * @param lifecycle - Hook runner.\n */\n constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {\n this.#services = services;\n this.#lifecycle = lifecycle;\n }\n\n /**\n * Validates an instance like Sequelize v6 `instance.validate()`.\n *\n * @param instance - Instance.\n * @param options - `hooks`, `skip`, `fields`.\n * @returns Resolves when valid.\n * @throws ValidationError with all failures.\n */\n async validate(instance: AnyModel, options: ValidateOptions): Promise<void> {\n const model = instance.constructor;\n const state = this.#services.registry.state(model);\n const hooks = options.hooks !== false;\n const skip = this.#skipped(state.definition, options);\n if (hooks) {\n await this.#lifecycle.runHooks(model, 'beforeValidate', instance, options);\n }\n const items = await this.#failures(instance, state, skip);\n if (items.length > 0) {\n const error = new ValidationError(null, items);\n if (hooks) {\n await this.#lifecycle.runHooks(model, 'validationFailed', instance, options, error);\n }\n throw error;\n }\n if (hooks) {\n await this.#lifecycle.runHooks(model, 'afterValidate', instance, options);\n }\n }\n\n /**\n * Validates instances of a bulk write; failures are collected into one error.\n *\n * @param instances - Instances.\n * @param hooks - Run validation hooks.\n * @returns Resolves when all are valid.\n * @throws AggregateError of BulkRecordError.\n */\n async validateAll(instances: readonly AnyModel[], hooks: boolean): Promise<void> {\n const failures = await Promise.all(\n instances.map((instance) =>\n instance.validate({ hooks }).then(\n () => undefined,\n (error: unknown) =>\n new BulkRecordError(\n error instanceof Error ? error : new Error(String(error)),\n instance,\n ),\n ),\n ),\n );\n const errors = failures.filter((failure): failure is BulkRecordError => failure !== undefined);\n if (errors.length > 0) {\n throw new AggregateError(errors);\n }\n }\n\n #skipped(definition: ModelDefinition, options: ValidateOptions): ReadonlySet<string> {\n const attributes = [...definition.attributes.keys()];\n return new Set(\n options.skip ??\n (options.fields === undefined\n ? []\n : attributes.filter((name) => !options.fields?.includes(name))),\n );\n }\n\n #failures(\n instance: AnyModel,\n state: ModelState,\n skip: ReadonlySet<string>,\n ): Promise<readonly ValidationErrorItem[]> {\n return this.#services.validator.validate(\n {\n instance,\n definition: state.definition,\n values: instance.dataValues as Readonly<Record<string, unknown>>,\n previous: instance._previousDataValues as Readonly<Record<string, unknown>>,\n isNewRecord: instance.isNewRecord,\n },\n { skip },\n state.validators,\n state.schema,\n );\n }\n}\n","import type { IncludeNode } from '../associations/include.ts';\nimport { InstanceError } from '../errors/errors.ts';\nimport { HookRegistry, type HookType } from '../hooks/hooks.ts';\nimport { InstanceDestroyer } from './instance-destroyer.ts';\nimport type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';\nimport { InstanceSaver } from './instance-saver.ts';\nimport { InstanceState } from './instance-state.ts';\nimport { InstanceValidation } from './instance-validation.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type {\n AnyModel,\n AttributeAmounts,\n BuildOptions,\n IncrementOptions,\n InstanceDestroyOptions,\n ModelStatic,\n SaveOptions,\n Values,\n} from './options.ts';\nimport type { QueryOptionsBase } from './runtime.ts';\nimport type { WhereOptions } from './types.ts';\n\nexport type { InstanceLifecycleServices, ValidateOptions } from './instance-lifecycle-services.ts';\n\n/**\n * Lifecycle of model instances: construction from values (with nested includes), validation with\n * hooks, `save` (INSERT or UPDATE of changed attributes with optimistic locking), `reload`,\n * `destroy` / `restore` (soft delete for paranoid models), instance `increment` / `decrement`,\n * and the model hook runner used by every operation.\n */\nexport class InstanceLifecycle {\n readonly #services: InstanceLifecycleServices;\n readonly #validation: InstanceValidation;\n readonly #saver: InstanceSaver;\n readonly #destroyer: InstanceDestroyer;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: InstanceLifecycleServices) {\n this.#services = services;\n this.#validation = new InstanceValidation(services, this);\n this.#saver = new InstanceSaver(services, this);\n this.#destroyer = new InstanceDestroyer(services, this);\n }\n\n /**\n * Runs model hooks, then Sequelize-level hooks, with the model class as `this`.\n *\n * @param model - Model class.\n * @param type - Hook type.\n * @param args - Hook arguments.\n * @returns Resolves when all hooks finished.\n */\n runHooks(model: object, type: HookType, ...args: readonly unknown[]): Promise<void> {\n const { hooks, runtime } = this.#services.registry.state(model);\n return HookRegistry.runAll([hooks, runtime.hooks()], type, model, ...args);\n }\n\n /**\n * Runs a hook for each instance, one after another (individual hooks of bulk operations).\n *\n * @param model - Model class.\n * @param type - Hook type.\n * @param instances - Instances, passed as the first hook argument.\n * @param args - Further hook arguments.\n * @returns Resolves when all hooks finished.\n */\n async runEach(\n model: object,\n type: HookType,\n instances: readonly object[],\n ...args: readonly unknown[]\n ): Promise<void> {\n for (const instance of instances) {\n // oxlint-disable-next-line no-await-in-loop -- hooks of one bulk call run in order, as in v6.\n await this.runHooks(model, type, instance, ...args);\n }\n }\n\n /**\n * Initializes a new instance (`new Model(values, options)`): defaults for new records, values\n * (raw or through setters), nested include instances and change tracking.\n *\n * @param instance - Instance being constructed.\n * @param values - Attribute values (and nested include values).\n * @param options - Build options.\n */\n initialize(instance: AnyModel, values: Values, options: BuildOptions): void {\n const model = instance.constructor as ModelStatic<AnyModel>;\n const { definition } = this.#services.registry.state(model);\n const state = InstanceState.of(instance);\n instance.isNewRecord = options.isNewRecord ?? true;\n instance.dataValues = instance.isNewRecord ? this.#services.values.initial(definition) : {};\n instance._previousDataValues = {};\n state.includes = this.#assign(instance, model, values, options);\n if (!instance.isNewRecord || options.raw === true) {\n instance._previousDataValues = { ...instance.dataValues };\n state.reset();\n }\n }\n\n /**\n * Validates an instance like Sequelize v6 `instance.validate()`.\n *\n * @param instance - Instance.\n * @param options - `hooks`, `skip`, `fields`.\n * @returns Resolves when valid.\n * @throws ValidationError with all failures.\n */\n validate(instance: AnyModel, options: ValidateOptions = {}): Promise<void> {\n return this.#validation.validate(instance, options);\n }\n\n /**\n * Validates instances of a bulk write; failures are collected into one error.\n *\n * @param instances - Instances.\n * @param hooks - Run validation hooks.\n * @returns Resolves when all are valid.\n * @throws AggregateError of BulkRecordError.\n */\n validateAll(instances: readonly AnyModel[], hooks: boolean): Promise<void> {\n return this.#validation.validateAll(instances, hooks);\n }\n\n /**\n * Inserts the instance if new, otherwise updates its changed attributes.\n *\n * @param instance - Instance.\n * @param options - Save options.\n * @returns The instance with values returned by the database.\n */\n save<I extends AnyModel>(instance: I, options: SaveOptions): Promise<I> {\n return this.#saver.save(instance, options);\n }\n\n /**\n * Reloads values from the database.\n *\n * @param instance - Instance.\n * @param options - Query options.\n * @returns The instance.\n * @throws InstanceError when the row no longer exists.\n */\n async reload<I extends AnyModel>(instance: I, options: QueryOptionsBase): Promise<I> {\n const { registry, compiler, selects, columns } = this.#services;\n const { definition, runtime } = registry.state(instance.constructor);\n const where = columns.primaryKeyWhere(definition, instance.dataValues as Values);\n const result = await runtime.execute(\n compiler.compile(selects.build(definition, { where, limit: 1 })),\n options,\n );\n if (result.rows[0] === undefined) {\n throw new InstanceError(\n 'Instance could not be reloaded because it does not exist anymore (find call returned null)',\n );\n }\n return this.refresh(instance, definition, result.rows[0]);\n }\n\n /**\n * Deletes the row of an instance (sets `deletedAt` for paranoid models unless `force`).\n *\n * @param instance - Instance.\n * @param options - Destroy options.\n * @returns Resolves when deleted.\n */\n destroy(instance: AnyModel, options: InstanceDestroyOptions): Promise<void> {\n return this.#destroyer.destroy(instance, options);\n }\n\n /**\n * Restores a soft-deleted instance of a paranoid model.\n *\n * @param instance - Instance.\n * @param options - Query options; `hooks: false` skips restore hooks.\n * @returns Resolves when restored.\n * @throws Error when the model is not paranoid.\n */\n restore(\n instance: AnyModel,\n options: QueryOptionsBase & Readonly<{ hooks?: boolean }>,\n ): Promise<void> {\n return this.#destroyer.restore(instance, options);\n }\n\n /**\n * Whether an instance of a paranoid model is soft-deleted.\n *\n * @param instance - Instance.\n * @returns True when `deletedAt` is set.\n * @throws Error when the model is not paranoid.\n */\n isSoftDeleted(instance: AnyModel): boolean {\n return this.#destroyer.isSoftDeleted(instance);\n }\n\n /**\n * Increments / decrements attributes of the instance's row through the model static.\n *\n * @param instance - Instance.\n * @param method - `'increment'` or `'decrement'`.\n * @param fields - Attribute name(s) or map of amounts.\n * @param options - Options.\n * @returns Result of the model static.\n */\n changeBy(\n instance: AnyModel,\n method: 'increment' | 'decrement',\n fields: AttributeAmounts<Values>,\n options: Omit<IncrementOptions, 'where'>,\n ): Promise<unknown> {\n const model = instance.constructor as ModelStatic<AnyModel>;\n const { definition } = this.#services.registry.state(model);\n const where = this.#services.columns.primaryKeyWhere(definition, instance.dataValues as Values);\n return model[method](fields, {\n ...(options as IncrementOptions),\n where: where as WhereOptions,\n });\n }\n\n /**\n * Applies a returned row to an instance and marks it as persisted and unchanged.\n *\n * @param instance - Instance.\n * @param definition - Model definition.\n * @param row - Returned row (`undefined` keeps the values).\n * @returns The instance.\n */\n refresh<I extends AnyModel>(\n instance: I,\n definition: ModelDefinition,\n row: Readonly<Record<string, unknown>> | undefined,\n ): I {\n if (row !== undefined) {\n instance.set(this.#services.rows.parse(definition, row), { raw: true });\n }\n instance.isNewRecord = false;\n instance._previousDataValues = { ...instance.dataValues };\n InstanceState.of(instance).reset();\n return instance;\n }\n\n #assign(\n instance: AnyModel,\n model: ModelStatic<AnyModel>,\n values: Values,\n options: BuildOptions,\n ): readonly IncludeNode[] {\n if (options.include === undefined) {\n instance.set(values, options.raw === true ? { raw: true } : {});\n return [];\n }\n const includes = this.#services.includes.normalize(model, options.include);\n const nested = new Set(includes.map((node) => node.as));\n const own = Object.fromEntries(Object.entries(values).filter(([key]) => !nested.has(key)));\n instance.set(own, options.raw === true ? { raw: true } : {});\n this.#buildNested(instance, includes, values);\n return includes;\n }\n\n #buildNested(instance: AnyModel, includes: readonly IncludeNode[], values: Values): void {\n includes.forEach((node) => {\n const value = values[node.as];\n if (value !== undefined) {\n (instance.dataValues as Values)[node.as] = this.#services.nested.build(node, value);\n }\n });\n }\n}\n","import type { SyncOptions } from '../query-interface/schema-synchronizer.ts';\nimport type { InstanceLifecycle } from './instance-lifecycle.ts';\n\n/** Runs the `beforeSync` / `afterSync` hooks of a model around its table sync. */\nexport class SyncHooks {\n readonly #lifecycle: InstanceLifecycle;\n\n /**\n * @param lifecycle - Hook runner (model hooks, then Sequelize-level hooks).\n */\n constructor(lifecycle: InstanceLifecycle) {\n this.#lifecycle = lifecycle;\n }\n\n /**\n * Runs `run` between the model's sync hooks unless `options.hooks` is `false`.\n *\n * @param model - Model class.\n * @param options - Sync options passed to the hooks.\n * @param run - The table sync.\n */\n async around(model: object, options: SyncOptions, run: () => Promise<void>): Promise<void> {\n if (options.hooks === false) {\n await run();\n return;\n }\n const hookOptions = { ...options, hooks: true };\n await this.#lifecycle.runHooks(model, 'beforeSync', hookOptions);\n await run();\n await this.#lifecycle.runHooks(model, 'afterSync', hookOptions);\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { InstanceState } from './instance-state.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport type { ModelValues } from './model-values.ts';\nimport type { AnyModel, Values } from './options.ts';\n\n/** Tells model instances apart from plain values (injected to avoid importing `Model`). */\nexport type InstanceCheck = (value: unknown) => value is AnyModel;\n\n/** Options of `instance.get()`. */\nexport type GetOptions = Readonly<{ plain?: boolean; raw?: boolean; clone?: boolean }>;\n\n/** Options of `instance.set()`. */\nexport type SetOptions = Readonly<{ raw?: boolean }>;\n\n/**\n * Attribute access of model instances (Sequelize v6 `get` / `set` / `setDataValue` / `changed` /\n * `previous` / `equals`): custom getters and setters, plain conversion of nested instances and\n * change tracking.\n */\nexport class InstanceValues {\n readonly #registry: ModelRegistry;\n readonly #values: ModelValues;\n readonly #isInstance: InstanceCheck;\n\n /**\n * @param registry - Model definitions.\n * @param values - Value equality.\n * @param isInstance - Checks whether a value is a model instance.\n */\n constructor(registry: ModelRegistry, values: ModelValues, isInstance: InstanceCheck) {\n this.#registry = registry;\n this.#values = values;\n this.#isInstance = isInstance;\n }\n\n /**\n * One attribute value (custom getter applied unless `raw`), or all values.\n *\n * @param instance - Model instance.\n * @param keyOrOptions - Attribute name, or options for all values.\n * @param options - `raw: true` skips the custom getter.\n * @returns Attribute value or values object.\n */\n get(\n instance: AnyModel,\n keyOrOptions: string | number | symbol | GetOptions | undefined,\n options: SetOptions,\n ): unknown {\n if (typeof keyOrOptions === 'string') {\n return this.#getOne(instance, keyOrOptions, options);\n }\n return this.#getAll(instance, keyOrOptions);\n }\n\n /**\n * Sets one attribute (custom setter applied unless `raw`) or several.\n *\n * @param instance - Model instance.\n * @param keyOrValues - Attribute name or values.\n * @param valueOrOptions - Value, or options when setting several values.\n * @param maybeOptions - Options when setting one value.\n */\n set(\n instance: AnyModel,\n keyOrValues: string | number | symbol | Values,\n valueOrOptions: unknown,\n maybeOptions: SetOptions | undefined,\n ): void {\n if (typeof keyOrValues === 'object') {\n const options = (valueOrOptions ?? {}) as SetOptions;\n if (options.raw === true) {\n // Raw values bypass setters, so they can be copied in one step (as v6 does).\n Object.assign(instance.dataValues as Values, keyOrValues);\n return;\n }\n Object.entries(keyOrValues).forEach(([key, value]) =>\n instance.set(key, value as never, options),\n );\n return;\n }\n this.#setOne(instance, String(keyOrValues), valueOrOptions, maybeOptions ?? {});\n }\n\n #getOne(instance: AnyModel, key: string, options: SetOptions): unknown {\n const getter = this.#registry.definition(instance.constructor).attributes.get(key)?.get;\n return getter !== undefined && options.raw !== true\n ? (getter as (this: unknown) => unknown).call(instance)\n : (instance.dataValues as Values)[key];\n }\n\n #getAll(instance: AnyModel, options: GetOptions | number | symbol | undefined): Values {\n const raw = typeof options === 'object' && options.raw === true;\n const plain = typeof options === 'object' && options.plain === true;\n const toPlain = (value: unknown): unknown =>\n !plain\n ? value\n : this.#isInstance(value)\n ? value.get({ plain: true })\n : Array.isArray(value) && value.some((item) => this.#isInstance(item))\n ? value.map(toPlain)\n : value;\n return Object.fromEntries(\n Object.keys(instance.dataValues).map((key) => [\n key,\n toPlain(raw ? (instance.dataValues as Values)[key] : instance.get(key)),\n ]),\n );\n }\n\n #setOne(instance: AnyModel, key: string, value: unknown, options: SetOptions): void {\n if (options.raw === true) {\n (instance.dataValues as Values)[key] = value;\n return;\n }\n const attribute = this.#registry.definition(instance.constructor).attributes.get(key);\n if (attribute === undefined) {\n return;\n }\n const values = instance.dataValues as Values;\n const original = values[key];\n if (attribute.set !== undefined) {\n (attribute.set as (this: unknown, value: unknown) => void).call(instance, value);\n this.#track(instance, key, original, values[key]);\n return;\n }\n this.#track(instance, key, original, value);\n values[key] = value;\n }\n\n /** v6 `set`: an attribute that differs from its value before the call stays changed for good. */\n #track(instance: AnyModel, key: string, original: unknown, value: unknown): void {\n if (value instanceof SqlExpression || !this.#values.isEqual(value, original)) {\n (instance._previousDataValues as Values)[key] = original;\n InstanceState.of(instance).mark(key, true);\n }\n }\n\n /**\n * Writes a value without custom setters, tracking the change.\n *\n * @param instance - Model instance.\n * @param key - Attribute name.\n * @param value - New value.\n */\n setDataValue(instance: AnyModel, key: string | number | symbol, value: unknown): void {\n const name = String(key);\n const state = InstanceState.of(instance);\n if (\n !this.#values.isEqual((instance._previousDataValues as Values)[name], value) ||\n value instanceof SqlExpression\n ) {\n state.mark(name, true);\n }\n (instance.dataValues as Values)[name] = value;\n }\n\n /**\n * Lists changed attributes, checks one, or marks one as changed / unchanged.\n *\n * @param instance - Model instance.\n * @param key - Attribute name.\n * @param value - Changed flag.\n * @returns Names (or `false`), a flag, or `undefined` when marking.\n */\n changed(instance: AnyModel, key: string | undefined, value: boolean | undefined): unknown {\n const state = InstanceState.of(instance);\n if (key === undefined) {\n return state.changed.size === 0 ? false : [...state.changed];\n }\n if (value === undefined) {\n return state.changed.has(key);\n }\n state.mark(key, value);\n return undefined;\n }\n\n /**\n * Previous value of an attribute, or all previous values of changed attributes.\n *\n * @param instance - Model instance.\n * @param key - Attribute name.\n * @returns Previous value(s).\n */\n previous(instance: AnyModel, key: string | number | symbol | undefined): unknown {\n if (key !== undefined) {\n return (instance._previousDataValues as Record<string | number | symbol, unknown>)[key];\n }\n return Object.fromEntries(\n [...InstanceState.of(instance).changed].map((name) => [\n name,\n (instance._previousDataValues as Values)[name],\n ]),\n );\n }\n\n /**\n * Compares primary keys of two instances of the same model.\n *\n * @param instance - Model instance.\n * @param other - Instance to compare with.\n * @returns True when `other` is an instance of the model and all primary keys are equal.\n */\n equals(instance: AnyModel, other: AnyModel): boolean {\n const definition = this.#registry.definition(instance.constructor);\n return (\n other instanceof (instance.constructor as abstract new (...args: never[]) => unknown) &&\n definition.primaryKeys.every((name) =>\n this.#values.isEqual(\n (instance.dataValues as Values)[name],\n (other.dataValues as Values)[name],\n ),\n )\n );\n }\n}\n","import { SqlCompiler, type CompiledQuery } from '../sql/compile.ts';\nimport type { ExprNode } from '../sql/ast.ts';\n\n/** Table reference accepted by QueryInterface: a name or `{ tableName, schema }`. */\nexport type TableName = string | QualifiedTable;\n\n/** Schema-qualified table reference. */\nexport type QualifiedTable = Readonly<{\n /** Table name. */\n tableName: string;\n /** Schema name. */\n schema?: string;\n}>;\n\nconst compiler = new SqlCompiler();\n\nconst PLACEHOLDER = /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|(?<![\\w$])\\$(\\d+)/g;\n\n/**\n * Renders values as PostgreSQL literals and table references as quoted names, for DDL where bind\n * parameters are not allowed (ADR-010).\n *\n * @internal\n */\nexport class SqlLiteral {\n /**\n * Renders a value as a PostgreSQL literal. Strings with backslashes use the `E'...'` form.\n *\n * @param value - Value to render.\n * @returns SQL literal.\n * @throws Error for non-finite numbers and strings with NUL characters.\n */\n escape(value: unknown): string {\n if (value === null || value === undefined) {\n return 'NULL';\n }\n switch (typeof value) {\n case 'boolean':\n return value ? 'true' : 'false';\n case 'number':\n return this.#escapeNumber(value);\n case 'bigint':\n return value.toString();\n case 'object':\n return this.#escapeObject(value);\n default:\n return this.#escapeString(String(value));\n }\n }\n\n /**\n * Replaces `$n` placeholders of a compiled query with escaped literals.\n *\n * @param query - Compiled query.\n * @returns SQL text without placeholders.\n */\n inlineValues(query: CompiledQuery): string {\n return query.text.replace(PLACEHOLDER, (token, index?: string) =>\n index === undefined ? token : this.escape(query.values[Number(index) - 1]),\n );\n }\n\n /**\n * Compiles an expression node and inlines its values (for DDL).\n *\n * @param node - Expression node.\n * @returns SQL text without placeholders.\n */\n inlineExpr(node: ExprNode): string {\n return this.inlineValues(compiler.compileExpr(node));\n }\n\n /**\n * Splits a table reference into name and schema.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param defaultSchema - Schema used when the reference has none.\n * @returns Table name and schema.\n */\n tableParts(\n table: TableName,\n defaultSchema?: string,\n ): Readonly<{ name: string; schema: string | undefined }> {\n return typeof table === 'string'\n ? { name: table, schema: defaultSchema }\n : { name: table.tableName, schema: table.schema ?? defaultSchema };\n }\n\n /**\n * Quoted, schema-qualified table name.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param defaultSchema - Schema used when the reference has none.\n * @returns Quoted table name.\n */\n quoteTable(table: TableName, defaultSchema?: string): string {\n const { name, schema } = this.tableParts(table, defaultSchema);\n return schema === undefined\n ? SqlCompiler.quoteIdent(name)\n : `${SqlCompiler.quoteIdent(schema)}.${SqlCompiler.quoteIdent(name)}`;\n }\n\n #escapeNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new Error(`Cannot render non-finite number ${String(value)} as SQL literal`);\n }\n return String(value);\n }\n\n #escapeObject(value: object): string {\n if (value instanceof Date) {\n return this.#escapeString(value.toISOString());\n }\n if (Buffer.isBuffer(value)) {\n return `'\\\\x${value.toString('hex')}'::bytea`;\n }\n if (Array.isArray(value)) {\n return value.length === 0\n ? \"'{}'\"\n : `ARRAY[${value.map((item: unknown) => this.escape(item)).join(', ')}]`;\n }\n return this.#escapeString(JSON.stringify(value));\n }\n\n #escapeString(text: string): string {\n if (text.includes('\\0')) {\n throw new Error('SQL literals cannot contain NUL characters');\n }\n const quoted = text.replaceAll(\"'\", \"''\");\n return text.includes('\\\\') ? `E'${quoted.replaceAll('\\\\', '\\\\\\\\')}'` : `'${quoted}'`;\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { SqlLiteral } from '../ddl/sql-literal.ts';\nimport { SqlAst, type ExprNode, type FromItem, type JsonTableColumn } from '../sql/ast.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport { validCastType } from '../where/operator-allowlist.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport type { JsonTableColumnOptions, JsonTableOptions } from './source-options.ts';\nimport { TableSampleBuilder } from './table-sample-builder.ts';\n\nconst ast = new SqlAst();\nconst literals = new SqlLiteral();\nconst values = new WhereCompiler({ resolve: () => undefined });\n\nconst expr = (value: unknown): ExprNode => values.toExpr(value);\n\ntype Plain = Readonly<Record<string, unknown>>;\n\n/** Converts the object forms of a `from` entry (`values`, `function`, `jsonTable`, `lateral`, `model` + `sample`). */\nexport class SourceOptionBuilder {\n readonly #registry: ModelRegistry;\n readonly #columns: AttributeColumns;\n readonly #samples = new TableSampleBuilder();\n\n /**\n * @param registry - Model definitions.\n * @param columns - Table references of models.\n */\n constructor(registry: ModelRegistry, columns: AttributeColumns) {\n this.#registry = registry;\n this.#columns = columns;\n }\n\n /**\n * Builds the FROM item of an object-form source.\n *\n * @param alias - Alias of the relation.\n * @param source - Source option.\n * @returns FROM item.\n * @throws Error for inconsistent options.\n */\n build(alias: string, source: Plain): FromItem {\n if ('values' in source) {\n return SourceOptionBuilder.#values(alias, source['values'] as Plain);\n }\n if ('function' in source) {\n return SourceOptionBuilder.#function(alias, source);\n }\n return 'jsonTable' in source || 'lateral' in source\n ? SourceOptionBuilder.#nested(alias, source)\n : {\n ...this.#columns.table(this.#registry.definition(source['model'] as never), alias),\n sample: this.#samples.build(source['sample'] as never),\n };\n }\n\n static #nested(alias: string, source: Plain): FromItem {\n return 'jsonTable' in source\n ? {\n jsonTable: SourceOptionBuilder.#jsonTable(source['jsonTable'] as JsonTableOptions),\n alias,\n }\n : { subquery: (source['lateral'] as { build(): never }).build(), alias, lateral: true };\n }\n\n static #values(alias: string, spec: Plain): FromItem {\n const columns = spec['columns'] as readonly string[];\n const rows = spec['rows'] as readonly (readonly unknown[])[];\n if (rows.length === 0 || columns.length === 0) {\n throw new Error('values needs at least one column and one row');\n }\n if (rows.some((row) => row.length !== columns.length)) {\n throw new Error('every row of values must have one cell per column');\n }\n return { values: rows.map((row) => row.map(expr)), alias, columns };\n }\n\n static #function(alias: string, source: Plain): FromItem {\n const ordinality = source['ordinality'] as string | undefined;\n const columns = source['columns'] as readonly string[] | undefined;\n if (ordinality !== undefined && columns === undefined) {\n throw new Error('function with ordinality needs columns');\n }\n return {\n function: String(source['function']).split('.'),\n args: ((source['args'] as readonly unknown[] | undefined) ?? []).map(expr),\n alias,\n ...(columns === undefined\n ? {}\n : { columns: ordinality === undefined ? columns : [...columns, ordinality] }),\n ...(ordinality === undefined ? {} : { ordinality }),\n };\n }\n\n static #jsonTable(\n options: JsonTableOptions,\n ): Extract<FromItem, { jsonTable: unknown }>['jsonTable'] {\n return {\n doc:\n options.doc instanceof SqlExpression\n ? expr(options.doc)\n : { kind: 'cast', expr: ast.param(JSON.stringify(options.doc)), type: 'jsonb' },\n path: literals.escape(options.path),\n columns: options.columns.map((column) => SourceOptionBuilder.#jsonColumn(column)),\n };\n }\n\n static #jsonColumn(column: JsonTableColumnOptions): JsonTableColumn {\n if (column.ordinality === true) {\n return { name: column.name, kind: 'ordinality' };\n }\n const exists = column.exists === true;\n const type = column.type ?? (exists ? 'boolean' : undefined);\n if (type === undefined) {\n throw new Error(`JSON_TABLE column \"${column.name}\" needs a type`);\n }\n return {\n name: column.name,\n kind: exists ? 'exists' : 'value',\n type: validCastType(type),\n ...(column.path === undefined ? {} : { path: literals.escape(column.path) }),\n };\n }\n}\n","import { Subquery } from '../expressions/methods.ts';\nimport type { FromItem } from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport { SourceOptionBuilder } from './source-option-builder.ts';\nimport type { FromSourceOption } from './source-options.ts';\n\n/**\n * Extra relations for finders' `from`, `UPDATE ... FROM` and `DELETE ... USING`, keyed by alias.\n * PostgreSQL extension.\n */\nexport type JoinSources = Readonly<Record<string, FromSourceOption>>;\n\n/** Converts `from` / `using` options (models, subqueries, relation names) into FROM items. */\nexport class JoinSourceBuilder {\n readonly #registry: ModelRegistry;\n readonly #columns: AttributeColumns;\n readonly #objects: SourceOptionBuilder;\n\n /**\n * @param registry - Model definitions.\n * @param columns - Table references of models.\n */\n constructor(registry: ModelRegistry, columns: AttributeColumns) {\n this.#registry = registry;\n this.#columns = columns;\n this.#objects = new SourceOptionBuilder(registry, columns);\n }\n\n /**\n * Converts `from` / `using` options into FROM items.\n *\n * @param sources - Relations by alias.\n * @returns FROM items (empty without sources).\n */\n build(sources: JoinSources | undefined): readonly FromItem[] {\n return Object.entries(sources ?? {}).map(([alias, source]): FromItem =>\n typeof source === 'string'\n ? { name: source, ...(alias === source ? {} : { alias }) }\n : source instanceof Subquery\n ? { subquery: source.build(), alias }\n : typeof source === 'function'\n ? this.#columns.table(this.#registry.definition(source), alias)\n : this.#objects.build(alias, source),\n );\n }\n}\n","import type { ConflictTarget, ExprNode, OnConflictNode } from '../sql/ast.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { BulkCreateOptions, Values } from './options.ts';\n\ntype UniqueKey = Readonly<{ fields: readonly string[]; where?: unknown }>;\n\nconst fieldsOf = (definition: ModelDefinition, names: readonly string[]): readonly string[] =>\n names.map((name) => definition.attributes.get(name)?.field ?? name);\n\nconst firstUniqueKey = (definition: ModelDefinition): readonly string[] | undefined =>\n [...definition.uniqueKeys.values()].find((fields) => fields.length > 0);\n\n/** Attribute names (and partial-index predicate) of each unique index declared in `indexes`. */\nconst uniqueIndexKeys = (definition: ModelDefinition, withPartial: boolean): readonly UniqueKey[] =>\n (definition.options.indexes ?? [])\n .filter((index) => index.unique === true && (withPartial || index.where === undefined))\n .filter((index) =>\n (index.fields ?? []).every((field) => typeof field === 'string' || field.name !== undefined),\n )\n .map((index) => ({\n fields: (index.fields ?? []).map((field) =>\n typeof field === 'string' ? field : (field.name as string),\n ),\n ...(index.where === undefined ? {} : { where: index.where }),\n }))\n .filter((key) => key.fields.length > 0);\n\nconst columnsTarget = (target: readonly string[], where: ExprNode | undefined): ConflictTarget => ({\n kind: 'columns',\n items: target.map((field) => ({ kind: 'ident', path: [field] }) as const),\n ...(where === undefined ? {} : { where }),\n});\n\nconst conflictUpdate = (\n attributes: readonly string[],\n target: readonly string[],\n where?: ExprNode,\n): OnConflictNode => ({\n target: columnsTarget(target, where),\n action:\n attributes.length === 0\n ? { kind: 'nothing' }\n : {\n kind: 'update',\n set: attributes.map((field) => ({\n column: field,\n value: { kind: 'excluded', column: field } as const,\n })),\n },\n});\n\n/**\n * Translates the Sequelize v6 conflict rules into ON CONFLICT clauses: `bulkCreate`\n * (`ignoreDuplicates`, `updateOnDuplicate`, `conflictAttributes`, `conflictWhere`) and `upsert`\n * (conflict target from unique keys / indexes).\n */\nexport class V6ConflictBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * ON CONFLICT clause of Sequelize v6 `bulkCreate` options.\n *\n * @param definition - Model definition.\n * @param options - `updateOnDuplicate`, `conflictAttributes`, `conflictWhere`, `ignoreDuplicates`.\n * @returns `{ onConflict }`, or `{}` without conflict handling.\n * @throws Error for an empty `updateOnDuplicate`.\n */\n bulk(\n definition: ModelDefinition,\n options: BulkCreateOptions,\n ): Readonly<{ onConflict?: OnConflictNode }> {\n if (options.updateOnDuplicate !== undefined) {\n return {\n onConflict: this.#updateOnDuplicate(definition, options, options.updateOnDuplicate),\n };\n }\n return options.ignoreDuplicates === true ? { onConflict: { action: { kind: 'nothing' } } } : {};\n }\n\n /**\n * ON CONFLICT clause of Sequelize v6 `upsert`.\n *\n * @param definition - Model definition.\n * @param insertValues - Inserted values.\n * @param updatable - Attributes updated on conflict.\n * @param conflictFields - `conflictFields` option (column names).\n * @returns ON CONFLICT node.\n */\n upsert(\n definition: ModelDefinition,\n insertValues: Values,\n updatable: readonly string[],\n conflictFields: readonly string[] | undefined,\n ): OnConflictNode {\n const update = V6ConflictBuilder.#upsertUpdate(definition, insertValues, updatable);\n const uniqueKey = V6ConflictBuilder.#upsertKey(definition, update);\n const target =\n conflictFields ?? fieldsOf(definition, uniqueKey?.fields ?? definition.primaryKeys);\n const where =\n conflictFields === undefined ? this.#compile(definition, uniqueKey?.where) : undefined;\n const assigned = update.filter(\n (name) => definition.attributes.get(name)?.identity !== 'always',\n );\n return conflictUpdate(fieldsOf(definition, assigned), [...new Set(target)], where);\n }\n\n #updateOnDuplicate(\n definition: ModelDefinition,\n options: BulkCreateOptions,\n updateOnDuplicate: readonly string[],\n ): OnConflictNode {\n if (updateOnDuplicate.length === 0) {\n throw new Error('updateOnDuplicate option only supports non-empty array.');\n }\n const updatable = updateOnDuplicate.filter(\n (name) => definition.attributes.has(name) && name !== definition.createdAt,\n );\n const indexed = [\n ...uniqueIndexKeys(definition, false).flatMap((key) => key.fields),\n ...(firstUniqueKey(definition) ?? []),\n ];\n const target =\n options.conflictAttributes ?? (indexed.length > 0 ? indexed : definition.primaryKeys);\n const where = this.#compile(definition, options.conflictWhere);\n return conflictUpdate(fieldsOf(definition, updatable), fieldsOf(definition, target), where);\n }\n\n #compile(definition: ModelDefinition, where: unknown): ExprNode | undefined {\n return WhereCompiler.isEmpty(where)\n ? undefined\n : this.#columns.whereCompiler(definition, undefined).compile(where);\n }\n\n static #upsertUpdate(\n definition: ModelDefinition,\n insertValues: Values,\n updatable: readonly string[],\n ): readonly string[] {\n return [\n ...updatable,\n ...(definition.updatedAt === undefined || updatable.includes(definition.updatedAt)\n ? []\n : [definition.updatedAt]),\n ].filter((name) => name in insertValues);\n }\n\n /** The first unique key (or unique index) containing an updated attribute, unless a primary key is updated. */\n static #upsertKey(definition: ModelDefinition, update: readonly string[]): UniqueKey | undefined {\n if (update.some((name) => definition.primaryKeys.includes(name))) {\n return undefined;\n }\n const uniqueKeys = [...definition.uniqueKeys.values()]\n .filter((fields) => fields.length > 0)\n .map((fields): UniqueKey => ({ fields }));\n const indexKeys = uniqueIndexKeys(definition, true);\n return update\n .map(\n (name) =>\n uniqueKeys.find((key) => key.fields.includes(name)) ??\n indexKeys.find((key) => key.fields.includes(name)),\n )\n .find((key) => key !== undefined);\n }\n}\n","import { excluded, SqlExpression, type Fn, type Literal } from '../expressions/methods.ts';\nimport { SqlAst, type ConflictTarget, type ExprNode, type OnConflictNode } from '../sql/ast.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { BulkCreateOptions, Values } from './options.ts';\nimport { V6ConflictBuilder } from './v6-conflict-builder.ts';\nimport type { WhereOptions } from './types.ts';\n\nconst ast = new SqlAst();\n\n/** Columns or index expressions identifying the unique index, optionally a partial index. */\nexport type OnConflictColumnsTarget<T> = Readonly<{\n /** Attribute names or index expressions (e.g. `fn('lower', col('email'))`, `literal('email COLLATE \"C\"')`). */\n columns: readonly ((keyof T & string) | Literal | Fn)[];\n /** Predicate of a partial unique index (`ON CONFLICT (...) WHERE ...`). */\n where?: WhereOptions<T>;\n}>;\n\n/** Named constraint used as arbiter (`ON CONFLICT ON CONSTRAINT name`). */\nexport type OnConflictConstraintTarget = Readonly<{\n /** Constraint name. */\n constraint: string;\n}>;\n\n/** Conflict target of {@link OnConflictOptions}. */\nexport type OnConflictTarget<T> =\n | readonly ((keyof T & string) | Literal | Fn)[]\n | OnConflictColumnsTarget<T>\n | OnConflictConstraintTarget;\n\n/**\n * Values assigned on conflict: a list of attributes (each set to `excluded(attribute)`) or a map\n * of attribute to value or expression (`excluded()`, `col()`, `fn()`, `literal()`).\n */\nexport type OnConflictUpdate<T> =\n | readonly (keyof T & string)[]\n | Readonly<{ [K in keyof T]?: T[K] | SqlExpression }>;\n\n/** `DO UPDATE` action of {@link OnConflictOptions}. */\nexport type OnConflictUpdateAction<T> = Readonly<{\n /** Assignments. */\n update: OnConflictUpdate<T>;\n /** Only update rows matching this condition (`DO UPDATE ... WHERE`); others are left unchanged. */\n where?: WhereOptions<T>;\n}>;\n\n/**\n * Advanced `INSERT ... ON CONFLICT` specification. PostgreSQL extension.\n *\n * @example\n * ```ts\n * const rows = [{ tenantId: 1, key: 'views', hits: 1, version: 2 }];\n * await Product.bulkCreate(rows, {\n * onConflict: {\n * target: ['tenantId', 'key'],\n * action: {\n * update: { hits: literal('\"Product\".\"hits\" + EXCLUDED.\"hits\"'), updatedAt: fn('now') },\n * where: { version: { [Op.lt]: excluded('version') } },\n * },\n * },\n * });\n * ```\n */\nexport type OnConflictOptions<T> = Readonly<{\n /** Unique index or constraint to arbitrate on. Required for `update`. */\n target?: OnConflictTarget<T>;\n /** `'nothing'` to skip conflicting rows, or an update. */\n action: 'nothing' | OnConflictUpdateAction<T>;\n}>;\n\nconst assertAttribute = (definition: ModelDefinition, name: string): string => {\n const attribute = definition.attributes.get(name);\n if (attribute === undefined) {\n throw new Error(`onConflict: unknown attribute \"${name}\" of model ${definition.name}`);\n }\n return attribute.field;\n};\n\nconst isConstraintTarget = (\n target: OnConflictTarget<unknown>,\n): target is OnConflictConstraintTarget => !Array.isArray(target) && 'constraint' in target;\n\n/**\n * Builds `INSERT ... ON CONFLICT` clauses: the `onConflict` option (PostgreSQL extension) and the\n * Sequelize v6 rules of `bulkCreate` (`ignoreDuplicates`, `updateOnDuplicate`, `conflictAttributes`,\n * `conflictWhere`) and `upsert` (conflict target from unique keys / indexes).\n */\nexport class OnConflictBuilder {\n /** Column added to `RETURNING` to tell inserted rows from updated ones. */\n static readonly INSERTED_FLAG = '__pgz_inserted';\n /** Sequelize v6 `bulkCreate` conflict options, not combinable with `onConflict`. */\n static readonly V6_OPTIONS = [\n 'ignoreDuplicates',\n 'updateOnDuplicate',\n 'conflictAttributes',\n 'conflictWhere',\n ] as const;\n\n readonly #columns: AttributeColumns;\n readonly #v6: V6ConflictBuilder;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n this.#v6 = new V6ConflictBuilder(columns);\n }\n\n /**\n * Validates `onConflict` and converts it into an AST node. The target table must be aliased with\n * the model name so `col()` and `where` refer to the existing row.\n *\n * @param definition - Model definition.\n * @param options - `onConflict` option.\n * @returns ON CONFLICT node.\n * @throws Error for unknown attributes, empty targets or an update without target.\n */\n build(definition: ModelDefinition, options: OnConflictOptions<unknown>): OnConflictNode {\n const target =\n options.target === undefined ? undefined : this.#target(definition, options.target);\n if (options.action === 'nothing') {\n return { ...(target === undefined ? {} : { target }), action: { kind: 'nothing' } };\n }\n if (target === undefined) {\n throw new Error('onConflict: target is required when action is an update');\n }\n return { target, action: this.#updateAction(definition, options.action) };\n }\n\n /**\n * `(xmax = 0) AS \"__pgz_inserted\"` — true for rows inserted by this statement.\n *\n * @returns RETURNING column.\n */\n insertedFlagColumn(): ExprNode {\n return {\n kind: 'alias',\n expr: ast.raw('(xmax = 0)'),\n alias: OnConflictBuilder.INSERTED_FLAG,\n };\n }\n\n /**\n * ON CONFLICT clause of Sequelize v6 `bulkCreate` options.\n *\n * @param definition - Model definition.\n * @param options - `updateOnDuplicate`, `conflictAttributes`, `conflictWhere`, `ignoreDuplicates`.\n * @returns `{ onConflict }`, or `{}` without conflict handling.\n * @throws Error for an empty `updateOnDuplicate`.\n */\n v6Bulk(\n definition: ModelDefinition,\n options: BulkCreateOptions,\n ): Readonly<{ onConflict?: OnConflictNode }> {\n return this.#v6.bulk(definition, options);\n }\n\n /**\n * ON CONFLICT clause of Sequelize v6 `upsert`: the target is the first unique key (or unique\n * index) containing an updated attribute, otherwise the primary key.\n *\n * @param definition - Model definition.\n * @param insertValues - Inserted values.\n * @param updatable - Attributes updated on conflict.\n * @param conflictFields - `conflictFields` option (column names).\n * @returns ON CONFLICT node.\n */\n v6Upsert(\n definition: ModelDefinition,\n insertValues: Values,\n updatable: readonly string[],\n conflictFields: readonly string[] | undefined,\n ): OnConflictNode {\n return this.#v6.upsert(definition, insertValues, updatable, conflictFields);\n }\n\n #updateAction(\n definition: ModelDefinition,\n action: OnConflictUpdateAction<unknown>,\n ): OnConflictNode['action'] {\n const ctx = new WhereCompiler({\n ...this.#columns.whereCompiler(definition, definition.name).context,\n allowExcluded: true,\n });\n const set = this.#columns.setItems(\n definition,\n this.#updateValues(definition, action.update),\n ctx,\n );\n const where = WhereCompiler.isEmpty(action.where) ? undefined : ctx.compile(action.where);\n return { kind: 'update', set, ...(where === undefined ? {} : { where }) };\n }\n\n #targetItem(definition: ModelDefinition, item: unknown): ExprNode {\n return item instanceof SqlExpression\n ? this.#columns.whereCompiler(definition, undefined).toExpr(item)\n : ast.ident(assertAttribute(definition, String(item)));\n }\n\n #target(definition: ModelDefinition, target: OnConflictTarget<unknown>): ConflictTarget {\n if (isConstraintTarget(target)) {\n return { kind: 'constraint', name: target.constraint };\n }\n const columnsTarget = (\n Array.isArray(target) ? { columns: target } : target\n ) as OnConflictColumnsTarget<unknown>;\n if (columnsTarget.columns.length === 0) {\n throw new Error('onConflict: target columns must not be empty');\n }\n const where = WhereCompiler.isEmpty(columnsTarget.where)\n ? undefined\n : this.#columns.whereCompiler(definition, undefined).compile(columnsTarget.where);\n return {\n kind: 'columns',\n items: columnsTarget.columns.map((item) => this.#targetItem(definition, item)),\n ...(where === undefined ? {} : { where }),\n };\n }\n\n #updateValues(\n definition: ModelDefinition,\n update: OnConflictUpdate<unknown>,\n ): Readonly<Record<string, unknown>> {\n const entries: readonly (readonly [string, unknown])[] = Array.isArray(update)\n ? update.map((name: string) => [name, excluded(name)] as const)\n : Object.entries(update);\n if (entries.length === 0) {\n throw new Error('onConflict: update must assign at least one attribute');\n }\n entries.forEach(([name]) => assertAttribute(definition, name));\n const updatedAt = definition.updatedAt;\n return Object.fromEntries(\n updatedAt === undefined || entries.some(([name]) => name === updatedAt)\n ? entries\n : [...entries, [updatedAt, excluded(updatedAt)] as const],\n );\n }\n}\n","import { SqlAst, type ExprNode } from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { RowMapper } from './row-mapper.ts';\nimport type { ModelRuntime } from './runtime.ts';\n\nconst ast = new SqlAst();\n\n/**\n * `returningOld` option (PostgreSQL 18+ `RETURNING WITH (OLD AS ...)`): checks the server\n * version, adds the pre-statement row to a write's RETURNING list and reads it back.\n */\nexport class ReturningOld {\n /** Alias of the pre-statement row in `RETURNING WITH (OLD AS ...)`. */\n static readonly ALIAS = '__pgz_old';\n /** Prefix of returned columns carrying pre-statement values. */\n static readonly PREFIX = `${ReturningOld.ALIAS}.`;\n\n readonly #columns: AttributeColumns;\n readonly #rows: RowMapper;\n\n /**\n * @param columns - Stored columns of a model.\n * @param rows - Parses returned values.\n */\n constructor(columns: AttributeColumns, rows: RowMapper) {\n this.#columns = columns;\n this.#rows = rows;\n }\n\n /**\n * Whether the write should return pre-statement values.\n *\n * @param runtime - Runtime of the model (server version).\n * @param options - Write options.\n * @returns True with `returningOld: true`.\n * @throws Error on PostgreSQL older than 18.\n */\n async enabled(\n runtime: Pick<ModelRuntime, 'serverVersion'>,\n options: Readonly<{ returningOld?: boolean }>,\n ): Promise<boolean> {\n if (options.returningOld !== true) {\n return false;\n }\n if ((await runtime.serverVersion()) < 180000) {\n throw new Error('returningOld requires PostgreSQL 18 or newer');\n }\n return true;\n }\n\n /**\n * Adds the pre-statement row (all stored columns) to the RETURNING list of a write.\n *\n * @param definition - Model definition.\n * @param node - INSERT / UPDATE / MERGE node.\n * @returns Node with `returningOld`.\n */\n node<N extends Readonly<{ returning?: readonly ExprNode[] }>>(\n definition: ModelDefinition,\n node: N,\n ): N & Readonly<{ returningOld: string }> {\n return {\n ...node,\n returningOld: ReturningOld.ALIAS,\n returning: [\n ...(node.returning ?? []),\n ...this.#columns.stored(definition).map((attribute): ExprNode => ({\n kind: 'alias',\n expr: ast.ident(ReturningOld.ALIAS, attribute.field),\n alias: `${ReturningOld.PREFIX}${attribute.fieldName}`,\n })),\n ],\n };\n }\n\n /**\n * Pre-statement values of a returned row.\n *\n * @param definition - Model definition.\n * @param row - Returned row.\n * @returns Attribute values, or `null` when the row did not exist before (inserted).\n */\n previous(\n definition: ModelDefinition,\n row: Readonly<Record<string, unknown>>,\n ): Readonly<Record<string, unknown>> | null {\n const old = Object.fromEntries(\n Object.entries(row)\n .filter(([key]) => key.startsWith(ReturningOld.PREFIX))\n .map(([key, value]) => [key.slice(ReturningOld.PREFIX.length), value]),\n );\n return definition.primaryKeys.every((name) => old[name] === null || old[name] === undefined)\n ? null\n : this.#rows.parse(definition, old);\n }\n}\n","import type { ModelDefinition } from './model-definition.ts';\n\n/** How one driver column is stored: the attribute it maps to and its data type parser. */\nexport type ColumnPlan = Readonly<{\n name: string;\n parse: ((value: unknown) => unknown) | undefined;\n}>;\n\n/**\n * Per-definition cache of column plans. A driver row is converted once per row and column, so the\n * attribute lookup (`attributes`, `fieldToAttribute`, type parser) is resolved once per column name\n * instead. Definitions are replaced, never mutated, so the cache is keyed by definition identity.\n */\nexport class RowPlans {\n readonly #plans = new WeakMap<ModelDefinition, Map<string, ColumnPlan>>();\n\n /**\n * Plans of a definition, filled lazily by {@link RowPlans.plan}.\n *\n * @param definition - Model definition.\n * @returns Column plans by driver column name.\n */\n columns(definition: ModelDefinition): Map<string, ColumnPlan> {\n let columns = this.#plans.get(definition);\n if (columns === undefined) {\n columns = new Map();\n this.#plans.set(definition, columns);\n }\n return columns;\n }\n\n /**\n * Resolves and remembers the plan of a column. Columns that match no attribute are kept as they\n * are, without a parser.\n *\n * @param definition - Model definition.\n * @param columns - The definition's plans.\n * @param key - Driver column name.\n * @returns The plan.\n */\n plan(definition: ModelDefinition, columns: Map<string, ColumnPlan>, key: string): ColumnPlan {\n const name = definition.attributes.has(key)\n ? key\n : (definition.fieldToAttribute.get(key) ?? key);\n const plan = { name, parse: definition.attributes.get(name)?.type.parse };\n columns.set(key, plan);\n return plan;\n }\n}\n","import type { QueryResultRow } from 'pg';\nimport type { AttributeDefinition, ModelDefinition } from './model-definition.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport { RowPlans } from './row-plan.ts';\nimport { ValuesWriter } from './values-writer.ts';\nimport type { AnyModel, ModelStatic, Values } from './options.ts';\n\nconst toNumber = (value: unknown): unknown =>\n typeof value === 'string' && value.trim() !== '' && !Number.isNaN(Number(value))\n ? Number(value)\n : value;\n\nconst NUMERIC_KEYS: ReadonlySet<string | undefined> = new Set([\n 'INTEGER',\n 'SMALLINT',\n 'FLOAT',\n 'DOUBLE',\n 'REAL',\n 'DECIMAL',\n 'BIGINT',\n]);\n\n/**\n * Converts driver rows into attribute values and model instances: column names to attribute\n * names, data type parsers, nested `raw` rows and aggregate results.\n */\nexport class RowMapper {\n readonly #registry: ModelRegistry;\n readonly #plans = new RowPlans();\n readonly #writer = new ValuesWriter();\n\n /**\n * @param registry - Model definitions.\n */\n constructor(registry: ModelRegistry) {\n this.#registry = registry;\n }\n\n /**\n * Converts a driver row into attribute values: maps column names to attribute names (when the\n * query did not alias them) and applies data type parsers. Unknown columns are kept as is.\n *\n * @param definition - Model definition.\n * @param row - Driver row.\n * @returns Attribute values.\n */\n parse(definition: ModelDefinition, row: QueryResultRow): Readonly<Record<string, unknown>> {\n const columns = this.#plans.columns(definition);\n const values: Record<string, unknown> = {};\n for (const key of Object.keys(row)) {\n const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);\n const value: unknown = row[key];\n const parsed = parse === undefined || value === null ? value : parse(value);\n this.#writer.set(values, name, parsed);\n }\n return values;\n }\n\n /**\n * Like {@link RowMapper.parse}, for a row nobody else reads afterwards (raw results): parsers\n * are applied in place and the row itself is returned, which saves one object per row. A column\n * that maps to another attribute name switches to {@link RowMapper.parse} for the remaining\n * columns, so the key order matches `parse`.\n *\n * @param definition - Model definition.\n * @param row - Driver row; modified.\n * @returns Attribute values.\n */\n parseOwned(definition: ModelDefinition, row: QueryResultRow): Readonly<Record<string, unknown>> {\n const columns = this.#plans.columns(definition);\n const keys = Object.keys(row);\n for (const [index, key] of keys.entries()) {\n const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);\n if (name !== key) {\n return this.#renamed(definition, row, keys, index);\n }\n const value: unknown = row[key];\n if (parse !== undefined && value !== null) {\n row[key] = parse(value);\n }\n }\n return row;\n }\n\n /**\n * {@link RowMapper.parseOwned} for every row of one result. All rows of a query have the same\n * columns, so the column plan is resolved once from the first row and each row only runs the\n * parsers: a result without parsers is returned untouched.\n *\n * @param definition - Model definition.\n * @param rows - Driver rows of one query; modified.\n * @returns Attribute values per row (the same array).\n */\n parseAllOwned(\n definition: ModelDefinition,\n rows: readonly QueryResultRow[],\n ): readonly Readonly<Record<string, unknown>>[] {\n const first = rows[0];\n const parsers = first === undefined ? [] : this.#parsersOf(definition, first);\n if (parsers === undefined) {\n return rows.map((row) => this.parseOwned(definition, row));\n }\n for (const row of rows) {\n for (const [key, parse] of parsers) {\n const value: unknown = row[key];\n if (value !== null) {\n row[key] = parse(value);\n }\n }\n }\n return rows;\n }\n\n // Parsers of the columns of a row; `undefined` when a column maps to another attribute name.\n #parsersOf(\n definition: ModelDefinition,\n row: QueryResultRow,\n ): [string, (value: unknown) => unknown][] | undefined {\n const columns = this.#plans.columns(definition);\n const parsers: [string, (value: unknown) => unknown][] = [];\n for (const key of Object.keys(row)) {\n const { name, parse } = columns.get(key) ?? this.#plans.plan(definition, columns, key);\n if (name !== key) {\n return undefined;\n }\n if (parse !== undefined) {\n parsers.push([key, parse]);\n }\n }\n return parsers;\n }\n\n #renamed(\n definition: ModelDefinition,\n row: QueryResultRow,\n keys: readonly string[],\n from: number,\n ): Readonly<Record<string, unknown>> {\n const done = Object.fromEntries(keys.slice(0, from).map((key) => [key, row[key]]));\n const rest = Object.fromEntries(keys.slice(from).map((key) => [key, row[key]]));\n return Object.assign(done, this.parse(definition, rest));\n }\n\n /**\n * Parses a driver row into attribute values of `model`.\n *\n * @param model - Model class.\n * @param row - Driver row.\n * @returns Attribute values.\n */\n parseModel(\n model: object,\n row: Readonly<Record<string, unknown>>,\n ): Readonly<Record<string, unknown>> {\n return this.parse(this.#registry.definition(model), row);\n }\n\n /**\n * Builds a persisted instance from a driver row.\n *\n * @param model - Model class.\n * @param row - Driver row.\n * @returns Instance with `isNewRecord: false`.\n */\n instance<M extends AnyModel>(model: ModelStatic<M>, row: Readonly<Record<string, unknown>>): M {\n return new model(this.parseModel(model, row), { isNewRecord: false, raw: true });\n }\n\n /**\n * Nests `a.b` keys of a raw row into objects (`nest: true`).\n *\n * @param row - Raw row.\n * @returns Nested values.\n */\n nest(row: Values): Values {\n return Object.entries(row).reduce<Values>((result, [key, value]) => {\n const path = key.split('.');\n const leaf = path.pop() ?? key;\n const parent = path.reduce<Values>((node, part) => {\n const child = node[part];\n return (typeof child === 'object' && child !== null ? child : (node[part] = {})) as Values;\n }, result);\n parent[leaf] = value;\n return result;\n }, {});\n }\n\n /**\n * Parses an aggregate result: numbers for counts and numeric attributes, the attribute parser\n * otherwise.\n *\n * @param attribute - Aggregated attribute.\n * @param aggregateFunction - Aggregate function name.\n * @param value - Returned value.\n * @returns Parsed value.\n */\n aggregate(\n attribute: Pick<AttributeDefinition, 'type'> | undefined,\n aggregateFunction: string,\n value: unknown,\n ): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n if (aggregateFunction === 'count' || NUMERIC_KEYS.has(attribute?.type.key ?? 'FLOAT')) {\n return toNumber(value);\n }\n return attribute?.type.parse === undefined ? value : attribute.type.parse(value);\n }\n}\n","import { SqlAst, type FromItem, type SetItem, type UpdateNode } from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { ModelDefinition } from './model-definition.ts';\n\nconst ast = new SqlAst();\n\n/** Options of {@link UpdateQueryBuilder.build}. */\nexport type UpdateBuildOptions = Readonly<{\n /** Return all stored columns. */\n returning?: boolean;\n /** Lists at least this long compile to `= ANY($n)`. */\n inAsAnyThreshold?: number;\n /** Extra relations (`UPDATE ... FROM`); the table is then aliased with the model name. */\n from?: readonly FromItem[];\n}>;\n\n/** Builds UPDATE statements and the SET items of `increment` / `decrement`. */\nexport class UpdateQueryBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Builds an UPDATE.\n *\n * @param definition - Model definition.\n * @param set - SET items.\n * @param where - Condition.\n * @param options - RETURNING, `= ANY` threshold, FROM relations.\n * @returns UPDATE node.\n */\n build(\n definition: ModelDefinition,\n set: readonly SetItem[],\n where: unknown,\n options: UpdateBuildOptions = {},\n ): UpdateNode {\n const alias =\n options.from === undefined || options.from.length === 0 ? undefined : definition.name;\n const ctx = this.#columns.whereCompiler(definition, alias, options.inAsAnyThreshold);\n const condition = this.#columns.where(where, ctx);\n return {\n kind: 'update',\n table: this.#columns.table(definition, alias),\n set,\n ...(alias === undefined ? {} : { from: options.from }),\n ...(condition === undefined ? {} : { where: condition }),\n ...this.#returning(definition, alias, options.returning),\n };\n }\n\n /**\n * SET items `field = field + by` (or `- by`) for increment / decrement.\n *\n * @param definition - Model definition.\n * @param by - Amount per attribute.\n * @param sign - `1` to increment, `-1` to decrement.\n * @returns SET items.\n */\n increment(\n definition: ModelDefinition,\n by: Readonly<Record<string, number>>,\n sign: 1 | -1,\n ): readonly SetItem[] {\n return Object.entries(by).map(([name, amount]) => {\n const field = definition.attributes.get(name)?.field ?? name;\n return {\n column: field,\n value: ast.binary(sign === 1 ? '+' : '-', ast.ident(field), ast.param(amount)),\n };\n });\n }\n\n #returning(\n definition: ModelDefinition,\n alias: string | undefined,\n returning: boolean | undefined,\n ): Pick<UpdateNode, 'returning'> {\n return returning === true ? { returning: this.#columns.returningAll(definition, alias) } : {};\n }\n}\n","import { ValuesWriter } from './values-writer.ts';\n\nconst MAX_DEPTH = 32;\n/** Marks a value the fast copy does not handle. */\nconst UNSUPPORTED = Symbol('postgrelize.unsupported');\n\n/**\n * Deep copy of attribute values for `toJSON`. Rows hold primitives, dates, arrays and plain JSON\n * objects, which are copied directly; `structuredClone` is the slow general path, so it is used\n * for the whole value as soon as something else shows up (functions, symbols, class instances,\n * typed arrays, `Map`, cycles or an object reachable twice), which keeps its exact semantics.\n */\nexport class ValueCloner {\n readonly #writer = new ValuesWriter();\n\n /**\n * Copies a value like `structuredClone` does.\n *\n * @param value - Value to copy.\n * @returns The copy.\n * @throws DataCloneError for values `structuredClone` rejects (functions, symbols).\n */\n clone<T>(value: T): T {\n const copy = this.#copy(value, new Set(), 0);\n return copy === UNSUPPORTED ? structuredClone(value) : (copy as T);\n }\n\n #copy(value: unknown, seen: Set<object>, depth: number): unknown {\n if (value === null || typeof value !== 'object') {\n return typeof value === 'function' || typeof value === 'symbol' ? UNSUPPORTED : value;\n }\n if (depth > MAX_DEPTH || seen.has(value)) {\n return UNSUPPORTED;\n }\n seen.add(value);\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n if (Array.isArray(value)) {\n return this.#array(value, seen, depth);\n }\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null\n ? this.#object(value, seen, depth)\n : UNSUPPORTED;\n }\n\n #array(value: readonly unknown[], seen: Set<object>, depth: number): unknown {\n const copy: unknown[] = [];\n copy.length = value.length;\n for (let index = 0; index < value.length; index += 1) {\n if (index in value) {\n const item = this.#copy(value[index], seen, depth + 1);\n if (item === UNSUPPORTED) {\n return UNSUPPORTED;\n }\n copy[index] = item;\n }\n }\n return copy;\n }\n\n #object(value: object, seen: Set<object>, depth: number): unknown {\n const copy: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n const itemCopy = this.#copy(item, seen, depth + 1);\n if (itemCopy === UNSUPPORTED) {\n return UNSUPPORTED;\n }\n this.#writer.set(copy, key, itemCopy);\n }\n return copy;\n }\n}\n","import { literal } from '../expressions/methods.ts';\nimport type { ExprNode, MergeNode, MergeWhen, QueryNode, SelectNode } from '../sql/ast.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { MergeInsertAction, MergeMatchedAction, MergeOptions } from './merge-options.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { Values } from './options.ts';\n\nconst asArray = <T>(value: T | readonly T[] | undefined): readonly T[] =>\n value === undefined ? [] : Array.isArray(value) ? value : [value as T];\n\nconst timestamps = (definition: ModelDefinition, values: Values, creating: boolean): Values => ({\n ...(creating && definition.createdAt !== undefined && !(definition.createdAt in values)\n ? { [definition.createdAt]: literal('now()') }\n : {}),\n ...(definition.updatedAt !== undefined && !(definition.updatedAt in values)\n ? { [definition.updatedAt]: literal('now()') }\n : {}),\n ...values,\n});\n\n// The column names of a set operation are those of its leftmost SELECT.\nconst leftmost = (query: QueryNode): SelectNode =>\n query.kind === 'setop' ? leftmost(query.left) : query;\n\nconst sourceColumns = (source: MergeNode['source']): readonly string[] =>\n source.kind === 'values'\n ? source.columns\n : leftmost(source.query).columns.map((column) =>\n column.kind === 'alias'\n ? column.alias\n : column.kind === 'ident'\n ? (column.path.at(-1) ?? '')\n : '',\n );\n\n/** Builds the join condition and the `WHEN [NOT] MATCHED [BY SOURCE]` clauses of `Model.merge`. */\nexport class MergeActionBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Join condition between target and source.\n *\n * @param definition - Model definition.\n * @param where - `on` option.\n * @returns Condition.\n * @throws Error for a missing condition.\n */\n on(definition: ModelDefinition, where: unknown): ExprNode {\n const on = this.#condition(definition, where);\n if (on === undefined) {\n throw new Error('merge: on condition is required');\n }\n return on;\n }\n\n /**\n * WHEN clauses in order: matched, not matched, not matched by source.\n *\n * @param definition - Model definition.\n * @param options - Merge options.\n * @param source - MERGE source.\n * @returns WHEN clauses.\n * @throws Error without any WHEN clause.\n */\n whens(\n definition: ModelDefinition,\n options: MergeOptions<unknown>,\n source: MergeNode['source'],\n ): readonly MergeWhen[] {\n const when: readonly MergeWhen[] = [\n ...asArray(options.whenMatched).map((action) => this.#matched('MATCHED', definition, action)),\n ...asArray(options.whenNotMatched).map((action) =>\n this.#notMatched(definition, source, action),\n ),\n ...asArray(options.whenNotMatchedBySource).map((action) =>\n this.#matched('NOT MATCHED BY SOURCE', definition, action),\n ),\n ];\n if (when.length === 0) {\n throw new Error('merge: at least one WHEN clause is required');\n }\n return when;\n }\n\n #matched(\n match: MergeWhen['match'],\n definition: ModelDefinition,\n action: MergeMatchedAction<unknown>,\n ): MergeWhen {\n const extra = this.#condition(definition, action.where);\n return {\n match,\n ...(extra === undefined ? {} : { condition: extra }),\n action: this.#matchedAction(definition, action),\n };\n }\n\n #notMatched(\n definition: ModelDefinition,\n source: MergeNode['source'],\n action: MergeInsertAction<unknown>,\n ): MergeWhen {\n const extra = this.#condition(definition, action.where);\n return {\n match: 'NOT MATCHED',\n ...(extra === undefined ? {} : { condition: extra }),\n action:\n action.insert === undefined\n ? { kind: 'nothing' }\n : this.#insertAction(definition, source, action.insert as true | Values),\n };\n }\n\n #insertAction(\n definition: ModelDefinition,\n source: MergeNode['source'],\n insert: true | Values,\n ): MergeWhen['action'] {\n const ctx = this.#columns.whereCompiler(definition, undefined, undefined);\n const values = insert === true ? MergeActionBuilder.#sourceValues(definition, source) : insert;\n const items = this.#columns.setItems(\n definition,\n timestamps(definition, values, true),\n new WhereCompiler({ ...ctx.context, tableAlias: source.alias }),\n );\n return {\n kind: 'insert',\n columns: items.map((item) => item.column),\n values: items.map((item) => item.value),\n };\n }\n\n #matchedAction(\n definition: ModelDefinition,\n action: MergeMatchedAction<unknown>,\n ): MergeWhen['action'] {\n if (action.delete === true) {\n return { kind: 'delete' };\n }\n if (action.update !== undefined) {\n return {\n kind: 'update',\n set: this.#columns.setItems(\n definition,\n timestamps(definition, action.update as Values, false),\n this.#columns.whereCompiler(definition, definition.name),\n ),\n };\n }\n return { kind: 'nothing' };\n }\n\n #condition(definition: ModelDefinition, where: unknown): ExprNode | undefined {\n return WhereCompiler.isEmpty(where)\n ? undefined\n : this.#columns.whereCompiler(definition, definition.name).compile(where);\n }\n\n /** `insert: true` copies same-named source columns as `\"source\".\"field\"` references. */\n static #sourceValues(definition: ModelDefinition, source: MergeNode['source']): Values {\n return Object.fromEntries(\n sourceColumns(source)\n .filter((field) => definition.fieldToAttribute.has(field))\n .map((field) => [\n definition.fieldToAttribute.get(field) ?? field,\n literal(`${SqlCompiler.quoteIdent(source.alias)}.${SqlCompiler.quoteIdent(field)}`),\n ]),\n );\n }\n}\n","import type { DataType } from '../data-types/data-types.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport type { PartitionKey } from './partition-types.ts';\nimport type { TableName } from './sql-literal.ts';\n\n/** `Deferrable` setting of a foreign key or transaction (Sequelize v6 `Deferrable`). */\nexport type DeferrableValue = Readonly<{\n /** SQL of the mode, e.g. `DEFERRABLE INITIALLY DEFERRED`. */\n sql: string;\n}>;\n\n/**\n * Deferrable constraint modes (Sequelize v6 `Deferrable`).\n *\n * @example\n * ```ts\n * await queryInterface.addColumn('posts', 'userId', {\n * type: DataTypes.INTEGER,\n * references: { model: 'Users', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED },\n * });\n * ```\n */\nexport const Deferrable = {\n /** `DEFERRABLE INITIALLY IMMEDIATE`. */\n INITIALLY_IMMEDIATE: Object.freeze<DeferrableValue>({ sql: 'DEFERRABLE INITIALLY IMMEDIATE' }),\n /** `DEFERRABLE INITIALLY DEFERRED`. */\n INITIALLY_DEFERRED: Object.freeze<DeferrableValue>({ sql: 'DEFERRABLE INITIALLY DEFERRED' }),\n /** `NOT DEFERRABLE`. */\n NOT: Object.freeze<DeferrableValue>({ sql: 'NOT DEFERRABLE' }),\n} as const;\n\n/** Column definition as used by DDL builders. */\nexport type ColumnDefinition = Readonly<{\n name: string;\n field: string;\n type: DataType;\n allowNull: boolean;\n primaryKey: boolean;\n autoIncrement: boolean;\n defaultValue: unknown;\n unique: AttributeDefinition['unique'];\n comment: string | undefined;\n references: AttributeDefinition['references'];\n onDelete: string | undefined;\n onUpdate: string | undefined;\n identity: 'always' | 'byDefault' | undefined;\n generated: AttributeDefinition['generated'];\n}>;\n\n/** Modifiers shared by every index element. */\ntype IndexElementModifiers = Readonly<{\n /** `ASC` / `DESC`. */\n order?: 'ASC' | 'DESC';\n /** `NULLS FIRST` / `NULLS LAST`. PostgreSQL extension. */\n nulls?: 'FIRST' | 'LAST';\n /** Collation name (quoted identifier). */\n collate?: string;\n /** Operator class, e.g. `'jsonb_path_ops'`. */\n operator?: string;\n}>;\n\n/**\n * Index field: a column name, `{ name, order, nulls, collate, operator }` or an expression\n * `{ expression, ... }`. The `expression` is trusted SQL (not escaped): never build it from user\n * input. An index with an expression field needs an explicit `name`.\n */\nexport type IndexField =\n | string\n | (IndexElementModifiers &\n Readonly<{\n /** Column name. */\n name: string;\n /** Not used for a column field. */\n expression?: undefined;\n }>)\n | (IndexElementModifiers &\n Readonly<{\n /** Trusted SQL expression, wrapped in parentheses. */\n expression: string;\n /** Not used for an expression field. */\n name?: undefined;\n }>);\n\n/**\n * Options of `addIndex` and model `indexes` (Sequelize v6 `IndexesOptions`).\n *\n * @example\n * ```ts\n * const options: IndexOptions = {\n * fields: ['email'],\n * unique: true,\n * where: { active: true },\n * using: 'btree',\n * };\n * await queryInterface.addIndex('users', options);\n * ```\n */\nexport type IndexOptions = Readonly<{\n /** Indexed columns. */\n fields?: readonly IndexField[];\n /** Index name; default `underscore(<table>_<fields>)`. Required when a field is an expression. */\n name?: string;\n /** Unique index. */\n unique?: boolean;\n /** `NULLS NOT DISTINCT` for unique indexes. PostgreSQL extension. */\n nullsNotDistinct?: boolean;\n /** Index method: `btree`, `hash`, `gist`, `gin`, `brin`, ... */\n using?: string;\n /** Default operator class for all fields. */\n operator?: string;\n /** Partial index predicate. */\n where?: unknown;\n /** `CREATE INDEX CONCURRENTLY`. */\n concurrently?: boolean;\n /** Covering index columns (`INCLUDE (...)`). */\n include?: readonly string[];\n /** `IF NOT EXISTS`. */\n ifNotExists?: boolean;\n}>;\n\n/**\n * One element of an `exclude` constraint: an index field plus the operator it is compared with.\n * The `expression`, when used, is trusted SQL.\n */\nexport type ExcludeElement = Exclude<IndexField, string> &\n Readonly<{\n /** Exclusion operator, e.g. `'&&'` or `'='` (operator characters only). */\n with: string;\n }>;\n\n/**\n * Options of `addConstraint` (Sequelize v6).\n *\n * @example\n * ```ts\n * const options: ConstraintOptions = {\n * type: 'foreign key',\n * fields: ['userId'],\n * name: 'posts_user_fk',\n * references: { table: 'users', field: 'id' },\n * onDelete: 'CASCADE',\n * };\n * await queryInterface.addConstraint('posts', options);\n * ```\n */\nexport type ConstraintOptions = Readonly<{\n /** Constraint kind. */\n type:\n | 'check'\n | 'unique'\n | 'primary key'\n | 'foreign key'\n | 'exclude'\n | 'CHECK'\n | 'UNIQUE'\n | 'PRIMARY KEY'\n | 'FOREIGN KEY'\n | 'EXCLUDE';\n /** Constrained columns. Not used by `exclude` (see `exclude`). */\n fields?: readonly string[];\n /** Constraint name. */\n name?: string;\n /** Check condition, or the partial predicate of an `exclude` constraint (where object). */\n where?: unknown;\n /** Foreign key target. */\n references?: Readonly<{\n /** Referenced table. */ table: TableName;\n /** Referenced column. */ field: string;\n /** Referenced columns, replacing `field` (needed with `period`). */ fields?: readonly string[];\n }>;\n /** `ON DELETE` action. */\n onDelete?: string;\n /** `ON UPDATE` action. */\n onUpdate?: string;\n /** Deferrable mode. */\n deferrable?: DeferrableValue;\n /** `NULLS NOT DISTINCT` for unique constraints. PostgreSQL extension. */\n nullsNotDistinct?: boolean;\n /** Exclusion elements: `{ column | expression, with }`. Required by `exclude`. PostgreSQL extension. */\n exclude?: readonly ExcludeElement[];\n /** Index method of an `exclude` constraint (`gist`, `spgist`, `btree`, ...). */\n using?: string;\n /** Covering columns of an `exclude` constraint (`INCLUDE (...)`). */\n include?: readonly string[];\n /** Last field of a `unique` / `primary key` constraint is `WITHOUT OVERLAPS` (temporal key, PostgreSQL 18). */\n withoutOverlaps?: boolean;\n /** Last field (and last referenced field) of a foreign key is `PERIOD` (PostgreSQL 18). */\n period?: boolean;\n /** `false` adds `NOT ENFORCED` (check and foreign key, PostgreSQL 18). */\n enforced?: boolean;\n /** Adds `NOT VALID` (check and foreign key only); run `validateConstraint` later. PostgreSQL extension. */\n notValid?: boolean;\n}>;\n\n/** Options of a column inside `CREATE TABLE` / `ADD COLUMN`. */\nexport type ColumnSqlOptions = Readonly<{ inlinePrimaryKey?: boolean; defaultSchema?: string }>;\n\n/** Options of `CREATE TABLE`. */\nexport type CreateTableOptions = Readonly<{\n comment?: string;\n unlogged?: boolean;\n temporary?: boolean;\n defaultSchema?: string;\n ifNotExists?: boolean;\n partitionBy?: PartitionKey;\n}>;\n","import { Deferrable, type DeferrableValue } from './ddl-types.ts';\n\nconst ACTIONS: ReadonlySet<string> = new Set([\n 'CASCADE',\n 'SET NULL',\n 'SET DEFAULT',\n 'RESTRICT',\n 'NO ACTION',\n]);\n\nconst IDENTIFIER_PATTERN = /^[A-Za-z_][\\w]*$/;\n\nconst OPERATOR_PATTERN = /^[-+*/<>=~!@#%^&|`?]{1,63}$/;\n\nconst DEFERRABLE_SQL: ReadonlySet<string> = new Set(\n Object.values(Deferrable).map((value) => value.sql),\n);\n\n/**\n * Allowlists for the DDL keywords that cannot be quoted: referential actions, deferrable modes,\n * index methods and operator classes (ADR-020).\n *\n * @internal\n */\nexport class DdlGuards {\n /**\n * SQL of a `Deferrable` value; anything that is not one of them is rejected.\n *\n * @param value - Deferrable value.\n * @returns SQL of the mode.\n * @throws Error for anything but a `Deferrable` constant.\n */\n deferrableSql(value: DeferrableValue): string {\n if (!DEFERRABLE_SQL.has((value as { sql?: unknown } | undefined)?.sql as string)) {\n throw new Error(`Invalid deferrable: use one of the Deferrable constants`);\n }\n return value.sql;\n }\n\n /**\n * Normalized referential action (`ON DELETE` / `ON UPDATE`).\n *\n * @param action - Action as given.\n * @returns Upper-case action.\n * @throws Error for an action outside the allowlist.\n */\n action(action: string): string {\n const normalized = action.trim().toUpperCase();\n if (!ACTIONS.has(normalized)) {\n throw new Error(`Invalid referential action: ${action}`);\n }\n return normalized;\n }\n\n /**\n * A plain identifier word (index method, operator class), rendered unquoted.\n *\n * @param value - Word.\n * @param kind - Kind named in the error.\n * @returns The word.\n * @throws Error for anything but `[A-Za-z_][\\w]*`.\n */\n word(value: string, kind: string): string {\n if (!IDENTIFIER_PATTERN.test(value)) {\n throw new Error(`Invalid ${kind}: ${value}`);\n }\n return value;\n }\n\n /**\n * An operator symbol (EXCLUDE `WITH` operator), rendered unquoted.\n *\n * @param value - Operator such as `&&` or `=`.\n * @returns The operator.\n * @throws Error for anything but 1-63 operator characters, or one that opens a comment.\n */\n operator(value: string): string {\n if (!OPERATOR_PATTERN.test(value) || value.includes('--') || value.includes('/*')) {\n throw new Error(`Invalid operator: ${value}`);\n }\n return value;\n }\n\n /**\n * A whole number rendered into DDL (sequence bounds, cache size); anything else is rejected.\n *\n * @param value - Number or bigint.\n * @param kind - Kind named in the error.\n * @returns Decimal text of the number.\n * @throws Error for non-integers and unsafe numbers.\n */\n integer(value: number | bigint, kind: string): string {\n if (typeof value === 'bigint' || Number.isSafeInteger(value)) {\n return value.toString();\n }\n throw new Error(`Invalid ${kind}: expected a whole number`);\n }\n\n /**\n * ` ON DELETE ... ON UPDATE ... <deferrable>` suffix of a foreign key; empty parts are omitted.\n *\n * @param onDelete - `ON DELETE` action.\n * @param onUpdate - `ON UPDATE` action.\n * @param deferrable - Deferrable mode.\n * @returns SQL suffix.\n */\n foreignKeySuffix(\n onDelete: string | undefined,\n onUpdate: string | undefined,\n deferrable: DeferrableValue | undefined,\n ): string {\n return [\n onDelete === undefined ? '' : ` ON DELETE ${this.action(onDelete)}`,\n onUpdate === undefined ? '' : ` ON UPDATE ${this.action(onUpdate)}`,\n deferrable === undefined ? '' : ` ${this.deferrableSql(deferrable)}`,\n ].join('');\n }\n}\n","import { DefaultValueGenerator } from '../data-types/default-value-generator.ts';\nimport { SqlExpression } from '../expressions/methods.ts';\nimport type { AttributeDefinition } from '../model/model-definition.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport type { ColumnDefinition, ColumnSqlOptions, DeferrableValue } from './ddl-types.ts';\nimport type { EnumDdl } from './enum-ddl.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new DdlGuards();\n\nconst noContext = new WhereCompiler({ resolve: () => undefined });\n\nconst sqlLiteral = new SqlLiteral();\n\n/** Types whose object defaults are serialized to their text form before escaping. */\nconst SERIALIZED_DEFAULTS = /^(HSTORE|POINT|LINE|LSEG|BOX|PATH|POLYGON|CIRCLE)$/;\n\n/**\n * Column parts of DDL: the SQL type, `DEFAULT`, `REFERENCES`, column definitions and comments.\n *\n * @internal\n */\nexport class ColumnDdl {\n readonly #enums: EnumDdl;\n\n /**\n * @param enums - Enum type names.\n */\n constructor(enums: EnumDdl) {\n this.#enums = enums;\n }\n\n /**\n * Converts a normalized attribute to a column definition.\n *\n * @param attribute - Normalized attribute.\n * @returns Column definition.\n */\n columnOf(attribute: AttributeDefinition): ColumnDefinition {\n return {\n name: attribute.fieldName,\n field: attribute.field,\n type: attribute.type,\n allowNull: attribute.allowNull,\n primaryKey: attribute.primaryKey === true,\n autoIncrement: attribute.autoIncrement === true,\n defaultValue: attribute.defaultValue,\n unique: attribute.unique,\n comment: attribute.comment,\n references: attribute.references,\n onDelete: attribute.onDelete,\n onUpdate: attribute.onUpdate,\n identity: attribute.identity,\n generated: attribute.generated,\n };\n }\n\n /**\n * SQL type of a column (SERIAL for auto-increment integers, enum type names).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns SQL type.\n */\n columnType(table: TableName, column: ColumnDefinition): string {\n if (column.identity !== undefined) {\n return `${column.type.sqlType} GENERATED ${column.identity === 'always' ? 'ALWAYS' : 'BY DEFAULT'} AS IDENTITY`;\n }\n if (column.autoIncrement) {\n return this.#serialType(column);\n }\n if (column.type.key === 'ENUM') {\n return this.#enums.quotedType(table, column.field);\n }\n if (column.type.key === 'ARRAY' && column.type.subtype?.key === 'ENUM') {\n return `${this.#enums.quotedType(table, column.field)}[]`;\n }\n return column.type.sqlType;\n }\n\n /**\n * `DEFAULT ...` clause value.\n *\n * @param column - Column definition.\n * @returns SQL of the default, or `undefined` for client-side defaults.\n */\n defaultSql(column: ColumnDefinition): string | undefined {\n const value = column.defaultValue;\n if (value === undefined || column.autoIncrement || column.generated !== undefined) {\n return undefined;\n }\n if (value instanceof DefaultValueGenerator) {\n return value.key === 'NOW' ? 'now()' : undefined;\n }\n if (value instanceof SqlExpression) {\n return sqlLiteral.inlineExpr(noContext.toExpr(value));\n }\n if (column.type.isJson === true) {\n return sqlLiteral.escape(JSON.stringify(value));\n }\n return sqlLiteral.escape(\n SERIALIZED_DEFAULTS.test(column.type.key) ? column.type.serialize?.(value) : value,\n );\n }\n\n /**\n * `REFERENCES ...` clause.\n *\n * @param column - Column definition.\n * @param defaultSchema - Schema of the referenced table when it has none.\n * @returns SQL of the clause, or `undefined` without references.\n */\n referencesSql(column: ColumnDefinition, defaultSchema?: string): string | undefined {\n const references = column.references;\n if (references === undefined) {\n return undefined;\n }\n const key = typeof references === 'string' ? 'id' : (references.key ?? 'id');\n const deferrable =\n typeof references === 'object'\n ? (references as { deferrable?: DeferrableValue }).deferrable\n : undefined;\n const target = `REFERENCES ${sqlLiteral.quoteTable(this.#referencedTable(references), defaultSchema)} (${SqlCompiler.quoteIdent(key)})`;\n return `${target}${guards.foreignKeySuffix(column.onDelete, column.onUpdate, deferrable)}`;\n }\n\n /**\n * One column of `CREATE TABLE` / `ADD COLUMN`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @param options - `inlinePrimaryKey` and the default schema of references.\n * @returns Column SQL.\n */\n columnSql(table: TableName, column: ColumnDefinition, options: ColumnSqlOptions = {}): string {\n return [\n `${SqlCompiler.quoteIdent(column.field)} ${this.columnType(table, column)}`,\n column.allowNull || column.primaryKey ? '' : ' NOT NULL',\n options.inlinePrimaryKey === true && column.primaryKey ? ' PRIMARY KEY' : '',\n this.#generatedSql(column),\n this.#uniqueSql(column.unique),\n this.#prefixed(' DEFAULT ', this.defaultSql(column)),\n this.#prefixed(' ', this.referencesSql(column, options.defaultSchema)),\n ].join('');\n }\n\n /**\n * `COMMENT ON COLUMN` for a column with a comment.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name and comment.\n * @returns The statement, or nothing without a comment.\n */\n commentSql(\n table: TableName,\n column: Readonly<{ field: string; comment?: string }>,\n ): readonly string[] {\n return column.comment === undefined\n ? []\n : [\n `COMMENT ON COLUMN ${sqlLiteral.quoteTable(table)}.${SqlCompiler.quoteIdent(column.field)} IS ${sqlLiteral.escape(column.comment)}`,\n ];\n }\n\n /**\n * Whether a `unique` option has `nullsNotDistinct: true`.\n *\n * @param unique - `unique` option of a column.\n * @returns The flag.\n */\n nullsNotDistinct(unique: ColumnDefinition['unique']): boolean {\n return (\n typeof unique === 'object' &&\n unique !== null &&\n (unique as { nullsNotDistinct?: boolean }).nullsNotDistinct === true\n );\n }\n\n #serialType(column: ColumnDefinition): string {\n return column.type.key === 'BIGINT'\n ? 'BIGSERIAL'\n : column.type.key === 'SMALLINT'\n ? 'SMALLSERIAL'\n : 'SERIAL';\n }\n\n #generatedSql(column: ColumnDefinition): string {\n return column.generated === undefined\n ? ''\n : ` GENERATED ALWAYS AS (${sqlLiteral.inlineExpr(noContext.toExpr(column.generated.as))}) ${column.generated.stored === false ? 'VIRTUAL' : 'STORED'}`;\n }\n\n #uniqueSql(unique: ColumnDefinition['unique']): string {\n const unnamed =\n unique === true ||\n (typeof unique === 'object' && unique !== null && unique.name === undefined);\n if (!unnamed) {\n return '';\n }\n return this.nullsNotDistinct(unique) ? ' UNIQUE NULLS NOT DISTINCT' : ' UNIQUE';\n }\n\n #prefixed(prefix: string, sql: string | undefined): string {\n return sql === undefined ? '' : `${prefix}${sql}`;\n }\n\n #referencedTable(references: NonNullable<ColumnDefinition['references']>): TableName {\n return typeof references === 'string'\n ? references\n : typeof references.model === 'string'\n ? references.model\n : (references.model as Readonly<{ tableName: string; schema?: string }>);\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport type { IndexField } from './ddl-types.ts';\n\nconst guards = new DdlGuards();\n\n/**\n * One element of an index or EXCLUDE constraint: a quoted column or a trusted SQL expression with\n * collation, operator class, order and nulls ordering.\n *\n * @internal\n */\nexport class IndexElementDdl {\n /**\n * SQL of an element.\n *\n * @param field - Column name or field object.\n * @param operator - Default operator class.\n * @returns Element SQL.\n * @throws Error for an empty expression or an invalid operator class.\n */\n elementSql(field: IndexField, operator: string | undefined): string {\n if (typeof field === 'string') {\n return `${SqlCompiler.quoteIdent(field)}${this.#operatorClass(operator)}`;\n }\n return [\n field.expression === undefined\n ? SqlCompiler.quoteIdent(field.name)\n : this.#expression(field.expression),\n field.collate === undefined ? '' : ` COLLATE ${SqlCompiler.quoteIdent(field.collate)}`,\n this.#operatorClass(field.operator ?? operator),\n field.order === undefined ? '' : ` ${field.order === 'DESC' ? 'DESC' : 'ASC'}`,\n field.nulls === undefined ? '' : ` NULLS ${field.nulls === 'FIRST' ? 'FIRST' : 'LAST'}`,\n ].join('');\n }\n\n #expression(expression: string): string {\n if (typeof expression !== 'string' || expression.trim() === '') {\n throw new Error('Index expression must be a non-empty SQL string');\n }\n return `(${expression})`;\n }\n\n #operatorClass(operator: string | undefined): string {\n return operator === undefined ? '' : ` ${guards.word(operator, 'operator class')}`;\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport type { ConstraintOptions } from './ddl-types.ts';\nimport { IndexElementDdl } from './index-element-ddl.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new DdlGuards();\n\nconst elements = new IndexElementDdl();\n\nconst identity = new WhereCompiler({ resolve: (field) => ({ field }) });\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * `ALTER TABLE ... ADD CONSTRAINT` statements (check, unique, primary, foreign key and exclusion constraints).\n *\n * @internal\n */\nexport class ConstraintDdl {\n /**\n * `ALTER TABLE ... ADD CONSTRAINT` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Constraint definition.\n * @param defaultSchema - Schema used when a table reference has none.\n * @returns Statement.\n * @throws Error for an unknown constraint type, a foreign key without references, an `exclude`\n * without elements or a `notValid` on a constraint that cannot be `NOT VALID`.\n */\n addConstraintSql(table: TableName, options: ConstraintOptions, defaultSchema?: string): string {\n const type = options.type.toLowerCase();\n const name = options.name ?? this.#defaultName(table, this.#nameFields(type, options), type);\n const fields = this.#fieldList(type, options);\n const body = this.#body(type, fields, options, defaultSchema);\n return `ALTER TABLE ${sqlLiteral.quoteTable(table, defaultSchema)} ADD CONSTRAINT ${SqlCompiler.quoteIdent(name)} ${body}${this.#attributes(type, options)}`;\n }\n\n /**\n * `ALTER TABLE ... VALIDATE CONSTRAINT` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statement.\n */\n validateConstraintSql(table: TableName, name: string, defaultSchema?: string): string {\n return `ALTER TABLE ${sqlLiteral.quoteTable(table, defaultSchema)} VALIDATE CONSTRAINT ${SqlCompiler.quoteIdent(name)}`;\n }\n\n #nameFields(type: string, options: ConstraintOptions): readonly string[] {\n if (type !== 'exclude') {\n return options.fields ?? [];\n }\n return (options.exclude ?? []).map((element) => {\n const name = element.name;\n if (name === undefined) {\n throw new Error('An exclusion constraint on an expression requires an explicit name');\n }\n return name;\n });\n }\n\n #attributes(type: string, options: ConstraintOptions): string {\n const checkable = type === 'check' || type === 'foreign key';\n if ((options.notValid === true || options.enforced === false) && !checkable) {\n throw new Error('notValid and enforced apply to check and foreign key constraints only');\n }\n return `${options.enforced === false ? ' NOT ENFORCED' : ''}${options.notValid === true ? ' NOT VALID' : ''}`;\n }\n\n #fieldList(type: string, options: ConstraintOptions): string {\n const names = (options.fields ?? []).map(SqlCompiler.quoteIdent);\n if (options.withoutOverlaps === true) {\n this.#requireType(type, ['unique', 'primary key'], 'withoutOverlaps');\n return this.#withLast(names, (last) => `${last} WITHOUT OVERLAPS`);\n }\n if (options.period === true) {\n this.#requireType(type, ['foreign key'], 'period');\n return this.#withLast(names, (last) => `PERIOD ${last}`);\n }\n return names.join(', ');\n }\n\n #requireType(type: string, allowed: readonly string[], option: string): void {\n if (!allowed.includes(type)) {\n throw new Error(`${option} applies to ${allowed.join(' and ')} constraints only`);\n }\n }\n\n #withLast(names: readonly string[], mark: (last: string) => string): string {\n const last = names.at(-1);\n if (last === undefined) {\n throw new Error('withoutOverlaps and period need at least one field');\n }\n return [...names.slice(0, -1), mark(last)].join(', ');\n }\n\n #defaultName(table: TableName, fields: readonly string[], type: string): string {\n const suffix = type\n .replace(' ', '_')\n .replace('primary_key', 'pk')\n .replace('foreign_key', 'fkey')\n .replace('check', 'ck')\n .replace('unique', 'uk')\n .replace('exclude', 'excl');\n return `${sqlLiteral.tableParts(table).name}_${fields.join('_')}_${suffix}`;\n }\n\n #body(\n type: string,\n fields: string,\n options: ConstraintOptions,\n defaultSchema: string | undefined,\n ): string {\n switch (type) {\n case 'check':\n return `CHECK (${sqlLiteral.inlineExpr(identity.compile(options.where))})`;\n case 'unique':\n case 'primary key':\n return this.#key(type, fields, options);\n case 'foreign key':\n return this.#foreignKey(fields, options, defaultSchema);\n case 'exclude':\n return this.#exclude(options);\n default:\n throw new Error(`Constraint type must be specified through options.type: ${options.type}`);\n }\n }\n\n #key(type: string, fields: string, options: ConstraintOptions): string {\n if (type === 'primary key') {\n return `PRIMARY KEY (${fields})`;\n }\n return `UNIQUE${options.nullsNotDistinct === true ? ' NULLS NOT DISTINCT' : ''} (${fields})`;\n }\n\n #foreignKey(\n fields: string,\n options: ConstraintOptions,\n defaultSchema: string | undefined,\n ): string {\n if (options.references === undefined) {\n throw new Error('Foreign key constraint requires references');\n }\n const target = `FOREIGN KEY (${fields}) REFERENCES ${sqlLiteral.quoteTable(options.references.table, defaultSchema)} (${this.#referenced(options.references, options.period === true)})`;\n return `${target}${guards.foreignKeySuffix(options.onDelete, options.onUpdate, options.deferrable)}`;\n }\n\n #referenced(references: NonNullable<ConstraintOptions['references']>, period: boolean): string {\n const names = (references.fields ?? [references.field]).map(SqlCompiler.quoteIdent);\n return period ? this.#withLast(names, (last) => `PERIOD ${last}`) : names.join(', ');\n }\n\n #exclude(options: ConstraintOptions): string {\n const items = options.exclude ?? [];\n if (items.length === 0) {\n throw new Error('Exclusion constraint requires exclude elements');\n }\n const list = items\n .map((item) => `${elements.elementSql(item, undefined)} WITH ${guards.operator(item.with)}`)\n .join(', ');\n return [\n 'EXCLUDE',\n options.using === undefined ? '' : ` USING ${guards.word(options.using, 'index method')}`,\n ` (${list})`,\n this.#excludeTail(options),\n ].join('');\n }\n\n #excludeTail(options: ConstraintOptions): string {\n return [\n options.include === undefined || options.include.length === 0\n ? ''\n : ` INCLUDE (${options.include.map(SqlCompiler.quoteIdent).join(', ')})`,\n options.where === undefined\n ? ''\n : ` WHERE (${sqlLiteral.inlineExpr(identity.compile(options.where))})`,\n options.deferrable === undefined ? '' : ` ${guards.deferrableSql(options.deferrable)}`,\n ].join('');\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport type { ColumnDefinition } from './ddl-types.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * PostgreSQL enum types of `ENUM` and `ARRAY(ENUM)` columns (`enum_<table>_<column>`, v6).\n *\n * @internal\n */\nexport class EnumDdl {\n /**\n * Name of the PostgreSQL enum type of a column (`enum_<table>_<column>`, v6).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param field - Column name.\n * @returns Unquoted enum type name.\n */\n typeName(table: TableName, field: string): string {\n return `enum_${sqlLiteral.tableParts(table).name}_${field}`;\n }\n\n /**\n * Quoted, schema-qualified enum type of a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param field - Column name.\n * @returns Quoted type name.\n */\n quotedType(table: TableName, field: string): string {\n const { schema } = sqlLiteral.tableParts(table);\n const name = SqlCompiler.quoteIdent(this.typeName(table, field));\n return schema === undefined ? name : `${SqlCompiler.quoteIdent(schema)}.${name}`;\n }\n\n /**\n * `CREATE TYPE ... AS ENUM` wrapped so an existing type is not an error (v6).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns Statement, or `undefined` for non-enum columns.\n */\n createSql(table: TableName, column: ColumnDefinition): string | undefined {\n const values = this.#values(column);\n if (values === undefined) {\n return undefined;\n }\n const body = `CREATE TYPE ${this.quotedType(table, column.field)} AS ENUM(${values.map((value) => sqlLiteral.escape(value)).join(', ')}); EXCEPTION WHEN duplicate_object THEN null;`;\n return `DO ${sqlLiteral.escape(`BEGIN ${body} END`)}`;\n }\n\n /**\n * `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for every enum value of a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns Statements; empty for non-enum columns.\n */\n addValuesSql(table: TableName, column: ColumnDefinition): readonly string[] {\n return (this.#values(column) ?? []).map(\n (value) =>\n `ALTER TYPE ${this.quotedType(table, column.field)} ADD VALUE IF NOT EXISTS ${sqlLiteral.escape(value)}`,\n );\n }\n\n #values(column: ColumnDefinition): readonly string[] | undefined {\n return column.type.key === 'ENUM'\n ? column.type.values\n : column.type.subtype?.key === 'ENUM'\n ? column.type.subtype.values\n : undefined;\n }\n}\n","import inflection from 'inflection';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport type { IndexField, IndexOptions } from './ddl-types.ts';\nimport { IndexElementDdl } from './index-element-ddl.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new DdlGuards();\n\nconst elements = new IndexElementDdl();\n\nconst identity = new WhereCompiler({ resolve: (field) => ({ field }) });\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * `CREATE INDEX` statements and v6 default index names.\n *\n * @internal\n */\nexport class IndexDdl {\n /**\n * Default index name (v6 `Utils.nameIndex`).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param fields - Indexed fields.\n * @returns Index name.\n */\n indexName(table: TableName, fields: readonly IndexField[]): string {\n const names = fields.map((field) => {\n const name = typeof field === 'string' ? field : field.name;\n if (name === undefined) {\n throw new Error('An index on an expression requires an explicit name');\n }\n return name;\n });\n return inflection\n .underscore(`${sqlLiteral.tableParts(table).name}_${names.join('_')}`)\n .replaceAll('.', '_');\n }\n\n /**\n * `CREATE [UNIQUE] INDEX` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Index options.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statement.\n * @throws Error without fields, with an invalid method / operator class, or with an expression\n * field and no name.\n */\n createIndexSql(table: TableName, options: IndexOptions, defaultSchema?: string): string {\n const fields = options.fields ?? [];\n if (fields.length === 0) {\n throw new Error('Index requires at least one field');\n }\n const columns = fields.map((field) => elements.elementSql(field, options.operator)).join(', ');\n const where = this.#whereSql(options.where);\n return [\n this.#head(options),\n `${SqlCompiler.quoteIdent(options.name ?? this.indexName(table, fields))} ON ${sqlLiteral.quoteTable(table, defaultSchema)}`,\n options.using === undefined ? '' : ` USING ${guards.word(options.using, 'index method')}`,\n ` (${columns})`,\n options.include === undefined || options.include.length === 0\n ? ''\n : ` INCLUDE (${options.include.map(SqlCompiler.quoteIdent).join(', ')})`,\n options.unique === true && options.nullsNotDistinct === true ? ' NULLS NOT DISTINCT' : '',\n where,\n ].join('');\n }\n\n #whereSql(where: unknown): string {\n return where === undefined ? '' : ` WHERE ${sqlLiteral.inlineExpr(identity.compile(where))}`;\n }\n\n #head(options: IndexOptions): string {\n return `CREATE ${options.unique === true ? 'UNIQUE ' : ''}INDEX ${options.concurrently === true ? 'CONCURRENTLY ' : ''}${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}`;\n }\n}\n","/** Partitioning method of a partitioned table. */\nexport type PartitionStrategy = 'range' | 'list' | 'hash';\n\n/** Marker of a `MINVALUE` / `MAXVALUE` bound inside a range partition bound. */\nexport type PartitionBoundMarker = Readonly<{\n /** Keyword the marker renders as. */\n keyword: 'MINVALUE' | 'MAXVALUE';\n}>;\n\n/**\n * `MINVALUE` and `MAXVALUE` for the `from` / `to` lists of a range partition bound. They are\n * markers, not strings, so a string value can never be read as a keyword.\n *\n * @example\n * ```ts\n * await queryInterface.createPartition('events', 'events_old', {\n * from: [PartitionBound.MINVALUE],\n * to: ['2020-01-01'],\n * });\n * ```\n */\nexport const PartitionBound = {\n /** Lowest possible value of a range column. */\n MINVALUE: Object.freeze<PartitionBoundMarker>({ keyword: 'MINVALUE' }),\n /** Highest possible value of a range column. */\n MAXVALUE: Object.freeze<PartitionBoundMarker>({ keyword: 'MAXVALUE' }),\n} as const;\n\n/** Element of a partition key: a column, or an expression (trusted SQL) with collation and operator class. */\nexport type PartitionKeyElement =\n | string\n | Readonly<{\n /** Column name. */\n name: string;\n /** Collation name. */\n collate?: string;\n /** Operator class. */\n operator?: string;\n /** Not used for a column element. */\n expression?: undefined;\n }>\n | Readonly<{\n /** Trusted SQL expression, wrapped in parentheses. */\n expression: string;\n /** Collation name. */\n collate?: string;\n /** Operator class. */\n operator?: string;\n /** Not used for an expression element. */\n name?: undefined;\n }>;\n\n/**\n * Partition key of `createTable({ partitionBy })` and of a sub-partitioned partition.\n *\n * @example\n * ```ts\n * const key: PartitionKey = { strategy: 'range', columns: ['createdAt'] };\n * await queryInterface.createTable('events', { createdAt: DataTypes.DATE }, { partitionBy: key });\n * ```\n */\nexport type PartitionKey = Readonly<{\n /** `'range'`, `'list'` or `'hash'`. */\n strategy: PartitionStrategy;\n /** Key columns or expressions. */\n columns: readonly PartitionKeyElement[];\n}>;\n\n/**\n * Bounds of a partition: `{ in }` (list), `{ from, to }` (range; `PartitionBound.MINVALUE` /\n * `MAXVALUE` allowed), `{ modulus, remainder }` (hash) or `{ default: true }`. Values are rendered\n * as literals.\n *\n * @example\n * ```ts\n * const bound: PartitionBoundSpec = { from: ['2026-01-01'], to: ['2027-01-01'] };\n * await queryInterface.createPartition('events', 'events_2026', bound);\n * ```\n */\nexport type PartitionBoundSpec =\n | Readonly<{\n /** List partition: the values the partition holds. */\n in: readonly unknown[];\n }>\n | Readonly<{\n /** Range partition: inclusive lower bound, one value per key column. */\n from: readonly unknown[];\n /** Range partition: exclusive upper bound, one value per key column. */\n to: readonly unknown[];\n }>\n | Readonly<{\n /** Hash partition: modulus. */\n modulus: number;\n /** Hash partition: remainder, `0 <= remainder < modulus`. */\n remainder: number;\n }>\n | Readonly<{\n /** Default partition, receiving rows that match no other partition. */\n default: true;\n }>;\n","import { DdlGuards } from './ddl-guards.ts';\nimport { IndexElementDdl } from './index-element-ddl.ts';\nimport {\n PartitionBound,\n type PartitionBoundSpec,\n type PartitionKey,\n type PartitionStrategy,\n} from './partition-types.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new DdlGuards();\n\nconst elements = new IndexElementDdl();\n\nconst sqlLiteral = new SqlLiteral();\n\nconst STRATEGIES: ReadonlySet<string> = new Set<PartitionStrategy>(['range', 'list', 'hash']);\n\n/**\n * Options of `createPartition`.\n *\n * @example\n * ```ts\n * await queryInterface.createPartition(\n * 'events',\n * 'events_2026',\n * { from: ['2026-01-01'], to: ['2027-01-01'] },\n * { ifNotExists: true, partitionBy: { strategy: 'list', columns: ['kind'] } },\n * );\n * ```\n */\nexport type CreatePartitionOptions = Readonly<{\n /** Makes the partition itself partitioned. */\n partitionBy?: PartitionKey;\n /** `IF NOT EXISTS`. */\n ifNotExists?: boolean;\n}>;\n\n/**\n * Options of `detachPartition`.\n *\n * @example\n * ```ts\n * await queryInterface.detachPartition('events', 'events_2026', { concurrently: true });\n * ```\n */\nexport type DetachPartitionOptions = Readonly<{\n /** `DETACH PARTITION ... CONCURRENTLY` (cannot run inside a transaction). */\n concurrently?: boolean;\n /** `DETACH PARTITION ... FINALIZE`, completing an interrupted concurrent detach. */\n finalize?: boolean;\n}>;\n\n/**\n * Declarative partitioning statements: `PARTITION BY`, `PARTITION OF`, `ATTACH` and `DETACH`.\n *\n * @internal\n */\nexport class PartitionDdl {\n /**\n * ` PARTITION BY ...` clause of `CREATE TABLE`.\n *\n * @param key - Strategy and key columns.\n * @returns Clause with a leading space.\n * @throws Error for an unknown strategy, no columns or an invalid operator class.\n */\n partitionBySql(key: PartitionKey): string {\n if (!STRATEGIES.has(key.strategy)) {\n throw new Error(`Invalid partition strategy: ${String(key.strategy)}`);\n }\n if (key.columns.length === 0) {\n throw new Error('Partition key requires at least one column');\n }\n const columns = key.columns.map((column) => elements.elementSql(column, undefined)).join(', ');\n return ` PARTITION BY ${key.strategy.toUpperCase()} (${columns})`;\n }\n\n /**\n * `CREATE TABLE ... PARTITION OF` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - New partition name.\n * @param bound - Bounds.\n * @param options - Sub-partitioning and `ifNotExists`.\n * @returns Statement.\n */\n createPartitionSql(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options: CreatePartitionOptions = {},\n ): string {\n const head = `CREATE TABLE ${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}${sqlLiteral.quoteTable(partition)}`;\n const sub = options.partitionBy === undefined ? '' : this.partitionBySql(options.partitionBy);\n return `${head} PARTITION OF ${sqlLiteral.quoteTable(parent)} ${this.boundSql(bound)}${sub}`;\n }\n\n /**\n * `ALTER TABLE ... ATTACH PARTITION` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - Existing table to attach.\n * @param bound - Bounds.\n * @returns Statement.\n */\n attachPartitionSql(parent: TableName, partition: TableName, bound: PartitionBoundSpec): string {\n return `ALTER TABLE ${sqlLiteral.quoteTable(parent)} ATTACH PARTITION ${sqlLiteral.quoteTable(partition)} ${this.boundSql(bound)}`;\n }\n\n /**\n * `ALTER TABLE ... DETACH PARTITION` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - Partition to detach.\n * @param options - `concurrently` or `finalize`.\n * @returns Statement.\n * @throws Error when both options are set.\n */\n detachPartitionSql(\n parent: TableName,\n partition: TableName,\n options: DetachPartitionOptions = {},\n ): string {\n if (options.concurrently === true && options.finalize === true) {\n throw new Error('concurrently and finalize cannot be combined');\n }\n const mode =\n options.concurrently === true\n ? ' CONCURRENTLY'\n : options.finalize === true\n ? ' FINALIZE'\n : '';\n return `ALTER TABLE ${sqlLiteral.quoteTable(parent)} DETACH PARTITION ${sqlLiteral.quoteTable(partition)}${mode}`;\n }\n\n /**\n * `FOR VALUES ...` or `DEFAULT` clause.\n *\n * @param bound - Bounds.\n * @returns Clause.\n * @throws Error for an unknown bound shape or non-integer modulus / remainder.\n */\n boundSql(bound: PartitionBoundSpec): string {\n if ('default' in bound) {\n return 'DEFAULT';\n }\n if ('in' in bound) {\n return `FOR VALUES IN (${this.#values(bound.in)})`;\n }\n if ('from' in bound) {\n return `FOR VALUES FROM (${this.#values(bound.from)}) TO (${this.#values(bound.to)})`;\n }\n if ('modulus' in bound) {\n return `FOR VALUES WITH (MODULUS ${guards.integer(bound.modulus, 'modulus')}, REMAINDER ${guards.integer(bound.remainder, 'remainder')})`;\n }\n throw new Error(\n 'Partition bound must be { in }, { from, to }, { modulus, remainder } or { default: true }',\n );\n }\n\n #values(values: readonly unknown[]): string {\n if (values.length === 0) {\n throw new Error('Partition bound needs at least one value');\n }\n return values\n .map((value) =>\n value === PartitionBound.MINVALUE || value === PartitionBound.MAXVALUE\n ? (value as { keyword: string }).keyword\n : sqlLiteral.escape(value),\n )\n .join(', ');\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport type { ColumnDdl } from './column-ddl.ts';\nimport type { ColumnDefinition, CreateTableOptions } from './ddl-types.ts';\nimport type { EnumDdl } from './enum-ddl.ts';\nimport { PartitionDdl } from './partition-ddl.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst sqlLiteral = new SqlLiteral();\n\nconst partitions = new PartitionDdl();\n\ntype NamedUniqueKey = Readonly<{ fields: readonly string[]; nullsNotDistinct: boolean }>;\n\n/**\n * `CREATE TABLE` (with enum types, keys and comments) and `ALTER COLUMN` statements.\n *\n * @internal\n */\nexport class TableDdl {\n readonly #columns: ColumnDdl;\n readonly #enums: EnumDdl;\n\n /**\n * @param columns - Column parts.\n * @param enums - Enum types.\n */\n constructor(columns: ColumnDdl, enums: EnumDdl) {\n this.#columns = columns;\n this.#enums = enums;\n }\n\n /**\n * Statements creating a table: enum types, `CREATE TABLE IF NOT EXISTS`, comments.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param columns - Column definitions.\n * @param options - Table comment, default schema and `ifNotExists` (default true).\n * @returns Statements in execution order.\n */\n createTableSql(\n table: TableName,\n columns: readonly ColumnDefinition[],\n options: CreateTableOptions = {},\n ): readonly string[] {\n this.#checkPersistence(table, options);\n const defaultSchema = options.temporary === true ? undefined : options.defaultSchema;\n const body = this.#tableBody(table, columns, defaultSchema);\n const qualified = sqlLiteral.quoteTable(table, defaultSchema);\n return [\n ...columns\n .map((column) => this.#enums.createSql(table, column))\n .filter((sql): sql is string => sql !== undefined),\n `CREATE ${this.#persistence(options)}TABLE ${options.ifNotExists === false ? '' : 'IF NOT EXISTS '}${qualified} (${body})${options.partitionBy === undefined ? '' : partitions.partitionBySql(options.partitionBy)}`,\n ...(options.comment === undefined\n ? []\n : [`COMMENT ON TABLE ${qualified} IS ${sqlLiteral.escape(options.comment)}`]),\n ...columns.flatMap((column) => this.#columns.commentSql(table, column)),\n ];\n }\n\n /**\n * `ALTER TABLE ... ALTER COLUMN` statements bringing a column to its definition (v6 changeColumn).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statements in execution order.\n */\n changeColumnSql(\n table: TableName,\n column: ColumnDefinition,\n defaultSchema?: string,\n ): readonly string[] {\n const qualified = sqlLiteral.quoteTable(table, defaultSchema);\n const target = `ALTER TABLE ${qualified} ALTER COLUMN ${SqlCompiler.quoteIdent(column.field)}`;\n const value = this.#columns.defaultSql(column);\n const enumSql = this.#enums.createSql(table, column);\n const type = this.#columns.columnType(table, { ...column, autoIncrement: false });\n return [\n `${target} ${column.allowNull ? 'DROP NOT NULL' : 'SET NOT NULL'}`,\n ...(column.autoIncrement === true && value === undefined\n ? []\n : [value === undefined ? `${target} DROP DEFAULT` : `${target} SET DEFAULT ${value}`]),\n ...(enumSql === undefined ? [] : [enumSql]),\n `${target} TYPE ${type}${column.type.key === 'ENUM' ? ` USING (${SqlCompiler.quoteIdent(column.field)}::${type})` : ''}`,\n ...this.#columns.commentSql(table, column),\n ];\n }\n\n #persistence(options: CreateTableOptions): string {\n return options.temporary === true ? 'TEMPORARY ' : options.unlogged === true ? 'UNLOGGED ' : '';\n }\n\n #checkPersistence(table: TableName, options: CreateTableOptions): void {\n if (options.temporary === true && options.unlogged === true) {\n throw new Error('A table cannot be both temporary and unlogged');\n }\n if (options.temporary === true && sqlLiteral.tableParts(table).schema !== undefined) {\n throw new Error('A temporary table lives in the session schema and cannot have a schema');\n }\n }\n\n #tableBody(\n table: TableName,\n columns: readonly ColumnDefinition[],\n defaultSchema: string | undefined,\n ): string {\n const primaryKey = this.#primaryKeyConstraint(columns);\n const uniqueKeys = this.#uniqueKeyConstraints(columns);\n return [\n ...columns.map((column) =>\n this.#columns.columnSql(\n table,\n column,\n defaultSchema === undefined ? {} : { defaultSchema },\n ),\n ),\n ...uniqueKeys,\n ...primaryKey,\n ].join(', ');\n }\n\n #primaryKeyConstraint(columns: readonly ColumnDefinition[]): readonly string[] {\n const primaryKeys = columns\n .filter((column) => column.primaryKey)\n .map((column) => SqlCompiler.quoteIdent(column.field));\n return primaryKeys.length === 0 ? [] : [`PRIMARY KEY (${primaryKeys.join(', ')})`];\n }\n\n #uniqueKeyConstraints(columns: readonly ColumnDefinition[]): readonly string[] {\n return [...this.#namedUniqueKeys(columns)].map(\n ([name, key]) =>\n `CONSTRAINT ${SqlCompiler.quoteIdent(name)} UNIQUE${key.nullsNotDistinct ? ' NULLS NOT DISTINCT' : ''} (${key.fields.map(SqlCompiler.quoteIdent).join(', ')})`,\n );\n }\n\n /** Named unique keys: name → fields, with the NULLS NOT DISTINCT flag. */\n #namedUniqueKeys(columns: readonly ColumnDefinition[]): ReadonlyMap<string, NamedUniqueKey> {\n return columns.reduce((keys, column) => {\n const name = this.#uniqueName(column.unique);\n if (name === undefined) {\n return keys;\n }\n const existing = keys.get(name);\n const nullsNotDistinct =\n (existing?.nullsNotDistinct ?? false) || this.#columns.nullsNotDistinct(column.unique);\n return new Map([\n ...keys,\n [name, { fields: [...(existing?.fields ?? []), column.field], nullsNotDistinct }],\n ]);\n }, new Map<string, NamedUniqueKey>());\n }\n\n #uniqueName(unique: ColumnDefinition['unique']): string | undefined {\n return typeof unique === 'string'\n ? unique\n : typeof unique === 'object' && unique !== null\n ? unique.name\n : undefined;\n }\n}\n","import type { AttributeDefinition } from '../model/model-definition.ts';\nimport { ColumnDdl } from './column-ddl.ts';\nimport { ConstraintDdl } from './constraint-ddl.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport type {\n ColumnDefinition,\n ConstraintOptions,\n CreateTableOptions,\n DeferrableValue,\n IndexField,\n IndexOptions,\n} from './ddl-types.ts';\nimport { EnumDdl } from './enum-ddl.ts';\nimport { IndexDdl } from './index-ddl.ts';\nimport {\n PartitionDdl,\n type CreatePartitionOptions,\n type DetachPartitionOptions,\n} from './partition-ddl.ts';\nimport type { PartitionBoundSpec } from './partition-types.ts';\nimport type { TableName } from './sql-literal.ts';\nimport { TableDdl } from './table-ddl.ts';\n\nexport {\n Deferrable,\n type ColumnDefinition,\n type ConstraintOptions,\n type DeferrableValue,\n type ExcludeElement,\n type IndexField,\n type IndexOptions,\n} from './ddl-types.ts';\n\nconst guards = new DdlGuards();\n\n/**\n * Generates DDL statements (tables, columns, enum types, indexes, constraints, comments,\n * references) for PostgreSQL. Values are inlined as escaped literals.\n *\n * @internal\n */\nexport class DdlGenerator {\n readonly #enums = new EnumDdl();\n readonly #columns = new ColumnDdl(this.#enums);\n readonly #tables = new TableDdl(this.#columns, this.#enums);\n readonly #indexes = new IndexDdl();\n readonly #constraints = new ConstraintDdl();\n readonly #partitions = new PartitionDdl();\n\n /**\n * SQL of a `Deferrable` value; anything that is not one of them is rejected.\n *\n * @internal\n */\n static deferrableSql(value: DeferrableValue): string {\n return guards.deferrableSql(value);\n }\n\n /**\n * Converts a normalized attribute to a column definition.\n *\n * @param attribute - Normalized attribute.\n * @returns Column definition.\n */\n columnOf(attribute: AttributeDefinition): ColumnDefinition {\n return this.#columns.columnOf(attribute);\n }\n\n /**\n * Name of the PostgreSQL enum type of a column (`enum_<table>_<column>`, v6).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param field - Column name.\n * @returns Unquoted enum type name.\n */\n enumTypeName(table: TableName, field: string): string {\n return this.#enums.typeName(table, field);\n }\n\n /**\n * SQL type of a column (SERIAL for auto-increment integers, enum type names).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns SQL type.\n */\n columnType(table: TableName, column: ColumnDefinition): string {\n return this.#columns.columnType(table, column);\n }\n\n /**\n * `DEFAULT ...` clause value.\n *\n * @param column - Column definition.\n * @returns SQL of the default, or `undefined` for client-side defaults.\n */\n defaultSql(column: ColumnDefinition): string | undefined {\n return this.#columns.defaultSql(column);\n }\n\n /**\n * `REFERENCES ...` clause.\n *\n * @param column - Column definition.\n * @param defaultSchema - Schema of the referenced table when it has none.\n * @returns SQL of the clause, or `undefined` without references.\n */\n referencesSql(column: ColumnDefinition, defaultSchema?: string): string | undefined {\n return this.#columns.referencesSql(column, defaultSchema);\n }\n\n /**\n * One column of `CREATE TABLE` / `ADD COLUMN`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @param options - `inlinePrimaryKey` and the default schema of references.\n * @returns Column SQL.\n */\n columnSql(\n table: TableName,\n column: ColumnDefinition,\n options: Readonly<{ inlinePrimaryKey?: boolean; defaultSchema?: string }> = {},\n ): string {\n return this.#columns.columnSql(table, column, options);\n }\n\n /**\n * `CREATE TYPE ... AS ENUM` wrapped so an existing type is not an error (v6).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns Statement, or `undefined` for non-enum columns.\n */\n createEnumSql(table: TableName, column: ColumnDefinition): string | undefined {\n return this.#enums.createSql(table, column);\n }\n\n /**\n * Statements creating a table: enum types, `CREATE TABLE IF NOT EXISTS`, comments.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param columns - Column definitions.\n * @param options - Table comment, persistence (`unlogged`, `temporary`), default schema and `ifNotExists` (default true).\n * @returns Statements in execution order.\n */\n createTableSql(\n table: TableName,\n columns: readonly ColumnDefinition[],\n options: CreateTableOptions = {},\n ): readonly string[] {\n return this.#tables.createTableSql(table, columns, options);\n }\n\n /**\n * `COMMENT ON COLUMN` for a column with a comment.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name and comment.\n * @returns The statement, or nothing without a comment.\n */\n columnCommentSql(\n table: TableName,\n column: Readonly<{ field: string; comment?: string }>,\n ): readonly string[] {\n return this.#columns.commentSql(table, column);\n }\n\n /**\n * `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for every enum value of a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @returns Statements; empty for non-enum columns.\n */\n addEnumValuesSql(table: TableName, column: ColumnDefinition): readonly string[] {\n return this.#enums.addValuesSql(table, column);\n }\n\n /**\n * `ALTER TABLE ... ALTER COLUMN` statements bringing a column to its definition (v6 changeColumn).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column definition.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statements in execution order.\n */\n changeColumnSql(\n table: TableName,\n column: ColumnDefinition,\n defaultSchema?: string,\n ): readonly string[] {\n return this.#tables.changeColumnSql(table, column, defaultSchema);\n }\n\n /**\n * Default index name (v6 `Utils.nameIndex`).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param fields - Indexed fields.\n * @returns Index name.\n */\n indexName(table: TableName, fields: readonly IndexField[]): string {\n return this.#indexes.indexName(table, fields);\n }\n\n /**\n * `CREATE [UNIQUE] INDEX` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Index options.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statement.\n * @throws Error without fields or with an invalid method / operator class.\n */\n createIndexSql(table: TableName, options: IndexOptions, defaultSchema?: string): string {\n return this.#indexes.createIndexSql(table, options, defaultSchema);\n }\n\n /**\n * `ALTER TABLE ... ADD CONSTRAINT` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Constraint definition.\n * @param defaultSchema - Schema used when a table reference has none.\n * @returns Statement.\n * @throws Error for an unknown constraint type or a foreign key without references.\n */\n addConstraintSql(table: TableName, options: ConstraintOptions, defaultSchema?: string): string {\n return this.#constraints.addConstraintSql(table, options, defaultSchema);\n }\n\n /**\n * `ALTER TABLE ... VALIDATE CONSTRAINT` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param defaultSchema - Schema used when the table reference has none.\n * @returns Statement.\n */\n validateConstraintSql(table: TableName, name: string, defaultSchema?: string): string {\n return this.#constraints.validateConstraintSql(table, name, defaultSchema);\n }\n\n /**\n * `CREATE TABLE ... PARTITION OF` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - New partition name.\n * @param bound - Bounds.\n * @param options - Sub-partitioning and `ifNotExists`.\n * @returns Statement.\n */\n createPartitionSql(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options?: CreatePartitionOptions,\n ): string {\n return this.#partitions.createPartitionSql(parent, partition, bound, options);\n }\n\n /**\n * `ALTER TABLE ... ATTACH PARTITION` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - Existing table to attach.\n * @param bound - Bounds.\n * @returns Statement.\n */\n attachPartitionSql(parent: TableName, partition: TableName, bound: PartitionBoundSpec): string {\n return this.#partitions.attachPartitionSql(parent, partition, bound);\n }\n\n /**\n * `ALTER TABLE ... DETACH PARTITION` statement.\n *\n * @param parent - Partitioned table.\n * @param partition - Partition to detach.\n * @param options - `concurrently` or `finalize`.\n * @returns Statement.\n */\n detachPartitionSql(\n parent: TableName,\n partition: TableName,\n options?: DetachPartitionOptions,\n ): string {\n return this.#partitions.detachPartitionSql(parent, partition, options);\n }\n}\n","import { DdlGenerator } from '../ddl/ddl-generator.ts';\nimport { Subquery } from '../expressions/methods.ts';\nimport type { ExprNode, MergeNode } from '../sql/ast.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { WhereCompiler } from '../where/where.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { MergeOptions } from './merge-options.ts';\nimport type { AttributeDefinition, ModelDefinition } from './model-definition.ts';\n\ntype SourceRow = Readonly<Record<string, unknown>>;\n\nconst ddl = new DdlGenerator();\n\nconst castType = (definition: ModelDefinition, attribute: AttributeDefinition): string =>\n attribute.type.key === 'ENUM'\n ? [definition.schema, ddl.enumTypeName(definition.tableName, attribute.field)]\n .filter((part): part is string => part !== undefined)\n .map(SqlCompiler.quoteIdent)\n .join('.')\n : attribute.type.sqlType;\n\n/** Builds the `USING` source of `Model.merge`: a subquery or typed `VALUES` rows. */\nexport class MergeSourceBuilder {\n readonly #columns: AttributeColumns;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n }\n\n /**\n * Builds the MERGE source.\n *\n * @param definition - Model definition.\n * @param source - Source rows (plain objects) or a subquery.\n * @param alias - Alias of the source.\n * @returns MERGE source.\n * @throws Error for empty source rows.\n */\n build(\n definition: ModelDefinition,\n source: MergeOptions<unknown>['source'],\n alias: string,\n ): MergeNode['source'] {\n return source instanceof Subquery\n ? { kind: 'query', query: source.build(), alias }\n : this.#values(definition, source as readonly SourceRow[], alias);\n }\n\n #values(\n definition: ModelDefinition,\n rows: readonly SourceRow[],\n alias: string,\n ): MergeNode['source'] {\n if (rows.length === 0) {\n throw new Error('merge: source rows must not be empty');\n }\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))];\n const ctx = this.#columns.whereCompiler(definition, undefined);\n return {\n kind: 'values',\n alias,\n columns: columns.map((name) => definition.attributes.get(name)?.field ?? name),\n rows: rows.map((row) => columns.map((name) => this.#cell(definition, ctx, name, row[name]))),\n };\n }\n\n #cell(definition: ModelDefinition, ctx: WhereCompiler, name: string, raw: unknown): ExprNode {\n const attribute = definition.attributes.get(name);\n const value = this.#columns.value(attribute, raw ?? null, ctx);\n return attribute === undefined || value.kind !== 'param'\n ? value\n : { kind: 'cast', expr: value, type: castType(definition, attribute) };\n }\n}\n","import { SqlAst, type ExprNode, type MergeNode } from '../sql/ast.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport { MergeActionBuilder } from './merge-action-builder.ts';\nimport type { MergeOptions } from './merge-options.ts';\nimport { MergeSourceBuilder } from './merge-source-builder.ts';\nimport type { ModelDefinition } from './model-definition.ts';\n\nexport type { MergeInsertAction, MergeMatchedAction, MergeOptions } from './merge-options.ts';\n\nconst ast = new SqlAst();\n\n/**\n * Builds `MERGE INTO ... USING ...` statements of `Model.merge`: a VALUES or subquery source, the\n * join condition, `WHEN [NOT] MATCHED [BY SOURCE]` actions with timestamps, and RETURNING with\n * `merge_action()`.\n */\nexport class MergeQueryBuilder {\n /** Column carrying `merge_action()` in RETURNING. */\n static readonly ACTION = '__pgz_merge_action';\n\n readonly #columns: AttributeColumns;\n readonly #sources: MergeSourceBuilder;\n readonly #actions: MergeActionBuilder;\n\n /**\n * @param columns - Attribute to column mapping.\n */\n constructor(columns: AttributeColumns) {\n this.#columns = columns;\n this.#sources = new MergeSourceBuilder(columns);\n this.#actions = new MergeActionBuilder(columns);\n }\n\n /**\n * Builds a MERGE statement for a model.\n *\n * @param definition - Model definition.\n * @param options - Source, join condition and WHEN clauses.\n * @param returning - Return written rows with the action taken.\n * @returns MERGE node.\n * @throws Error for empty sources, a missing `on` condition or no WHEN clause.\n */\n build(\n definition: ModelDefinition,\n options: MergeOptions<unknown>,\n returning: boolean,\n ): MergeNode {\n const source = this.#sources.build(definition, options.source, options.as ?? 'source');\n const on = this.#actions.on(definition, options.on);\n const when = this.#actions.whens(definition, options, source);\n return {\n kind: 'merge',\n table: this.#columns.table(definition, definition.name),\n source,\n on,\n when,\n ...(returning ? { returning: this.#returning(definition) } : {}),\n };\n }\n\n #returning(definition: ModelDefinition): readonly ExprNode[] {\n return [\n {\n kind: 'alias',\n expr: ast.fnCall('merge_action', []),\n alias: MergeQueryBuilder.ACTION,\n } as const,\n ...this.#columns.returningAll(definition, definition.name),\n ];\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { InstanceState } from './instance-state.ts';\nimport { MergeQueryBuilder } from './merge-query-builder.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport { OnConflictBuilder } from './on-conflict-builder.ts';\nimport type { AnyModel, ModelStatic, Values } from './options.ts';\nimport { ReturningOld } from './returning-old.ts';\nimport type { RowMapper } from './row-mapper.ts';\n\ntype Row = Readonly<Record<string, unknown>>;\n\nconst sameValue = (left: unknown, right: unknown): boolean =>\n left === right ||\n (left instanceof Date && right instanceof Date\n ? left.getTime() === right.getTime()\n : JSON.stringify(left) === JSON.stringify(right) || String(left) === String(right));\n\n/**\n * Turns rows returned by writes into instances: strips the marker columns (inserted flag, merge\n * action, pre-statement values), records `wasInserted` / `oldValues`, and aligns `DO NOTHING`\n * results with the input rows.\n */\nexport class WrittenRows {\n readonly #registry: ModelRegistry;\n readonly #rows: RowMapper;\n readonly #returningOld: ReturningOld;\n\n /**\n * @param registry - Model definitions.\n * @param rows - Builds instances from rows.\n * @param returningOld - Reads pre-statement values.\n */\n constructor(registry: ModelRegistry, rows: RowMapper, returningOld: ReturningOld) {\n this.#registry = registry;\n this.#rows = rows;\n this.#returningOld = returningOld;\n }\n\n /**\n * Row without the marker columns added to RETURNING.\n *\n * @param row - Returned row.\n * @returns Row of model columns.\n */\n withoutMarkers(row: Row): Row {\n return Object.fromEntries(\n Object.entries(row).filter(\n ([key]) =>\n key !== OnConflictBuilder.INSERTED_FLAG &&\n key !== MergeQueryBuilder.ACTION &&\n !key.startsWith(ReturningOld.PREFIX),\n ),\n );\n }\n\n /**\n * Instance of a returned row; with `old`, its pre-statement values become `oldValues`.\n *\n * @param model - Model class.\n * @param row - Returned row.\n * @param old - Whether RETURNING included the pre-statement row.\n * @returns Instance.\n */\n instance<M extends AnyModel>(model: ModelStatic<M>, row: Row, old: boolean): M {\n const instance = this.#rows.instance(model, this.withoutMarkers(row));\n if (old) {\n InstanceState.of(instance).oldValues = this.#returningOld.previous(\n this.#registry.definition(model),\n row,\n );\n }\n return instance;\n }\n\n /**\n * Instance of a row returned by an INSERT with the inserted flag column; sets `wasInserted`.\n *\n * @param model - Model class.\n * @param row - Returned row.\n * @param old - Whether RETURNING included the pre-statement row.\n * @returns Instance.\n */\n inserted<M extends AnyModel>(model: ModelStatic<M>, row: Row, old: boolean): M {\n const instance = this.instance(model, row, old);\n InstanceState.of(instance).wasInserted = row[OnConflictBuilder.INSERTED_FLAG] === true;\n return instance;\n }\n\n /**\n * With `ON CONFLICT DO NOTHING` RETURNING has rows only for inserted records (in VALUES order).\n * Aligns them with the input rows; skipped records get `undefined`.\n *\n * @param definition - Model definition.\n * @param inputs - Inserted values.\n * @param returned - Returned rows.\n * @returns One returned row (or `undefined`) per input.\n */\n aligned(\n definition: ModelDefinition,\n inputs: readonly Values[],\n returned: readonly Row[],\n ): readonly (Row | undefined)[] {\n return inputs.reduce<Readonly<{ aligned: readonly (Row | undefined)[]; next: number }>>(\n (state, input) => {\n const row = returned[state.next];\n const parsed = row === undefined ? undefined : this.#rows.parse(definition, row);\n const matches = parsed !== undefined && this.#matches(definition, input, parsed);\n return matches\n ? { aligned: [...state.aligned, row], next: state.next + 1 }\n : { aligned: [...state.aligned, undefined], next: state.next };\n },\n { aligned: [], next: 0 },\n ).aligned;\n }\n\n #matches(definition: ModelDefinition, input: Values, parsed: Row): boolean {\n return Object.entries(input).every(\n ([name, value]) =>\n value === undefined ||\n (value === null && definition.attributes.get(name)?.autoIncrement === true) ||\n value instanceof SqlExpression ||\n !(name in parsed) ||\n sameValue(parsed[name], value),\n );\n }\n}\n","import { IncludeLoader } from '../associations/include-loader.ts';\nimport { IncludeQueryBuilder } from '../associations/include-query-builder.ts';\nimport { IncludeResolver } from '../associations/include-resolver.ts';\nimport { NestedCreator } from '../associations/nested-creator.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport { InstanceValidator } from '../validation/instance-validator.ts';\nimport { AttributeColumns } from './attribute-columns.ts';\nimport { CteBuilder } from './cte-builder.ts';\nimport { DeleteQueryBuilder } from './delete-query-builder.ts';\nimport { FindQueryBuilder } from './find-query-builder.ts';\nimport { InsertQueryBuilder } from './insert-query-builder.ts';\nimport { InstanceLifecycle } from './instance-lifecycle.ts';\nimport { SyncHooks } from './sync-hooks.ts';\nimport { InstanceState } from './instance-state.ts';\nimport { InstanceValues } from './instance-values.ts';\nimport { JoinSourceBuilder } from './join-source-builder.ts';\nimport { ModelRegistry } from './model-registry.ts';\nimport { ModelValues } from './model-values.ts';\nimport { OnConflictBuilder } from './on-conflict-builder.ts';\nimport type { AnyModel } from './options.ts';\nimport { ReturningOld } from './returning-old.ts';\nimport { RowMapper } from './row-mapper.ts';\nimport { SelectQueryBuilder } from './select-query-builder.ts';\nimport { UpdateQueryBuilder } from './update-query-builder.ts';\nimport { ValueCloner } from './value-cloner.ts';\nimport { WrittenRows } from './written-rows.ts';\n\n// Shared, stateless services of all models (internal wiring of `Model`).\n\n// Every model instance has an internal state; plain value objects never do.\nconst isInstance = (value: unknown): value is AnyModel => InstanceState.has(value);\n\nexport const registry = new ModelRegistry();\nexport const attributeColumns = new AttributeColumns();\nexport const modelValues = new ModelValues();\nexport const valueCloner = new ValueCloner();\nexport const rowMapper = new RowMapper(registry);\nexport const sqlCompiler = new SqlCompiler();\nexport const selectQueries = new SelectQueryBuilder(attributeColumns);\nexport const insertQueries = new InsertQueryBuilder(attributeColumns);\nexport const updateQueries = new UpdateQueryBuilder(attributeColumns);\nexport const deleteQueries = new DeleteQueryBuilder(attributeColumns);\nexport const joinSources = new JoinSourceBuilder(registry, attributeColumns);\nexport const cteBuilder = new CteBuilder(joinSources);\nexport const onConflictBuilder = new OnConflictBuilder(attributeColumns);\nexport const returningOld = new ReturningOld(attributeColumns, rowMapper);\nexport const writtenRows = new WrittenRows(registry, rowMapper, returningOld);\nexport const includeResolver = new IncludeResolver();\nexport const includeQueries = new IncludeQueryBuilder();\nexport const includeLoader = new IncludeLoader(includeResolver);\nexport const nestedCreator = new NestedCreator(includeResolver, isInstance);\nexport const findQueries = new FindQueryBuilder(selectQueries, cteBuilder, includeQueries);\nexport const instanceValues = new InstanceValues(registry, modelValues, isInstance);\nexport const lifecycle = new InstanceLifecycle({\n registry,\n values: modelValues,\n rows: rowMapper,\n columns: attributeColumns,\n selects: selectQueries,\n inserts: insertQueries,\n updates: updateQueries,\n deletes: deleteQueries,\n includes: includeResolver,\n nested: nestedCreator,\n validator: new InstanceValidator(),\n compiler: sqlCompiler,\n});\nexport const syncHooks = new SyncHooks(lifecycle);\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { InstanceState } from './instance-state.ts';\nimport type {\n AttributeDefinition,\n DefinitionOptions,\n ModelAttributes,\n} from './model-definition.ts';\nimport { lifecycle, registry } from './model-services.ts';\nimport type {\n AnyModel,\n BuildOptions,\n InitOptions,\n ModelStatic,\n QualifiedTableName,\n Values,\n} from './options.ts';\nimport type { RuntimeOwner } from './runtime.ts';\n\n/**\n * Core of every model: instance state, model metadata and `init`. Capabilities are added by the\n * model mixins; `Model` is the public class.\n *\n * @internal\n */\nexport class ModelBase {\n /**\n * @param values - Attribute values.\n * @param options - Build options.\n */\n constructor(values: Values = {}, options: BuildOptions = {}) {\n InstanceState.attach(this);\n lifecycle.initialize(this as unknown as AnyModel, values, options);\n }\n\n /**\n * For instances returned by `insert`, `create` / `bulkCreate` / `upsert` with `onConflict`:\n * true when the row was inserted, false when an existing row was updated (or nothing was\n * written). `undefined` otherwise. PostgreSQL extension.\n */\n get wasInserted(): boolean | undefined {\n return InstanceState.of(this).wasInserted;\n }\n\n /**\n * For instances returned with `returningOld: true`: attribute values of the row before the\n * statement, or `null` when the row did not exist (inserted). `undefined` otherwise. PostgreSQL 18+.\n */\n get oldValues(): Readonly<Record<string, unknown>> | null | undefined {\n return InstanceState.of(this).oldValues;\n }\n\n /** `Sequelize` instance the model belongs to. */\n get sequelize(): RuntimeOwner {\n return (this.constructor as typeof ModelBase).sequelize;\n }\n\n /** Name the model was registered under, as given by `modelName` in the init options (default: the class name). */\n static get modelName(): string {\n return registry.state(this).definition.name;\n }\n\n /** Name of the database table backing the model (pluralized model name unless `tableName` was set). */\n static get tableName(): string {\n return registry.state(this).definition.tableName;\n }\n\n /** Normalized attributes keyed by attribute name. */\n static get rawAttributes(): Readonly<Record<string, AttributeDefinition>> {\n return Object.fromEntries(registry.state(this).definition.attributes);\n }\n\n /** First primary key attribute name. */\n static get primaryKeyAttribute(): string | undefined {\n return registry.state(this).definition.primaryKeys[0];\n }\n\n /** All primary key attribute names. */\n static get primaryKeyAttributes(): readonly string[] {\n return registry.state(this).definition.primaryKeys;\n }\n\n /** Model options after defaults were applied. */\n static get options(): DefinitionOptions {\n return registry.state(this).definition.options;\n }\n\n /** `Sequelize` instance the model belongs to. */\n static get sequelize(): RuntimeOwner {\n return (\n registry.sequelizeOf(this) ??\n (() => {\n throw new Error('Model is not initialized.');\n })()\n );\n }\n\n /**\n * Defines attributes and options of the model and registers it in `sequelize.models`. Does not\n * touch the database; call {@link Model.sync} or run migrations to create the table.\n *\n * @param this - The model class being initialized.\n * @param attributes - Attribute definitions.\n * @param options - Model options, including the `sequelize` instance.\n * @returns The model class.\n * @example\n * ```ts\n * class Project extends Model {}\n * Project.init(\n * { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING },\n * { sequelize, modelName: 'Project', paranoid: true },\n * );\n * ```\n */\n static init<MS extends ModelStatic<AnyModel>>(\n this: MS,\n attributes: ModelAttributes,\n options: InitOptions,\n ): MS {\n registry.init(this, attributes, options);\n return this;\n }\n\n /**\n * Returns the normalized attribute definitions, same as {@link Model.rawAttributes}.\n *\n * @returns Attribute definitions.\n * @example\n * ```ts\n * const attributes = User.getAttributes();\n * Object.keys(attributes);\n * ```\n */\n static getAttributes(): Readonly<Record<string, AttributeDefinition>> {\n return this.rawAttributes;\n }\n\n /**\n * Table name, or the qualified table (`{ tableName, schema, delimiter, ... }`, like v6) when the\n * model has a schema. `String(qualified)` is the quoted `\"schema\".\"table\"` reference.\n *\n * @returns Table name or qualified table.\n * @example\n * ```ts\n * const table = User.getTableName();\n * ```\n */\n static getTableName(): string | QualifiedTableName {\n const { definition } = registry.state(this);\n const { tableName, schema } = definition;\n return schema === undefined\n ? tableName\n : {\n tableName,\n table: tableName,\n name: definition.name,\n schema,\n delimiter: definition.options.schemaDelimiter ?? '.',\n toString: (): string =>\n `${SqlCompiler.quoteIdent(schema)}.${SqlCompiler.quoteIdent(tableName)}`,\n };\n }\n}\n","import type { ValidateOptions } from './instance-lifecycle.ts';\nimport { lifecycle } from './model-services.ts';\nimport type {\n AnyModel,\n AttributeAmounts,\n IncrementOptions,\n InstanceDestroyOptions,\n SaveOptions,\n Values,\n} from './options.ts';\nimport type { QueryOptionsBase } from './runtime.ts';\n\n/**\n * Persistence of model instances: `save`, `validate`, `update`, `reload`, `destroy`, `restore`, `isSoftDeleted`, `increment`, `decrement`.\n *\n * @internal\n */\nexport class ModelInstancePersistence<TAttributes extends object = Values> {\n /** Current attribute values. */\n declare dataValues: TAttributes;\n\n /**\n * Inserts the instance when it is new, otherwise updates its changed attributes. Runs validation\n * and the `beforeValidate`/`afterValidate`, `beforeSave`/`afterSave` and `beforeCreate`/`beforeUpdate`\n * (and `after*`) hooks unless disabled in the options; updating an unchanged instance sends no query.\n *\n * @param options - Save options.\n * @returns This instance with values returned by the database.\n * @throws ValidationError when validation fails.\n * @throws UniqueConstraintError when a unique constraint is violated.\n * @throws ForeignKeyConstraintError when a foreign key constraint is violated.\n * @example\n * ```ts\n * const user = User.build({ email: 'ada@example.com' });\n * await user.save({ transaction });\n * ```\n */\n save(options: SaveOptions<TAttributes> = {}): Promise<this> {\n return lifecycle.save(\n this as unknown as AnyModel,\n options as SaveOptions,\n ) as unknown as Promise<this>;\n }\n\n /**\n * Runs the attribute validators and model validators without saving (Sequelize v6 `instance.validate()`).\n *\n * @param options - `hooks`, `skip`, `fields`.\n * @returns Resolves when valid.\n * @throws ValidationError with all failures.\n * @example\n * ```ts\n * await user.validate();\n * ```\n */\n validate(options: ValidateOptions = {}): Promise<void> {\n return lifecycle.validate(this as unknown as AnyModel, options);\n }\n\n /**\n * Sets values and saves the instance, same as {@link Model.set} followed by {@link Model.save}.\n *\n * @param values - New values.\n * @param options - Save options.\n * @returns This instance.\n * @throws ValidationError when validation fails.\n * @example\n * ```ts\n * await user.update({ email: 'ada@example.com' });\n * ```\n */\n async update(\n values: Partial<TAttributes>,\n options: SaveOptions<TAttributes> = {},\n ): Promise<this> {\n (this as unknown as AnyModel).set(values);\n return this.save(options);\n }\n\n /**\n * Re-reads the row from the database and replaces the instance values, discarding unsaved changes.\n *\n * @param options - Query options.\n * @returns This instance.\n * @throws InstanceError when the row no longer exists.\n * @example\n * ```ts\n * await user.reload({ transaction });\n * ```\n */\n reload(options: QueryOptionsBase = {}): Promise<this> {\n return lifecycle.reload(this as unknown as AnyModel, options) as unknown as Promise<this>;\n }\n\n /**\n * Deletes the row of this instance. For paranoid models it sets `deletedAt` instead, unless\n * `force: true`. Runs `beforeDestroy`/`afterDestroy` hooks unless `hooks: false`.\n *\n * @param options - Destroy options (`force`, `hooks`, query options).\n * @returns Resolves when deleted.\n * @example\n * ```ts\n * await user.destroy();\n * ```\n */\n destroy(options: InstanceDestroyOptions = {}): Promise<void> {\n return lifecycle.destroy(this as unknown as AnyModel, options);\n }\n\n /**\n * Clears `deletedAt` of this soft-deleted instance of a paranoid model.\n *\n * @param options - Query options; `hooks: false` skips restore hooks.\n * @returns Resolves when restored.\n * @throws Error when the model is not paranoid.\n * @example\n * ```ts\n * await user.restore();\n * ```\n */\n restore(options: QueryOptionsBase & Readonly<{ hooks?: boolean }> = {}): Promise<void> {\n return lifecycle.restore(this as unknown as AnyModel, options);\n }\n\n /**\n * Whether this instance of a paranoid model is soft-deleted.\n *\n * @returns True when `deletedAt` is set.\n * @throws Error when the model is not paranoid.\n * @example\n * ```ts\n * if (user.isSoftDeleted()) {\n * await user.restore();\n * }\n * ```\n */\n isSoftDeleted(): boolean {\n return lifecycle.isSoftDeleted(this as unknown as AnyModel);\n }\n\n /**\n * Increments numeric attributes of this row in the database (`SET x = x + by`). The instance values are\n * not reloaded; call {@link Model.reload} to read the new numbers.\n *\n * @param fields - Attribute name(s) or map of amounts.\n * @param options - `by` (default 1), `silent`, and query options.\n * @returns This instance.\n * @example\n * ```ts\n * await user.increment('loginCount');\n * await user.increment({ loginCount: 2, score: 10 });\n * ```\n */\n async increment(\n fields: AttributeAmounts<TAttributes>,\n options: Omit<IncrementOptions<TAttributes>, 'where'> = {},\n ): Promise<this> {\n await lifecycle.changeBy(\n this as unknown as AnyModel,\n 'increment',\n fields as AttributeAmounts<Values>,\n options as Omit<IncrementOptions, 'where'>,\n );\n return this;\n }\n\n /**\n * Decrements numeric attributes of this row in the database (`SET x = x - by`). The instance values are\n * not reloaded; call {@link Model.reload} to read the new numbers.\n *\n * @param fields - Attribute name(s) or map of amounts.\n * @param options - `by` (default 1), `silent`, and query options.\n * @returns This instance.\n * @example\n * ```ts\n * await user.decrement('credits', { by: 5 });\n * ```\n */\n async decrement(\n fields: AttributeAmounts<TAttributes>,\n options: Omit<IncrementOptions<TAttributes>, 'where'> = {},\n ): Promise<this> {\n await lifecycle.changeBy(\n this as unknown as AnyModel,\n 'decrement',\n fields as AttributeAmounts<Values>,\n options as Omit<IncrementOptions, 'where'>,\n );\n return this;\n }\n}\n","import { instanceValues, valueCloner } from './model-services.ts';\nimport type { Model } from './model.ts';\nimport type { AnyModel, Values } from './options.ts';\n\n/**\n * Value access of model instances: `get`, `set`, `getDataValue`, `setDataValue`, `changed`, `previous`, `equals`, `toJSON`.\n *\n * @internal\n */\nexport class ModelInstanceValues<TAttributes extends object = Values> {\n /** Current attribute values. */\n declare dataValues: TAttributes;\n\n /**\n * Returns all attribute values of the instance; no query is run.\n *\n * @param options - `plain: true` returns a copy of all values with custom getters applied; `raw: true` skips custom getters.\n * @returns Values object.\n * @example\n * ```ts\n * const values = user.get({ plain: true });\n * ```\n */\n get(options?: Readonly<{ plain?: boolean; raw?: boolean; clone?: boolean }>): TAttributes;\n\n /**\n * Returns one attribute value, applying its custom getter unless `raw` is set.\n *\n * @param key - Attribute name.\n * @param options - `raw: true` skips the custom getter.\n * @returns Attribute value.\n * @example\n * ```ts\n * const email = user.get('email');\n * ```\n */\n get<K extends keyof TAttributes>(key: K, options?: Readonly<{ raw?: boolean }>): TAttributes[K];\n get(\n keyOrOptions?: string | number | symbol | Readonly<{ plain?: boolean; raw?: boolean }>,\n options: Readonly<{ raw?: boolean }> = {},\n ): unknown {\n return instanceValues.get(this as unknown as AnyModel, keyOrOptions, options);\n }\n\n /**\n * Sets one attribute value, applying its custom setter unless `raw` is set. Nothing is written to\n * the database until {@link Model.save}; the attribute is marked as changed when the value differs.\n *\n * @param key - Attribute name.\n * @param value - New value.\n * @param options - `raw: true` skips the custom setter and change tracking.\n * @returns This instance.\n * @example\n * ```ts\n * user.set('email', 'ada@example.com');\n * await user.save();\n * ```\n */\n set<K extends keyof TAttributes>(\n key: K,\n value: TAttributes[K],\n options?: Readonly<{ raw?: boolean }>,\n ): this;\n\n /**\n * Sets several attribute values at once, applying custom setters unless `raw` is set.\n *\n * @param values - Attribute values.\n * @param options - `raw: true` skips custom setters and change tracking.\n * @returns This instance.\n * @example\n * ```ts\n * user.set({ email: 'ada@example.com', active: true });\n * ```\n */\n set(values: Partial<TAttributes> | Values, options?: Readonly<{ raw?: boolean }>): this;\n set(\n keyOrValues: string | number | symbol | Values,\n valueOrOptions?: unknown,\n maybeOptions?: Readonly<{ raw?: boolean }>,\n ): this {\n instanceValues.set(this as unknown as AnyModel, keyOrValues, valueOrOptions, maybeOptions);\n return this;\n }\n\n /**\n * Reads the stored value of an attribute, bypassing its custom getter.\n *\n * @param key - Attribute name.\n * @returns Raw value.\n * @example\n * ```ts\n * const stored = user.getDataValue('email');\n * ```\n */\n getDataValue<K extends keyof TAttributes>(key: K): TAttributes[K] {\n return this.dataValues[key];\n }\n\n /**\n * Writes the stored value of an attribute, bypassing its custom setter, and marks it as changed.\n *\n * @param key - Attribute name.\n * @param value - New value.\n * @returns This instance.\n * @example\n * ```ts\n * user.setDataValue('email', 'ada@example.com');\n * ```\n */\n setDataValue<K extends keyof TAttributes>(key: K, value: TAttributes[K]): this {\n instanceValues.setDataValue(this as unknown as AnyModel, key, value);\n return this;\n }\n\n /**\n * Lists the attributes changed since the instance was loaded or last saved.\n *\n * @returns Changed attribute names, or `false` when nothing changed.\n * @example\n * ```ts\n * user.set('email', 'ada@example.com');\n * const changedFields = user.changed();\n * ```\n */\n changed(): (keyof TAttributes & string)[] | false;\n\n /**\n * Checks whether one attribute changed since the instance was loaded or last saved.\n *\n * @param key - Attribute name.\n * @returns True when changed.\n */\n changed(key: keyof TAttributes & string): boolean;\n\n /**\n * Marks an attribute as changed or unchanged, which controls whether {@link Model.save} writes it.\n *\n * @param key - Attribute name.\n * @param value - Changed flag.\n */\n changed(key: keyof TAttributes & string, value: boolean): void;\n changed(key?: string, value?: boolean): unknown {\n return instanceValues.changed(this as unknown as AnyModel, key, value);\n }\n\n /**\n * Returns the value an attribute had before it was changed, or all previous values of changed\n * attributes when no key is given.\n *\n * @param key - Attribute name; omit to get all.\n * @returns Previous value(s).\n * @example\n * ```ts\n * user.set('email', 'ada@example.com');\n * const before = user.previous('email');\n * ```\n */\n previous<K extends keyof TAttributes>(\n key?: K,\n ): TAttributes[K] | Partial<TAttributes> | undefined {\n return instanceValues.previous(this as unknown as AnyModel, key) as\n | TAttributes[K]\n | Partial<TAttributes>\n | undefined;\n }\n\n /**\n * Compares the primary keys of two instances.\n *\n * @param other - Instance to compare with.\n * @returns True when all primary key values are equal.\n * @example\n * ```ts\n * const other = User.build({ id: user.get('id') });\n * const same = user.equals(other);\n * ```\n */\n equals(other: Model): boolean {\n return instanceValues.equals(this as unknown as AnyModel, other);\n }\n\n /**\n * Returns a deep copy of the values with custom getters applied, used by `JSON.stringify`.\n *\n * @returns Plain object.\n * @example\n * ```ts\n * const json = JSON.stringify(user);\n * ```\n */\n toJSON(): TAttributes {\n return valueCloner.clone(this.get({ plain: true }));\n }\n}\n","/** Minimal view of the `pg` connection used by COPY. */\ntype CopyConnection = Readonly<{\n query: (text: string) => void;\n sendCopyFromChunk: (chunk: Buffer) => unknown;\n endCopyFrom: () => void;\n sendCopyFail: (message: string) => void;\n stream?: Readonly<{\n writableNeedDrain?: boolean;\n once: (event: 'drain', listener: () => void) => unknown;\n }>;\n}>;\n\n/**\n * `pg` submittable running `COPY ... FROM STDIN` and streaming text lines produced by `lines`.\n * Resolves with the number of copied rows.\n */\nexport class CopyFromStdin {\n /** Completion callback set by `pg`. */\n callback: ((error: Error | null, rowCount?: number) => void) | undefined;\n readonly #text: string;\n readonly #lines: AsyncIterable<string>;\n #finished = false;\n #pumping: Promise<void> = Promise.resolve();\n #rowCount = 0;\n\n /**\n * @param text - `COPY ... FROM STDIN` statement.\n * @param lines - Encoded rows.\n */\n constructor(text: string, lines: AsyncIterable<string>) {\n this.#text = text;\n this.#lines = lines;\n }\n\n /** Promise resolving with the copied row count. */\n done(): Promise<number> {\n return new Promise((resolve, reject) => {\n this.callback = (error, rowCount) =>\n error === null ? resolve(rowCount ?? 0) : reject(error);\n });\n }\n\n /** @internal Called by `pg` to start the query. */\n submit(connection: CopyConnection): void {\n connection.query(this.#text);\n }\n\n /** Resolves when no more data will be written to the connection. */\n settled(): Promise<void> {\n return this.#pumping;\n }\n\n /** @internal Server is ready to receive data. */\n handleCopyInResponse(connection: CopyConnection): void {\n this.#pumping = this.#pump(connection);\n }\n\n async #pump(connection: CopyConnection): Promise<void> {\n try {\n for await (const line of this.#lines) {\n if (this.#finished) {\n break;\n }\n connection.sendCopyFromChunk(Buffer.from(line, 'utf8'));\n if (connection.stream?.writableNeedDrain === true) {\n await new Promise<void>((resolve) => connection.stream?.once('drain', resolve));\n }\n }\n connection.endCopyFrom();\n } catch (error) {\n connection.sendCopyFail(error instanceof Error ? error.message : String(error));\n }\n }\n\n /** @internal */\n handleCommandComplete(message: Readonly<{ text?: string }>): void {\n this.#rowCount = Number(/COPY (\\d+)/.exec(message.text ?? '')?.[1] ?? 0);\n }\n\n /** @internal `pg` detaches the query on error, so report it right away. */\n handleError(error: Error): void {\n this.#finish(error);\n }\n\n /** @internal */\n handleReadyForQuery(): void {\n this.#finish(null);\n }\n\n #finish(error: Error | null): void {\n if (!this.#finished) {\n this.#finished = true;\n this.callback?.(error, this.#rowCount);\n }\n }\n\n /** @internal */\n handleRowDescription(): void {}\n\n /** @internal */\n handleDataRow(): void {}\n\n /** @internal */\n handleEmptyQuery(): void {}\n\n /** @internal */\n handlePortalSuspended(): void {}\n\n /** @internal */\n handleCopyData(): void {}\n}\n","/** Minimal view of the `pg` connection used by COPY TO. */\ntype CopyOutConnection = Readonly<{\n query: (text: string) => void;\n stream?: Readonly<{ pause: () => unknown; resume: () => unknown }>;\n}>;\n\nconst HIGH_WATER_MARK = 64;\n\n/** `pg` submittable running `COPY ... TO STDOUT` and exposing the output as an async iterator of chunks. */\nexport class CopyToStdout {\n /** Completion callback set by `pg`. */\n callback: ((error: Error | null, rowCount?: number) => void) | undefined;\n readonly #text: string;\n #connection: CopyOutConnection | undefined;\n #queue: Buffer[] = [];\n #wake: (() => void) | undefined;\n #finished = false;\n #error: Error | undefined;\n #discard = false;\n #paused = false;\n #rowCount = 0;\n readonly #done: Promise<number>;\n\n /**\n * @param text - `COPY ... TO STDOUT` statement.\n */\n constructor(text: string) {\n this.#text = text;\n this.#done = new Promise((resolve, reject) => {\n this.callback = (error, rowCount) =>\n error === null ? resolve(rowCount ?? 0) : reject(error);\n });\n this.#done.catch(() => undefined);\n }\n\n /** Resolves with the copied row count when the server finished. */\n done(): Promise<number> {\n return this.#done;\n }\n\n /** Output chunks in order; throws the server error, if any. */\n async *chunks(): AsyncGenerator<Buffer, void, undefined> {\n for (;;) {\n const chunk = this.#queue.shift();\n if (chunk !== undefined) {\n this.#resumeIfDrained();\n yield chunk;\n continue;\n }\n if (this.#finished) {\n if (this.#error !== undefined) {\n throw this.#error;\n }\n return;\n }\n await new Promise<void>((resolve) => {\n this.#wake = resolve;\n });\n }\n }\n\n /** Stops delivering chunks and lets the remaining output drain. */\n discard(): void {\n this.#discard = true;\n this.#queue = [];\n this.#resumeIfDrained();\n }\n\n /** @internal Called by `pg` to start the query. */\n submit(connection: CopyOutConnection): void {\n this.#connection = connection;\n connection.query(this.#text);\n }\n\n /** @internal */\n handleCopyData(message: Readonly<{ chunk: Buffer }>): void {\n if (this.#discard) {\n return;\n }\n this.#queue.push(Buffer.from(message.chunk));\n if (this.#queue.length >= HIGH_WATER_MARK && !this.#paused) {\n this.#paused = true;\n this.#connection?.stream?.pause();\n }\n this.#notify();\n }\n\n /** @internal */\n handleCommandComplete(message: Readonly<{ text?: string }>): void {\n this.#rowCount = Number(/COPY (\\d+)/.exec(message.text ?? '')?.[1] ?? 0);\n }\n\n /** @internal `pg` detaches the query on error, so report it right away. */\n handleError(error: Error): void {\n this.#finish(error);\n }\n\n /** @internal */\n handleReadyForQuery(): void {\n this.#finish(undefined);\n }\n\n /** @internal */\n handleCopyInResponse(): void {}\n\n /** @internal */\n handleRowDescription(): void {}\n\n /** @internal */\n handleDataRow(): void {}\n\n /** @internal */\n handleEmptyQuery(): void {}\n\n /** @internal */\n handlePortalSuspended(): void {}\n\n #resumeIfDrained(): void {\n if (this.#paused && this.#queue.length < HIGH_WATER_MARK / 2) {\n this.#paused = false;\n this.#connection?.stream?.resume();\n }\n }\n\n #notify(): void {\n const wake = this.#wake;\n this.#wake = undefined;\n wake?.();\n }\n\n #finish(error: Error | undefined): void {\n if (this.#finished) {\n return;\n }\n this.#finished = true;\n this.#error = error;\n if (this.#paused) {\n this.#paused = false;\n this.#connection?.stream?.resume();\n }\n this.callback?.(error ?? null, this.#rowCount);\n this.#notify();\n }\n}\n","/** Value accepted by the COPY text encoder. */\ntype CopyValue = unknown;\n\n/** Encodes values and rows in PostgreSQL COPY text format. */\nexport class CopyEncoder {\n readonly #encodeValue = (value: CopyValue): string => this.encodeValue(value);\n readonly #arrayElement = (value: unknown): string =>\n value === null || value === undefined\n ? 'NULL'\n : Array.isArray(value)\n ? this.#arrayLiteral(value)\n : `\"${String(value instanceof Date ? value.toISOString() : typeof value === 'object' ? JSON.stringify(value) : value).replace(/[\"\\\\]/g, (char) => `\\\\${char}`)}\"`;\n\n /**\n * Encodes one value in PostgreSQL COPY text format (`\\N` for NULL).\n *\n * @param value - Value to encode.\n * @returns Encoded field.\n */\n encodeValue(value: CopyValue): string {\n return CopyEncoder.#raw(value) ?? CopyEncoder.#escapeText(this.#text(value));\n }\n\n /**\n * Encodes a row (already in column order) as one COPY text line.\n *\n * @param values - Values in column order.\n * @returns Encoded line ending with a newline.\n */\n encodeRow(values: readonly CopyValue[]): string {\n return `${values.map(this.#encodeValue).join('\\t')}\\n`;\n }\n\n #text(value: CopyValue): string {\n if (Array.isArray(value)) {\n return this.#arrayLiteral(value);\n }\n return typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n // Values with a fixed COPY representation that must not be text-escaped.\n static #raw(value: CopyValue): string | undefined {\n if (value === null || value === undefined) {\n return '\\\\N';\n }\n if (typeof value === 'boolean') {\n return value ? 't' : 'f';\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n return Buffer.isBuffer(value) ? `\\\\\\\\x${value.toString('hex')}` : undefined;\n }\n\n #arrayLiteral(values: readonly unknown[]): string {\n return `{${values.map(this.#arrayElement).join(',')}}`;\n }\n\n static #escapeText(text: string): string {\n return text.replace(/[\\\\\\t\\n\\r]/g, (char) =>\n char === '\\\\' ? '\\\\\\\\' : char === '\\t' ? '\\\\t' : char === '\\n' ? '\\\\n' : '\\\\r',\n );\n }\n}\n\nexport { CopyFromStdin } from './copy-from-stdin.ts';\nexport { CopyToStdout } from './copy-to-stdout.ts';\n","import type { HookType } from '../../hooks/hooks.ts';\nimport type { InstanceLifecycle } from '../instance-lifecycle.ts';\nimport type { MutableOptions } from '../options.ts';\n\n/** Services every operation has: the hook runner. */\nexport type OperationServices = Readonly<{\n /** Hooks. */\n lifecycle: InstanceLifecycle;\n}>;\n\n// oxlint-disable-next-line typescript/no-explicit-any -- decorated methods take further arguments of any type.\ntype OperationMethod = (model: any, options: MutableOptions, ...rest: any[]) => Promise<unknown>;\n\n/**\n * Base of `Model` operations: holds the injected services and provides the hook decorators.\n *\n * @typeParam S - Services of the operation.\n * @internal\n */\nexport abstract class ModelOperation<S extends OperationServices> {\n /** Injected collaborators. */\n protected readonly services: S;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: S) {\n this.services = services;\n }\n\n /**\n * Method decorator: runs `before` / `after` hooks with the options around a\n * `(model, options, ...rest)` method when `options.hooks === true`.\n *\n * @param before - Hook run before the method.\n * @param after - Hook run after the method resolved.\n * @returns The decorator.\n */\n static bulkHooks(\n before: HookType,\n after: HookType,\n ): <T extends OperationMethod>(\n method: T,\n context: ClassMethodDecoratorContext<ModelOperation<OperationServices>>,\n ) => T {\n return <T extends OperationMethod>(method: T): T =>\n async function (this: ModelOperation<OperationServices>, model, options, ...rest) {\n const run = (type: HookType): Promise<void> =>\n options['hooks'] === true\n ? this.services.lifecycle.runHooks(model, type, options)\n : Promise.resolve();\n await run(before);\n const result: unknown = await method.call(this, model, options, ...rest);\n await run(after);\n return result;\n } as T;\n }\n}\n","import type { BulkInsertBuilder } from '../bulk-insert-builder.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport { OnConflictBuilder, type OnConflictOptions } from '../on-conflict-builder.ts';\nimport type {\n AnyModel,\n BulkCreateOptions,\n ModelStatic,\n MutableOptions,\n Values,\n} from '../options.ts';\nimport type { WrittenRows } from '../written-rows.ts';\nimport type { InsertOperation } from './insert-operation.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link BulkCreateOperation}. */\nexport type BulkCreateOperationServices = OperationServices &\n Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** INSERT builder. */\n bulkInserts: BulkInsertBuilder;\n /** ON CONFLICT builder. */\n conflicts: OnConflictBuilder;\n /** Conflict-aware inserts. */\n inserter: InsertOperation;\n /** Alignment of `ignoreDuplicates` results. */\n written: WrittenRows;\n }>;\n\n// One `Model.bulkCreate` call: the built instances, hook-visible options and caller's options.\ntype BulkCreateCall = Readonly<{\n model: ModelStatic<AnyModel>;\n definition: ModelDefinition;\n instances: AnyModel[];\n opts: MutableOptions;\n options: BulkCreateOptions;\n}>;\n\n/**\n * `Model.bulkCreate`: one multi-row INSERT (Sequelize v6 conflict options or `onConflict`), or\n * one `save` per instance with `individualHooks` / nested includes.\n */\nexport class BulkCreateOperation extends ModelOperation<BulkCreateOperationServices> {\n /**\n * `Model.bulkCreate`.\n *\n * @param model - Model class.\n * @param records - Values per row.\n * @param options - Bulk create options.\n * @returns Instances with values returned by the database.\n * @throws Error when `onConflict` is combined with Sequelize v6 conflict options.\n */\n async bulkCreate<M extends AnyModel>(\n model: ModelStatic<M>,\n records: readonly Values[],\n options: BulkCreateOptions,\n ): Promise<M[]> {\n const { definition } = this.services.registry.state(model);\n const opts = BulkCreateOperation.#options(options);\n const instances = BulkCreateOperation.#instances(model, records, options);\n if (instances.length === 0) {\n return [];\n }\n const call = { model, definition, instances, opts, options };\n await this.#before(call);\n const created = await this.#create(call);\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'afterBulkCreate', created, opts);\n }\n return created as M[];\n }\n\n static #options(options: BulkCreateOptions): MutableOptions {\n if (\n options.onConflict !== undefined &&\n OnConflictBuilder.V6_OPTIONS.some((name) => options[name] !== undefined)\n ) {\n throw new Error(\n `onConflict cannot be combined with ${OnConflictBuilder.V6_OPTIONS.join(', ')}`,\n );\n }\n return {\n hooks: true,\n validate: false,\n individualHooks: options.include !== undefined,\n ...options,\n };\n }\n\n static #instances<M extends AnyModel>(\n model: ModelStatic<M>,\n records: readonly Values[],\n options: BulkCreateOptions,\n ): M[] {\n return records.map(\n (values) =>\n new model(values, options.include === undefined ? {} : { include: options.include }),\n );\n }\n\n async #before({ model, instances, opts }: BulkCreateCall): Promise<void> {\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'beforeBulkCreate', instances, opts);\n }\n if (opts['validate'] === true) {\n await this.services.lifecycle.validateAll(instances, opts['individualHooks'] === true);\n }\n }\n\n #create(call: BulkCreateCall): Promise<AnyModel[]> {\n return call.opts['individualHooks'] === true\n ? BulkCreateOperation.#saveEach(call)\n : this.#insert(call);\n }\n\n static async #saveEach({ instances, opts }: BulkCreateCall): Promise<AnyModel[]> {\n const {\n fields: _fields,\n individualHooks: _individual,\n ignoreDuplicates: _ignore,\n include: _include,\n ...saveOptions\n } = opts;\n await instances.reduce<Promise<unknown>>(\n (previous, instance) =>\n previous.then(() => instance.save({ ...saveOptions, validate: false, hooks: true })),\n Promise.resolve(),\n );\n return instances;\n }\n\n async #insert(call: BulkCreateCall): Promise<AnyModel[]> {\n const { model, definition, options } = call;\n const rows = this.#rows(call);\n if (options.onConflict !== undefined) {\n const onConflict = options.onConflict as OnConflictOptions<unknown>;\n const conflict = this.services.conflicts.build(definition, onConflict);\n return this.services.inserter.withConflict(model, rows, conflict, options);\n }\n return this.#insertRows(call, rows);\n }\n\n #rows({ definition, instances, opts, options }: BulkCreateCall): Values[] {\n const { values } = this.services;\n const now = new Date();\n const fields = values.bulkFields(definition, options.fields as readonly string[] | undefined);\n const silent = opts['silent'] === true;\n return instances.map((instance) =>\n values.pick(\n values.withTimestamps(definition, instance.dataValues as Values, now, true, silent),\n fields,\n ),\n );\n }\n\n async #insertRows(call: BulkCreateCall, rows: Values[]): Promise<AnyModel[]> {\n const { model, definition, instances, options } = call;\n const { runtime } = this.services.registry.state(model);\n const { bulkInserts, lifecycle, written } = this.services;\n const query = bulkInserts.build(definition, rows, options);\n const result = await runtime.execute(query, options);\n const returned =\n options.ignoreDuplicates === true\n ? written.aligned(definition, rows, result.rows)\n : result.rows;\n instances.forEach((instance, index) =>\n lifecycle.refresh(instance, definition, returned[index]),\n );\n return instances;\n }\n}\n","import type { CopyEncoder } from '../../connection/copy.ts';\nimport { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeDefinition, ModelDefinition } from '../model-definition.ts';\nimport type { CopyFromOptions, Values } from '../options.ts';\n\ntype CopySource = Iterable<Values> | AsyncIterable<Values>;\n\n/** Copied columns: attribute definitions in row order and the timestamps filled by `copyFrom`. */\nexport type CopyColumns = Readonly<{\n /** Attributes in row order. */\n attributes: readonly AttributeDefinition[];\n /** Timestamp attributes filled with the current time. */\n stamps: readonly string[];\n}>;\n\n/**\n * Columns, statement text and encoded lines of `Model.copyFrom` (`COPY ... FROM STDIN`).\n *\n * @internal\n */\nexport class CopyFromSource {\n readonly #encoder: CopyEncoder;\n\n /**\n * @param encoder - COPY text encoding of rows.\n */\n constructor(encoder: CopyEncoder) {\n this.#encoder = encoder;\n }\n\n /**\n * Resolves the copied columns: listed (or first-row) attributes plus missing timestamps.\n *\n * @param definition - Model definition.\n * @param rows - Row source.\n * @param options - `columns`.\n * @returns Attributes in row order and filled timestamps.\n * @throws Error without columns or for unknown attributes.\n */\n columns(definition: ModelDefinition, rows: CopySource, options: CopyFromOptions): CopyColumns {\n const listed = CopyFromSource.#listed(definition, rows, options);\n const stamps = [definition.createdAt, definition.updatedAt].filter(\n (name): name is string => name !== undefined && !listed.includes(name as never),\n );\n const columns = [...(listed as readonly string[]), ...stamps];\n columns.forEach((name) => {\n if (!definition.attributes.has(name)) {\n throw new Error(`copyFrom: unknown attribute \"${name}\" of model ${definition.name}`);\n }\n });\n const attributes = columns.map(\n (name) => definition.attributes.get(name) as AttributeDefinition,\n );\n return { attributes, stamps };\n }\n\n static #listed(\n definition: ModelDefinition,\n rows: CopySource,\n options: CopyFromOptions,\n ): readonly string[] {\n const listed =\n options.columns ??\n (Array.isArray(rows) && rows.length > 0\n ? Object.keys(rows[0] as Values).filter((name) => definition.attributes.has(name))\n : undefined);\n if (listed === undefined || listed.length === 0) {\n throw new Error('copyFrom: columns are required for non-array sources');\n }\n return listed;\n }\n\n /**\n * `COPY table (columns) FROM STDIN` text.\n *\n * @param definition - Model definition.\n * @param attributes - Copied attributes.\n * @returns Statement text.\n */\n sql(definition: ModelDefinition, attributes: readonly AttributeDefinition[]): string {\n const table = [definition.schema, definition.tableName]\n .filter((part): part is string => part !== undefined)\n .map(SqlCompiler.quoteIdent)\n .join('.');\n return `COPY ${table} (${attributes.map((attribute) => SqlCompiler.quoteIdent(attribute.field)).join(', ')}) FROM STDIN`;\n }\n\n /**\n * Encodes rows as COPY text lines, filling timestamps with `now`.\n *\n * @param rows - Row source.\n * @param columns - Copied columns.\n * @param now - Timestamp value.\n * @returns Async iterator of encoded lines.\n */\n async *lines(\n rows: CopySource,\n { attributes, stamps }: CopyColumns,\n now: Date,\n ): AsyncGenerator<string> {\n for await (const row of rows as AsyncIterable<Values>) {\n yield this.#encoder.encodeRow(\n attributes.map((attribute) => {\n const value = stamps.includes(attribute.fieldName) ? now : row[attribute.fieldName];\n return value === undefined || value === null || attribute.type.serialize === undefined\n ? value\n : attribute.type.serialize(value);\n }),\n );\n }\n }\n}\n","import type { IncludeResolver } from '../../associations/include-resolver.ts';\nimport type { CopyEncoder } from '../../connection/copy.ts';\nimport type { SqlLiteral } from '../../ddl/sql-literal.ts';\nimport type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { FindQueryBuilder } from '../find-query-builder.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type {\n AnyModel,\n CopyFromOptions,\n CopyToFormatOptions,\n CopyToOptions,\n FindOptions,\n ModelStatic,\n Values,\n} from '../options.ts';\nimport { CopyFromSource } from './copy-from-source.ts';\n\nconst COPY_FORMATS: ReadonlySet<string> = new Set(['text', 'csv', 'binary']);\n\n/** Collaborators of {@link CopyOperation}. */\nexport type CopyOperationServices = Readonly<{\n /** Model state and scopes. */\n registry: ModelRegistry;\n /** Paranoid filter. */\n columns: AttributeColumns;\n /** Finder SELECT builder. */\n finds: FindQueryBuilder;\n /** Include trees. */\n includes: IncludeResolver;\n /** COPY text encoding of rows. */\n encoder: CopyEncoder;\n /** Escaped literals (COPY takes no parameters). */\n literals: SqlLiteral;\n /** SQL compiler. */\n compiler: SqlCompiler;\n}>;\n\n/** `Model.copyFrom` (`COPY ... FROM STDIN`) and `Model.copyTo` (`COPY (SELECT ...) TO STDOUT`). */\nexport class CopyOperation {\n readonly #services: CopyOperationServices;\n readonly #source: CopyFromSource;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: CopyOperationServices) {\n this.#services = services;\n this.#source = new CopyFromSource(services.encoder);\n }\n\n /**\n * `Model.copyFrom`: bulk-loads rows with `COPY ... FROM STDIN` (text format); timestamps are\n * filled when the model has them.\n *\n * @param model - Model class.\n * @param rows - Array, iterable or async iterable of attribute values.\n * @param options - `columns` and query options.\n * @returns Number of copied rows.\n * @throws Error without columns or for unknown attributes.\n */\n async copyFrom(\n model: ModelStatic<AnyModel>,\n rows: Iterable<Values> | AsyncIterable<Values>,\n options: CopyFromOptions,\n ): Promise<number> {\n const { definition, runtime } = this.#services.registry.state(model);\n const columns = this.#source.columns(definition, rows, options);\n const text = this.#source.sql(definition, columns.attributes);\n const lines = this.#source.lines(rows, columns, new Date());\n return runtime.copyFrom(text, lines, options);\n }\n\n /**\n * `Model.copyTo`: streams `COPY (SELECT ...) TO STDOUT` output; values of the query are inlined\n * as escaped literals.\n *\n * @param model - Model class.\n * @param options - Find options and output format.\n * @returns Async iterator of raw output chunks.\n * @throws Error for unsupported formats or multi-character delimiters / quotes.\n */\n copyTo(\n model: ModelStatic<AnyModel>,\n options: CopyToOptions,\n ): AsyncGenerator<Buffer, void, undefined> {\n const { runtime } = this.#services.registry.state(model);\n const { compiler, literals } = this.#services;\n const select = this.#select(model, options);\n return runtime.copyTo(\n `COPY (${literals.inlineValues(compiler.compile(select))}) TO STDOUT${this.#formatSql(options)}`,\n options,\n 'read',\n );\n }\n\n #select(model: ModelStatic<AnyModel>, options: CopyToOptions) {\n const { definition, runtime } = this.#services.registry.state(model);\n const { registry, columns, includes, finds } = this.#services;\n const scoped = registry.scoped(model, options);\n const query = {\n ...scoped,\n where: columns.paranoid(definition, scoped.where, scoped.paranoid),\n };\n const normalized = includes.normalize(model, query.include);\n return finds.build(definition, query as FindOptions, normalized, runtime.inAsAnyThreshold);\n }\n\n #formatSql(options: CopyToFormatOptions): string {\n if (options.format !== undefined && !COPY_FORMATS.has(options.format)) {\n throw new Error(`copyTo: unsupported format ${String(options.format)}`);\n }\n const parts = [\n ...(options.format === undefined ? [] : [`FORMAT ${options.format}`]),\n ...(options.header === undefined ? [] : [`HEADER ${options.header ? 'true' : 'false'}`]),\n ...(options.delimiter === undefined\n ? []\n : [`DELIMITER ${this.#singleCharacter(options.delimiter, 'delimiter')}`]),\n ...(options.quote === undefined\n ? []\n : [`QUOTE ${this.#singleCharacter(options.quote, 'quote')}`]),\n ...(options.nullString === undefined\n ? []\n : [`NULL ${this.#services.literals.escape(options.nullString)}`]),\n ];\n return parts.length === 0 ? '' : ` WITH (${parts.join(', ')})`;\n }\n\n #singleCharacter(value: string, name: string): string {\n if ([...value].length !== 1) {\n throw new Error(`copyTo: ${name} must be a single character`);\n }\n return this.#services.literals.escape(value);\n }\n}\n","import type { IncludeOption } from '../../associations/include.ts';\nimport type { IncludeQueryBuilder } from '../../associations/include-query-builder.ts';\nimport type { IncludeResolver } from '../../associations/include-resolver.ts';\nimport type { QueryResult } from '../../connection/connection-manager.ts';\nimport { AbstractDataType } from '../../data-types/abstract-data-type.ts';\nimport type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { CteBuilder } from '../cte-builder.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type {\n AggregateOptions,\n AnyModel,\n CountOptions,\n ModelStatic,\n MutableOptions,\n} from '../options.ts';\nimport type { RowMapper } from '../row-mapper.ts';\nimport type { SelectOptions, SelectQueryBuilder } from '../select-query-builder.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link CountOperation}. */\nexport type CountOperationServices = OperationServices &\n Readonly<{\n /** Model state and scopes. */\n registry: ModelRegistry;\n /** Paranoid filter. */\n columns: AttributeColumns;\n /** SELECT builder. */\n selects: SelectQueryBuilder;\n /** CTE options. */\n cte: CteBuilder;\n /** Row parsing. */\n rows: RowMapper;\n /** Include trees. */\n includes: IncludeResolver;\n /** Include count joins. */\n includeQueries: IncludeQueryBuilder;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\n// Count options after scopes and the paranoid filter.\ntype CountQuery = Omit<CountOptions, 'where'> & Readonly<{ where: unknown }>;\n\n/** `Model.count` (with includes and `group`) and `Model.aggregate` (`max`, `min`, `sum`, ...). */\nexport class CountOperation extends ModelOperation<CountOperationServices> {\n /**\n * `Model.count` (default scope and paranoid filter applied).\n *\n * @param model - Model class.\n * @param options - Count options.\n * @returns Count, or `{ count, ...groups }[]` with `group`.\n */\n async count(model: ModelStatic<AnyModel>, options: CountOptions): Promise<number> {\n const { definition, runtime } = this.services.registry.state(model);\n const { compiler, includes, lifecycle } = this.services;\n const opts: MutableOptions = { hooks: true, ...this.services.registry.scoped(model, options) };\n if (opts['hooks'] === true) {\n await lifecycle.runHooks(model, 'beforeCount', opts);\n }\n const query = this.#filtered(definition, opts as CountOptions) as CountQuery;\n const normalized = includes.normalize(model, opts['include'] as IncludeOption | undefined);\n const select = this.#countSelect(model, query, normalized);\n const result = await runtime.execute(\n compiler.compile(select),\n query,\n this.services.cte.route(select),\n );\n return this.#counted(definition, query, result.rows);\n }\n\n #filtered<Q extends Readonly<{ where?: unknown; paranoid?: boolean }>>(\n definition: ModelDefinition,\n query: Q,\n ): Omit<Q, 'where'> & Readonly<{ where: unknown }> {\n return {\n ...query,\n where: this.services.columns.paranoid(definition, query.where, query.paranoid),\n };\n }\n\n #counted(definition: ModelDefinition, query: CountQuery, rows: QueryResult['rows']): number {\n if (query.group !== undefined) {\n return rows.map((row) => ({\n ...this.services.rows.parse(definition, row),\n count: Number(row['count']),\n })) as unknown as number;\n }\n return Number(rows[0]?.['count'] ?? 0);\n }\n\n #countSelect(\n model: ModelStatic<AnyModel>,\n query: CountQuery,\n includes: ReturnType<IncludeResolver['normalize']>,\n ) {\n const { definition, runtime } = this.services.registry.state(model);\n const { cte, includeQueries, selects } = this.services;\n const countQuery = CountOperation.#countQuery(definition, query, includes.length);\n const counted = selects.count(\n cte.sourceDefinition(definition, query.source),\n { ...countQuery, ...cte.selectOptions(query) },\n runtime.inAsAnyThreshold,\n );\n return includes.length === 0\n ? counted\n : { ...counted, joins: includeQueries.countJoins(definition, includes) };\n }\n\n static #countQuery(\n definition: ModelDefinition,\n query: CountQuery,\n includes: number,\n ): SelectOptions & CountOptions {\n if (includes === 0 || query.col !== undefined) {\n return query as SelectOptions & CountOptions;\n }\n const field = definition.attributes.get(definition.primaryKeys[0] ?? 'id')?.field ?? 'id';\n return { ...query, col: `${definition.name}.${field}` } as SelectOptions & CountOptions;\n }\n\n /**\n * `Model.aggregate`: runs an aggregate function over a column.\n *\n * @param model - Model class.\n * @param field - Attribute name or `'*'`.\n * @param aggregateFunction - SQL aggregate function name, e.g. `'max'`.\n * @param options - Options.\n * @returns Aggregated value (the raw driver rows with `plain: false`, like v6: numeric results\n * such as `sum` arrive as strings).\n */\n async aggregate(\n model: ModelStatic<AnyModel>,\n field: string,\n aggregateFunction: string,\n options: AggregateOptions,\n ): Promise<unknown> {\n const { definition, runtime } = this.services.registry.state(model);\n const { compiler, registry, selects } = this.services;\n const query = this.#filtered(definition, registry.scoped(model, options));\n const threshold = runtime.inAsAnyThreshold;\n const select = selects.aggregate(\n definition,\n field,\n aggregateFunction,\n query as SelectOptions,\n threshold,\n );\n const result = await runtime.execute(compiler.compile(select), query, 'read');\n return this.#aggregated(definition, field, aggregateFunction, options, result.rows);\n }\n\n #aggregated(\n definition: ModelDefinition,\n field: string,\n aggregateFunction: string,\n options: AggregateOptions,\n rows: QueryResult['rows'],\n ): unknown {\n if (options.plain === false) {\n return rows;\n }\n const attribute =\n options.dataType === undefined\n ? definition.attributes.get(field)\n : { type: AbstractDataType.from(options.dataType) };\n const mapper = this.services.rows;\n return mapper.aggregate(attribute, aggregateFunction, rows[0]?.[aggregateFunction]);\n }\n}\n","import { InstanceState } from '../instance-state.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type { OnConflictBuilder, OnConflictOptions } from '../on-conflict-builder.ts';\nimport type {\n AnyModel,\n CreateOptions,\n ModelStatic,\n MutableOptions,\n SaveOptions,\n Values,\n} from '../options.ts';\nimport type { InsertOperation } from './insert-operation.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link CreateOperation}. */\nexport type CreateOperationServices = OperationServices &\n Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** ON CONFLICT builder. */\n conflicts: OnConflictBuilder;\n /** Conflict-aware inserts. */\n inserter: InsertOperation;\n }>;\n\n// One `Model.create` call with `onConflict`: the built instance and both option objects.\ntype CreateCall = Readonly<{\n model: ModelStatic<AnyModel>;\n definition: ModelDefinition;\n instance: AnyModel;\n opts: MutableOptions;\n options: CreateOptions;\n}>;\n\n/** `Model.create`: builds and saves an instance, or inserts it with `onConflict`. */\nexport class CreateOperation extends ModelOperation<CreateOperationServices> {\n /**\n * `Model.create`.\n *\n * @param model - Model class.\n * @param values - Attribute values.\n * @param options - Create options.\n * @returns Saved instance (with `onConflict`: the written row, or the unsaved instance with\n * `wasInserted: false` when nothing was written).\n */\n async create<M extends AnyModel>(\n model: ModelStatic<M>,\n values: Values | undefined,\n options: CreateOptions,\n ): Promise<M> {\n const instance = new model(\n values,\n options.include === undefined ? {} : { include: options.include },\n );\n if (options.onConflict === undefined) {\n return instance.save(options as SaveOptions);\n }\n const { definition } = this.services.registry.state(model);\n const opts: MutableOptions = { hooks: true, validate: true, ...options };\n return (await this.#createOnConflict({ model, definition, instance, opts, options })) as M;\n }\n\n async #createOnConflict(call: CreateCall): Promise<AnyModel> {\n const { model, instance, opts } = call;\n if (opts['validate'] === true) {\n await instance.validate({ hooks: opts['hooks'] === true });\n }\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'beforeCreate', instance, opts);\n }\n const [inserted] = await this.#insert(call);\n if (inserted === undefined) {\n InstanceState.of(instance).wasInserted = false;\n return instance;\n }\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'afterCreate', inserted, opts);\n }\n return inserted;\n }\n\n #insert({ model, definition, instance, opts, options }: CreateCall): Promise<AnyModel[]> {\n const { conflicts, inserter, values } = this.services;\n const silent = opts['silent'] === true;\n const row = values.withTimestamps(\n definition,\n instance.dataValues as Values,\n new Date(),\n true,\n silent,\n );\n const fields = options.fields as readonly string[] | undefined;\n const onConflict = options.onConflict as OnConflictOptions<unknown>;\n return inserter.withConflict(\n model,\n [values.pick(row, fields)],\n conflicts.build(definition, onConflict),\n options,\n );\n }\n}\n","import type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { DeleteQueryBuilder } from '../delete-query-builder.ts';\nimport type { JoinSourceBuilder } from '../join-source-builder.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type {\n AnyModel,\n DestroyOptions,\n ModelStatic,\n MutableOptions,\n RestoreOptions,\n} from '../options.ts';\nimport type { RowMapper } from '../row-mapper.ts';\nimport type { QueryOptionsBase } from '../runtime.ts';\nimport type { UpdateQueryBuilder } from '../update-query-builder.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link DestroyOperation}. */\nexport type DestroyOperationServices = OperationServices &\n Readonly<{\n /** Model state and scopes. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** SET items, paranoid filter. */\n columns: AttributeColumns;\n /** UPDATE builder (soft delete, restore). */\n updates: UpdateQueryBuilder;\n /** DELETE / TRUNCATE builder. */\n deletes: DeleteQueryBuilder;\n /** `using` relations. */\n joins: JoinSourceBuilder;\n /** Instances of returned rows. */\n rows: RowMapper;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\n// One `Model.destroy` call after the bulk hook: the filter and whether rows are soft-deleted.\ntype DestroyCall = Readonly<{\n model: ModelStatic<AnyModel>;\n options: DestroyOptions;\n where: unknown;\n soft: boolean;\n}>;\n\n/**\n * `Model.destroy` (DELETE, or soft delete of paranoid models), `Model.restore` and\n * `Model.truncate`, with bulk and individual hooks.\n */\nexport class DestroyOperation extends ModelOperation<DestroyOperationServices> {\n /**\n * `Model.destroy`.\n *\n * @param model - Model class.\n * @param options - Destroy options.\n * @returns Number of deleted rows, or deleted instances with `returning: true`.\n */\n async destroy<M extends AnyModel>(\n model: ModelStatic<M>,\n options: DestroyOptions,\n ): Promise<number | M[]> {\n const opts: MutableOptions = {\n hooks: true,\n individualHooks: false,\n force: false,\n ...this.services.registry.scoped(model, options),\n };\n return (await this.#bulkDestroy(model, opts, options)) as number | M[];\n }\n\n @ModelOperation.bulkHooks('beforeBulkDestroy', 'afterBulkDestroy')\n async #bulkDestroy(\n model: ModelStatic<AnyModel>,\n opts: MutableOptions,\n options: DestroyOptions,\n ): Promise<number | AnyModel[]> {\n const { definition } = this.services.registry.state(model);\n const { columns, lifecycle } = this.services;\n const soft = definition.deletedAt !== undefined && opts['force'] !== true;\n const where = soft ? columns.paranoid(definition, opts['where'], true) : opts['where'];\n const targets = await this.#targets(model, opts, where, options);\n await lifecycle.runEach(model, 'beforeDestroy', targets, opts);\n const deleted = await this.#delete({ model, options, where, soft });\n await lifecycle.runEach(model, 'afterDestroy', targets, opts);\n return deleted;\n }\n\n async #targets(\n model: ModelStatic<AnyModel>,\n opts: MutableOptions,\n where: unknown,\n options: QueryOptionsBase,\n ): Promise<AnyModel[]> {\n return opts['individualHooks'] === true\n ? model.findAll({\n where: where as never,\n ...this.services.values.queryOptions(options),\n paranoid: false,\n })\n : [];\n }\n\n async #delete(call: DestroyCall): Promise<number | AnyModel[]> {\n const { model, options } = call;\n if (options.truncate === true) {\n await model.truncate(options);\n return 0;\n }\n const { runtime } = this.services.registry.state(model);\n const node = this.#statement(call);\n const result = await runtime.execute(this.services.compiler.compile(node), options);\n return options.returning === true\n ? result.rows.map((row) => this.services.rows.instance(model, row))\n : result.rowCount;\n }\n\n #statement({ model, options, where, soft }: DestroyCall) {\n const { definition, runtime } = this.services.registry.state(model);\n const { columns, deletes, joins, updates } = this.services;\n const inAsAny = DestroyOperation.#inAsAny(runtime.inAsAnyThreshold);\n const returning = options.returning === true ? { returning: true } : {};\n if (soft && definition.deletedAt !== undefined) {\n const set = columns.setItems(definition, { [definition.deletedAt]: new Date() });\n return updates.build(definition, set, where, { ...returning, ...inAsAny });\n }\n return deletes.build(definition, where, {\n ...(options.using === undefined ? {} : { using: joins.build(options.using) }),\n ...returning,\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n ...inAsAny,\n });\n }\n\n static #inAsAny(threshold: number | undefined) {\n return threshold === undefined ? {} : { inAsAnyThreshold: threshold };\n }\n\n /**\n * `Model.restore`: sets `deletedAt = NULL` on matching rows of a paranoid model.\n *\n * @param model - Model class.\n * @param options - Rows to restore and hook options.\n * @returns Resolves when done.\n * @throws Error when the model is not paranoid.\n */\n async restore(model: ModelStatic<AnyModel>, options: RestoreOptions): Promise<void> {\n const { definition } = this.services.registry.state(model);\n if (definition.deletedAt === undefined) {\n throw new Error('Model is not paranoid');\n }\n const opts: MutableOptions = { hooks: true, individualHooks: false, ...options };\n await this.#bulkRestore(model, opts, options, definition.deletedAt);\n }\n\n @ModelOperation.bulkHooks('beforeBulkRestore', 'afterBulkRestore')\n async #bulkRestore(\n model: ModelStatic<AnyModel>,\n opts: MutableOptions,\n options: RestoreOptions,\n deletedAt: string,\n ): Promise<void> {\n const { definition, runtime } = this.services.registry.state(model);\n const { columns, compiler, lifecycle, updates } = this.services;\n const targets = await this.#targets(model, opts, opts['where'], options);\n await lifecycle.runEach(model, 'beforeRestore', targets, opts);\n const set = columns.setItems(definition, { [deletedAt]: null });\n const inAsAny = DestroyOperation.#inAsAny(runtime.inAsAnyThreshold);\n const node = updates.build(definition, set, opts['where'], inAsAny);\n await runtime.execute(compiler.compile(node), options);\n await lifecycle.runEach(model, 'afterRestore', targets, opts);\n }\n\n /**\n * `Model.truncate`.\n *\n * @param model - Model class.\n * @param options - `cascade`, `restartIdentity` and query options.\n * @returns Resolves when done.\n */\n async truncate(\n model: object,\n options: QueryOptionsBase & Readonly<{ cascade?: boolean; restartIdentity?: boolean }>,\n ): Promise<void> {\n const { definition, runtime } = this.services.registry.state(model);\n const { compiler, deletes } = this.services;\n await runtime.execute(compiler.compile(deletes.truncate(definition, options)), options);\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { IncludeNode } from '../../associations/include.ts';\nimport type { QueryResult } from '../../connection/connection-manager.ts';\nimport { type CompiledQuery, SqlCompiler } from '../../sql/compile.ts';\nimport type { Transaction } from '../../transaction/transaction.ts';\nimport type { AnyModel, FindOptions, ModelStatic } from '../options.ts';\nimport type { ModelRuntime } from '../runtime.ts';\nimport type { SelectOptions } from '../select-query-builder.ts';\nimport type { FindOperationServices } from './find-lookups.ts';\nimport { ModelOperation } from './model-operation.ts';\n\ntype CursorRun = (text: string, values?: readonly unknown[]) => Promise<QueryResult>;\n\n// One open cursor of `Model.findEach`.\ntype CursorCall<M extends AnyModel> = Readonly<{\n model: ModelStatic<M>;\n includes: readonly IncludeNode[];\n batchSize: number;\n compiled: CompiledQuery;\n own: Transaction | undefined;\n transaction: Transaction;\n name: string;\n run: CursorRun;\n}>;\n\n/**\n * `Model.findEach`: streams rows with a server-side cursor.\n *\n * @internal\n */\nexport class FindCursor extends ModelOperation<FindOperationServices> {\n /**\n * Streams instances of matching rows in batches.\n *\n * @param model - Model class.\n * @param options - Find options.\n * @param cursor - `batchSize` (rows per FETCH, default 100).\n * @returns Async iterator of instances.\n * @throws Error for joined includes or an invalid batch size.\n */\n async *each<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOptions,\n cursor: Readonly<{ batchSize?: number }>,\n ): AsyncGenerator<M, void, undefined> {\n const { runtime } = this.services.registry.state(model);\n const scoped = this.services.registry.scoped(model, options);\n const includes = this.services.includes.normalize(model, scoped.include);\n const batchSize = FindCursor.#batchSize(includes, cursor);\n const compiled = this.#compile(model, scoped);\n const { own, transaction } = await FindCursor.#begin(runtime, options);\n const name = SqlCompiler.quoteIdent(`pgz_cursor_${randomUUID().replaceAll('-', '')}`);\n const run: CursorRun = (text, values = []) =>\n runtime.execute(\n { text, values },\n { ...this.services.values.queryOptions(options), transaction },\n );\n yield* this.#iterate({ model, includes, batchSize, compiled, own, transaction, name, run });\n }\n\n static #batchSize(\n includes: readonly IncludeNode[],\n cursor: Readonly<{ batchSize?: number }>,\n ): number {\n if (includes.some((node) => !node.separate)) {\n throw new Error('findEach does not support joined includes');\n }\n const batchSize = cursor.batchSize ?? 100;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error('findEach: batchSize must be a positive integer');\n }\n return batchSize;\n }\n\n #compile(model: ModelStatic<AnyModel>, scoped: FindOptions): CompiledQuery {\n const { definition, runtime } = this.services.registry.state(model);\n const { columns, compiler, selects } = this.services;\n const query = {\n ...scoped,\n where: columns.paranoid(definition, scoped.where, scoped.paranoid),\n };\n return compiler.compile(\n selects.build(definition, query as SelectOptions, runtime.inAsAnyThreshold),\n );\n }\n\n static async #begin(\n runtime: ModelRuntime,\n options: FindOptions,\n ): Promise<Readonly<{ own: Transaction | undefined; transaction: Transaction }>> {\n const own =\n options.transaction === undefined || options.transaction === null\n ? await runtime.beginTransaction()\n : undefined;\n return { own, transaction: own ?? (options.transaction as Transaction) };\n }\n\n async *#iterate<M extends AnyModel>(call: CursorCall<M>): AsyncGenerator<M, void, undefined> {\n let failed = false;\n try {\n yield* this.#fetch(call);\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n await FindCursor.#close(call, failed);\n }\n }\n\n async *#fetch<M extends AnyModel>(call: CursorCall<M>): AsyncGenerator<M, void, undefined> {\n const { model, includes, batchSize, compiled, transaction, name, run } = call;\n await run(`DECLARE ${name} NO SCROLL CURSOR FOR ${compiled.text}`, compiled.values);\n for (;;) {\n const batch = await run(`FETCH ${batchSize} FROM ${name}`);\n if (batch.rows.length === 0) {\n break;\n }\n const instances = batch.rows.map((row) => this.services.rows.instance(model, row));\n if (includes.length > 0) {\n await this.services.loader.loadSeparate(instances, includes, { transaction });\n }\n yield* instances;\n }\n }\n\n static async #close({ own, run, name }: CursorCall<AnyModel>, failed: boolean): Promise<void> {\n if (own === undefined) {\n await run(`CLOSE ${name}`).catch(() => undefined);\n } else if (failed) {\n await own.rollback().catch(() => undefined);\n } else {\n await own.commit();\n }\n }\n}\n","import type { IncludeLoader } from '../../associations/include-loader.ts';\nimport type { IncludeResolver } from '../../associations/include-resolver.ts';\nimport { EmptyResultError } from '../../errors/errors.ts';\nimport type { SqlCompiler } from '../../sql/compile.ts';\nimport type { Transaction } from '../../transaction/transaction.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { FindQueryBuilder } from '../find-query-builder.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type {\n AnyModel,\n CreationAttributes,\n FindOptions,\n FindOrCreateOptions,\n ModelStatic,\n Values,\n} from '../options.ts';\nimport type { RowMapper } from '../row-mapper.ts';\nimport type { SelectQueryBuilder } from '../select-query-builder.ts';\nimport type { WhereOptions } from '../types.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of `FindOperation`. */\nexport type FindOperationServices = OperationServices &\n Readonly<{\n /** Model state and scopes. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** Paranoid filter. */\n columns: AttributeColumns;\n /** Plain SELECT builder (`findEach`). */\n selects: SelectQueryBuilder;\n /** Finder SELECT builder. */\n finds: FindQueryBuilder;\n /** Row parsing. */\n rows: RowMapper;\n /** Include trees. */\n includes: IncludeResolver;\n /** Include row assembly and separate loading. */\n loader: IncludeLoader;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\n/**\n * Finders of `Model` built on `findAll` / `findOne` / `count`: `findOne`, `findByPk`,\n * `findAndCountAll`, `findOrCreate` and `findOrBuild`.\n *\n * @internal\n */\nexport abstract class FindLookups extends ModelOperation<FindOperationServices> {\n /**\n * `Model.findOne`: `findAll` with `limit: 1` (unless given), honouring `rejectOnEmpty`.\n *\n * @param model - Model class.\n * @param options - Find options.\n * @returns Instance or `null`.\n * @throws EmptyResultError (or the given error) with `rejectOnEmpty`.\n */\n async findOne<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOptions & Readonly<{ rejectOnEmpty?: boolean | Error }>,\n ): Promise<M | null> {\n const [first] = await model.findAll({ ...options, limit: options.limit ?? 1 });\n if (\n first === undefined &&\n options.rejectOnEmpty !== undefined &&\n options.rejectOnEmpty !== false\n ) {\n throw options.rejectOnEmpty instanceof Error ? options.rejectOnEmpty : new EmptyResultError();\n }\n return first ?? null;\n }\n\n /**\n * `Model.findByPk`.\n *\n * @param model - Model class.\n * @param key - Primary key value.\n * @param options - Find options.\n * @returns Instance or `null`.\n */\n async findByPk<M extends AnyModel>(\n model: ModelStatic<M>,\n key: unknown,\n options: Omit<FindOptions, 'where'>,\n ): Promise<M | null> {\n if (key === null || key === undefined) {\n return null;\n }\n const name = this.services.registry.definition(model).primaryKeys[0] ?? 'id';\n return model.findOne({ ...options, where: { [name]: key } as WhereOptions });\n }\n\n /**\n * `Model.findAndCountAll`: `count` and `findAll` with the same filter, in parallel.\n *\n * @param model - Model class.\n * @param options - Find options.\n * @returns Total count and rows.\n */\n async findAndCountAll<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOptions,\n ): Promise<Readonly<{ count: number; rows: M[] }>> {\n const [count, rows] = await Promise.all([\n model.count({\n ...(options.where === undefined ? {} : { where: options.where }),\n ...(options.include === undefined ? {} : { include: options.include }),\n ...(options.paranoid === undefined ? {} : { paranoid: options.paranoid }),\n ...this.services.values.queryOptions(options),\n }),\n model.findAll(options),\n ]);\n return { count, rows };\n }\n\n /**\n * `Model.findOrCreate`: finds a row or creates it inside a transaction (re-reading it when a\n * concurrent insert wins).\n *\n * @param model - Model class.\n * @param options - `where` to search, `defaults` to add on creation.\n * @returns `[instance, created]`.\n */\n async findOrCreate<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOrCreateOptions,\n ): Promise<[M, boolean]> {\n const { runtime } = this.services.registry.state(model);\n const found = await model.findOne(options);\n if (found !== null) {\n return [found, false];\n }\n return runtime.transaction(\n (transaction) => this.#create(model, options, transaction),\n options.transaction,\n );\n }\n\n async #create<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOrCreateOptions,\n transaction: Transaction,\n ): Promise<[M, boolean]> {\n const values = {\n ...this.services.values.fromWhere(options.where),\n ...options.defaults,\n } as CreationAttributes<M>;\n try {\n return [\n await model.create(values, { transaction, ...this.services.values.queryOptions(options) }),\n true,\n ];\n } catch (error) {\n return FindLookups.#existing(model, options, error);\n }\n }\n\n static async #existing<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOrCreateOptions,\n error: unknown,\n ): Promise<[M, boolean]> {\n const existing = await model.findOne({ ...options, transaction: options.transaction ?? null });\n if (existing === null) {\n throw error;\n }\n return [existing, false];\n }\n\n /**\n * `Model.findOrBuild`: finds a row or builds (without saving) a new instance.\n *\n * @param model - Model class.\n * @param options - `where` to search, `defaults` to add when building.\n * @returns `[instance, built]`.\n */\n async findOrBuild<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOrCreateOptions,\n ): Promise<[M, boolean]> {\n const found = await model.findOne(options);\n const { values } = this.services;\n return found === null\n ? [model.build({ ...values.fromWhere(options.where), ...options.defaults } as Values), true]\n : [found, false];\n }\n}\n","import type { IncludeNode, IncludeOption } from '../../associations/include.ts';\nimport type { QueryResult } from '../../connection/connection-manager.ts';\nimport { Subquery } from '../../expressions/methods.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { AnyModel, FindOptions, ModelStatic, MutableOptions, Values } from '../options.ts';\nimport { FindCursor } from './find-cursor.ts';\nimport { FindLookups, type FindOperationServices } from './find-lookups.ts';\n\nexport type { FindOperationServices } from './find-lookups.ts';\n\ntype Row = Readonly<Record<string, unknown>>;\n\n// One `Model.findAll` call after the `before` hooks: hook-visible options, query and includes.\ntype FindCall = Readonly<{\n model: ModelStatic<AnyModel>;\n definition: ModelDefinition;\n opts: MutableOptions;\n query: FindOptions;\n includes: readonly IncludeNode[];\n}>;\n\n/**\n * Finders of `Model`: `findAll` (scopes, paranoid filter, hooks, includes, raw / nested rows),\n * `findOne`, `findByPk`, `findAndCountAll`, `findOrCreate`, `findOrBuild`, the cursor-based\n * `findEach` and embeddable `subquery`.\n */\nexport class FindOperation extends FindLookups {\n readonly #cursor: FindCursor;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: FindOperationServices) {\n super(services);\n this.#cursor = new FindCursor(services);\n }\n\n /**\n * `Model.findAll`.\n *\n * @param model - Model class.\n * @param options - Find options.\n * @returns Instances, or plain objects with `raw: true`.\n */\n async findAll<M extends AnyModel>(model: ModelStatic<M>, options: FindOptions): Promise<M[]> {\n const { definition, runtime } = this.services.registry.state(model);\n const { compiler, finds, lifecycle } = this.services;\n const opts: MutableOptions = { hooks: true, ...this.services.registry.scoped(model, options) };\n await this.#beforeFind(model, opts);\n const call = this.#call(model, opts);\n const threshold = runtime.inAsAnyThreshold;\n const select = finds.build(definition, call.query, call.includes, threshold);\n const result = await runtime.execute(compiler.compile(select), call.query, finds.route(select));\n const found = await this.#found(call, result.rows);\n if (opts['hooks'] === true) {\n await lifecycle.runHooks(model, 'afterFind', found, opts);\n }\n return found as M[];\n }\n\n async #beforeFind(model: object, opts: MutableOptions): Promise<void> {\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'beforeFind', opts);\n await this.services.lifecycle.runHooks(model, 'beforeFindAfterExpandIncludeAll', opts);\n await this.services.lifecycle.runHooks(model, 'beforeFindAfterOptions', opts);\n }\n }\n\n #call(model: ModelStatic<AnyModel>, opts: MutableOptions): FindCall {\n const { definition } = this.services.registry.state(model);\n const { columns, includes } = this.services;\n const query = {\n ...(opts as FindOptions),\n where: columns.paranoid(definition, opts['where'], opts['paranoid'] as boolean | undefined),\n };\n const nodes = includes.normalize(model, opts['include'] as IncludeOption | undefined);\n return { model, definition, opts, query: query as FindOptions, includes: nodes };\n }\n\n async #found(call: FindCall, rows: QueryResult['rows']): Promise<AnyModel[]> {\n if (call.opts['raw'] === true) {\n return this.#raw(call, rows);\n }\n const found = this.#instances(call, rows);\n if (call.includes.length > 0) {\n await this.services.loader.loadSeparate(found, call.includes, call.query);\n }\n return found;\n }\n\n #instances({ model, definition, includes }: FindCall, rows: QueryResult['rows']): AnyModel[] {\n return includes.length === 0\n ? rows.map((row) => this.services.rows.instance(model, row))\n : (this.services.loader.assemble(\n model,\n includes,\n rows,\n (row: Row) => this.services.rows.parse(definition, row),\n (target, values) => new target(values, { isNewRecord: false, raw: true }),\n ) as AnyModel[]);\n }\n\n #raw({ definition, opts, includes }: FindCall, rows: QueryResult['rows']): AnyModel[] {\n const { loader, rows: mapper } = this.services;\n const nest = (row: Row): Row => (opts['nest'] === true ? mapper.nest(row as Values) : row);\n if (includes.length === 0) {\n const parsed = mapper.parseAllOwned(definition, rows);\n return (opts['nest'] === true ? parsed.map(nest) : [...parsed]) as unknown as AnyModel[];\n }\n const parseMain = (row: Row) => mapper.parse(definition, row);\n return rows.map((row) =>\n nest(loader.parseRawRow(includes, row, parseMain)),\n ) as unknown as AnyModel[];\n }\n\n /**\n * `Model.findEach`: streams rows with a server-side cursor inside `options.transaction` or its\n * own transaction; the cursor is closed when iteration ends or is stopped early.\n *\n * @param model - Model class.\n * @param options - Find options.\n * @param cursor - `batchSize` (rows per FETCH, default 100).\n * @returns Async iterator of instances.\n * @throws Error for joined includes or an invalid batch size.\n */\n async *findEach<M extends AnyModel>(\n model: ModelStatic<M>,\n options: FindOptions,\n cursor: Readonly<{ batchSize?: number }>,\n ): AsyncGenerator<M, void, undefined> {\n yield* this.#cursor.each(model, options, cursor);\n }\n\n /**\n * `Model.subquery`: a SELECT embeddable in another query, built when the outer query compiles.\n *\n * @param model - Model class.\n * @param options - Find options and `as` (table alias).\n * @returns Subquery expression.\n */\n subquery(\n model: ModelStatic<AnyModel>,\n options: FindOptions & Readonly<{ as?: string }>,\n ): Subquery {\n return new Subquery(() => this.#subquerySelect(model, options));\n }\n\n #subquerySelect(model: ModelStatic<AnyModel>, options: FindOptions & Readonly<{ as?: string }>) {\n const { definition, runtime } = this.services.registry.state(model);\n const { columns, finds, includes, registry } = this.services;\n const { as, ...findOptions } = options;\n const scoped = registry.scoped(model, findOptions as FindOptions);\n const query = {\n ...scoped,\n where: columns.paranoid(definition, scoped.where, scoped.paranoid),\n };\n const nodes = includes.normalize(model, query.include);\n return finds.build(definition, query as FindOptions, nodes, runtime.inAsAnyThreshold, as);\n }\n}\n","import type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type {\n AnyModel,\n AttributeAmounts,\n IncrementOptions,\n ModelStatic,\n Values,\n} from '../options.ts';\nimport type { RowMapper } from '../row-mapper.ts';\nimport type { UpdateQueryBuilder } from '../update-query-builder.ts';\n\n/** Collaborators of {@link IncrementOperation}. */\nexport type IncrementOperationServices = Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** SET items. */\n columns: AttributeColumns;\n /** UPDATE builder. */\n updates: UpdateQueryBuilder;\n /** Instances of returned rows. */\n rows: RowMapper;\n /** SQL compiler. */\n compiler: SqlCompiler;\n}>;\n\n/** `Model.increment` / `Model.decrement`: `SET x = x ± by` (and `updatedAt`) on matching rows. */\nexport class IncrementOperation {\n readonly #services: IncrementOperationServices;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: IncrementOperationServices) {\n this.#services = services;\n }\n\n /**\n * Increments (`sign` 1) or decrements (`sign` -1) attributes of matching rows.\n *\n * @param model - Model class.\n * @param fields - Attribute name(s), or a map of attribute to amount.\n * @param options - Increment options.\n * @param sign - `1` or `-1`.\n * @returns Updated instances and the affected row count.\n */\n async change<M extends AnyModel>(\n model: ModelStatic<M>,\n fields: AttributeAmounts<Values>,\n options: IncrementOptions,\n sign: 1 | -1,\n ): Promise<[M[], number]> {\n const { definition, runtime } = this.#services.registry.state(model);\n const { compiler, rows, updates } = this.#services;\n const set = this.#setItems(definition, fields, options, sign);\n const node = updates.build(definition, set, options.where ?? {}, { returning: true });\n const result = await runtime.execute(compiler.compile(node), options);\n return [result.rows.map((row) => rows.instance(model, row)), result.rowCount];\n }\n\n #setItems(\n definition: ModelDefinition,\n fields: AttributeAmounts<Values>,\n options: IncrementOptions,\n sign: 1 | -1,\n ) {\n const { columns, updates, values } = this.#services;\n const amounts = values.amounts(fields, options.by ?? 1);\n const silent = options.silent === true;\n const timestamp = values.withTimestamps(definition, {}, new Date(), false, silent);\n return [\n ...updates.increment(definition, amounts, sign),\n ...columns.setItems(definition, timestamp),\n ];\n }\n}\n","import type { Subquery } from '../../expressions/methods.ts';\nimport type { InsertNode, OnConflictNode } from '../../sql/ast.ts';\nimport type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { InsertQueryBuilder } from '../insert-query-builder.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type { OnConflictBuilder, OnConflictOptions } from '../on-conflict-builder.ts';\nimport type {\n AnyModel,\n InsertFromOptions,\n InsertOptions,\n ModelStatic,\n MutableOptions,\n Values,\n} from '../options.ts';\nimport type { ReturningOld } from '../returning-old.ts';\nimport type { QueryOptionsBase } from '../runtime.ts';\nimport type { WrittenRows } from '../written-rows.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link InsertOperation}. */\nexport type InsertOperationServices = OperationServices &\n Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** RETURNING lists. */\n columns: AttributeColumns;\n /** INSERT builder. */\n inserts: InsertQueryBuilder;\n /** ON CONFLICT builder. */\n conflicts: OnConflictBuilder;\n /** `returningOld` support. */\n returningOld: ReturningOld;\n /** Instances of returned rows. */\n written: WrittenRows;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\ntype ConflictOptions = Readonly<{ onConflict?: unknown }>;\n\n/**\n * `INSERT ... ON CONFLICT ... RETURNING` writes that return the written rows with `wasInserted`:\n * `Model.insert`, `Model.insertFrom` and the `onConflict` paths of `create` / `bulkCreate`.\n */\nexport class InsertOperation extends ModelOperation<InsertOperationServices> {\n /**\n * `Model.insert`: inserts rows with `INSERT ... ON CONFLICT` and returns the written rows.\n *\n * @param model - Model class.\n * @param values - One row or several rows.\n * @param options - Insert options.\n * @returns Instances of the rows written by the statement.\n */\n async insert<M extends AnyModel>(\n model: ModelStatic<M>,\n values: Values | readonly Values[],\n options: InsertOptions,\n ): Promise<M[]> {\n const { definition } = this.services.registry.state(model);\n const now = new Date();\n const records: readonly Values[] = Array.isArray(values) ? values : [values as Values];\n if (records.length === 0) {\n return [];\n }\n const opts: MutableOptions = { hooks: true, validate: false, ...options };\n const instances = records.map((record) => new model(record));\n await this.#before(model, instances, opts);\n const inserted = await this.#write(model, definition, instances, now, options);\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'afterBulkCreate', inserted, opts);\n }\n return inserted;\n }\n\n async #before(model: object, instances: readonly AnyModel[], opts: MutableOptions) {\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'beforeBulkCreate', instances, opts);\n }\n if (opts['validate'] === true) {\n await this.services.lifecycle.validateAll(instances, false);\n }\n }\n\n #write<M extends AnyModel>(\n model: ModelStatic<M>,\n definition: ModelDefinition,\n instances: readonly AnyModel[],\n now: Date,\n options: InsertOptions,\n ): Promise<M[]> {\n const rows = this.#rows(definition, instances, now, options);\n const onConflict = this.#onConflict(definition, options);\n return this.withConflict(model, rows, onConflict, options);\n }\n\n #rows(\n definition: ModelDefinition,\n instances: readonly AnyModel[],\n now: Date,\n options: InsertOptions,\n ): Values[] {\n const { values } = this.services;\n return instances.map((instance) =>\n values.pick(\n values.withTimestamps(definition, instance.dataValues as Values, now, true, false),\n options.fields as readonly string[] | undefined,\n ),\n );\n }\n\n #onConflict(definition: ModelDefinition, options: ConflictOptions): OnConflictNode | undefined {\n return options.onConflict === undefined\n ? undefined\n : this.services.conflicts.build(definition, options.onConflict as OnConflictOptions<unknown>);\n }\n\n /**\n * `Model.insertFrom`: `INSERT INTO ... SELECT` from a subquery.\n *\n * @param model - Model class.\n * @param source - Subquery whose columns match `options.columns`.\n * @param options - Target columns, `onConflict` and query options.\n * @returns Written rows.\n */\n async insertFrom<M extends AnyModel>(\n model: ModelStatic<M>,\n source: Subquery,\n options: InsertFromOptions,\n ): Promise<M[]> {\n const { definition, runtime } = this.services.registry.state(model);\n const onConflict = this.#onConflict(definition, options);\n const node = this.services.inserts.fromSelect(\n definition,\n options.columns as readonly string[],\n source.build(),\n onConflict,\n this.#returning(definition),\n );\n const old = await this.services.returningOld.enabled(runtime, options);\n return this.#execute(model, node, old, options);\n }\n\n /**\n * Inserts attribute-keyed rows with an optional ON CONFLICT clause and returns the written rows\n * with `wasInserted`.\n *\n * @param model - Model class.\n * @param rows - Values by attribute name.\n * @param onConflict - ON CONFLICT clause.\n * @param options - Query options, `overriding`, `returningOld`.\n * @returns Instances of the written rows.\n */\n async withConflict<M extends AnyModel>(\n model: ModelStatic<M>,\n rows: readonly Values[],\n onConflict: OnConflictNode | undefined,\n options: QueryOptionsBase &\n Readonly<{ overriding?: 'system' | 'user'; returningOld?: boolean }>,\n ): Promise<M[]> {\n const { definition, runtime } = this.services.registry.state(model);\n const old = await this.services.returningOld.enabled(runtime, options);\n const insert = this.services.inserts.build(definition, rows, {\n ...(onConflict === undefined ? {} : { onConflict }),\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n returning: this.#returning(definition),\n });\n return this.#execute(model, insert, old, options);\n }\n\n #returning(definition: ModelDefinition) {\n const { columns, conflicts } = this.services;\n return [...columns.returningAll(definition), conflicts.insertedFlagColumn()];\n }\n\n async #execute<M extends AnyModel>(\n model: ModelStatic<M>,\n node: InsertNode,\n old: boolean,\n options: QueryOptionsBase,\n ): Promise<M[]> {\n const { definition, runtime } = this.services.registry.state(model);\n const { compiler, returningOld, written } = this.services;\n const statement = old ? returningOld.node(definition, node) : node;\n const result = await runtime.execute(compiler.compile(statement), options);\n return result.rows.map((row) => written.inserted(model, row, old));\n }\n}\n","import type { CompiledQuery, SqlCompiler } from '../sql/compile.ts';\nimport type { InsertQueryBuilder } from './insert-query-builder.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { OnConflictBuilder } from './on-conflict-builder.ts';\nimport type { BulkCreateOptions } from './options.ts';\nimport type { UnnestInsertBuilder } from './unnest-insert-builder.ts';\n\n/** Builds the INSERT of `Model.bulkCreate`: multi-row `VALUES`, or `unnest` arrays with `unnest: true`. */\nexport class BulkInsertBuilder {\n readonly #inserts: InsertQueryBuilder;\n readonly #unnests: UnnestInsertBuilder;\n readonly #conflicts: OnConflictBuilder;\n readonly #compiler: SqlCompiler;\n\n /**\n * @param inserts - VALUES INSERT builder.\n * @param unnests - `unnest` INSERT builder.\n * @param conflicts - Sequelize v6 conflict options builder.\n * @param compiler - SQL compiler.\n */\n constructor(\n inserts: InsertQueryBuilder,\n unnests: UnnestInsertBuilder,\n conflicts: OnConflictBuilder,\n compiler: SqlCompiler,\n ) {\n this.#inserts = inserts;\n this.#unnests = unnests;\n this.#conflicts = conflicts;\n this.#compiler = compiler;\n }\n\n /**\n * @param definition - Model definition.\n * @param rows - Values by attribute name.\n * @param options - Bulk create options.\n * @returns The compiled INSERT.\n */\n build(\n definition: ModelDefinition,\n rows: readonly Readonly<Record<string, unknown>>[],\n options: BulkCreateOptions,\n ): CompiledQuery {\n if (options.unnest === true) {\n return this.#unnests.build(definition, rows, options);\n }\n return this.#compiler.compile(\n this.#inserts.build(definition, rows, {\n returning: options.returning !== false,\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n ...this.#conflicts.v6Bulk(definition, options),\n }),\n );\n }\n}\n","import type { InsertNode } from '../sql/ast.ts';\nimport type { CompiledQuery, SqlCompiler } from '../sql/compile.ts';\nimport type { InsertQueryBuilder } from './insert-query-builder.ts';\nimport type { ModelDefinition } from './model-definition.ts';\nimport type { BulkCreateOptions } from './options.ts';\n\nconst SOURCE_NAME = '__pgz_unnest__';\n\ntype Column = Readonly<{ type: string; cells: readonly unknown[] }>;\n\n/**\n * Builds `INSERT INTO t (cols) SELECT * FROM unnest($1::type[], …)` for `bulkCreate({ unnest: true })`:\n * one array parameter per column, so the 65535-parameter limit does not cap the batch size.\n */\nexport class UnnestInsertBuilder {\n readonly #inserts: InsertQueryBuilder;\n readonly #compiler: SqlCompiler;\n\n /**\n * @param inserts - VALUES INSERT builder, reused for columns, table and RETURNING.\n * @param compiler - SQL compiler.\n */\n constructor(inserts: InsertQueryBuilder, compiler: SqlCompiler) {\n this.#inserts = inserts;\n this.#compiler = compiler;\n }\n\n /**\n * @param definition - Model definition.\n * @param rows - Values by attribute name.\n * @param options - `returning` and `overriding` of the bulk create.\n * @returns The compiled INSERT; its values are the column arrays.\n * @throws Error for conflict options, `ARRAY` columns, or rows that leave a column to its default.\n */\n build(\n definition: ModelDefinition,\n rows: readonly Readonly<Record<string, unknown>>[],\n options: BulkCreateOptions,\n ): CompiledQuery {\n UnnestInsertBuilder.#assertSupported(options);\n const node = this.#inserts.build(definition, rows, {\n returning: options.returning !== false,\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n });\n const columns = UnnestInsertBuilder.#columns(definition, node);\n const source = columns.map(({ type }, index) => `$${index + 1}::${type}[]`).join(', ');\n return {\n text: this.#compile(node).replace(`\"${SOURCE_NAME}\"`, `unnest(${source})`),\n values: columns.map(({ cells }) => cells),\n };\n }\n\n // The AST has no function in FROM yet: the source is a placeholder table swapped after compiling.\n #compile(node: InsertNode): string {\n return this.#compiler.compile({\n ...node,\n rows: [],\n select: { kind: 'select', columns: [{ kind: 'raw', sql: '*' }], from: { name: SOURCE_NAME } },\n }).text;\n }\n\n static #assertSupported(options: BulkCreateOptions): void {\n if (\n options.onConflict !== undefined ||\n options.ignoreDuplicates === true ||\n options.updateOnDuplicate !== undefined\n ) {\n throw new Error('bulkCreate unnest cannot be combined with conflict options');\n }\n }\n\n static #columns(definition: ModelDefinition, node: InsertNode): readonly Column[] {\n return node.columns.map((field, index) => {\n const attribute = [...definition.attributes.values()].find((item) => item.field === field);\n if (attribute === undefined || attribute.type.key === 'ARRAY') {\n throw new Error(`bulkCreate unnest does not support column \"${field}\"`);\n }\n const cells = node.rows.map((row) => {\n const cell = row[index];\n if (cell?.kind !== 'param') {\n throw new Error(`bulkCreate unnest needs a value for \"${field}\" in every row`);\n }\n return cell.value;\n });\n return { type: attribute.type.sqlType, cells };\n });\n }\n}\n","import type { SqlCompiler } from '../../sql/compile.ts';\nimport { MergeQueryBuilder, type MergeOptions } from '../merge-query-builder.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport type { ReturningOld } from '../returning-old.ts';\nimport type { QueryOptionsBase } from '../runtime.ts';\nimport type { WrittenRows } from '../written-rows.ts';\n\n/** Action reported by `merge_action()`. */\nexport type MergeActionName = 'INSERT' | 'UPDATE' | 'DELETE';\n\n/** Result of `Model.merge`. */\nexport type MergeResult<M> = Readonly<{\n /** Number of affected rows. */\n rowCount: number;\n /** Written rows (with `returning: true`). */\n rows: readonly Readonly<{\n /** Action taken. */ action: MergeActionName;\n /** Row after the action. */ instance: M;\n }>[];\n}>;\n\n/** Options of `Model.merge` with query and RETURNING options. */\nexport type MergeCallOptions = MergeOptions<unknown> &\n QueryOptionsBase &\n Readonly<{\n /** Return written rows (PostgreSQL 17+). */\n returning?: boolean;\n /** With `returning`: expose pre-statement values as `instance.oldValues` (PostgreSQL 18+). */\n returningOld?: boolean;\n }>;\n\n/** Collaborators of {@link MergeOperation}. */\nexport type MergeOperationServices = Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** MERGE builder. */\n merges: MergeQueryBuilder;\n /** `returningOld` support. */\n returningOld: ReturningOld;\n /** Instances of returned rows. */\n written: WrittenRows;\n /** SQL compiler. */\n compiler: SqlCompiler;\n}>;\n\n/** `Model.merge`: `MERGE INTO ... USING ...` with server version checks (PostgreSQL 15 / 17 / 18). */\nexport class MergeOperation {\n readonly #services: MergeOperationServices;\n\n /**\n * @param services - Collaborators.\n */\n constructor(services: MergeOperationServices) {\n this.#services = services;\n }\n\n /**\n * `Model.merge`.\n *\n * @param model - Model class.\n * @param options - Source, join condition, WHEN clauses, `returning`, `returningOld`.\n * @returns Affected row count and, with `returning`, `{ action, instance }` per row.\n * @throws Error when the server is too old for the requested features.\n */\n async merge<M extends AnyModel>(\n model: ModelStatic<M>,\n options: MergeCallOptions,\n ): Promise<MergeResult<M>> {\n const { definition, runtime } = this.#services.registry.state(model);\n const { compiler, merges, returningOld, written } = this.#services;\n MergeOperation.#check(await runtime.serverVersion(), options);\n const old = await returningOld.enabled(runtime, options);\n const node = merges.build(definition, options, options.returning === true);\n const statement = old ? returningOld.node(definition, node) : node;\n const result = await runtime.execute(compiler.compile(statement), options);\n return {\n rowCount: result.rowCount,\n rows: result.rows.map((row) => ({\n action: String(row[MergeQueryBuilder.ACTION]) as MergeActionName,\n instance: written.instance(model, row, old),\n })),\n };\n }\n\n static #check(version: number, options: MergeCallOptions): void {\n if (version < 150000) {\n throw new Error('merge requires PostgreSQL 15 or newer');\n }\n if (\n (options.returning === true || options.whenNotMatchedBySource !== undefined) &&\n version < 170000\n ) {\n throw new Error(\n 'merge with returning or whenNotMatchedBySource requires PostgreSQL 17 or newer',\n );\n }\n if (options.returningOld === true && options.returning !== true) {\n throw new Error('merge: returningOld requires returning: true');\n }\n }\n}\n","import type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { JoinSourceBuilder } from '../join-source-builder.ts';\nimport type { ModelRegistry, ModelState } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport type { AnyModel, ModelStatic, MutableOptions, UpdateOptions, Values } from '../options.ts';\nimport type { ReturningOld } from '../returning-old.ts';\nimport type { UpdateQueryBuilder } from '../update-query-builder.ts';\nimport type { WrittenRows } from '../written-rows.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link UpdateOperation}. */\nexport type UpdateOperationServices = OperationServices &\n Readonly<{\n /** Model state and scopes. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** SET items, paranoid filter. */\n columns: AttributeColumns;\n /** UPDATE builder. */\n updates: UpdateQueryBuilder;\n /** `from` relations. */\n joins: JoinSourceBuilder;\n /** `returningOld` support. */\n returningOld: ReturningOld;\n /** Instances of returned rows. */\n written: WrittenRows;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\ntype UpdateResult<M> = [affectedCount: number, affectedRows?: M[]];\n\n// One `Model.update` call: the hook-visible options and the caller's options.\ntype UpdateCall = Readonly<{\n model: ModelStatic<AnyModel>;\n state: ModelState;\n opts: MutableOptions;\n options: UpdateOptions;\n where: unknown;\n individual: boolean;\n}>;\n\n/** `Model.update`: bulk UPDATE with validation, bulk / individual hooks, `from` and `returning`. */\nexport class UpdateOperation extends ModelOperation<UpdateOperationServices> {\n /**\n * `Model.update`.\n *\n * @param model - Model class.\n * @param values - New attribute values.\n * @param options - Update options.\n * @returns `[affectedCount]`, or `[affectedCount, rows]` with `returning: true`.\n * @throws Error for `individualHooks` with `from`, or `returningOld` without `returning`.\n */\n async update<M extends AnyModel>(\n model: ModelStatic<M>,\n values: Values,\n options: UpdateOptions,\n ): Promise<UpdateResult<M>> {\n const opts: MutableOptions = {\n validate: true,\n hooks: true,\n individualHooks: false,\n ...this.services.registry.scoped(model, options),\n attributes: { ...values },\n };\n if (opts['validate'] === true) {\n await this.#validate(model, values, opts);\n }\n return (await this.#bulkUpdate(model, opts, options)) as UpdateResult<M>;\n }\n\n async #validate(model: ModelStatic<AnyModel>, values: Values, opts: MutableOptions) {\n const { definition } = this.services.registry.state(model);\n await new model(values, { isNewRecord: false }).validate({\n hooks: opts['hooks'] === true,\n skip: [...definition.attributes.keys()].filter((name) => !(name in values)),\n });\n }\n\n @ModelOperation.bulkHooks('beforeBulkUpdate', 'afterBulkUpdate')\n async #bulkUpdate(\n model: ModelStatic<AnyModel>,\n opts: MutableOptions,\n options: UpdateOptions,\n ): Promise<UpdateResult<AnyModel>> {\n const state = this.services.registry.state(model);\n const paranoid = opts['paranoid'] as boolean | undefined;\n const where = this.services.columns.paranoid(state.definition, opts['where'], paranoid);\n const individual = opts['individualHooks'] === true;\n const call = { model, state, opts, options, where, individual };\n if (call.individual) {\n await this.#beforeEach(call);\n }\n UpdateOperation.#check(call);\n const updated = await this.#execute(call);\n if (call.individual) {\n await this.services.lifecycle.runEach(model, 'afterUpdate', updated.rows, opts);\n }\n return options.returning === true ? [updated.count, updated.rows] : [updated.count];\n }\n\n async #beforeEach({ model, where, opts, options }: UpdateCall) {\n const targets = await model.findAll({\n where: where as never,\n ...this.services.values.queryOptions(options),\n paranoid: false,\n });\n targets.forEach((instance) => instance.set(opts['attributes'] as Values));\n await this.services.lifecycle.runEach(model, 'beforeUpdate', targets, opts);\n }\n\n static #check({ options, individual }: UpdateCall): void {\n if (individual && options.from !== undefined) {\n throw new Error('update: individualHooks cannot be combined with from');\n }\n if (options.returningOld === true && options.returning !== true) {\n throw new Error('update: returningOld requires returning: true');\n }\n }\n\n async #execute(call: UpdateCall): Promise<Readonly<{ count: number; rows: AnyModel[] }>> {\n const { definition, runtime } = call.state;\n const { returningOld, compiler, written } = this.services;\n const old = await returningOld.enabled(runtime, call.options);\n const node = this.#statement(call);\n const statement = old ? returningOld.node(definition, node) : node;\n const result = await runtime.execute(compiler.compile(statement), call.options);\n const rows = result.rows.map((row) => written.instance(call.model, row, old));\n return { count: result.rowCount, rows };\n }\n\n #statement(call: UpdateCall) {\n const { definition, runtime } = call.state;\n const { columns, joins, updates } = this.services;\n const from = joins.build(call.options.from);\n const ctx = columns.whereCompiler(definition, from.length === 0 ? undefined : definition.name);\n const threshold = runtime.inAsAnyThreshold;\n return updates.build(\n definition,\n columns.setItems(definition, this.#changes(call), ctx),\n call.where,\n {\n ...(from.length === 0 ? {} : { from }),\n ...(call.options.returning === true || call.individual ? { returning: true } : {}),\n ...(threshold === undefined ? {} : { inAsAnyThreshold: threshold }),\n },\n );\n }\n\n #changes({ state: { definition }, opts, options }: UpdateCall): Values {\n const { values } = this.services;\n const fields = options.fields as readonly string[] | undefined;\n const picked = values.pick(opts['attributes'] as Values, fields);\n return values.withTimestamps(definition, picked, new Date(), false, opts['silent'] === true);\n }\n}\n","import type { SqlCompiler } from '../../sql/compile.ts';\nimport type { AttributeColumns } from '../attribute-columns.ts';\nimport type { InsertQueryBuilder } from '../insert-query-builder.ts';\nimport { InstanceState } from '../instance-state.ts';\nimport type { ModelDefinition } from '../model-definition.ts';\nimport type { ModelRegistry } from '../model-registry.ts';\nimport type { ModelValues } from '../model-values.ts';\nimport { OnConflictBuilder, type OnConflictOptions } from '../on-conflict-builder.ts';\nimport type { AnyModel, ModelStatic, MutableOptions, UpsertOptions, Values } from '../options.ts';\nimport type { WrittenRows } from '../written-rows.ts';\nimport { ModelOperation, type OperationServices } from './model-operation.ts';\n\n/** Collaborators of {@link UpsertOperation}. */\nexport type UpsertOperationServices = OperationServices &\n Readonly<{\n /** Model state. */\n registry: ModelRegistry;\n /** Value rules. */\n values: ModelValues;\n /** RETURNING lists. */\n columns: AttributeColumns;\n /** INSERT builder. */\n inserts: InsertQueryBuilder;\n /** ON CONFLICT builder. */\n conflicts: OnConflictBuilder;\n /** Marker columns of returned rows. */\n written: WrittenRows;\n /** SQL compiler. */\n compiler: SqlCompiler;\n }>;\n\ntype UpsertResult = [AnyModel, boolean | null];\n\n// One `Model.upsert` call: the built instance, both option objects and the updatable attributes.\ntype UpsertCall = Readonly<{\n model: ModelStatic<AnyModel>;\n definition: ModelDefinition;\n instance: AnyModel;\n values: Values;\n opts: MutableOptions;\n options: UpsertOptions;\n now: Date;\n updatable: readonly string[];\n}>;\n\n/** `Model.upsert`: `INSERT ... ON CONFLICT DO UPDATE` with Sequelize v6 target rules or `onConflict`. */\nexport class UpsertOperation extends ModelOperation<UpsertOperationServices> {\n /**\n * `Model.upsert`.\n *\n * @param model - Model class.\n * @param values - Attribute values.\n * @param options - Upsert options.\n * @returns `[instance, null]` like Sequelize v6, or `[instance, created]` with `onConflict`.\n */\n async upsert<M extends AnyModel>(\n model: ModelStatic<M>,\n values: Values,\n options: UpsertOptions,\n ): Promise<[M, boolean | null]> {\n const { definition } = this.services.registry.state(model);\n const opts: MutableOptions = { hooks: true, validate: true, returning: true, ...options };\n const instance = new model(values);\n const now = new Date();\n const updatable = UpsertOperation.#updatable(definition, values, options);\n const call = { model, definition, instance, values, opts, options, now, updatable };\n await this.#before(call);\n const upserted = await this.#write(call);\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'afterUpsert', upserted, opts);\n }\n return upserted as [M, boolean | null];\n }\n\n static #updatable(definition: ModelDefinition, values: Values, options: UpsertOptions): string[] {\n const provided = Object.keys(values).filter((name) => definition.attributes.has(name));\n return options.fields === undefined\n ? provided\n : provided.filter((name) => options.fields?.includes(name as never));\n }\n\n async #before({ model, instance, values, opts, updatable }: UpsertCall): Promise<void> {\n if (opts['validate'] === true) {\n await instance.validate({ hooks: opts['hooks'] === true, fields: updatable });\n }\n if (opts['hooks'] === true) {\n await this.services.lifecycle.runHooks(model, 'beforeUpsert', values, opts);\n }\n }\n\n async #write(call: UpsertCall): Promise<UpsertResult> {\n const { runtime } = this.services.registry.state(call.model);\n const insert = this.#statement(call);\n const result = await runtime.execute(this.services.compiler.compile(insert), call.options);\n return this.#refresh(call, result.rows[0]);\n }\n\n #statement(call: UpsertCall) {\n const { definition, options, updatable } = call;\n const { columns, conflicts, inserts } = this.services;\n const insertValues = this.#insertValues(call);\n const onConflict =\n options.onConflict === undefined\n ? conflicts.v6Upsert(definition, insertValues, updatable, options.conflictFields)\n : conflicts.build(definition, options.onConflict as OnConflictOptions<unknown>);\n return inserts.build(definition, [insertValues], {\n onConflict,\n ...(options.overriding === undefined ? {} : { overriding: options.overriding }),\n returning: [...columns.returningAll(definition), conflicts.insertedFlagColumn()],\n });\n }\n\n #insertValues({ definition, instance, values, now }: UpsertCall): Values {\n const data = instance.dataValues as Values;\n return this.#withoutGeneratedKey(definition, values, {\n ...this.services.values.withTimestamps(definition, data, now, true, false),\n ...(definition.updatedAt !== undefined &&\n values[definition.updatedAt] !== undefined &&\n values[definition.updatedAt] !== null\n ? { [definition.updatedAt]: data[definition.updatedAt] }\n : {}),\n });\n }\n\n #refresh(\n { definition, instance, options }: UpsertCall,\n row: Readonly<Record<string, unknown>> | undefined,\n ): UpsertResult {\n const flag = row?.[OnConflictBuilder.INSERTED_FLAG];\n this.services.lifecycle.refresh(\n instance,\n definition,\n row === undefined ? undefined : this.services.written.withoutMarkers(row),\n );\n if (options.onConflict !== undefined) {\n InstanceState.of(instance).wasInserted = flag === true;\n }\n return [instance, options.onConflict === undefined ? null : flag === true];\n }\n\n /** Leaves out an auto-generated primary key that was not provided (so the sequence fills it). */\n #withoutGeneratedKey(definition: ModelDefinition, provided: Values, values: Values): Values {\n const key = definition.primaryKeys[0];\n return key !== undefined &&\n !(key in provided) &&\n definition.attributes.get(key)?.defaultValue === undefined\n ? Object.fromEntries(Object.entries(values).filter(([name]) => name !== key))\n : values;\n }\n}\n","import { CopyEncoder } from '../connection/copy.ts';\nimport { SqlLiteral } from '../ddl/sql-literal.ts';\nimport { MergeQueryBuilder } from './merge-query-builder.ts';\nimport {\n attributeColumns,\n cteBuilder,\n deleteQueries,\n findQueries,\n includeLoader,\n includeQueries,\n includeResolver,\n insertQueries,\n joinSources,\n lifecycle,\n modelValues,\n onConflictBuilder,\n registry,\n returningOld,\n rowMapper,\n selectQueries,\n sqlCompiler,\n updateQueries,\n writtenRows,\n} from './model-services.ts';\nimport { BulkCreateOperation } from './operations/bulk-create-operation.ts';\nimport { CopyOperation } from './operations/copy-operation.ts';\nimport { CountOperation } from './operations/count-operation.ts';\nimport { CreateOperation } from './operations/create-operation.ts';\nimport { DestroyOperation } from './operations/destroy-operation.ts';\nimport { FindOperation } from './operations/find-operation.ts';\nimport { IncrementOperation } from './operations/increment-operation.ts';\nimport { InsertOperation } from './operations/insert-operation.ts';\nimport { BulkInsertBuilder } from './bulk-insert-builder.ts';\nimport { UnnestInsertBuilder } from './unnest-insert-builder.ts';\nimport { MergeOperation } from './operations/merge-operation.ts';\nimport { UpdateOperation } from './operations/update-operation.ts';\nimport { UpsertOperation } from './operations/upsert-operation.ts';\n\n// Model operations wired to the shared services (internal wiring of `Model`).\n\nexport const finder = new FindOperation({\n registry,\n lifecycle,\n values: modelValues,\n columns: attributeColumns,\n selects: selectQueries,\n finds: findQueries,\n rows: rowMapper,\n includes: includeResolver,\n loader: includeLoader,\n compiler: sqlCompiler,\n});\nexport const counter = new CountOperation({\n registry,\n lifecycle,\n columns: attributeColumns,\n selects: selectQueries,\n cte: cteBuilder,\n rows: rowMapper,\n includes: includeResolver,\n includeQueries,\n compiler: sqlCompiler,\n});\nexport const inserter = new InsertOperation({\n registry,\n lifecycle,\n values: modelValues,\n columns: attributeColumns,\n inserts: insertQueries,\n conflicts: onConflictBuilder,\n returningOld,\n written: writtenRows,\n compiler: sqlCompiler,\n});\nexport const creator = new CreateOperation({\n registry,\n lifecycle,\n values: modelValues,\n conflicts: onConflictBuilder,\n inserter,\n});\nexport const bulkCreator = new BulkCreateOperation({\n registry,\n lifecycle,\n values: modelValues,\n bulkInserts: new BulkInsertBuilder(\n insertQueries,\n new UnnestInsertBuilder(insertQueries, sqlCompiler),\n onConflictBuilder,\n sqlCompiler,\n ),\n conflicts: onConflictBuilder,\n inserter,\n written: writtenRows,\n});\nexport const upserter = new UpsertOperation({\n registry,\n lifecycle,\n values: modelValues,\n columns: attributeColumns,\n inserts: insertQueries,\n conflicts: onConflictBuilder,\n written: writtenRows,\n compiler: sqlCompiler,\n});\nexport const updater = new UpdateOperation({\n registry,\n lifecycle,\n values: modelValues,\n columns: attributeColumns,\n updates: updateQueries,\n joins: joinSources,\n returningOld,\n written: writtenRows,\n compiler: sqlCompiler,\n});\nexport const destroyer = new DestroyOperation({\n registry,\n lifecycle,\n values: modelValues,\n columns: attributeColumns,\n updates: updateQueries,\n deletes: deleteQueries,\n joins: joinSources,\n rows: rowMapper,\n compiler: sqlCompiler,\n});\nexport const incrementer = new IncrementOperation({\n registry,\n values: modelValues,\n columns: attributeColumns,\n updates: updateQueries,\n rows: rowMapper,\n compiler: sqlCompiler,\n});\nexport const merger = new MergeOperation({\n registry,\n merges: new MergeQueryBuilder(attributeColumns),\n returningOld,\n written: writtenRows,\n compiler: sqlCompiler,\n});\nexport const copier = new CopyOperation({\n registry,\n columns: attributeColumns,\n finds: findQueries,\n includes: includeResolver,\n encoder: new CopyEncoder(),\n literals: new SqlLiteral(),\n compiler: sqlCompiler,\n});\n","import { counter } from '../model-operations.ts';\nimport type { Model } from '../model.ts';\nimport type { AggregateOptions, AnyModel, Attributes, ModelStatic } from '../options.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Aggregate statics of `Model`: `aggregate`, `max`, `min`, `sum`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelAggregates = <TBase extends ModelConstructor>(Base: TBase) => {\n return class AggregatesCapability extends Base {\n /**\n * Runs one SQL aggregate function over a column (`SELECT fn(col) ...`), applying the default scope\n * and the paranoid filter. The function name is checked against a safe name pattern, never\n * concatenated unchecked.\n *\n * @param this - The model class.\n * @param field - Attribute name or `'*'`.\n * @param aggregateFunction - SQL aggregate function name, e.g. `'max'`.\n * @param options - Options (`where`, `distinct`, `group`, `plain: false` to get rows, query options).\n * @returns Aggregated value: a number for `count` and numeric attributes, otherwise parsed like the attribute; rows with `plain: false`.\n * @example\n * ```ts\n * const avgPrice = await Product.aggregate('price', 'avg', { where: { active: true } });\n * ```\n */\n static aggregate<M extends AnyModel, T = unknown>(\n this: ModelStatic<M>,\n field: keyof Attributes<M> | '*',\n aggregateFunction: string,\n options: AggregateOptions<Attributes<M>> = {},\n ): Promise<T> {\n return counter.aggregate(\n this,\n String(field),\n aggregateFunction,\n options as AggregateOptions,\n ) as Promise<T>;\n }\n\n /**\n * Finds the largest value of an attribute with `max()`.\n *\n * @param this - The model class.\n * @param field - Attribute name.\n * @param options - Options, see {@link Model.aggregate}.\n * @returns Maximum or `null` when there are no rows.\n * @example\n * ```ts\n * const highest = await Product.max('price');\n * ```\n */\n static max<M extends AnyModel, T = unknown>(\n this: ModelStatic<M>,\n field: keyof Attributes<M>,\n options?: AggregateOptions<Attributes<M>>,\n ): Promise<T> {\n return (this as unknown as typeof Model).aggregate.call(\n this,\n field as never,\n 'max',\n options as AggregateOptions,\n ) as Promise<T>;\n }\n\n /**\n * Finds the smallest value of an attribute with `min()`.\n *\n * @param this - The model class.\n * @param field - Attribute name.\n * @param options - Options, see {@link Model.aggregate}.\n * @returns Minimum or `null` when there are no rows.\n * @example\n * ```ts\n * const lowest = await Product.min('price', { where: { active: true } });\n * ```\n */\n static min<M extends AnyModel, T = unknown>(\n this: ModelStatic<M>,\n field: keyof Attributes<M>,\n options?: AggregateOptions<Attributes<M>>,\n ): Promise<T> {\n return (this as unknown as typeof Model).aggregate.call(\n this,\n field as never,\n 'min',\n options as AggregateOptions,\n ) as Promise<T>;\n }\n\n /**\n * Adds up the values of an attribute with `sum()`.\n *\n * @param this - The model class.\n * @param field - Attribute name.\n * @param options - Options, see {@link Model.aggregate}.\n * @returns Sum, or `null` when there are no rows (as returned by PostgreSQL).\n * @example\n * ```ts\n * const total = await Invoice.sum('amount', { where: { paid: true } });\n * ```\n */\n static sum<M extends AnyModel>(\n this: ModelStatic<M>,\n field: keyof Attributes<M>,\n options?: AggregateOptions<Attributes<M>>,\n ): Promise<number> {\n return (this as unknown as typeof Model).aggregate.call(\n this,\n field as never,\n 'sum',\n options as AggregateOptions,\n ) as Promise<number>;\n }\n };\n};\n","import type { AnyModel } from '../model/options.ts';\nimport type { AssociationName, AssociationType } from './types.ts';\n\ntype Instance = AnyModel;\ntype AccessorImplementation = (instance: Instance, ...args: never[]) => unknown;\n\n/** Accessor key (see {@link Association.accessors}) → association method implementing it. */\nconst ACCESSOR_METHODS: Readonly<Record<string, string>> = {\n get: 'get',\n set: 'set',\n create: 'create',\n add: 'add',\n addMultiple: 'add',\n remove: 'remove',\n removeMultiple: 'remove',\n hasSingle: 'has',\n hasAll: 'has',\n count: 'count',\n};\n\n/** Names of the accessor methods of an association and their installation on a prototype. */\nexport class AssociationAccessors {\n /**\n * Accessor method names of an association.\n *\n * @param type - Kind of association.\n * @param name - Singular and plural alias forms.\n * @returns Accessor key → method name.\n */\n namesFor(type: AssociationType, name: AssociationName): Readonly<Record<string, string>> {\n const singular = this.#upperFirst(name.singular);\n const plural = this.#upperFirst(name.plural);\n return type === 'BelongsTo' || type === 'HasOne'\n ? this.#single(singular)\n : this.#multi(singular, plural);\n }\n\n /**\n * Installs the accessor methods on a model prototype, leaving existing methods untouched.\n *\n * @param association - Association whose methods implement the accessors.\n * @param prototype - Source model prototype.\n * @param accessors - Accessor key → method name.\n */\n install(\n association: object,\n prototype: object,\n accessors: Readonly<Record<string, string>>,\n ): void {\n const methods = association as Readonly<Record<string, unknown>>;\n Object.entries(accessors).forEach(([key, methodName]) => {\n const implementation = methods[ACCESSOR_METHODS[key] ?? ''];\n if (\n typeof implementation === 'function' &&\n !Object.prototype.hasOwnProperty.call(prototype, methodName)\n ) {\n Object.defineProperty(prototype, methodName, {\n configurable: true,\n writable: true,\n value: this.#instanceMethod(association, implementation as AccessorImplementation),\n });\n }\n });\n }\n\n #upperFirst(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n }\n\n #single(singular: string): Readonly<Record<string, string>> {\n return { get: `get${singular}`, set: `set${singular}`, create: `create${singular}` };\n }\n\n #multi(singular: string, plural: string): Readonly<Record<string, string>> {\n return {\n get: `get${plural}`,\n set: `set${plural}`,\n addMultiple: `add${plural}`,\n add: `add${singular}`,\n create: `create${singular}`,\n remove: `remove${singular}`,\n removeMultiple: `remove${plural}`,\n hasSingle: `has${singular}`,\n hasAll: `has${plural}`,\n count: `count${plural}`,\n };\n }\n\n #instanceMethod(\n association: object,\n implementation: AccessorImplementation,\n ): (this: Instance, ...args: never[]) => unknown {\n return function accessor(this: Instance, ...args: never[]): unknown {\n return implementation.call(association, this, ...args);\n };\n }\n}\n","import type { AnyModel, ModelStatic } from '../model/options.ts';\nimport { AssociationAccessors } from './association-accessors.ts';\nimport type { AssociationKeyFields } from './association-key-types.ts';\nimport type {\n Association as AssociationFields,\n AssociationName,\n AssociationOptions,\n AssociationType,\n} from './types.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\n/** Everything an association is built from. */\nexport type AssociationInit = Readonly<{\n type: AssociationType;\n source: Model;\n target: Model;\n options: AssociationOptions;\n name: AssociationName;\n keys: AssociationKeyFields;\n}>;\n\n/** Computes the public fields of an association from its definition. */\nexport class AssociationShape {\n readonly #accessors = new AssociationAccessors();\n\n /**\n * Public fields of an association.\n *\n * @param init - Kind, models, options, alias forms and resolved keys.\n * @returns Field values.\n */\n fields(init: AssociationInit): AssociationFields {\n const multi = init.type === 'HasMany' || init.type === 'BelongsToMany';\n return {\n ...init.keys,\n associationType: init.type,\n source: init.source,\n target: init.target,\n as: multi ? init.name.plural : init.name.singular,\n name: init.name,\n isAliased: init.options.as !== undefined,\n scope: init.options.scope,\n isSingleAssociation: !multi,\n isMultiAssociation: multi,\n accessors: this.#accessors.namesFor(init.type, init.name),\n };\n }\n}\n","import { AssociationError } from '../errors/errors.ts';\nimport { Op } from '../expressions/op.ts';\nimport type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport { AssociationAccessors } from './association-accessors.ts';\nimport type { AssociationKeyFields } from './association-key-types.ts';\nimport { AssociationShape } from './association-shape.ts';\nimport type {\n Association as AssociationFields,\n AssociationName,\n AssociationOptions,\n AssociationThrough,\n AssociationType,\n} from './types.ts';\n\nconst registry = new ModelRegistry();\nconst shape = new AssociationShape();\nconst accessors = new AssociationAccessors();\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\n\n/** Query options accepted by the accessor methods (`getPosts(options)`, ...). */\nexport type AccessorOptions = Values &\n Readonly<{ where?: unknown; transaction?: unknown; logging?: unknown }>;\n\n/**\n * Association between two models (Sequelize v6 `Association`). Subclasses resolve the keys,\n * add the foreign key attributes and implement the accessor methods that are installed on the\n * source prototype (`getX`, `setX`, `createX`, ...).\n */\nexport abstract class Association implements AssociationFields {\n /** Kind of association. */\n declare readonly associationType: AssociationType;\n /** Model the association is defined on. */\n declare readonly source: Model;\n /** Associated model. */\n declare readonly target: Model;\n /** Alias used in `include` and as the instance property. */\n declare readonly as: string;\n /** Singular and plural alias forms. */\n declare readonly name: AssociationName;\n /** Whether `as` was given explicitly. */\n declare readonly isAliased: boolean;\n /** Association scope. */\n declare readonly scope: Readonly<Record<string, unknown>> | undefined;\n /** True for belongsTo / hasOne. */\n declare readonly isSingleAssociation: boolean;\n /** True for hasMany / belongsToMany. */\n declare readonly isMultiAssociation: boolean;\n /** Names of the instance methods added to the source model. */\n declare readonly accessors: Readonly<Record<string, string>>;\n /** Foreign key attribute (on the source for belongsTo, on the target for hasOne/hasMany, on the junction for belongsToMany). */\n declare readonly foreignKey: string;\n /** Column of the foreign key. */\n declare readonly identifierField: string;\n /** Source attribute referenced by the foreign key. */\n declare readonly sourceKey: string;\n /** Target attribute referenced by the foreign key (belongsTo) or by `otherKey` (belongsToMany). */\n declare readonly targetKey: string;\n /** Junction foreign key pointing at the target (belongsToMany). */\n declare readonly otherKey: string | undefined;\n /** Junction model (belongsToMany). */\n declare readonly through: AssociationThrough | undefined;\n\n /**\n * @param type - Kind of association.\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n * @param name - Singular and plural alias forms.\n * @param keys - Resolved keys.\n */\n protected constructor(\n type: AssociationType,\n source: Model,\n target: Model,\n options: AssociationOptions,\n name: AssociationName,\n keys: AssociationKeyFields,\n ) {\n Object.assign(this, shape.fields({ type, source, target, options, name, keys }));\n }\n\n /**\n * Registers the association on the source model, installs the accessor methods and the\n * instance properties of the alias (and of the junction model on the target).\n *\n * @throws AssociationError when the alias is already used on the source.\n */\n protected install(): void {\n registry.update(this.source, (state) => {\n if (state.associations.has(this.as)) {\n throw new AssociationError(\n `You have used the alias ${this.as} in two separate associations. Aliased associations must have unique aliases.`,\n );\n }\n return { ...state, associations: new Map([...state.associations, [this.as, this]]) };\n });\n accessors.install(this, this.source.prototype as object, this.accessors);\n registry.defineAssociationAccessor((this.source as { prototype: object }).prototype, this.as);\n if (this.through !== undefined) {\n registry.defineAssociationAccessor(\n (this.target as { prototype: object }).prototype,\n registry.state(this.through.model).definition.name,\n );\n }\n }\n\n /**\n * Values of an array-or-single argument as a list.\n *\n * @param value - One value, a list, `null` or `undefined`.\n * @returns List of values.\n */\n protected toArray<T>(value: T | readonly T[] | null | undefined): readonly T[] {\n return value === null || value === undefined ? [] : Array.isArray(value) ? value : [value as T];\n }\n\n /**\n * Attribute of an instance, or the value itself for a key given directly.\n *\n * @param item - Instance or key value.\n * @param key - Attribute name.\n * @returns Key value.\n */\n protected keyOf(item: unknown, key: string): unknown {\n return typeof item === 'object' && item !== null && 'get' in item\n ? (item as Instance).get(key)\n : item;\n }\n\n /**\n * `Op.and` of the given conditions, skipping missing ones.\n *\n * @param parts - Conditions.\n * @returns Where condition.\n */\n protected andWhere(...parts: readonly unknown[]): Values {\n return { [Op.and]: parts.filter((part) => part !== undefined && part !== null) };\n }\n\n /**\n * Query options passed on to the queries an accessor runs.\n *\n * @param options - Accessor options.\n * @returns `transaction`, `logging` and `benchmark`.\n */\n protected passThrough(options: AccessorOptions): Values {\n return Object.fromEntries(\n Object.entries(options).filter(([key]) =>\n ['transaction', 'logging', 'benchmark'].includes(key),\n ),\n );\n }\n}\n","import inflection from 'inflection';\nimport type { AttributeDefinition, ModelAttributes } from '../model/model-definition.ts';\nimport type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport type { ReferenceDefaults, ReferenceSpec } from './association-key-types.ts';\nimport type { AssociationName, AssociationOptions, ForeignKeyOptions } from './types.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\n\nexport type {\n AssociationKeyFields,\n ReferenceDefaults,\n ReferenceSpec,\n TargetKeys,\n} from './association-key-types.ts';\n\n/** Naming and foreign key attribute rules shared by the association classes (Sequelize v6 defaults). */\nexport class AssociationKeys {\n /**\n * Converts `snake_case` / `kebab-case` / spaced names to camelCase.\n *\n * @param value - Name to convert.\n * @returns camelCase name.\n */\n camelize(value: string): string {\n return value\n .trim()\n .replace(/[-_\\s]+(.)?/g, (_match, char?: string) => (char ?? '').toUpperCase());\n }\n\n /**\n * Singular and plural forms of a model name.\n *\n * @param model - Model class.\n * @returns Name forms.\n */\n modelName(model: Model): AssociationName {\n const name = registry.state(model).definition.name;\n return { singular: inflection.singularize(name), plural: inflection.pluralize(name) };\n }\n\n /**\n * First primary key attribute of a model.\n *\n * @param model - Model class.\n * @returns Attribute name (`id` when the model has none).\n */\n primaryKey(model: Model): string {\n return registry.state(model).definition.primaryKeys[0] ?? 'id';\n }\n\n /**\n * Attribute definition by name.\n *\n * @param model - Model class.\n * @param name - Attribute name.\n * @returns Definition, if the attribute exists.\n */\n attributeOf(model: Model, name: string): AttributeDefinition | undefined {\n return registry.state(model).definition.attributes.get(name);\n }\n\n /**\n * Column of an attribute.\n *\n * @param model - Model class.\n * @param name - Attribute name.\n * @returns Column name (the attribute name when not defined).\n */\n fieldOf(model: Model, name: string): string {\n return this.attributeOf(model, name)?.field ?? name;\n }\n\n /**\n * Attribute name of a `foreignKey` / `otherKey` option.\n *\n * @param option - Option value.\n * @returns Attribute name, if given.\n */\n foreignKeyName(option: string | ForeignKeyOptions | undefined): string | undefined {\n return option === undefined ? undefined : typeof option === 'string' ? option : option.name;\n }\n\n /**\n * Object form of a `foreignKey` / `otherKey` option.\n *\n * @param option - Option value.\n * @returns Foreign key options (empty for a string).\n */\n foreignKeyExtras(option: string | ForeignKeyOptions | undefined): ForeignKeyOptions {\n return option === undefined || typeof option === 'string' ? {} : option;\n }\n\n /**\n * Singular and plural alias forms.\n *\n * @param as - `as` option.\n * @param fallback - Forms used without `as`.\n * @param multi - Whether a string alias is the plural form.\n * @returns Alias forms.\n */\n aliasNames(\n as: string | AssociationName | undefined,\n fallback: AssociationName,\n multi: boolean,\n ): AssociationName {\n return as === undefined\n ? fallback\n : typeof as === 'string'\n ? multi\n ? { singular: inflection.singularize(as), plural: as }\n : { singular: as, plural: inflection.pluralize(as) }\n : as;\n }\n\n /**\n * `references` / `onDelete` / `onUpdate` attribute options of a foreign key.\n *\n * @param spec - Referenced model and key, with the actions from the options.\n * @param allowNull - Whether the key may be `NULL` (for the `auto` delete action).\n * @param defaults - Actions used when the options give none.\n * @returns Attribute options (empty with `constraints: false`).\n */\n reference(spec: ReferenceSpec, allowNull: boolean, defaults: ReferenceDefaults): Values {\n if (spec.constraints === false) {\n return {};\n }\n const definition = registry.state(spec.model).definition;\n return {\n references: {\n model: {\n tableName: definition.tableName,\n ...(definition.schema === undefined ? {} : { schema: definition.schema }),\n },\n key: definition.attributes.get(spec.key)?.field ?? spec.key,\n },\n onDelete:\n spec.onDelete ??\n (defaults.onDelete === 'auto' ? (allowNull ? 'SET NULL' : 'NO ACTION') : defaults.onDelete),\n onUpdate: spec.onUpdate ?? defaults.onUpdate,\n };\n }\n\n /**\n * Attribute options of a foreign key.\n *\n * @param type - Referenced attribute (its data type is reused).\n * @param extras - Object form of the foreign key option.\n * @param base - Further attribute options.\n * @returns Attribute options.\n */\n keyAttribute(\n type: AttributeDefinition | undefined,\n extras: ForeignKeyOptions,\n base: Values = {},\n ): Values {\n return {\n type: type?.type,\n allowNull: true,\n ...base,\n ...(extras.field === undefined ? {} : { field: extras.field }),\n ...(extras.allowNull === undefined ? {} : { allowNull: extras.allowNull }),\n };\n }\n\n /**\n * Adds the foreign key attribute (with its reference) to the model that holds the key.\n *\n * @param owner - Model that holds the foreign key.\n * @param referenced - Model the key references.\n * @param referencedKey - Referenced attribute.\n * @param foreignKey - Foreign key attribute name.\n * @param options - Association options.\n */\n addForeignKey(\n owner: Model,\n referenced: Model,\n referencedKey: string,\n foreignKey: string,\n options: AssociationOptions,\n ): void {\n const extras = this.foreignKeyExtras(options.foreignKey);\n const spec = { model: referenced, key: referencedKey, ...this.#actions(options) };\n registry.addAssociationAttributes(owner, {\n [foreignKey]: this.keyAttribute(\n this.attributeOf(referenced, referencedKey),\n extras,\n this.reference(spec, extras.allowNull !== false, { onDelete: 'auto', onUpdate: 'CASCADE' }),\n ),\n } as ModelAttributes);\n }\n\n #actions(options: AssociationOptions): Omit<ReferenceSpec, 'model' | 'key'> {\n return {\n onDelete: options.onDelete,\n onUpdate: options.onUpdate,\n constraints: options.constraints,\n };\n }\n}\n","import inflection from 'inflection';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { AssociationKeys, AssociationKeyFields, TargetKeys } from './association-keys.ts';\nimport type { AssociationOptions } from './types.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\n/** Resolves alias and keys of belongsTo / hasOne / hasMany and adds the foreign key attribute. */\nexport class OwnerKeys {\n readonly #keys: AssociationKeys;\n\n /**\n * @param keys - Naming and foreign key attribute rules.\n */\n constructor(keys: AssociationKeys) {\n this.#keys = keys;\n }\n\n /**\n * Resolves the alias and keys of a belongsTo association and adds the foreign key attribute\n * to the source.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n * @returns Alias forms and keys.\n */\n belongsTo(source: Model, target: Model, options: AssociationOptions): TargetKeys {\n const keys = this.#keys;\n const name = keys.aliasNames(options.as, keys.modelName(target), false);\n const targetKey = options.targetKey ?? keys.primaryKey(target);\n const foreignKey =\n keys.foreignKeyName(options.foreignKey) ??\n keys.camelize(`${name.singular}_${keys.primaryKey(target)}`);\n keys.addForeignKey(source, target, targetKey, foreignKey, options);\n return { name, keys: this.#fields(source, foreignKey, foreignKey, targetKey) };\n }\n\n /**\n * Resolves the alias and keys of a hasOne / hasMany association and adds the foreign key\n * attribute to the target.\n *\n * @param multi - True for hasMany.\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n * @returns Alias forms and keys.\n */\n hasOneOrMany(\n multi: boolean,\n source: Model,\n target: Model,\n options: AssociationOptions,\n ): TargetKeys {\n const keys = this.#keys;\n const sourceKey = options.sourceKey ?? keys.primaryKey(source);\n const foreignKey =\n keys.foreignKeyName(options.foreignKey) ??\n keys.camelize(`${this.#sourcePrefix(multi, source, options)}_${keys.primaryKey(source)}`);\n keys.addForeignKey(target, source, sourceKey, foreignKey, options);\n return {\n name: keys.aliasNames(options.as, keys.modelName(target), multi),\n keys: this.#fields(target, foreignKey, sourceKey, foreignKey),\n };\n }\n\n #fields(\n owner: Model,\n foreignKey: string,\n sourceKey: string,\n targetKey: string,\n ): AssociationKeyFields {\n const identifierField = this.#keys.fieldOf(owner, foreignKey);\n return {\n foreignKey,\n identifierField,\n sourceKey,\n targetKey,\n otherKey: undefined,\n through: undefined,\n };\n }\n\n #sourcePrefix(multi: boolean, source: Model, options: AssociationOptions): string {\n const own = this.#keys.modelName(source).singular;\n return multi ? own : inflection.singularize(typeof options.as === 'string' ? options.as : own);\n }\n}\n","import type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { Association, type AccessorOptions } from './association.ts';\nimport { AssociationKeys } from './association-keys.ts';\nimport { OwnerKeys } from './owner-keys.ts';\nimport type { AssociationOptions } from './types.ts';\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\n\nconst ownerKeys = new OwnerKeys(new AssociationKeys());\n\n/** `source.belongsTo(target)` (Sequelize v6 `BelongsTo`): the foreign key lives on the source. */\nexport class BelongsTo extends Association {\n /**\n * Adds the foreign key attribute to the source and registers the association.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n */\n constructor(source: Model, target: Model, options: AssociationOptions = {}) {\n const resolved = ownerKeys.belongsTo(source, target, options);\n super('BelongsTo', source, target, options, resolved.name, resolved.keys);\n this.install();\n }\n\n /**\n * Loads the associated instance (`getX`).\n *\n * @param instance - Source instance.\n * @param options - Find options.\n * @returns Associated instance, or `null`.\n */\n get(instance: Instance, options: AccessorOptions = {}): Promise<Instance | null> {\n const value = instance.get(this.foreignKey);\n return value === null || value === undefined\n ? Promise.resolve(null)\n : this.target.findOne({\n ...options,\n where: this.andWhere(options.where, this.scope, { [this.targetKey]: value }),\n } as never);\n }\n\n /**\n * Points the foreign key at `associated` and saves the source (`setX`).\n *\n * @param instance - Source instance.\n * @param associated - Instance, key value or `null`.\n * @param options - Query options; `save: false` skips saving.\n * @returns The saved source instance, or `undefined` with `save: false` (like v6).\n */\n async set(\n instance: Instance,\n associated: unknown,\n options: AccessorOptions & Readonly<{ save?: boolean }> = {},\n ): Promise<Instance | undefined> {\n instance.set(\n this.foreignKey,\n associated === null ? null : this.keyOf(associated, this.targetKey),\n );\n if (options.save === false) {\n return undefined;\n }\n return (await instance.save({\n ...this.passThrough(options),\n fields: [this.foreignKey],\n } as never)) as Instance;\n }\n\n /**\n * Creates the associated instance and points the foreign key at it (`createX`).\n *\n * @param instance - Source instance.\n * @param values - Values of the new instance.\n * @param options - Query options.\n * @returns The created instance.\n */\n async create(\n instance: Instance,\n values: Values = {},\n options: AccessorOptions = {},\n ): Promise<Instance> {\n const created = await this.target.create(\n { ...values, ...this.scope } as never,\n this.passThrough(options) as never,\n );\n instance.set(this.foreignKey, created.get(this.targetKey));\n await instance.save({ ...this.passThrough(options), fields: [this.foreignKey] } as never);\n return created;\n }\n}\n","import inflection from 'inflection';\nimport type { ModelAttributes } from '../model/model-definition.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport type { AssociationKeys, TargetKeys } from './association-keys.ts';\nimport type {\n AssociationName,\n BelongsToManyOptions,\n ForeignKeyOptions,\n ThroughOptions,\n} from './types.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\n\n/** Alias, keys and foreign key attribute names of a belongsToMany association. */\ntype JunctionNames = Readonly<{\n name: AssociationName;\n sourceKey: string;\n targetKey: string;\n foreignKey: string;\n otherKey: string;\n}>;\n\n/** Resolves alias and keys of belongsToMany and defines the junction model's key attributes. */\nexport class JunctionKeys {\n readonly #keys: AssociationKeys;\n\n /**\n * @param keys - Naming and foreign key attribute rules.\n */\n constructor(keys: AssociationKeys) {\n this.#keys = keys;\n }\n\n /**\n * Resolves the alias and keys of a belongsToMany association, creating the junction model\n * when given by name and adding both foreign key attributes to it.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options with `through`.\n * @returns Alias forms and keys (including the junction).\n */\n resolve(source: Model, target: Model, options: BelongsToManyOptions): TargetKeys {\n const names = this.#names(source, target, options);\n const through = this.#through(options);\n const model = this.#throughModel(source, through.model, {\n [names.foreignKey]: this.#attribute(source, names.sourceKey, options.foreignKey, options),\n [names.otherKey]: this.#attribute(target, names.targetKey, options.otherKey, options),\n } as ModelAttributes);\n return {\n name: names.name,\n keys: {\n foreignKey: names.foreignKey,\n identifierField: this.#keys.fieldOf(model, names.foreignKey),\n sourceKey: names.sourceKey,\n targetKey: names.targetKey,\n otherKey: names.otherKey,\n through: { model, ...(through.scope === undefined ? {} : { scope: through.scope }) },\n },\n };\n }\n\n #names(source: Model, target: Model, options: BelongsToManyOptions): JunctionNames {\n const keys = this.#keys;\n const name = keys.aliasNames(options.as, keys.modelName(target), true);\n const sourceKey = options.sourceKey ?? keys.primaryKey(source);\n const targetKey = options.targetKey ?? keys.primaryKey(target);\n const targetPrefix =\n source === target ? inflection.singularize(name.plural) : keys.modelName(target).singular;\n const foreignKey =\n keys.foreignKeyName(options.foreignKey) ??\n keys.camelize(`${keys.modelName(source).singular}_${sourceKey}`);\n const otherKey =\n keys.foreignKeyName(options.otherKey) ?? keys.camelize(`${targetPrefix}_${targetKey}`);\n return { name, sourceKey, targetKey, foreignKey, otherKey };\n }\n\n #through(options: BelongsToManyOptions): ThroughOptions {\n const { through } = options;\n return typeof through === 'object' && through !== null && 'model' in through\n ? through\n : { model: through };\n }\n\n #attribute(\n model: Model,\n key: string,\n option: string | ForeignKeyOptions | undefined,\n options: BelongsToManyOptions,\n ): Values {\n const keys = this.#keys;\n const spec = {\n model,\n key,\n onDelete: options.onDelete,\n onUpdate: options.onUpdate,\n constraints: options.constraints,\n };\n return keys.keyAttribute(keys.attributeOf(model, key), keys.foreignKeyExtras(option), {\n primaryKey: true,\n allowNull: false,\n ...keys.reference(spec, false, { onDelete: 'CASCADE', onUpdate: 'CASCADE' }),\n });\n }\n\n #throughModel(source: Model, through: string | Model, attributes: ModelAttributes): Model {\n const { runtime } = registry.state(source);\n const model =\n typeof through === 'string'\n ? ((runtime.models()[through] as Model | undefined) ??\n (runtime.defineModel(through, {}, { tableName: through }) as Model))\n : through;\n registry.addAssociationAttributes(model, attributes);\n return model;\n }\n}\n","import type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport { Association, type AccessorOptions } from './association.ts';\nimport { AssociationKeys } from './association-keys.ts';\nimport { JunctionKeys } from './junction-keys.ts';\nimport type { AssociationThrough, BelongsToManyOptions } from './types.ts';\n\nconst registry = new ModelRegistry();\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\ntype JoinOptions = Readonly<{ joinTableAttributes?: readonly string[] }>;\ntype LinkOptions = AccessorOptions & Readonly<{ through?: Values }>;\n\nconst junctionKeys = new JunctionKeys(new AssociationKeys());\n\n/**\n * `source.belongsToMany(target, { through })` (Sequelize v6 `BelongsToMany`): both foreign keys\n * live on a junction model, which is created when given by name.\n */\nexport class BelongsToMany extends Association {\n readonly #junction: Model;\n readonly #junctionName: string;\n readonly #otherKey: string;\n\n /**\n * Adds the foreign key attributes to the junction model and registers the association.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options with `through`.\n */\n constructor(source: Model, target: Model, options: BelongsToManyOptions) {\n const resolved = junctionKeys.resolve(source, target, options);\n const model = (resolved.keys.through as AssociationThrough).model;\n super('BelongsToMany', source, target, options, resolved.name, resolved.keys);\n this.#junction = model;\n this.#junctionName = registry.state(model).definition.name;\n this.#otherKey = resolved.keys.otherKey as string;\n this.install();\n }\n\n /**\n * Loads the associated instances, each with its junction row under the junction model name\n * (`getXs`).\n *\n * @param instance - Source instance.\n * @param options - Find options.\n * @returns Associated instances.\n */\n async get(instance: Instance, options: AccessorOptions = {}): Promise<Instance[]> {\n const joined = await this.#links(instance, options);\n const byKey = new Map(joined.map((link) => [link.get(this.#otherKey), link]));\n const rows = (await this.target.findAll({\n ...options,\n where: this.andWhere(options.where, this.scope, { [this.targetKey]: [...byKey.keys()] }),\n } as never)) as Instance[];\n const attributes = (options as JoinOptions).joinTableAttributes;\n rows.forEach((row) => {\n const link = byKey.get(this.#rowKey(row, options));\n this.#attach(row, link as Instance, attributes, options.raw === true);\n });\n return rows;\n }\n\n #rowKey(row: Instance, options: AccessorOptions): unknown {\n return options.raw === true\n ? (row as unknown as Values)[this.targetKey]\n : row.get(this.targetKey);\n }\n\n #attach(\n row: Instance,\n link: Instance,\n attributes: readonly string[] | undefined,\n raw: boolean,\n ): void {\n const names = attributes ?? Object.keys(link.dataValues as Values);\n if (raw) {\n names.forEach((name) => {\n (row as unknown as Values)[`${this.#junctionName}.${name}`] = link.get(name);\n });\n } else if (attributes === undefined || names.length > 0) {\n (row.dataValues as Values)[this.#junctionName] = link;\n }\n }\n\n /**\n * Counts the associated instances (`countXs`).\n *\n * @param instance - Source instance.\n * @param options - Count options.\n * @returns Number of associated rows.\n */\n async count(instance: Instance, options: AccessorOptions = {}): Promise<number> {\n const linked = (await this.#links(instance, options)).map((link) => link.get(this.#otherKey));\n return this.target.count({\n ...options,\n where: this.andWhere(options.where, this.scope, { [this.targetKey]: linked }),\n } as never) as Promise<number>;\n }\n\n /**\n * Checks whether all given instances are associated (`hasX` / `hasXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or target key value(s).\n * @param options - Query options.\n * @returns True when every item is associated.\n */\n async has(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<boolean> {\n return (\n (await this.#links(instance, options, this.#ids(items))).length === this.#ids(items).length\n );\n }\n\n /**\n * Creates the missing junction rows (`addX` / `addXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or target key value(s).\n * @param options - Query options; `through` gives junction values.\n * @returns The source instance.\n */\n async add(instance: Instance, items: unknown, options: LinkOptions = {}): Promise<Instance> {\n await this.#addLinks(instance, items, options);\n return instance;\n }\n\n /**\n * Deletes the junction rows (`removeX` / `removeXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or target key value(s).\n * @param options - Query options.\n * @returns The source instance.\n */\n async remove(\n instance: Instance,\n items: unknown,\n options: AccessorOptions = {},\n ): Promise<Instance> {\n await this.#removeLinks(instance, items, options);\n return instance;\n }\n\n /**\n * Replaces the associated instances: deletes stale junction rows, adds missing ones (`setXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or target key value(s).\n * @param options - Query options; `through` gives junction values.\n * @returns The source instance.\n */\n async set(instance: Instance, items: unknown, options: LinkOptions = {}): Promise<Instance> {\n const wanted = new Set(this.#ids(items));\n const stale = (await this.#links(instance, options))\n .map((link) => link.get(this.#otherKey))\n .filter((id) => !wanted.has(id));\n await this.#removeLinks(instance, stale, options);\n await this.#addLinks(instance, items, options);\n return instance;\n }\n\n /**\n * Creates an associated instance and its junction row (`createX`).\n *\n * @param instance - Source instance.\n * @param values - Values of the new instance.\n * @param options - Query options; `through` gives junction values.\n * @returns The created instance.\n */\n async create(\n instance: Instance,\n values: Values = {},\n options: LinkOptions = {},\n ): Promise<Instance> {\n const created = (await this.target.create(\n { ...values, ...this.scope } as never,\n this.passThrough(options) as never,\n )) as Instance;\n await this.#addLinks(instance, created, options);\n return created;\n }\n\n #own(instance: Instance): Values {\n return { [this.foreignKey]: instance.get(this.sourceKey), ...this.through?.scope };\n }\n\n #ids(items: unknown): readonly unknown[] {\n return this.toArray(items).map((item) => this.keyOf(item, this.targetKey));\n }\n\n #links(\n instance: Instance,\n options: AccessorOptions,\n wanted?: readonly unknown[],\n ): Promise<Instance[]> {\n return this.#junction.findAll({\n ...this.passThrough(options),\n where: this.andWhere(\n this.#own(instance),\n wanted === undefined ? undefined : { [this.#otherKey]: wanted },\n ),\n } as never) as Promise<Instance[]>;\n }\n\n async #addLinks(instance: Instance, items: unknown, options: LinkOptions): Promise<void> {\n const wanted = this.#ids(items);\n const existing = new Set(\n (await this.#links(instance, options, wanted)).map((link) => link.get(this.#otherKey)),\n );\n const missing = wanted.filter((id) => !existing.has(id));\n if (missing.length > 0) {\n await this.#junction.bulkCreate(\n missing.map((id) => ({\n ...options.through,\n ...this.#own(instance),\n [this.#otherKey]: id,\n })) as never,\n this.passThrough(options) as never,\n );\n }\n }\n\n async #removeLinks(instance: Instance, items: unknown, options: AccessorOptions): Promise<void> {\n const wanted = this.#ids(items);\n if (wanted.length > 0) {\n await this.#junction.destroy({\n ...this.passThrough(options),\n where: this.andWhere(this.#own(instance), { [this.#otherKey]: wanted }),\n } as never);\n }\n }\n}\n","import { Op } from '../expressions/op.ts';\nimport type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { Association, type AccessorOptions } from './association.ts';\nimport { AssociationKeys } from './association-keys.ts';\nimport { OwnerKeys } from './owner-keys.ts';\nimport type { AssociationOptions } from './types.ts';\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\n\nconst keys = new AssociationKeys();\nconst ownerKeys = new OwnerKeys(keys);\n\n/** `source.hasMany(target)` (Sequelize v6 `HasMany`): the foreign key lives on the target. */\nexport class HasMany extends Association {\n readonly #targetPk: string;\n\n /**\n * Adds the foreign key attribute to the target and registers the association.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n */\n constructor(source: Model, target: Model, options: AssociationOptions = {}) {\n const resolved = ownerKeys.hasOneOrMany(true, source, target, options);\n super('HasMany', source, target, options, resolved.name, resolved.keys);\n this.#targetPk = keys.primaryKey(target);\n this.install();\n }\n\n /**\n * Loads the associated instances (`getXs`).\n *\n * @param instance - Source instance.\n * @param options - Find options.\n * @returns Associated instances.\n */\n get(instance: Instance, options: AccessorOptions = {}): Promise<Instance[]> {\n return this.target.findAll({\n ...options,\n where: this.andWhere(options.where, this.scope, this.#own(instance)),\n } as never);\n }\n\n /**\n * Counts the associated instances (`countXs`).\n *\n * @param instance - Source instance.\n * @param options - Count options.\n * @returns Number of associated rows.\n */\n count(instance: Instance, options: AccessorOptions = {}): Promise<number> {\n return this.target.count({\n ...options,\n where: this.andWhere(options.where, this.scope, this.#own(instance)),\n } as never) as Promise<number>;\n }\n\n /**\n * Checks whether all given instances are associated (`hasX` / `hasXs`).\n *\n * @param instance - Source instance.\n * @param item - Instance(s) or primary key value(s).\n * @param options - Query options.\n * @returns True when every item is associated.\n */\n async has(instance: Instance, item: unknown, options: AccessorOptions = {}): Promise<boolean> {\n const wanted = this.#ids(item);\n return (\n (await this.target.count({\n ...this.passThrough(options),\n where: this.andWhere(this.scope, this.#own(instance), { [this.#targetPk]: wanted }),\n } as never)) === wanted.length\n );\n }\n\n /**\n * Links the given instances to the source (`addX` / `addXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or primary key value(s).\n * @param options - Query options.\n * @returns The source instance.\n */\n async add(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<Instance> {\n const wanted = this.#ids(items);\n if (wanted.length > 0) {\n await this.target.update(\n { ...this.#own(instance), ...this.scope } as never,\n { ...this.passThrough(options), where: { [this.#targetPk]: wanted } } as never,\n );\n }\n return instance;\n }\n\n /**\n * Unlinks the given instances (`removeX` / `removeXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or primary key value(s).\n * @param options - Query options.\n * @returns The source instance.\n */\n async remove(\n instance: Instance,\n items: unknown,\n options: AccessorOptions = {},\n ): Promise<Instance> {\n const wanted = this.#ids(items);\n if (wanted.length > 0) {\n await this.target.update(\n { [this.foreignKey]: null } as never,\n {\n ...this.passThrough(options),\n where: this.andWhere(this.#own(instance), { [this.#targetPk]: wanted }),\n } as never,\n );\n }\n return instance;\n }\n\n /**\n * Replaces the associated instances (`setXs`).\n *\n * @param instance - Source instance.\n * @param items - Instance(s) or primary key value(s).\n * @param options - Query options.\n * @returns The source instance.\n */\n async set(instance: Instance, items: unknown, options: AccessorOptions = {}): Promise<Instance> {\n const wanted = this.#ids(items);\n await this.target.update(\n { [this.foreignKey]: null } as never,\n {\n ...this.passThrough(options),\n where: this.andWhere(\n this.#own(instance),\n wanted.length === 0 ? undefined : { [this.#targetPk]: { [Op.notIn]: wanted } },\n ),\n } as never,\n );\n if (wanted.length > 0) {\n await this.target.update(\n { ...this.#own(instance), ...this.scope } as never,\n { ...this.passThrough(options), where: { [this.#targetPk]: wanted } } as never,\n );\n }\n return instance;\n }\n\n /**\n * Creates an associated instance linked to the source (`createX`).\n *\n * @param instance - Source instance.\n * @param values - Values of the new instance.\n * @param options - Query options.\n * @returns The created instance.\n */\n create(\n instance: Instance,\n values: Values = {},\n options: AccessorOptions = {},\n ): Promise<Instance> {\n return this.target.create(\n { ...values, ...this.scope, ...this.#own(instance) } as never,\n this.passThrough(options) as never,\n );\n }\n\n #own(instance: Instance): Values {\n return { [this.foreignKey]: instance.get(this.sourceKey) };\n }\n\n #ids(items: unknown): readonly unknown[] {\n return this.toArray(items).map((item) => this.keyOf(item, this.#targetPk));\n }\n}\n","import type { AnyModel, ModelStatic, Values } from '../model/options.ts';\nimport { Association, type AccessorOptions } from './association.ts';\nimport { AssociationKeys } from './association-keys.ts';\nimport { OwnerKeys } from './owner-keys.ts';\nimport type { AssociationOptions } from './types.ts';\n\ntype Model = ModelStatic<AnyModel>;\ntype Instance = AnyModel;\n\nconst keys = new AssociationKeys();\nconst ownerKeys = new OwnerKeys(keys);\n\n/** `source.hasOne(target)` (Sequelize v6 `HasOne`): the foreign key lives on the target. */\nexport class HasOne extends Association {\n /**\n * Adds the foreign key attribute to the target and registers the association.\n *\n * @param source - Model the association is defined on.\n * @param target - Associated model.\n * @param options - Association options.\n */\n constructor(source: Model, target: Model, options: AssociationOptions = {}) {\n const resolved = ownerKeys.hasOneOrMany(false, source, target, options);\n super('HasOne', source, target, options, resolved.name, resolved.keys);\n this.install();\n }\n\n /**\n * Loads the associated instance (`getX`).\n *\n * @param instance - Source instance.\n * @param options - Find options.\n * @returns Associated instance, or `null`.\n */\n get(instance: Instance, options: AccessorOptions = {}): Promise<Instance | null> {\n return this.target.findOne({\n ...options,\n where: this.andWhere(options.where, this.scope, {\n [this.foreignKey]: instance.get(this.sourceKey),\n }),\n } as never);\n }\n\n /**\n * Makes `associated` the associated instance, unlinking the current one (`setX`).\n *\n * @param instance - Source instance.\n * @param associated - Instance, primary key value or `null`.\n * @param options - Query options.\n * @returns The new associated instance, or `null`.\n */\n async set(\n instance: Instance,\n associated: unknown,\n options: AccessorOptions = {},\n ): Promise<Instance | null> {\n const value = instance.get(this.sourceKey);\n const current = await this.#current(value, options);\n if (this.#isLinked(current, associated)) {\n return null;\n }\n await this.#unlink(current, options);\n if (associated === null || associated === undefined) {\n return null;\n }\n const next = this.#toInstance(associated);\n next.set({ [this.foreignKey]: value, ...this.scope });\n return (await next.save(this.passThrough(options) as never)) as Instance;\n }\n\n /**\n * Creates the associated instance linked to the source (`createX`).\n *\n * @param instance - Source instance.\n * @param values - Values of the new instance.\n * @param options - Query options.\n * @returns The created instance.\n */\n create(\n instance: Instance,\n values: Values = {},\n options: AccessorOptions = {},\n ): Promise<Instance> {\n return this.target.create(\n { ...values, ...this.scope, [this.foreignKey]: instance.get(this.sourceKey) } as never,\n this.passThrough(options) as never,\n );\n }\n\n async #current(value: unknown, options: AccessorOptions): Promise<Instance | null> {\n return (await this.target.findOne({\n ...this.passThrough(options),\n where: { [this.foreignKey]: value },\n } as never)) as Instance | null;\n }\n\n #isLinked(current: Instance | null, associated: unknown): boolean {\n if (current === null || associated === null || associated === undefined) {\n return false;\n }\n const pk = keys.primaryKey(this.target);\n const other = this.#isInstance(associated) ? associated.get(pk) : associated;\n return current.get(pk) === other;\n }\n\n #isInstance(value: unknown): value is Instance {\n return typeof value === 'object' && value !== null && 'get' in value;\n }\n\n #toInstance(associated: unknown): Instance {\n return this.#isInstance(associated)\n ? associated\n : (this.target.build({ [keys.primaryKey(this.target)]: associated } as never, {\n isNewRecord: false,\n }) as Instance);\n }\n\n async #unlink(current: Instance | null, options: AccessorOptions): Promise<void> {\n if (current !== null) {\n current.set(this.foreignKey, null);\n await current.save({ ...this.passThrough(options), fields: [this.foreignKey] } as never);\n }\n }\n}\n","import { BelongsTo } from '../../associations/belongs-to.ts';\nimport { BelongsToMany } from '../../associations/belongs-to-many.ts';\nimport { HasMany } from '../../associations/has-many.ts';\nimport { HasOne } from '../../associations/has-one.ts';\nimport type {\n Association,\n AssociationOptions,\n BelongsToManyOptions,\n} from '../../associations/types.ts';\nimport { registry } from '../model-services.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Association statics of `Model`: `associations`, `belongsTo`, `hasOne`, `hasMany`, `belongsToMany`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelAssociations = <TBase extends ModelConstructor>(Base: TBase) => {\n return class AssociationsCapability extends Base {\n /** Associations of the model by alias (Sequelize v6 `Model.associations`). */\n static get associations(): Readonly<Record<string, Association>> {\n return Object.fromEntries(\n registry.state(this).associations as ReadonlyMap<string, Association>,\n );\n }\n\n /**\n * Declares that each row of this model refers to one row of the target; the foreign key column\n * lives on this model's table. Adds accessors such as `getX` / `setX` / `createX` to instances.\n *\n * @param this - The source model class.\n * @param target - Associated model.\n * @param options - Association options.\n * @returns The association.\n * @example\n * ```ts\n * Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' });\n * ```\n * @see [Associations guide](/guide/associations)\n */\n static belongsTo<M extends AnyModel, T extends AnyModel>(\n this: ModelStatic<M>,\n target: ModelStatic<T>,\n options?: AssociationOptions,\n ): Association {\n return new BelongsTo(this, target, options);\n }\n\n /**\n * Declares that each row of this model has at most one related target row; the foreign key column\n * lives on the target's table.\n *\n * @param this - The source model class.\n * @param target - Associated model.\n * @param options - Association options.\n * @returns The association.\n * @example\n * ```ts\n * User.hasOne(Profile, { foreignKey: 'userId' });\n * ```\n */\n static hasOne<M extends AnyModel, T extends AnyModel>(\n this: ModelStatic<M>,\n target: ModelStatic<T>,\n options?: AssociationOptions,\n ): Association {\n return new HasOne(this, target, options);\n }\n\n /**\n * Declares that each row of this model has many related target rows; the foreign key column\n * lives on the target's table.\n *\n * @param this - The source model class.\n * @param target - Associated model.\n * @param options - Association options.\n * @returns The association.\n * @example\n * ```ts\n * User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' });\n * ```\n */\n static hasMany<M extends AnyModel, T extends AnyModel>(\n this: ModelStatic<M>,\n target: ModelStatic<T>,\n options?: AssociationOptions,\n ): Association {\n return new HasMany(this, target, options);\n }\n\n /**\n * Declares a many-to-many relation between this model and the target through a junction table.\n *\n * @param this - The source model class.\n * @param target - Associated model.\n * @param options - Association options with `through`.\n * @returns The association.\n * @example\n * ```ts\n * Project.belongsToMany(Task, { through: 'ProjectTasks' });\n * ```\n */\n static belongsToMany<M extends AnyModel, T extends AnyModel>(\n this: ModelStatic<M>,\n target: ModelStatic<T>,\n options: BelongsToManyOptions,\n ): Association {\n return new BelongsToMany(this, target, options);\n }\n };\n};\n","import { counter, finder } from '../model-operations.ts';\nimport type {\n AnyModel,\n Attributes,\n CountOptions,\n FindAndCountResult,\n FindOptions,\n FindOrCreateOptions,\n ModelStatic,\n} from '../options.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Read statics of `Model`: `findAll`, `findOne`, `findByPk`, `count`, `findAndCountAll`, `findOrCreate`, `findOrBuild`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelFinders = <TBase extends ModelConstructor>(Base: TBase) => {\n return class FindersCapability extends Base {\n /**\n * Selects all rows matching the options, applying the default scope and, for paranoid models,\n * hiding soft-deleted rows. Runs `beforeFind` and `afterFind` hooks unless `hooks: false`.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - Query options (`where`, `attributes`, `order`, `limit`, `include`, ...).\n * @returns Instances, or plain objects with `raw: true`.\n * @example\n * ```ts\n * const posts = await Post.findAll({\n * where: { published: true },\n * order: [['createdAt', 'DESC']],\n * limit: 20,\n * include: [User],\n * });\n * ```\n * @see {@link Model.findEach} to stream large result sets.\n */\n static findAll<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> = {},\n ): Promise<M[]> {\n return finder.findAll(this, options as FindOptions);\n }\n\n /**\n * Selects the first row matching the options and rejects when none is found.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - Query options with `rejectOnEmpty`.\n * @returns Instance.\n * @throws EmptyResultError (or the given error) when nothing is found.\n * @example\n * ```ts\n * const user = await User.findOne({ where: { email: 'ada@example.com' }, rejectOnEmpty: true });\n * ```\n */\n static findOne<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> & Readonly<{ rejectOnEmpty: true | Error }>,\n ): Promise<M>;\n\n /**\n * Selects the first row matching the options (`LIMIT 1` unless `limit` is given).\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - Query options.\n * @returns Instance or `null`.\n */\n static findOne<M extends AnyModel>(\n this: ModelStatic<M>,\n options?: FindOptions<Attributes<M>>,\n ): Promise<M | null>;\n static findOne<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> = {},\n ): Promise<M | null> {\n return finder.findOne(this, options as FindOptions);\n }\n\n /**\n * Selects the row with the given primary key.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param key - Primary key value.\n * @param options - Query options other than `where`.\n * @returns Instance or `null`.\n * @example\n * ```ts\n * const user = await User.findByPk(42, { include: [Profile] });\n * ```\n */\n static findByPk<M extends AnyModel>(\n this: ModelStatic<M>,\n key: unknown,\n options: Omit<FindOptions<Attributes<M>>, 'where'> = {},\n ): Promise<M | null> {\n return finder.findByPk(this, key, options as Omit<FindOptions, 'where'>);\n }\n\n /**\n * Counts rows, applying the default scope and the paranoid filter. Runs `beforeCount` hooks\n * unless `hooks: false`.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - Count options (`where`, `col`, `distinct`, `group`, `include`).\n * @returns The count. With `group` the runtime value is an array of `{ count, ...groupColumns }` objects, as in Sequelize v6.\n * @example\n * ```ts\n * const active = await User.count({ where: { active: true } });\n * ```\n */\n static count<M extends AnyModel>(\n this: ModelStatic<M>,\n options: CountOptions<Attributes<M>> = {},\n ): Promise<number> {\n return counter.count(this, options as CountOptions);\n }\n\n /**\n * Runs {@link Model.findAll} and {@link Model.count} with the same filter, so `limit` / `offset`\n * paginate the rows while `count` is the total.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - Query options.\n * @returns Total count and the current page of rows.\n * @example\n * ```ts\n * const { count, rows } = await Post.findAndCountAll({ where: { published: true }, limit: 10, offset: 20 });\n * ```\n */\n static findAndCountAll<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> = {},\n ): Promise<FindAndCountResult<M>> {\n return finder.findAndCountAll(this, options as FindOptions);\n }\n\n /**\n * Finds a row, or creates it when none matches. Creation runs inside a transaction (a nested\n * one when `options.transaction` is given); when creation fails but the row exists after all\n * (a concurrent insert won), that row is returned, otherwise the error is rethrown.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - `where` to search (its equality values also seed the new row), `defaults` to add on creation.\n * @returns `[instance, created]`.\n * @example\n * ```ts\n * const [tag, created] = await Tag.findOrCreate({ where: { name: 'news' }, defaults: { color: 'red' } });\n * ```\n */\n static findOrCreate<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOrCreateOptions<Attributes<M>>,\n ): Promise<[M, boolean]> {\n return finder.findOrCreate(this, options as FindOrCreateOptions);\n }\n\n /**\n * Finds a row, or builds a new unsaved instance when none matches; nothing is inserted.\n *\n * @param this - The model class (or a scoped model class from {@link Model.scope}).\n * @param options - `where` to search (its equality values also seed the built instance), `defaults` to add when building.\n * @returns `[instance, built]`.\n * @example\n * ```ts\n * const [tag, built] = await Tag.findOrBuild({ where: { name: 'news' } });\n * if (built) {\n * await tag.save();\n * }\n * ```\n */\n static findOrBuild<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOrCreateOptions<Attributes<M>>,\n ): Promise<[M, boolean]> {\n return finder.findOrBuild(this, options as FindOrCreateOptions);\n }\n };\n};\n","import type { HookFunction, HookType } from '../../hooks/hooks.ts';\n\n/**\n * Named hook method of a model class, e.g. `Model.beforeCreate`: registers a hook function, optionally under a name that\n * {@link Model.removeHook} can use later.\n *\n * @example\n * ```ts\n * User.beforeCreate(async (instance: User) => {\n * instance.set('email', String(instance.get('email')).trim());\n * });\n * User.afterCreate('audit', async (instance: User) => {\n * console.log('created', instance.get('id'));\n * });\n * ```\n */\nexport type NamedHookAdder = {\n /**\n * @param fn - Hook function.\n */\n (fn: HookFunction): void;\n /**\n * @param name - Hook name, used to remove it later.\n * @param fn - Hook function.\n */\n (name: string, fn: HookFunction): void;\n};\n\n/** @internal Hook types that get a named adder method on model classes. */\nexport const NAMED_HOOKS = [\n 'beforeValidate',\n 'afterValidate',\n 'validationFailed',\n 'beforeCreate',\n 'afterCreate',\n 'beforeUpdate',\n 'afterUpdate',\n 'beforeSave',\n 'afterSave',\n 'beforeDestroy',\n 'afterDestroy',\n 'beforeRestore',\n 'afterRestore',\n 'beforeUpsert',\n 'afterUpsert',\n 'beforeBulkCreate',\n 'afterBulkCreate',\n 'beforeBulkUpdate',\n 'afterBulkUpdate',\n 'beforeBulkDestroy',\n 'afterBulkDestroy',\n 'beforeBulkRestore',\n 'afterBulkRestore',\n 'beforeFind',\n 'beforeFindAfterExpandIncludeAll',\n 'beforeFindAfterOptions',\n 'afterFind',\n 'beforeCount',\n] as const satisfies readonly HookType[];\n","import type { HookFunction, HookType } from '../../hooks/hooks.ts';\nimport type { Model } from '../model.ts';\nimport { lifecycle, registry } from '../model-services.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport { NAMED_HOOKS, type NamedHookAdder } from './named-hooks.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Hook statics of `Model`: `addHook`, `removeHook`, `hasHook(s)`, `runHooks` and the named adders (`Model.beforeCreate(fn)`, ...).\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelHooks = <TBase extends ModelConstructor>(Base: TBase) => {\n const Mixin = class HooksCapability extends Base {\n /** Adds a `beforeValidate` hook: `Model.beforeValidate(fn)` or `Model.beforeValidate(name, fn)`. */\n declare static beforeValidate: NamedHookAdder;\n\n /** Adds a `afterValidate` hook: `Model.afterValidate(fn)` or `Model.afterValidate(name, fn)`. */\n declare static afterValidate: NamedHookAdder;\n\n /** Adds a `validationFailed` hook: `Model.validationFailed(fn)` or `Model.validationFailed(name, fn)`. */\n declare static validationFailed: NamedHookAdder;\n\n /** Adds a `beforeCreate` hook: `Model.beforeCreate(fn)` or `Model.beforeCreate(name, fn)`. */\n declare static beforeCreate: NamedHookAdder;\n\n /** Adds a `afterCreate` hook: `Model.afterCreate(fn)` or `Model.afterCreate(name, fn)`. */\n declare static afterCreate: NamedHookAdder;\n\n /** Adds a `beforeUpdate` hook: `Model.beforeUpdate(fn)` or `Model.beforeUpdate(name, fn)`. */\n declare static beforeUpdate: NamedHookAdder;\n\n /** Adds a `afterUpdate` hook: `Model.afterUpdate(fn)` or `Model.afterUpdate(name, fn)`. */\n declare static afterUpdate: NamedHookAdder;\n\n /** Adds a `beforeSave` hook: `Model.beforeSave(fn)` or `Model.beforeSave(name, fn)`. */\n declare static beforeSave: NamedHookAdder;\n\n /** Adds a `afterSave` hook: `Model.afterSave(fn)` or `Model.afterSave(name, fn)`. */\n declare static afterSave: NamedHookAdder;\n\n /** Adds a `beforeDestroy` hook: `Model.beforeDestroy(fn)` or `Model.beforeDestroy(name, fn)`. */\n declare static beforeDestroy: NamedHookAdder;\n\n /** Adds a `afterDestroy` hook: `Model.afterDestroy(fn)` or `Model.afterDestroy(name, fn)`. */\n declare static afterDestroy: NamedHookAdder;\n\n /** Adds a `beforeRestore` hook: `Model.beforeRestore(fn)` or `Model.beforeRestore(name, fn)`. */\n declare static beforeRestore: NamedHookAdder;\n\n /** Adds a `afterRestore` hook: `Model.afterRestore(fn)` or `Model.afterRestore(name, fn)`. */\n declare static afterRestore: NamedHookAdder;\n\n /** Adds a `beforeUpsert` hook: `Model.beforeUpsert(fn)` or `Model.beforeUpsert(name, fn)`. */\n declare static beforeUpsert: NamedHookAdder;\n\n /** Adds a `afterUpsert` hook: `Model.afterUpsert(fn)` or `Model.afterUpsert(name, fn)`. */\n declare static afterUpsert: NamedHookAdder;\n\n /** Adds a `beforeBulkCreate` hook: `Model.beforeBulkCreate(fn)` or `Model.beforeBulkCreate(name, fn)`. */\n declare static beforeBulkCreate: NamedHookAdder;\n\n /** Adds a `afterBulkCreate` hook: `Model.afterBulkCreate(fn)` or `Model.afterBulkCreate(name, fn)`. */\n declare static afterBulkCreate: NamedHookAdder;\n\n /** Adds a `beforeBulkUpdate` hook: `Model.beforeBulkUpdate(fn)` or `Model.beforeBulkUpdate(name, fn)`. */\n declare static beforeBulkUpdate: NamedHookAdder;\n\n /** Adds a `afterBulkUpdate` hook: `Model.afterBulkUpdate(fn)` or `Model.afterBulkUpdate(name, fn)`. */\n declare static afterBulkUpdate: NamedHookAdder;\n\n /** Adds a `beforeBulkDestroy` hook: `Model.beforeBulkDestroy(fn)` or `Model.beforeBulkDestroy(name, fn)`. */\n declare static beforeBulkDestroy: NamedHookAdder;\n\n /** Adds a `afterBulkDestroy` hook: `Model.afterBulkDestroy(fn)` or `Model.afterBulkDestroy(name, fn)`. */\n declare static afterBulkDestroy: NamedHookAdder;\n\n /** Adds a `beforeBulkRestore` hook: `Model.beforeBulkRestore(fn)` or `Model.beforeBulkRestore(name, fn)`. */\n declare static beforeBulkRestore: NamedHookAdder;\n\n /** Adds a `afterBulkRestore` hook: `Model.afterBulkRestore(fn)` or `Model.afterBulkRestore(name, fn)`. */\n declare static afterBulkRestore: NamedHookAdder;\n\n /** Adds a `beforeFind` hook: `Model.beforeFind(fn)` or `Model.beforeFind(name, fn)`. */\n declare static beforeFind: NamedHookAdder;\n\n /** Adds a `beforeFindAfterExpandIncludeAll` hook: `Model.beforeFindAfterExpandIncludeAll(fn)` or `Model.beforeFindAfterExpandIncludeAll(name, fn)`. */\n declare static beforeFindAfterExpandIncludeAll: NamedHookAdder;\n\n /** Adds a `beforeFindAfterOptions` hook: `Model.beforeFindAfterOptions(fn)` or `Model.beforeFindAfterOptions(name, fn)`. */\n declare static beforeFindAfterOptions: NamedHookAdder;\n\n /** Adds a `afterFind` hook: `Model.afterFind(fn)` or `Model.afterFind(name, fn)`. */\n declare static afterFind: NamedHookAdder;\n\n /** Adds a `beforeCount` hook: `Model.beforeCount(fn)` or `Model.beforeCount(name, fn)`. */\n declare static beforeCount: NamedHookAdder;\n\n /**\n * Registers a hook function for a lifecycle event of this model, same as the named adders such as\n * `Model.beforeCreate(fn)`. Hooks of one type run in registration order.\n *\n * @param this - The model class.\n * @param type - Hook type, e.g. `'beforeCreate'`.\n * @param nameOrFn - Hook name (to remove it later) or the hook function.\n * @param fn - Hook function when a name is given.\n * @returns The model class.\n * @example\n * ```ts\n * User.addHook('beforeCreate', 'normalizeEmail', async (instance: User) => {\n * instance.set('email', String(instance.get('email')).toLowerCase());\n * });\n * ```\n * @see [Hooks guide](/guide/hooks-validation)\n */\n static addHook<MS extends ModelStatic<AnyModel>>(\n this: MS,\n type: HookType,\n nameOrFn: string | HookFunction,\n fn?: HookFunction,\n ): MS {\n registry.addHook(this, type, nameOrFn, fn);\n return this;\n }\n\n /**\n * Removes hooks of a type from this model: one by name or function, or all of them.\n *\n * @param this - The model class.\n * @param type - Hook type.\n * @param nameOrFn - Hook name or function; all hooks of the type when omitted.\n * @returns The model class.\n * @example\n * ```ts\n * User.removeHook('beforeCreate', 'normalizeEmail');\n * ```\n */\n static removeHook<MS extends ModelStatic<AnyModel>>(\n this: MS,\n type: HookType,\n nameOrFn?: string | HookFunction,\n ): MS {\n registry.removeHook(this, type, nameOrFn);\n return this;\n }\n\n /**\n * Checks whether hooks of the type are registered on the model.\n *\n * @param type - Hook type.\n * @returns True when at least one hook exists, `false` after all were removed and\n * `undefined` (typed `boolean`, like Sequelize v6) for a type that never had a hook.\n * @example\n * ```ts\n * const registered = User.hasHook('beforeCreate');\n * ```\n */\n static hasHook(type: HookType): boolean {\n return registry.state(this).hooks.hasOrUndefined(type) as boolean;\n }\n\n /**\n * Alias of {@link Model.hasHook}.\n *\n * @param type - Hook type.\n * @returns Same as {@link Model.hasHook}.\n * @example\n * ```ts\n * const registered = User.hasHooks('afterFind');\n * ```\n */\n static hasHooks(type: HookType): boolean {\n return this.hasHook(type);\n }\n\n /**\n * Runs the hooks of a type with the given arguments (model hooks, then Sequelize-level hooks).\n *\n * @param type - Hook type.\n * @param args - Hook arguments.\n * @returns Resolves when all hooks finished.\n * @example\n * ```ts\n * await User.runHooks('beforeCreate', user, {});\n * ```\n */\n static runHooks(type: HookType, ...args: readonly unknown[]): Promise<void> {\n return lifecycle.runHooks(this, type, ...args);\n }\n };\n NAMED_HOOKS.forEach((type) => {\n Object.defineProperty(Mixin, type, {\n configurable: true,\n writable: true,\n value(this: typeof Mixin, nameOrFn: string | HookFunction, fn?: HookFunction): void {\n (this as unknown as typeof Model).addHook(type, nameOrFn, fn);\n },\n });\n });\n return Mixin;\n};\n","import { WriteStatement } from '../expressions/methods.ts';\nimport type { AttributeColumns } from './attribute-columns.ts';\nimport type { DeleteQueryBuilder } from './delete-query-builder.ts';\nimport type { InsertQueryBuilder } from './insert-query-builder.ts';\nimport type { ModelRegistry } from './model-registry.ts';\nimport type { ModelValues } from './model-values.ts';\nimport type { AnyModel, ModelStatic, Values } from './options.ts';\nimport type { UpdateQueryBuilder } from './update-query-builder.ts';\nimport type { WhereOptions } from './types.ts';\n\n/**\n * Options of `Model.deleteStatement()` and `Model.updateStatement()`.\n *\n * @example\n * ```ts\n * const options: WriteStatementOptions<Task> = { where: { done: true }, returning: true };\n * ```\n */\nexport type WriteStatementOptions<T = Values> = Readonly<{\n /** Rows to change; all rows when omitted. The default scope applies. */\n where?: WhereOptions<T>;\n /** Add `RETURNING` with all columns, so that the CTE can be read. */\n returning?: boolean;\n}>;\n\n/**\n * Options of `Model.updateStatement()`.\n *\n * @example\n * ```ts\n * const options: UpdateStatementOptions<Task> = { where: { id: 1 }, returning: true, silent: true };\n * ```\n */\nexport type UpdateStatementOptions<T = Values> = WriteStatementOptions<T> &\n Readonly<{\n /** Leave `updatedAt` unchanged. */\n silent?: boolean;\n }>;\n\n/** Builds the INSERT / UPDATE / DELETE statements of data-modifying CTEs. No hooks or validation run. */\nexport class StatementBuilder {\n readonly #registry: ModelRegistry;\n readonly #values: ModelValues;\n readonly #columns: AttributeColumns;\n readonly #updates: UpdateQueryBuilder;\n readonly #deletes: DeleteQueryBuilder;\n readonly #inserts: InsertQueryBuilder;\n\n /**\n * @param services - Model state, value rules and statement builders.\n */\n constructor(\n services: Readonly<{\n registry: ModelRegistry;\n values: ModelValues;\n columns: AttributeColumns;\n updates: UpdateQueryBuilder;\n deletes: DeleteQueryBuilder;\n inserts: InsertQueryBuilder;\n }>,\n ) {\n this.#registry = services.registry;\n this.#values = services.values;\n this.#columns = services.columns;\n this.#updates = services.updates;\n this.#deletes = services.deletes;\n this.#inserts = services.inserts;\n }\n\n /**\n * An UPDATE statement.\n *\n * @param model - Model class.\n * @param values - New attribute values.\n * @param options - Condition, RETURNING, `silent`.\n * @returns Statement for a CTE.\n */\n update(\n model: ModelStatic<AnyModel>,\n values: Values,\n options: UpdateStatementOptions,\n ): WriteStatement {\n return new WriteStatement(() => this.#updateNode(model, values, options));\n }\n\n #updateNode(model: ModelStatic<AnyModel>, values: Values, options: UpdateStatementOptions) {\n const { definition, runtime } = this.#registry.state(model);\n const changes = this.#values.withTimestamps(\n definition,\n values,\n new Date(),\n false,\n options.silent === true,\n );\n return this.#updates.build(\n definition,\n this.#columns.setItems(\n definition,\n changes,\n this.#columns.whereCompiler(definition, undefined),\n ),\n this.#where(model, options, true),\n this.#build(runtime.inAsAnyThreshold, options),\n );\n }\n\n /**\n * A DELETE statement (a real delete, also for paranoid models).\n *\n * @param model - Model class.\n * @param options - Condition and RETURNING.\n * @returns Statement for a CTE.\n */\n delete(model: ModelStatic<AnyModel>, options: WriteStatementOptions): WriteStatement {\n return new WriteStatement(() =>\n this.#deletes.build(\n this.#registry.state(model).definition,\n this.#where(model, options, false),\n this.#build(this.#registry.state(model).runtime.inAsAnyThreshold, options),\n ),\n );\n }\n\n /**\n * An INSERT statement of attribute-keyed rows (defaults and timestamps are filled in).\n *\n * @param model - Model class.\n * @param rows - Rows to insert.\n * @param options - RETURNING.\n * @returns Statement for a CTE.\n * @throws Error without rows.\n */\n insert(\n model: ModelStatic<AnyModel>,\n rows: readonly Values[],\n options: Pick<WriteStatementOptions, 'returning'>,\n ): WriteStatement {\n if (rows.length === 0) {\n throw new Error('insertStatement needs at least one row');\n }\n return new WriteStatement(() => {\n const { definition } = this.#registry.state(model);\n const initial = this.#values.initial(definition);\n const full = rows.map((row) =>\n this.#values.withTimestamps(definition, { ...initial, ...row }, new Date(), true, false),\n );\n return this.#inserts.build(definition, full, { returning: options.returning === true });\n });\n }\n\n #where(model: ModelStatic<AnyModel>, options: WriteStatementOptions, paranoid: boolean): unknown {\n const { definition } = this.#registry.state(model);\n const scoped = this.#registry.scoped(model, { where: options.where } as never) as {\n where?: unknown;\n };\n return paranoid ? this.#columns.paranoid(definition, scoped.where, undefined) : scoped.where;\n }\n\n #build(threshold: number | undefined, options: WriteStatementOptions) {\n return {\n ...(options.returning === true ? { returning: true } : {}),\n ...(threshold === undefined ? {} : { inAsAnyThreshold: threshold }),\n };\n }\n}\n","import { StatementBuilder } from './statement-builder.ts';\nimport {\n attributeColumns,\n deleteQueries,\n insertQueries,\n modelValues,\n registry,\n updateQueries,\n} from './model-services.ts';\n\n// Statement builder of data-modifying CTEs wired to the shared services (internal wiring of `Model`).\nexport const statements = new StatementBuilder({\n registry,\n values: modelValues,\n columns: attributeColumns,\n updates: updateQueries,\n deletes: deleteQueries,\n inserts: insertQueries,\n});\n","import type { Subquery, WriteStatement } from '../../expressions/methods.ts';\nimport type { MergeOptions } from '../merge-query-builder.ts';\nimport { copier, finder, inserter, merger } from '../model-operations.ts';\nimport { statements } from '../statement-services.ts';\nimport type { UpdateStatementOptions, WriteStatementOptions } from '../statement-builder.ts';\nimport type { MergeCallOptions, MergeResult } from '../operations/merge-operation.ts';\nimport type {\n AnyModel,\n Attributes,\n CopyFromOptions,\n CopyToOptions,\n CreationAttributes,\n FindOptions,\n InsertFromOptions,\n InsertOptions,\n ModelStatic,\n Values,\n} from '../options.ts';\nimport type { QueryOptionsBase } from '../runtime.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * PostgreSQL extension statics of `Model`: `insert`, `insertFrom`, `merge`, `subquery`, `updateStatement`, `deleteStatement`, `insertStatement`, `findEach`, `copyFrom`, `copyTo`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelPostgres = <TBase extends ModelConstructor>(Base: TBase) => {\n return class PostgresCapability extends Base {\n /**\n * Inserts rows with `INSERT ... ON CONFLICT` and returns the inserted or updated rows. Unlike\n * `bulkCreate`, rows skipped by `DO NOTHING` or by the `DO UPDATE ... WHERE` condition are not\n * returned. Each instance has `wasInserted`. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param values - Attribute values of one row or several rows.\n * @param options - Insert options (`onConflict`, `fields`, `hooks`, `validate`, `overriding`, `returningOld`, query options).\n * @returns Instances of the rows written by the statement.\n * @see {@link Model.bulkCreate} for the Sequelize v6 variant.\n * @see [Bulk writes guide](/guide/bulk-writes)\n * @example\n * ```ts\n * const items = [{ sku: 'a-1', qty: 5 }];\n * const rows = await Product.insert(items, {\n * onConflict: { target: ['sku'], action: { update: { qty: literal('\"Product\".\"qty\" + EXCLUDED.\"qty\"') } } },\n * });\n * const inserted = rows.filter((row) => row.wasInserted);\n * ```\n */\n static insert<M extends AnyModel>(\n this: ModelStatic<M>,\n values: CreationAttributes<M> | readonly CreationAttributes<M>[],\n options: InsertOptions<Attributes<M>> = {},\n ): Promise<M[]> {\n return inserter.insert(this, values as Values | readonly Values[], options as InsertOptions);\n }\n\n /**\n * `INSERT INTO ... SELECT`: inserts the rows produced by a subquery. Returns the inserted (or, with\n * `onConflict`, updated) rows with `wasInserted`. PostgreSQL extension.\n *\n * @param this - The target model class.\n * @param source - Subquery from `Model.subquery()`; its columns must match `options.columns`.\n * @param options - Target columns, `onConflict` and query options.\n * @returns Written rows.\n * @example\n * ```ts\n * await Task.insertFrom(\n * Post.subquery({ attributes: ['id', 'title'], where: { published: false } }),\n * { columns: ['postId', 'title'] },\n * );\n * ```\n */\n static insertFrom<M extends AnyModel>(\n this: ModelStatic<M>,\n source: Subquery,\n options: InsertFromOptions<Attributes<M>>,\n ): Promise<M[]> {\n return inserter.insertFrom(this, source, options as InsertFromOptions);\n }\n\n /**\n * `MERGE INTO ... USING ...` (PostgreSQL 15+). With `returning: true` (PostgreSQL 17+) returns the\n * written rows with the action taken. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param options - Source, join condition and WHEN clauses.\n * @returns Affected row count and, with `returning`, `{ action, instance }` per row.\n * @throws DatabaseError when the server rejects the statement (for example on PostgreSQL older than 15).\n * @example\n * ```ts\n * await Product.merge({\n * source: [{ sku: 'a', qty: 5 }],\n * on: { sku: col('source.sku') },\n * whenMatched: { update: { qty: literal('\"Product\".\"qty\" + \"source\".\"qty\"') } },\n * whenNotMatched: { insert: true },\n * });\n * ```\n */\n static merge<M extends AnyModel>(\n this: ModelStatic<M>,\n options: MergeOptions<Attributes<M>> &\n QueryOptionsBase &\n Readonly<{\n /** Return written rows (PostgreSQL 17+). */\n returning?: boolean;\n /** With `returning`: expose pre-statement values as `instance.oldValues` (PostgreSQL 18+). */\n returningOld?: boolean;\n }>,\n ): Promise<MergeResult<M>> {\n return merger.merge(this, options as MergeCallOptions);\n }\n\n /**\n * Builds a SELECT that can be embedded in another query: in `where` (`[Op.in]`, `=`, `exists()`),\n * in `attributes` (scalar subquery) and as a source of `insertFrom` / `merge`. Default scope and\n * paranoid filter apply; values stay bound parameters of the outer statement. PostgreSQL extension.\n *\n * @param this - The model class the subquery selects from.\n * @param options - Find options (`attributes`, `where`, `order`, `limit`, `include`, ...) and `as` (table alias).\n * @returns Subquery expression.\n * @example\n * ```ts\n * await User.findAll({ where: { id: { [Op.in]: Post.subquery({ attributes: ['userId'], where: { published: true } }) } } });\n * ```\n */\n static subquery<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> & Readonly<{ as?: string }> = {},\n ): Subquery {\n return finder.subquery(this, options as FindOptions & Readonly<{ as?: string }>);\n }\n\n /**\n * Builds an `UPDATE` for a data-modifying CTE (`with`); nothing runs until the outer query does.\n * No hooks or validation run; `updatedAt` is set unless `silent`. With `returning: true` the CTE\n * can be read through `source`. Queries with such a CTE always use the writer. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param values - New attribute values.\n * @param options - `where`, `returning`, `silent`.\n * @returns Statement for the `with` option.\n * @example\n * ```ts\n * const bumped = Task.updateStatement({ done: true }, { where: { id: 1 }, returning: true });\n * const rows = await Task.findAll({ with: { bumped }, source: 'bumped' });\n * ```\n */\n static updateStatement<M extends AnyModel>(\n this: ModelStatic<M>,\n values: Partial<Attributes<M>>,\n options: UpdateStatementOptions<Attributes<M>> = {},\n ): WriteStatement {\n return statements.update(this, values as Values, options as UpdateStatementOptions);\n }\n\n /**\n * Builds a `DELETE` for a data-modifying CTE (`with`). It is a real delete, also for paranoid\n * models, and ignores the paranoid filter. With `returning: true` the deleted rows can be read\n * through `source`, e.g. to move them to another table. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param options - `where`, `returning`.\n * @returns Statement for the `with` option.\n * @example\n * ```ts\n * const done = Task.deleteStatement({ where: { done: true }, returning: true });\n * const removed = await Task.findAll({ with: { done }, source: 'done' });\n * ```\n */\n static deleteStatement<M extends AnyModel>(\n this: ModelStatic<M>,\n options: WriteStatementOptions<Attributes<M>> = {},\n ): WriteStatement {\n return statements.delete(this, options as WriteStatementOptions);\n }\n\n /**\n * Builds an `INSERT` of attribute-keyed rows for a data-modifying CTE (`with`). Defaults and\n * timestamps are filled in; no hooks or validation run. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param rows - Rows to insert (at least one).\n * @param options - `returning`.\n * @returns Statement for the `with` option.\n * @throws Error without rows.\n * @example\n * ```ts\n * const added = Task.insertStatement([{ title: 'write docs' }], { returning: true });\n * const rows = await Task.findAll({ with: { added }, source: 'added' });\n * ```\n */\n static insertStatement<M extends AnyModel>(\n this: ModelStatic<M>,\n rows: readonly CreationAttributes<M>[],\n options: Pick<WriteStatementOptions<Attributes<M>>, 'returning'> = {},\n ): WriteStatement {\n return statements.insert(this, rows as readonly Values[], options);\n }\n\n /**\n * Streams rows with a server-side cursor (`DECLARE ... CURSOR` + `FETCH n`), so large result sets\n * are not loaded at once. Runs inside `options.transaction` or its own transaction; the cursor is\n * closed when iteration ends or is stopped early. Joined includes are not supported. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param options - Find options.\n * @param cursor - `batchSize` (rows per FETCH, default 100).\n * @returns Async iterator of instances.\n * @example\n * ```ts\n * for await (const user of User.findEach({ where: { active: true } }, { batchSize: 500 })) {\n * console.log(user.get('email'));\n * }\n * ```\n */\n static findEach<M extends AnyModel>(\n this: ModelStatic<M>,\n options: FindOptions<Attributes<M>> = {},\n cursor: Readonly<{ batchSize?: number }> = {},\n ): AsyncGenerator<M, void, undefined> {\n return finder.findEach(this, options as FindOptions, cursor);\n }\n\n /**\n * Bulk-loads rows with `COPY ... FROM STDIN` (text format) — much faster than INSERT for large\n * volumes. No hooks or validation run; missing values are written as `NULL`. `createdAt` /\n * `updatedAt` are filled when the model has timestamps. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param rows - Rows (array, iterable or async iterable of attribute values).\n * @param options - `columns` (attribute names; default: keys of the first row of an array) and query options.\n * @returns Number of copied rows.\n * @example\n * ```ts\n * const copied = await Task.copyFrom(\n * [{ title: 'first' }, { title: 'second' }],\n * { columns: ['title'] },\n * );\n * ```\n */\n static copyFrom<M extends AnyModel>(\n this: ModelStatic<M>,\n rows: Iterable<CreationAttributes<M>> | AsyncIterable<CreationAttributes<M>>,\n options: CopyFromOptions<Attributes<M>> = {},\n ): Promise<number> {\n return copier.copyFrom(\n this,\n rows as Iterable<Values> | AsyncIterable<Values>,\n options as CopyFromOptions,\n );\n }\n\n /**\n * Streams `COPY (SELECT ...) TO STDOUT` output — the fastest way to export rows (e.g. CSV). Default\n * scope, paranoid filter, `with` / `source` and includes apply. Values of the query are inlined as\n * escaped literals because COPY cannot take parameters (ADR-013). Stopping early drains the rest\n * before the connection is released. PostgreSQL extension.\n *\n * @param this - The model class.\n * @param options - Find options and output format (`format`, `header`, ...).\n * @returns Async iterator of raw output chunks.\n * @example\n * ```ts\n * for await (const chunk of User.copyTo({ attributes: ['id', 'email'], format: 'csv', header: true })) {\n * process.stdout.write(chunk);\n * }\n * ```\n */\n static copyTo<M extends AnyModel>(\n this: ModelStatic<M>,\n options: CopyToOptions<Attributes<M>> = {},\n ): AsyncGenerator<Buffer, void, undefined> {\n return copier.copyTo(this, options as CopyToOptions);\n }\n };\n};\n","import { DdlGenerator, type ColumnDefinition } from '../ddl/ddl-generator.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { ModelDefinition } from '../model/model-definition.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { ModelTables } from './model-tables.ts';\nimport type { QueryInterface } from './query-interface.ts';\nimport type { ColumnDescription } from './query-interface-types.ts';\n\nconst ddl = new DdlGenerator();\n\nconst sqlLiteral = new SqlLiteral();\n\n/** Existing table and model columns compared by `alter`. */\ntype AlterTarget = Readonly<{\n table: TableName;\n qualified: string;\n columns: readonly ColumnDefinition[];\n described: Readonly<Record<string, ColumnDescription>>;\n}>;\n\n/**\n * Diffs a model against its existing table for `sync({ alter })`: added, changed, referencing and\n * dropped columns, in that order.\n *\n * @internal\n */\nexport class AlterPlanner {\n readonly #queryInterface: QueryInterface;\n readonly #tables: ModelTables;\n\n /**\n * @param queryInterface - Query interface used to inspect the table.\n * @param tables - Model table DDL.\n */\n constructor(queryInterface: QueryInterface, tables: ModelTables) {\n this.#queryInterface = queryInterface;\n this.#tables = tables;\n }\n\n /**\n * Statements that bring the existing table in line with the model.\n *\n * @param definition - Model definition.\n * @param alter - `alter` option; `{ drop: false }` keeps extra columns.\n * @param options - `schema` and query options.\n * @returns Statements.\n */\n async statements(\n definition: ModelDefinition,\n alter: boolean | Readonly<{ drop?: boolean }>,\n options: QueryOptionsBase & Readonly<{ schema?: string }>,\n ): Promise<readonly string[]> {\n const table = this.#tables.tableOf(definition);\n const qualified = sqlLiteral.quoteTable(table);\n const described = await this.#queryInterface.describeTable(table, options);\n const columns = this.#tables.storedColumns(definition);\n const foreignKeys = await this.foreignKeyColumns(table, options);\n const target: AlterTarget = { table, qualified, columns, described };\n return [\n ...this.#added(target),\n ...this.#changed(target),\n ...this.#references(target, foreignKeys, options.schema),\n ...this.#dropped(target, alter),\n ];\n }\n\n /**\n * Columns of the table that already have a foreign key.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns Column names.\n */\n async foreignKeyColumns(\n table: TableName,\n options: QueryOptionsBase,\n ): Promise<ReadonlySet<string>> {\n const references = await this.#queryInterface.getForeignKeyReferencesForTable(table, options);\n return new Set(references.map((reference) => reference.columnName));\n }\n\n #added({ table, qualified, columns, described }: AlterTarget): readonly string[] {\n return columns\n .filter((column) => described[column.field] === undefined)\n .flatMap((column) => {\n const enumSql = ddl.createEnumSql(table, column);\n return [\n ...(enumSql === undefined ? [] : [enumSql]),\n `ALTER TABLE ${qualified} ADD COLUMN ${ddl.columnSql(table, column)}`,\n ...ddl.columnCommentSql(table, column),\n ];\n });\n }\n\n #changed({ table, columns, described }: AlterTarget): readonly string[] {\n return columns\n .filter(\n (column) =>\n described[column.field] !== undefined &&\n !column.primaryKey &&\n column.generated === undefined &&\n column.identity === undefined,\n )\n .flatMap((column) => [\n ...ddl.addEnumValuesSql(table, column),\n ...ddl.changeColumnSql(table, column),\n ]);\n }\n\n #references(\n { qualified, columns, described }: AlterTarget,\n foreignKeys: ReadonlySet<string>,\n schema: string | undefined,\n ): readonly string[] {\n return columns\n .filter(\n (column) =>\n described[column.field] !== undefined &&\n column.references !== undefined &&\n !foreignKeys.has(column.field),\n )\n .map((column) => this.#tables.foreignKeySql(qualified, column, schema));\n }\n\n #dropped(\n { qualified, columns, described }: AlterTarget,\n alter: boolean | Readonly<{ drop?: boolean }>,\n ): readonly string[] {\n if (typeof alter === 'object' && alter.drop === false) {\n return [];\n }\n const fields = new Set(columns.map((column) => column.field));\n return Object.keys(described)\n .filter((field) => !fields.has(field))\n .map((field) => `ALTER TABLE ${qualified} DROP COLUMN ${SqlCompiler.quoteIdent(field)}`);\n }\n}\n","import { DdlGenerator, type ColumnDefinition, type IndexField } from '../ddl/ddl-generator.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { ModelDefinition } from '../model/model-definition.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\n\nconst ddl = new DdlGenerator();\n\n/**\n * Table, column, index and foreign key DDL derived from a model definition for `sync()`.\n *\n * @internal\n */\nexport class ModelTables {\n /**\n * The definition moved to another schema (the `schema` option of `sync()` / `drop()`).\n *\n * @param definition - Model definition.\n * @param schema - Target schema, or undefined to keep the model's.\n * @returns Definition in the schema.\n */\n inSchema(definition: ModelDefinition, schema: string | undefined): ModelDefinition {\n return schema === undefined ? definition : { ...definition, schema };\n }\n\n /**\n * Table reference of a definition.\n *\n * @param definition - Model definition.\n * @returns Table name or `{ tableName, schema }`.\n */\n tableOf(definition: ModelDefinition): TableName {\n return definition.schema === undefined\n ? definition.tableName\n : { tableName: definition.tableName, schema: definition.schema };\n }\n\n /**\n * Columns stored in the table (virtual attributes excluded).\n *\n * @param definition - Model definition.\n * @returns Column definitions.\n */\n storedColumns(definition: ModelDefinition): readonly ColumnDefinition[] {\n return [...definition.attributes.values()]\n .filter((attribute) => attribute.type.isVirtual !== true)\n .map((attribute) => ddl.columnOf(attribute));\n }\n\n /**\n * `CREATE TABLE` (and enum types) of a definition; deferred columns lose their foreign keys.\n *\n * @param definition - Model definition.\n * @param deferred - Columns created without their foreign keys.\n * @param schema - `schema` option of `sync()`.\n * @returns Statements.\n */\n createStatements(\n definition: ModelDefinition,\n deferred: readonly string[],\n schema: string | undefined,\n ): readonly string[] {\n return ddl.createTableSql(\n this.tableOf(definition),\n this.storedColumns(definition).map((column) =>\n deferred.includes(column.field) ? this.#withoutReferences(column) : column,\n ),\n {\n ...(definition.options.comment === undefined\n ? {}\n : { comment: definition.options.comment }),\n ...(definition.options.unlogged === true ? { unlogged: true } : {}),\n ...(definition.options.temporary === true ? { temporary: true } : {}),\n ...(schema === undefined ? {} : { defaultSchema: schema }),\n },\n );\n }\n\n /**\n * `CREATE INDEX IF NOT EXISTS` of the model indexes, attribute names mapped to fields.\n *\n * @param definition - Model definition.\n * @returns Statements.\n */\n indexStatements(definition: ModelDefinition): readonly string[] {\n const table = this.tableOf(definition);\n return (definition.options.indexes ?? []).map((index) =>\n ddl.createIndexSql(table, {\n ...index,\n ifNotExists: true,\n fields: (index.fields ?? []).map((field) => this.#indexField(definition, field)),\n }),\n );\n }\n\n /**\n * `ALTER TABLE ... ADD FOREIGN KEY` of a column.\n *\n * @param qualified - Quoted table name.\n * @param column - Column with `references`.\n * @param schema - `schema` option of `sync()`.\n * @returns Statement.\n */\n foreignKeySql(qualified: string, column: ColumnDefinition, schema: string | undefined): string {\n return `ALTER TABLE ${qualified} ADD FOREIGN KEY (${SqlCompiler.quoteIdent(column.field)}) ${ddl.referencesSql(column, schema) ?? ''}`;\n }\n\n #indexField(definition: ModelDefinition, field: IndexField): IndexField {\n if (typeof field === 'string') {\n return definition.attributes.get(field)?.field ?? field;\n }\n return field.name === undefined\n ? field\n : { ...field, name: definition.attributes.get(field.name)?.field ?? field.name };\n }\n\n #withoutReferences(column: ColumnDefinition): ColumnDefinition {\n return Object.fromEntries(\n Object.entries(column).filter(([key]) => key !== 'references'),\n ) as ColumnDefinition;\n }\n}\n","import type { AttributeDefinition, ModelDefinition } from '../model/model-definition.ts';\n\n/**\n * Plans the order of `sync()` over several models: referenced tables first, and the foreign keys\n * of reference cycles deferred until every table exists.\n *\n * @internal\n */\nexport class SyncPlanner {\n /**\n * Orders definitions so that referenced tables come first.\n *\n * @param definitions - Model definitions.\n * @returns Definitions in dependency order.\n */\n dependencyOrder(definitions: readonly ModelDefinition[]): readonly ModelDefinition[] {\n const byTable = new Map(definitions.map((definition) => [definition.tableName, definition]));\n return definitions.reduce<readonly ModelDefinition[]>(\n (ordered, definition) => this.#visit(byTable, definition, new Set(), ordered),\n [],\n );\n }\n\n /**\n * Columns (by field) of each definition whose foreign key points to a table created later in\n * `ordered` — a reference cycle. Their tables are created without these constraints, which are\n * added once every table exists.\n *\n * @param ordered - Definitions in dependency order.\n * @returns Deferred fields per definition.\n */\n deferredReferences(\n ordered: readonly ModelDefinition[],\n ): ReadonlyMap<ModelDefinition, readonly string[]> {\n const position = new Map(ordered.map((definition, index) => [definition.tableName, index]));\n return new Map(\n ordered.map((definition, index) => [\n definition,\n [...definition.attributes.values()]\n .filter((attribute) => {\n const target = position.get(this.#referencedTable(attribute.references) ?? '');\n return target !== undefined && target > index;\n })\n .map((attribute) => attribute.field),\n ]),\n );\n }\n\n #visit(\n byTable: ReadonlyMap<string, ModelDefinition>,\n definition: ModelDefinition,\n seen: ReadonlySet<string>,\n ordered: readonly ModelDefinition[],\n ): readonly ModelDefinition[] {\n if (ordered.includes(definition) || seen.has(definition.tableName)) {\n return ordered;\n }\n const nextSeen = new Set([...seen, definition.tableName]);\n const withDependencies = this.#dependencies(byTable, definition).reduce(\n (acc, dependency) => this.#visit(byTable, dependency, nextSeen, acc),\n ordered,\n );\n return withDependencies.includes(definition)\n ? withDependencies\n : [...withDependencies, definition];\n }\n\n #dependencies(\n byTable: ReadonlyMap<string, ModelDefinition>,\n definition: ModelDefinition,\n ): readonly ModelDefinition[] {\n return this.#referencedTables(definition)\n .map((table) => byTable.get(table))\n .filter(\n (dependency): dependency is ModelDefinition =>\n dependency !== undefined && dependency !== definition,\n );\n }\n\n #referencedTable(references: AttributeDefinition['references']): string | undefined {\n return references === undefined\n ? undefined\n : typeof references === 'string'\n ? references\n : typeof references.model === 'string'\n ? references.model\n : references.model.tableName;\n }\n\n #referencedTables(definition: ModelDefinition): readonly string[] {\n return [...definition.attributes.values()].flatMap((attribute) => {\n const table = this.#referencedTable(attribute.references);\n return table === undefined ? [] : [table];\n });\n }\n}\n","import { SqlLiteral } from '../ddl/sql-literal.ts';\nimport type { ModelDefinition } from '../model/model-definition.ts';\nimport type { ModelRuntime, QueryOptionsBase } from '../model/runtime.ts';\nimport { AlterPlanner } from './alter-planner.ts';\nimport { ModelTables } from './model-tables.ts';\nimport type { QueryInterface } from './query-interface.ts';\nimport { SyncPlanner } from './sync-planner.ts';\n\n/**\n * `alter` options of `sync()`.\n *\n * @example\n * ```ts\n * const alter: AlterOptions = { drop: false };\n * await sequelize.sync({ alter });\n * ```\n */\nexport type AlterOptions = Readonly<{\n /** Drop columns that are not in the model. Default true. */\n drop?: boolean;\n}>;\n\n/**\n * Options of `sync()`: `force`, `alter`, `match`, `schema` plus the common query options.\n *\n * @example\n * ```ts\n * const options: SyncOptions = { alter: true, match: /_test$/, schema: 'tenant_1' };\n * await sequelize.sync(options);\n * ```\n */\nexport type SyncOptions = QueryOptionsBase &\n Readonly<{\n /** Drop and re-create tables. */\n force?: boolean;\n /** Alter existing tables to match models; `{ drop: false }` keeps extra columns. */\n alter?: boolean | AlterOptions;\n /** Only sync when the database name matches this pattern. */\n match?: RegExp;\n /** Create the tables in this schema instead of the models' schema (references stay in it too). */\n schema?: string;\n /** Run the `beforeSync` / `afterSync` hooks. Default true. */\n hooks?: boolean;\n }>;\n\n/** Wraps the sync of one model (used to run its sync hooks). */\nexport type SyncWrapper = (definition: ModelDefinition, run: () => Promise<void>) => Promise<void>;\n\n/**\n * Options of `drop()`: `cascade`, `schema` plus the common query options.\n *\n * @example\n * ```ts\n * const options: DropOptions = { cascade: true, schema: 'tenant_1' };\n * await sequelize.drop(options);\n * ```\n */\nexport type DropOptions = QueryOptionsBase &\n Readonly<{\n /** `DROP TABLE ... CASCADE`. */\n cascade?: boolean;\n /** Drop the tables in this schema instead of the models' schema. */\n schema?: string;\n }>;\n\nconst sqlLiteral = new SqlLiteral();\n\nconst planner = new SyncPlanner();\n\nconst tables = new ModelTables();\n\n/**\n * Creates, alters and drops the tables of model definitions (`sync()` / `drop()`): dependency\n * order, deferred foreign keys for reference cycles, `force`, `alter` and the `schema` option.\n *\n * @internal\n */\nexport class SchemaSynchronizer {\n readonly #runtime: ModelRuntime;\n readonly #queryInterface: QueryInterface;\n readonly #alter: AlterPlanner;\n\n /**\n * @param runtime - Runtime executing the statements.\n * @param queryInterface - Query interface used to inspect and drop tables.\n */\n constructor(runtime: ModelRuntime, queryInterface: QueryInterface) {\n this.#runtime = runtime;\n this.#queryInterface = queryInterface;\n this.#alter = new AlterPlanner(queryInterface, tables);\n }\n\n /**\n * Syncs several models: referenced tables first, foreign keys of reference cycles added once\n * every table exists. With `force`, drops the tables in reverse order first.\n *\n * @param definitions - Model definitions.\n * @param options - `force`, `alter`, `schema` and query options.\n * @param wrap - Runs around the sync of each model.\n */\n async syncAll(\n definitions: readonly ModelDefinition[],\n options: SyncOptions = {},\n wrap: SyncWrapper = (_definition, run) => run(),\n ): Promise<void> {\n const ordered = planner.dependencyOrder(definitions);\n if (options.force === true) {\n await this.#each(ordered.toReversed(), (definition) =>\n this.drop(definition, { ...options, cascade: true }),\n );\n }\n await this.#syncOrdered(ordered, options, wrap);\n }\n\n async #syncOrdered(\n ordered: readonly ModelDefinition[],\n options: SyncOptions,\n wrap: SyncWrapper,\n ): Promise<void> {\n const deferred = planner.deferredReferences(ordered);\n await this.#each(ordered, (definition) =>\n wrap(definition, () =>\n this.sync(definition, { ...options, force: false }, deferred.get(definition)),\n ),\n );\n await this.#each(ordered, (definition) =>\n this.#addDeferredReferences(definition, deferred.get(definition) ?? [], options),\n );\n }\n\n /**\n * Drops the tables of several models in reverse foreign-key order.\n *\n * @param definitions - Model definitions.\n * @param options - `cascade`, `schema` and query options.\n */\n async dropAll(definitions: readonly ModelDefinition[], options: DropOptions = {}): Promise<void> {\n await this.#each(planner.dependencyOrder(definitions).toReversed(), (definition) =>\n this.drop(definition, options),\n );\n }\n\n /**\n * Creates (or alters / re-creates) the table of a model and its indexes.\n *\n * @param model - Model definition.\n * @param options - `force`, `alter`, `schema` and query options.\n * @param deferred - Columns created without their foreign keys (added later).\n */\n async sync(\n model: ModelDefinition,\n options: SyncOptions = {},\n deferred: readonly string[] = [],\n ): Promise<void> {\n const definition = tables.inSchema(model, options.schema);\n if (options.force === true) {\n await this.drop(definition, { ...options, cascade: true });\n }\n const statements = await this.#tableStatements(definition, options, deferred);\n await this.#run([...statements, ...tables.indexStatements(definition)], options);\n }\n\n /**\n * Drops the table of a model and its enum types.\n *\n * @param model - Model definition.\n * @param options - `cascade`, `schema` and query options.\n */\n async drop(model: ModelDefinition, options: DropOptions = {}): Promise<void> {\n const definition = tables.inSchema(model, options.schema);\n const table = tables.tableOf(definition);\n await this.#queryInterface.dropTable(table, options);\n const enumFields = [...definition.attributes.values()]\n .filter(\n (attribute) => attribute.type.key === 'ENUM' || attribute.type.subtype?.key === 'ENUM',\n )\n .map((attribute) => attribute.field);\n await this.#queryInterface.dropEnumsOf(table, enumFields, options);\n }\n\n async #tableStatements(\n definition: ModelDefinition,\n options: SyncOptions,\n deferred: readonly string[],\n ): Promise<readonly string[]> {\n const exists =\n options.force !== true &&\n (await this.#queryInterface.tableExists(tables.tableOf(definition), options));\n if (exists && options.alter !== undefined && options.alter !== false) {\n return await this.#alter.statements(definition, options.alter, options);\n }\n return exists ? [] : tables.createStatements(definition, deferred, options.schema);\n }\n\n async #each(\n definitions: readonly ModelDefinition[],\n action: (definition: ModelDefinition) => Promise<void>,\n ): Promise<void> {\n await definitions.reduce<Promise<unknown>>(\n (previous, definition) => previous.then(() => action(definition)),\n Promise.resolve(),\n );\n }\n\n async #run(statements: readonly string[], options: QueryOptionsBase): Promise<void> {\n await statements.reduce<Promise<unknown>>(\n (previous, text) => previous.then(() => this.#runtime.execute({ text, values: [] }, options)),\n Promise.resolve(),\n );\n }\n\n /** Adds the deferred foreign keys of a table that are not there yet. */\n async #addDeferredReferences(\n model: ModelDefinition,\n fields: readonly string[],\n options: QueryOptionsBase & Readonly<{ schema?: string }>,\n ): Promise<void> {\n if (fields.length === 0) {\n return;\n }\n const { schema } = options;\n const definition = tables.inSchema(model, schema);\n const table = tables.tableOf(definition);\n const existing = await this.#alter.foreignKeyColumns(table, options);\n await this.#run(\n tables\n .storedColumns(definition)\n .filter((column) => fields.includes(column.field) && !existing.has(column.field))\n .map((column) => tables.foreignKeySql(sqlLiteral.quoteTable(table), column, schema)),\n options,\n );\n }\n}\n","import {\n SchemaSynchronizer,\n type DropOptions,\n type SyncOptions,\n} from '../../query-interface/schema-synchronizer.ts';\nimport { destroyer } from '../model-operations.ts';\nimport { registry, syncHooks } from '../model-services.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport type { QueryOptionsBase } from '../runtime.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Schema statics of `Model`: `sync`, `drop`, `truncate`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelSchema = <TBase extends ModelConstructor>(Base: TBase) => {\n return class SchemaCapability extends Base {\n /**\n * Creates the table of this model and its indexes when missing. `force: true` drops it first\n * (with `CASCADE`); `alter` changes an existing table to match the model.\n *\n * @param this - The model class.\n * @param options - `force`, `alter`, `match`, `schema` and query options.\n * @returns The model class.\n * @example\n * ```ts\n * await User.sync({ alter: true });\n * ```\n * @see [Schema guide](/guide/schema)\n */\n static async sync<MS extends ModelStatic<AnyModel>>(\n this: MS,\n options: SyncOptions = {},\n ): Promise<MS> {\n const { definition, runtime } = registry.state(this);\n await syncHooks.around(this, options, () =>\n new SchemaSynchronizer(runtime, runtime.queryInterface()).sync(definition, options),\n );\n return this;\n }\n\n /**\n * Drops the table of this model and the enum types it owns.\n *\n * @param options - `cascade`, `schema` and query options.\n * @returns Resolves when done.\n * @example\n * ```ts\n * await Task.drop({ cascade: true });\n * ```\n */\n static async drop(options: DropOptions = {}): Promise<void> {\n const { definition, runtime } = registry.state(this);\n await new SchemaSynchronizer(runtime, runtime.queryInterface()).drop(definition, options);\n }\n\n /**\n * Removes all rows with `TRUNCATE`, without running hooks.\n *\n * @param options - `cascade`, `restartIdentity` and query options.\n * @returns Resolves when done.\n * @example\n * ```ts\n * await Task.truncate({ restartIdentity: true, cascade: true });\n * ```\n */\n static truncate(\n options: QueryOptionsBase & Readonly<{ cascade?: boolean; restartIdentity?: boolean }> = {},\n ): Promise<void> {\n return destroyer.truncate(this, options);\n }\n };\n};\n","import { registry } from '../model-services.ts';\nimport type { Model } from '../model.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Schema binding static of `Model`: `schema`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelSchemaBinding = <TBase extends ModelConstructor>(Base: TBase) => {\n return class SchemaBindingCapability extends Base {\n /**\n * Returns a model class whose queries target a PostgreSQL schema, like Sequelize v6.\n *\n * The copy has the attributes, hooks, scopes and associations of this model as they are at\n * the time of the call and keeps the scope selection of this class. Changes made to the\n * original afterwards are not seen by the copy.\n *\n * @param this - The model class being bound.\n * @param schema - Schema name.\n * @param options - Separator between schema and table reported by `getTableName` (a string,\n * or `{ schemaDelimiter }`); PostgreSQL always qualifies with `.` in SQL. Defaults to `.`.\n * @returns Schema-bound model class (instances are instances of this model).\n * @example\n * ```ts\n * const TenantUser = User.schema('tenant_a');\n * await TenantUser.findAll(); // SELECT ... FROM \"tenant_a\".\"users\"\n * TenantUser.getTableName(); // { tableName: 'users', schema: 'tenant_a', delimiter: '.' }\n * ```\n */\n static schema<MS extends ModelStatic<AnyModel>>(\n this: MS,\n schema: string,\n options?: string | Readonly<{ schemaDelimiter?: string }>,\n ): MS {\n const Bound = { [this.name]: class extends (this as unknown as typeof Model) {} }[\n this.name\n ] as unknown as MS;\n const delimiter = typeof options === 'string' ? options : options?.schemaDelimiter;\n registry.bindSchema(this, Bound, schema, delimiter || undefined);\n return Bound;\n }\n };\n};\n","import { registry } from '../model-services.ts';\nimport type { Model } from '../model.ts';\nimport type { AnyModel, ModelStatic } from '../options.ts';\nimport type { ScopeDefinition, ScopeSelector } from '../scope-registry.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Scope statics of `Model`: `scope`, `unscoped`, `addScope`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelScopes = <TBase extends ModelConstructor>(Base: TBase) => {\n return class ScopesCapability extends Base {\n /**\n * Creates a model class that applies the given scopes to its queries instead of the default\n * scope. The original class is not changed.\n *\n * @param this - The model class.\n * @param selectors - Scope names, `{ method: [name, ...args] }`, inline options, `'defaultScope'`, or `null`.\n * @returns Scoped model class (instances are instances of this model).\n * @throws Error when a named scope does not exist.\n * @example\n * ```ts\n * await User.scope('active', { method: ['olderThan', 18] }).findAll();\n * ```\n * @see [Querying guide](/guide/querying)\n */\n static scope<MS extends ModelStatic<AnyModel>>(\n this: MS,\n ...selectors: readonly (ScopeSelector | readonly ScopeSelector[])[]\n ): MS {\n const Scoped = { [this.name]: class extends (this as unknown as typeof Model) {} }[\n this.name\n ] as unknown as MS;\n const flat = selectors.flatMap((selector) =>\n Array.isArray(selector) ? selector : [selector],\n ) as readonly ScopeSelector[];\n registry.selectScopes(this, Scoped, flat);\n return Scoped;\n }\n\n /**\n * Creates a model class that applies no scope at all, not even the default scope.\n *\n * @param this - The model class.\n * @returns Unscoped model class.\n * @example\n * ```ts\n * const everyone = await User.unscoped().findAll();\n * ```\n */\n static unscoped<MS extends ModelStatic<AnyModel>>(this: MS): MS {\n return this.scope();\n }\n\n /**\n * Adds a named scope (or replaces the default scope with name `'defaultScope'`).\n *\n * @param name - Scope name.\n * @param scope - Options or a function returning options.\n * @param options - `override: true` replaces an existing scope.\n * @throws Error when the scope exists and `override` is not set.\n * @example\n * ```ts\n * User.addScope('active', { where: { active: true } });\n * User.addScope('olderThan', (age: number) => ({ where: { age: { [Op.gt]: age } } }));\n * ```\n */\n static addScope(\n name: string,\n scope: ScopeDefinition,\n options: Readonly<{ override?: boolean }> = {},\n ): void {\n registry.addScope(this, name, scope, options.override === true);\n }\n };\n};\n","import {\n bulkCreator,\n creator,\n destroyer,\n incrementer,\n updater,\n upserter,\n} from '../model-operations.ts';\nimport type {\n AnyModel,\n AttributeAmounts,\n Attributes,\n BuildOptions,\n BulkCreateOptions,\n CreateOptions,\n CreationAttributes,\n DestroyOptions,\n IncrementOptions,\n ModelStatic,\n RestoreOptions,\n UpdateOptions,\n UpsertOptions,\n Values,\n} from '../options.ts';\nimport type { ModelConstructor } from './model-constructor.ts';\n\n/**\n * Write statics of `Model`: `build`, `bulkBuild`, `create`, `bulkCreate`, `upsert`, `update`, `destroy`, `restore`, `increment`, `decrement`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const ModelWriters = <TBase extends ModelConstructor>(Base: TBase) => {\n return class WritersCapability extends Base {\n /**\n * Builds a new instance in memory without touching the database; call `save()` to insert it.\n * Defaults and custom setters are applied.\n *\n * @param this - The model class.\n * @param values - Attribute values.\n * @param options - Build options.\n * @returns New instance.\n * @example\n * ```ts\n * const user = User.build({ email: 'ada@example.com' });\n * await user.save();\n * ```\n */\n static build<M extends AnyModel>(\n this: ModelStatic<M>,\n values?: CreationAttributes<M> | Values,\n options?: BuildOptions,\n ): M {\n return new this(values as Values, options);\n }\n\n /**\n * Builds several new instances in memory, same as calling {@link Model.build} for each record.\n *\n * @param this - The model class.\n * @param records - Attribute values per instance.\n * @param options - Build options.\n * @returns New instances.\n * @example\n * ```ts\n * const tags = Tag.bulkBuild([{ name: 'news' }, { name: 'sports' }]);\n * ```\n */\n static bulkBuild<M extends AnyModel>(\n this: ModelStatic<M>,\n records: readonly (CreationAttributes<M> | Values)[],\n options?: BuildOptions,\n ): M[] {\n return records.map((values) => new this(values as Values, options));\n }\n\n /**\n * Builds an instance and inserts it with `INSERT ... RETURNING`, running validation and the\n * create/save hooks. With `onConflict` (PostgreSQL extension) the insert may be skipped or turned\n * into an update, and `instance.wasInserted` tells which happened.\n *\n * @param this - The model class.\n * @param values - Attribute values.\n * @param options - Create options (`fields`, `hooks`, `validate`, `include`, `onConflict`, query options).\n * @returns Saved instance.\n * @throws ValidationError when validation fails.\n * @throws UniqueConstraintError when a unique constraint is violated.\n * @throws ForeignKeyConstraintError when a foreign key constraint is violated.\n * @throws DatabaseError for other database errors.\n * @example\n * ```ts\n * const user = await User.create({ email: 'ada@example.com' }, { transaction });\n * ```\n */\n static create<M extends AnyModel>(\n this: ModelStatic<M>,\n values?: CreationAttributes<M>,\n options: CreateOptions<Attributes<M>> = {},\n ): Promise<M> {\n return creator.create(this, values as Values | undefined, options as CreateOptions);\n }\n\n /**\n * Inserts many rows with one multi-row `INSERT ... RETURNING`. Runs `beforeBulkCreate` and\n * `afterBulkCreate` hooks; rows are not validated unless `validate: true`. `ignoreDuplicates`,\n * `updateOnDuplicate` and `onConflict` map to `ON CONFLICT`; `individualHooks` or `include`\n * insert row by row like Sequelize v6.\n *\n * @param this - The model class.\n * @param records - Attribute values per row.\n * @param options - Bulk create options.\n * @returns Instances with values returned by the database.\n * @throws ValidationError with `validate: true` when a row is invalid.\n * @throws UniqueConstraintError when a unique constraint is violated and no conflict handling is set.\n * @example\n * ```ts\n * const tags = await Tag.bulkCreate([{ name: 'news' }, { name: 'sports' }], { ignoreDuplicates: true });\n * ```\n * @see {@link Model.insert} for the PostgreSQL variant that returns only the rows actually written.\n */\n static bulkCreate<M extends AnyModel>(\n this: ModelStatic<M>,\n records: readonly CreationAttributes<M>[],\n options: BulkCreateOptions<Attributes<M>> = {},\n ): Promise<M[]> {\n return bulkCreator.bulkCreate(\n this,\n records as readonly Values[],\n options as BulkCreateOptions,\n );\n }\n\n /**\n * Inserts a row, or updates it when it conflicts with a unique key (`INSERT ... ON CONFLICT DO UPDATE`,\n * Sequelize v6 `upsert`). Runs the `beforeUpsert` and `afterUpsert` hooks.\n *\n * @param this - The model class.\n * @param values - Attribute values.\n * @param options - Upsert options (`conflictFields`, `fields`, `onConflict`, query options).\n * @returns `[instance, null]` like Sequelize v6, or `[instance, created]` with `onConflict`.\n * @throws ValidationError when validation fails.\n * @throws UniqueConstraintError when a unique constraint other than the conflict target is violated.\n * @example\n * ```ts\n * const [user] = await User.upsert({ email: 'ada@example.com', name: 'Ada' }, { conflictFields: ['email'] });\n * ```\n */\n static upsert<M extends AnyModel>(\n this: ModelStatic<M>,\n values: CreationAttributes<M>,\n options: UpsertOptions<Attributes<M>> = {},\n ): Promise<[M, boolean | null]> {\n return upserter.upsert(this, values as Values, options as UpsertOptions);\n }\n\n /**\n * Updates all rows matching `where` with one `UPDATE` and refreshes `updatedAt` unless `silent`.\n * Values are validated unless `validate: false`; bulk hooks run unless `hooks: false`.\n *\n * @param this - The model class.\n * @param values - New attribute values.\n * @param options - Update options; `where` is required.\n * @returns `[affectedCount]`, or `[affectedCount, rows]` with `returning: true`.\n * @throws ValidationError when the new values are invalid.\n * @example\n * ```ts\n * const [count] = await Post.update({ published: true }, { where: { userId: 1 } });\n * ```\n */\n static update<M extends AnyModel>(\n this: ModelStatic<M>,\n values: Partial<Attributes<M>>,\n options: UpdateOptions<Attributes<M>>,\n ): Promise<[affectedCount: number, affectedRows?: M[]]> {\n return updater.update(this, values as Values, options as UpdateOptions);\n }\n\n /**\n * Deletes rows matching `where` and returns the deleted instances (`DELETE ... RETURNING`, a\n * PostgreSQL extension). For paranoid models the rows are soft-deleted unless `force: true`.\n *\n * @param this - The model class.\n * @param options - Destroy options with `returning: true`.\n * @returns Deleted instances.\n * @example\n * ```ts\n * const removed = await Post.destroy({ where: { published: false }, returning: true });\n * ```\n */\n static destroy<M extends AnyModel>(\n this: ModelStatic<M>,\n options: DestroyOptions<Attributes<M>> & Readonly<{ returning: true }>,\n ): Promise<M[]>;\n\n /**\n * Deletes rows matching `where` (`truncate: true` empties the table instead). For paranoid models\n * the rows are soft-deleted (`deletedAt` is set) unless `force: true`. Runs bulk destroy hooks\n * unless `hooks: false`.\n *\n * @param this - The model class.\n * @param options - Destroy options.\n * @returns Number of deleted rows.\n */\n static destroy<M extends AnyModel>(\n this: ModelStatic<M>,\n options?: DestroyOptions<Attributes<M>>,\n ): Promise<number>;\n static destroy<M extends AnyModel>(\n this: ModelStatic<M>,\n options: DestroyOptions<Attributes<M>> = {},\n ): Promise<number | M[]> {\n return destroyer.destroy(this, options as DestroyOptions);\n }\n\n /**\n * Restores soft-deleted rows of a paranoid model by setting `deletedAt` back to `NULL`.\n *\n * @param this - The model class.\n * @param options - Rows to restore and hook options.\n * @returns Resolves when done.\n * @throws Error when the model is not paranoid.\n * @example\n * ```ts\n * await Post.restore({ where: { userId: 1 } });\n * ```\n */\n static restore<M extends AnyModel>(\n this: ModelStatic<M>,\n options: RestoreOptions<Attributes<M>> = {},\n ): Promise<void> {\n return destroyer.restore(this, options as RestoreOptions);\n }\n\n /**\n * Atomically increments numeric attributes of the rows matching `where` (`SET x = x + by`).\n *\n * @param this - The model class.\n * @param fields - Attribute name(s), or a map of attribute to amount.\n * @param options - Increment options (`where`, `by` default 1, `silent`, query options).\n * @returns `[affectedRows, affectedCount]`: the updated instances and their number.\n * @example\n * ```ts\n * await Post.increment('views', { by: 1, where: { id: 5 } });\n * ```\n */\n static increment<M extends AnyModel>(\n this: ModelStatic<M>,\n fields: AttributeAmounts<Attributes<M>>,\n options: IncrementOptions<Attributes<M>> = {},\n ): Promise<[affectedRows: M[], affectedCount: number]> {\n return incrementer.change(\n this,\n fields as AttributeAmounts<Values>,\n options as IncrementOptions,\n 1,\n );\n }\n\n /**\n * Atomically decrements numeric attributes of the rows matching `where` (`SET x = x - by`).\n *\n * @param this - The model class.\n * @param fields - Attribute name(s), or a map of attribute to amount.\n * @param options - Decrement options (`where`, `by` default 1, `silent`, query options).\n * @returns `[affectedRows, affectedCount]`: the updated instances and their number.\n * @example\n * ```ts\n * await Product.decrement({ stock: 3 }, { where: { id: 7 } });\n * ```\n */\n static decrement<M extends AnyModel>(\n this: ModelStatic<M>,\n fields: AttributeAmounts<Attributes<M>>,\n options: IncrementOptions<Attributes<M>> = {},\n ): Promise<[affectedRows: M[], affectedCount: number]> {\n return incrementer.change(\n this,\n fields as AttributeAmounts<Values>,\n options as IncrementOptions,\n -1,\n );\n }\n };\n};\n","import { ModelBase } from './model-base.ts';\nimport { ModelInstancePersistence } from './model-instance-persistence.ts';\nimport { ModelInstanceValues } from './model-instance-values.ts';\nimport { ModelAggregates } from './mixins/model-aggregates.ts';\nimport { ModelAssociations } from './mixins/model-associations.ts';\nimport { ModelFinders } from './mixins/model-finders.ts';\nimport { ModelHooks } from './mixins/model-hooks.ts';\nimport { ModelPostgres } from './mixins/model-postgres.ts';\nimport { ModelSchema } from './mixins/model-schema.ts';\nimport { ModelSchemaBinding } from './mixins/model-schema-binding.ts';\nimport { ModelScopes } from './mixins/model-scopes.ts';\nimport { ModelWriters } from './mixins/model-writers.ts';\nimport type { BuildOptions, Values } from './options.ts';\n\nexport type { NamedHookAdder } from './mixins/named-hooks.ts';\n\nconst ModelStatics = ModelPostgres(\n ModelWriters(\n ModelAggregates(\n ModelFinders(\n ModelSchemaBinding(ModelScopes(ModelHooks(ModelSchema(ModelAssociations(ModelBase))))),\n ),\n ),\n ),\n);\n\n// Instance methods use the class type parameters, which mixins cannot see: they are declared on the\n// merged interface below and copied onto the prototype at the end of this file.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- intentional merge.\nexport interface Model<\n TAttributes extends object = Values,\n // oxlint-disable-next-line no-unused-vars -- merged declarations need identical type parameters.\n TCreationAttributes extends object = TAttributes,\n>\n extends ModelInstanceValues<TAttributes>, ModelInstancePersistence<TAttributes> {}\n\n/**\n * Base class of models, API-compatible with Sequelize v6 `Model`.\n *\n * @typeParam TAttributes - Attribute types (usually `InferAttributes<M>`).\n * @typeParam TCreationAttributes - Attribute types accepted on creation (usually `InferCreationAttributes<M>`).\n * @example\n * ```ts\n * class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {\n * declare id: CreationOptional<number>;\n * declare email: string;\n * }\n * User.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: DataTypes.STRING }, { sequelize });\n * ```\n */\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- see the interface above.\nexport class Model<\n TAttributes extends object = Values,\n TCreationAttributes extends object = TAttributes,\n> extends ModelStatics {\n /** Phantom type of attributes; not set at runtime. */\n declare _attributes: TAttributes;\n\n /** Phantom type of creation attributes; not set at runtime. */\n declare _creationAttributes: TCreationAttributes;\n\n /** Current attribute values. */\n declare dataValues: TAttributes;\n\n /** Values as of the last load/save. */\n declare _previousDataValues: Partial<TAttributes>;\n\n /** True until the instance is saved or when built from a query result. */\n declare isNewRecord: boolean;\n\n /** Model class of the instance. */\n get _model(): typeof Model {\n return this.constructor as typeof Model;\n }\n\n /**\n * Builds an instance without saving it. Prefer `Model.build`.\n *\n * @param values - Attribute values.\n * @param options - Build options.\n */\n constructor(values: Partial<TCreationAttributes> | Values = {}, options: BuildOptions = {}) {\n super(values as Values, options);\n }\n}\n\nfor (const source of [ModelInstanceValues, ModelInstancePersistence]) {\n for (const key of Object.getOwnPropertyNames(source.prototype)) {\n if (key !== 'constructor') {\n Object.defineProperty(\n Model.prototype,\n key,\n Object.getOwnPropertyDescriptor(source.prototype, key) as PropertyDescriptor,\n );\n }\n }\n}\n","import type { QueryResult } from '../connection/connection-manager.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { RowMapper } from '../model/row-mapper.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { BindParameters, Replacements } from './raw-query.ts';\n\n/** Query types of `sequelize.query` (Sequelize v6 `QueryTypes`). */\nexport const QueryTypes = {\n /** Returns rows. */\n SELECT: 'SELECT',\n /** Returns `[rows, rowCount]`. */\n INSERT: 'INSERT',\n /** Returns `[rows, rowCount]`. */\n UPDATE: 'UPDATE',\n /** Returns `[undefined, null]` like v6 on PostgreSQL (the statement runs; its rows are not returned). */\n UPSERT: 'UPSERT',\n /** Returns the rows of the statement (`[]` without `RETURNING`). */\n DELETE: 'DELETE',\n /** Returns the number of affected rows. */\n BULKUPDATE: 'BULKUPDATE',\n /** Returns the number of affected rows. */\n BULKDELETE: 'BULKDELETE',\n /** Returns `[rows, result]` (default). */\n RAW: 'RAW',\n /** Returns `[rows, result]`. */\n SHOWTABLES: 'SHOWTABLES',\n /** Returns `[rows, result]`. */\n DESCRIBE: 'DESCRIBE',\n /** Returns `[rows, result]`. */\n VERSION: 'VERSION',\n /** Returns `[rows, result]`. */\n FOREIGNKEYS: 'FOREIGNKEYS',\n /** Returns `[rows, result]`. */\n SHOWINDEXES: 'SHOWINDEXES',\n} as const;\n\n/** One of {@link QueryTypes}. */\nexport type QueryType = (typeof QueryTypes)[keyof typeof QueryTypes];\n\n/**\n * Options of `sequelize.query`, in addition to the common query options such as `transaction` and `logging`.\n *\n * @example\n * ```ts\n * const rows = await sequelize.query('SELECT * FROM users WHERE id = :id', {\n * type: QueryTypes.SELECT,\n * replacements: { id: 1 },\n * model: User,\n * mapToModel: true,\n * });\n * ```\n */\nexport type QueryOptions = QueryOptionsBase &\n Readonly<{\n /** Shapes the result; default `RAW`. */\n type?: QueryType;\n /** Values for `?` / `:name` placeholders; bound as parameters. */\n replacements?: Replacements;\n /** Values for `$1` / `$name` placeholders. */\n bind?: BindParameters;\n /** Return only the first row (or `null`). */\n plain?: boolean;\n /** Build instances of this model from SELECT rows. */\n model?: ModelStatic<AnyModel>;\n /** Map column names to attribute names of `model`. */\n mapToModel?: boolean;\n /** Return plain rows even with `model`. */\n raw?: boolean;\n }>;\n\n/**\n * Shapes the result of `sequelize.query` like Sequelize v6: rows (optionally as model instances),\n * `[rows, rowCount]`, a row count or `[rows, result]` depending on the query type.\n */\nexport class QueryResultShaper {\n readonly #rows: RowMapper;\n\n /**\n * @param rows - Maps columns to attributes for `mapToModel`.\n */\n constructor(rows: RowMapper) {\n this.#rows = rows;\n }\n\n /**\n * Query type in effect: the `type` option, or `SELECT` with `model` / `plain`.\n *\n * @param options - Query options.\n * @returns Query type, or `undefined` for RAW.\n */\n type(options: QueryOptions): QueryType | undefined {\n return (\n options.type ??\n (options.model !== undefined || options.plain === true ? QueryTypes.SELECT : undefined)\n );\n }\n\n /**\n * Shapes a driver result according to the query options.\n *\n * @param result - Driver result.\n * @param options - Query options.\n * @returns Shaped result.\n */\n shape(result: QueryResult, options: QueryOptions): unknown {\n const rows = this.#shapeRows(result, options);\n switch (this.type(options)) {\n case QueryTypes.SELECT:\n return options.plain === true ? (rows[0] ?? null) : rows;\n case QueryTypes.INSERT:\n case QueryTypes.UPDATE:\n return [rows, result.rowCount];\n case QueryTypes.UPSERT:\n return [undefined, null];\n case QueryTypes.DELETE:\n return rows;\n case QueryTypes.BULKDELETE:\n case QueryTypes.BULKUPDATE:\n return result.rowCount;\n default:\n return options.plain === true ? (rows[0] ?? null) : [rows, result];\n }\n }\n\n #shapeRows(result: QueryResult, options: QueryOptions): readonly unknown[] {\n const model = options.model;\n if (model === undefined || options.raw === true) {\n return result.rows;\n }\n return result.rows.map((row) =>\n model.build(options.mapToModel === true ? this.#rows.parseModel(model, row) : row, {\n isNewRecord: false,\n raw: true,\n }),\n );\n }\n}\n","import type { AssociationOptions, ThroughOptions } from '../associations/types.ts';\nimport type { IndexOptions } from '../ddl/ddl-generator.ts';\nimport type { HookType } from '../hooks/hooks.ts';\nimport type { AttributeOptions } from '../model/attribute-options.ts';\nimport type { AnyModel, InitOptions, ModelStatic } from '../model/options.ts';\nimport type { ScopeDefinition, ScopeOptions } from '../model/scope-registry.ts';\nimport type { DecoratorTarget } from './decorator-signature.ts';\n\n/** Lazily resolved model class, so decorators can refer to classes defined later in the file. */\nexport type ModelGetter = () => ModelStatic<AnyModel>;\n\n/**\n * Table options of `@Table`: the `Model.init` options without the `sequelize` instance.\n *\n * @example\n * ```ts\n * const options: TableOptions = { tableName: 'users', schema: 'app', paranoid: true, timestamps: true };\n * ```\n */\nexport type TableOptions = Omit<InitOptions, 'sequelize'>;\n\n/** Named scopes given to `@Scopes`. */\nexport type ScopesInput = Readonly<Record<string, ScopeDefinition>>;\n\n/** Association collected from `@HasOne`, `@HasMany`, `@BelongsTo` or `@BelongsToMany`. */\nexport type AssociationSpec = Readonly<{\n kind: 'hasOne' | 'hasMany' | 'belongsTo' | 'belongsToMany';\n key: string;\n target: ModelGetter;\n options: AssociationOptions;\n through?: string | ModelGetter | ThroughOptions;\n}>;\n\n/** Index collected from `@Index` on an attribute. */\nexport type IndexSpec = Readonly<{ key: string; options: IndexOptions }>;\n\n/** Everything the decorators collected for one class. */\nexport type ModelMetadata = {\n table: TableOptions;\n defaultScope?: ScopeOptions | (() => ScopeOptions);\n scopes?: ScopesInput | (() => ScopesInput);\n columns: Record<string, Partial<AttributeOptions>>;\n timestamps: Partial<Record<'createdAt' | 'updatedAt' | 'deletedAt', string>>;\n foreignKeys: Record<string, ModelGetter>;\n indexes: IndexSpec[];\n associations: AssociationSpec[];\n hooks: { type: HookType; key: string }[];\n};\n\nconst empty = (): ModelMetadata => ({\n table: {},\n columns: {},\n timestamps: {},\n foreignKeys: {},\n indexes: [],\n associations: [],\n hooks: [],\n});\n\nconst symbolMetadata = (): symbol => (Symbol as unknown as { metadata: symbol }).metadata;\n\n/**\n * Metadata that decorators collect, kept outside the decorated classes (no `reflect-metadata`).\n * Decorated classes are looked up by the class itself (legacy decorators) or by their TC39\n * `Symbol.metadata` bag; base classes contribute first.\n *\n * @internal\n */\nexport class MetadataStore {\n readonly #entries = new WeakMap<object, ModelMetadata>();\n\n /**\n * @param target - What the running decorator decorates.\n * @returns The metadata bag of its class, created on first use.\n */\n of(target: DecoratorTarget): ModelMetadata {\n const found = this.#entries.get(target.owner) ?? empty();\n this.#entries.set(target.owner, found);\n return found;\n }\n\n /**\n * @param model - Decorated class.\n * @returns Metadata of the class merged with its base classes' (derived classes win).\n */\n collect(model: object): ModelMetadata {\n const chain: object[] = [];\n for (let link: object | null = model; link !== null; link = Object.getPrototypeOf(link)) {\n chain.unshift(link);\n }\n return chain.flatMap((link) => this.#bags(link)).reduce(merge, empty());\n }\n\n #bags(link: object): ModelMetadata[] {\n const bag = Object.hasOwn(link, symbolMetadata())\n ? (link as Record<symbol, object>)[symbolMetadata()]\n : undefined;\n return [this.#entries.get(link), bag === undefined ? undefined : this.#entries.get(bag)].filter(\n (entry): entry is ModelMetadata => entry !== undefined,\n );\n }\n}\n\nconst mergeColumns = (\n base: ModelMetadata['columns'],\n next: ModelMetadata['columns'],\n): ModelMetadata['columns'] =>\n Object.fromEntries(\n [...Object.keys(base), ...Object.keys(next)].map((key) => [\n key,\n { ...base[key], ...next[key] },\n ]),\n );\n\nconst merge = (base: ModelMetadata, next: ModelMetadata): ModelMetadata => ({\n table: { ...base.table, ...next.table },\n defaultScope: next.defaultScope ?? base.defaultScope,\n scopes: next.scopes ?? base.scopes,\n columns: mergeColumns(base.columns, next.columns),\n timestamps: { ...base.timestamps, ...next.timestamps },\n foreignKeys: { ...base.foreignKeys, ...next.foreignKeys },\n indexes: [...base.indexes, ...next.indexes],\n associations: [...base.associations, ...next.associations],\n hooks: [...base.hooks, ...next.hooks],\n});\n\n/** @internal Shared metadata store of all decorators. */\nexport const metadata = new MetadataStore();\n","import type { AssociationOptions, BelongsToManyOptions } from '../associations/types.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport { metadata, type AssociationSpec } from './model-metadata.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\nconst references = (target: Model, referenced: Model): boolean =>\n referenced === target || referenced.prototype instanceof target;\n\n/**\n * Applies the associations collected by decorators with the same `hasOne` / `hasMany` /\n * `belongsTo` / `belongsToMany` calls an application would write by hand.\n *\n * @internal\n */\nexport class AssociationApplier {\n /**\n * @param model - Model that owns the property the association was declared on.\n * @param spec - Collected association.\n */\n apply(model: Model, spec: AssociationSpec): void {\n const target = spec.target();\n const options = { as: spec.key, ...this.#keys(model, target, spec), ...spec.options };\n if (spec.kind === 'belongsToMany') {\n model.belongsToMany(target, {\n ...options,\n through: this.#through(spec),\n } as BelongsToManyOptions);\n } else {\n model[spec.kind](target, options as AssociationOptions);\n }\n }\n\n #through(spec: AssociationSpec): BelongsToManyOptions['through'] {\n const { through } = spec;\n return typeof through === 'function' ? through() : (through as never);\n }\n\n #keys(model: Model, target: Model, spec: AssociationSpec): AssociationOptions {\n switch (spec.kind) {\n case 'belongsTo':\n return this.#key('foreignKey', model, target);\n case 'belongsToMany':\n return this.#manyKeys(model, target, spec);\n default:\n return this.#key('foreignKey', target, model);\n }\n }\n\n #manyKeys(model: Model, target: Model, spec: AssociationSpec): Record<string, string> {\n const through = this.#through(spec);\n const junction = typeof through === 'object' && 'model' in through ? through.model : through;\n if (typeof junction !== 'function') {\n return {};\n }\n return {\n ...this.#key('foreignKey', junction as Model, model),\n ...this.#key('otherKey', junction as Model, target),\n };\n }\n\n #key(name: string, holder: Model, referenced: Model): Record<string, string> {\n const found = Object.entries(metadata.collect(holder).foreignKeys).find(([, getter]) =>\n references(getter(), referenced),\n );\n return found === undefined ? {} : { [name]: found[0] };\n }\n}\n","import type { HookFunction, HookType, HooksOption } from '../hooks/hooks.ts';\nimport type { ModelAttributes } from '../model/model-definition.ts';\nimport type { AnyModel, InitOptions, ModelStatic } from '../model/options.ts';\nimport type { RuntimeOwner } from '../model/runtime.ts';\nimport type { IndexOptions } from '../ddl/ddl-generator.ts';\nimport type { ModelMetadata } from './model-metadata.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\n/**\n * Turns the metadata collected for a class into the arguments of `Model.init`, so a decorated\n * model is initialized exactly like a hand-written `init` call.\n *\n * @internal\n */\nexport class InitArguments {\n /**\n * @param model - Decorated class.\n * @param meta - Metadata collected for it.\n * @returns Attributes for `Model.init`.\n * @throws Error when an attribute has no type.\n */\n attributes(model: Model, meta: ModelMetadata): ModelAttributes {\n for (const [key, column] of Object.entries(meta.columns)) {\n if (column.type === undefined) {\n throw new Error(`${model.name}.${key} has no type: use @Column(DataTypes.<TYPE>).`);\n }\n }\n return meta.columns as ModelAttributes;\n }\n\n /**\n * @param model - Decorated class.\n * @param meta - Metadata collected for it.\n * @param sequelize - Owning instance.\n * @returns Options for `Model.init`.\n */\n options(model: Model, meta: ModelMetadata, sequelize: RuntimeOwner): InitOptions {\n const { table, timestamps } = meta;\n const paranoid = timestamps.deletedAt === undefined ? {} : { paranoid: true };\n return {\n ...paranoid,\n ...table,\n ...timestamps,\n ...this.#indexes(meta),\n ...this.#hooks(model, meta),\n ...this.#scopes(meta),\n sequelize,\n };\n }\n\n #indexes({ table, indexes }: ModelMetadata): Pick<InitOptions, 'indexes'> {\n const named = new Map<string, IndexOptions>();\n const all: IndexOptions[] = [...(table.indexes ?? [])];\n for (const { key, options } of indexes) {\n const known = options.name === undefined ? undefined : named.get(options.name);\n if (known === undefined) {\n const created = { ...options, fields: [key] };\n all.push(created);\n if (options.name !== undefined) {\n named.set(options.name, created);\n }\n } else {\n (known.fields as string[]).push(key);\n }\n }\n return all.length === 0 ? {} : { indexes: all };\n }\n\n #hooks(model: Model, { table, hooks }: ModelMetadata): Pick<InitOptions, 'hooks'> {\n if (hooks.length === 0) {\n return {};\n }\n const merged: Partial<Record<HookType, HookFunction[]>> = {};\n for (const [type, value] of Object.entries(table.hooks ?? {})) {\n merged[type as HookType] = [value].flat() as HookFunction[];\n }\n for (const { type, key } of hooks) {\n const call = (...args: unknown[]): unknown =>\n (model as never as Record<string, (...a: unknown[]) => unknown>)[key]?.(...args);\n (merged[type] ??= []).push(call as HookFunction);\n }\n return { hooks: merged as HooksOption };\n }\n\n #scopes({ defaultScope, scopes }: ModelMetadata): Pick<InitOptions, 'defaultScope' | 'scopes'> {\n return {\n ...(defaultScope === undefined\n ? {}\n : { defaultScope: typeof defaultScope === 'function' ? defaultScope() : defaultScope }),\n ...(scopes === undefined ? {} : { scopes: typeof scopes === 'function' ? scopes() : scopes }),\n };\n }\n}\n","import type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { RuntimeOwner } from '../model/runtime.ts';\nimport { AssociationApplier } from './association-applier.ts';\nimport { InitArguments } from './init-arguments.ts';\nimport { metadata } from './model-metadata.ts';\n\ntype Model = ModelStatic<AnyModel>;\n\n/**\n * Registers decorated model classes: initializes every class with `Model.init`, then adds the\n * declared associations, so classes may refer to each other regardless of their order.\n *\n * @internal\n */\nexport class ModelDecorators {\n readonly #init = new InitArguments();\n readonly #associations = new AssociationApplier();\n\n /**\n * @param sequelize - Instance the models are registered with.\n * @param models - Decorated model classes.\n */\n register(sequelize: RuntimeOwner, models: readonly Model[]): void {\n for (const model of models) {\n const meta = metadata.collect(model);\n model.init(this.#init.attributes(model, meta), this.#init.options(model, meta, sequelize));\n }\n for (const model of models) {\n for (const spec of metadata.collect(model).associations) {\n this.#associations.apply(model, spec);\n }\n }\n }\n}\n","import type { PoolConfig } from 'pg';\nimport type {\n ConnectionConfig as ConnectionSettings,\n ReplicationMember,\n SequelizeOptions,\n} from './options.ts';\n\ntype ConstructorArgs =\n | readonly [SequelizeOptions?]\n | readonly [string, SequelizeOptions?]\n | readonly [string, string | null | undefined, (string | null | undefined)?, SequelizeOptions?];\n\n/**\n * Connection configuration of a `Sequelize` instance: normalizes the overloaded Sequelize v6\n * constructor arguments and derives the `pg` pool configurations (writer and read replicas).\n */\nexport class ConnectionConfig {\n /** Normalized constructor options. */\n readonly options: SequelizeOptions;\n\n /**\n * @param args - Arguments of the `Sequelize` constructor (URI, database / username / password, options).\n * @throws Error for a non-postgres URI or dialect.\n */\n constructor(args: ConstructorArgs) {\n this.options = ConnectionConfig.#parse(args);\n }\n\n /**\n * Connection settings exposed as `sequelize.config`.\n *\n * @returns Database, user name, password, host and port.\n */\n settings(): ConnectionSettings {\n return ConnectionConfig.#settings(this.options);\n }\n\n /**\n * Pool configurations of the writer and the readers (no readers without `replication`).\n *\n * @returns Writer and reader `pg` pool configurations.\n */\n replicationPoolConfigs(): Readonly<{ write: PoolConfig; read: readonly PoolConfig[] }> {\n const options = this.options;\n const replication = options.replication;\n if (replication === undefined) {\n return { write: ConnectionConfig.#poolConfig(options), read: [] };\n }\n const readers: readonly ReplicationMember[] = Array.isArray(replication.read)\n ? replication.read\n : [replication.read as ReplicationMember];\n return {\n write: ConnectionConfig.#poolConfig(ConnectionConfig.#withMember(options, replication.write)),\n read: readers.map((member) =>\n ConnectionConfig.#poolConfig(ConnectionConfig.#withMember(options, member)),\n ),\n };\n }\n\n static #parse(args: ConstructorArgs): SequelizeOptions {\n const options = ConnectionConfig.#merge(args);\n if (options.dialect !== undefined && options.dialect !== 'postgres') {\n throw new Error(\n `postgrelize supports only the postgres dialect, got ${String(options.dialect)}`,\n );\n }\n return options;\n }\n\n static #merge(args: ConstructorArgs): SequelizeOptions {\n const [first, second, third, fourth] = args;\n if (first === undefined || typeof first === 'object') {\n return first ?? {};\n }\n const secondOptions = typeof second === 'object' && second !== null ? second : {};\n return ConnectionConfig.#isUri(first)\n ? { ...secondOptions, ...ConnectionConfig.#fromUri(first) }\n : {\n ...(fourth ?? secondOptions),\n ...ConnectionConfig.#definedOnly({\n database: first,\n username: typeof second === 'string' ? second : undefined,\n password: typeof third === 'string' ? third : undefined,\n }),\n };\n }\n\n static #fromUri(uri: string): SequelizeOptions {\n const url = new URL(uri);\n if (!['postgres:', 'postgresql:'].includes(url.protocol)) {\n throw new Error(`postgrelize supports only postgres:// connection URIs, got ${url.protocol}`);\n }\n const database = decodeURIComponent(url.pathname.replace(/^\\//, ''));\n const sslmode = url.searchParams.get('sslmode');\n return {\n host: url.hostname,\n ...(url.port === '' ? {} : { port: Number(url.port) }),\n ...(database === '' ? {} : { database }),\n ...(url.username === '' ? {} : { username: decodeURIComponent(url.username) }),\n ...(url.password === '' ? {} : { password: decodeURIComponent(url.password) }),\n ...(sslmode === null || sslmode === 'disable' ? {} : { ssl: true }),\n };\n }\n\n static #isUri(value: string): boolean {\n return /^[a-z]+:\\/\\//i.test(value);\n }\n\n static #definedOnly<T extends object>(value: T): T {\n return Object.fromEntries(\n Object.entries(value).filter(([, item]) => item !== undefined && item !== null),\n ) as T;\n }\n\n static #settings(options: SequelizeOptions): ConnectionSettings {\n return {\n database: options.database,\n username: options.username,\n password: options.password,\n host: options.host ?? 'localhost',\n port: options.port ?? 5432,\n };\n }\n\n static #withMember(\n options: SequelizeOptions,\n member: ReplicationMember | undefined,\n ): SequelizeOptions {\n return member === undefined\n ? options\n : {\n ...options,\n ...Object.fromEntries(Object.entries(member).filter(([, value]) => value !== undefined)),\n };\n }\n\n // A UTC offset or an IANA zone name: it is passed as a libpq startup option, so no spaces.\n static #timezone(timezone: string): string {\n if (!/^(?:[+-]\\d{2}:\\d{2}|[A-Za-z][\\w+\\-/]*)$/.test(timezone)) {\n throw new Error(`Invalid timezone: ${timezone}`);\n }\n return timezone;\n }\n\n static #poolConfig(options: SequelizeOptions): PoolConfig {\n const config = ConnectionConfig.#settings(options);\n const timezone = ConnectionConfig.#timezone(options.timezone ?? '+00:00');\n return ConnectionConfig.#definedOnly({\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.username,\n password: config.password,\n ssl: options.ssl,\n ...ConnectionConfig.#poolLimits(options),\n ...options.dialectOptions,\n options: [`-c TimeZone=${timezone}`, options.dialectOptions?.options]\n .filter(Boolean)\n .join(' '),\n });\n }\n\n static #poolLimits(options: SequelizeOptions): PoolConfig {\n const pool = options.pool ?? {};\n return {\n max: pool.max ?? 5,\n idleTimeoutMillis: pool.idle ?? 10_000,\n connectionTimeoutMillis: pool.acquire ?? 60_000,\n maxUses: pool.maxUses,\n };\n }\n}\n","import { SqlExpression } from '../expressions/methods.ts';\nimport { SqlCompiler, type Chunks, type CompiledQuery } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\n\n/** Values substituted into raw SQL: `?` for arrays, `:name` for objects. */\nexport type Replacements = readonly unknown[] | Readonly<Record<string, unknown>>;\n\n/** Bind parameters for raw SQL: `$1` for arrays, `$name` for objects. */\nexport type BindParameters = readonly unknown[] | Readonly<Record<string, unknown>>;\n\nconst TOKEN =\n /'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\"|--[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/|\\$([A-Za-z_]\\w*)?\\$[\\s\\S]*?\\$\\1\\$|::|:([A-Za-z_]\\w*)|\\?(?![|&])|\\$([A-Za-z_]\\w*|\\d+)/g;\n\nconst noContext = new WhereCompiler({ resolve: () => undefined });\n\nconst compiler = new SqlCompiler();\n\ntype TokenContext = Readonly<{\n replacements: Replacements | undefined;\n bind: BindParameters | undefined;\n bindParams: ReadonlyMap<string, Readonly<{ param: unknown }>>;\n}>;\n\n/**\n * Converts raw SQL with Sequelize v6 `replacements` and `bind` into a parameterized query.\n * Replacement values are bound as parameters instead of being inlined; string literals,\n * quoted identifiers, comments, dollar-quoted strings and `::` casts are left untouched.\n *\n * @internal\n */\nexport class RawQuery {\n /**\n * Prepares raw SQL for execution.\n *\n * @param sql - SQL text with `?` / `:name` replacements and `$1` / `$name` bind parameters.\n * @param options - Replacements and bind parameters.\n * @returns Query text with `$n` placeholders and its values.\n * @throws Error for a missing replacement or bind parameter.\n */\n prepare(\n sql: string,\n options: Readonly<{ replacements?: Replacements; bind?: BindParameters }> = {},\n ): CompiledQuery {\n if (options.replacements === undefined && options.bind === undefined) {\n return { text: sql, values: [] };\n }\n const ctx: TokenContext = {\n replacements: options.replacements,\n bind: options.bind,\n bindParams: this.#bindChunks(options.bind),\n };\n const matches = [...sql.matchAll(TOKEN)];\n return compiler.finalize([\n ...this.#chunks(sql, matches, ctx),\n RawQuery.#tail(sql, matches.at(-1)),\n ]);\n }\n\n #chunks(sql: string, matches: readonly RegExpExecArray[], ctx: TokenContext): Chunks {\n return matches.flatMap((match, index): Chunks => {\n const previous = matches[index - 1];\n const previousEnd = previous === undefined ? 0 : previous.index + previous[0].length;\n const questionIndex = matches.slice(0, index).filter((item) => item[0] === '?').length;\n return [sql.slice(previousEnd, match.index), ...this.#tokenChunks(match, questionIndex, ctx)];\n });\n }\n\n static #tail(sql: string, last: RegExpExecArray | undefined): string {\n return last === undefined ? sql : sql.slice(last.index + last[0].length);\n }\n\n #valueChunks(value: unknown): Chunks {\n if (value instanceof SqlExpression) {\n const compiled = compiler.compileExpr(noContext.toExpr(value));\n if (compiled.values.length > 0) {\n throw new Error('Expressions with bound values are not supported in replacements');\n }\n return [compiled.text];\n }\n if (Array.isArray(value)) {\n return value.flatMap((item: unknown, index) =>\n index === 0 ? this.#valueChunks(item) : [', ', ...this.#valueChunks(item)],\n );\n }\n return [{ param: value }];\n }\n\n #lookup(source: Replacements | BindParameters, key: string | number, kind: string): unknown {\n const value = Array.isArray(source)\n ? source[Number(key)]\n : (source as Readonly<Record<string, unknown>>)[key];\n if (\n value === undefined &&\n !(Array.isArray(source) ? Number(key) < source.length : key in source)\n ) {\n throw new Error(`Missing ${kind} value for ${String(key)}`);\n }\n return value;\n }\n\n #tokenChunks(match: RegExpExecArray, questionIndex: number, ctx: TokenContext): Chunks {\n const [token, , named, bindName] = match;\n if (named !== undefined && ctx.replacements !== undefined && !Array.isArray(ctx.replacements)) {\n return this.#valueChunks(this.#lookup(ctx.replacements, named, 'replacement'));\n }\n if (token === '?' && Array.isArray(ctx.replacements)) {\n return this.#valueChunks(this.#lookup(ctx.replacements, questionIndex, 'replacement'));\n }\n if (bindName !== undefined && ctx.bind !== undefined) {\n const key = Array.isArray(ctx.bind) ? String(Number(bindName) - 1) : bindName;\n const chunk = ctx.bindParams.get(key);\n if (chunk === undefined) {\n throw new Error(`Missing bind parameter $${bindName}`);\n }\n return [chunk];\n }\n return [token];\n }\n\n #bindChunks(bind: BindParameters | undefined): ReadonlyMap<string, Readonly<{ param: unknown }>> {\n return new Map(\n bind === undefined\n ? []\n : Object.entries(bind).map(([key, value]) => [key, { param: value }] as const),\n );\n }\n}\n","import { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlAst, type ExprNode, type TableRef } from '../sql/ast.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst ast = new SqlAst();\n\nconst sqlLiteral = new SqlLiteral();\n\nconst sqlCompiler = new SqlCompiler();\n\nconst identity = new WhereCompiler({ resolve: (name) => ({ field: name }) });\n\n/**\n * Bulk data methods of `QueryInterface` (seeders). Values are bound as parameters; `where` objects\n * are keyed by column.\n *\n * @internal\n */\nexport class BulkData {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Inserts rows; missing values become `DEFAULT`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param records - Rows keyed by column name.\n * @param options - Query options.\n * @returns Number of inserted rows.\n */\n async bulkInsert(\n table: TableName,\n records: readonly Readonly<Record<string, unknown>>[],\n options: QueryOptionsBase,\n ): Promise<number> {\n if (records.length === 0) {\n return 0;\n }\n const columns = [...new Set(records.flatMap((record) => Object.keys(record)))];\n const target = this.#table(table);\n const rows = records.map((record) => columns.map((column) => this.#value(record[column])));\n const query = sqlCompiler.compile({ kind: 'insert', table: target, columns, rows });\n return (await this.#runner.execute(query, options)).rowCount;\n }\n\n /**\n * Updates rows matching `where`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param values - New column values.\n * @param where - Filter.\n * @param options - Query options.\n * @returns Number of updated rows.\n */\n async bulkUpdate(\n table: TableName,\n values: Readonly<Record<string, unknown>>,\n where: unknown,\n options: QueryOptionsBase,\n ): Promise<number> {\n const query = sqlCompiler.compile({\n kind: 'update',\n table: this.#table(table),\n set: Object.entries(values).map(([column, value]) => ({\n column,\n value: identity.toExpr(value),\n })),\n ...this.#where(where),\n });\n return (await this.#runner.execute(query, options)).rowCount;\n }\n\n /**\n * Deletes rows matching `where`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param where - Filter; empty deletes all rows.\n * @param options - Query options.\n * @returns Number of deleted rows.\n */\n async bulkDelete(table: TableName, where: unknown, options: QueryOptionsBase): Promise<number> {\n const query = sqlCompiler.compile({\n kind: 'delete',\n table: this.#table(table),\n ...this.#where(where),\n });\n return (await this.#runner.execute(query, options)).rowCount;\n }\n\n #table(table: TableName): TableRef {\n const { name, schema } = sqlLiteral.tableParts(table);\n return { name, ...(schema === undefined ? {} : { schema }) };\n }\n\n #value(value: unknown): ExprNode {\n return value === undefined ? ast.raw('DEFAULT') : identity.toExpr(value);\n }\n\n #where(where: unknown): Readonly<{ where?: ExprNode }> {\n return WhereCompiler.isEmpty(where) ? {} : { where: identity.compile(where) };\n }\n}\n","import type { DataTypeInput } from '../data-types/data-types.ts';\nimport { DdlGenerator, type ColumnDefinition } from '../ddl/ddl-generator.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport { ModelDefinition, type AttributeOptions } from '../model/model-definition.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst ddl = new DdlGenerator();\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Column DDL of `QueryInterface`: add, remove, change and rename. Names are quoted identifiers.\n *\n * @internal\n */\nexport class ColumnCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Adds a column and its enum type and comment.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param attribute - Column definition.\n * @param options - Query options.\n */\n async addColumn(\n table: TableName,\n column: string,\n attribute: DataTypeInput | AttributeOptions,\n options?: QueryOptionsBase,\n ): Promise<void> {\n const definition = this.#column(column, attribute);\n const enumSql = ddl.createEnumSql(table, definition);\n await this.#runner.runAll(\n [\n ...(enumSql === undefined ? [] : [enumSql]),\n `ALTER TABLE ${sqlLiteral.quoteTable(table)} ADD COLUMN ${ddl.columnSql(table, definition, { inlinePrimaryKey: true })}`,\n ...ddl.columnCommentSql(table, definition),\n ],\n options,\n );\n }\n\n /**\n * Removes a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param options - Query options.\n */\n async removeColumn(table: TableName, column: string, options?: QueryOptionsBase): Promise<void> {\n await this.#runner.run(\n `ALTER TABLE ${sqlLiteral.quoteTable(table)} DROP COLUMN ${SqlCompiler.quoteIdent(column)}`,\n options,\n );\n }\n\n /**\n * Changes type, nullability, default and comment of a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param attribute - New column definition.\n * @param options - Query options.\n */\n async changeColumn(\n table: TableName,\n column: string,\n attribute: DataTypeInput | AttributeOptions,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.runAll(ddl.changeColumnSql(table, this.#column(column, attribute)), options);\n }\n\n /**\n * Renames a column.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param before - Current column name.\n * @param after - New column name.\n * @param options - Query options.\n */\n async renameColumn(\n table: TableName,\n before: string,\n after: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(\n `ALTER TABLE ${sqlLiteral.quoteTable(table)} RENAME COLUMN ${SqlCompiler.quoteIdent(before)} TO ${SqlCompiler.quoteIdent(after)}`,\n options,\n );\n }\n\n #column(name: string, attribute: DataTypeInput | AttributeOptions): ColumnDefinition {\n return ddl.columnOf(ModelDefinition.attribute(name, attribute, false));\n }\n}\n","import { DdlGenerator } from '../ddl/ddl-generator.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst ddl = new DdlGenerator();\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Enum type DDL of `QueryInterface`. Lookups filter by schema; names are quoted identifiers.\n *\n * @internal\n */\nexport class EnumCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Drops an enum type.\n *\n * @param name - Enum type name.\n * @param options - Query options.\n */\n async dropEnum(name: string, options?: QueryOptionsBase): Promise<void> {\n await this.#runner.run(`DROP TYPE IF EXISTS ${SqlCompiler.quoteIdent(name)}`, options);\n }\n\n /**\n * Drops all enum types of the current schema.\n *\n * @param options - Query options.\n */\n async dropAllEnums(options?: QueryOptionsBase): Promise<void> {\n const rows = await this.#runner.run(\n \"SELECT t.typname FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'e' AND n.nspname = current_schema()\",\n options,\n );\n await this.#runner.runAll(\n rows.map(\n (row) => `DROP TYPE IF EXISTS ${SqlCompiler.quoteIdent(String(row['typname']))} CASCADE`,\n ),\n options,\n );\n }\n\n /**\n * Drops the enum types of table columns.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param fields - Enum column names.\n * @param options - Query options.\n */\n async dropEnumsOf(\n table: TableName,\n fields: readonly string[],\n options?: QueryOptionsBase,\n ): Promise<void> {\n const { schema } = sqlLiteral.tableParts(table);\n await this.#runner.runAll(\n fields.map((field) => {\n const name = SqlCompiler.quoteIdent(ddl.enumTypeName(table, field));\n return `DROP TYPE IF EXISTS ${schema === undefined ? name : `${SqlCompiler.quoteIdent(schema)}.${name}`}`;\n }),\n options,\n );\n }\n}\n","import {\n DdlGenerator,\n type ConstraintOptions,\n type IndexField,\n type IndexOptions,\n} from '../ddl/ddl-generator.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst ddl = new DdlGenerator();\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Index and constraint DDL of `QueryInterface`. Names are quoted identifiers.\n *\n * @internal\n */\nexport class IndexCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Creates an index.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param fieldsOrOptions - Indexed fields or index options.\n * @param options - Index options when fields are given separately.\n */\n async addIndex(\n table: TableName,\n fieldsOrOptions: readonly IndexField[] | IndexOptions,\n options: IndexOptions & QueryOptionsBase,\n ): Promise<void> {\n const index: IndexOptions = Array.isArray(fieldsOrOptions)\n ? { ...options, fields: fieldsOrOptions as readonly IndexField[] }\n : { ...(fieldsOrOptions as IndexOptions), ...options };\n await this.#runner.run(ddl.createIndexSql(table, index), options);\n }\n\n /**\n * Drops an index by name or by its fields (default name).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param nameOrFields - Index name or indexed fields.\n * @param options - `concurrently` and query options.\n */\n async removeIndex(\n table: TableName,\n nameOrFields: string | readonly IndexField[],\n options: QueryOptionsBase & Readonly<{ concurrently?: boolean }>,\n ): Promise<void> {\n const { schema } = sqlLiteral.tableParts(table);\n const name =\n typeof nameOrFields === 'string' ? nameOrFields : ddl.indexName(table, nameOrFields);\n const qualified =\n schema === undefined\n ? SqlCompiler.quoteIdent(name)\n : `${SqlCompiler.quoteIdent(schema)}.${SqlCompiler.quoteIdent(name)}`;\n await this.#runner.run(\n `DROP INDEX ${options.concurrently === true ? 'CONCURRENTLY ' : ''}IF EXISTS ${qualified}`,\n options,\n );\n }\n\n /**\n * Adds a constraint.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Constraint definition.\n */\n async addConstraint(\n table: TableName,\n options: ConstraintOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(ddl.addConstraintSql(table, options), options);\n }\n\n /**\n * Drops a constraint.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param options - Query options.\n */\n async removeConstraint(\n table: TableName,\n name: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(\n `ALTER TABLE ${sqlLiteral.quoteTable(table)} DROP CONSTRAINT ${SqlCompiler.quoteIdent(name)}`,\n options,\n );\n }\n\n /**\n * Validates a `NOT VALID` constraint.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param options - Query options.\n */\n async validateConstraint(\n table: TableName,\n name: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(ddl.validateConstraintSql(table, name), options);\n }\n}\n","import {\n PartitionDdl,\n type CreatePartitionOptions,\n type DetachPartitionOptions,\n} from '../ddl/partition-ddl.ts';\nimport type { PartitionBoundSpec } from '../ddl/partition-types.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst partitions = new PartitionDdl();\n\n/**\n * Declarative partitioning DDL of `QueryInterface`. Names are quoted, bound values are literals.\n *\n * @internal\n */\nexport class PartitionCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Runs `CREATE TABLE ... PARTITION OF`.\n *\n * @param parent - Partitioned table.\n * @param partition - New partition.\n * @param bound - Bounds.\n * @param options - Partition and query options.\n */\n async create(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options: CreatePartitionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(\n partitions.createPartitionSql(parent, partition, bound, options),\n options,\n );\n }\n\n /**\n * Runs `ALTER TABLE ... ATTACH PARTITION`.\n *\n * @param parent - Partitioned table.\n * @param partition - Existing table.\n * @param bound - Bounds.\n * @param options - Query options.\n */\n async attach(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(partitions.attachPartitionSql(parent, partition, bound), options);\n }\n\n /**\n * Runs `ALTER TABLE ... DETACH PARTITION`.\n *\n * @param parent - Partitioned table.\n * @param partition - Partition.\n * @param options - Detach and query options.\n */\n async detach(\n parent: TableName,\n partition: TableName,\n options: DetachPartitionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(partitions.detachPartitionSql(parent, partition, options), options);\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { WhereCompiler } from '../where/where.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst sqlLiteral = new SqlLiteral();\n\nconst identity = new WhereCompiler({ resolve: (field) => ({ field }) });\n\nconst COMMANDS: Readonly<Record<string, string>> = {\n all: 'ALL',\n select: 'SELECT',\n insert: 'INSERT',\n update: 'UPDATE',\n delete: 'DELETE',\n};\n\nconst KINDS: Readonly<Record<string, string>> = {\n permissive: 'PERMISSIVE',\n restrictive: 'RESTRICTIVE',\n};\n\nconst ROLE_KEYWORDS: Readonly<Record<string, string>> = {\n public: 'PUBLIC',\n current_user: 'CURRENT_USER',\n current_role: 'CURRENT_ROLE',\n session_user: 'SESSION_USER',\n};\n\n/** Condition of a policy: SQL text (trusted) or a where object (values rendered as literals). */\nexport type PolicyCondition = string | Readonly<Record<string | symbol, unknown>>;\n\n/**\n * Options of `enableRowLevelSecurity`.\n *\n * @example\n * ```ts\n * const options: EnableRowLevelSecurityOptions = { force: true };\n * await queryInterface.enableRowLevelSecurity('documents', options);\n * ```\n */\nexport type EnableRowLevelSecurityOptions = Readonly<{\n /** Also `FORCE ROW LEVEL SECURITY`: the table owner is subject to the policies too. */\n force?: boolean;\n}>;\n\n/**\n * Options of `disableRowLevelSecurity`.\n *\n * @example\n * ```ts\n * const options: DisableRowLevelSecurityOptions = { noForce: true };\n * await queryInterface.disableRowLevelSecurity('documents', options);\n * ```\n */\nexport type DisableRowLevelSecurityOptions = Readonly<{\n /** Also `NO FORCE ROW LEVEL SECURITY`. */\n noForce?: boolean;\n}>;\n\n/**\n * Options of `createPolicy`.\n *\n * @example\n * ```ts\n * const options: CreatePolicyOptions = {\n * command: 'select',\n * roles: ['app_user'],\n * using: \"tenant_id = current_setting('app.tenant_id')::int\",\n * };\n * await queryInterface.createPolicy('documents', 'tenant_isolation', options);\n * ```\n */\nexport type CreatePolicyOptions = Readonly<{\n /** Command the policy applies to; defaults to `'all'`. */\n command?: 'all' | 'select' | 'insert' | 'update' | 'delete';\n /** `'permissive'` (default) or `'restrictive'`. */\n kind?: 'permissive' | 'restrictive';\n /** Roles the policy applies to: role names, or `'public'`, `'current_user'`, `'current_role'`, `'session_user'`. */\n roles?: readonly string[];\n /** `USING (...)`: which existing rows are visible. SQL text is trusted; a where object is compiled with literals. */\n using?: PolicyCondition;\n /** `WITH CHECK (...)`: which new rows may be written. Same forms as `using`. */\n withCheck?: PolicyCondition;\n}>;\n\n/**\n * Options of `alterPolicy`.\n *\n * @example\n * ```ts\n * const options: AlterPolicyOptions = { roles: ['app_user', 'app_admin'], rename: 'tenant_rows' };\n * await queryInterface.alterPolicy('documents', 'tenant_isolation', options);\n * ```\n */\nexport type AlterPolicyOptions = Readonly<\n Pick<CreatePolicyOptions, 'roles' | 'using' | 'withCheck'> & {\n /** New policy name (applied after the other changes). */\n rename?: string;\n }\n>;\n\n/**\n * Options of `dropPolicy`.\n *\n * @example\n * ```ts\n * const options: DropPolicyOptions = { ifExists: true };\n * await queryInterface.dropPolicy('documents', 'tenant_isolation', options);\n * ```\n */\nexport type DropPolicyOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** Also drops objects that depend on the policy. */\n cascade?: boolean;\n}>;\n\nconst lookup = (map: Readonly<Record<string, string>>, key: string, kind: string): string => {\n const value =\n typeof key === 'string' && Object.hasOwn(map, key.toLowerCase())\n ? map[key.toLowerCase()]\n : undefined;\n if (value === undefined) {\n throw new Error(`Invalid policy ${kind}: ${String(key)}`);\n }\n return value;\n};\n\n/**\n * Row-level security DDL: `ENABLE` / `DISABLE ROW LEVEL SECURITY` and `CREATE` / `ALTER` / `DROP\n * POLICY`. Names and roles are quoted; commands and kinds are allowlisted; string conditions are\n * trusted SQL (ADR-025).\n *\n * @internal\n */\nexport class PolicyDdl {\n /**\n * `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` statement.\n *\n * @param table - Table.\n * @param options - Statement options.\n * @returns Statement.\n */\n enableSql(table: TableName, options: EnableRowLevelSecurityOptions): string {\n return `ALTER TABLE ${sqlLiteral.quoteTable(table)} ENABLE ROW LEVEL SECURITY${options.force === true ? ', FORCE ROW LEVEL SECURITY' : ''}`;\n }\n\n /**\n * `ALTER TABLE ... DISABLE ROW LEVEL SECURITY` statement.\n *\n * @param table - Table.\n * @param options - Statement options.\n * @returns Statement.\n */\n disableSql(table: TableName, options: DisableRowLevelSecurityOptions): string {\n return `ALTER TABLE ${sqlLiteral.quoteTable(table)} DISABLE ROW LEVEL SECURITY${options.noForce === true ? ', NO FORCE ROW LEVEL SECURITY' : ''}`;\n }\n\n /**\n * `CREATE POLICY` statement.\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Policy options.\n * @returns Statement.\n * @throws Error for an unknown command or kind.\n */\n createSql(table: TableName, name: string, options: CreatePolicyOptions): string {\n return [\n `CREATE POLICY ${SqlCompiler.quoteIdent(name)} ON ${sqlLiteral.quoteTable(table)}`,\n options.kind === undefined ? '' : ` AS ${lookup(KINDS, options.kind, 'kind')}`,\n options.command === undefined ? '' : ` FOR ${lookup(COMMANDS, options.command, 'command')}`,\n this.#tail(options),\n ].join('');\n }\n\n /**\n * `ALTER POLICY` statements (the change, then the rename).\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Changes.\n * @returns Statements.\n * @throws Error without any change.\n */\n alterSql(table: TableName, name: string, options: AlterPolicyOptions): readonly string[] {\n const on = `${SqlCompiler.quoteIdent(name)} ON ${sqlLiteral.quoteTable(table)}`;\n const change = this.#tail(options);\n const statements = [\n ...(change === '' ? [] : [`ALTER POLICY ${on}${change}`]),\n ...(options.rename === undefined\n ? []\n : [`ALTER POLICY ${on} RENAME TO ${SqlCompiler.quoteIdent(options.rename)}`]),\n ];\n if (statements.length === 0) {\n throw new Error('alterPolicy requires at least one option');\n }\n return statements;\n }\n\n /**\n * `DROP POLICY` statement.\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Statement options.\n * @returns Statement.\n */\n dropSql(table: TableName, name: string, options: DropPolicyOptions): string {\n return `DROP POLICY ${options.ifExists === true ? 'IF EXISTS ' : ''}${SqlCompiler.quoteIdent(name)} ON ${sqlLiteral.quoteTable(table)}${options.cascade === true ? ' CASCADE' : ''}`;\n }\n\n #tail(options: Pick<CreatePolicyOptions, 'roles' | 'using' | 'withCheck'>): string {\n return [\n this.#roles(options.roles),\n options.using === undefined ? '' : ` USING (${this.#condition(options.using)})`,\n options.withCheck === undefined ? '' : ` WITH CHECK (${this.#condition(options.withCheck)})`,\n ].join('');\n }\n\n #roles(roles: readonly string[] | undefined): string {\n if (roles === undefined) {\n return '';\n }\n if (roles.length === 0) {\n throw new Error('Policy roles must not be empty');\n }\n const names = roles.map(\n (role) => ROLE_KEYWORDS[role.toLowerCase()] ?? SqlCompiler.quoteIdent(role),\n );\n return ` TO ${names.join(', ')}`;\n }\n\n #condition(condition: PolicyCondition): string {\n if (typeof condition === 'string') {\n if (condition.trim() === '') {\n throw new Error('A policy condition must not be empty');\n }\n return condition;\n }\n return sqlLiteral.inlineExpr(identity.compile(condition));\n }\n}\n","import {\n PolicyDdl,\n type AlterPolicyOptions,\n type CreatePolicyOptions,\n type DisableRowLevelSecurityOptions,\n type DropPolicyOptions,\n type EnableRowLevelSecurityOptions,\n} from '../ddl/policy-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst policies = new PolicyDdl();\n\n/**\n * Row-level security DDL of `QueryInterface`. Names are quoted; string conditions are trusted SQL.\n *\n * @internal\n */\nexport class PolicyCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Runs `ENABLE ROW LEVEL SECURITY`.\n *\n * @param table - Table.\n * @param options - Statement and query options.\n */\n async enable(\n table: TableName,\n options: EnableRowLevelSecurityOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(policies.enableSql(table, options), options);\n }\n\n /**\n * Runs `DISABLE ROW LEVEL SECURITY`.\n *\n * @param table - Table.\n * @param options - Statement and query options.\n */\n async disable(\n table: TableName,\n options: DisableRowLevelSecurityOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(policies.disableSql(table, options), options);\n }\n\n /**\n * Runs `CREATE POLICY`.\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Policy and query options.\n */\n async create(\n table: TableName,\n name: string,\n options: CreatePolicyOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(policies.createSql(table, name, options), options);\n }\n\n /**\n * Runs `ALTER POLICY`.\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Changes and query options.\n */\n async alter(\n table: TableName,\n name: string,\n options: AlterPolicyOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.runAll(policies.alterSql(table, name, options), options);\n }\n\n /**\n * Runs `DROP POLICY`.\n *\n * @param table - Table.\n * @param name - Policy name.\n * @param options - Statement and query options.\n */\n async drop(\n table: TableName,\n name: string,\n options: DropPolicyOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(policies.dropSql(table, name, options), options);\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { SqlLiteral } from './sql-literal.ts';\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Options of `createExtension`.\n *\n * @example\n * ```ts\n * const options: CreateExtensionOptions = { ifNotExists: true, schema: 'public' };\n * await queryInterface.createExtension('pg_trgm', options);\n * ```\n */\nexport type CreateExtensionOptions = Readonly<{\n /** Adds `IF NOT EXISTS`. */\n ifNotExists?: boolean;\n /** Schema that receives the extension objects. */\n schema?: string;\n /** Extension version to install. */\n version?: string;\n /** Also installs the extensions it depends on. */\n cascade?: boolean;\n}>;\n\n/**\n * Options of `dropExtension`.\n *\n * @example\n * ```ts\n * const options: DropExtensionOptions = { ifExists: true, cascade: true };\n * await queryInterface.dropExtension('pg_trgm', options);\n * ```\n */\nexport type DropExtensionOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** Also drops objects that depend on the extension. */\n cascade?: boolean;\n}>;\n\n/**\n * `CREATE EXTENSION` and `DROP EXTENSION` statements.\n *\n * @internal\n */\nexport class ExtensionDdl {\n /**\n * `CREATE EXTENSION` statement.\n *\n * @param name - Extension name.\n * @param options - Statement options.\n * @returns Statement.\n */\n createSql(name: string, options: CreateExtensionOptions): string {\n return [\n `CREATE EXTENSION ${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}${SqlCompiler.quoteIdent(name)}`,\n options.schema === undefined ? '' : ` SCHEMA ${SqlCompiler.quoteIdent(options.schema)}`,\n options.version === undefined ? '' : ` VERSION ${sqlLiteral.escape(options.version)}`,\n options.cascade === true ? ' CASCADE' : '',\n ].join('');\n }\n\n /**\n * `DROP EXTENSION` statement.\n *\n * @param name - Extension name.\n * @param options - Statement options.\n * @returns Statement.\n */\n dropSql(name: string, options: DropExtensionOptions): string {\n return `DROP EXTENSION ${options.ifExists === true ? 'IF EXISTS ' : ''}${SqlCompiler.quoteIdent(name)}${options.cascade === true ? ' CASCADE' : ''}`;\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { DdlGuards } from './ddl-guards.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new DdlGuards();\n\nconst sqlLiteral = new SqlLiteral();\n\nconst DATA_TYPES: ReadonlySet<string> = new Set(['smallint', 'integer', 'bigint']);\n\n/** Whole number accepted in sequence options. */\nexport type SequenceNumber = number | bigint;\n\n/** Column that owns a sequence (the sequence is dropped with the column). */\nexport type SequenceOwner = Readonly<{\n /** Owning table. */\n table: TableName;\n /** Owning column. */\n column: string;\n}>;\n\n/**\n * Options of `createSequence`.\n *\n * @example\n * ```ts\n * const options: CreateSequenceOptions = { dataType: 'bigint', start: 1000, cache: 10 };\n * await queryInterface.createSequence('invoice_number', options);\n * ```\n */\nexport type CreateSequenceOptions = Readonly<{\n /** `AS smallint | integer | bigint`. */\n dataType?: 'smallint' | 'integer' | 'bigint';\n /** `START WITH`. */\n start?: SequenceNumber;\n /** `INCREMENT BY`. */\n increment?: SequenceNumber;\n /** `MINVALUE`; `false` renders `NO MINVALUE`. */\n minValue?: SequenceNumber | false;\n /** `MAXVALUE`; `false` renders `NO MAXVALUE`. */\n maxValue?: SequenceNumber | false;\n /** `CACHE`. */\n cache?: SequenceNumber;\n /** `CYCLE` / `NO CYCLE`. */\n cycle?: boolean;\n /** `OWNED BY table.column`; `null` renders `OWNED BY NONE`. */\n ownedBy?: SequenceOwner | null;\n /** Adds `IF NOT EXISTS`. */\n ifNotExists?: boolean;\n}>;\n\n/**\n * Options of `alterSequence`.\n *\n * @example\n * ```ts\n * const options: AlterSequenceOptions = { restartWith: 1, cycle: true };\n * await queryInterface.alterSequence('invoice_number', options);\n * ```\n */\nexport type AlterSequenceOptions = Omit<\n CreateSequenceOptions,\n 'dataType' | 'start' | 'ifNotExists'\n> &\n Readonly<{\n /** `RESTART WITH n`; `true` renders a bare `RESTART` (back to the start value). */\n restartWith?: SequenceNumber | true;\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n }>;\n\n/**\n * Options of `dropSequence`.\n *\n * @example\n * ```ts\n * const options: DropSequenceOptions = { ifExists: true };\n * await queryInterface.dropSequence('invoice_number', options);\n * ```\n */\nexport type DropSequenceOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** Also drops objects that depend on the sequence. */\n cascade?: boolean;\n}>;\n\n/**\n * `CREATE`, `ALTER` and `DROP SEQUENCE` statements. Numbers must be whole; names are quoted.\n *\n * @internal\n */\nexport class SequenceDdl {\n /**\n * `CREATE SEQUENCE` statement.\n *\n * @param name - Sequence name.\n * @param options - Sequence options.\n * @returns Statement.\n * @throws Error for an unknown data type or a non-integer number.\n */\n createSql(name: TableName, options: CreateSequenceOptions): string {\n const type = options.dataType;\n if (type !== undefined && !DATA_TYPES.has(type)) {\n throw new Error(`Invalid sequence data type: ${String(type)}`);\n }\n return [\n `CREATE SEQUENCE ${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}${sqlLiteral.quoteTable(name)}`,\n type === undefined ? '' : ` AS ${type}`,\n this.#numbers(options),\n options.start === undefined ? '' : ` START WITH ${guards.integer(options.start, 'start')}`,\n this.#tail(options),\n ].join('');\n }\n\n /**\n * `ALTER SEQUENCE` statement.\n *\n * @param name - Sequence name.\n * @param options - Properties to change.\n * @returns Statement.\n * @throws Error without any property or with a non-integer number.\n */\n alterSql(name: TableName, options: AlterSequenceOptions): string {\n const restart = options.restartWith;\n const parts = [\n this.#numbers(options),\n restart === undefined\n ? ''\n : restart === true\n ? ' RESTART'\n : ` RESTART WITH ${guards.integer(restart, 'restartWith')}`,\n this.#tail(options),\n ].join('');\n if (parts === '') {\n throw new Error('alterSequence requires at least one option');\n }\n return `ALTER SEQUENCE ${options.ifExists === true ? 'IF EXISTS ' : ''}${sqlLiteral.quoteTable(name)}${parts}`;\n }\n\n /**\n * `DROP SEQUENCE` statement.\n *\n * @param name - Sequence name.\n * @param options - Statement options.\n * @returns Statement.\n */\n dropSql(name: TableName, options: DropSequenceOptions): string {\n return `DROP SEQUENCE ${options.ifExists === true ? 'IF EXISTS ' : ''}${sqlLiteral.quoteTable(name)}${options.cascade === true ? ' CASCADE' : ''}`;\n }\n\n #numbers(options: AlterSequenceOptions | CreateSequenceOptions): string {\n return [\n options.increment === undefined\n ? ''\n : ` INCREMENT BY ${guards.integer(options.increment, 'increment')}`,\n this.#bound('MINVALUE', options.minValue),\n this.#bound('MAXVALUE', options.maxValue),\n ].join('');\n }\n\n #bound(keyword: string, value: SequenceNumber | false | undefined): string {\n if (value === undefined) {\n return '';\n }\n return value === false\n ? ` NO ${keyword}`\n : ` ${keyword} ${guards.integer(value, keyword.toLowerCase())}`;\n }\n\n #tail(options: AlterSequenceOptions | CreateSequenceOptions): string {\n const owner = options.ownedBy;\n return [\n options.cache === undefined ? '' : ` CACHE ${guards.integer(options.cache, 'cache')}`,\n options.cycle === undefined ? '' : options.cycle ? ' CYCLE' : ' NO CYCLE',\n owner === undefined\n ? ''\n : owner === null\n ? ' OWNED BY NONE'\n : ` OWNED BY ${sqlLiteral.quoteTable(owner.table)}.${SqlCompiler.quoteIdent(owner.column)}`,\n ].join('');\n }\n}\n","import {\n ExtensionDdl,\n type CreateExtensionOptions,\n type DropExtensionOptions,\n} from '../ddl/extension-ddl.ts';\nimport {\n SequenceDdl,\n type AlterSequenceOptions,\n type CreateSequenceOptions,\n type DropSequenceOptions,\n type SequenceNumber,\n} from '../ddl/sequence-ddl.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst extensions = new ExtensionDdl();\n\nconst sequences = new SequenceDdl();\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Extension and sequence DDL of `QueryInterface`. Names are quoted identifiers; sequence numbers\n * are validated integers; `nextval` / `setval` bind everything.\n *\n * @internal\n */\nexport class ObjectCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Runs `CREATE EXTENSION`.\n *\n * @param name - Extension name.\n * @param options - Statement and query options.\n */\n async createExtension(\n name: string,\n options: CreateExtensionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(extensions.createSql(name, options), options);\n }\n\n /**\n * Runs `DROP EXTENSION`.\n *\n * @param name - Extension name.\n * @param options - Statement and query options.\n */\n async dropExtension(\n name: string,\n options: DropExtensionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(extensions.dropSql(name, options), options);\n }\n\n /**\n * Runs `CREATE SEQUENCE`.\n *\n * @param name - Sequence name.\n * @param options - Sequence and query options.\n */\n async createSequence(\n name: TableName,\n options: CreateSequenceOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(sequences.createSql(name, options), options);\n }\n\n /**\n * Runs `ALTER SEQUENCE`.\n *\n * @param name - Sequence name.\n * @param options - Properties to change and query options.\n */\n async alterSequence(\n name: TableName,\n options: AlterSequenceOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(sequences.alterSql(name, options), options);\n }\n\n /**\n * Runs `DROP SEQUENCE`.\n *\n * @param name - Sequence name.\n * @param options - Statement and query options.\n */\n async dropSequence(\n name: TableName,\n options: DropSequenceOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(sequences.dropSql(name, options), options);\n }\n\n /**\n * Advances a sequence and returns the new value.\n *\n * @param name - Sequence name.\n * @param options - Query options.\n * @returns Value as text (bigint safe).\n */\n async nextval(name: TableName, options: QueryOptionsBase): Promise<string> {\n const result = await this.#runner.execute(\n { text: 'SELECT nextval($1::regclass) AS value', values: [sqlLiteral.quoteTable(name)] },\n options,\n );\n return String(result.rows[0]?.['value']);\n }\n\n /**\n * Sets the current value of a sequence.\n *\n * @param name - Sequence name.\n * @param value - New value.\n * @param isCalled - `false` makes the next `nextval` return `value` itself.\n * @param options - Query options.\n * @returns The value set, as text.\n */\n async setval(\n name: TableName,\n value: SequenceNumber,\n isCalled: boolean,\n options: QueryOptionsBase,\n ): Promise<string> {\n const result = await this.#runner.execute(\n {\n text: 'SELECT setval($1::regclass, $2::bigint, $3::boolean) AS value',\n values: [sqlLiteral.quoteTable(name), value.toString(), isCalled],\n },\n options,\n );\n return String(result.rows[0]?.['value']);\n }\n}\n","import type { QueryResult } from '../connection/connection-manager.ts';\nimport { runtimeKey, type QueryOptionsBase, type RuntimeOwner } from '../model/runtime.ts';\nimport type { CompiledQuery } from '../sql/compile.ts';\n\n/** Result rows of a statement. */\nexport type StatementRows = readonly Readonly<Record<string, unknown>>[];\n\n/**\n * Runs schema statements through the runtime of a `Sequelize` instance, one after another.\n *\n * @internal\n */\nexport class StatementRunner {\n readonly #owner: RuntimeOwner;\n\n /**\n * @param owner - Owning `Sequelize` instance.\n */\n constructor(owner: RuntimeOwner) {\n this.#owner = owner;\n }\n\n /**\n * Runs a compiled query.\n *\n * @param query - Compiled query.\n * @param options - Query options.\n * @returns Query result.\n */\n async execute(query: CompiledQuery, options: QueryOptionsBase): Promise<QueryResult> {\n return await this.#owner[runtimeKey].execute(query, options);\n }\n\n /**\n * Runs one statement without parameters.\n *\n * @param sql - SQL statement.\n * @param options - Query options.\n * @returns Result rows.\n */\n async run(sql: string, options: QueryOptionsBase = {}): Promise<StatementRows> {\n const result = await this.execute({ text: sql, values: [] }, options);\n return result.rows;\n }\n\n /**\n * Runs statements in order, each after the previous one finished.\n *\n * @param statements - SQL statements.\n * @param options - Query options.\n */\n async runAll(statements: readonly string[], options: QueryOptionsBase = {}): Promise<void> {\n await statements.reduce<Promise<unknown>>(\n (previous, sql) => previous.then(() => this.run(sql, options)),\n Promise.resolve(),\n );\n }\n}\n","import { DdlGenerator } from '../ddl/ddl-generator.ts';\nimport { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport { ModelDefinition, type ModelAttributes } from '../model/model-definition.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { SqlCompiler } from '../sql/compile.ts';\nimport type { CreateTableOptions, DropTableOptions } from './query-interface-types.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst ddl = new DdlGenerator();\n\nconst sqlLiteral = new SqlLiteral();\n\n/**\n * Schema and table DDL of `QueryInterface`. Names are quoted identifiers.\n *\n * @internal\n */\nexport class TableCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * `CREATE SCHEMA IF NOT EXISTS`.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n */\n async createSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.#runner.run(\n `CREATE SCHEMA IF NOT EXISTS ${SqlCompiler.quoteIdent(schema)}`,\n options,\n );\n }\n\n /**\n * `DROP SCHEMA IF EXISTS ... CASCADE`.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n */\n async dropSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.#runner.run(\n `DROP SCHEMA IF EXISTS ${SqlCompiler.quoteIdent(schema)} CASCADE`,\n options,\n );\n }\n\n /**\n * Creates a table and its enum types.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param attributes - Column definitions keyed by column name.\n * @param options - Comment and query options.\n */\n async createTable(\n table: TableName,\n attributes: ModelAttributes,\n options: CreateTableOptions,\n ): Promise<void> {\n const columns = Object.entries(attributes).map(([name, attribute]) =>\n ddl.columnOf(ModelDefinition.attribute(name, attribute, false)),\n );\n const { comment, unlogged, temporary, partitionBy } = options;\n const persistence = {\n ...(comment === undefined ? {} : { comment }),\n ...(unlogged === undefined ? {} : { unlogged }),\n ...(temporary === undefined ? {} : { temporary }),\n ...(partitionBy === undefined ? {} : { partitionBy }),\n };\n await this.#runner.runAll(ddl.createTableSql(table, columns, persistence), options);\n }\n\n /**\n * `DROP TABLE IF EXISTS`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `cascade` and query options.\n */\n async dropTable(table: TableName, options: DropTableOptions): Promise<void> {\n await this.#runner.run(\n `DROP TABLE IF EXISTS ${sqlLiteral.quoteTable(table)}${options.cascade === true ? ' CASCADE' : ''}`,\n options,\n );\n }\n\n /**\n * Drops tables of the current schema with `CASCADE`, except the skipped ones.\n *\n * @param tables - Table names.\n * @param options - `skip`: table names to keep.\n */\n async dropTables(\n tables: readonly string[],\n options: QueryOptionsBase & Readonly<{ skip?: readonly string[] }>,\n ): Promise<void> {\n await this.#runner.runAll(\n tables\n .filter((name) => !(options.skip ?? []).includes(name))\n .map((name) => `DROP TABLE IF EXISTS ${SqlCompiler.quoteIdent(name)} CASCADE`),\n options,\n );\n }\n\n /**\n * Renames a table.\n *\n * @param before - Current table.\n * @param after - New table name.\n * @param options - Query options.\n */\n async renameTable(\n before: TableName,\n after: TableName,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(\n `ALTER TABLE ${sqlLiteral.quoteTable(before)} RENAME TO ${SqlCompiler.quoteIdent(sqlLiteral.tableParts(after).name)}`,\n options,\n );\n }\n}\n","import type { ColumnDescription } from './query-interface-types.ts';\nimport type { StatementRows } from './statement-runner.ts';\n\n/**\n * Converts `describeTable` catalog rows into Sequelize v6 column descriptions.\n *\n * @internal\n */\nexport class ColumnDescriber {\n /**\n * Column descriptions keyed by column name.\n *\n * @param rows - Rows of the `describeTable` query.\n * @returns Column descriptions.\n */\n describe(rows: StatementRows): Record<string, ColumnDescription> {\n return Object.fromEntries(rows.map((row) => [String(row['Field']), this.#column(row)]));\n }\n\n #column(row: Readonly<Record<string, unknown>>): ColumnDescription {\n const type = String(row['Type']).toUpperCase();\n return {\n type,\n allowNull: row['Null'] === 'YES',\n defaultValue: this.#cleanDefault(type, row['Default']),\n comment: (row['Comment'] as string | null) ?? null,\n special: this.#parseArray(row['special']),\n primaryKey: row['Constraint'] === 'PRIMARY KEY',\n };\n }\n\n #parseArray(value: unknown): readonly string[] {\n return Array.isArray(value)\n ? value.map(String)\n : typeof value === 'string' && value.startsWith('{')\n ? value\n .slice(1, -1)\n .split(',')\n .filter((item) => item !== '')\n .map((item) => item.replace(/^\"(.*)\"$/, '$1'))\n : [];\n }\n\n #cleanDefault(type: string, value: unknown): unknown {\n if (type === 'BOOLEAN') {\n return value === 'true' ? true : value === 'false' ? false : null;\n }\n if (typeof value !== 'string') {\n return value;\n }\n const literal = /^'((?:[^']|'')*)'(?:::[\\w .\"[\\]]+)*$/.exec(value);\n if (literal !== null) {\n return (literal[1] ?? '').replaceAll(\"''\", \"'\");\n }\n const unquoted = value.replaceAll(\"'\", '');\n const [head, tail] = unquoted.split('::');\n return tail !== undefined && tail.toLowerCase() !== 'regclass)' ? head : unquoted;\n }\n}\n","import { SqlLiteral, type TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport { ColumnDescriber } from './column-describer.ts';\nimport type { ColumnDescription, ForeignKeyReference } from './query-interface-types.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst sqlLiteral = new SqlLiteral();\n\nconst columnDescriber = new ColumnDescriber();\n\n/**\n * Catalog lookups of `QueryInterface`: schemas, tables, columns and foreign keys. Every lookup\n * filters by schema (the given one or `current_schema()`); values are escaped literals.\n *\n * @internal\n */\nexport class TableIntrospector {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Lists user schemas.\n *\n * @param options - Query options.\n * @returns Schema names.\n */\n async showAllSchemas(options?: QueryOptionsBase): Promise<string[]> {\n const rows = await this.#runner.run(\n \"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name <> 'public' AND schema_name !~ E'^pg_' ORDER BY schema_name\",\n options,\n );\n return rows.map((row) => String(row['schema_name']));\n }\n\n /**\n * Checks whether a table exists.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns True when the table exists.\n */\n async tableExists(table: TableName, options?: QueryOptionsBase): Promise<boolean> {\n const { name, schema } = sqlLiteral.tableParts(table);\n const rows = await this.#runner.run(\n `SELECT 1 FROM information_schema.tables WHERE table_name = ${sqlLiteral.escape(name)} AND table_schema = ${this.#schemaSql(schema)}`,\n options,\n );\n return rows.length > 0;\n }\n\n /**\n * Lists tables of the current schema.\n *\n * @param options - Query options.\n * @returns Table names.\n */\n async showAllTables(options?: QueryOptionsBase): Promise<string[]> {\n const rows = await this.#runner.run(\n \"SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type LIKE '%TABLE' AND table_name <> 'spatial_ref_sys' ORDER BY table_name\",\n options,\n );\n return rows.map((row) => String(row['table_name']));\n }\n\n /**\n * Describes the columns of a table.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `schema` and query options.\n * @returns Column descriptions keyed by column name.\n * @throws Error when the table does not exist.\n */\n async describeTable(\n table: TableName,\n options: QueryOptionsBase & Readonly<{ schema?: string }>,\n ): Promise<Record<string, ColumnDescription>> {\n const { name, schema } = sqlLiteral.tableParts(table, options.schema);\n const rows = await this.#runner.run(this.#describeSql(name, this.#schemaSql(schema)), options);\n if (rows.length === 0) {\n throw new Error(\n `No description found for table ${name}. Check the table name and schema; remember, they _are_ case sensitive.`,\n );\n }\n return columnDescriber.describe(rows);\n }\n\n /**\n * Foreign keys of a table.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns Constraint name, column and referenced table/column per foreign key column.\n */\n async getForeignKeyReferencesForTable(\n table: TableName,\n options?: QueryOptionsBase,\n ): Promise<ForeignKeyReference[]> {\n const { name, schema } = sqlLiteral.tableParts(table);\n const rows = await this.#runner.run(\n `SELECT tc.constraint_name, kcu.column_name, ccu.table_name AS referenced_table_name, ccu.column_name AS referenced_column_name FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = ${sqlLiteral.escape(name)} AND tc.table_schema = ${this.#schemaSql(schema)}`,\n options,\n );\n return rows.map((row) => ({\n constraintName: String(row['constraint_name']),\n columnName: String(row['column_name']),\n referencedTableName: String(row['referenced_table_name']),\n referencedColumnName: String(row['referenced_column_name']),\n }));\n }\n\n #schemaSql(schema: string | undefined): string {\n return schema === undefined ? 'current_schema()' : sqlLiteral.escape(schema);\n }\n\n #describeSql(name: string, schemaSql: string): string {\n return `SELECT pk.constraint_type AS \"Constraint\", c.column_name AS \"Field\", c.column_default AS \"Default\", c.is_nullable AS \"Null\", (CASE WHEN c.udt_name = 'hstore' THEN c.udt_name ELSE c.data_type END) || (CASE WHEN c.character_maximum_length IS NOT NULL THEN '(' || c.character_maximum_length || ')' ELSE '' END) AS \"Type\", (SELECT array_agg(e.enumlabel::text ORDER BY e.enumsortorder) FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid = t.typnamespace JOIN pg_catalog.pg_enum e ON t.oid = e.enumtypid WHERE t.typname = c.udt_name AND tn.nspname = c.udt_schema) AS \"special\", (SELECT pgd.description FROM pg_catalog.pg_statio_all_tables AS st INNER JOIN pg_catalog.pg_description pgd ON (pgd.objoid = st.relid) WHERE c.ordinal_position = pgd.objsubid AND c.table_name = st.relname AND st.schemaname = c.table_schema) AS \"Comment\" FROM information_schema.columns c LEFT JOIN (SELECT tc.table_schema, tc.table_name, cu.column_name, tc.constraint_type FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage cu ON tc.table_schema = cu.table_schema AND tc.table_name = cu.table_name AND tc.constraint_name = cu.constraint_name AND tc.constraint_type = 'PRIMARY KEY') pk ON pk.table_schema = c.table_schema AND pk.table_name = c.table_name AND pk.column_name = c.column_name WHERE c.table_name = ${sqlLiteral.escape(name)} AND c.table_schema = ${schemaSql} ORDER BY c.ordinal_position`;\n }\n}\n","import type { TableName } from '../ddl/sql-literal.ts';\nimport type { ModelAttributes } from '../model/model-definition.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport type {\n ColumnDescription,\n CreateTableOptions,\n DropTableOptions,\n ForeignKeyReference,\n} from './query-interface-types.ts';\nimport { StatementRunner } from './statement-runner.ts';\nimport { TableCommands } from './table-commands.ts';\nimport { TableIntrospector } from './table-introspector.ts';\n\n/**\n * Schema and table part of {@link QueryInterface}: schemas, tables and catalog lookups.\n */\nexport class QueryInterfaceTables {\n /** Owning `Sequelize` instance. */\n readonly sequelize: RuntimeOwner;\n readonly #introspector: TableIntrospector;\n readonly #tables: TableCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n this.sequelize = sequelize;\n const runner = new StatementRunner(sequelize);\n this.#introspector = new TableIntrospector(runner);\n this.#tables = new TableCommands(runner);\n }\n\n /**\n * Runs `CREATE SCHEMA IF NOT EXISTS` for a schema.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.createSchema('tenant_1');\n * ```\n */\n async createSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.#tables.createSchema(schema, options);\n }\n\n /**\n * Runs `DROP SCHEMA IF EXISTS ... CASCADE`, removing the schema and everything in it.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropSchema('tenant_1');\n * ```\n */\n async dropSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.#tables.dropSchema(schema, options);\n }\n\n /**\n * Lists application schemas, leaving out `public`, `information_schema` and `pg_*` schemas.\n *\n * @param options - Query options.\n * @returns Schema names.\n *\n * @example\n * ```ts\n * const schemas = await queryInterface.showAllSchemas();\n * ```\n */\n async showAllSchemas(options?: QueryOptionsBase): Promise<string[]> {\n return await this.#introspector.showAllSchemas(options);\n }\n\n /**\n * Drops, with `CASCADE`, every schema listed by {@link QueryInterface.showAllSchemas} Destructive.\n *\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropAllSchemas();\n * ```\n */\n async dropAllSchemas(options?: QueryOptionsBase): Promise<void> {\n const schemas = await this.showAllSchemas(options);\n await Promise.all(schemas.map((schema) => this.dropSchema(schema, options)));\n }\n\n /**\n * Creates a table together with the enum types its columns need, if the table does not exist yet. Foreign keys, defaults and comments come from the attribute definitions.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param attributes - Column definitions keyed by column name.\n * @param options - Comment and query options.\n *\n * @example\n * ```ts\n * await queryInterface.createTable(\n * { tableName: 'posts', schema: 'tenant_1' },\n * {\n * id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n * title: { type: DataTypes.STRING, allowNull: false },\n * },\n * { comment: 'Blog posts' },\n * );\n * ```\n */\n async createTable(\n table: TableName,\n attributes: ModelAttributes,\n options: CreateTableOptions = {},\n ): Promise<void> {\n await this.#tables.createTable(table, attributes, options);\n }\n\n /**\n * Runs `DROP TABLE IF EXISTS` for a table; it does not drop the table's enum types.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropTable('posts', { cascade: true });\n * ```\n */\n async dropTable(table: TableName, options: DropTableOptions = {}): Promise<void> {\n await this.#tables.dropTable(table, options);\n }\n\n /**\n * Drops every table of the current schema with `CASCADE`, except the skipped ones. Destructive.\n *\n * @param options - `skip`: table names to keep, plus query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropAllTables({ skip: ['SequelizeMeta'] });\n * ```\n */\n async dropAllTables(\n options: QueryOptionsBase & Readonly<{ skip?: readonly string[] }> = {},\n ): Promise<void> {\n await this.#tables.dropTables(await this.showAllTables(options), options);\n }\n\n /**\n * Renames a table with `ALTER TABLE ... RENAME TO`; the schema of `after` is ignored.\n *\n * @param before - Current table.\n * @param after - New table name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.renameTable('posts', 'articles');\n * ```\n */\n async renameTable(\n before: TableName,\n after: TableName,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#tables.renameTable(before, after, options);\n }\n\n /**\n * Tells whether a table exists in its schema (the current schema when none is given).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns True when the table exists.\n *\n * @example\n * ```ts\n * if (!(await queryInterface.tableExists('posts'))) {\n * await queryInterface.createTable('posts', { title: DataTypes.STRING });\n * }\n * ```\n */\n async tableExists(table: TableName, options?: QueryOptionsBase): Promise<boolean> {\n return await this.#introspector.tableExists(table, options);\n }\n\n /**\n * Lists the table names of the current schema in alphabetical order.\n *\n * @param options - Query options.\n * @returns Table names.\n *\n * @example\n * ```ts\n * const tables = await queryInterface.showAllTables(); // e.g. ['posts', 'users']\n * ```\n */\n async showAllTables(options?: QueryOptionsBase): Promise<string[]> {\n return await this.#introspector.showAllTables(options);\n }\n\n /**\n * Reads the column metadata of a table from the catalog.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `schema` and query options.\n * @returns Column descriptions keyed by column name.\n * @throws Error when the table does not exist.\n *\n * @example\n * ```ts\n * const columns = await queryInterface.describeTable('users');\n * const emailNullable = columns['email']?.allowNull;\n * ```\n */\n async describeTable(\n table: TableName,\n options: QueryOptionsBase & Readonly<{ schema?: string }> = {},\n ): Promise<Record<string, ColumnDescription>> {\n return await this.#introspector.describeTable(table, options);\n }\n\n /**\n * Lists the foreign key columns of a table with the table and column each one references.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns Constraint name, column and referenced table/column per foreign key column.\n *\n * @example\n * ```ts\n * const references = await queryInterface.getForeignKeyReferencesForTable('posts');\n * const targets = references.map((reference) => reference.referencedTableName);\n * ```\n */\n async getForeignKeyReferencesForTable(\n table: TableName,\n options?: QueryOptionsBase,\n ): Promise<ForeignKeyReference[]> {\n return await this.#introspector.getForeignKeyReferencesForTable(table, options);\n }\n}\n","import type { CreateExtensionOptions, DropExtensionOptions } from '../ddl/extension-ddl.ts';\nimport type {\n AlterSequenceOptions,\n CreateSequenceOptions,\n DropSequenceOptions,\n SequenceNumber,\n} from '../ddl/sequence-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { ObjectCommands } from './object-commands.ts';\nimport { QueryInterfaceTables } from './query-interface-tables.ts';\nimport { StatementRunner } from './statement-runner.ts';\n\n/**\n * Schema object part of {@link QueryInterface}: extensions and sequences.\n */\nexport class QueryInterfaceObjects extends QueryInterfaceTables {\n readonly #objects: ObjectCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n this.#objects = new ObjectCommands(new StatementRunner(sequelize));\n }\n\n /**\n * Installs an extension with `CREATE EXTENSION`. Needs the privileges PostgreSQL requires for that extension (superuser or a trusted extension).\n *\n * @param name - Extension name, quoted as an identifier.\n * @param options - `ifNotExists`, `schema`, `version`, `cascade` and query options.\n * @throws DatabaseError when the extension is not available on the server or the role may not install it.\n *\n * @example\n * ```ts\n * await queryInterface.createExtension('pg_trgm', { ifNotExists: true });\n * ```\n * @see [Schema guide](/guide/schema)\n */\n async createExtension(\n name: string,\n options: CreateExtensionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#objects.createExtension(name, options);\n }\n\n /**\n * Removes an extension with `DROP EXTENSION`.\n *\n * @param name - Extension name.\n * @param options - `ifExists`, `cascade` and query options.\n * @throws DatabaseError when objects depend on the extension and `cascade` is not set.\n *\n * @example\n * ```ts\n * await queryInterface.dropExtension('pg_trgm', { ifExists: true });\n * ```\n */\n async dropExtension(\n name: string,\n options: DropExtensionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#objects.dropExtension(name, options);\n }\n\n /**\n * Creates a sequence with `CREATE SEQUENCE`. Numbers must be whole (`number` or `bigint`).\n *\n * @param name - Sequence name or `{ tableName, schema }`.\n * @param options - Sequence properties and query options.\n * @throws Error for an unknown `dataType` or a non-integer number.\n *\n * @example\n * ```ts\n * await queryInterface.createSequence('invoice_number', { start: 1000, increment: 1, cache: 10 });\n * ```\n */\n async createSequence(\n name: TableName,\n options: CreateSequenceOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#objects.createSequence(name, options);\n }\n\n /**\n * Changes a sequence with `ALTER SEQUENCE`.\n *\n * @param name - Sequence name or `{ tableName, schema }`.\n * @param options - Properties to change (at least one) and query options.\n * @throws Error when no property is given or a number is not whole.\n *\n * @example\n * ```ts\n * await queryInterface.alterSequence('invoice_number', { restartWith: 5000, cycle: false });\n * ```\n */\n async alterSequence(\n name: TableName,\n options: AlterSequenceOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#objects.alterSequence(name, options);\n }\n\n /**\n * Drops a sequence with `DROP SEQUENCE`.\n *\n * @param name - Sequence name or `{ tableName, schema }`.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropSequence('invoice_number', { ifExists: true });\n * ```\n */\n async dropSequence(\n name: TableName,\n options: DropSequenceOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#objects.dropSequence(name, options);\n }\n\n /**\n * Advances a sequence and returns the new value (`SELECT nextval(...)`; the name is bound).\n *\n * @param name - Sequence name or `{ tableName, schema }`.\n * @param options - Query options.\n * @returns The value as text, so bigint values stay exact.\n *\n * @example\n * ```ts\n * const next = await queryInterface.nextval('invoice_number');\n * ```\n */\n async nextval(name: TableName, options: QueryOptionsBase = {}): Promise<string> {\n return await this.#objects.nextval(name, options);\n }\n\n /**\n * Sets the current value of a sequence (`SELECT setval(...)`; name and value are bound).\n *\n * @param name - Sequence name or `{ tableName, schema }`.\n * @param value - New value (`number` or `bigint`).\n * @param isCalled - `true` (default): the next `nextval` returns `value + increment`; `false`: it returns `value`.\n * @param options - Query options.\n * @returns The value set, as text.\n *\n * @example\n * ```ts\n * await queryInterface.setval('invoice_number', 9000, false);\n * ```\n */\n async setval(\n name: TableName,\n value: SequenceNumber,\n isCalled = true,\n options: QueryOptionsBase = {},\n ): Promise<string> {\n return await this.#objects.setval(name, value, isCalled, options);\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\n\nconst WORD = /^[A-Za-z_]\\w*$/;\n\nconst TYPE_NAME =\n /^(?:SETOF\\s+)?[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)?(?:\\s+[A-Za-z_]\\w*){0,4}(?:\\(\\s*\\d+(?:\\s*,\\s*\\d+)?\\s*\\))?(?:\\s+[A-Za-z_]\\w*){0,4}(?:\\[\\d*\\])*$/;\n\nconst DIRECTIONS: ReadonlySet<string> = new Set(['IN', 'OUT', 'INOUT', 'VARIADIC']);\n\nconst FUNCTION_OPTIONS: ReadonlySet<string> = new Set([\n 'IMMUTABLE',\n 'STABLE',\n 'VOLATILE',\n 'STRICT',\n 'CALLED ON NULL INPUT',\n 'RETURNS NULL ON NULL INPUT',\n 'LEAKPROOF',\n 'NOT LEAKPROOF',\n 'PARALLEL SAFE',\n 'PARALLEL UNSAFE',\n 'PARALLEL RESTRICTED',\n 'SECURITY DEFINER',\n 'SECURITY INVOKER',\n 'WINDOW',\n]);\n\nconst FUNCTION_NUMBER_OPTION = /^(?:COST|ROWS) \\d+$/;\n\nconst TRIGGER_OPTIONS: ReadonlySet<string> = new Set([\n 'FOR EACH ROW',\n 'FOR EACH STATEMENT',\n 'DEFERRABLE',\n 'NOT DEFERRABLE',\n 'INITIALLY DEFERRED',\n 'INITIALLY IMMEDIATE',\n]);\n\nconst TRIGGER_REFERENCING =\n /^REFERENCING (?:OLD|NEW) TABLE AS [A-Za-z_]\\w*(?: (?:OLD|NEW) TABLE AS [A-Za-z_]\\w*)?$/;\n\nconst TRIGGER_WHEN = /^WHEN\\s*\\(/i;\n\nconst normalize = (value: string): string => value.trim().replaceAll(/\\s+/g, ' ').toUpperCase();\n\n/**\n * Allowlists and patterns for the keywords and type names of functions and triggers that cannot be\n * quoted (ADR-020, ADR-025).\n *\n * @internal\n */\nexport class RoutineGuards {\n /**\n * A plain identifier word (parameter, variable, language), rendered unquoted so it folds like v6.\n *\n * @param value - Word.\n * @param kind - Kind named in the error.\n * @returns The word.\n * @throws Error for anything but `[A-Za-z_]\\w*`.\n */\n word(value: string, kind: string): string {\n if (!WORD.test(value)) {\n throw new Error(`Invalid ${kind}: ${value}`);\n }\n return value;\n }\n\n /**\n * A type name: words, an optional schema, a length / precision and array brackets.\n *\n * @param value - Type as written in SQL.\n * @param kind - Kind named in the error.\n * @returns The type.\n * @throws Error for anything that is not a type name.\n */\n typeName(value: string, kind: string): string {\n if (typeof value !== 'string' || !TYPE_NAME.test(value.trim())) {\n throw new Error(`Invalid ${kind}: ${String(value)}`);\n }\n return value.trim();\n }\n\n /**\n * Parameter direction keyword.\n *\n * @param value - Direction.\n * @returns Upper-case direction.\n * @throws Error outside `IN`, `OUT`, `INOUT`, `VARIADIC`.\n */\n direction(value: string): string {\n const direction = normalize(value);\n if (!DIRECTIONS.has(direction)) {\n throw new Error(`Invalid parameter direction: ${value}`);\n }\n return direction;\n }\n\n /**\n * Function characteristic keywords (`IMMUTABLE`, `SECURITY DEFINER`, `COST n`, ...).\n *\n * @param options - Keywords as given.\n * @returns Normalized keywords.\n * @throws Error for a keyword outside the allowlist.\n */\n functionOptions(options: readonly string[]): readonly string[] {\n return options.map((option) => {\n const keyword = normalize(option);\n if (!FUNCTION_OPTIONS.has(keyword) && !FUNCTION_NUMBER_OPTION.test(keyword)) {\n throw new Error(`Invalid function option: ${option}`);\n }\n return keyword;\n });\n }\n\n /**\n * Trigger clauses: row / statement level, deferrability, `REFERENCING` transition tables and\n * `WHEN (condition)`. The condition is trusted SQL.\n *\n * @param options - Clauses as given.\n * @returns Normalized clauses (`WHEN` kept as written).\n * @throws Error for a clause outside the allowlist.\n */\n triggerOptions(options: readonly string[]): readonly string[] {\n return options.map((option) => {\n if (TRIGGER_WHEN.test(option.trim())) {\n return option.trim();\n }\n const keyword = normalize(option);\n if (!TRIGGER_OPTIONS.has(keyword) && !TRIGGER_REFERENCING.test(keyword)) {\n throw new Error(`Invalid trigger option: ${option}`);\n }\n return keyword;\n });\n }\n\n /**\n * Function name: a word or `schema.word` string (unquoted, folds like v6) or `{ name, schema }`\n * (quoted exactly).\n *\n * @param name - Function name.\n * @returns SQL name.\n * @throws Error for a string that is not one or two identifier words.\n */\n functionName(name: string | Readonly<{ name: string; schema?: string }>): string {\n if (typeof name !== 'string') {\n return name.schema === undefined\n ? SqlCompiler.quoteIdent(name.name)\n : `${SqlCompiler.quoteIdent(name.schema)}.${SqlCompiler.quoteIdent(name.name)}`;\n }\n return name\n .split('.')\n .map((part) => this.word(part, 'function name'))\n .join('.');\n }\n}\n","import { RoutineGuards } from './routine-guards.ts';\nimport { SqlLiteral } from './sql-literal.ts';\n\nconst guards = new RoutineGuards();\n\nconst sqlLiteral = new SqlLiteral();\n\n/** Function reference: a plain name (`'touch'`, `'app.touch'`) or `{ name, schema }` (quoted exactly). */\nexport type FunctionName =\n | string\n | Readonly<{\n /** Function name, quoted exactly. */\n name: string;\n /** Schema name, quoted exactly. */\n schema?: string;\n }>;\n\n/** Parameter of a function. */\nexport type FunctionParam = Readonly<{\n /** SQL type, e.g. `'integer'`, `'varchar(10)'`, `'text[]'`. */\n type: string;\n /** Parameter name (identifier word). */\n name?: string;\n /** `IN`, `OUT`, `INOUT` or `VARIADIC`. */\n direction?: string;\n}>;\n\n/** Local variable declared before `BEGIN`. */\nexport type FunctionVariable = Readonly<{\n /** Variable name (identifier word). */\n name: string;\n /** SQL type. */\n type: string;\n /** Initial value, rendered as a literal. */\n default?: unknown;\n}>;\n\n/**\n * Options of `createFunction`.\n *\n * @example\n * ```ts\n * const options: CreateFunctionOptions = {\n * force: true,\n * variables: [{ name: 'limit_rows', type: 'integer', default: 100 }],\n * };\n * await queryInterface.createFunction('f', [], 'integer', 'plpgsql', 'RETURN limit_rows;', [], options);\n * ```\n */\nexport type CreateFunctionOptions = Readonly<{\n /** Local variables (`DECLARE name type := default;`). */\n variables?: readonly FunctionVariable[];\n /** `CREATE OR REPLACE FUNCTION`. */\n force?: boolean;\n}>;\n\n/**\n * Options of `dropFunction`.\n *\n * @example\n * ```ts\n * const options: DropFunctionOptions = { ifExists: true, cascade: true };\n * await queryInterface.dropFunction('f', [], options);\n * ```\n */\nexport type DropFunctionOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** `CASCADE` instead of the default `RESTRICT`. */\n cascade?: boolean;\n}>;\n\n/**\n * `CREATE`, `DROP` and `ALTER ... RENAME` statements for functions (Sequelize v6 shapes).\n *\n * @internal\n */\nexport class FunctionDdl {\n /**\n * `CREATE [OR REPLACE] FUNCTION` statement; the body is wrapped in `BEGIN ... END;` like v6.\n *\n * @param name - Function name.\n * @param params - Parameters.\n * @param returnType - Return type.\n * @param language - Language word.\n * @param body - Trusted SQL / PL/pgSQL text.\n * @param optionsArray - Characteristic keywords.\n * @param options - Statement options.\n * @returns Statement.\n * @throws Error for missing parts or values outside the guards.\n */\n createSql(\n name: FunctionName,\n params: readonly FunctionParam[],\n returnType: string,\n language: string,\n body: string,\n optionsArray: readonly string[],\n options: CreateFunctionOptions,\n ): string {\n this.#require([returnType, language, body]);\n return [\n this.#head(name, params, options),\n ` RETURNS ${guards.typeName(returnType, 'return type')}`,\n this.#body(body, options.variables ?? []),\n ` LANGUAGE ${guards.word(language, 'language')}`,\n ...guards.functionOptions(optionsArray).map((option) => ` ${option}`),\n ].join('');\n }\n\n /**\n * `DROP FUNCTION` statement (`RESTRICT` unless `cascade`).\n *\n * @param name - Function name.\n * @param params - Parameters identifying the overload.\n * @param options - Statement options.\n * @returns Statement.\n */\n dropSql(\n name: FunctionName,\n params: readonly FunctionParam[],\n options: DropFunctionOptions,\n ): string {\n return `DROP FUNCTION ${options.ifExists === true ? 'IF EXISTS ' : ''}${guards.functionName(name)}(${this.#params(params)}) ${options.cascade === true ? 'CASCADE' : 'RESTRICT'}`;\n }\n\n /**\n * `ALTER FUNCTION ... RENAME TO` statement.\n *\n * @param name - Current name.\n * @param params - Parameters identifying the overload.\n * @param newName - New unqualified name.\n * @returns Statement.\n */\n renameSql(name: FunctionName, params: readonly FunctionParam[], newName: string): string {\n return `ALTER FUNCTION ${guards.functionName(name)}(${this.#params(params)}) RENAME TO ${guards.word(newName, 'function name')}`;\n }\n\n #params(params: readonly FunctionParam[]): string {\n if (!Array.isArray(params)) {\n throw new Error(\n 'function parameters array required, including an empty one for no arguments',\n );\n }\n return params\n .map((param) =>\n [\n param.direction === undefined ? '' : guards.direction(param.direction),\n param.name === undefined ? '' : guards.word(param.name, 'parameter name'),\n guards.typeName(param.type, 'parameter type'),\n ]\n .filter((part) => part !== '')\n .join(' '),\n )\n .join(', ');\n }\n\n #require(parts: readonly string[]): void {\n if (parts.some((part) => part === '')) {\n throw new Error('createFunction requires functionName, returnType, language and body');\n }\n }\n\n #head(\n name: FunctionName,\n params: readonly FunctionParam[],\n options: CreateFunctionOptions,\n ): string {\n return `CREATE ${options.force === true ? 'OR REPLACE ' : ''}FUNCTION ${guards.functionName(name)}(${this.#params(params)})`;\n }\n\n #body(body: string, variables: readonly FunctionVariable[]): string {\n const tag = this.#tag(body);\n const declared = variables.map((variable) => this.#variable(variable)).join(' ');\n return ` AS ${tag} ${declared} BEGIN ${body} END; ${tag}`;\n }\n\n #variable(variable: FunctionVariable): string {\n const initial =\n variable.default === undefined ? '' : ` := ${sqlLiteral.escape(variable.default)}`;\n return `DECLARE ${guards.word(variable.name, 'variable name')} ${guards.typeName(variable.type, 'variable type')}${initial};`;\n }\n\n #tag(body: string): string {\n let tag = '$func$';\n for (let index = 1; body.includes(tag); index += 1) {\n tag = `$func${index}$`;\n }\n return tag;\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { type FunctionName } from './function-ddl.ts';\nimport { RoutineGuards } from './routine-guards.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new RoutineGuards();\n\nconst sqlLiteral = new SqlLiteral();\n\nconst TIMINGS: Readonly<Record<string, string>> = {\n before: 'BEFORE',\n after: 'AFTER',\n instead_of: 'INSTEAD OF',\n after_constraint: 'AFTER',\n};\n\nconst EVENTS: Readonly<Record<string, string>> = {\n insert: 'INSERT',\n update: 'UPDATE',\n delete: 'DELETE',\n truncate: 'TRUNCATE',\n};\n\n/** When a trigger fires relative to the event (Sequelize v6 values). */\nexport type TriggerTiming = 'before' | 'after' | 'instead_of' | 'after_constraint';\n\n/** Table event that fires a trigger. */\nexport type TriggerEvent = 'insert' | 'update' | 'delete' | 'truncate';\n\n/** Argument passed to the trigger function, rendered as a literal. */\nexport type TriggerArgument = string | number | boolean | bigint;\n\n/**\n * Options of `createTrigger`.\n *\n * @example\n * ```ts\n * const options: CreateTriggerOptions = { replace: true };\n * await queryInterface.createTrigger('Posts', 'posts_touch', 'before', ['update'], 'touch', [], [], options);\n * ```\n */\nexport type CreateTriggerOptions = Readonly<{\n /** `CREATE OR REPLACE TRIGGER` (PostgreSQL 14+). */\n replace?: boolean;\n}>;\n\n/**\n * Options of `dropTrigger`.\n *\n * @example\n * ```ts\n * const options: DropTriggerOptions = { ifExists: true };\n * await queryInterface.dropTrigger('Posts', 'posts_touch', options);\n * ```\n */\nexport type DropTriggerOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** `CASCADE` instead of the default `RESTRICT`. */\n cascade?: boolean;\n}>;\n\n/** Definition of a trigger (the arguments of `createTrigger` before the options). @internal */\nexport type TriggerSpec = Readonly<{\n table: TableName;\n name: string;\n timing: TriggerTiming;\n events: readonly TriggerEvent[];\n functionName: FunctionName;\n functionArgs: readonly TriggerArgument[];\n optionsArray: readonly string[];\n}>;\n\nconst own = (map: Readonly<Record<string, string>>, key: unknown): string | undefined =>\n typeof key === 'string' && Object.hasOwn(map, key) ? map[key] : undefined;\n\n/**\n * `CREATE`, `DROP` and `ALTER ... RENAME` statements for triggers (Sequelize v6 shapes).\n *\n * @internal\n */\nexport class TriggerDdl {\n /**\n * `CREATE [CONSTRAINT] TRIGGER` statement.\n *\n * @param spec - Trigger definition.\n * @param options - Statement options.\n * @returns Statement.\n * @throws Error for an unknown timing, event or clause.\n */\n createSql(spec: TriggerSpec, options: CreateTriggerOptions): string {\n const clauses = guards.triggerOptions(spec.optionsArray).map((clause) => ` ${clause}`);\n const head = `CREATE ${options.replace === true ? 'OR REPLACE ' : ''}${spec.timing === 'after_constraint' ? 'CONSTRAINT ' : ''}TRIGGER ${SqlCompiler.quoteIdent(spec.name)}`;\n return [\n head,\n ` ${this.#timing(spec.timing)} ${this.#events(spec.events)} ON ${sqlLiteral.quoteTable(spec.table)}`,\n clauses.join(''),\n ` EXECUTE FUNCTION ${guards.functionName(spec.functionName)}(${this.#args(spec.functionArgs)})`,\n ].join('');\n }\n\n /**\n * `DROP TRIGGER` statement (`RESTRICT` unless `cascade`).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Trigger name.\n * @param options - Statement options.\n * @returns Statement.\n */\n dropSql(table: TableName, name: string, options: DropTriggerOptions): string {\n return `DROP TRIGGER ${options.ifExists === true ? 'IF EXISTS ' : ''}${SqlCompiler.quoteIdent(name)} ON ${sqlLiteral.quoteTable(table)} ${options.cascade === true ? 'CASCADE' : 'RESTRICT'}`;\n }\n\n /**\n * `ALTER TRIGGER ... RENAME TO` statement.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Current trigger name.\n * @param newName - New trigger name.\n * @returns Statement.\n */\n renameSql(table: TableName, name: string, newName: string): string {\n return `ALTER TRIGGER ${SqlCompiler.quoteIdent(name)} ON ${sqlLiteral.quoteTable(table)} RENAME TO ${SqlCompiler.quoteIdent(newName)}`;\n }\n\n #timing(timing: TriggerTiming): string {\n const sql = own(TIMINGS, timing);\n if (sql === undefined) {\n throw new Error(`Invalid trigger event specified: ${String(timing)}`);\n }\n return sql;\n }\n\n #events(events: readonly TriggerEvent[]): string {\n if (!Array.isArray(events) || events.length === 0) {\n throw new Error('no table change events specified to trigger on');\n }\n return events\n .map((event) => {\n const sql = own(EVENTS, event);\n if (sql === undefined) {\n throw new Error(`parseTriggerEventSpec: undefined trigger event ${String(event)}`);\n }\n return sql;\n })\n .join(' OR ');\n }\n\n #args(args: readonly TriggerArgument[]): string {\n if (!Array.isArray(args)) {\n throw new Error('trigger arguments array required, including an empty one for no arguments');\n }\n return args\n .map((arg) => {\n if (typeof arg === 'object' || typeof arg === 'function') {\n throw new Error('trigger arguments must be strings, numbers, booleans or bigints');\n }\n return sqlLiteral.escape(arg);\n })\n .join(', ');\n }\n}\n","import {\n FunctionDdl,\n type CreateFunctionOptions,\n type DropFunctionOptions,\n type FunctionName,\n type FunctionParam,\n} from '../ddl/function-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport {\n TriggerDdl,\n type CreateTriggerOptions,\n type DropTriggerOptions,\n type TriggerSpec,\n} from '../ddl/trigger-ddl.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst functions = new FunctionDdl();\n\nconst triggers = new TriggerDdl();\n\n/**\n * Function and trigger DDL of `QueryInterface`. Names are quoted or guarded words, trigger\n * arguments are literals, function bodies are trusted SQL (ADR-025).\n *\n * @internal\n */\nexport class RoutineCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Runs `CREATE FUNCTION`.\n *\n * @param name - Function name.\n * @param params - Parameters.\n * @param returnType - Return type.\n * @param language - Language.\n * @param body - Trusted body text.\n * @param optionsArray - Characteristic keywords.\n * @param options - Statement and query options.\n */\n async createFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n returnType: string,\n language: string,\n body: string,\n optionsArray: readonly string[],\n options: CreateFunctionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(\n functions.createSql(name, params, returnType, language, body, optionsArray, options),\n options,\n );\n }\n\n /**\n * Runs `DROP FUNCTION`.\n *\n * @param name - Function name.\n * @param params - Parameters identifying the overload.\n * @param options - Statement and query options.\n */\n async dropFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n options: DropFunctionOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(functions.dropSql(name, params, options), options);\n }\n\n /**\n * Runs `ALTER FUNCTION ... RENAME TO`.\n *\n * @param name - Current name.\n * @param params - Parameters identifying the overload.\n * @param newName - New name.\n * @param options - Query options.\n */\n async renameFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n newName: string,\n options: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(functions.renameSql(name, params, newName), options);\n }\n\n /**\n * Runs `CREATE TRIGGER`.\n *\n * @param spec - Trigger definition.\n * @param options - Statement and query options.\n */\n async createTrigger(\n spec: TriggerSpec,\n options: CreateTriggerOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(triggers.createSql(spec, options), options);\n }\n\n /**\n * Runs `DROP TRIGGER`.\n *\n * @param table - Table.\n * @param name - Trigger name.\n * @param options - Statement and query options.\n */\n async dropTrigger(\n table: TableName,\n name: string,\n options: DropTriggerOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(triggers.dropSql(table, name, options), options);\n }\n\n /**\n * Runs `ALTER TRIGGER ... RENAME TO`.\n *\n * @param table - Table.\n * @param name - Current name.\n * @param newName - New name.\n * @param options - Query options.\n */\n async renameTrigger(\n table: TableName,\n name: string,\n newName: string,\n options: QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(triggers.renameSql(table, name, newName), options);\n }\n}\n","import type {\n CreateFunctionOptions,\n DropFunctionOptions,\n FunctionName,\n FunctionParam,\n} from '../ddl/function-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type {\n CreateTriggerOptions,\n DropTriggerOptions,\n TriggerArgument,\n TriggerEvent,\n TriggerTiming,\n} from '../ddl/trigger-ddl.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { QueryInterfaceObjects } from './query-interface-objects.ts';\nimport { RoutineCommands } from './routine-commands.ts';\nimport { StatementRunner } from './statement-runner.ts';\n\n/**\n * Function and trigger part of {@link QueryInterface}.\n */\nexport class QueryInterfaceRoutines extends QueryInterfaceObjects {\n readonly #routines: RoutineCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n this.#routines = new RoutineCommands(new StatementRunner(sequelize));\n }\n\n /**\n * Creates a function with `CREATE [OR REPLACE] FUNCTION` (Sequelize v6 `createFunction`). The body is wrapped in `BEGIN ... END;` as in v6.\n *\n * The `body` is SQL text you provide: it is not escaped, so never build it from user input. Names, parameter names and the language are validated identifier words; types and characteristic keywords are checked against strict patterns and allowlists. A function name given as a string is unquoted (folds to lower case, like v6); use `{ name, schema }` for an exact quoted name.\n *\n * @param name - Function name (`'touch'`, `'app.touch'` or `{ name, schema }`).\n * @param params - Parameters `{ type, name?, direction? }`; pass `[]` for none.\n * @param returnType - Return type, e.g. `'trigger'`, `'integer'`, `'SETOF text'`.\n * @param language - Language, e.g. `'plpgsql'`.\n * @param body - Trusted function body without `BEGIN` / `END`.\n * @param optionsArray - Characteristic keywords such as `'IMMUTABLE'`, `'SECURITY DEFINER'`, `'COST 10'`.\n * @param options - `variables`, `force` (`OR REPLACE`) and query options.\n * @throws Error when a part is missing or fails validation.\n * @throws DatabaseError when PostgreSQL rejects the function.\n *\n * @example\n * ```ts\n * await queryInterface.createFunction(\n * 'touch_updated_at',\n * [],\n * 'trigger',\n * 'plpgsql',\n * 'NEW.\"updatedAt\" := now(); RETURN NEW;',\n * ['VOLATILE'],\n * { force: true },\n * );\n * ```\n * @see [Schema objects guide](/guide/schema-objects)\n */\n async createFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n returnType: string,\n language: string,\n body: string,\n optionsArray: readonly string[] = [],\n options: CreateFunctionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#routines.createFunction(\n name,\n params,\n returnType,\n language,\n body,\n optionsArray,\n options,\n );\n }\n\n /**\n * Drops a function with `DROP FUNCTION ... RESTRICT` (Sequelize v6 `dropFunction`).\n *\n * @param name - Function name.\n * @param params - Parameters that identify the overload; pass `[]` for none.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropFunction('touch_updated_at', [], { ifExists: true });\n * ```\n */\n async dropFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n options: DropFunctionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#routines.dropFunction(name, params, options);\n }\n\n /**\n * Renames a function with `ALTER FUNCTION ... RENAME TO` (Sequelize v6 `renameFunction`).\n *\n * @param name - Current function name.\n * @param params - Parameters that identify the overload.\n * @param newName - New unqualified name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.renameFunction('touch_updated_at', [], 'set_updated_at');\n * ```\n */\n async renameFunction(\n name: FunctionName,\n params: readonly FunctionParam[],\n newName: string,\n options: QueryOptionsBase = {},\n ): Promise<void> {\n await this.#routines.renameFunction(name, params, newName, options);\n }\n\n /**\n * Creates a trigger with `CREATE TRIGGER` (Sequelize v6 `createTrigger`; `'after_constraint'` creates a `CONSTRAINT TRIGGER`).\n *\n * `functionArgs` are rendered as literals (v6 rendered typed parameter declarations, which PostgreSQL rejects). The `optionsArray` clauses are checked against an allowlist (`'FOR EACH ROW'`, `'FOR EACH STATEMENT'`, `'DEFERRABLE'`, `'INITIALLY DEFERRED'`, `REFERENCING ... TABLE AS name`); a `WHEN (condition)` clause is trusted SQL and is not escaped.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Trigger name.\n * @param timing - `'before'`, `'after'`, `'instead_of'` or `'after_constraint'`.\n * @param events - Events that fire the trigger: `'insert'`, `'update'`, `'delete'`, `'truncate'`.\n * @param functionName - Trigger function (see {@link QueryInterface.createFunction}).\n * @param functionArgs - Literal arguments for the function; pass `[]` for none.\n * @param optionsArray - Clauses such as `['FOR EACH ROW']`.\n * @param options - `replace` (`OR REPLACE`, PostgreSQL 14+) and query options.\n * @throws Error for an unknown timing, event or clause.\n *\n * @example\n * ```ts\n * await queryInterface.createTrigger('Posts', 'posts_touch', 'before', ['insert', 'update'], 'touch_updated_at', [], ['FOR EACH ROW']);\n * ```\n */\n async createTrigger(\n table: TableName,\n name: string,\n timing: TriggerTiming,\n events: readonly TriggerEvent[],\n functionName: FunctionName,\n functionArgs: readonly TriggerArgument[] = [],\n optionsArray: readonly string[] = [],\n options: CreateTriggerOptions & QueryOptionsBase = {},\n ): Promise<void> {\n const spec = { table, name, timing, events, functionName, functionArgs, optionsArray };\n await this.#routines.createTrigger(spec, options);\n }\n\n /**\n * Drops a trigger with `DROP TRIGGER ... RESTRICT` (Sequelize v6 `dropTrigger`).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Trigger name.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropTrigger('Posts', 'posts_touch', { ifExists: true });\n * ```\n */\n async dropTrigger(\n table: TableName,\n name: string,\n options: DropTriggerOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#routines.dropTrigger(table, name, options);\n }\n\n /**\n * Renames a trigger with `ALTER TRIGGER ... RENAME TO` (Sequelize v6 `renameTrigger`).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Current trigger name.\n * @param newName - New trigger name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.renameTrigger('Posts', 'posts_touch', 'posts_set_updated_at');\n * ```\n */\n async renameTrigger(\n table: TableName,\n name: string,\n newName: string,\n options: QueryOptionsBase = {},\n ): Promise<void> {\n await this.#routines.renameTrigger(table, name, newName, options);\n }\n}\n","import { SqlCompiler } from '../sql/compile.ts';\nimport { RoutineGuards } from './routine-guards.ts';\nimport { SqlLiteral, type TableName } from './sql-literal.ts';\n\nconst guards = new RoutineGuards();\n\nconst sqlLiteral = new SqlLiteral();\n\nconst CHECK_OPTIONS: Readonly<Record<string, string>> = { local: 'LOCAL', cascaded: 'CASCADED' };\n\n/**\n * Options of `createView`.\n *\n * @example\n * ```ts\n * const options: CreateViewOptions = { replace: true, columns: ['id', 'title'], checkOption: 'local' };\n * await queryInterface.createView('published_posts', 'SELECT id, title FROM \"Posts\" WHERE published', options);\n * ```\n */\nexport type CreateViewOptions = Readonly<{\n /** `CREATE OR REPLACE VIEW`. */\n replace?: boolean;\n /** `CREATE TEMPORARY VIEW`: lives as long as the database session (pooled connection). */\n temporary?: boolean;\n /** `CREATE RECURSIVE VIEW`; needs `columns`. */\n recursive?: boolean;\n /** Output column names. */\n columns?: readonly string[];\n /** `WITH LOCAL | CASCADED CHECK OPTION` for updatable views. */\n checkOption?: 'local' | 'cascaded';\n /** `security_barrier` view option. */\n securityBarrier?: boolean;\n /** `security_invoker` view option (queries run with the privileges of the caller). */\n securityInvoker?: boolean;\n}>;\n\n/**\n * Options of `createMaterializedView`.\n *\n * @example\n * ```ts\n * const options: CreateMaterializedViewOptions = { ifNotExists: true, withData: false };\n * await queryInterface.createMaterializedView('post_stats', 'SELECT count(*) AS n FROM \"Posts\"', options);\n * ```\n */\nexport type CreateMaterializedViewOptions = Readonly<{\n /** Adds `IF NOT EXISTS`. */\n ifNotExists?: boolean;\n /** Output column names. */\n columns?: readonly string[];\n /** Table access method (`USING heap`). */\n using?: string;\n /** `false` renders `WITH NO DATA`: the view is created empty and unreadable until refreshed. */\n withData?: boolean;\n}>;\n\n/**\n * Options of `refreshMaterializedView`.\n *\n * @example\n * ```ts\n * const options: RefreshMaterializedViewOptions = { concurrently: true };\n * await queryInterface.refreshMaterializedView('post_stats', options);\n * ```\n */\nexport type RefreshMaterializedViewOptions = Readonly<{\n /** `REFRESH ... CONCURRENTLY`: readers are not blocked; needs a unique index and cannot be combined with `withData: false`. */\n concurrently?: boolean;\n /** `false` renders `WITH NO DATA` (empties the view). */\n withData?: boolean;\n}>;\n\n/**\n * Options of `dropView` and `dropMaterializedView`.\n *\n * @example\n * ```ts\n * const options: DropViewOptions = { ifExists: true, cascade: true };\n * await queryInterface.dropView('published_posts', options);\n * ```\n */\nexport type DropViewOptions = Readonly<{\n /** Adds `IF EXISTS`. */\n ifExists?: boolean;\n /** Also drops objects that depend on the view. */\n cascade?: boolean;\n}>;\n\n/**\n * `CREATE`, `REFRESH` and `DROP` statements for views and materialized views. The query text is\n * trusted SQL (ADR-025); names and column lists are quoted.\n *\n * @internal\n */\nexport class ViewDdl {\n /**\n * `CREATE [OR REPLACE] [TEMPORARY] [RECURSIVE] VIEW` statement.\n *\n * @param name - View name.\n * @param query - Trusted `SELECT` text.\n * @param options - View options.\n * @returns Statement.\n * @throws Error for an empty query, a recursive view without columns or an unknown check option.\n */\n createSql(name: TableName, query: string, options: CreateViewOptions): string {\n if (options.recursive === true && (options.columns ?? []).length === 0) {\n throw new Error('A recursive view requires columns');\n }\n const head = `CREATE ${options.replace === true ? 'OR REPLACE ' : ''}${options.temporary === true ? 'TEMPORARY ' : ''}${options.recursive === true ? 'RECURSIVE ' : ''}VIEW ${sqlLiteral.quoteTable(name)}`;\n return [\n head,\n this.#columns(options.columns),\n this.#withOptions(options),\n ` AS ${this.#query(query)}`,\n this.#checkOption(options.checkOption),\n ].join('');\n }\n\n /**\n * `CREATE MATERIALIZED VIEW` statement.\n *\n * @param name - View name.\n * @param query - Trusted `SELECT` text.\n * @param options - View options.\n * @returns Statement.\n * @throws Error for an empty query or an invalid access method.\n */\n createMaterializedSql(\n name: TableName,\n query: string,\n options: CreateMaterializedViewOptions,\n ): string {\n return [\n `CREATE MATERIALIZED VIEW ${options.ifNotExists === true ? 'IF NOT EXISTS ' : ''}${sqlLiteral.quoteTable(name)}`,\n this.#columns(options.columns),\n options.using === undefined ? '' : ` USING ${guards.word(options.using, 'access method')}`,\n ` AS ${this.#query(query)}`,\n options.withData === false ? ' WITH NO DATA' : '',\n ].join('');\n }\n\n /**\n * `REFRESH MATERIALIZED VIEW` statement.\n *\n * @param name - View name.\n * @param options - Refresh options.\n * @returns Statement.\n * @throws Error when `concurrently` is combined with `withData: false`.\n */\n refreshSql(name: TableName, options: RefreshMaterializedViewOptions): string {\n if (options.concurrently === true && options.withData === false) {\n throw new Error('CONCURRENTLY cannot be combined with WITH NO DATA');\n }\n return `REFRESH MATERIALIZED VIEW ${options.concurrently === true ? 'CONCURRENTLY ' : ''}${sqlLiteral.quoteTable(name)}${options.withData === false ? ' WITH NO DATA' : ''}`;\n }\n\n /**\n * `DROP VIEW` or `DROP MATERIALIZED VIEW` statement.\n *\n * @param name - View name.\n * @param materialized - Drops a materialized view.\n * @param options - Drop options.\n * @returns Statement.\n */\n dropSql(name: TableName, materialized: boolean, options: DropViewOptions): string {\n return `DROP ${materialized ? 'MATERIALIZED ' : ''}VIEW ${options.ifExists === true ? 'IF EXISTS ' : ''}${sqlLiteral.quoteTable(name)}${options.cascade === true ? ' CASCADE' : ''}`;\n }\n\n #query(query: string): string {\n if (typeof query !== 'string' || query.trim() === '') {\n throw new Error('A view requires a query');\n }\n return query.trim().replace(/;+\\s*$/, '');\n }\n\n #columns(columns: readonly string[] | undefined): string {\n return columns === undefined || columns.length === 0\n ? ''\n : ` (${columns.map(SqlCompiler.quoteIdent).join(', ')})`;\n }\n\n #withOptions(options: CreateViewOptions): string {\n const settings = [\n options.securityBarrier === undefined\n ? ''\n : `security_barrier = ${String(options.securityBarrier === true)}`,\n options.securityInvoker === undefined\n ? ''\n : `security_invoker = ${String(options.securityInvoker === true)}`,\n ].filter((setting) => setting !== '');\n return settings.length === 0 ? '' : ` WITH (${settings.join(', ')})`;\n }\n\n #checkOption(checkOption: string | undefined): string {\n if (checkOption === undefined) {\n return '';\n }\n const sql = Object.hasOwn(CHECK_OPTIONS, checkOption) ? CHECK_OPTIONS[checkOption] : undefined;\n if (sql === undefined) {\n throw new Error(`Invalid check option: ${checkOption}`);\n }\n return ` WITH ${sql} CHECK OPTION`;\n }\n}\n","import {\n ViewDdl,\n type CreateMaterializedViewOptions,\n type CreateViewOptions,\n type DropViewOptions,\n type RefreshMaterializedViewOptions,\n} from '../ddl/view-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { StatementRunner } from './statement-runner.ts';\n\nconst views = new ViewDdl();\n\n/**\n * View and materialized view DDL of `QueryInterface`. Names are quoted; the query is trusted SQL.\n *\n * @internal\n */\nexport class ViewCommands {\n readonly #runner: StatementRunner;\n\n /**\n * @param runner - Statement runner.\n */\n constructor(runner: StatementRunner) {\n this.#runner = runner;\n }\n\n /**\n * Runs `CREATE VIEW`.\n *\n * @param name - View name.\n * @param query - Trusted `SELECT` text.\n * @param options - View and query options.\n */\n async createView(\n name: TableName,\n query: string,\n options: CreateViewOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(views.createSql(name, query, options), options);\n }\n\n /**\n * Runs `CREATE MATERIALIZED VIEW`.\n *\n * @param name - View name.\n * @param query - Trusted `SELECT` text.\n * @param options - View and query options.\n */\n async createMaterializedView(\n name: TableName,\n query: string,\n options: CreateMaterializedViewOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(views.createMaterializedSql(name, query, options), options);\n }\n\n /**\n * Runs `REFRESH MATERIALIZED VIEW`.\n *\n * @param name - View name.\n * @param options - Refresh and query options.\n */\n async refreshMaterializedView(\n name: TableName,\n options: RefreshMaterializedViewOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(views.refreshSql(name, options), options);\n }\n\n /**\n * Runs `DROP VIEW` or `DROP MATERIALIZED VIEW`.\n *\n * @param name - View name.\n * @param materialized - Drops a materialized view.\n * @param options - Drop and query options.\n */\n async dropView(\n name: TableName,\n materialized: boolean,\n options: DropViewOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#runner.run(views.dropSql(name, materialized, options), options);\n }\n}\n","import type {\n CreateMaterializedViewOptions,\n CreateViewOptions,\n DropViewOptions,\n RefreshMaterializedViewOptions,\n} from '../ddl/view-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { QueryInterfaceRoutines } from './query-interface-routines.ts';\nimport { StatementRunner } from './statement-runner.ts';\nimport { ViewCommands } from './view-commands.ts';\n\n/**\n * View part of {@link QueryInterface}: views and materialized views.\n */\nexport class QueryInterfaceViews extends QueryInterfaceRoutines {\n readonly #views: ViewCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n this.#views = new ViewCommands(new StatementRunner(sequelize));\n }\n\n /**\n * Creates a view with `CREATE VIEW`; `replace` renders `CREATE OR REPLACE VIEW`.\n *\n * The `query` is SQL text you provide: it is not escaped, so never build it from user input. Names and column lists are quoted identifiers. A trailing `;` is removed.\n *\n * @param name - View name or `{ tableName, schema }`.\n * @param query - Trusted `SELECT` text.\n * @param options - `replace`, `temporary`, `recursive`, `columns`, `checkOption`, `securityBarrier`, `securityInvoker` and query options.\n * @throws Error for an empty query, a recursive view without `columns` or an unknown `checkOption`.\n *\n * @example\n * ```ts\n * await queryInterface.createView('published_posts', 'SELECT id, title FROM \"Posts\" WHERE published', { replace: true });\n * ```\n * @see [Schema objects guide](/guide/schema-objects)\n */\n async createView(\n name: TableName,\n query: string,\n options: CreateViewOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#views.createView(name, query, options);\n }\n\n /**\n * Drops a view with `DROP VIEW`.\n *\n * @param name - View name or `{ tableName, schema }`.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropView('published_posts', { ifExists: true });\n * ```\n */\n async dropView(name: TableName, options: DropViewOptions & QueryOptionsBase = {}): Promise<void> {\n await this.#views.dropView(name, false, options);\n }\n\n /**\n * Creates a materialized view with `CREATE MATERIALIZED VIEW`.\n *\n * The `query` is trusted SQL text, as in {@link QueryInterface.createView}. PostgreSQL has no `OR REPLACE` for materialized views: drop and create, or use `ifNotExists`.\n *\n * @param name - View name or `{ tableName, schema }`.\n * @param query - Trusted `SELECT` text.\n * @param options - `ifNotExists`, `columns`, `using`, `withData` and query options.\n * @throws Error for an empty query or an invalid access method.\n *\n * @example\n * ```ts\n * await queryInterface.createMaterializedView('post_stats', 'SELECT author_id, count(*) AS n FROM \"Posts\" GROUP BY author_id');\n * ```\n */\n async createMaterializedView(\n name: TableName,\n query: string,\n options: CreateMaterializedViewOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#views.createMaterializedView(name, query, options);\n }\n\n /**\n * Recomputes a materialized view with `REFRESH MATERIALIZED VIEW`.\n *\n * @param name - View name or `{ tableName, schema }`.\n * @param options - `concurrently` (needs a unique index), `withData` and query options.\n * @throws Error when `concurrently` is combined with `withData: false`.\n *\n * @example\n * ```ts\n * await queryInterface.refreshMaterializedView('post_stats', { concurrently: true });\n * ```\n */\n async refreshMaterializedView(\n name: TableName,\n options: RefreshMaterializedViewOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#views.refreshMaterializedView(name, options);\n }\n\n /**\n * Drops a materialized view with `DROP MATERIALIZED VIEW`.\n *\n * @param name - View name or `{ tableName, schema }`.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropMaterializedView('post_stats', { ifExists: true });\n * ```\n */\n async dropMaterializedView(\n name: TableName,\n options: DropViewOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#views.dropView(name, true, options);\n }\n}\n","import type {\n AlterPolicyOptions,\n CreatePolicyOptions,\n DisableRowLevelSecurityOptions,\n DropPolicyOptions,\n EnableRowLevelSecurityOptions,\n} from '../ddl/policy-ddl.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { PolicyCommands } from './policy-commands.ts';\nimport { QueryInterfaceViews } from './query-interface-views.ts';\nimport { StatementRunner } from './statement-runner.ts';\n\n/**\n * Row-level security part of {@link QueryInterface}.\n */\nexport class QueryInterfacePolicies extends QueryInterfaceViews {\n readonly #policies: PolicyCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n this.#policies = new PolicyCommands(new StatementRunner(sequelize));\n }\n\n /**\n * Turns on row-level security for a table (`ALTER TABLE ... ENABLE ROW LEVEL SECURITY`). Without policies, non-owners see no rows.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `force` (also applies to the table owner) and query options.\n *\n * @example\n * ```ts\n * await queryInterface.enableRowLevelSecurity('documents', { force: true });\n * ```\n * @see [Schema objects guide](/guide/schema-objects)\n */\n async enableRowLevelSecurity(\n table: TableName,\n options: EnableRowLevelSecurityOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#policies.enable(table, options);\n }\n\n /**\n * Turns off row-level security for a table (`ALTER TABLE ... DISABLE ROW LEVEL SECURITY`); policies are kept.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - `noForce` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.disableRowLevelSecurity('documents', { noForce: true });\n * ```\n */\n async disableRowLevelSecurity(\n table: TableName,\n options: DisableRowLevelSecurityOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#policies.disable(table, options);\n }\n\n /**\n * Creates a row-level security policy with `CREATE POLICY`.\n *\n * `using` and `withCheck` are SQL text you provide (not escaped, never build them from user input) or a where object, whose values are rendered as escaped literals. Session variables set with the `settings` transaction option work in conditions: `\"tenant_id = current_setting('app.tenant_id')::int\"`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Policy name.\n * @param options - `command`, `kind`, `roles`, `using`, `withCheck` and query options.\n * @throws Error for an unknown `command` or `kind`, empty `roles` or an empty condition.\n *\n * @example\n * ```ts\n * await queryInterface.createPolicy('documents', 'tenant_isolation', {\n * roles: ['app_user'],\n * using: \"tenant_id = current_setting('app.tenant_id')::int\",\n * withCheck: \"tenant_id = current_setting('app.tenant_id')::int\",\n * });\n * ```\n */\n async createPolicy(\n table: TableName,\n name: string,\n options: CreatePolicyOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#policies.create(table, name, options);\n }\n\n /**\n * Changes a policy with `ALTER POLICY`: roles, conditions and name (`rename`, applied last).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Current policy name.\n * @param options - Changes (at least one) and query options.\n * @throws Error when no change is given.\n *\n * @example\n * ```ts\n * await queryInterface.alterPolicy('documents', 'tenant_isolation', { roles: ['app_user', 'app_admin'] });\n * ```\n */\n async alterPolicy(\n table: TableName,\n name: string,\n options: AlterPolicyOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#policies.alter(table, name, options);\n }\n\n /**\n * Drops a policy with `DROP POLICY`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Policy name.\n * @param options - `ifExists`, `cascade` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropPolicy('documents', 'tenant_isolation', { ifExists: true });\n * ```\n */\n async dropPolicy(\n table: TableName,\n name: string,\n options: DropPolicyOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#policies.drop(table, name, options);\n }\n}\n","import type { CreatePartitionOptions, DetachPartitionOptions } from '../ddl/partition-ddl.ts';\nimport type { PartitionBoundSpec } from '../ddl/partition-types.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { PartitionCommands } from './partition-commands.ts';\nimport { QueryInterfacePolicies } from './query-interface-policies.ts';\nimport { StatementRunner } from './statement-runner.ts';\n\n/**\n * Declarative partitioning part of {@link QueryInterface}.\n */\nexport class QueryInterfacePartitions extends QueryInterfacePolicies {\n readonly #partitions: PartitionCommands;\n\n /**\n * @param sequelize - Owning `Sequelize` instance.\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n this.#partitions = new PartitionCommands(new StatementRunner(sequelize));\n }\n\n /**\n * Creates a partition of a partitioned table (`CREATE TABLE ... PARTITION OF`). The partitioned parent comes from `createTable` with `partitionBy`.\n *\n * @param parent - Partitioned table name or `{ tableName, schema }`.\n * @param partition - New partition name or `{ tableName, schema }`.\n * @param bound - `{ in }` (list), `{ from, to }` (range), `{ modulus, remainder }` (hash) or `{ default: true }`; values are rendered as literals.\n * @param options - `partitionBy` (sub-partitioning), `ifNotExists` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.createTable('events', { at: DataTypes.DATE }, {\n * partitionBy: { strategy: 'range', columns: ['at'] },\n * });\n * await queryInterface.createPartition('events', 'events_2026', {\n * from: ['2026-01-01'],\n * to: ['2027-01-01'],\n * });\n * ```\n * @see [Constraints and indexes guide](/guide/constraints-indexes)\n */\n async createPartition(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options: CreatePartitionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#partitions.create(parent, partition, bound, options);\n }\n\n /**\n * Attaches an existing table as a partition (`ALTER TABLE ... ATTACH PARTITION`). PostgreSQL scans the table to check the bounds unless a matching `CHECK` constraint exists.\n *\n * @param parent - Partitioned table name or `{ tableName, schema }`.\n * @param partition - Existing table name or `{ tableName, schema }`.\n * @param bound - Partition bounds, see {@link QueryInterface.createPartition}.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.attachPartition('events', 'events_2027', {\n * from: ['2027-01-01'],\n * to: ['2028-01-01'],\n * });\n * ```\n */\n async attachPartition(\n parent: TableName,\n partition: TableName,\n bound: PartitionBoundSpec,\n options: QueryOptionsBase = {},\n ): Promise<void> {\n await this.#partitions.attach(parent, partition, bound, options);\n }\n\n /**\n * Detaches a partition, keeping it as a standalone table (`ALTER TABLE ... DETACH PARTITION`).\n *\n * @param parent - Partitioned table name or `{ tableName, schema }`.\n * @param partition - Partition name or `{ tableName, schema }`.\n * @param options - `concurrently` (PostgreSQL 14+, not inside a transaction), `finalize` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.detachPartition('events', 'events_2026', { concurrently: true });\n * ```\n */\n async detachPartition(\n parent: TableName,\n partition: TableName,\n options: DetachPartitionOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#partitions.detach(parent, partition, options);\n }\n}\n","import type { DataTypeInput } from '../data-types/data-types.ts';\nimport type { ConstraintOptions, IndexField, IndexOptions } from '../ddl/ddl-generator.ts';\nimport type { TableName } from '../ddl/sql-literal.ts';\nimport type { AttributeOptions } from '../model/model-definition.ts';\nimport type { QueryOptionsBase, RuntimeOwner } from '../model/runtime.ts';\nimport { BulkData } from './bulk-data.ts';\nimport { ColumnCommands } from './column-commands.ts';\nimport { EnumCommands } from './enum-commands.ts';\nimport { IndexCommands } from './index-commands.ts';\nimport { QueryInterfacePartitions } from './query-interface-partitions.ts';\nimport { StatementRunner } from './statement-runner.ts';\n\nexport type {\n ColumnDescription,\n CreateTableOptions,\n DropTableOptions,\n ForeignKeyReference,\n} from './query-interface-types.ts';\n\n/**\n * Schema manipulation API (Sequelize v6 `QueryInterface`) for PostgreSQL. Used by `sync()` and by\n * migrations (`sequelize-cli`, umzug). Obtain the instance with {@link Sequelize.getQueryInterface}.\n * Table names are `string` or `{ tableName, schema }`; identifiers are always quoted and values bound or\n * escaped, never concatenated raw.\n *\n * @example\n * ```ts\n * const queryInterface = sequelize.getQueryInterface();\n * await queryInterface.createTable('users', {\n * id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },\n * name: { type: DataTypes.STRING, allowNull: false },\n * });\n * await queryInterface.addIndex('users', ['name'], { unique: true });\n * ```\n * @see [Schema guide](/guide/schema)\n */\nexport class QueryInterface extends QueryInterfacePartitions {\n readonly #columns: ColumnCommands;\n readonly #indexes: IndexCommands;\n readonly #enums: EnumCommands;\n readonly #bulk: BulkData;\n\n /**\n * Creates the schema API bound to a `Sequelize` instance; prefer {@link Sequelize.getQueryInterface}.\n *\n * @param sequelize - Owning `Sequelize` instance.\n * @example\n * ```ts\n * const api = new QueryInterface(sequelize);\n * await api.showAllTables();\n * ```\n */\n constructor(sequelize: RuntimeOwner) {\n super(sequelize);\n const runner = new StatementRunner(sequelize);\n this.#columns = new ColumnCommands(runner);\n this.#indexes = new IndexCommands(runner);\n this.#enums = new EnumCommands(runner);\n this.#bulk = new BulkData(runner);\n }\n\n /**\n * Adds a column with `ALTER TABLE ... ADD COLUMN`; a plain data type or a full attribute definition (nullability, default, references, ...) is accepted.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param attribute - Column definition.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.addColumn('users', 'nickname', { type: DataTypes.STRING, allowNull: true });\n * ```\n */\n async addColumn(\n table: TableName,\n column: string,\n attribute: DataTypeInput | AttributeOptions,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#columns.addColumn(table, column, attribute, options);\n }\n\n /**\n * Drops a column with `ALTER TABLE ... DROP COLUMN`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.removeColumn('users', 'nickname');\n * ```\n */\n async removeColumn(table: TableName, column: string, options?: QueryOptionsBase): Promise<void> {\n await this.#columns.removeColumn(table, column, options);\n }\n\n /**\n * Alters the type, nullability, default and comment of an existing column in one go.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param column - Column name.\n * @param attribute - New column definition.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.changeColumn('users', 'name', { type: DataTypes.STRING(100), allowNull: false });\n * ```\n */\n async changeColumn(\n table: TableName,\n column: string,\n attribute: DataTypeInput | AttributeOptions,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#columns.changeColumn(table, column, attribute, options);\n }\n\n /**\n * Renames a column with `ALTER TABLE ... RENAME COLUMN`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param before - Current column name.\n * @param after - New column name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.renameColumn('users', 'name', 'full_name');\n * ```\n */\n async renameColumn(\n table: TableName,\n before: string,\n after: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#columns.renameColumn(table, before, after, options);\n }\n\n /**\n * Creates an index on a table, optionally unique, partial, covering or `CONCURRENTLY`.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param fieldsOrOptions - Indexed fields or index options.\n * @param options - Index options when fields are given separately.\n *\n * @example\n * ```ts\n * await queryInterface.addIndex('users', ['email'], { unique: true, name: 'users_email_unique' });\n * await queryInterface.addIndex('users', {\n * name: 'users_lower_email',\n * fields: [{ expression: 'lower(email)', nulls: 'LAST' }],\n * });\n * ```\n */\n async addIndex(\n table: TableName,\n fieldsOrOptions: readonly IndexField[] | IndexOptions,\n options: IndexOptions & QueryOptionsBase = {},\n ): Promise<void> {\n await this.#indexes.addIndex(table, fieldsOrOptions, options);\n }\n\n /**\n * Drops an index identified by name, or by the fields it was created on (the default generated name is derived from them).\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param nameOrFields - Index name or indexed fields.\n * @param options - `concurrently` and query options.\n *\n * @example\n * ```ts\n * await queryInterface.removeIndex('users', 'users_email_unique');\n * ```\n */\n async removeIndex(\n table: TableName,\n nameOrFields: string | readonly IndexField[],\n options: QueryOptionsBase & Readonly<{ concurrently?: boolean }> = {},\n ): Promise<void> {\n await this.#indexes.removeIndex(table, nameOrFields, options);\n }\n\n /**\n * Adds a `CHECK`, `UNIQUE`, `PRIMARY KEY`, `FOREIGN KEY` or `EXCLUDE` constraint to a table.\n * `notValid: true` skips checking existing rows (check and foreign key); validate later with\n * {@link QueryInterface.validateConstraint}.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param options - Constraint definition.\n *\n * @example\n * ```ts\n * await queryInterface.addConstraint('products', {\n * type: 'check',\n * fields: ['price'],\n * name: 'products_price_positive',\n * where: { price: { [Op.gt]: 0 } },\n * });\n * await queryInterface.addConstraint('bookings', {\n * type: 'exclude',\n * name: 'bookings_no_overlap',\n * using: 'gist',\n * exclude: [\n * { name: 'room', with: '=' },\n * { expression: 'tstzrange(starts, ends)', with: '&&' },\n * ],\n * });\n * ```\n */\n async addConstraint(\n table: TableName,\n options: ConstraintOptions & QueryOptionsBase,\n ): Promise<void> {\n await this.#indexes.addConstraint(table, options);\n }\n\n /**\n * Validates a constraint added with `notValid: true`, scanning existing rows without blocking writes.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.addConstraint('products', {\n * type: 'check',\n * name: 'products_price_positive',\n * where: { price: { [Op.gt]: 0 } },\n * notValid: true,\n * });\n * await queryInterface.validateConstraint('products', 'products_price_positive');\n * ```\n */\n async validateConstraint(\n table: TableName,\n name: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#indexes.validateConstraint(table, name, options);\n }\n\n /**\n * Drops a named constraint from a table.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param name - Constraint name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.removeConstraint('products', 'products_price_positive');\n * ```\n */\n async removeConstraint(\n table: TableName,\n name: string,\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#indexes.removeConstraint(table, name, options);\n }\n\n /**\n * Runs `DROP TYPE IF EXISTS` for an enum type.\n *\n * @param name - Enum type name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropEnum('enum_users_role');\n * ```\n */\n async dropEnum(name: string, options?: QueryOptionsBase): Promise<void> {\n await this.#enums.dropEnum(name, options);\n }\n\n /**\n * Drops every enum type of the current schema with `CASCADE`, which also drops dependent columns' defaults. Destructive.\n *\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await queryInterface.dropAllEnums();\n * ```\n */\n async dropAllEnums(options?: QueryOptionsBase): Promise<void> {\n await this.#enums.dropAllEnums(options);\n }\n\n /** @internal */\n async dropEnumsOf(\n table: TableName,\n fields: readonly string[],\n options?: QueryOptionsBase,\n ): Promise<void> {\n await this.#enums.dropEnumsOf(table, fields, options);\n }\n\n /**\n * Inserts several rows with one `INSERT` (used by seeders). Values are bound as parameters.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param records - Rows keyed by column name.\n * @param options - Query options.\n * @returns Number of inserted rows.\n *\n * @example\n * ```ts\n * const inserted = await queryInterface.bulkInsert('users', [\n * { name: 'Ada', email: 'ada@example.com' },\n * { name: 'Alan', email: 'alan@example.com' },\n * ]);\n * ```\n */\n async bulkInsert(\n table: TableName,\n records: readonly Readonly<Record<string, unknown>>[],\n options: QueryOptionsBase = {},\n ): Promise<number> {\n return await this.#bulk.bulkInsert(table, records, options);\n }\n\n /**\n * Updates every row matching a where object with one `UPDATE`, without model hooks or validation.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param values - New column values.\n * @param where - Filter (where object keyed by column).\n * @param options - Query options.\n * @returns Number of updated rows.\n *\n * @example\n * ```ts\n * const updated = await queryInterface.bulkUpdate('users', { active: false }, { name: 'Ada' });\n * ```\n */\n async bulkUpdate(\n table: TableName,\n values: Readonly<Record<string, unknown>>,\n where: unknown,\n options: QueryOptionsBase = {},\n ): Promise<number> {\n return await this.#bulk.bulkUpdate(table, values, where, options);\n }\n\n /**\n * Deletes every row matching a where object with one `DELETE`, without model hooks.\n *\n * @param table - Table name or `{ tableName, schema }`.\n * @param where - Filter (where object keyed by column); empty deletes all rows.\n * @param options - Query options.\n * @returns Number of deleted rows.\n *\n * @example\n * ```ts\n * const removed = await queryInterface.bulkDelete('users', { active: false });\n * ```\n */\n async bulkDelete(\n table: TableName,\n where: unknown = {},\n options: QueryOptionsBase = {},\n ): Promise<number> {\n return await this.#bulk.bulkDelete(table, where, options);\n }\n}\n","import type { PgErrorMapper } from '../errors/map-pg-error.ts';\nimport { CopyFromStdin } from './copy-from-stdin.ts';\nimport { CopyToStdout } from './copy-to-stdout.ts';\nimport type { Client, ExecuteOptions } from './connection-types.ts';\nimport type { QueryLogger } from './query-logger.ts';\n\ntype Submit<T> = Readonly<{ query: (submittable: T) => unknown }>;\n\n/** Runs `COPY ... FROM STDIN` and `COPY ... TO STDOUT` on a writer connection. */\nexport class CopyRunner {\n readonly #acquire: () => Promise<Client>;\n readonly #logger: QueryLogger;\n readonly #errors: PgErrorMapper;\n\n /**\n * @param acquire - Acquires a writer connection.\n * @param logger - Logger of executed statements.\n * @param errors - Driver error mapper.\n */\n constructor(acquire: () => Promise<Client>, logger: QueryLogger, errors: PgErrorMapper) {\n this.#acquire = acquire;\n this.#logger = logger;\n this.#errors = errors;\n }\n\n /**\n * Streams `lines` into `COPY ... FROM STDIN`.\n *\n * @param text - `COPY ... FROM STDIN` statement.\n * @param lines - Encoded rows.\n * @param options - Client and logging settings.\n * @returns Copied row count.\n */\n async from(text: string, lines: AsyncIterable<string>, options: ExecuteOptions): Promise<number> {\n const client = options.client ?? (await this.#acquire());\n try {\n return await this.#copyIn(client, text, lines, options);\n } finally {\n if (options.client === undefined) {\n client.release();\n }\n }\n }\n\n /**\n * Runs `COPY ... TO STDOUT` and yields the output chunks.\n *\n * @param text - `COPY ... TO STDOUT` statement.\n * @param options - Client and logging settings.\n * @returns Async iterator of output chunks.\n */\n async *to(text: string, options: ExecuteOptions): AsyncGenerator<Buffer, void, undefined> {\n const client = options.client ?? (await this.#acquire());\n try {\n yield* this.#copyOut(client, text, options);\n } catch (error) {\n throw this.#errors.mapQueryError(error, { sql: text, parameters: [] });\n } finally {\n if (options.client === undefined) {\n client.release();\n }\n }\n }\n\n async #copyIn(\n client: Client,\n text: string,\n lines: AsyncIterable<string>,\n options: ExecuteOptions,\n ): Promise<number> {\n const started = performance.now();\n const copy = new CopyFromStdin(text, lines);\n const done = copy.done();\n try {\n void (client as unknown as Submit<CopyFromStdin>).query(copy);\n const rowCount = await done;\n this.#logger.log({ text, values: [] }, options, performance.now() - started);\n return rowCount;\n } catch (error) {\n throw this.#errors.mapQueryError(error, { sql: text, parameters: [] });\n } finally {\n await copy.settled();\n }\n }\n\n async *#copyOut(\n client: Client,\n text: string,\n options: ExecuteOptions,\n ): AsyncGenerator<Buffer, void, undefined> {\n const started = performance.now();\n const copy = new CopyToStdout(text);\n void (client as unknown as Submit<CopyToStdout>).query(copy);\n let completed = false;\n try {\n yield* copy.chunks();\n await copy.done();\n completed = true;\n this.#logger.log({ text, values: [] }, options, performance.now() - started);\n } finally {\n if (!completed) {\n await CopyRunner.#discard(copy);\n }\n }\n }\n\n static async #discard(copy: CopyToStdout): Promise<void> {\n copy.discard();\n await copy.done().catch(() => undefined);\n }\n}\n","/** Chooses the pool a query runs on: the writer, or the next read replica in round-robin order. */\nexport class ReplicaRouter<P> {\n /** Writer pool. */\n readonly writer: P;\n /** Read replica pools (may be empty). */\n readonly readers: readonly P[];\n #next = 0;\n\n /**\n * @param writer - Writer pool.\n * @param readers - Read replica pools.\n */\n constructor(writer: P, readers: readonly P[]) {\n this.writer = writer;\n this.readers = readers;\n }\n\n /**\n * Pool for a query.\n *\n * @param route - `'read'` to use a replica when one is configured; anything else uses the writer.\n * @returns Chosen pool.\n */\n pool(route: 'read' | 'write' | undefined): P {\n const readers = this.readers;\n if (route !== 'read' || readers.length === 0) {\n return this.writer;\n }\n const reader = readers[this.#next % readers.length] ?? this.writer;\n this.#next += 1;\n return reader;\n }\n}\n","import type { Client } from './connection-types.ts';\n\nconst SET = 'SELECT set_config($1, $2, true)';\n\n/**\n * Per-query `statement_timeout`: applied with `set_config(..., true)`, so the value is transaction-local\n * and never reaches a pooled connection. The timeout value is a validated integer and is bound.\n */\nexport class StatementTimeout {\n /**\n * Runs `work` with `statement_timeout` set to `milliseconds`.\n *\n * Outside a transaction the work runs in its own `BEGIN … COMMIT` on the client. Inside one the previous\n * value is restored afterwards, so later statements of the transaction keep their timeout.\n *\n * @param client - Connection the work runs on.\n * @param inTransaction - Whether `client` already holds a transaction.\n * @param milliseconds - Timeout; `0` disables it.\n * @param work - The query to run.\n * @returns The result of `work`.\n * @throws Error when `milliseconds` is not a non-negative integer.\n */\n async run<T>(\n client: Pick<Client, 'query'>,\n inTransaction: boolean,\n milliseconds: number,\n work: () => Promise<T>,\n ): Promise<T> {\n if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) {\n throw new Error(\n `statementTimeout must be a non-negative integer, got ${String(milliseconds)}`,\n );\n }\n return inTransaction\n ? this.#inTransaction(client, milliseconds, work)\n : this.#alone(client, milliseconds, work);\n }\n\n async #inTransaction<T>(\n client: Pick<Client, 'query'>,\n milliseconds: number,\n work: () => Promise<T>,\n ): Promise<T> {\n const previous = await client.query({\n text: \"SELECT current_setting('statement_timeout') AS value\",\n });\n await StatementTimeout.#set(client, String(milliseconds));\n try {\n return await work();\n } finally {\n const value = (previous.rows[0] as { value: string } | undefined)?.value ?? '0';\n await StatementTimeout.#set(client, value).catch(() => undefined);\n }\n }\n\n async #alone<T>(\n client: Pick<Client, 'query'>,\n milliseconds: number,\n work: () => Promise<T>,\n ): Promise<T> {\n await client.query({ text: 'BEGIN' });\n try {\n await StatementTimeout.#set(client, String(milliseconds));\n const result = await work();\n await client.query({ text: 'COMMIT' });\n return result;\n } catch (error) {\n await client.query({ text: 'ROLLBACK' }).catch(() => undefined);\n throw error;\n }\n }\n\n static #set(client: Pick<Client, 'query'>, value: string): Promise<unknown> {\n return client.query({ text: SET, values: ['statement_timeout', value] });\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { QueryResultRow } from 'pg';\nimport type { CompiledQuery } from '../sql/compile.ts';\nimport type { StatementCacheOptions } from './options.ts';\n\n/** Minimal client surface the cache needs: the `pg` `query` overload with a config object. */\nexport type StatementClient = Readonly<{\n query: (config: {\n name?: string;\n text: string;\n values: unknown[];\n }) => Promise<{ rows: QueryResultRow[]; rowCount: number | null; command: string }>;\n}>;\n\nconst DEFAULT_MAX = 100;\nconst MAX_TEXT_LENGTH = 8192;\nconst NAMEABLE = /^\\s*(?:select|insert|update|delete|with)\\b/i;\nconst STALE_PLAN = /cached plan must not change result type/i;\n\ntype Entries = Map<string, string | null>;\n\n/**\n * Opt-in named prepared statements (ADR-023): names eligible statements `pgz_<hash of the SQL text>` so\n * PostgreSQL parses and plans them once per connection. Bounded per connection, never evicts.\n */\nexport class StatementCache {\n readonly #max: number;\n readonly #entries = new WeakMap<object, Entries>();\n\n /**\n * @param options - `true` for defaults, or `{ max }` statements per connection.\n * @throws Error when `max` is not a positive integer.\n */\n constructor(options: true | StatementCacheOptions) {\n const max = options === true ? undefined : options.max;\n if (max !== undefined && (!Number.isInteger(max) || max < 1)) {\n throw new Error(`statementCache.max must be a positive integer, got ${String(max)}`);\n }\n this.#max = max ?? DEFAULT_MAX;\n }\n\n /**\n * Runs a query on `client`, as a named statement when it is eligible.\n *\n * @param client - Connection to run on.\n * @param query - Compiled query.\n * @param retryable - Whether a stale-plan failure may be retried unnamed (false inside a transaction).\n * @returns The driver result.\n */\n async run(\n client: StatementClient,\n query: CompiledQuery,\n retryable: boolean,\n ): ReturnType<StatementClient['query']> {\n const entries = this.#entriesOf(client);\n const name = this.#name(entries, query.text);\n const values = query.values as unknown[];\n if (name === undefined) {\n return client.query({ text: query.text, values });\n }\n try {\n const result = await client.query({ name, text: query.text, values });\n entries.set(name, query.text);\n return result;\n } catch (error) {\n return StatementCache.#recover(client, query, { entries, name, retryable }, error);\n }\n }\n\n // A stale plan poisons the name on this connection: the server keeps the old statement, so the\n // text stays unnamed from now on.\n static async #recover(\n client: StatementClient,\n query: CompiledQuery,\n state: Readonly<{ entries: Entries; name: string; retryable: boolean }>,\n error: unknown,\n ): ReturnType<StatementClient['query']> {\n if (!STALE_PLAN.test(error instanceof Error ? error.message : '')) {\n throw error;\n }\n state.entries.set(state.name, null);\n if (!state.retryable) {\n throw error;\n }\n return client.query({ text: query.text, values: query.values as unknown[] });\n }\n\n #entriesOf(client: object): Entries {\n let entries = this.#entries.get(client);\n if (entries === undefined) {\n entries = new Map();\n this.#entries.set(client, entries);\n }\n return entries;\n }\n\n #name(entries: Entries, text: string): string | undefined {\n if (text.length > MAX_TEXT_LENGTH || text.includes(';') || !NAMEABLE.test(text)) {\n return undefined;\n }\n const name = `pgz_${createHash('sha256').update(text).digest('hex').slice(0, 16)}`;\n if (!entries.has(name)) {\n return entries.size < this.#max ? name : undefined;\n }\n return entries.get(name) === text ? name : undefined;\n }\n}\n","import { Client as PgClient, Pool, types, type PoolClient, type PoolConfig } from 'pg';\nimport { CopyRunner } from './copy-runner.ts';\nimport type { Client, ExecuteOptions, QueryResult } from './connection-types.ts';\nimport { ConnectionAcquireTimeoutError } from '../errors/errors.ts';\nimport type { PgErrorMapper } from '../errors/map-pg-error.ts';\nimport type { CompiledQuery } from '../sql/compile.ts';\nimport type { QueryLogger } from './query-logger.ts';\nimport { ReplicaRouter } from './replica-router.ts';\nimport { StatementTimeout } from './statement-timeout.ts';\nimport { StatementCache, type StatementClient } from './statement-cache.ts';\nimport type { StatementCacheOptions } from './options.ts';\n\nexport type { Client, ExecuteOptions, QueryResult } from './connection-types.ts';\n\nconst DATE_OID = 1082;\nconst INTERVAL_OID = 1186;\nconst RAW_TEXT_OIDS: ReadonlySet<number> = new Set([DATE_OID, INTERVAL_OID]);\n\nconst typeParsers: NonNullable<PoolConfig['types']> = {\n getTypeParser: ((oid: number, format?: 'text' | 'binary') =>\n RAW_TEXT_OIDS.has(oid) && format !== 'binary'\n ? (value: string) => value\n : types.getTypeParser(oid, format)) as NonNullable<PoolConfig['types']>['getTypeParser'],\n};\n\n/**\n * Owner of the `pg` pools of a `Sequelize` instance: runs queries (mapping driver errors to Sequelize v6\n * error classes), acquires clients for transactions, streams COPY data and closes the pools.\n */\nexport class ConnectionManager {\n readonly #config: PoolConfig;\n readonly #router: ReplicaRouter<Pool>;\n readonly #logger: QueryLogger;\n readonly #errors: PgErrorMapper;\n readonly #copies: CopyRunner;\n readonly #statements: StatementCache | undefined;\n readonly #timeouts = new StatementTimeout();\n\n /**\n * @param config - Writer pool configuration.\n * @param readConfigs - Read replica pool configurations.\n * @param logger - Logger of executed statements.\n * @param errors - Driver error mapper.\n * @param statementCache - Named prepared statement settings; unnamed statements when absent.\n */\n constructor(\n config: PoolConfig,\n readConfigs: readonly PoolConfig[],\n logger: QueryLogger,\n errors: PgErrorMapper,\n statementCache?: boolean | StatementCacheOptions,\n ) {\n this.#config = config;\n this.#logger = logger;\n this.#errors = errors;\n this.#statements =\n statementCache === undefined || statementCache === false\n ? undefined\n : new StatementCache(statementCache);\n this.#copies = new CopyRunner(() => this.acquire(), logger, errors);\n this.#router = new ReplicaRouter(\n ConnectionManager.#pool(config),\n readConfigs.map((readConfig) => ConnectionManager.#pool(readConfig)),\n );\n }\n\n /**\n * Runs a compiled query and maps driver errors to Sequelize v6 error classes.\n *\n * @param query - Query text and parameters.\n * @param options - Client, route and logging settings.\n * @returns Rows, row count and command.\n */\n async execute(query: CompiledQuery, options: ExecuteOptions = {}): Promise<QueryResult> {\n const client = options.client ?? (await this.#acquire(this.#router.pool(options.route)));\n const logged = this.#logger.enabled(options);\n const started = logged ? performance.now() : 0;\n try {\n const result = await this.#send(client, query, options);\n if (logged) {\n this.#logger.log(query, options, performance.now() - started);\n }\n return { rows: result.rows, rowCount: result.rowCount ?? 0, command: result.command };\n } catch (error) {\n throw this.#errors.mapQueryError(error, { sql: query.text, parameters: query.values });\n } finally {\n if (options.client === undefined) {\n client.release();\n }\n }\n }\n\n /**\n * Acquires a writer connection (e.g. for a transaction); release it when done.\n *\n * @returns Pooled client.\n */\n acquire(): Promise<Client> {\n return this.#acquire(this.#router.writer);\n }\n\n /**\n * Streams `lines` into `COPY ... FROM STDIN`.\n *\n * @param text - `COPY ... FROM STDIN` statement.\n * @param lines - Encoded rows.\n * @param options - Client and logging settings.\n * @returns Copied row count.\n */\n async copyFrom(\n text: string,\n lines: AsyncIterable<string>,\n options: ExecuteOptions = {},\n ): Promise<number> {\n return this.#copies.from(text, lines, options);\n }\n\n /**\n * Runs `COPY ... TO STDOUT` and yields the output chunks.\n *\n * @param text - `COPY ... TO STDOUT` statement.\n * @param options - Client and logging settings.\n * @returns Async iterator of output chunks.\n */\n async *copyTo(\n text: string,\n options: ExecuteOptions = {},\n ): AsyncGenerator<Buffer, void, undefined> {\n yield* this.#copies.to(text, options);\n }\n\n /**\n * Opens a dedicated (non-pooled) client, e.g. for LISTEN.\n *\n * @returns Connected client.\n */\n async dedicated(): Promise<PgClient> {\n const client = new PgClient({ ...this.#config, types: typeParsers });\n try {\n await client.connect();\n } catch (error) {\n throw this.#errors.mapConnectionError(error);\n }\n return client;\n }\n\n /**\n * Closes the writer and reader pools.\n *\n * @returns Resolves when all pools are closed.\n */\n async close(): Promise<void> {\n await Promise.all([\n this.#router.writer.end(),\n ...this.#router.readers.map((reader) => reader.end()),\n ]);\n }\n\n #send(\n client: Client,\n query: CompiledQuery,\n options: ExecuteOptions,\n ): ReturnType<StatementClient['query']> {\n const run = (): ReturnType<StatementClient['query']> =>\n this.#statements === undefined\n ? client.query({ text: query.text, values: query.values as unknown[] })\n : this.#statements.run(client, query, options.client === undefined);\n return options.statementTimeout === undefined\n ? run()\n : this.#timeouts.run(client, options.client !== undefined, options.statementTimeout, run);\n }\n\n async #acquire(pool: Pool): Promise<PoolClient> {\n try {\n return ConnectionManager.#guard(await pool.connect());\n } catch (error) {\n throw ConnectionManager.#isAcquireTimeout(error)\n ? new ConnectionAcquireTimeoutError(\n error instanceof Error ? error : new Error(String(error)),\n )\n : this.#errors.mapConnectionError(error);\n }\n }\n\n static #guard(client: PoolClient): PoolClient {\n let broken: Error | undefined;\n const onError = (error: Error): void => {\n broken = error;\n };\n client.on('error', onError);\n const release = client.release.bind(client);\n client.release = (error?: Error | boolean): void => {\n client.removeListener('error', onError);\n release(error ?? broken);\n };\n return client;\n }\n\n static #pool(config: PoolConfig): Pool {\n const pool = new Pool({ ...config, types: typeParsers });\n pool.on('error', () => {});\n return pool;\n }\n\n static #isAcquireTimeout(error: unknown): boolean {\n return error instanceof Error && /timeout exceeded when trying to connect/i.test(error.message);\n }\n}\n","import type { Client as PgClient } from 'pg';\nimport { SqlCompiler } from '../sql/compile.ts';\n\n/** Handler of `LISTEN` notifications. */\nexport type NotificationHandler = (payload: string | undefined, channel: string) => unknown;\n\nconst RECONNECT_DELAY_MS = 1000;\n\n/**\n * Dedicated LISTEN connection shared by all subscriptions of a Sequelize instance: opened lazily and\n * re-subscribed after connection loss.\n */\nexport class NotificationListener {\n readonly #connect: () => Promise<PgClient>;\n readonly #handlers = new Map<string, Set<NotificationHandler>>();\n #client: Promise<PgClient> | undefined;\n #closed = false;\n\n /**\n * @param connect - Opens a dedicated client.\n */\n constructor(connect: () => Promise<PgClient>) {\n this.#connect = connect;\n }\n\n /**\n * Subscribes `handler` to a channel.\n *\n * @param channel - Channel name.\n * @param handler - Called with the payload and the channel.\n * @returns Function that unsubscribes the handler.\n */\n async listen(channel: string, handler: NotificationHandler): Promise<() => Promise<void>> {\n const existing = this.#handlers.get(channel);\n if (existing === undefined) {\n this.#handlers.set(channel, new Set([handler]));\n const client = await this.#open();\n await client.query(`LISTEN ${SqlCompiler.quoteIdent(channel)}`);\n } else {\n existing.add(handler);\n await this.#open();\n }\n return async () => {\n const handlers = this.#handlers.get(channel);\n handlers?.delete(handler);\n if (handlers !== undefined && handlers.size === 0) {\n this.#handlers.delete(channel);\n const client = await this.#client;\n await client?.query(`UNLISTEN ${SqlCompiler.quoteIdent(channel)}`);\n }\n };\n }\n\n /**\n * Removes all subscriptions and closes the connection.\n *\n * @returns Resolves when closed.\n */\n async close(): Promise<void> {\n this.#closed = true;\n this.#handlers.clear();\n const client = await this.#client?.catch(() => undefined);\n this.#client = undefined;\n await client?.end();\n }\n\n #dispatch(message: Readonly<{ channel: string; payload?: string }>): void {\n this.#handlers.get(message.channel)?.forEach((handler) => {\n void Promise.resolve()\n .then(() => handler(message.payload, message.channel))\n .catch(() => undefined);\n });\n }\n\n #open(): Promise<PgClient> {\n if (this.#client !== undefined) {\n return this.#client;\n }\n const opening = this.#connect().then((client) => this.#attach(client));\n this.#client = opening;\n opening.catch(() => {\n if (this.#client === opening) {\n this.#client = undefined;\n }\n });\n return opening;\n }\n\n async #attach(client: PgClient): Promise<PgClient> {\n client.on('notification', (message) => this.#dispatch(message));\n client.on('error', () => undefined);\n client.on('end', () => {\n this.#client = undefined;\n if (!this.#closed && this.#handlers.size > 0) {\n setTimeout(() => void this.#resubscribe(), RECONNECT_DELAY_MS);\n }\n });\n await [...this.#handlers.keys()].reduce<Promise<unknown>>(\n (previous, channel) =>\n previous.then(() => client.query(`LISTEN ${SqlCompiler.quoteIdent(channel)}`)),\n Promise.resolve(),\n );\n return client;\n }\n\n async #resubscribe(): Promise<void> {\n if (!this.#closed) {\n await this.#open().catch(() => {\n setTimeout(() => void this.#resubscribe(), RECONNECT_DELAY_MS);\n });\n }\n }\n}\n","import type { CompiledQuery } from '../sql/compile.ts';\nimport type { LoggingFunction } from './options.ts';\n\n/** Logging settings: instance defaults or per-query overrides. */\nexport type QueryLogSettings = Readonly<{\n /** SQL logger, or `false` to disable. */\n logging?: LoggingFunction | false;\n /** Pass the query duration to the logger. */\n benchmark?: boolean;\n /** Transaction id shown in the log line. */\n transactionId?: string;\n}>;\n\n/** Writes executed SQL to the configured logger (Sequelize v6 `logging` / `benchmark` output). */\nexport class QueryLogger {\n readonly #defaults: QueryLogSettings;\n\n /**\n * Logger for the `logging` / `benchmark` constructor options (`console.log` when `logging` is unset).\n *\n * @param options - Instance-level options.\n * @returns Logger.\n */\n static fromOptions(options: QueryLogSettings): QueryLogger {\n return new QueryLogger({\n logging: options.logging === undefined ? console.log : options.logging,\n ...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),\n });\n }\n\n /**\n * @param defaults - Instance-level `logging` and `benchmark` settings.\n */\n constructor(defaults: QueryLogSettings) {\n this.#defaults = defaults;\n }\n\n /**\n * Whether a statement run with these settings is logged, so callers can skip timing it.\n *\n * @param options - Per-query settings overriding the defaults.\n * @returns True when a logger is configured.\n */\n enabled(options: QueryLogSettings): boolean {\n const logging = options.logging ?? this.#defaults.logging;\n return logging !== false && logging !== undefined;\n }\n\n /**\n * Logs one executed statement.\n *\n * @param query - Executed query.\n * @param options - Per-query settings overriding the defaults.\n * @param elapsed - Duration in milliseconds.\n */\n log(query: CompiledQuery, options: QueryLogSettings, elapsed: number): void {\n const logging = options.logging ?? this.#defaults.logging;\n if (logging === false || logging === undefined) {\n return;\n }\n const sql = `Executing (${options.transactionId ?? 'default'}): ${query.text}`;\n if (options.benchmark ?? this.#defaults.benchmark) {\n logging(sql.replace('Executing', 'Executed'), elapsed);\n } else {\n logging(sql, { bind: query.values });\n }\n }\n}\n","import {\n AccessDeniedError,\n BaseError,\n ConnectionError,\n ConnectionRefusedError,\n ConnectionTimedOutError,\n DatabaseError,\n ExclusionConstraintError,\n ForeignKeyConstraintError,\n HostNotFoundError,\n HostNotReachableError,\n InvalidConnectionError,\n TimeoutError,\n UniqueConstraintError,\n ValidationErrorItem,\n type DriverError,\n type QueryErrorContext,\n} from './errors.ts';\n\nconst KEY_DETAIL = /Key \\((.*?)\\)=\\((.*?)\\)/;\n\nconst CONNECTION_CODES: ReadonlyMap<string, new (parent: Error) => ConnectionError> = new Map<\n string,\n new (parent: Error) => ConnectionError\n>([\n ['ECONNREFUSED', ConnectionRefusedError],\n ['ENOTFOUND', HostNotFoundError],\n ['EAI_AGAIN', HostNotFoundError],\n ['EHOSTUNREACH', HostNotReachableError],\n ['EINVAL', InvalidConnectionError],\n ['ETIMEDOUT', ConnectionTimedOutError],\n ['28P01', AccessDeniedError],\n ['28000', AccessDeniedError],\n]);\n\n/** Maps `pg` driver errors to the matching Sequelize v6 error classes. */\nexport class PgErrorMapper {\n /**\n * Parses `Key (a, b)=(1, 2)` from a PostgreSQL error detail into `{ a: '1', b: '2' }`.\n *\n * @param detail - `detail` of the driver error.\n * @returns Key values by column, or `undefined` when the detail has no key.\n */\n parseKeyDetail(detail: string | undefined): Readonly<Record<string, string>> | undefined {\n const match = detail === undefined ? null : KEY_DETAIL.exec(detail);\n if (match === null) {\n return undefined;\n }\n const keys = PgErrorMapper.#splitList(match[1] ?? '');\n const values = PgErrorMapper.#splitList(match[2] ?? '');\n return Object.fromEntries(keys.map((key, index) => [key, values[index] ?? '']));\n }\n\n /**\n * Maps a `pg` error raised by a query to the matching Sequelize v6 error class.\n *\n * @param error - Error thrown by the driver.\n * @param context - SQL and parameters of the failed query.\n * @returns Sequelize error (the error itself when it already is one).\n */\n mapQueryError(error: unknown, context: QueryErrorContext = {}): BaseError {\n if (error instanceof BaseError) {\n return error;\n }\n const driverError: DriverError = error instanceof Error ? error : new Error(String(error));\n switch (driverError.code) {\n case '23505':\n return this.#uniqueViolation(driverError, context);\n case '23503':\n return new ForeignKeyConstraintError(this.#constraintOptions(driverError, context));\n case '23P01':\n return new ExclusionConstraintError(this.#constraintOptions(driverError, context));\n case '57014':\n return new TimeoutError(driverError, context);\n default:\n return PgErrorMapper.#isConnectionFailure(driverError)\n ? this.mapConnectionError(driverError)\n : new DatabaseError(driverError, context);\n }\n }\n\n /**\n * Maps an error raised while connecting to the matching Sequelize v6 connection error class.\n *\n * @param error - Error thrown by the driver.\n * @returns Connection error (the error itself when it already is one).\n */\n mapConnectionError(error: unknown): ConnectionError {\n if (error instanceof ConnectionError) {\n return error;\n }\n const driverError: DriverError = error instanceof Error ? error : new Error(String(error));\n const ErrorClass =\n (driverError.code === undefined ? undefined : CONNECTION_CODES.get(driverError.code)) ??\n ConnectionError;\n return new ErrorClass(driverError);\n }\n\n #uniqueViolation(error: DriverError, context: QueryErrorContext): UniqueConstraintError {\n const fields = this.parseKeyDetail(error.detail);\n const base = { parent: error, ...context, ...PgErrorMapper.#tableAndConstraint(error) };\n return fields === undefined\n ? new UniqueConstraintError({ ...base, message: error.message })\n : new UniqueConstraintError({ ...base, fields, errors: PgErrorMapper.#uniqueItems(fields) });\n }\n\n #constraintOptions(error: DriverError, context: QueryErrorContext) {\n return {\n parent: error,\n ...context,\n fields: Object.keys(this.parseKeyDetail(error.detail) ?? {}),\n ...PgErrorMapper.#tableAndConstraint(error),\n };\n }\n\n static #tableAndConstraint(error: DriverError): { table?: string; constraint?: string } {\n return {\n ...(error.table === undefined ? {} : { table: error.table }),\n ...(error.constraint === undefined ? {} : { constraint: error.constraint }),\n };\n }\n\n static #uniqueItems(fields: Readonly<Record<string, string>>): ValidationErrorItem[] {\n return Object.entries(fields).map(\n ([field, value]) =>\n new ValidationErrorItem(\n `${field} must be unique`,\n 'unique violation',\n field,\n value,\n null,\n 'not_unique',\n ),\n );\n }\n\n static #splitList(value: string): readonly string[] {\n return value.split(',').map((part) => part.trim().replace(/^\"(.*)\"$/, '$1'));\n }\n\n static #isConnectionFailure(error: DriverError): boolean {\n return (\n error.code !== undefined && (CONNECTION_CODES.has(error.code) || error.code.startsWith('08'))\n );\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Transaction } from './transaction.ts';\n\n/** Continuation-local storage of the current transaction (`AsyncLocalStorage`, used by `Sequelize.useCLS`). */\nexport class TransactionContext {\n readonly #storage = new AsyncLocalStorage<Transaction>();\n\n /**\n * Transaction of the current async context.\n *\n * @returns The transaction, or `undefined` outside `run`.\n */\n current(): Transaction | undefined {\n return this.#storage.getStore();\n }\n\n /**\n * Runs `run` with `transaction` as the current transaction.\n *\n * @param transaction - Transaction to make current.\n * @param run - Callback.\n * @returns Result of `run`.\n */\n run<T>(transaction: Transaction, run: () => Promise<T>): Promise<T> {\n return this.#storage.run(transaction, run);\n }\n}\n\n/** Runs managed transactions: begins, runs the callback, commits on success and rolls back on error. */\nexport class TransactionRunner {\n readonly #context: TransactionContext;\n\n /**\n * @param context - Context the transaction is made current in while the callback runs.\n */\n constructor(context: TransactionContext) {\n this.#context = context;\n }\n\n /**\n * Runs `run` inside `transaction`.\n *\n * @param transaction - Transaction, not started yet.\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n */\n async run<T>(\n transaction: Transaction,\n run: (transaction: Transaction) => Promise<T>,\n ): Promise<T> {\n await transaction.begin();\n try {\n const result = await this.#context.run(transaction, () => run(transaction));\n await transaction.commit();\n return result;\n } catch (error) {\n if (transaction.finished === undefined) {\n await transaction.rollback().catch(() => undefined);\n }\n throw error;\n }\n }\n}\n\n/**\n * Transaction scope shared by every `Sequelize` instance: the `useCLS` switch, the current\n * transaction of the async context and the managed-transaction runner.\n */\nexport class TransactionScope {\n readonly #context = new TransactionContext();\n readonly #runner = new TransactionRunner(this.#context);\n #cls = false;\n\n /** Enables continuation-local transactions. */\n enableCls(): void {\n this.#cls = true;\n }\n\n /**\n * Transaction of the current async context.\n *\n * @returns The transaction, or `undefined` when CLS is off or outside a managed transaction.\n */\n active(): Transaction | undefined {\n return this.#cls ? this.#context.current() : undefined;\n }\n\n /**\n * Runs `run` inside `transaction`, committing or rolling back.\n *\n * @param transaction - Transaction, not started yet.\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n */\n run<T>(transaction: Transaction, run: (transaction: Transaction) => Promise<T>): Promise<T> {\n return this.#runner.run(transaction, run);\n }\n}\n\n/** The scope used by all `Sequelize` instances. */\nexport const transactionScope = new TransactionScope();\n","import type { ConnectionManager } from '../connection/connection-manager.ts';\nimport { Transaction, type TransactionOptions } from './transaction.ts';\nimport { transactionScope } from './transaction-runner.ts';\n\n/** Creates transactions on a connection manager, nesting them in the CLS transaction when enabled. */\nexport class TransactionStarter {\n readonly #connections: ConnectionManager;\n\n /**\n * @param connections - Connection manager of the owning `Sequelize` instance.\n */\n constructor(connections: ConnectionManager) {\n this.#connections = connections;\n }\n\n /**\n * Starts an unmanaged transaction.\n *\n * @param options - Transaction options.\n * @returns Started transaction.\n */\n begin(options: TransactionOptions): Promise<Transaction> {\n return this.#create(options).begin();\n }\n\n /**\n * Runs `run` in a managed transaction: committed on success, rolled back on error.\n *\n * @param options - Transaction options.\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n */\n managed<T>(\n options: TransactionOptions,\n run: (transaction: Transaction) => Promise<T>,\n ): Promise<T> {\n return transactionScope.run(this.#create(options), run);\n }\n\n #create(options: TransactionOptions): Transaction {\n const parent =\n options.transaction === undefined ? transactionScope.active() : options.transaction;\n return new Transaction(this.#connections, {\n ...options,\n ...(parent === undefined ? {} : { transaction: parent }),\n });\n }\n}\n","import type { PoolConfig } from 'pg';\nimport type { ConnectionConfig } from '../connection/connection-config.ts';\nimport { ConnectionManager } from '../connection/connection-manager.ts';\nimport type { ExecuteOptions, QueryResult } from '../connection/connection-types.ts';\nimport { NotificationListener, type NotificationHandler } from '../connection/notifications.ts';\nimport type {\n ConnectionConfig as ConnectionSettings,\n SequelizeOptions,\n} from '../connection/options.ts';\nimport { QueryLogger } from '../connection/query-logger.ts';\nimport { PgErrorMapper } from '../errors/map-pg-error.ts';\nimport { HookRegistry } from '../hooks/hooks.ts';\nimport type { ModelAttributes } from '../model/model-definition.ts';\nimport type { AnyModel, ModelStatic } from '../model/options.ts';\nimport type { ModelRuntime, QueryOptionsBase } from '../model/runtime.ts';\nimport type { QueryInterface } from '../query-interface/query-interface.ts';\nimport type { CompiledQuery } from '../sql/compile.ts';\nimport type { Transaction, TransactionOptions } from '../transaction/transaction.ts';\nimport { transactionScope } from '../transaction/transaction-runner.ts';\nimport { TransactionStarter } from '../transaction/transaction-starter.ts';\n\n/** What the internals need from the owning `Sequelize` instance. */\nexport type InternalsOwner = Readonly<{\n models: Record<string, ModelStatic<AnyModel>>;\n config: ConnectionSettings;\n define: (name: string, attributes: ModelAttributes, options?: Record<string, unknown>) => object;\n getQueryInterface: () => QueryInterface;\n}>;\n\n/**\n * State and services behind a `Sequelize` instance: hooks, connections, query execution,\n * transactions, notifications and the runtime handed to models.\n *\n * @internal\n */\nexport class SequelizeInternals {\n /** Hooks registered on the instance. */\n hooks: HookRegistry;\n /** Pools of the instance. */\n readonly connections: ConnectionManager;\n /** Schema API, created on first use. */\n queryInterface: QueryInterface | undefined;\n /** Services provided to models. */\n readonly runtime: ModelRuntime;\n readonly #owner: InternalsOwner;\n readonly #transactions: TransactionStarter;\n #serverVersion: Promise<number> | undefined;\n #notifier: NotificationListener | undefined;\n\n /**\n * @param owner - The `Sequelize` instance.\n * @param connectionConfig - Normalized connection configuration.\n */\n constructor(owner: InternalsOwner, connectionConfig: ConnectionConfig) {\n this.#owner = owner;\n this.hooks = HookRegistry.fromOption(connectionConfig.options.hooks);\n this.connections = this.#createConnections(connectionConfig);\n this.#transactions = new TransactionStarter(this.connections);\n this.runtime = this.#createRuntime(connectionConfig.options);\n }\n\n /**\n * Runs a compiled query on the pool or transaction the options select.\n *\n * @param query - Query text and values.\n * @param options - Transaction, logging and routing options.\n * @param kind - `'read'` queries may run on a replica.\n * @returns Query result.\n */\n execute(\n query: CompiledQuery,\n options: QueryOptionsBase,\n kind: 'read' | 'write' = 'write',\n ): Promise<QueryResult> {\n return this.connections.execute(query, this.executeOptions(options, kind));\n }\n\n /**\n * Resolves the transaction, replica route and logging of one query.\n *\n * @param options - Query options.\n * @param kind - `'read'` queries may run on a replica.\n * @returns Connection manager execute options.\n */\n executeOptions(options: QueryOptionsBase, kind: 'read' | 'write' = 'write'): ExecuteOptions {\n const transaction =\n options.transaction === undefined\n ? transactionScope.active()\n : (options.transaction ?? undefined);\n return {\n ...(transaction === undefined ? {} : transaction.executeOptions()),\n ...(transaction === undefined && kind === 'read' && options.useMaster !== true\n ? { route: 'read' as const }\n : {}),\n ...(options.logging === undefined ? {} : { logging: options.logging }),\n ...(options.benchmark === undefined ? {} : { benchmark: options.benchmark }),\n ...(options.statementTimeout === undefined\n ? {}\n : { statementTimeout: options.statementTimeout }),\n };\n }\n\n /**\n * Starts an unmanaged transaction.\n *\n * @param options - Transaction options.\n * @returns Started transaction.\n */\n begin(options: TransactionOptions = {}): Promise<Transaction> {\n return this.#transactions.begin(options);\n }\n\n /**\n * Runs `run` in a managed transaction.\n *\n * @param options - Transaction options.\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n */\n managed<T>(\n options: TransactionOptions,\n run: (transaction: Transaction) => Promise<T>,\n ): Promise<T> {\n return this.#transactions.managed(options, run);\n }\n\n /**\n * Subscribes to a `NOTIFY` channel.\n *\n * @param channel - Channel name.\n * @param handler - Notification handler.\n * @returns Function that unsubscribes the handler.\n */\n listen(channel: string, handler: NotificationHandler): Promise<() => Promise<void>> {\n this.#notifier ??= new NotificationListener(() => this.connections.dedicated());\n return this.#notifier.listen(channel, handler);\n }\n\n /**\n * Closes the notification connection and all pools.\n *\n * @returns Resolves when closed.\n */\n async close(): Promise<void> {\n await this.#notifier?.close();\n await this.connections.close();\n }\n\n #createConnections(connectionConfig: ConnectionConfig): ConnectionManager {\n const { options } = connectionConfig;\n const pools = connectionConfig.replicationPoolConfigs();\n const withHookPassword = (config: PoolConfig): PoolConfig => ({\n ...config,\n password: () => this.#connectPassword(config.password),\n });\n return new ConnectionManager(\n withHookPassword(pools.write),\n pools.read.map(withHookPassword),\n QueryLogger.fromOptions(options),\n new PgErrorMapper(),\n options.statementCache,\n );\n }\n\n async #connectPassword(configured: PoolConfig['password']): Promise<string> {\n const password = typeof configured === 'function' ? await configured() : (configured ?? '');\n if (!this.hooks.has('beforeConnect')) {\n return password;\n }\n const config = { ...this.#owner.config, password };\n await this.hooks.run('beforeConnect', this.#owner, config);\n return config.password ?? '';\n }\n\n #createRuntime(options: SequelizeOptions): ModelRuntime {\n return {\n ...this.#queryRuntime(),\n ...this.#modelRuntime(),\n beginTransaction: (transactionOptions) => this.begin(transactionOptions),\n transaction: (run, parent) =>\n this.managed(parent === undefined || parent === null ? {} : { transaction: parent }, run),\n defaults: options.define ?? {},\n inAsAnyThreshold: options.inAsAnyThreshold,\n };\n }\n\n #queryRuntime(): Pick<ModelRuntime, 'execute' | 'copyFrom' | 'copyTo' | 'serverVersion'> {\n return {\n execute: (query, options, kind) => this.execute(query, options, kind),\n copyFrom: (text, lines, options) =>\n this.connections.copyFrom(text, lines, this.executeOptions(options)),\n copyTo: (text, options, kind) =>\n this.connections.copyTo(text, this.executeOptions(options, kind)),\n serverVersion: () => this.#serverVersionNumber(),\n };\n }\n\n #modelRuntime(): Pick<\n ModelRuntime,\n 'register' | 'hooks' | 'defineModel' | 'models' | 'queryInterface'\n > {\n return {\n register: (name, model) => {\n this.#owner.models[name] = model as ModelStatic<AnyModel>;\n },\n hooks: () => this.hooks,\n defineModel: (name, attributes, options) =>\n this.#owner.define(name, attributes as ModelAttributes, options),\n models: () => this.#owner.models,\n queryInterface: () => this.#owner.getQueryInterface(),\n };\n }\n\n #serverVersionNumber(): Promise<number> {\n this.#serverVersion ??= this.execute({ text: 'SHOW server_version_num', values: [] }, {}).then(\n (result) => Number(result.rows[0]?.['server_version_num'] ?? 0),\n );\n return this.#serverVersion;\n }\n}\n","import { ModelDecorators } from '../decorators/model-decorators.ts';\nimport { ConnectionConfig } from '../connection/connection-config.ts';\nimport type {\n ConnectionConfig as ConnectionSettings,\n SequelizeOptions,\n} from '../connection/options.ts';\nimport { cast, col, fn, json, literal, where, type Literal } from '../expressions/methods.ts';\nimport { Model } from '../model/model.ts';\nimport type { ModelAttributes } from '../model/model-definition.ts';\nimport { ModelRegistry } from '../model/model-registry.ts';\nimport type { AnyModel, InitOptions, ModelStatic } from '../model/options.ts';\nimport {\n runtimeKey,\n type ModelRuntime,\n type QueryOptionsBase,\n type RuntimeOwner,\n} from '../model/runtime.ts';\nimport { QueryResultShaper, QueryTypes, type QueryOptions } from '../query/query-result-shaper.ts';\nimport { RawQuery } from '../query/raw-query.ts';\nimport { QueryInterface } from '../query-interface/query-interface.ts';\nimport { RowMapper } from '../model/row-mapper.ts';\nimport { SequelizeInternals } from './sequelize-internals.ts';\n\nconst decorators = new ModelDecorators();\nconst rawQuery = new RawQuery();\nconst resultShaper = new QueryResultShaper(new RowMapper(new ModelRegistry()));\n\n/**\n * Options of `sequelize.define`: the model options of `Model.init` without `sequelize`.\n *\n * @example\n * ```ts\n * const options: DefineOptions = { tableName: 'products', timestamps: false, paranoid: false };\n * const Product = sequelize.define('Product', { sku: DataTypes.STRING }, options);\n * ```\n */\nexport type DefineOptions = Omit<InitOptions, 'sequelize'>;\n\n/**\n * Core of `Sequelize`: options, models, query execution and connection lifecycle. The remaining\n * capabilities are added by the `Sequelize` mixins; `Sequelize` is the public class.\n *\n * @internal\n */\nexport class SequelizeBase {\n /** Normalized constructor options. */\n readonly options: SequelizeOptions;\n /** Connection settings. */\n readonly config: ConnectionSettings;\n /** Models registered with `define` / `Model.init`, by model name. */\n readonly models: Record<string, ModelStatic<AnyModel>> = {};\n /** Raw SQL fragment builder. */\n readonly literal = literal;\n /** SQL function call builder. */\n readonly fn = fn;\n /** Column reference builder. */\n readonly col = col;\n /** Type cast builder. */\n readonly cast = cast;\n /** Comparison builder. */\n readonly where = where;\n /** JSON path builder. */\n readonly json = json;\n /** @internal */\n readonly internals: SequelizeInternals;\n\n /**\n * @param args - Connection URI, or database / username / password, followed by options.\n */\n constructor(...args: readonly unknown[]) {\n const connectionConfig = new ConnectionConfig(\n args as ConstructorParameters<typeof ConnectionConfig>[0],\n );\n this.options = connectionConfig.options;\n this.config = connectionConfig.settings();\n this.internals = new SequelizeInternals(this, connectionConfig);\n }\n\n /**\n * Reports the SQL dialect of this instance; postgrelize supports PostgreSQL only.\n *\n * @returns Always `'postgres'`.\n *\n * @example\n * ```ts\n * sequelize.getDialect(); // 'postgres'\n * ```\n */\n getDialect(): 'postgres' {\n return 'postgres';\n }\n\n /**\n * Defines a model without declaring a class, like `Model.init` on an anonymous subclass named `modelName`.\n * The model is registered in `sequelize.models`.\n *\n * @param modelName - Model name.\n * @param attributes - Attribute definitions keyed by attribute name.\n * @param options - Model options (`sequelize` is set for you).\n * @returns The model class.\n * @see {@link Model.init}\n *\n * @example\n * ```ts\n * const Product = sequelize.define('Product', {\n * sku: { type: DataTypes.STRING, allowNull: false, unique: true },\n * price: DataTypes.DECIMAL(10, 2),\n * });\n * await Product.sync();\n * ```\n */\n define<M extends AnyModel = Model>(\n modelName: string,\n attributes: ModelAttributes,\n options: DefineOptions = {},\n ): ModelStatic<M> {\n const DefinedModel = { [modelName]: class extends Model {} }[\n modelName\n ] as unknown as ModelStatic<M>;\n return DefinedModel.init(attributes, {\n ...options,\n modelName,\n sequelize: this as unknown as RuntimeOwner,\n }) as ModelStatic<M>;\n }\n\n /**\n * Registers model classes defined with decorators (`@Table`, `@Column`, `@HasMany`, …): initializes\n * each one like `Model.init` and then adds its associations, so classes may refer to each other\n * in any order. Pass every class of an association before using it.\n *\n * @param models - Model classes.\n * @returns This instance.\n * @example\n * ```ts\n * sequelize.addModels([User, Post]);\n * ```\n * @see {@link Table}\n */\n addModels(models: readonly ModelStatic<AnyModel>[]): this {\n decorators.register(this as unknown as RuntimeOwner, models);\n return this;\n }\n\n /**\n * Looks up a model registered with `define`, `Model.init` or `addModels`.\n *\n * @param modelName - Model name.\n * @returns The model class.\n * @throws Error when the model is not defined.\n *\n * @example\n * ```ts\n * const Product = sequelize.model('Product');\n * const total = await Product.count();\n * ```\n */\n model(modelName: string): ModelStatic<AnyModel> {\n const model = this.models[modelName];\n if (model === undefined) {\n throw new Error(`${modelName} has not been defined`);\n }\n return model;\n }\n\n /**\n * Tells whether a model with the given name is registered on this instance.\n *\n * @param modelName - Model name.\n * @returns True when defined.\n *\n * @example\n * ```ts\n * if (!sequelize.isDefined('Product')) {\n * sequelize.define('Product', { sku: DataTypes.STRING });\n * }\n * ```\n */\n isDefined(modelName: string): boolean {\n return modelName in this.models;\n }\n\n /**\n * Runs a raw SQL statement and shapes the result by `options.type`. Replacements are bound as parameters (never inlined).\n * The SQL text itself is sent as is: never build it from user input — pass user values through\n * `replacements` or `bind`.\n *\n * @param sql - SQL text, or a literal.\n * @param options - Query options.\n * @returns Shaped according to `options.type`, like Sequelize v6.\n * @throws DatabaseError subclasses mapped from the PostgreSQL error (unique violation, foreign key violation, ...).\n * @see {@link QueryTypes}\n *\n * @example\n * ```ts\n * const rows = await sequelize.query('SELECT id, name FROM users WHERE name = :name', {\n * type: QueryTypes.SELECT,\n * replacements: { name: 'Ada' },\n * });\n * ```\n */\n async query(sql: string | Literal, options: QueryOptions = {}): Promise<unknown> {\n const text = typeof sql === 'string' ? sql : sql.val;\n const prepared = rawQuery.prepare(text, {\n ...(options.replacements === undefined ? {} : { replacements: options.replacements }),\n ...(options.bind === undefined ? {} : { bind: options.bind }),\n });\n const kind = resultShaper.type(options) === QueryTypes.SELECT ? 'read' : 'write';\n return resultShaper.shape(await this.internals.execute(prepared, options, kind), options);\n }\n\n /**\n * Returns the schema manipulation API of this instance (used by migrations). The instance is created on first use and then reused.\n *\n * @returns The QueryInterface of this instance.\n *\n * @example\n * ```ts\n * const queryInterface = sequelize.getQueryInterface();\n * await queryInterface.dropTable('legacy_logs');\n * ```\n */\n getQueryInterface(): QueryInterface {\n this.internals.queryInterface ??= new QueryInterface(this as unknown as RuntimeOwner);\n return this.internals.queryInterface;\n }\n\n /**\n * Verifies that the database is reachable by running `SELECT 1+1 AS result`.\n *\n * @param options - Query options.\n * @returns Resolves when the database is reachable.\n * @throws ConnectionError and its subclasses when the connection cannot be established.\n *\n * @example\n * ```ts\n * try {\n * await sequelize.authenticate();\n * } catch (error) {\n * console.error('Database unreachable', error);\n * }\n * ```\n */\n async authenticate(options: QueryOptionsBase = {}): Promise<void> {\n await this.internals.execute({ text: 'SELECT 1+1 AS result', values: [] }, options);\n }\n\n /**\n * Reads the PostgreSQL server version with `SHOW server_version`, e.g. `'16.4'`.\n *\n * @param options - Query options.\n * @returns Version string.\n *\n * @example\n * ```ts\n * const version = await sequelize.databaseVersion(); // e.g. '17.2'\n * ```\n */\n async databaseVersion(options: QueryOptionsBase = {}): Promise<string> {\n const query = { text: 'SHOW server_version', values: [] };\n const result = await this.internals.execute(query, options);\n return String(result.rows[0]?.['server_version'] ?? '').split(' ')[0] ?? '';\n }\n\n /**\n * Closes all pooled connections and stops the notification listener. The instance cannot run queries afterwards.\n *\n * @returns Resolves when closed.\n *\n * @example\n * ```ts\n * await sequelize.close();\n * ```\n */\n async close(): Promise<void> {\n await this.internals.close();\n }\n}\n\n// The services models use are reached through `RuntimeOwner` (declared on `Sequelize`).\nObject.defineProperty(SequelizeBase.prototype, runtimeKey, {\n get(this: SequelizeBase): ModelRuntime {\n return this.internals.runtime;\n },\n});\n","import type { HookFunction } from '../hooks/hooks.ts';\nimport type { SequelizeConstructor } from './sequelize-constructor.ts';\n\nconst missingHook = (): never => {\n throw new Error('addHook: hook function is required');\n};\n\n/**\n * Hook methods of `Sequelize`: `addHook`, `removeHook`, `hasHook`, `hasHooks`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const SequelizeHooks = <TBase extends SequelizeConstructor>(Base: TBase) =>\n class HooksCapability extends Base {\n /**\n * Registers a global hook that runs for every model of this instance, or a connection hook such as `beforeConnect`. Global hooks are not fired for models that never use the hook type.\n *\n * @param type - Hook type, e.g. `'beforeCreate'`.\n * @param nameOrFn - Hook name (to remove it later) or the hook function.\n * @param hook - Hook function when a name is given.\n * @returns This instance.\n *\n * @example\n * ```ts\n * sequelize.addHook('beforeCreate', 'stamp', (instance: any) => {\n * instance.createdBy = 'system';\n * });\n * ```\n */\n addHook(type: string, nameOrFn: string | HookFunction, hook?: HookFunction): this {\n const { internals } = this;\n internals.hooks =\n typeof nameOrFn === 'string'\n ? internals.hooks.add(type, hook ?? missingHook(), nameOrFn)\n : internals.hooks.add(type, nameOrFn);\n return this;\n }\n\n /**\n * Unregisters global hooks by name or by function reference.\n *\n * @param type - Hook type.\n * @param nameOrFn - Hook name or function; all hooks of the type when omitted.\n * @returns This instance.\n *\n * @example\n * ```ts\n * sequelize.removeHook('beforeCreate', 'stamp');\n * ```\n */\n removeHook(type: string, nameOrFn?: string | HookFunction): this {\n this.internals.hooks = this.internals.hooks.remove(type, nameOrFn);\n return this;\n }\n\n /**\n * Tells whether this instance has at least one global hook of the given type.\n *\n * @param type - Hook type.\n * @returns True when at least one hook exists.\n *\n * @example\n * ```ts\n * if (!sequelize.hasHook('beforeCreate')) {\n * sequelize.addHook('beforeCreate', () => {});\n * }\n * ```\n */\n hasHook(type: string): boolean {\n return this.internals.hooks.has(type);\n }\n\n /**\n * Alias of {@link Sequelize.hasHook}, kept for Sequelize v6 compatibility.\n *\n * @param type - Hook type.\n * @returns True when at least one hook exists.\n *\n * @example\n * ```ts\n * const registered = sequelize.hasHooks('afterUpdate');\n * ```\n */\n hasHooks(type: string): boolean {\n return this.hasHook(type);\n }\n };\n","import type { NotificationHandler } from '../connection/notifications.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport type { SequelizeConstructor } from './sequelize-constructor.ts';\n\n/**\n * Notification methods of `Sequelize` (PostgreSQL extension): `listen` and `notify`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const SequelizeNotifications = <TBase extends SequelizeConstructor>(Base: TBase) =>\n class NotificationsCapability extends Base {\n /**\n * Subscribes a handler to `NOTIFY` messages on a channel over one dedicated connection per instance, which is\n * re-subscribed after connection loss. PostgreSQL extension.\n *\n * @param channel - Channel name.\n * @param handler - Called with the payload and the channel.\n * @returns Function that unsubscribes the handler.\n *\n * @example\n * ```ts\n * const stop = await sequelize.listen('jobs', (payload, channel) => {\n * console.log(channel, payload);\n * });\n * await sequelize.notify('jobs', { id: 1 });\n * await stop();\n * ```\n */\n listen(channel: string, handler: NotificationHandler): Promise<() => Promise<void>> {\n return this.internals.listen(channel, handler);\n }\n\n /**\n * Sends a notification to a channel with `pg_notify`. PostgreSQL extension.\n *\n * @param channel - Channel name.\n * @param payload - Payload text (objects are sent as JSON).\n * @param options - Query options (inside a transaction the notification is sent on commit).\n * @returns Resolves when sent.\n * @see {@link Sequelize.listen}\n *\n * @example\n * ```ts\n * await sequelize.notify('jobs', 'refresh');\n * await sequelize.notify('jobs', { id: 42 }, { transaction });\n * ```\n */\n async notify(\n channel: string,\n payload?: unknown,\n options: QueryOptionsBase = {},\n ): Promise<void> {\n const text =\n payload === undefined\n ? ''\n : typeof payload === 'string'\n ? payload\n : JSON.stringify(payload);\n const query = { text: 'SELECT pg_notify($1, $2)', values: [channel, text] };\n await this.internals.execute(query, options);\n }\n };\n","import { ModelRegistry } from '../model/model-registry.ts';\nimport { syncHooks } from '../model/model-services.ts';\nimport type { QueryOptionsBase } from '../model/runtime.ts';\nimport {\n SchemaSynchronizer,\n type DropOptions,\n type SyncOptions,\n} from '../query-interface/schema-synchronizer.ts';\nimport type { SequelizeBase } from './sequelize-base.ts';\nimport type { SequelizeConstructor } from './sequelize-constructor.ts';\n\nconst registry = new ModelRegistry();\n\nconst synchronizer = (sequelize: SequelizeBase): SchemaSynchronizer =>\n new SchemaSynchronizer(sequelize.internals.runtime, sequelize.getQueryInterface());\n\nconst definitions = (sequelize: SequelizeBase): ReturnType<ModelRegistry['definition']>[] =>\n Object.values(sequelize.models).map((model) => registry.definition(model));\n\nconst runSync = async (sequelize: SequelizeBase, options: SyncOptions): Promise<void> => {\n const hooks = options.hooks !== false;\n const hookOptions = { ...options, hooks };\n if (hooks) {\n await sequelize.internals.hooks.run('beforeBulkSync', sequelize, hookOptions);\n }\n const models = new Map(Object.values(sequelize.models).map((m) => [registry.definition(m), m]));\n await synchronizer(sequelize).syncAll(definitions(sequelize), options, (definition, run) =>\n syncHooks.around(models.get(definition) ?? {}, hookOptions, run),\n );\n if (hooks) {\n await sequelize.internals.hooks.run('afterBulkSync', sequelize, hookOptions);\n }\n};\n\n/**\n * Schema methods of `Sequelize`: schema management, `sync` and `drop`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const SequelizeSchema = <TBase extends SequelizeConstructor>(Base: TBase) =>\n class SchemaCapability extends Base {\n /**\n * Runs `CREATE SCHEMA IF NOT EXISTS` for a schema.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await sequelize.createSchema('tenant_1');\n * ```\n */\n async createSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.getQueryInterface().createSchema(schema, options);\n }\n\n /**\n * Lists the schemas that belong to the application (without `public`, `information_schema` and `pg_*`).\n *\n * @param options - Query options.\n * @returns Schema names.\n *\n * @example\n * ```ts\n * const schemas = await sequelize.showAllSchemas(); // e.g. ['tenant_1']\n * ```\n */\n async showAllSchemas(options?: QueryOptionsBase): Promise<string[]> {\n return await this.getQueryInterface().showAllSchemas(options);\n }\n\n /**\n * Runs `DROP SCHEMA IF EXISTS ... CASCADE`, removing the schema and every object in it.\n *\n * @param schema - Schema name.\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await sequelize.dropSchema('tenant_1');\n * ```\n */\n async dropSchema(schema: string, options?: QueryOptionsBase): Promise<void> {\n await this.getQueryInterface().dropSchema(schema, options);\n }\n\n /**\n * Drops every schema returned by {@link Sequelize.showAllSchemas} with `CASCADE`. Destructive.\n *\n * @param options - Query options.\n *\n * @example\n * ```ts\n * await sequelize.dropAllSchemas();\n * ```\n */\n async dropAllSchemas(options?: QueryOptionsBase): Promise<void> {\n await this.getQueryInterface().dropAllSchemas(options);\n }\n\n /**\n * Creates (or alters / re-creates) the tables of all defined models in foreign-key order. Reference cycles use deferred foreign keys.\n *\n * @param options - `force`, `alter`, `match` and query options.\n * @returns This instance.\n * @throws Error when `options.match` does not match the database name.\n * @see {@link Model.sync}\n *\n * @example\n * ```ts\n * await sequelize.sync({ alter: { drop: false } });\n * await sequelize.sync({ force: true, match: /_test$/ });\n * ```\n */\n async sync(options: SyncOptions = {}): Promise<this> {\n if (options.match !== undefined && !options.match.test(this.config.database ?? '')) {\n throw new Error(\n `Database \"${this.config.database ?? ''}\" does not match sync match parameter \"${String(options.match)}\"`,\n );\n }\n await runSync(this, options);\n return this;\n }\n\n /**\n * Drops the tables of all defined models in reverse foreign-key order. Destructive.\n *\n * @param options - `cascade` and query options.\n * @returns Resolves when done.\n *\n * @example\n * ```ts\n * await sequelize.drop({ cascade: true });\n * ```\n */\n async drop(options: DropOptions = {}): Promise<void> {\n await synchronizer(this).dropAll(definitions(this), options);\n }\n };\n","import type {\n AdvisoryLockKey,\n Transaction,\n TransactionOptions,\n} from '../transaction/transaction.ts';\nimport type { SequelizeConstructor } from './sequelize-constructor.ts';\n\n/**\n * Transaction methods of `Sequelize`: `transaction` and `withAdvisoryLock`.\n *\n * @internal\n */\n// oxlint-disable-next-line max-lines-per-function, typescript/explicit-module-boundary-types -- a mixin factory's body is its class (each method is still size-checked); its type can only be inferred.\nexport const SequelizeTransactions = <TBase extends SequelizeConstructor>(Base: TBase) =>\n class TransactionsCapability extends Base {\n /**\n * Begins an unmanaged transaction that you must commit or roll back yourself. With `options.transaction` it becomes a savepoint inside that transaction.\n *\n * @param options - Transaction options.\n * @returns Started transaction.\n *\n * @example\n * ```ts\n * const t = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE });\n * try {\n * await User.create({ name: 'Ada' }, { transaction: t });\n * await t.commit();\n * } catch (error) {\n * await t.rollback();\n * throw error;\n * }\n * ```\n */\n transaction(options?: TransactionOptions): Promise<Transaction>;\n /**\n * Runs a callback in a managed transaction: committed when it resolves, rolled back when it throws. Queries must pass `{ transaction }` unless CLS is enabled with {@link Sequelize.useCLS}.\n *\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n *\n * @example\n * ```ts\n * const created = await sequelize.transaction(async (t) => {\n * const owner = await User.create({ name: 'Ada' }, { transaction: t });\n * return Post.create({ title: 'Hello', userId: owner.id }, { transaction: t });\n * });\n * ```\n */\n transaction<T>(run: (transaction: Transaction) => Promise<T>): Promise<T>;\n /**\n * Runs a callback in a managed transaction started with the given options (isolation level, read only, settings, savepoint parent).\n *\n * @param options - Transaction options.\n * @param run - Callback receiving the transaction.\n * @returns Result of `run`.\n *\n * @example\n * ```ts\n * const count = await sequelize.transaction({ readOnly: true }, async (t) => {\n * return User.count({ transaction: t });\n * });\n * ```\n */\n transaction<T>(\n options: TransactionOptions,\n run: (transaction: Transaction) => Promise<T>,\n ): Promise<T>;\n async transaction<T>(\n optionsOrRun?: TransactionOptions | ((transaction: Transaction) => Promise<T>),\n maybeRun?: (transaction: Transaction) => Promise<T>,\n ): Promise<T | Transaction> {\n const options = typeof optionsOrRun === 'function' ? {} : (optionsOrRun ?? {});\n const run = typeof optionsOrRun === 'function' ? optionsOrRun : maybeRun;\n return run === undefined\n ? this.internals.begin(options)\n : this.internals.managed(options, run);\n }\n\n /**\n * Runs a callback in a managed transaction that first takes a transaction-level advisory lock, so concurrent callers with the same key run one at a time. The lock is released when the transaction ends. PostgreSQL extension.\n *\n * @param key - Lock key (integer or string).\n * @param run - Callback receiving the transaction.\n * @param options - Transaction options.\n * @returns Result of `run`.\n *\n * @example\n * ```ts\n * await sequelize.withAdvisoryLock('nightly-report', async (t) => {\n * await Invoice.update({ status: 'sent' }, { where: { status: 'ready' }, transaction: t });\n * });\n * ```\n */\n withAdvisoryLock<T>(\n key: AdvisoryLockKey,\n run: (transaction: Transaction) => Promise<T>,\n options: TransactionOptions = {},\n ): Promise<T> {\n return this.transaction(options, async (transaction) => {\n await transaction.advisoryLock(key);\n return run(transaction);\n });\n }\n };\n","import { DataTypes } from './data-types/data-types.ts';\nimport { cast, col, fn, json, literal, where } from './expressions/methods.ts';\nimport { Op } from './expressions/op.ts';\nimport { Model } from './model/model.ts';\nimport type { RuntimeOwner } from './model/runtime.ts';\nimport { QueryTypes } from './query/query-result-shaper.ts';\nimport { SequelizeBase } from './sequelize/sequelize-base.ts';\nimport { SequelizeHooks } from './sequelize/sequelize-hooks.ts';\nimport { SequelizeNotifications } from './sequelize/sequelize-notifications.ts';\nimport { SequelizeSchema } from './sequelize/sequelize-schema.ts';\nimport { SequelizeTransactions } from './sequelize/sequelize-transactions.ts';\nimport type { SequelizeOptions } from './connection/options.ts';\nimport { Transaction } from './transaction/transaction.ts';\nimport { transactionScope } from './transaction/transaction-runner.ts';\n\nexport { QueryTypes } from './query/query-result-shaper.ts';\nexport type { QueryOptions, QueryType } from './query/query-result-shaper.ts';\nexport type { DefineOptions } from './sequelize/sequelize-base.ts';\n\nconst SequelizeMembers = SequelizeNotifications(\n SequelizeTransactions(SequelizeSchema(SequelizeHooks(SequelizeBase))),\n);\n\n// Declaration files cannot name the symbol key of a class member, so `RuntimeOwner` is merged in as an interface.\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- intentional merge.\nexport interface Sequelize extends RuntimeOwner {}\n\n/**\n * Entry point, API-compatible with Sequelize v6 `Sequelize` for PostgreSQL.\n *\n * @example\n * ```ts\n * const sequelize = new Sequelize('postgres://user:pass@localhost:5432/app', { logging: false });\n * ```\n */\n// oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- see the interface above.\nexport class Sequelize extends SequelizeMembers {\n /** Column types. */\n static readonly DataTypes = DataTypes;\n /** Query operators. */\n static readonly Op: typeof Op = Op;\n /** Result shapes accepted by the `type` option of {@link Sequelize.query}, e.g. `QueryTypes.SELECT`. */\n static readonly QueryTypes = QueryTypes;\n /** Transaction class. */\n static readonly Transaction = Transaction;\n /** Model base class. */\n static readonly Model = Model;\n /** Raw SQL fragment builder. */\n static readonly literal = literal;\n /** SQL function call builder. */\n static readonly fn = fn;\n /** Column reference builder. */\n static readonly col = col;\n /** Type cast builder. */\n static readonly cast = cast;\n /** Comparison builder. */\n static readonly where = where;\n /** JSON path builder. */\n static readonly json = json;\n\n /**\n * Enables continuation-local transactions: queries inside `sequelize.transaction(fn)` use the\n * transaction automatically. The namespace argument of Sequelize v6 is accepted and ignored;\n * `AsyncLocalStorage` is used instead.\n *\n * @param _namespace - Ignored.\n * @returns The `Sequelize` class.\n * @see {@link Sequelize.transaction}\n *\n * @example\n * ```ts\n * Sequelize.useCLS();\n * await sequelize.transaction(async () => {\n * // No `{ transaction }` option needed: the queries join the managed transaction.\n * const user = await User.create({ name: 'Ada' });\n * await Post.create({ title: 'Hello', userId: user.id });\n * });\n * ```\n */\n static useCLS(_namespace?: unknown): typeof Sequelize {\n transactionScope.enableCls();\n return Sequelize;\n }\n\n /**\n * Creates an instance from a connection URI.\n *\n * @param uri - `postgres://user:password@host:port/database`.\n * @param options - Options.\n */\n constructor(uri: string, options?: SequelizeOptions);\n /**\n * Creates an instance from connection parameters.\n *\n * @param database - Database name.\n * @param username - User name.\n * @param password - Password.\n * @param options - Options.\n */\n constructor(\n database: string,\n username?: string | null,\n password?: string | null,\n options?: SequelizeOptions,\n );\n /**\n * Creates an instance from options only.\n *\n * @param options - Options including connection settings.\n */\n constructor(options?: SequelizeOptions);\n // oxlint-disable-next-line no-useless-constructor -- re-declares the typed overloads that mixin construction would erase.\n constructor(...args: readonly unknown[]) {\n super(...args);\n }\n}\n","import { Cast, Fn } from './call-expressions.ts';\n\nconst KINDS: ReadonlyMap<string, string> = new Map([\n ['exists', 'jsonb_path_exists'],\n ['match', 'jsonb_path_match'],\n ['query', 'jsonb_path_query'],\n ['queryFirst', 'jsonb_path_query_first'],\n ['queryArray', 'jsonb_path_query_array'],\n]);\n\n/** Function of {@link jsonbPath}: `exists`, `match`, `query`, `queryFirst` or `queryArray`. */\nexport type JsonbPathKind = 'exists' | 'match' | 'query' | 'queryFirst' | 'queryArray';\n\n/**\n * Options of {@link jsonbPath}.\n *\n * @example\n * ```ts\n * const options: JsonbPathOptions = { vars: { min: 10 }, silent: true };\n * ```\n */\nexport type JsonbPathOptions = Readonly<{\n /** Values of the `$name` variables of the path; serialized to jsonb and bound as a parameter. */\n vars?: Readonly<Record<string, unknown>>;\n /** Suppresses missing-key and type errors of the path (the `silent` argument). */\n silent?: boolean;\n /** Uses the `_tz` variant, which converts between time zones (stable instead of immutable). */\n tz?: boolean;\n}>;\n\nconst functionName = (kind: string, tz: boolean): string => {\n const name = KINDS.get(kind);\n if (name === undefined) {\n throw new Error(`Invalid jsonb path function: ${String(kind)}`);\n }\n return tz ? `${name}_tz` : name;\n};\n\nconst optionalArgs = (options: JsonbPathOptions): readonly unknown[] =>\n options.vars === undefined && options.silent === undefined\n ? []\n : [\n new Cast(JSON.stringify(options.vars ?? {}), 'jsonb'),\n ...(options.silent === undefined ? [] : [new Cast(options.silent === true, 'boolean')]),\n ];\n\n/**\n * Calls a `jsonb_path_*` function (`exists`, `match`, `query`, `queryFirst`, `queryArray`) with a\n * bound jsonpath. PostgreSQL extension.\n *\n * `Op.jsonPathExists` (`@?`) and `Op.match` (`@@`) are the operator forms of `exists` and `match`.\n *\n * @param kind - Which function to call.\n * @param target - jsonb expression, e.g. `col('doc')`.\n * @param path - jsonpath text, bound as a parameter. Invalid syntax is a database error.\n * @param options - `vars`, `silent` and `tz`.\n * @returns Function call expression.\n * @throws Error when `kind` is not one of the five names.\n * @example\n * ```ts\n * await Product.findAll({ where: where(jsonbPath('exists', col('attrs'), '$.price ? (@ > $min)', { vars: { min: 10 } }), true) });\n * ```\n */\nexport const jsonbPath = (\n kind: JsonbPathKind,\n target: unknown,\n path: string,\n options: JsonbPathOptions = {},\n): Fn =>\n new Fn(functionName(kind, options.tz === true), [\n target,\n new Cast(path, 'jsonpath'),\n ...optionalArgs(options),\n ]);\n","import { Cast, Fn } from './call-expressions.ts';\nimport { Literal } from './methods.ts';\n\nconst CONFIG_NAME = /^[A-Za-z_][\\w$]*(?:\\.[A-Za-z_][\\w$]*)?$/;\nconst WEIGHTS: ReadonlySet<string> = new Set(['A', 'B', 'C', 'D']);\nconst MAX_NORMALIZATION = 63;\n\n/**\n * Options of {@link tsRank}.\n *\n * @example\n * ```ts\n * const options: TsRankOptions = { cd: true, weights: [0.1, 0.2, 0.4, 1], normalization: 1 };\n * ```\n */\nexport type TsRankOptions = Readonly<{\n /** Uses `ts_rank_cd` (cover density) instead of `ts_rank`. */\n cd?: boolean;\n /** Weights of the labels `D`, `C`, `B`, `A`, in this order. */\n weights?: readonly [number, number, number, number];\n /** Normalization bit mask, an integer from 0 to 63. */\n normalization?: number;\n}>;\n\n/**\n * Options of {@link tsHeadline}.\n *\n * @example\n * ```ts\n * const options: TsHeadlineOptions = { config: 'english', options: 'StartSel=<b>, StopSel=</b>' };\n * ```\n */\nexport type TsHeadlineOptions = Readonly<{\n /** Text search configuration, e.g. `'english'`. */\n config?: string;\n /** `ts_headline` options string, e.g. `'StartSel=<b>, StopSel=</b>'`. Bound as a parameter. */\n options?: string;\n}>;\n\nconst regconfig = (config: string): Cast => {\n if (typeof config !== 'string' || !CONFIG_NAME.test(config)) {\n throw new Error(`Invalid text search configuration: ${String(config)}`);\n }\n return new Cast(config, 'regconfig');\n};\n\nconst withConfig = (name: string, text: unknown, config: string | undefined): Fn =>\n new Fn(name, config === undefined ? [text] : [regconfig(config), text]);\n\nconst weightsOf = (weights: readonly number[]): Cast => {\n if (weights.length !== 4 || !weights.every((weight) => Number.isFinite(weight))) {\n throw new Error('weights must be four finite numbers');\n }\n return new Cast([...weights], 'real[]');\n};\n\nconst normalizationOf = (value: number): Cast => {\n if (!Number.isInteger(value) || value < 0 || value > MAX_NORMALIZATION) {\n throw new Error('normalization must be an integer from 0 to 63');\n }\n return new Cast(value, 'integer');\n};\n\n/**\n * `to_tsvector([config,] document)`: parses a document into a `tsvector`. PostgreSQL extension.\n *\n * @param document - Text value (bound as a parameter) or an expression such as `col('body')`.\n * @param config - Text search configuration; the server default when omitted.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ where: where(toTsVector(col('body'), 'english'), Op.match, websearchToTsQuery('cat -dog', 'english')) });\n * ```\n */\nexport const toTsVector = (document: unknown, config?: string): Fn =>\n withConfig('to_tsvector', document, config);\n\n/**\n * `to_tsquery([config,] query)`: parses `tsquery` syntax (`&`, `|`, `!`, `<->`). PostgreSQL extension.\n *\n * @param query - Query text in `tsquery` syntax, bound as a parameter. Invalid syntax is a database error.\n * @param config - Text search configuration; the server default when omitted.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ where: { search: { [Op.match]: toTsQuery('cat & !dog', 'english') } } });\n * ```\n */\nexport const toTsQuery = (query: unknown, config?: string): Fn =>\n withConfig('to_tsquery', query, config);\n\n/**\n * `plainto_tsquery([config,] text)`: ANDs all words of plain text. PostgreSQL extension.\n *\n * @param text - Plain text, bound as a parameter.\n * @param config - Text search configuration; the server default when omitted.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ where: { search: { [Op.match]: plainToTsQuery('fat cats', 'english') } } });\n * ```\n */\nexport const plainToTsQuery = (text: unknown, config?: string): Fn =>\n withConfig('plainto_tsquery', text, config);\n\n/**\n * `phraseto_tsquery([config,] text)`: words of plain text that must follow each other. PostgreSQL extension.\n *\n * @param text - Plain text, bound as a parameter.\n * @param config - Text search configuration; the server default when omitted.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ where: { search: { [Op.match]: phraseToTsQuery('fat cats', 'english') } } });\n * ```\n */\nexport const phraseToTsQuery = (text: unknown, config?: string): Fn =>\n withConfig('phraseto_tsquery', text, config);\n\n/**\n * `websearch_to_tsquery([config,] text)`: web-search syntax (quotes, `or`, `-`) that never fails to parse. PostgreSQL extension.\n *\n * @param text - User search text, bound as a parameter.\n * @param config - Text search configuration; the server default when omitted.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ where: { search: { [Op.match]: websearchToTsQuery('\"fat cat\" -dog', 'english') } } });\n * ```\n */\nexport const websearchToTsQuery = (text: unknown, config?: string): Fn =>\n withConfig('websearch_to_tsquery', text, config);\n\n/**\n * `ts_rank` / `ts_rank_cd`: relevance of a `tsvector` for a `tsquery`, for `attributes` and `order`. PostgreSQL extension.\n *\n * @param vector - `tsvector` expression, e.g. `col('search')`.\n * @param query - `tsquery` expression, e.g. {@link websearchToTsQuery}.\n * @param options - `cd`, `weights` and `normalization`.\n * @returns Function call expression.\n * @throws Error when `weights` is not four finite numbers or `normalization` is not an integer from 0 to 63.\n * @example\n * ```ts\n * const query = websearchToTsQuery('cat', 'english');\n * await Post.findAll({ where: { search: { [Op.match]: query } }, order: [[tsRank(col('search'), query, { normalization: 1 }), 'DESC']] });\n * ```\n */\nexport const tsRank = (vector: unknown, query: unknown, options: TsRankOptions = {}): Fn => {\n const weights = options.weights === undefined ? [] : [weightsOf(options.weights)];\n const normalization =\n options.normalization === undefined ? [] : [normalizationOf(options.normalization)];\n return new Fn(options.cd === true ? 'ts_rank_cd' : 'ts_rank', [\n ...weights,\n vector,\n query,\n ...normalization,\n ]);\n};\n\n/**\n * `ts_headline`: a document excerpt with the query terms highlighted. PostgreSQL extension.\n *\n * @param document - Text expression or value, bound as a parameter.\n * @param query - `tsquery` expression.\n * @param options - Configuration and `ts_headline` options string.\n * @returns Function call expression.\n * @throws Error when `config` is not a plain or schema-qualified identifier.\n * @example\n * ```ts\n * await Post.findAll({ attributes: [[tsHeadline(col('body'), websearchToTsQuery('cat'), { options: 'StartSel=<b>, StopSel=</b>' }), 'excerpt']] });\n * ```\n */\nexport const tsHeadline = (\n document: unknown,\n query: unknown,\n options: TsHeadlineOptions = {},\n): Fn =>\n new Fn('ts_headline', [\n ...(options.config === undefined ? [] : [regconfig(options.config)]),\n document,\n query,\n ...(options.options === undefined ? [] : [new Cast(options.options, 'text')]),\n ]);\n\n/**\n * `setweight(vector, weight)`: labels every lexeme of a `tsvector` `A`, `B`, `C` or `D`. PostgreSQL extension.\n *\n * @param vector - `tsvector` expression, e.g. {@link toTsVector}.\n * @param weight - Label `'A'`, `'B'`, `'C'` or `'D'`.\n * @returns Function call expression.\n * @throws Error when `weight` is not one of the four labels.\n * @example\n * ```ts\n * await Post.findAll({ attributes: [[setWeight(toTsVector(col('title'), 'english'), 'A'), 'titleVector']] });\n * ```\n */\nexport const setWeight = (vector: unknown, weight: 'A' | 'B' | 'C' | 'D'): Fn => {\n if (!WEIGHTS.has(weight)) {\n throw new Error(`Invalid text search weight: ${String(weight)}`);\n }\n return new Fn('setweight', [vector, new Literal(`'${weight}'`)]);\n};\n","import { Fn } from './call-expressions.ts';\nimport { Where } from './condition-expressions.ts';\n\n/**\n * `similarity(a, b)` of `pg_trgm`: trigram similarity from 0 to 1. PostgreSQL extension; needs\n * `CREATE EXTENSION pg_trgm`.\n *\n * @param left - Text expression, e.g. `col('name')`.\n * @param right - Text expression or value (bound as a parameter).\n * @returns Function call expression.\n * @example\n * ```ts\n * await User.findAll({ order: [[trigramSimilarity(col('name'), 'jon'), 'DESC']], limit: 5 });\n * ```\n */\nexport const trigramSimilarity = (left: unknown, right: unknown): Fn =>\n new Fn('similarity', [left, right]);\n\n/**\n * `word_similarity(a, b)` of `pg_trgm`: similarity of `a` to the best matching part of `b`. PostgreSQL extension.\n *\n * @param left - Text expression or value, the searched word.\n * @param right - Text expression, e.g. `col('body')`.\n * @returns Function call expression.\n * @example\n * ```ts\n * await Post.findAll({ attributes: [[trigramWordSimilarity('postgre', col('title')), 'score']] });\n * ```\n */\nexport const trigramWordSimilarity = (left: unknown, right: unknown): Fn =>\n new Fn('word_similarity', [left, right]);\n\n/**\n * `left <-> right` of `pg_trgm`: trigram distance (`1 - similarity`), served by GiST trigram\n * indexes for nearest-neighbour `order`. PostgreSQL extension.\n *\n * @param left - Text expression, e.g. `col('name')`.\n * @param right - Text expression or value (bound as a parameter).\n * @returns Where expression usable in `order` and `attributes`.\n * @example\n * ```ts\n * await User.findAll({ order: [[trigramDistance(col('name'), 'jon'), 'ASC']], limit: 5 });\n * ```\n */\nexport const trigramDistance = (left: unknown, right: unknown): Where =>\n new Where(left, '<->', right);\n","// TC39 decorators reach the class through `context.metadata` (`Symbol.metadata`), which engines\n// do not ship yet; it must exist before the first decorated class is evaluated.\n(Symbol as { metadata?: symbol }).metadata ??= Symbol.for('Symbol.metadata');\n\n/** What a decorator call decorates, independent of the decorator signature in use. */\nexport type DecoratorTarget = Readonly<{\n /** Object that stores the metadata: the class (legacy) or its `context.metadata` bag (TC39). */\n owner: object;\n /** Decorated member name; `undefined` for a class. */\n key: string | undefined;\n /** Whether the member is static. */\n isStatic: boolean;\n}>;\n\ntype Tc39Context = Readonly<{\n kind: string;\n name?: string | symbol;\n static?: boolean;\n metadata?: object;\n}>;\n\nconst isTc39Context = (value: unknown): value is Tc39Context =>\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { kind?: unknown }).kind === 'string';\n\nconst NO_METADATA =\n 'Decorators need Symbol.metadata: import postgrelize before the decorated class is defined.';\n\n/**\n * Tells the two decorator calling conventions apart: TC39 standard `(value, context)` and legacy\n * `experimentalDecorators` `(constructor)` / `(target, key, descriptor?)`.\n *\n * @internal\n */\nexport class DecoratorSignature {\n /**\n * @param args - Arguments the decorator was called with.\n * @returns The decorated class or member.\n * @throws Error when the arguments match neither convention.\n */\n resolve(args: readonly unknown[]): DecoratorTarget {\n const [first, second] = args;\n if (isTc39Context(second)) {\n return this.#standard(second);\n }\n if (typeof first === 'function') {\n return { owner: first, key: this.#name(second), isStatic: second !== undefined };\n }\n if (typeof first === 'object' && first !== null && second !== undefined) {\n return { owner: first.constructor, key: this.#name(second), isStatic: false };\n }\n throw new Error('Unsupported decorator usage.');\n }\n\n #standard(context: Tc39Context): DecoratorTarget {\n if (context.metadata === undefined) {\n throw new Error(NO_METADATA);\n }\n return {\n owner: context.metadata,\n key: this.#name(context.name),\n isStatic: context.static === true,\n };\n }\n\n #name(key: unknown): string | undefined {\n return typeof key === 'symbol' ? key.description : (key as string | undefined);\n }\n}\n\n/** @internal Shared signature adapter. */\nexport const signature = new DecoratorSignature();\n","import type { HookType } from '../hooks/hooks.ts';\nimport type { AttributeOptions } from '../model/attribute-options.ts';\nimport { signature } from './decorator-signature.ts';\nimport type {\n ModelClassDecorator,\n ModelPropertyDecorator,\n ModelStaticMethodDecorator,\n} from './decorator-types.ts';\nimport { metadata, type ModelMetadata } from './model-metadata.ts';\n\ntype Tc39FieldContext = Readonly<{\n name: string | symbol;\n addInitializer: (initializer: (this: object) => void) => void;\n}>;\n\n/**\n * Builds decorators that work with both calling conventions from a function that records\n * something in the metadata of the decorated class.\n *\n * @internal\n */\nexport class DecoratorFactory {\n /**\n * @param record - Records into the metadata of the class.\n * @returns A class decorator.\n */\n forClass(record: (meta: ModelMetadata) => void): ModelClassDecorator {\n return ((...args: unknown[]): void => {\n record(metadata.of(signature.resolve(args)));\n }) as never;\n }\n\n /**\n * @param record - Records into the metadata of the class, given the attribute name.\n * @returns An attribute decorator.\n */\n forProperty(record: (meta: ModelMetadata, key: string) => void): ModelPropertyDecorator {\n return ((...args: unknown[]) => {\n const target = signature.resolve(args);\n record(metadata.of(target), target.key as string);\n this.#unshadow(args[1]);\n }) as never;\n }\n\n /**\n * @param partial - Column options to merge into the attribute.\n * @returns An attribute decorator.\n */\n column(partial: Partial<AttributeOptions>): ModelPropertyDecorator {\n return this.forProperty((meta, key) => {\n meta.columns[key] = { ...meta.columns[key], ...partial };\n });\n }\n\n /**\n * @param build - Creates the decorator from the optional argument of the factory call.\n * @returns A decorator usable bare (`@Unique`) and called (`@Unique('name')`).\n */\n optionalProperty<A, D extends ModelPropertyDecorator>(\n build: (argument?: A) => D,\n ): D & ((argument?: A) => D) {\n return ((...args: unknown[]) =>\n args.length >= 2\n ? (build() as unknown as (...a: unknown[]) => void)(...args)\n : build(args[0] as A | undefined)) as never;\n }\n\n /**\n * @param build - Creates the decorator from the optional argument of the factory call.\n * @returns A class decorator usable bare (`@Table`) and called (`@Table({ ... })`).\n */\n optionalClass<A>(\n build: (argument?: A) => ModelClassDecorator,\n ): ModelClassDecorator & ((argument?: A) => ModelClassDecorator) {\n return ((...args: unknown[]) =>\n typeof args[0] === 'function'\n ? (build() as unknown as (...a: unknown[]) => void)(...args)\n : build(args[0] as A | undefined)) as never;\n }\n\n /**\n * @param type - Hook type to register the decorated static method for.\n * @returns A static method decorator.\n */\n forHook(type: HookType): ModelStaticMethodDecorator {\n return ((...args: unknown[]) => {\n const target = signature.resolve(args);\n if (!target.isStatic || target.key === undefined) {\n throw new Error(`Hook decorators apply to static methods only (${type}).`);\n }\n metadata.of(target).hooks.push({ type, key: target.key });\n }) as never;\n }\n\n // A class field would shadow the attribute accessors Model.init installs on the prototype, so\n // standard decorators drop the own property right after the field is defined.\n #unshadow(context: unknown): void {\n const field = context as Partial<Tc39FieldContext>;\n if (field.addInitializer === undefined || field.name === undefined) {\n return;\n }\n const name = field.name;\n field.addInitializer(function dropOwnField(this: object) {\n Reflect.deleteProperty(this, name);\n });\n }\n}\n\n/** @internal Shared decorator factory. */\nexport const decorate = new DecoratorFactory();\n","import type { AssociationOptions, BelongsToManyOptions } from '../associations/types.ts';\nimport { decorate } from './decorator-factory.ts';\nimport type { ModelPropertyDecorator } from './decorator-types.ts';\nimport type { AssociationSpec, ModelGetter } from './model-metadata.ts';\n\ntype Kind = AssociationSpec['kind'];\n\nconst association = (\n kind: Kind,\n target: ModelGetter,\n options: AssociationOptions = {},\n through?: AssociationSpec['through'],\n): ModelPropertyDecorator =>\n decorate.forProperty((meta, key) => {\n meta.associations.push({\n kind,\n key,\n target,\n options,\n ...(through === undefined ? {} : { through }),\n });\n });\n\n/**\n * Adds a `hasOne` association; the foreign key is on the target. The property name is the alias (`as`).\n * The foreign key is the attribute of the target marked with `@ForeignKey` for this model, unless\n * `options.foreignKey` is given.\n *\n * @param target - Function returning the associated model.\n * @param options - Association options (`foreignKey`, `onDelete`, …).\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @HasOne(() => Profile)\n * profile!: Profile;\n * }\n * ```\n */\nexport const HasOne = (target: ModelGetter, options?: AssociationOptions): ModelPropertyDecorator =>\n association('hasOne', target, options);\n\n/**\n * Adds a `hasMany` association; the foreign key is on the target. The property name is the alias (`as`).\n *\n * @param target - Function returning the associated model.\n * @param options - Association options (`foreignKey`, `onDelete`, …).\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @HasMany(() => Post)\n * posts!: Post[];\n * }\n * ```\n */\nexport const HasMany = (\n target: ModelGetter,\n options?: AssociationOptions,\n): ModelPropertyDecorator => association('hasMany', target, options);\n\n/**\n * Adds a `belongsTo` association; the foreign key is on this model, marked with `@ForeignKey`\n * for the target unless `options.foreignKey` is given. The property name is the alias (`as`).\n *\n * @param target - Function returning the associated model.\n * @param options - Association options (`foreignKey`, `targetKey`, `onDelete`, …).\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class Post extends Model {\n * @ForeignKey(() => User)\n * @Column(DataTypes.INTEGER)\n * userId!: number;\n *\n * @BelongsTo(() => User)\n * user!: User;\n * }\n * ```\n */\nexport const BelongsTo = (\n target: ModelGetter,\n options?: AssociationOptions,\n): ModelPropertyDecorator => association('belongsTo', target, options);\n\n/**\n * Adds a `belongsToMany` association through a junction model. The junction model's `@ForeignKey`\n * attributes give `foreignKey` (to this model) and `otherKey` (to the target) unless `options` sets them.\n *\n * @param target - Function returning the associated model.\n * @param through - Junction table name, function returning the junction model, or `{ model, scope }`.\n * @param options - Association options (`foreignKey`, `otherKey`, …).\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class Post extends Model {\n * @BelongsToMany(() => Tag, 'post_tags')\n * tags!: Tag[];\n * }\n * ```\n */\nexport const BelongsToMany = (\n target: ModelGetter,\n through: NonNullable<AssociationSpec['through']>,\n options?: Omit<BelongsToManyOptions, 'through'>,\n): ModelPropertyDecorator => association('belongsToMany', target, options, through);\n","import type { IndexOptions } from '../ddl/ddl-generator.ts';\nimport type { AttributeOptions, UniqueOptions } from '../model/attribute-options.ts';\nimport type { DataTypeInput } from '../data-types/data-types.ts';\nimport { decorate } from './decorator-factory.ts';\nimport type { ModelPropertyDecorator } from './decorator-types.ts';\n\n/** Argument of `@Column`: a data type or column options. */\nexport type ColumnInput = DataTypeInput | AttributeOptions;\n\nconst isOptions = (input: ColumnInput): input is AttributeOptions =>\n typeof input === 'object' && 'type' in input && !('sqlType' in input);\n\n/**\n * Declares a class field as a model attribute (a column).\n *\n * The type is not inferred from the TypeScript type (there is no `reflect-metadata`): pass a\n * `DataTypes` value or an options object with `type`. Combine with the shortcut decorators.\n *\n * @param input - A data type (`DataTypes.STRING(64)`) or column options (`{ type, allowNull, … }`).\n * @returns An attribute decorator.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @Column({ type: DataTypes.STRING, allowNull: false })\n * name!: string;\n * }\n * ```\n */\nexport const Column = (input: ColumnInput): ModelPropertyDecorator =>\n decorate.column(isOptions(input) ? input : { type: input });\n\n/**\n * Makes the attribute part of the primary key (`primaryKey: true`).\n *\n * @example\n * ```ts\n * class User extends Model {\n * @PrimaryKey\n * @Column(DataTypes.INTEGER)\n * id!: number;\n * }\n * ```\n */\nexport const PrimaryKey: ModelPropertyDecorator = decorate.column({ primaryKey: true });\n\n/**\n * Generates the attribute from a sequence (`autoIncrement: true`).\n *\n * @example\n * ```ts\n * class User extends Model {\n * @PrimaryKey\n * @AutoIncrement\n * @Column(DataTypes.INTEGER)\n * id!: number;\n * }\n * ```\n */\nexport const AutoIncrement: ModelPropertyDecorator = decorate.column({ autoIncrement: true });\n\n/**\n * Sets `allowNull`. Usable bare (`@AllowNull`, meaning `true`) or called.\n *\n * @param allowNull - Whether `NULL` is allowed.\n * @defaultValue true\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @AllowNull(false)\n * @Column(DataTypes.TEXT)\n * name!: string;\n * }\n * ```\n */\nexport const AllowNull = decorate.optionalProperty<boolean, ModelPropertyDecorator>(\n (allowNull = true) => decorate.column({ allowNull }),\n);\n\n/**\n * Sets the default value of the attribute (`defaultValue`).\n *\n * @param value - A value, an expression, or `DataTypes.NOW` / `DataTypes.UUIDV4`.\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @Default(false)\n * @Column(DataTypes.BOOLEAN)\n * active!: boolean;\n * }\n * ```\n */\nexport const Default = (value: unknown): ModelPropertyDecorator =>\n decorate.column({ defaultValue: value });\n\n/**\n * Adds a unique constraint (`unique`). Usable bare or with a constraint name or options.\n *\n * @param unique - Constraint name or `{ name, msg, nullsNotDistinct }`. Attributes sharing a name form a composite key.\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @Unique\n * @Column(DataTypes.STRING)\n * email!: string;\n * }\n * ```\n */\nexport const Unique = decorate.optionalProperty<string | UniqueOptions, ModelPropertyDecorator>(\n (unique = true as never) => decorate.column({ unique }),\n);\n\n/**\n * Sets the column comment (`comment`).\n *\n * @param text - Comment text.\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class User extends Model {\n * @Comment('Login name')\n * @Column(DataTypes.STRING)\n * login!: string;\n * }\n * ```\n */\nexport const Comment = (text: string): ModelPropertyDecorator => decorate.column({ comment: text });\n\n/**\n * Adds the attribute to an index of the table (`indexes`). Usable bare, with an index name or\n * with index options; attributes sharing a name form one composite index.\n *\n * Hidden from the generated API reference on purpose: VitePress treats a page named `Index.md` as a\n * directory index (case-insensitive), so it is documented in the Decorators guide instead.\n *\n * @param index - Index name or index options (without `fields`).\n * @returns An attribute decorator.\n * @hidden\n * @example\n * ```ts\n * class User extends Model {\n * @Index({ name: 'users_name_idx', using: 'btree' })\n * @Column(DataTypes.STRING)\n * name!: string;\n * }\n * ```\n */\nexport const Index = decorate.optionalProperty<\n string | Omit<IndexOptions, 'fields'>,\n ModelPropertyDecorator\n>((index = {}) =>\n decorate.forProperty((meta, key) => {\n meta.indexes.push({ key, options: typeof index === 'string' ? { name: index } : index });\n }),\n);\n","import type { ForeignKey as ForeignKeyType } from '../model/types.ts';\nimport { decorate } from './decorator-factory.ts';\nimport type { ModelPropertyDecorator } from './decorator-types.ts';\nimport type { ModelGetter } from './model-metadata.ts';\n\n/** Marks an attribute type as a foreign key, so it stays out of the creation attributes (Sequelize v6 `ForeignKey`). */\nexport type ForeignKey<T> = ForeignKeyType<T>;\n\n/**\n * Marks the attribute as a foreign key to a model (also the v6 type `ForeignKey<T>` of the same name). Association decorators use it to find the\n * foreign key; it does not change the column definition.\n *\n * @param target - Function returning the referenced model.\n * @returns An attribute decorator.\n * @example\n * ```ts\n * class Post extends Model {\n * @ForeignKey(() => User)\n * @Column(DataTypes.INTEGER)\n * userId!: number;\n * }\n * ```\n */\nexport const ForeignKey = (target: ModelGetter): ModelPropertyDecorator =>\n decorate.forProperty((meta, key) => {\n meta.foreignKeys[key] = target;\n });\n","import { decorate } from './decorator-factory.ts';\nimport type { ModelStaticMethodDecorator } from './decorator-types.ts';\n\n/**\n * Registers the decorated static method as a `beforeValidate` hook of the model (like `Model.beforeValidate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeValidate\n * static async onBeforeValidate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeValidate: ModelStaticMethodDecorator = decorate.forHook('beforeValidate');\n\n/**\n * Registers the decorated static method as an `afterValidate` hook of the model (like `Model.afterValidate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterValidate\n * static async onAfterValidate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterValidate: ModelStaticMethodDecorator = decorate.forHook('afterValidate');\n\n/**\n * Registers the decorated static method as a `validationFailed` hook of the model (like `Model.validationFailed`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @ValidationFailed\n * static async onValidationFailed(user: User, options: unknown, error: unknown) {}\n * }\n * ```\n */\nexport const ValidationFailed: ModelStaticMethodDecorator = decorate.forHook('validationFailed');\n\n/**\n * Registers the decorated static method as a `beforeCreate` hook of the model (like `Model.beforeCreate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeCreate\n * static async onBeforeCreate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeCreate: ModelStaticMethodDecorator = decorate.forHook('beforeCreate');\n\n/**\n * Registers the decorated static method as an `afterCreate` hook of the model (like `Model.afterCreate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterCreate\n * static async onAfterCreate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterCreate: ModelStaticMethodDecorator = decorate.forHook('afterCreate');\n\n/**\n * Registers the decorated static method as a `beforeUpdate` hook of the model (like `Model.beforeUpdate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeUpdate\n * static async onBeforeUpdate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeUpdate: ModelStaticMethodDecorator = decorate.forHook('beforeUpdate');\n\n/**\n * Registers the decorated static method as an `afterUpdate` hook of the model (like `Model.afterUpdate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterUpdate\n * static async onAfterUpdate(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterUpdate: ModelStaticMethodDecorator = decorate.forHook('afterUpdate');\n\n/**\n * Registers the decorated static method as a `beforeSave` hook of the model (like `Model.beforeSave`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeSave\n * static async onBeforeSave(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeSave: ModelStaticMethodDecorator = decorate.forHook('beforeSave');\n\n/**\n * Registers the decorated static method as an `afterSave` hook of the model (like `Model.afterSave`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterSave\n * static async onAfterSave(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterSave: ModelStaticMethodDecorator = decorate.forHook('afterSave');\n\n/**\n * Registers the decorated static method as a `beforeDestroy` hook of the model (like `Model.beforeDestroy`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeDestroy\n * static async onBeforeDestroy(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeDestroy: ModelStaticMethodDecorator = decorate.forHook('beforeDestroy');\n\n/**\n * Registers the decorated static method as an `afterDestroy` hook of the model (like `Model.afterDestroy`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterDestroy\n * static async onAfterDestroy(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterDestroy: ModelStaticMethodDecorator = decorate.forHook('afterDestroy');\n\n/**\n * Registers the decorated static method as a `beforeRestore` hook of the model (like `Model.beforeRestore`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeRestore\n * static async onBeforeRestore(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeRestore: ModelStaticMethodDecorator = decorate.forHook('beforeRestore');\n\n/**\n * Registers the decorated static method as an `afterRestore` hook of the model (like `Model.afterRestore`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterRestore\n * static async onAfterRestore(user: User, options: unknown) {}\n * }\n * ```\n */\nexport const AfterRestore: ModelStaticMethodDecorator = decorate.forHook('afterRestore');\n\n/**\n * Registers the decorated static method as a `beforeUpsert` hook of the model (like `Model.beforeUpsert`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeUpsert\n * static async onBeforeUpsert(values: unknown, options: unknown) {}\n * }\n * ```\n */\nexport const BeforeUpsert: ModelStaticMethodDecorator = decorate.forHook('beforeUpsert');\n\n/**\n * Registers the decorated static method as an `afterUpsert` hook of the model (like `Model.afterUpsert`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterUpsert\n * static async onAfterUpsert(result: unknown, options: unknown) {}\n * }\n * ```\n */\nexport const AfterUpsert: ModelStaticMethodDecorator = decorate.forHook('afterUpsert');\n\n/**\n * Registers the decorated static method as a `beforeBulkCreate` hook of the model (like `Model.beforeBulkCreate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeBulkCreate\n * static async onBeforeBulkCreate(users: User[], options: unknown) {}\n * }\n * ```\n */\nexport const BeforeBulkCreate: ModelStaticMethodDecorator = decorate.forHook('beforeBulkCreate');\n\n/**\n * Registers the decorated static method as an `afterBulkCreate` hook of the model (like `Model.afterBulkCreate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterBulkCreate\n * static async onAfterBulkCreate(users: User[], options: unknown) {}\n * }\n * ```\n */\nexport const AfterBulkCreate: ModelStaticMethodDecorator = decorate.forHook('afterBulkCreate');\n\n/**\n * Registers the decorated static method as a `beforeBulkUpdate` hook of the model (like `Model.beforeBulkUpdate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeBulkUpdate\n * static async onBeforeBulkUpdate(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeBulkUpdate: ModelStaticMethodDecorator = decorate.forHook('beforeBulkUpdate');\n\n/**\n * Registers the decorated static method as an `afterBulkUpdate` hook of the model (like `Model.afterBulkUpdate`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterBulkUpdate\n * static async onAfterBulkUpdate(options: unknown) {}\n * }\n * ```\n */\nexport const AfterBulkUpdate: ModelStaticMethodDecorator = decorate.forHook('afterBulkUpdate');\n\n/**\n * Registers the decorated static method as a `beforeBulkDestroy` hook of the model (like `Model.beforeBulkDestroy`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeBulkDestroy\n * static async onBeforeBulkDestroy(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeBulkDestroy: ModelStaticMethodDecorator = decorate.forHook('beforeBulkDestroy');\n\n/**\n * Registers the decorated static method as an `afterBulkDestroy` hook of the model (like `Model.afterBulkDestroy`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterBulkDestroy\n * static async onAfterBulkDestroy(options: unknown) {}\n * }\n * ```\n */\nexport const AfterBulkDestroy: ModelStaticMethodDecorator = decorate.forHook('afterBulkDestroy');\n\n/**\n * Registers the decorated static method as a `beforeBulkRestore` hook of the model (like `Model.beforeBulkRestore`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeBulkRestore\n * static async onBeforeBulkRestore(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeBulkRestore: ModelStaticMethodDecorator = decorate.forHook('beforeBulkRestore');\n\n/**\n * Registers the decorated static method as an `afterBulkRestore` hook of the model (like `Model.afterBulkRestore`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterBulkRestore\n * static async onAfterBulkRestore(options: unknown) {}\n * }\n * ```\n */\nexport const AfterBulkRestore: ModelStaticMethodDecorator = decorate.forHook('afterBulkRestore');\n\n/**\n * Registers the decorated static method as a `beforeFind` hook of the model (like `Model.beforeFind`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeFind\n * static async onBeforeFind(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeFind: ModelStaticMethodDecorator = decorate.forHook('beforeFind');\n\n/**\n * Registers the decorated static method as a `beforeFindAfterExpandIncludeAll` hook of the model (like `Model.beforeFindAfterExpandIncludeAll`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeFindAfterExpandIncludeAll\n * static async onBeforeFindAfterExpandIncludeAll(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeFindAfterExpandIncludeAll: ModelStaticMethodDecorator = decorate.forHook(\n 'beforeFindAfterExpandIncludeAll',\n);\n\n/**\n * Registers the decorated static method as a `beforeFindAfterOptions` hook of the model (like `Model.beforeFindAfterOptions`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeFindAfterOptions\n * static async onBeforeFindAfterOptions(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeFindAfterOptions: ModelStaticMethodDecorator =\n decorate.forHook('beforeFindAfterOptions');\n\n/**\n * Registers the decorated static method as an `afterFind` hook of the model (like `Model.afterFind`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @AfterFind\n * static async onAfterFind(result: unknown, options: unknown) {}\n * }\n * ```\n */\nexport const AfterFind: ModelStaticMethodDecorator = decorate.forHook('afterFind');\n\n/**\n * Registers the decorated static method as a `beforeCount` hook of the model (like `Model.beforeCount`).\n * The method receives the hook arguments; static methods only. Registered when `sequelize.addModels` applies the class.\n * Accepts the TC39 and the legacy `experimentalDecorators` call signature.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @BeforeCount\n * static async onBeforeCount(options: unknown) {}\n * }\n * ```\n */\nexport const BeforeCount: ModelStaticMethodDecorator = decorate.forHook('beforeCount');\n","import type { ScopeOptions } from '../model/scope-registry.ts';\nimport { decorate } from './decorator-factory.ts';\nimport type { ModelClassDecorator } from './decorator-types.ts';\nimport type { ScopesInput, TableOptions } from './model-metadata.ts';\n\n/**\n * Marks a class as a model and sets its table options: everything `Model.init` accepts except\n * `sequelize`. Optional; a decorated class without `@Table` gets the `Model.init` defaults.\n *\n * Use it bare (`@Table`) or called. The class must be registered with `sequelize.addModels`.\n *\n * @param options - Table options (`tableName`, `schema`, `timestamps`, `paranoid`, `indexes`, `hooks`, …).\n * @returns A class decorator.\n * @example\n * ```ts\n * @Table({ tableName: 'users', paranoid: true })\n * class User extends Model {}\n * ```\n * @see {@link Sequelize.addModels}\n */\nexport const Table = decorate.optionalClass<TableOptions>((options) =>\n decorate.forClass((meta) => Object.assign(meta.table, options)),\n);\n\n/**\n * Sets the default scope of a model (`defaultScope` of `Model.init`).\n *\n * @param scope - Scope options, or a function returning them (evaluated by `addModels`, so it may refer to other models).\n * @returns A class decorator.\n * @example\n * ```ts\n * @DefaultScope(() => ({ where: { active: true } }))\n * class User extends Model {}\n * ```\n */\nexport const DefaultScope = (scope: ScopeOptions | (() => ScopeOptions)): ModelClassDecorator =>\n decorate.forClass((meta) => {\n meta.defaultScope = scope;\n });\n\n/**\n * Defines the named scopes of a model (`scopes` of `Model.init`).\n *\n * @param scopes - Scopes by name (options or functions returning options), or a function returning them.\n * @returns A class decorator.\n * @example\n * ```ts\n * @Scopes({ recent: { order: [['createdAt', 'DESC']] }, named: (name: string) => ({ where: { name } }) })\n * class User extends Model {}\n * ```\n */\nexport const Scopes = (scopes: ScopesInput | (() => ScopesInput)): ModelClassDecorator =>\n decorate.forClass((meta) => {\n meta.scopes = scopes;\n });\n","import { decorate } from './decorator-factory.ts';\nimport type { ModelPropertyDecorator } from './decorator-types.ts';\n\n/**\n * Names the attribute that holds the creation time (`createdAt: '<attribute>'`).\n *\n * @example\n * ```ts\n * class User extends Model {\n * @CreatedAt\n * creationDate!: Date;\n * }\n * ```\n */\nexport const CreatedAt: ModelPropertyDecorator = decorate.forProperty((meta, key) => {\n meta.timestamps.createdAt = key;\n});\n\n/**\n * Names the attribute that holds the last update time (`updatedAt: '<attribute>'`).\n *\n * @example\n * ```ts\n * class User extends Model {\n * @UpdatedAt\n * updatedOn!: Date;\n * }\n * ```\n */\nexport const UpdatedAt: ModelPropertyDecorator = decorate.forProperty((meta, key) => {\n meta.timestamps.updatedAt = key;\n});\n\n/**\n * Names the attribute that holds the deletion time (`deletedAt: '<attribute>'`) and makes the\n * model paranoid unless `@Table` sets `paranoid` explicitly.\n *\n * @example\n * ```ts\n * class User extends Model {\n * @DeletedAt\n * removedAt!: Date | null;\n * }\n * ```\n */\nexport const DeletedAt: ModelPropertyDecorator = decorate.forProperty((meta, key) => {\n meta.timestamps.deletedAt = key;\n});\n"],"mappings":";;;;;;;;;;;;;AAkCA,IAAsB,mBAAtB,MAA2D;;CAEzD;;CAEA;;;;;CAMA,YAAY,KAAa,SAAiB;EACxC,KAAK,MAAM;EACX,KAAK,UAAU;CACjB;;;;;;;;CASA,OAAiB,QAAQ,MAAc,OAAuB;EAC5D,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,MAAM,GAAG,KAAK,uCAAuC,OAAO,KAAK,GAAG;EAEhF,OAAO;CACT;;;;;;;CAQA,OAAO,KAAK,OAAgC;EAC1C,OAAO,OAAO,UAAU,aAAc,QAAgC;CACxE;AACF;;;;;;;AC7DA,IAAa,qBAAb,MAAgC;;;;;;;CAO9B,MAAM,MAAsB;EAC1B,MAAM,OAAO,KAAK,QAAQ,GAAG;EAC7B,OAAO,SAAS,KAAK,CAAC,IAAI,KAAK,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC;CACvD;CAEA,UAAU,MAAc,OAAsB;EAC5C,MAAM,MAAM,KAAK,MAAM,KAAK,CAAC,CAAC,OAAO,MAAM;EAC3C,MAAM,OAAO,QAAQ,KAAK,KAAK,SAAS,QAAQ;EAChD,OAAO;GA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