viborm 1.3.1 → 1.3.3

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 (206) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-CWLEmon2.mjs} +2 -2
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-CWLEmon2.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DGJPz8-G.mjs} +2 -2
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DGJPz8-G.mjs.map} +1 -1
  7. package/dist/{bind-parameter-capacity-qfEejeOX.mjs → bind-parameter-capacity-DiwRmZ1h.mjs} +2 -2
  8. package/dist/{bind-parameter-capacity-qfEejeOX.mjs.map → bind-parameter-capacity-DiwRmZ1h.mjs.map} +1 -1
  9. package/dist/{builder-s1ySUuMb.mjs → builder-D6Ug-zjM.mjs} +2 -2
  10. package/dist/{builder-s1ySUuMb.mjs.map → builder-D6Ug-zjM.mjs.map} +1 -1
  11. package/dist/bun-sql.d.mts +1 -1
  12. package/dist/bun-sql.mjs +1 -1
  13. package/dist/bun-sqlite.d.mts +1 -1
  14. package/dist/bun-sqlite.mjs +1 -1
  15. package/dist/cache/cloudflare-kv.d.mts +1 -1
  16. package/dist/cache/cloudflare-kv.mjs +1 -1
  17. package/dist/cache/memory.d.mts +1 -1
  18. package/dist/cache/memory.mjs +1 -1
  19. package/dist/cache.d.mts +1 -1
  20. package/dist/cache.mjs +1 -1
  21. package/dist/cache.mjs.map +1 -1
  22. package/dist/chain-B5IbqLGi.mjs +2 -0
  23. package/dist/chain-B5IbqLGi.mjs.map +1 -0
  24. package/dist/cli.mjs +1 -1
  25. package/dist/client-BmcHzDBa.mjs +2 -0
  26. package/dist/client-BmcHzDBa.mjs.map +1 -0
  27. package/dist/{client-70MrTq1E.d.mts → client-DR0vYetv.d.mts} +2 -2
  28. package/dist/{client-BgJ7Faln.mjs → client-DjtWangN.mjs} +3 -3
  29. package/dist/{client-BgJ7Faln.mjs.map → client-DjtWangN.mjs.map} +1 -1
  30. package/dist/client.d.mts +1 -1
  31. package/dist/client.mjs +1 -1
  32. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  33. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  34. package/dist/config.d.mts +1 -1
  35. package/dist/config.mjs +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/datetime-physical-codec-qKxFtI3B.mjs +2 -0
  39. package/dist/datetime-physical-codec-qKxFtI3B.mjs.map +1 -0
  40. package/dist/{driver-vn-9CN0y.mjs → driver-BvP7eW0A.mjs} +2 -2
  41. package/dist/{driver-vn-9CN0y.mjs.map → driver-BvP7eW0A.mjs.map} +1 -1
  42. package/dist/{driver-B9fIori_.mjs → driver-Bzc0GCQ4.mjs} +2 -2
  43. package/dist/{driver-B9fIori_.mjs.map → driver-Bzc0GCQ4.mjs.map} +1 -1
  44. package/dist/driver.d.mts +1 -1
  45. package/dist/driver.mjs +1 -1
  46. package/dist/{error-mapping-C9WgitPi.mjs → error-mapping-6op318w6.mjs} +2 -2
  47. package/dist/error-mapping-6op318w6.mjs.map +1 -0
  48. package/dist/every-WUr3mlvg.mjs +2 -0
  49. package/dist/{every-CcpKWCVo.mjs.map → every-WUr3mlvg.mjs.map} +1 -1
  50. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  51. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  52. package/dist/{geo-area-codec-CbkmFArQ.mjs → geo-area-codec-BmMmWgU_.mjs} +2 -2
  53. package/dist/{geo-area-codec-CbkmFArQ.mjs.map → geo-area-codec-BmMmWgU_.mjs.map} +1 -1
  54. package/dist/{geo-point-codec-DyEHMdJg.mjs → geo-point-codec-D95uXgDF.mjs} +2 -2
  55. package/dist/{geo-point-codec-DyEHMdJg.mjs.map → geo-point-codec-D95uXgDF.mjs.map} +1 -1
  56. package/dist/{hydration-BsPZI4jE.mjs → hydration-BflrXEIQ.mjs} +2 -2
  57. package/dist/{hydration-BsPZI4jE.mjs.map → hydration-BflrXEIQ.mjs.map} +1 -1
  58. package/dist/{identifier-conversion-BneQiLxQ.mjs → identifier-conversion-Bs7A2GGU.mjs} +2 -2
  59. package/dist/{identifier-conversion-BneQiLxQ.mjs.map → identifier-conversion-Bs7A2GGU.mjs.map} +1 -1
  60. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  61. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  62. package/dist/{index-VsM29vYN.d.mts → index-B_jh2oaQ.d.mts} +38 -11
  63. package/dist/index.d.mts +2 -2
  64. package/dist/index.mjs +1 -1
  65. package/dist/instrumentation.d.mts +1 -1
  66. package/dist/instrumentation.mjs +1 -1
  67. package/dist/{key-D9LtHxVK.mjs → key-B89Z4vxn.mjs} +2 -2
  68. package/dist/{key-D9LtHxVK.mjs.map → key-B89Z4vxn.mjs.map} +1 -1
  69. package/dist/{libsql-BlSBYwd_.mjs → libsql-C8dn4id0.mjs} +2 -2
  70. package/dist/{libsql-BlSBYwd_.mjs.map → libsql-C8dn4id0.mjs.map} +1 -1
  71. package/dist/libsql.d.mts +1 -1
  72. package/dist/libsql.mjs +1 -1
  73. package/dist/{memory-C0k-_S_n.mjs → memory-B7CcHS6I.mjs} +2 -2
  74. package/dist/{memory-C0k-_S_n.mjs.map → memory-B7CcHS6I.mjs.map} +1 -1
  75. package/dist/migrations/mysql.d.mts +4 -4
  76. package/dist/migrations/mysql.mjs +1 -1
  77. package/dist/migrations/postgres.d.mts +4 -4
  78. package/dist/migrations/postgres.mjs +1 -1
  79. package/dist/migrations/sqlite.d.mts +4 -4
  80. package/dist/migrations/sqlite.mjs +1 -1
  81. package/dist/migrations/storage/durable-object.mjs +1 -1
  82. package/dist/migrations/storage/fs.mjs +1 -1
  83. package/dist/migrations/storage/r2.mjs +1 -1
  84. package/dist/migrations/tenant.d.mts +2 -2
  85. package/dist/migrations/tenant.mjs +1 -1
  86. package/dist/migrations.d.mts +4 -4
  87. package/dist/migrations.mjs +1 -1
  88. package/dist/mysql-adapter-ABpgFB2N.mjs +2 -0
  89. package/dist/mysql-adapter-ABpgFB2N.mjs.map +1 -0
  90. package/dist/{mysql-DOLHwIM_.mjs → mysql-mUmhH9Cf.mjs} +2 -2
  91. package/dist/{mysql-DOLHwIM_.mjs.map → mysql-mUmhH9Cf.mjs.map} +1 -1
  92. package/dist/mysql2.d.mts +1 -1
  93. package/dist/mysql2.mjs +1 -1
  94. package/dist/neon-http.d.mts +1 -1
  95. package/dist/neon-http.mjs +1 -1
  96. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  97. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  98. package/dist/{object-store-D9mvOHP4.d.mts → object-store-Ds9NKRU6.d.mts} +3 -3
  99. package/dist/permissions.d.mts +2 -2
  100. package/dist/permissions.mjs +1 -1
  101. package/dist/permissions.mjs.map +1 -1
  102. package/dist/pg.d.mts +1 -1
  103. package/dist/pg.mjs +1 -1
  104. package/dist/pglite.d.mts +1 -1
  105. package/dist/pglite.mjs +1 -1
  106. package/dist/{physical-CAOaNM4R.mjs → physical-uJfmo4-Z.mjs} +2 -2
  107. package/dist/{physical-CAOaNM4R.mjs.map → physical-uJfmo4-Z.mjs.map} +1 -1
  108. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-C79aDzOg.mjs} +2 -2
  109. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-C79aDzOg.mjs.map} +1 -1
  110. package/dist/planetscale.d.mts +1 -1
  111. package/dist/planetscale.mjs +1 -1
  112. package/dist/{planner-C1NzLBge.d.mts → planner-DHZG9Vy7.d.mts} +1 -1
  113. package/dist/{postgres-DQVSTqVm.mjs → postgres-BACQ_wqF.mjs} +2 -2
  114. package/dist/{postgres-DQVSTqVm.mjs.map → postgres-BACQ_wqF.mjs.map} +1 -1
  115. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-Ci07rgh_.mjs} +2 -2
  116. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-Ci07rgh_.mjs.map} +1 -1
  117. package/dist/postgres-adapter-DaMvNOkx.mjs +2 -0
  118. package/dist/postgres-adapter-DaMvNOkx.mjs.map +1 -0
  119. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-D403cLyA.mjs} +2 -2
  120. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-D403cLyA.mjs.map} +1 -1
  121. package/dist/postgres.d.mts +1 -1
  122. package/dist/postgres.mjs +1 -1
  123. package/dist/{provider-limits-Da00ilvv.mjs → provider-limits-DSv2tYFr.mjs} +2 -2
  124. package/dist/{provider-limits-Da00ilvv.mjs.map → provider-limits-DSv2tYFr.mjs.map} +1 -1
  125. package/dist/result-shape-BKydBCsR.mjs +2 -0
  126. package/dist/result-shape-BKydBCsR.mjs.map +1 -0
  127. package/dist/rows-v1VuwOTa.mjs +2 -0
  128. package/dist/rows-v1VuwOTa.mjs.map +1 -0
  129. package/dist/{scalar-CpEwuJvn.mjs → scalar-Cm7nMFmO.mjs} +2 -2
  130. package/dist/{scalar-CpEwuJvn.mjs.map → scalar-Cm7nMFmO.mjs.map} +1 -1
  131. package/dist/schema/json.d.mts +1 -1
  132. package/dist/schema/json.mjs +1 -1
  133. package/dist/{schema-BnzGHn7k.mjs → schema-D3-ScVH6.mjs} +2 -2
  134. package/dist/{schema-BnzGHn7k.mjs.map → schema-D3-ScVH6.mjs.map} +1 -1
  135. package/dist/{schema-introspection-DZsdP6bi.mjs → schema-introspection-TdJrSaKd.mjs} +3 -3
  136. package/dist/{schema-introspection-DZsdP6bi.mjs.map → schema-introspection-TdJrSaKd.mjs.map} +1 -1
  137. package/dist/schema.d.mts +1 -1
  138. package/dist/schema.mjs +1 -1
  139. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-uZfvbYjz.mjs} +2 -2
  140. package/dist/select-assembly-uZfvbYjz.mjs.map +1 -0
  141. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  142. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  143. package/dist/sha256-CEYo7k7R.mjs +2 -0
  144. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  145. package/dist/soft-delete.d.mts +1 -1
  146. package/dist/sql-BvHwL73I.mjs +2 -0
  147. package/dist/sql-BvHwL73I.mjs.map +1 -0
  148. package/dist/{sql-EsoN_7Et.d.mts → sql-Q_twK-wW.d.mts} +5 -0
  149. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  150. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  151. package/dist/sql.d.mts +1 -1
  152. package/dist/sql.mjs +1 -1
  153. package/dist/sqlite-adapter-DPc9T6Lh.mjs +2 -0
  154. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +1 -0
  155. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-BvSlEs5W.mjs} +2 -2
  156. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-BvSlEs5W.mjs.map} +1 -1
  157. package/dist/sqlite3.d.mts +1 -1
  158. package/dist/sqlite3.mjs +1 -1
  159. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-CYdZ_KXH.mjs} +2 -2
  160. package/dist/standard-sql-CYdZ_KXH.mjs.map +1 -0
  161. package/dist/{to-many-C5RMZl05.mjs → to-many-Btc9X5Ga.mjs} +2 -2
  162. package/dist/{to-many-C5RMZl05.mjs.map → to-many-Btc9X5Ga.mjs.map} +1 -1
  163. package/dist/{utils-C3r4gO3Y.mjs → utils-Qr8ug94X.mjs} +2 -2
  164. package/dist/{utils-C3r4gO3Y.mjs.map → utils-Qr8ug94X.mjs.map} +1 -1
  165. package/dist/v-514RME2X.mjs +2 -0
  166. package/dist/v-514RME2X.mjs.map +1 -0
  167. package/dist/{validation-BQtO6srU.mjs → validation-CPnrLcjW.mjs} +2 -2
  168. package/dist/{validation-BQtO6srU.mjs.map → validation-CPnrLcjW.mjs.map} +1 -1
  169. package/dist/validation-gwZYm3Yn.mjs +2 -0
  170. package/dist/validation-gwZYm3Yn.mjs.map +1 -0
  171. package/dist/validation.d.mts +1 -1
  172. package/dist/validation.mjs +1 -1
  173. package/dist/{validator-CVSrhn0u.mjs → validator-CQOw7G3q.mjs} +2 -2
  174. package/dist/{validator-CVSrhn0u.mjs.map → validator-CQOw7G3q.mjs.map} +1 -1
  175. package/dist/version-0RVYpih5.mjs +2 -0
  176. package/dist/{version-C8QLCt1n.mjs.map → version-0RVYpih5.mjs.map} +1 -1
  177. package/package.json +15 -15
  178. package/dist/chain-7qiFSE8J.mjs +0 -2
  179. package/dist/chain-7qiFSE8J.mjs.map +0 -1
  180. package/dist/client-6YgGlXzN.mjs +0 -2
  181. package/dist/client-6YgGlXzN.mjs.map +0 -1
  182. package/dist/controls-KQ85SWfT.mjs +0 -2
  183. package/dist/controls-KQ85SWfT.mjs.map +0 -1
  184. package/dist/datetime-physical-codec-BEqQbIP_.mjs +0 -2
  185. package/dist/datetime-physical-codec-BEqQbIP_.mjs.map +0 -1
  186. package/dist/error-mapping-C9WgitPi.mjs.map +0 -1
  187. package/dist/every-CcpKWCVo.mjs +0 -2
  188. package/dist/identity-oQvIe7u8.mjs +0 -2
  189. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  190. package/dist/mysql-adapter-C6c5govr.mjs +0 -2
  191. package/dist/mysql-adapter-C6c5govr.mjs.map +0 -1
  192. package/dist/postgres-adapter-CxEit2-v.mjs +0 -2
  193. package/dist/postgres-adapter-CxEit2-v.mjs.map +0 -1
  194. package/dist/result-shape-B6yWtnx_.mjs +0 -2
  195. package/dist/result-shape-B6yWtnx_.mjs.map +0 -1
  196. package/dist/select-assembly-CkGe2ABs.mjs.map +0 -1
  197. package/dist/sql-Bhxq9arK.mjs +0 -2
  198. package/dist/sql-Bhxq9arK.mjs.map +0 -1
  199. package/dist/sqlite-adapter-BXAJy3mI.mjs +0 -2
  200. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +0 -1
  201. package/dist/standard-sql-CoGqv-iX.mjs.map +0 -1
  202. package/dist/v-DtLdBQYg.mjs +0 -2
  203. package/dist/v-DtLdBQYg.mjs.map +0 -1
  204. package/dist/validation-BamBwne9.mjs +0 -2
  205. package/dist/validation-BamBwne9.mjs.map +0 -1
  206. package/dist/version-C8QLCt1n.mjs +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"file":"mysql-adapter-C6c5govr.mjs","names":["sql","#batchRefs","#assemble"],"sources":["../src/adapters/databases/mysql/mysql-adapter.ts"],"sourcesContent":["import { unsupportedVector } from \"@errors\";\nimport type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { type Sql, sql } from \"@sql\";\nimport { encodeMySqlDateTime } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport type { ArithmeticTarget } from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport {\n type AdapterResultParser,\n passThroughParseResult,\n} from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createMySqlBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n halfEvenQuotient,\n scaleFactorSql,\n scaleUnitSql,\n signedNumerator,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport { parseIntegerBoolean } from \"../../shared/result-parsing\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n buildJsonPath,\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createEmulatedNullsOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMembershipOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n stringifyJson,\n} from \"../../shared/standard-sql\";\n\nconst quoteIdent = createIdentifierQuoter(\"`\");\nconst MYSQL_CONSTRAINTS = createNamedConstraintIdentities(() => \"PRIMARY\");\n\n/**\n * MySQL has `MOD()` but no exact integer-quotient function for decimals: `DIV`\n * converts both sides to BIGINT (so it overflows and truncates a wide\n * `DECIMAL`), and `TRUNCATE(n / d, 0)` computes `n / d` to\n * `div_precision_increment` extra digits and ROUNDS there first, which can turn\n * a value just below a half into an exact-looking tie.\n *\n * `(n - MOD(n, d)) / d` avoids both: the numerator is exactly divisible by `d`,\n * so the division's true result has no fractional digits and the extra digits\n * MySQL computes are all zero.\n */\nconst MYSQL_INTEGERS: ExactIntegerArithmetic = {\n // The CAST is not decoration. MySQL's `/` ALWAYS returns\n // `div_precision_increment` (four, by default) fractional digits, so an exact\n // integer quotient arrives typed `DECIMAL(w, 4)` — four digits of the 65-digit\n // exact domain spent on zeros, and any product taking that value as an operand\n // would carry them into ITS width. Casting back to the widest exact integer\n // domain is exact here (the value has no fraction to lose) and is what keeps\n // every downstream term integer-typed.\n quotient: (n: Sql, d: Sql): Sql =>\n sql`CAST((${n} - MOD(${n}, ${d})) / ${d} AS DECIMAL(65,0))`,\n remainder: (n: Sql, d: Sql): Sql => sql`MOD(${n}, ${d})`,\n};\n\n/**\n * MySQL's exact decimal domain, in digits — the ceiling every expression below\n * is written to stay under (plan 5.3: \"MySQL expressions avoid an intermediate\n * wider than its 65-digit exact domain\").\n */\nconst MYSQL_EXACT_DIGITS = 65;\n\nconst mysqlMaximumCoefficient = (digits: number): Sql =>\n sql.raw(\"9\".repeat(digits));\n\nconst mysqlStrictMode = sql`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`;\n\nconst mysqlArithmeticFailure = sql`JSON_EXTRACT('x', '$')`;\n\n/** `CAST(<expr> AS DECIMAL(precision,scale))`, the width-declaring device. */\nconst decimalCast = (expr: Sql, precision: number, scale: number): Sql =>\n sql`CAST(${expr} AS ${sql.raw(`DECIMAL(${precision},${scale})`)})`;\n\n/**\n * The signed unscaled COEFFICIENT of a logical `DECIMAL(p,s)` expression, as an\n * exact integer — WITHOUT ever multiplying the whole value by `10^s`.\n *\n * `column * 10^s` is the obvious spelling and it is the unsafe one. MySQL types\n * a product as `DECIMAL(p1+p2, s1+s2)` capped at `(65, 30)`, so multiplying a\n * `DECIMAL(65,30)` column by a `DECIMAL(31,0)` factor asks for a 96-digit type,\n * gets a 65-digit one whose 30 fractional digits leave 35 for an integer that\n * needs 65 — and MySQL answers ZERO, with no warning and no error (measured on\n * 8.4: `SELECT CAST(REPEAT('9',50) AS DECIMAL(65,0)) * 0.<29 zeros>1` is\n * `0.000…0`). Splitting the value first is what keeps every factor small:\n *\n * whole = TRUNCATE(v, 0) |whole| < 10^(p-s), scale 0\n * fraction = v - whole |fraction| < 1, scale s\n * coefficient = whole * 10^s + fraction * 10^s\n *\n * Widths, by construction, for every descriptor MySQL admits (`p <= 65`,\n * `s <= 30`, `p + s <= 65`): `whole * 10^s` is typed\n * `DECIMAL(min(p+2,65), 0)` and valued\n * below `10^p`; `fraction * 10^s` is typed `DECIMAL(2s+2, s)` — at most 62\n * digits — and valued below `10^s`, so its cast to `DECIMAL(s,0)` is exact.\n * Neither product's operands sum past the exact domain, so neither can take the\n * silent arm above.\n */\nconst mysqlCoefficient = (value: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return value;\n const factor = scaleFactorSql(scale);\n const whole = sql`TRUNCATE(${value}, 0)`;\n const fraction = decimalCast(sql`(${value} - ${whole})`, scale + 1, scale);\n return sql`(${whole} * ${factor} + ${decimalCast(sql`(${fraction} * ${factor})`, scale, 0)})`;\n};\n\n/**\n * The logical `DECIMAL(p,s)` value of an exact integer COEFFICIENT — the\n * inverse of {@link mysqlCoefficient}, and unsafe for the same reason in the\n * same place.\n *\n * `coefficient * 10^-s` would multiply a `p`-digit integer by a\n * `DECIMAL(s+1,s)` literal: `p + s + 1` digits of type for a value that needs\n * `p`, which is the silent-zero arm again for a wide descriptor. So the\n * coefficient is split by `10^s` FIRST — an integer part that is already the\n * answer's integer part, and a remainder below `10^s` that is the only thing\n * the tiny `10^-s` literal ever multiplies:\n *\n * integer part = (coefficient - MOD(coefficient, 10^s)) / 10^s\n * fraction = MOD(coefficient, 10^s) * 10^-s\n *\n * Widths: the division is typed `DECIMAL(w, 4)` over a value below `10^(p-s)`,\n * and the fractional product's operands sum to `2s + 1` — at most 61 digits.\n */\nconst mysqlLogical = (coefficient: Sql, descriptor: DecimalDescriptor): Sql => {\n const { scale } = descriptor;\n if (scale === 0) return coefficient;\n const factor = scaleFactorSql(scale);\n const remainder = sql`MOD(${coefficient}, ${factor})`;\n return sql`((${coefficient} - ${remainder}) / ${factor} + ${decimalCast(remainder, scale, 0)} * ${scaleUnitSql(scale)})`;\n};\n\n/**\n * Assign one coefficient-space answer without letting a non-strict MySQL\n * session turn overflow into a clipped value. Strict sessions retain their\n * native error. A non-strict session reaches the answer only after the caller's\n * operation-specific precondition proves its intermediate is exact and the\n * target-domain check proves the final coefficient fits.\n *\n * The session-mode arm is deliberately first. `CASE` is the same lazy error\n * primitive used by this adapter's assertion queries, so a safe or NULL arm\n * never evaluates the invalid JSON expression that raises the provider error.\n */\nconst mysqlGuardedDecimalAssignment = (\n column: Sql,\n coefficient: Sql,\n descriptor: DecimalDescriptor,\n intermediateFits: Sql\n): Sql => {\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const logical = mysqlLogical(coefficient, descriptor);\n return sql`${column} = CASE WHEN ${mysqlStrictMode} THEN ${logical} WHEN ${column} IS NULL THEN NULL WHEN ${intermediateFits} THEN CASE WHEN ${coefficient} BETWEEN -${maximum} AND ${maximum} THEN ${logical} ELSE ${mysqlArithmeticFailure} END ELSE ${mysqlArithmeticFailure} END`;\n};\n\nconst mysqlDecimalIncrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} <= ${maximum} - ${operand} WHEN ${operand} < 0 THEN ${current} >= -${maximum} - ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} + ${operand})`,\n descriptor,\n fits\n );\n};\n\nconst mysqlDecimalDecrement = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const current = mysqlCoefficient(column, descriptor);\n const operand = mysqlCoefficient(by, descriptor);\n const maximum = mysqlMaximumCoefficient(descriptor.precision);\n const fits = sql`CASE WHEN ${operand} > 0 THEN ${current} >= -${maximum} + ${operand} WHEN ${operand} < 0 THEN ${current} <= ${maximum} + ${operand} ELSE TRUE END`;\n return mysqlGuardedDecimalAssignment(\n column,\n sql`(${current} - ${operand})`,\n descriptor,\n fits\n );\n};\n\n/**\n * `column = halfEven(column x by)`, computed on COEFFICIENTS.\n *\n * This is plan 5.3's rule verbatim — `multiply = halfEven((x * y) / F)` — and\n * it is stated on integers because MySQL cannot state it on logical values: the\n * exact product of two `DECIMAL(p,s)` values carries `2s` fractional digits,\n * and MySQL caps an expression's scale at 30, ROUNDING anything finer away\n * before the tie this rule exists to decide is ever visible (measured: `1e-30 *\n * 1e-30` is `0.000…0` at `DECIMAL(65,30)`, no warning). Coefficients have no\n * fractional digits at all, so nothing can be rounded away underneath the rule.\n *\n * WIDTH, BY CONSTRUCTION. `|x|, |y| < 10^p`, and the answer is in the field's\n * domain exactly when `|x * y| < 10^(p+s)`, so the product needs at most\n * `p + s` digits: within the 65-digit exact domain for every descriptor with\n * `precision + scale <= 65`. The quotient is `< 10^p`, the remainder `< 10^s`,\n * and the tie test compares `|r|` against `10^s - |r|` — the non-doubling form,\n * so nothing widens there either.\n *\n * Outside that bound the operation is loud on every session. A strict session\n * reaches MySQL's native overflow error. A non-strict session first proves the\n * product can be formed inside 65 digits and that the rounded coefficient fits\n * the field; a failed proof evaluates the adapter's lazy error expression\n * instead of letting MySQL clip the assignment. Both leave the row unchanged.\n */\nconst mysqlDecimalMultiply = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const left = mysqlCoefficient(column, descriptor);\n const right = mysqlCoefficient(by, descriptor);\n const maximumIntermediate = mysqlMaximumCoefficient(MYSQL_EXACT_DIGITS);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`(${left} * ${right})`,\n scaleFactorSql(descriptor.scale)\n );\n const intermediateFits = sql`CASE WHEN ${right} = 0 THEN TRUE ELSE ABS(${left}) <= ${MYSQL_INTEGERS.quotient(maximumIntermediate, sql`ABS(${right})`)} END`;\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n intermediateFits\n );\n};\n\n/**\n * `column = halfEven(column / by)`, computed on COEFFICIENTS — plan 5.3's\n * `divide = halfEven((x * F) / y)`.\n *\n * The divisor is the operand's COEFFICIENT rather than its logical value: an\n * exact quotient is spelled `(n - MOD(n, d)) / d`, and with a fractional `d`\n * the numerator `n - MOD(n, d)` is `q * d` — a `p`-digit magnitude carrying `s`\n * fractional digits, `p + s` digits for a value the integer form states in `p`.\n * Integers on both sides keep every term at its own width.\n *\n * WIDTH, BY CONSTRUCTION: `|x * F| < 10^(p+s)` — inside the exact domain for\n * every descriptor with `precision + scale <= 65`, and unconditionally, not\n * only when the answer fits. The quotient is the answer's coefficient\n * (`< 10^p` when it fits the field), the remainder is below `|y| < 10^p`, and\n * the tie compares `|r|` against `|y| - |r|`, which is why the doubled form was\n * dropped: `2|r|` at `p = 65` needs 66.\n *\n * `by` is never zero — division by canonical zero is refused before I/O.\n */\nconst mysqlDecimalDivide = (\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const divisor = mysqlCoefficient(by, descriptor);\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n signedNumerator(\n sql`(${mysqlCoefficient(column, descriptor)} * ${scaleFactorSql(descriptor.scale)})`,\n divisor\n ),\n sql`ABS(${divisor})`\n );\n return mysqlGuardedDecimalAssignment(\n column,\n coefficient,\n descriptor,\n sql.raw`TRUE`\n );\n};\n\n/**\n * The exact decimal average, on coefficients: `SUM` of the column's\n * coefficients over `COUNT(column)`, quantized half to even.\n *\n * Summing the COEFFICIENTS rather than scaling the sum is what removes the last\n * `x 10^s` from this expression: `SUM(column) * 10^s` multiplies a value MySQL\n * already types up to 65 digits by a 31-digit factor, which is the silent-zero\n * arm {@link mysqlCoefficient} exists to avoid. Every row's coefficient is\n * below `10^p`, so the only way the sum leaves the exact domain is by genuinely\n * exceeding it, and MySQL raises there.\n *\n * `COUNT(column)` counts non-nulls, so an empty or all-null group answers NULL\n * through the null-strict operators instead of dividing by zero.\n */\nconst mysqlDecimalAverage = (\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n MYSQL_INTEGERS,\n sql`SUM(${mysqlCoefficient(column, descriptor)})`,\n sql`COUNT(${column})`\n );\n return mysqlLogical(coefficient, descriptor);\n};\nconst ASCII_UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst ASCII_LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\n\nconst asciiCaseFold = (expr: Sql): Sql => {\n let folded = expr;\n for (let index = 0; index < ASCII_UPPERCASE.length; index++) {\n const upper = sql.raw(`'${ASCII_UPPERCASE[index]}'`);\n const lower = sql.raw(`'${ASCII_LOWERCASE[index]}'`);\n folded = sql`REPLACE(${folded}, ${upper}, ${lower})`;\n }\n return folded;\n};\n\n// MySQL DATETIME rejects ISO-8601's 'Z' suffix (\"Incorrect datetime value\"),\n// so datetimes are stored as naive UTC wall-clock 'YYYY-MM-DD HH:MM:SS.mmm'.\n\n// Naive datetime string as it comes back from MySQL (top-level on string\n// drivers, or inside JSON_ARRAYAGG/JSON_OBJECT includes): no 'Z'/offset.\nconst NAIVE_DATETIME_REGEX =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?$/;\n\n/** Reattach UTC to a naive MySQL datetime string so it parses as the stored instant. */\nconst naiveDateTimeToIso = (value: string): string | undefined => {\n const match = NAIVE_DATETIME_REGEX.exec(value);\n if (!match) return undefined;\n const fraction = match[3] ? match[3].padEnd(4, \"0\").slice(0, 4) : \".000\";\n return `${match[1]}T${match[2]}${fraction}Z`;\n};\n\n/** Replace a single-integer-parameter fragment with an inline literal. */\nconst inlineIntegerLiteral = (fragment: Sql): Sql => {\n const value = fragment.values.length === 1 ? fragment.values[0] : undefined;\n return typeof value === \"number\" && Number.isInteger(value)\n ? sql.raw(String(value))\n : fragment;\n};\n\nconst mysqlJsonObject = (pairs: [string, Sql][]): Sql => {\n if (pairs.length === 0) return sql.raw`JSON_OBJECT()`;\n const args = pairs.flatMap(([key, value]) => [sql`${key}`, value]);\n return sql`JSON_OBJECT(${sql.join(args, \", \")})`;\n};\n\n/** The one JSON list container every MySQL list value crosses as. */\nconst mysqlJsonListValue = (values: unknown[]): Sql =>\n sql`CAST(${stringifyJson(values)} AS JSON)`;\n\nexport class MySQLAdapter implements DatabaseAdapter {\n /**\n * The bound database, or `undefined` for the unqualified mode a\n * provider-configured MySQL2 client and every PlanetScale client keep. Under\n * Vitess the value is the keyspace qualifier submitted before routing rules\n * apply, not a proof of the routed backend.\n */\n declare readonly namespace: string | undefined;\n\n constructor(namespace?: string) {\n installAdapterNamespace(this, namespace, \"mysql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, this.geoPoint);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: MYSQL_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // MySQL requires JSON values to be stringified\n json: (v: unknown): Sql => sql`${JSON.stringify(v)}`,\n\n dateTime: (\n iso: string,\n _nativeType?: NativeTypeDeclaration,\n member?: boolean\n ): Sql =>\n sql`${member || iso.length === 10 ? iso : encodeMySqlDateTime(iso)}`,\n\n // The cast is load-bearing, not decoration. MySQL's comparison rules say\n // that when one side is a number and the other a string, BOTH are converted\n // to double and compared as floating point — so `amount = '0.1'` against a\n // `DECIMAL` column would silently answer at float precision on an otherwise\n // exact column. Casting the operand into the SAME `DECIMAL(p,s)` the DDL\n // emits keeps the whole comparison in MySQL's exact decimal domain, and\n // names one domain for the operand and the column instead of two.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${encodePhysicalDecimal(canonical, descriptor, \"text\")} AS ${sql.raw(decimalColumnType(\"mysql\", descriptor))})`,\n\n // MySQL has no `uuid` type: every compact domain is a `BINARY(n)` column\n // and takes the payload's bytes as an ordinary binary parameter, which is\n // the same parameter a blob scalar already binds. A text-stored domain\n // takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n _representation: IdRepresentation\n ): Sql => sql`${physical}`,\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder.\n // The literal is doubled ('\\\\') because MySQL's default mode treats\n // backslash as a string-literal escape; under NO_BACKSLASH_ESCAPES it\n // fails loudly rather than silently matching wildcards.\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${asciiCaseFold(column)} NOT LIKE ${asciiCaseFold(pattern)} ESCAPE '\\\\\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`LOCATE(BINARY ${value}, BINARY ${column}) > 0`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`RIGHT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value}`,\n // Two conjuncts, because on MySQL no single predicate is both exact and\n // index-usable. The index stores the column's own collation's sort keys —\n // `utf8mb4_0900_ai_ci` on a default install, which is case- AND\n // accent-insensitive — so any comparison forced to BINARY cannot range on\n // it. Measured on MySQL 8 (Docker, 20k rows): `col LIKE 'x%'` is a `range`\n // over 111 rows, while both `col LIKE BINARY 'x%'` and the\n // `LEFT(BINARY col, …)` spelling above degrade to a full `index` scan of\n // all 19731 entries.\n //\n // So the collation-native LIKE goes first as an index accelerator, and the\n // BINARY predicate — byte-identical to `startsWithText` above — follows as\n // the semantics. The accelerator can never drop a row the BINARY conjunct\n // would keep: byte-equal strings compare equal under every collation, so a\n // binary prefix match implies the collation-native one. It is not a second\n // guard on the same invariant — it decides no row's membership, only which\n // rows the server has to look at.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n startsWithPrefix: (column: Sql, value: string): Sql =>\n sql`(${column} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\\\\\' AND LEFT(BINARY ${column}, OCTET_LENGTH(${value})) = BINARY ${value})`,\n\n // `startsWithPrefix`'s twin, for the same reason and in the same shape\n // (plan §10.2). `BINARY col` is a FUNCTION of the column, so MySQL cannot\n // range on it: measured on MySQL 8.4 over 20,000 rows in the collation\n // viborm's own DDL declares, `BINARY name = ?` planned `index` over 20,455\n // rows where `name = ?` planned `ref` over 1, and `BINARY name IN (…)`\n // planned `index` over 20,455 where `name IN (…)` planned `range` over 3.\n //\n // The collation-native conjunct is the accelerator and decides no row's\n // membership: byte-identical strings compare equal under every collation\n // of the charset, so the BINARY comparison IMPLIES it. On the tables\n // viborm creates (`utf8mb4_0900_bin`) the two conjuncts say the same\n // thing; on a table viborm did not create the BINARY one is what keeps the\n // case-sensitivity contract, and the same measurement shows the pair still\n // plans `ref` over 1 row there.\n //\n // `notIn` and `not` deliberately have no such pair. Their implication runs\n // the other way — `BINARY col NOT IN ('X')` KEEPS a row spelled `x` that\n // `col NOT IN ('X')` drops on a case-insensitive column, measured at\n // 20,000 rows against 19,999 — so a conjunct would remove rows. There is\n // also nothing to win: both spellings of `NOT IN` scan all 20,442 rows.\n //\n // Parenthesized because this fragment gets composed into AND/OR chains.\n exactTextEq: (column: Sql, value: Sql): Sql =>\n sql`(${column} = ${value} AND BINARY ${column} = ${value})`,\n exactTextIn: (column: Sql, values: Sql): Sql =>\n sql`(${column} IN ${values} AND BINARY ${column} IN ${values})`,\n\n ...createMembershipOperators(),\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n asciiCaseFold,\n caseSensitiveText: (expr: Sql): Sql => sql`BINARY ${expr}`,\n\n // String operations - MySQL uses CONCAT() function\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`CONCAT(${sql.join(parts, \", \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // The expression form of `set.divide`'s integer arm: MySQL `/` yields a\n // DECIMAL quotient even for two integers, so the truncation is explicit.\n integerDivide: (left: Sql, right: Sql): Sql =>\n sql`TRUNCATE(${left} / ${right}, 0)`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n decimalCast(expr, descriptor.precision, descriptor.scale),\n\n // `CHAR` rather than `TEXT`: MySQL's CAST target list has no `TEXT`, which\n // is why `cast` below maps the generic text cast to `CHAR` too.\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`UNHEX(${expr})`\n : sql`CAST(${expr} AS CHAR)`,\n\n cast: createCastExpression({\n text: \"CHAR\",\n integer: \"SIGNED\",\n bigint: \"SIGNED\",\n boolean: \"UNSIGNED\",\n numeric: \"DECIMAL\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`LOWER(HEX(${expr}))`,\n };\n\n aggregates = {\n ...createAggregateFunctions(),\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n mysqlDecimalAverage(column, descriptor),\n\n // MySQL's widest exact DECIMAL cast operand. SUM itself can return more\n // than 65 digits; this bound belongs to exact HAVING operand lowering.\n decimalSumOperandPrecision:\n createDecimalSumOperandPrecision(MYSQL_EXACT_DIGITS),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql => sql`${left} = ${right}`,\n number: (expression: Sql): Sql => expression,\n boolean: (condition: Sql): Sql =>\n sql`JSON_EXTRACT(CASE WHEN ${condition} THEN 'true' ELSE 'false' END, '$')`,\n document: (expression: Sql): Sql => expression,\n\n object: mysqlJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`JSON_ARRAY()`,\n\n agg: (expr: Sql): Sql =>\n sql`COALESCE(JSON_ARRAYAGG(${expr}), JSON_ARRAY())`,\n\n objectFromColumns: mysqlJsonObject,\n\n // buildJsonPath quotes/escapes key segments and maps integer segments\n // to array indices; '$' alone extracts the document root\n extract: (column: Sql, path: string[]): Sql =>\n sql`JSON_EXTRACT(${column}, ${buildJsonPath(path)})`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`JSON_UNQUOTE(JSON_EXTRACT(${column}, ${buildJsonPath(path)}))`,\n\n // JSON_TYPE spells numbers three ways depending on how the literal was\n // stored; anything else (including an absent path, where JSON_TYPE is\n // NULL) falls through the CASE to NULL\n numberAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS DOUBLE) END)`;\n },\n\n // CAST(... AS BINARY) yields VARBINARY, so < / > compare bytes instead of\n // the column's (case- and accent-insensitive by default) collation\n stringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) AS BINARY) END)`;\n },\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${target}, ${value})`,\n\n lastElement: (target: Sql): Sql => sql`JSON_EXTRACT(${target}, '$[last]')`,\n\n // Comparing a JSON column to a plain string coerces the string to a JSON\n // string scalar (always-false for documents); CAST parses it as JSON\n value: (v: unknown): Sql => sql`CAST(${stringifyJson(v)} AS JSON)`,\n };\n\n arrays = {\n // MySQL uses JSON arrays\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`JSON_ARRAY()`;\n return sql`JSON_ARRAY(${sql.join(items, \", \")})`;\n },\n\n value: mysqlJsonListValue,\n\n // Deliberately the same container, by identity: MySQL stores an enum LIST\n // as JSON like every other list, so its members are ordinary JSON strings\n // and there is no element type to spell. The inline `ENUM(...)` describes\n // one member.\n enumValue: mysqlJsonListValue,\n\n // JSON_CONTAINS requires a JSON document as candidate; a bare string\n // parameter throws ER_INVALID_JSON_TEXT. JSON_ARRAY keeps the parameter's\n // type (strings quoted, numbers not): [x] ⊆ column ⟺ x ∈ column\n has: (column: Sql, value: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, JSON_ARRAY(${value}))`,\n\n hasEvery: (column: Sql, values: Sql): Sql =>\n sql`JSON_CONTAINS(${column}, ${values})`,\n\n hasSome: (column: Sql, values: Sql): Sql =>\n sql`JSON_OVERLAPS(${column}, ${values})`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(JSON_LENGTH(${column}) = 0 OR ${column} IS NULL)`,\n\n // The container as TEXT, so it reaches the decode as the exact bytes the\n // codec wrote: uncast, mysql2 parses a JSON column into a JavaScript\n // document and JSON_OBJECT nests it as a live array, and the coefficient\n // grammar would then be read off values a JSON parser already interpreted.\n exactNumericProjection: (column: Sql): Sql => sql`CAST(${column} AS CHAR)`,\n\n length: (column: Sql): Sql => sql`JSON_LENGTH(${column})`,\n\n get: (column: Sql, index: Sql): Sql =>\n sql`JSON_EXTRACT(${column}, CONCAT('$[', ${index}, ']'))`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`JSON_ARRAY_APPEND(${column}, '$', ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`JSON_SET(${column}, CONCAT('$[', ${index}, ']'), ${value})`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n // MySQL doesn't support NULLS FIRST/LAST natively - emulated\n ...createEmulatedNullsOrderBy(),\n };\n\n // mysql2's binary protocol binds JS numbers as DOUBLE, which MySQL rejects\n // in integer-only positions (\"Incorrect arguments to mysqld_stmt_execute\").\n // Inline integer LIMIT/OFFSET values instead of parameterizing them.\n clauses = {\n ...createStandardClauses(),\n limit: (count: Sql): Sql => sql`LIMIT ${inlineIntegerLiteral(count)}`,\n offset: (count: Sql): Sql => sql`OFFSET ${inlineIntegerLiteral(count)}`,\n };\n\n // JSON_MERGE_PRESERVE concatenates arrays element-wise; JSON_ARRAY_APPEND\n // would append the whole param as a single (stringified) element.\n set = {\n ...createNumericSetOperations(),\n\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalIncrement(column, by, target.decimal)\n : sql`${column} = ${column} + ${by}`,\n\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalDecrement(column, by, target.decimal)\n : sql`${column} = ${column} - ${by}`,\n\n // A decimal target rounds the product back to the field's scale; every\n // other numeric column keeps MySQL's native multiplication.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? mysqlDecimalMultiply(column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n // MySQL `/` yields DECIMAL and rounds when assigned to an integer column.\n // Truncate explicitly so integer division matches PostgreSQL and SQLite.\n // A decimal target takes neither: `/` would round at\n // `div_precision_increment` digits, so the exact half-even quotient rule\n // decides the last digit instead.\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql => {\n if (target?.decimal) {\n return mysqlDecimalDivide(column, by, target.decimal);\n }\n return target?.integer\n ? sql`${column} = TRUNCATE(${column} / ${by}, 0)`\n : sql`${column} = ${column} / ${by}`;\n },\n\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(COALESCE(${column}, JSON_ARRAY()), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = JSON_MERGE_PRESERVE(${values}, COALESCE(${column}, JSON_ARRAY()))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n // MySQL has no bare OFFSET; per the manual, use an all-ones LIMIT sentinel\n noLimitValue = sql.raw`18446744073709551615`;\n\n readonly #assemble = {\n select: (rawParts: QueryParts): Sql => {\n // Inline integer LIMIT/OFFSET (see clauses above for why)\n const parts: QueryParts = {\n ...rawParts,\n limit: rawParts.limit && inlineIntegerLiteral(rawParts.limit),\n offset: rawParts.offset && inlineIntegerLiteral(rawParts.offset),\n };\n\n // MySQL doesn't support DISTINCT ON natively\n // Simulate using ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)\n if (parts.distinct) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape,\n this.noLimitValue\n );\n }\n\n return assembleSelectQuery(sql`SELECT ${parts.columns}`, parts, {\n forUpdate: \"append\",\n noLimitValue: this.noLimitValue,\n });\n },\n };\n\n // MySQL 8.0+ common table expressions\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"recoverableUniqueError\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql => sql`INSERT INTO ${table} () VALUES ()`,\n\n ...createMutationCommands(),\n\n // MySQL doesn't support RETURNING - returns empty\n // Use LAST_INSERT_ID() or SELECT after mutation\n returning: (_columns: Sql): Sql => sql.empty,\n\n // This low-level MySQL primitive ignores `_target`: ON DUPLICATE KEY UPDATE\n // fires on any unique collision. Public non-returning upserts therefore do\n // not execute this primitive; the query engine uses a locked, target-aware\n // branch so an unrelated unique collision still throws on every database.\n onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql): Sql => {\n return sql`ON DUPLICATE KEY UPDATE ${action}`;\n },\n\n // MySQL doesn't need UPDATE SET prefix - onConflict already includes UPDATE\n onConflictUpdate: (sets: Sql, _setWhere?: Sql): Sql => sets,\n\n // A self-assignment reacts only to duplicate-key conflicts. Unlike\n // INSERT IGNORE, unrelated constraint and conversion failures still abort.\n //\n // It stays the JUNCTION insert's clause on MySQL as well, because\n // `ON DUPLICATE KEY UPDATE` cannot name a target (`onConflict` above says\n // so) — correct for every junction whose PK is its sole unique constraint,\n // which is every ordinary pair table. A polymorphic member table with a\n // SINGULAR inverse also carries a target-side UNIQUE that this clause would\n // swallow; the seam for that case is documented at `junctionDuplicateSkip`\n // in `query-engine/builders/many-to-many-utils.ts`.\n skipDuplicates: (duplicateNoopColumn: string) => {\n const column = sql.raw(quoteIdent(duplicateNoopColumn));\n return {\n prefix: sql.empty,\n suffix: sql`ON DUPLICATE KEY UPDATE ${column} = ${column}`,\n };\n },\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n notExists: (query: Sql): Sql =>\n sql`SELECT CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \\`__viborm_assert__\\``,\n // The refusal is an invalid path (3143), never the invalid text (3141)\n // a premise fails with.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \\`__viborm_judged__\\`${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n // MySQL doesn't support FULL OUTER JOIN (would need a UNION of LEFT and\n // RIGHT joins). Never silently downgrade to LEFT JOIN: that drops rows.\n // The query engine never calls this today.\n full: (_table: Sql, _condition: Sql): Sql => {\n throw new Error(\n \"MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.\"\n );\n },\n\n // MySQL 8.0.14+ supports LATERAL\n ...createLateralJoins(quoteIdent),\n };\n\n setOperations = createSetOperations(quoteIdent);\n\n capabilities = {\n supportsReturning: false,\n supportsCteWithMutations: false, // MySQL CTEs are read-only\n supportsFullOuterJoin: false,\n supportsLateralJoins: true, // MySQL 8.0.14+\n supportsVector: false,\n supportsUpsertWhere: false, // ON DUPLICATE KEY UPDATE doesn't support WHERE clauses\n // ON DUPLICATE KEY UPDATE carries no conflict target and fires on ANY unique\n // collision — see the `onConflict` note above. A targeted upsert cannot be\n // spelled here, so the ON CONFLICT fold never opens on MySQL.\n supportsTargetedUpsert: false,\n // ERROR 1093: UPDATE/DELETE can't select from the mutated table in a\n // subquery. The engine wraps relation-filter subqueries in a derived\n // table when this is false (requires MySQL 8.0.14+ for outer references\n // in derived tables).\n supportsMutationTargetInSubquery: false,\n // MySQL's single-table UPDATE/DELETE take a native LIMIT, which is also the\n // only portable spelling here: the PK-subquery form would re-read the\n // mutated table and trip the same ERROR 1093 as above.\n supportsMutationRowLimit: true,\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`LAST_INSERT_ID()`;\n\n readonly #batchRefs = createMySqlBatchRefs({\n table: sql.raw`\\`__viborm_batch_refs\\``,\n batchIdColumn: sql.raw`\\`batch_id\\``,\n keyColumn: sql.raw`\\`ref_key\\``,\n valueColumn: sql.raw`\\`ref_value\\``,\n duplicateValue: sql.raw`VALUES(\\`ref_value\\`)`,\n createTable: sql.raw`CREATE TEMPORARY TABLE IF NOT EXISTS \\`__viborm_batch_refs\\` (\\`batch_id\\` VARCHAR(191) NOT NULL, \\`ref_key\\` VARCHAR(191) NOT NULL, \\`ref_value\\` TEXT, PRIMARY KEY (\\`batch_id\\`, \\`ref_key\\`))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS CHAR)`,\n lastInsertId: () => this.lastInsertId(),\n });\n\n vector = unsupportedVector;\n\n readonly geoPoint: GeoPointSql = (() => {\n const longitude = (point: Sql): Sql => sql`ST_Longitude(${point})`;\n const latitude = (point: Sql): Sql => sql`ST_Latitude(${point})`;\n return {\n // EPSG:4326 is latitude-longitude in MySQL's SRS catalog. The explicit\n // WKT option makes the two bound coordinates longitude-latitude instead.\n value: (pointLongitude, pointLatitude) =>\n sql`ST_GeomFromText(CONCAT('POINT(', ${pointLongitude}, ' ', ${pointLatitude}, ')'), 4326, 'axis-order=long-lat')`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`MBRIntersects(${point}, ST_GeomFromGeoJSON(${polygon}, 1, 4326))`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}, 1, 4326)`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) =>\n sql`ST_Distance_Sphere(${left}, ${right}, ${GEO_POINT_EARTH_RADIUS_METERS})`,\n };\n })();\n\n // RESULT PARSING\n // MySQL: booleans and naive UTC datetimes - both ROW VALUES.\n // This adapter says nothing about a RESULT: the engine's decoder asks for\n // the alias `_count` and reads it back, and mysql2 preserves that alias\n // (Arnaud's D-40, measured live).\n // Relation carriers decode at the query-engine boundary that knows their\n // value is JSON, so the adapter never sniffs ordinary strings.\n result: AdapterResultParser = {\n // A MySQL SCALAR decimal is `DECIMAL(p,s)` and answers with exact text, so\n // `decimalRepresentation` stays at its default. A decimal LIST is JSON,\n // which has no exact decimal at all, so its members are stored and returned\n // as unscaled coefficient strings (plan 6.1). This adapter is the reason\n // the two are separate declarations.\n decimalListRepresentation: \"coefficient\",\n\n // Derived from the ONE storage owner, so the column the migration creates\n // and the value this reads back cannot be two decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"mysql\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing on all 20 asks D-40 measured over\n // seven operations and both routes on live MySQL - the `count`/`exist` arm\n // was entered on 10 of them and answered `undefined` every time\n // (`g4/rulings/o2/receipts/leg-probe-mysql.log`). A RESULT is the\n // decoder's, and D-28's chain ends there.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => next(),\n\n parseField: (\n value: unknown,\n scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // MySQL stores booleans as TINYINT(1) - 0/1\n if (scalarType === \"boolean\") {\n const parsed = parseIntegerBoolean(\n value === \"0\" ? 0 : value === \"1\" ? 1 : value\n );\n if (parsed !== undefined) {\n return next(parsed);\n }\n }\n // Datetime strings are naive UTC wall-clock; without this, the default\n // parser's new Date(str) would shift them by the process timezone\n if (scalarType === \"datetime\" && typeof value === \"string\") {\n const iso = naiveDateTimeToIso(value);\n if (iso !== undefined) {\n return next(iso);\n }\n }\n return next();\n },\n };\n}\n"],"mappings":"64BA4EA,MAAM,EAAa,GAAuB,IAAI,CACxC,EAAoB,MAAsC,UAAU,CAapE,EAAyC,CAQ7C,UAAW,EAAQ,IACjB,CAAG,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,oBAC1C,WAAY,EAAQ,IAAgB,CAAG,OAAO,EAAE,IAAI,EAAE,GACvD,CASK,wBAA2B,GAC/BA,EAAI,IAAI,IAAI,OAAO,EAAO,CAAC,CAEvB,GAAkB,CAAG,2HAErB,EAAyB,CAAG,yBAG5B,aAAe,EAAW,EAAmB,IACjD,CAAG,QAAQ,EAAK,MAAMA,EAAI,IAAI,WAAW,EAAU,GAAG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ACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,iBAAiB,EAAM,uBAAuB,EAAQ,aAC5D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,sBAAsB,EACzC,EACD,CAAC,YACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IACf,CAAG,sBAAsB,EAAK,IAAI,EAAM,IAAI,EAA8B,GAC7E,IACC,CASJ,OAA8B,CAM5B,0BAA2B,cAI3B,kBAAmB,EAAQ,IACzB,EAAY,EAAQ,EAAY,QAAQ,EAAE,gBAAkB,OAO9D,YAAa,EAEb,eACE,EACA,IACY,GAAM,CAEpB,YACE,EACA,EACA,IACY,CAEZ,GAAI,IAAe,UAAW,CAC5B,IAAM,EAAS,GACb,IAAU,IAAM,EAAI,IAAU,IAAM,EAAI,EACzC,CACD,GAAI,IAAW,IAAA,GACb,OAAO,EAAK,EAAO,CAKvB,GAAI,IAAe,YAAc,OAAO,GAAU,SAAU,CAC1D,IAAM,EAAM,mBAAmB,EAAM,CACrC,GAAI,IAAQ,IAAA,GACV,OAAO,EAAK,EAAI,CAGpB,OAAO,GAAM,EAEhB"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-D3m1S7Uc.mjs";import{m as n,p as r}from"./validation-BamBwne9.mjs";import{E as i,g as a}from"./geo-point-codec-DyEHMdJg.mjs";import{o,t as s}from"./sql-Bhxq9arK.mjs";import{o as c}from"./native-types-asNCr26n.mjs";import{a as ee}from"./physical-CAOaNM4R.mjs";import{t as l}from"./geo-area-codec-CbkmFArQ.mjs";import{r as u}from"./adapter-internals-AGgQRu5t.mjs";import{a as d}from"./datetime-physical-codec-BEqQbIP_.mjs";import{t as f}from"./array-literal-BKdLfNzM.mjs";import{A as te,C as p,D as m,E as h,N as g,S as _,T as v,_ as y,a as b,b as x,c as S,d as C,f as w,h as T,i as E,j as D,l as O,m as k,n as A,o as j,p as M,r as ne,s as N,v as P,w as F,x as I,y as L}from"./standard-sql-CoGqv-iX.mjs";import{r as R}from"./batch-refs-B4zn-FAu.mjs";import{t as z}from"./adapter-namespace-BpMbLKpL.mjs";import{a as B,c as V,g as H,i as U,l as W,m as G,n as K,p as q,r as J,s as Y,t as X}from"./select-assembly-CkGe2ABs.mjs";var Z=class JsonParameter{json;constructor(e){this.json=e,Object.freeze(this)}static from(e){let t=JSON.stringify(e);return t===void 0?void 0:new JsonParameter(t)}toString(){return this.json}toJSON(){return JSON.parse(this.json)}};const Q=g(`"`);function postgresLikeLiteral(e){return o`REPLACE(REPLACE(REPLACE(${e}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`}function postgresAsciiCaseFold(e){return o`TRANSLATE(${e}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`}function postgresJsonObject(e){if(e.length===0)return o.raw`'{}'::json`;let t=[],n=o.raw(e.length>50?`jsonb_build_object`:`json_build_object`);for(let r=0;r<e.length;r+=50){let i=e.slice(r,r+50).flatMap(([e,t])=>[o`${e}::text`,t]);t.push(o`${n}(${o.join(i,`, `)})`)}return t.length===1?t[0]:o`(${o.join(t,` || `)})::json`}const re=G(e=>`${e}_pkey`);var CastParameter=class extends s{type;constructor(e,t){super([`CAST(`,` AS ${t})`],[e]),this.type=t}},ArrayParameter=class extends s{};const ie=h().list;function arrayParameter(e){let t=e[0];if(t===void 0)return;let n=t instanceof CastParameter?t.type:void 0,r=[];for(let t of e){let e=t instanceof CastParameter?t:void 0,[i,a,o]=t.strings;if(e?.type!==n||!e&&(i!==``||a!==``||o!==void 0))return;let s=t.values[0];if(s instanceof Uint8Array)r.push(`\\x${Array.from(s,e=>e.toString(16).padStart(2,`0`)).join(``)}`);else if(typeof s==`string`||typeof s==`number`||typeof s==`bigint`||typeof s==`boolean`)r.push(String(s));else return}let i=f(r);return n===void 0?new ArrayParameter([``,``],[i]):new ArrayParameter([`CAST(`,` AS ${n}[])`],[i])}const $={quotient:(e,t)=>o`div(${e}, ${t})`,remainder:(e,t)=>o`mod(${e}, ${t})`},ae=/^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\(|$)/i;var PostgresAdapter=class{geoPoint;constructor(e=`public`,t=!1){z(this,e,`postgresql`),this.identifiers=w(Q,this.namespace),q(this,t?this.#r():void 0),u(this,{batchRefs:this.#n,constraints:re,select:this.#e.select})}raw=_();identifiers;literals={...h(),dateTime:e=>o`${d(e)}`,true:()=>o.raw`TRUE`,false:()=>o.raw`FALSE`,json:e=>o`${Z.from(e)}`,decimal:(e,t)=>new CastParameter(i(e,t,`text`),a(`pg`,t)),id:(e,t)=>t===`uuid`?new CastParameter(e,`UUID`):o`${e}`,list:e=>arrayParameter(e)??ie(e)};operators={...b(),like:(e,t)=>o`${e} LIKE ${t} ESCAPE '\\'`,notLike:(e,t)=>o`${e} NOT LIKE ${t} ESCAPE '\\'`,ilike:(e,t)=>o`${postgresAsciiCaseFold(e)} LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,notIlike:(e,t)=>o`${postgresAsciiCaseFold(e)} NOT LIKE ${postgresAsciiCaseFold(t)} ESCAPE '\\'`,containsText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,startsWithText:(e,t)=>o`${e} LIKE (${postgresLikeLiteral(t)} || '%') ESCAPE '\\'`,endsWithText:(e,t)=>o`${e} LIKE ('%' || ${postgresLikeLiteral(t)}) ESCAPE '\\'`,startsWithPrefix:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!0)} LIKE ${`${te(t)}%`} ESCAPE '\\'`,exactTextEq:(e,t,n)=>o`${this.expressions.caseSensitiveText(e,n,!1)} = ${t}`,exactTextIn:(e,t,n)=>this.operators.in(this.expressions.caseSensitiveText(e,n,!1),t),in:(e,t)=>t instanceof ArrayParameter?o`${e} = ANY(${t})`:o`${e} IN ${t}`,notIn:(e,t)=>t instanceof ArrayParameter?o`${e} <> ALL(${t})`:o`${e} NOT IN ${t}`,...P(),...I(),...T(this.literals.true,this.literals.false),...C()};expressions={...E(),caseSensitiveText:(e,t,r=!1)=>{let i=c(t,`pg`)?.type;if(!r&&i?.toLowerCase()===`xml`)throw new n(`PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.`,{meta:{dialect:`pg`,scalarType:`string`}});return r&&i&&ae.test(i)?o`CAST(${e} AS TEXT)`:e},asciiCaseFold:postgresAsciiCaseFold,concat:(...e)=>e.length===0?o.raw`''`:e.length===1?e[0]:o`(${o.join(e,` || `)})`,greatest:(...e)=>o`GREATEST(${o.join(e,`, `)})`,least:(...e)=>o`LEAST(${o.join(e,`, `)})`,integerDivide:(e,t)=>o`(${e} / ${t})`,decimalCast:(e,t)=>o`CAST(${e} AS ${o.raw(a(`pg`,t))})`,idCast:(e,t)=>t===`bytes`?o`decode(${e}, 'hex')`:o`CAST(${e} AS ${o.raw(t===`uuid`?`UUID`:`TEXT`)})`,cast:ne({text:`TEXT`,integer:`INTEGER`,bigint:`BIGINT`,boolean:`BOOLEAN`,numeric:`NUMERIC`}),blobToHex:e=>o`encode(${e}, 'hex')`};aggregates={...A(`'Infinity'::float8`),min:(e,t=!1)=>t?o`BOOL_AND(${e})`:o`MIN(${e})`,max:(e,t=!1)=>t?o`BOOL_OR(${e})`:o`MAX(${e})`,decimalAvg:(e,t)=>Y($,e,t),decimalSumOperandPrecision:S(1e3)};json={equals:(e,t)=>o`(${e})::jsonb = (${t})::jsonb`,boolean:e=>e,document:e=>e,number:e=>e,object:postgresJsonObject,array:e=>e.length===0?o.raw`'[]'::json`:o`json_build_array(${o.join(e,`, `)})`,emptyArray:()=>o.raw`'[]'::json`,agg:e=>o`COALESCE(json_agg(${e}), '[]'::json)`,objectFromColumns:postgresJsonObject,extract:(e,t)=>o`(${e})::jsonb#>${t}::text[]`,extractText:(e,t)=>o`(${e})::jsonb#>>${t}::text[]`,numberAtPath:(e,t)=>o`(CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'number' THEN ((${e})::jsonb#>>${t}::text[])::double precision END)`,stringAtPath:(e,t)=>o`((CASE WHEN jsonb_typeof((${e})::jsonb#>${t}::text[]) = 'string' THEN (${e})::jsonb#>>${t}::text[] END) COLLATE "C")`,contains:(e,t)=>o`(${e})::jsonb @> ${t}`,lastElement:e=>o`(${e})::jsonb -> -1`,value:e=>o`${Z.from(e)}`};arrays={literal:e=>e.length===0?o.raw`'{}'`:o`ARRAY[${o.join(e,`, `)}]`,value:(e,t)=>o`${t?e.map(e=>typeof e==`string`?d(e):e):e}`,enumValue:e=>o`${f(e)}`,has:(e,t)=>o`${t} = ANY(${e})`,hasEvery:(e,t)=>o`${e} @> ${t}`,hasSome:(e,t)=>o`${e} && ${t}`,isEmpty:e=>o`(cardinality(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>o`CAST(${e} AS TEXT[])`,length:e=>o`cardinality(${e})`,get:(e,t)=>o`${e}[${t}]`,push:(e,t)=>o`array_append(${e}, ${t})`,set:(e,t,n)=>o`${e}[:${t}-1] || ARRAY[${n}] || ${e}[${t}+1:]`};orderBy={...O(),nullsFirst:(e,t)=>t===`desc`?o`${e} DESC NULLS FIRST`:o`${e} ASC NULLS FIRST`,nullsLast:(e,t)=>t===`desc`?o`${e} DESC NULLS LAST`:o`${e} ASC NULLS LAST`};clauses=v();set={...L(),multiply:(e,t,n)=>n?.decimal?W($,e,t,n.decimal):o`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?V($,e,t,n.decimal):o`${e} = ${e} / ${t}`,push:(e,t)=>o`${e} = array_cat(COALESCE(${e}, '{}'), ${t})`,unshift:(e,t)=>o`${e} = array_cat(${t}, COALESCE(${e}, '{}'))`};filters=p();subqueries=m(Q);#e={select:e=>e.distinct&&e.orderBy?X(e,e.distinct,this.identifiers.escape):K(e.distinct?o`SELECT DISTINCT ON (${e.distinct}) ${e.columns}`:o`SELECT ${e.columns}`,e,{forUpdate:`append`})};cte=N(Q);mutations={skipDuplicatesStrategy:`sql`,insert:M(Q),insertDefault:e=>o`INSERT INTO ${e} DEFAULT VALUES`,...y(),returning:e=>o`RETURNING ${e}`,...x()};assertions={exists:e=>o`SELECT 1 / CASE WHEN EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,notExists:e=>o`SELECT 1 / CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE 0 END AS "__viborm_assert__"`,holds:(e,t)=>o`SELECT CASE WHEN ${e} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS "__viborm_judged__"${t?o` FROM ${t}`:o``}`};joins={...j(),full:(e,t)=>o`FULL OUTER JOIN ${e} ON ${t}`,...k(Q)};setOperations=F(Q,(e,t,n)=>{let r=o.raw(Q(e.alias)),column=e=>o.raw(Q(e)),[i,...a]=t,s=i.map((t,n)=>o`COALESCE(${t}, (${r}."row").${column(e.columns[n])})`);return o`(SELECT NULL::${e.table} AS "row") AS ${r} CROSS JOIN LATERAL (VALUES ${o.join([s,...a].map(D),`, `)}) AS ${o.raw(Q(n))}(${o.join(e.columns.map(column),`, `)})`});capabilities={supportsReturning:!0,supportsCteWithMutations:!0,supportsFullOuterJoin:!0,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!0,supportsTargetedUpsert:!0,supportsMutationTargetInSubquery:!0,supportsMutationRowLimit:!1,supportsRowLocks:!0};lastInsertId=()=>o.raw`lastval()`;#t=R({table:o.raw`"__viborm_batch_refs"`,batchIdColumn:o.raw`"batch_id"`,keyColumn:o.raw`"ref_key"`,valueColumn:o.raw`"ref_value"`,createTable:o.raw`CREATE TEMP TABLE IF NOT EXISTS "__viborm_batch_refs" ("batch_id" TEXT NOT NULL, "ref_key" TEXT NOT NULL, "ref_value" TEXT, PRIMARY KEY ("batch_id", "ref_key"))`,castValue:e=>o`CAST((${e}) AS TEXT)`,storeReturning:(e,t,n,r)=>o`WITH "__viborm_inserted" AS (${n} RETURNING ${r}) INSERT INTO "__viborm_batch_refs" ("batch_id", "ref_key", "ref_value") SELECT ${e}, ${t}, CAST(${r} AS TEXT) FROM "__viborm_inserted"`});#n=(()=>{let e=this.#t,t=this.capabilities;return{setup:e.setup,cleanup:e.cleanup,store:e.store,read:e.read,get storeReturning(){return t.supportsCteWithMutations?e.storeReturning:void 0},get storeInsertedKey(){return t.supportsCteWithMutations?e.storeInsertedKey:void 0}}})();vector={literal:e=>{if(e.some(e=>!Number.isFinite(Math.fround(e))))throw new r(`PostgreSQL vector components must fit a finite float32 value.`,{code:t.INVALID_INPUT});return o`${`[${e.join(`,`)}]`}::vector`},l2:(e,t)=>o`${e} <-> ${t}`,cosine:(e,t)=>o`NULLIF(${e} <=> ${t}, 'NaN'::double precision)`};#r(){let longitude=e=>o`ST_X(${e}::geometry)`,latitude=e=>o`ST_Y(${e}::geometry)`;return{value:(e,t)=>o`ST_SetSRID(ST_MakePoint(${e}, ${t}), 4326)::geography`,longitude,latitude,...J(longitude,latitude,this.operators,(e,t)=>{let n=U(t);if(n.length!==0)return this.operators.or(...n.map(t=>o`${e} && ST_SetSRID(ST_GeomFromGeoJSON(${t}), 4326)::geography`))}),withinPolygon:(e,t)=>o`ST_Intersects(${o`ST_SetSRID(ST_GeomFromGeoJSON(${B(t)}), 4326)::geography`}, ${e})`,distance:(e,t)=>{let n=o`RADIANS(ST_X(${e}::geometry))`,r=o`RADIANS(ST_Y(${e}::geometry))`,i=o`RADIANS(ST_X(${t}::geometry))`,a=o`RADIANS(ST_Y(${t}::geometry))`;return o`CASE WHEN ${e} IS NULL OR ${t} IS NULL THEN NULL ELSE CAST(${l} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${o`POWER(SIN((${a} - ${r}) / 2), 2) + COS(${r}) * COS(${a}) * POWER(SIN((${i} - ${n}) / 2), 2)`})))) END`}}}result={nativeScalarPassthrough:!0,enumListRepresentation:`arrayText`,idRepresentation:(e,t)=>ee(e,t,`pg`)?.representation??`text`,parseResult:H,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>n()}};export{PostgresAdapter as t};
2
- //# sourceMappingURL=postgres-adapter-CxEit2-v.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-adapter-CxEit2-v.mjs","names":["sql","#createGeoPointSql","#batchRefs","#assemble","#cteBatchRefs"],"sources":["../src/sql/json-parameter.ts","../src/adapters/databases/postgres/postgres-adapter.ts"],"sourcesContent":["/**\n * One JSON document, bound as one statement parameter.\n *\n * PostgreSQL's JSON literals bind CANONICAL JSON TEXT and let the server cast\n * that text from the parameter's column context. Nothing at the driver can\n * tell that text apart from an ordinary string, so every transport that\n * re-serializes a `json`/`jsonb` parameter has to be told not to, and only some\n * of them offer a place to say it: postgres.js takes a `json` type override\n * (`src/drivers/postgres/index.ts`), PGlite's own JSON serializer already\n * passes strings through, and node-postgres/Neon never touch a string. Bun SQL\n * offers no such hook and JSON-ENCODES a string bound to a `json`/`jsonb`\n * parameter, storing the physical document `\"[1,2,3]\"` — a JSON string — where\n * `[1,2,3]` was meant (upstream Drizzle #5287).\n *\n * This carrier is the missing distinction, and it needs no per-transport hook:\n * a PostgreSQL transport can only reach a bound value through string coercion\n * or through JSON serialization, and this renders as its canonical text under\n * BOTH. The text captured at construction is the ONE stored fact: `toJSON`\n * answers it parsed back, and `JSON.stringify` of its own output re-serializes\n * to those exact bytes, so both protocols agree even if the caller mutates the\n * original value after binding.\n * Bun, which serializes an object parameter for a `json`/`jsonb` column with\n * `JSON.stringify`, therefore stores the exact document for every JSON type,\n * including the number, boolean and null primitives that no bare JavaScript\n * value can express to it (a JS number is bound as `integer`, `null` as SQL\n * NULL).\n *\n * `json` is an own property rather than a private field because it is what a\n * parameter snapshot shows: diagnostics read own properties, so an opted-in\n * `includeParams` disclosure keeps the document instead of reporting `{}`.\n */\nexport class JsonParameter {\n /** The canonical JSON text — `JSON.stringify(value)`. */\n readonly json: string;\n\n private constructor(json: string) {\n this.json = json;\n Object.freeze(this);\n }\n\n /**\n * The carrier for `value`, or `undefined` when `JSON.stringify` has no text\n * for it (`undefined`, a function, a symbol). Those bound `undefined`\n * directly before this carrier existed, which providers send as SQL NULL;\n * carrying them would bind the text `\"undefined\"` instead.\n */\n static from(value: unknown): JsonParameter | undefined {\n // The lib signature says `string`, which is only true for the values it can\n // represent.\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? undefined : new JsonParameter(json);\n }\n\n toString(): string {\n return this.json;\n }\n\n toJSON(): unknown {\n return JSON.parse(this.json);\n }\n}\n","import {\n QueryError,\n UnsupportedOperationError,\n VibORMErrorCode,\n} from \"@errors\";\nimport {\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"@schema/scalars/native-types\";\nimport { idStorageOf } from \"@schema/scalars/string/id-domain\";\nimport { Sql, sql } from \"@sql\";\nimport { encodePostgresTemporal } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n encodePhysicalDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { GEO_POINT_EARTH_RADIUS_METERS } from \"@validation/primitives/geo-area-codec\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport { createIdentifierQuoter } from \"../../../sql/identifiers\";\nimport { JsonParameter } from \"../../../sql/json-parameter\";\nimport type {\n ArithmeticTarget,\n BatchReferenceSqlAdapter,\n} from \"../../adapter-core-types\";\nimport { installAdapterInternals } from \"../../adapter-internals\";\nimport { installAdapterNamespace } from \"../../adapter-namespace\";\nimport type { QueryParts } from \"../../adapter-query-parts\";\nimport { passThroughParseResult } from \"../../adapter-result-parser\";\nimport { createNamedConstraintIdentities } from \"../../constraint-identity\";\nimport {\n type DatabaseAdapter,\n type GeoPointSql,\n installGeoPointSql,\n} from \"../../database-adapter\";\nimport { createOnConflictBatchRefs } from \"../../shared/batch-refs\";\nimport {\n type ExactIntegerArithmetic,\n logicalDecimalAverage,\n logicalDecimalDivide,\n logicalDecimalMultiply,\n} from \"../../shared/decimal-arithmetic\";\nimport {\n createGeoPointCoordinatePredicates,\n geoBoundsIndexPolygons,\n geoPolygonJson,\n} from \"../../shared/geo-point\";\nimport {\n assembleDistinctOnEmulation,\n assembleSelectQuery,\n} from \"../../shared/select-assembly\";\nimport {\n createAggregateFunctions,\n createCastExpression,\n createCommonExpressions,\n createComparisonOperators,\n createCoreJoins,\n createCteBuilders,\n createDecimalSumOperandPrecision,\n createDirectionOrderBy,\n createExistenceOperators,\n createIdentifiers,\n createInsertStatement,\n createLateralJoins,\n createLogicalOperators,\n createMutationCommands,\n createNullOperators,\n createNumericSetOperations,\n createOnConflictBuilders,\n createRangeOperators,\n createRawSql,\n createRelationFilters,\n createSetOperations,\n createStandardClauses,\n createStandardLiterals,\n createSubqueries,\n escapeLikeLiteral,\n rowValues,\n} from \"../../shared/standard-sql\";\nimport { arrayLiteralText } from \"./array-literal\";\n\nconst quoteIdent = createIdentifierQuoter('\"');\nfunction postgresLikeLiteral(value: Sql): Sql {\n return sql`REPLACE(REPLACE(REPLACE(${value}, CHR(92), CHR(92) || CHR(92)), '%', CHR(92) || '%'), '_', CHR(92) || '_')`;\n}\nfunction postgresAsciiCaseFold(expr: Sql): Sql {\n return sql`TRANSLATE(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;\n}\nfunction postgresJsonObject(pairs: [string, Sql][]): Sql {\n if (pairs.length === 0) return sql.raw`'{}'::json`;\n const chunks: Sql[] = [];\n const buildObject = sql.raw(\n pairs.length > 50 ? \"jsonb_build_object\" : \"json_build_object\"\n );\n // PostgreSQL limits a function call to 100 arguments. Chunking preserves\n // the surrounding aggregate scope, unlike moving values into a subquery.\n for (let start = 0; start < pairs.length; start += 50) {\n const args = pairs\n .slice(start, start + 50)\n .flatMap(([key, value]) => [sql`${key}::text`, value]);\n chunks.push(sql`${buildObject}(${sql.join(args, \", \")})`);\n }\n return chunks.length === 1\n ? chunks[0]!\n : sql`(${sql.join(chunks, \" || \")})::json`;\n}\nconst POSTGRES_CONSTRAINTS = createNamedConstraintIdentities(\n (tableName) => `${tableName}_pkey`\n);\n\n/** An operand cast to the type its column holds: `uuid`, `NUMERIC(p,s)`. */\nclass CastParameter extends Sql {\n readonly type: string;\n constructor(value: unknown, type: string) {\n super([\"CAST(\", ` AS ${type})`], [value]);\n this.type = type;\n }\n}\n\n/** A value list bound as ONE array parameter: `= ANY(…)`, `<> ALL(…)`. */\nclass ArrayParameter extends Sql {}\nconst PARENTHESIZED_LIST = createStandardLiterals().list;\n\n/**\n * engine-09: a list whose members are each one parameter — bare, or all cast\n * to one type — as one array parameter: PostgreSQL's own array text, typed by\n * the members' cast or, bare, by the compared column, as a list column's\n * parameter is. Any other list keeps a parameter per member.\n */\nfunction arrayParameter(members: readonly Sql[]): ArrayParameter | undefined {\n const first = members[0];\n if (first === undefined) return;\n const type = first instanceof CastParameter ? first.type : undefined;\n const elements: string[] = [];\n for (const member of members) {\n const cast = member instanceof CastParameter ? member : undefined;\n const [head, tail, extra] = member.strings;\n if (\n cast?.type !== type ||\n (!cast && (head !== \"\" || tail !== \"\" || extra !== undefined))\n )\n return;\n const value = member.values[0];\n if (value instanceof Uint8Array)\n elements.push(\n `\\\\x${Array.from(value, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`\n );\n else if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n )\n elements.push(String(value));\n else return;\n }\n const text = arrayLiteralText(elements);\n return type === undefined\n ? new ArrayParameter([\"\", \"\"], [text])\n : new ArrayParameter([\"CAST(\", ` AS ${type}[])`], [text]);\n}\n\n/**\n * `div`/`mod` rather than `/` and a hand-rolled remainder: both are exact on\n * `numeric` for any operand, including a fractional divisor, and `div`\n * truncates toward zero — which is what the half-even rule's quotient means.\n * `/` on numerics picks its own result scale and would round the last digit.\n */\nconst POSTGRES_INTEGERS: ExactIntegerArithmetic = {\n quotient: (n: Sql, d: Sql): Sql => sql`div(${n}, ${d})`,\n remainder: (n: Sql, d: Sql): Sql => sql`mod(${n}, ${d})`,\n};\n\n/** The two characters PostgreSQL reads structurally inside a quoted member. */\n\n/**\n * PostgreSQL's own text spelling of one list, for a column whose element type\n * the driver cannot serialize.\n *\n * Every member is quoted, so a member that is empty, spells `NULL`, or holds a\n * brace, comma, quote or backslash is still exactly one member: those are the\n * only characters the server reads structurally, and quoting makes the reading\n * unambiguous without a per-member decision.\n */\n\nconst NON_TEXT_STRING_TYPE =\n /^(?:inet|cidr|macaddr8?|uuid|xml|tsvector|tsquery|bit|varbit)(?:\\(|$)/i;\n\nexport class PostgresAdapter implements DatabaseAdapter {\n /**\n * The bound schema. PostgreSQL always qualifies, so this adapter has no\n * unbound mode: an omitted or explicitly `undefined` argument means the\n * `public` schema, whatever a connection's `search_path` says.\n */\n declare readonly namespace: string;\n readonly geoPoint: GeoPointSql | undefined;\n\n constructor(namespace = \"public\", postgis = false) {\n installAdapterNamespace(this, namespace, \"postgresql\");\n // Reads the installed value, so it cannot be a field initializer: those run\n // before the constructor body.\n this.identifiers = createIdentifiers(quoteIdent, this.namespace);\n installGeoPointSql(this, postgis ? this.#createGeoPointSql() : undefined);\n installAdapterInternals(this, {\n batchRefs: this.#batchRefs,\n constraints: POSTGRES_CONSTRAINTS,\n select: this.#assemble.select,\n });\n }\n\n raw = createRawSql();\n\n identifiers: DatabaseAdapter[\"identifiers\"];\n\n literals = {\n ...createStandardLiterals(),\n\n dateTime: (iso: string): Sql => sql`${encodePostgresTemporal(iso)}`,\n\n true: (): Sql => sql.raw`TRUE`,\n\n false: (): Sql => sql.raw`FALSE`,\n\n // Serialized JSON text — PG casts the param to json/jsonb from the column\n // context. Stringifying (not raw binding) keeps primitives valid: a bare\n // 'hello' is not valid JSON input, '\"hello\"' is. The carrier is what tells\n // a transport that this text is already a document; see json-parameter.ts.\n json: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n\n // Cast into the operand's own `NUMERIC(p,s)` domain, the same type the DDL\n // emits for the field. PostgreSQL would usually infer `numeric` from the\n // column context anyway; saying it makes the comparison independent of what\n // the surrounding expression does to the operand's inferred type, and\n // naming the precision keeps the operand and the column one domain rather\n // than two that happen to agree.\n decimal: (canonical: string, descriptor: DecimalDescriptor): Sql =>\n new CastParameter(\n encodePhysicalDecimal(canonical, descriptor, \"text\"),\n decimalColumnType(\"pg\", descriptor)\n ),\n\n // A `uuid` column takes canonical text and is TYPED: PostgreSQL has no\n // `uuid = text` operator, so an untyped operand raises 42883 rather than\n // comparing. `bytea` takes the payload's bytes as an ordinary binary\n // parameter — the same parameter every blob scalar already binds — and a\n // text-stored domain takes the public string unchanged.\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ): Sql =>\n representation === \"uuid\"\n ? new CastParameter(physical, \"UUID\")\n : sql`${physical}`,\n\n list: (values: Sql[]): Sql =>\n arrayParameter(values) ?? PARENTHESIZED_LIST(values),\n };\n\n operators = {\n ...createComparisonOperators(),\n\n // Explicit ESCAPE '\\' pairs with wildcard escaping in the where-builder\n like: (column: Sql, pattern: Sql): Sql =>\n sql`${column} LIKE ${pattern} ESCAPE '\\\\'`,\n notLike: (column: Sql, pattern: Sql): Sql =>\n sql`${column} NOT LIKE ${pattern} ESCAPE '\\\\'`,\n ilike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n notIlike: (column: Sql, pattern: Sql): Sql =>\n sql`${postgresAsciiCaseFold(column)} NOT LIKE ${postgresAsciiCaseFold(pattern)} ESCAPE '\\\\'`,\n containsText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n startsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE (${postgresLikeLiteral(value)} || '%') ESCAPE '\\\\'`,\n endsWithText: (column: Sql, value: Sql): Sql =>\n sql`${column} LIKE ('%' || ${postgresLikeLiteral(value)}) ESCAPE '\\\\'`,\n // PostgreSQL is the one dialect where the escaped LIKE spelling is both\n // exact and index-usable, so it stands alone here: `LIKE` is case- and\n // accent-sensitive natively, which is the contract `startsWithText` holds,\n // and `match_pattern_prefix` extracts `name >= 'x' AND name < 'y'` from the\n // constant-folded pattern even though it arrives as a bound parameter.\n //\n // THE INDEX RANGE HAS A COLLATION PRECONDITION, and the common case does\n // not meet it. Measured, 20k rows, plain btree index:\n // - C-collated database (PGlite, `datcollate = 'C'`): Bitmap Index Scan\n // over 111 rows, where `LEFT(col, LENGTH($1)) = $1` is a Seq Scan over\n // all 20000.\n // - `en_US.utf8` (postgres:16 — the project's own test container, and\n // what a default `initdb` produces): BOTH spellings Seq Scan. Only a\n // `(col text_pattern_ops)` index ranges, and `generateCreateIndex`\n // (src/migrations/drivers/postgres/index.ts) emits no opclass, so\n // viborm cannot create one.\n // What survives on a default-locale cluster — and the reason this spelling\n // still stands there — is the row estimate: `LIKE` tracks the data\n // (202/1010/11111/19998 against truths 111/1111/11111/20000) while\n // `LEFT(...)` is an opaque function estimated at a flat 100 for every\n // prefix width, a 111x error at `name1%` that propagates into the row\n // estimate of any join above it. It is never worse than the spelling it\n // replaced on any measured leg. Full record: Decision 7.3 in\n // docs/architecture/query-performance-plan.md.\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, true)} LIKE ${`${escapeLikeLiteral(value)}%`} ESCAPE '\\\\'`,\n\n // Preserve native equality and indexes; the shared text boundary refuses\n // native types such as XML that cannot express an exact comparison.\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n sql`${this.expressions.caseSensitiveText(column, nativeType, false)} = ${value}`,\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ): Sql =>\n this.operators.in(\n this.expressions.caseSensitiveText(column, nativeType, false),\n values\n ),\n\n // Set membership: a bound list (`literals.list`) is an array, read by\n // ANY/ALL; a parenthesized list or a subquery is read by IN.\n in: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} = ANY(${values})`\n : sql`${column} IN ${values}`,\n notIn: (column: Sql, values: Sql): Sql =>\n values instanceof ArrayParameter\n ? sql`${column} <> ALL(${values})`\n : sql`${column} NOT IN ${values}`,\n\n ...createNullOperators(),\n\n ...createRangeOperators(),\n\n ...createLogicalOperators(this.literals.true, this.literals.false),\n\n ...createExistenceOperators(),\n };\n\n expressions = {\n ...createCommonExpressions(),\n\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation = false\n ): Sql => {\n const type = nativeTypeFor(nativeType, \"pg\")?.type;\n if (!textOperation && type?.toLowerCase() === \"xml\")\n throw new UnsupportedOperationError(\n \"PostgreSQL XML has no equality or ordering operator; use a text pattern filter or raw SQL.\",\n { meta: { dialect: \"pg\", scalarType: \"string\" } }\n );\n return textOperation && type && NON_TEXT_STRING_TYPE.test(type)\n ? sql`CAST(${expr} AS TEXT)`\n : expr;\n },\n asciiCaseFold: postgresAsciiCaseFold,\n\n concat: (...parts: Sql[]): Sql => {\n if (parts.length === 0) return sql.raw`''`;\n if (parts.length === 1) return parts[0]!;\n return sql`(${sql.join(parts, \" || \")})`;\n },\n\n greatest: (...exprs: Sql[]): Sql => sql`GREATEST(${sql.join(exprs, \", \")})`,\n least: (...exprs: Sql[]): Sql => sql`LEAST(${sql.join(exprs, \", \")})`,\n\n // PostgreSQL integer division already truncates toward zero, which is why\n // `set.divide` ignores `target.integer` here as well. Casting either side\n // would narrow a `bigint` operand to `int4`.\n integerDivide: (left: Sql, right: Sql): Sql => sql`(${left} / ${right})`,\n\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor): Sql =>\n sql`CAST(${expr} AS ${sql.raw(decimalColumnType(\"pg\", descriptor))})`,\n\n idCast: (expr: Sql, representation: IdRepresentation): Sql =>\n representation === \"bytes\"\n ? sql`decode(${expr}, 'hex')`\n : sql`CAST(${expr} AS ${sql.raw(\n representation === \"uuid\" ? \"UUID\" : \"TEXT\"\n )})`,\n\n cast: createCastExpression({\n text: \"TEXT\",\n integer: \"INTEGER\",\n bigint: \"BIGINT\",\n boolean: \"BOOLEAN\",\n numeric: \"NUMERIC\",\n }),\n\n blobToHex: (expr: Sql): Sql => sql`encode(${expr}, 'hex')`,\n };\n\n aggregates = {\n ...createAggregateFunctions(\"'Infinity'::float8\"),\n\n min: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_AND(${column})` : sql`MIN(${column})`,\n max: (column: Sql, boolean = false): Sql =>\n boolean ? sql`BOOL_OR(${column})` : sql`MAX(${column})`,\n\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor): Sql =>\n logicalDecimalAverage(POSTGRES_INTEGERS, column, descriptor),\n\n // `sum(numeric)` is itself unbounded on PostgreSQL; 1000 is the widest\n // `NUMERIC(p,s)` an operand can be CAST into to meet it, which is the\n // domain a comparison against that sum is actually limited by.\n decimalSumOperandPrecision: createDecimalSumOperandPrecision(1000),\n };\n\n json = {\n equals: (left: Sql, right: Sql): Sql =>\n sql`(${left})::jsonb = (${right})::jsonb`,\n boolean: (condition: Sql): Sql => condition,\n document: (expression: Sql): Sql => expression,\n number: (expression: Sql): Sql => expression,\n\n object: postgresJsonObject,\n\n array: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'[]'::json`;\n return sql`json_build_array(${sql.join(items, \", \")})`;\n },\n\n emptyArray: (): Sql => sql.raw`'[]'::json`,\n\n agg: (expr: Sql): Sql => sql`COALESCE(json_agg(${expr}), '[]'::json)`,\n\n objectFromColumns: postgresJsonObject,\n\n // #>/#>> with a text[] param handles every path shape uniformly:\n // '{}' returns the document root, and integer segments address array\n // elements (a single-segment `-> '0'` would only match an object key)\n extract: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>${path}::text[]`,\n\n extractText: (column: Sql, path: string[]): Sql =>\n sql`(${column})::jsonb#>>${path}::text[]`,\n\n // jsonb_typeof gates the cast: a non-number (or an absent path, where\n // jsonb_typeof is NULL) short-circuits to NULL instead of raising\n // \"invalid input syntax for type double precision\"\n numberAtPath: (column: Sql, path: string[]): Sql =>\n sql`(CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'number' THEN ((${column})::jsonb#>>${path}::text[])::double precision END)`,\n\n // COLLATE \"C\" pins byte (= code point) ordering; the database's default\n // collation (en_US.UTF-8 and friends) orders 'a' before 'B', which would\n // make < / > disagree with MySQL and SQLite\n stringAtPath: (column: Sql, path: string[]): Sql =>\n sql`((CASE WHEN jsonb_typeof((${column})::jsonb#>${path}::text[]) = 'string' THEN (${column})::jsonb#>>${path}::text[] END) COLLATE \"C\")`,\n\n contains: (target: Sql, value: Sql): Sql =>\n sql`(${target})::jsonb @> ${value}`,\n\n lastElement: (target: Sql): Sql => sql`(${target})::jsonb -> -1`,\n\n // Serialized JSON text, same format literals.json writes — PG casts the\n // param to jsonb from the comparison context\n value: (v: unknown): Sql => sql`${JsonParameter.from(v)}`,\n };\n\n arrays = {\n literal: (items: Sql[]): Sql => {\n if (items.length === 0) return sql.raw`'{}'`;\n return sql`ARRAY[${sql.join(items, \", \")}]`;\n },\n\n // Native array parameter; drivers serialize JS arrays to PG array format\n value: (values: unknown[], temporal?: \"date\" | \"datetime\"): Sql =>\n sql`${temporal ? values.map((value) => (typeof value === \"string\" ? encodePostgresTemporal(value) : value)) : values}`,\n\n // One untyped parameter holding PostgreSQL's own array literal. A managed\n // enum's array OID is created by the estate, so no driver has a serializer\n // for it and the native parameter above arrives malformed; an unknown\n // parameter instead takes its type from the column or operand it meets,\n // which is how the enum type is reached without naming it here.\n enumValue: (values: unknown[]): Sql => sql`${arrayLiteralText(values)}`,\n\n has: (column: Sql, value: Sql): Sql => sql`${value} = ANY(${column})`,\n\n hasEvery: (column: Sql, values: Sql): Sql => sql`${column} @> ${values}`,\n\n hasSome: (column: Sql, values: Sql): Sql => sql`${column} && ${values}`,\n\n isEmpty: (column: Sql): Sql =>\n sql`(cardinality(${column}) = 0 OR ${column} IS NULL)`,\n\n // `numeric[]::text[]` casts every ELEMENT. `numeric[]::text` would produce\n // one string holding PostgreSQL's array literal, and `to_json(numeric[])`\n // JSON numbers — the two spellings a decimal list cannot survive.\n exactNumericProjection: (column: Sql): Sql =>\n sql`CAST(${column} AS TEXT[])`,\n\n length: (column: Sql): Sql => sql`cardinality(${column})`,\n\n get: (column: Sql, index: Sql): Sql => sql`${column}[${index}]`,\n\n push: (column: Sql, value: Sql): Sql =>\n sql`array_append(${column}, ${value})`,\n\n set: (column: Sql, index: Sql, value: Sql): Sql =>\n sql`${column}[:${index}-1] || ARRAY[${value}] || ${column}[${index}+1:]`,\n };\n\n orderBy = {\n ...createDirectionOrderBy(),\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS FIRST`\n : sql`${column} ASC NULLS FIRST`,\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\"): Sql =>\n direction === \"desc\"\n ? sql`${column} DESC NULLS LAST`\n : sql`${column} ASC NULLS LAST`,\n };\n\n clauses = createStandardClauses();\n\n set = {\n ...createNumericSetOperations(),\n\n // A decimal target rounds the product/quotient back to the field's scale\n // half-to-even; every other numeric column keeps PostgreSQL's own\n // arithmetic, whose integer division already truncates toward zero.\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalMultiply(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} * ${by}`,\n\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget): Sql =>\n target?.decimal\n ? logicalDecimalDivide(POSTGRES_INTEGERS, column, by, target.decimal)\n : sql`${column} = ${column} / ${by}`,\n\n // `values` is already the destination field's one complete list crossing:\n // a native array parameter for ordinary lists or an untyped PostgreSQL\n // array literal for managed enums. `array_cat` lets the column resolve that\n // one parameter's exact array type and keeps bind/SQL size constant.\n push: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(COALESCE(${column}, '{}'), ${values})`,\n\n unshift: (column: Sql, values: Sql): Sql =>\n sql`${column} = array_cat(${values}, COALESCE(${column}, '{}'))`,\n };\n\n filters = createRelationFilters();\n\n subqueries = createSubqueries(quoteIdent);\n\n readonly #assemble = {\n select: (parts: QueryParts): Sql => {\n // DISTINCT ON requires ORDER BY to lead with the distinct columns, which\n // would override the user's ordering — emulate via ROW_NUMBER() instead\n if (parts.distinct && parts.orderBy) {\n return assembleDistinctOnEmulation(\n parts,\n parts.distinct,\n this.identifiers.escape\n );\n }\n\n // PostgreSQL supports DISTINCT ON (columns)\n const selectClause = parts.distinct\n ? sql`SELECT DISTINCT ON (${parts.distinct}) ${parts.columns}`\n : sql`SELECT ${parts.columns}`;\n\n return assembleSelectQuery(selectClause, parts, { forUpdate: \"append\" });\n },\n };\n\n cte = createCteBuilders(quoteIdent);\n\n mutations = {\n skipDuplicatesStrategy: \"sql\" as const,\n insert: createInsertStatement(quoteIdent),\n insertDefault: (table: Sql): Sql =>\n sql`INSERT INTO ${table} DEFAULT VALUES`,\n\n ...createMutationCommands(),\n\n returning: (columns: Sql): Sql => sql`RETURNING ${columns}`,\n\n ...createOnConflictBuilders(),\n };\n\n assertions = {\n exists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n notExists: (query: Sql): Sql =>\n sql`SELECT 1 / CASE WHEN NOT EXISTS (${query}) THEN 1 ELSE 0 END AS \"__viborm_assert__\"`,\n // The refusal names its sentinel (22P02, `invalid input syntax for type\n // integer: \"__viborm_refused__\"`), which no caller's division by zero\n // does; the text is a sublink, which PostgreSQL does not fold while\n // planning, so it is evaluated only where it is reached.\n holds: (condition: Sql, from?: Sql): Sql =>\n sql`SELECT CASE WHEN ${condition} THEN 1 ELSE CAST((SELECT '__viborm_refused__') AS integer) END AS \"__viborm_judged__\"${from ? sql` FROM ${from}` : sql``}`,\n };\n\n joins = {\n ...createCoreJoins(),\n\n full: (table: Sql, condition: Sql): Sql =>\n sql`FULL OUTER JOIN ${table} ON ${condition}`,\n\n ...createLateralJoins(quoteIdent),\n };\n\n /**\n * The produced rows as a `VALUES` list: PostgreSQL parses each `UNION ALL`\n * arm one recursion deeper (`54001`, stack depth, at 8,000 rows on 16.14),\n * and a list is no deeper for its length. A `VALUES` column is typed by its\n * own rows, an unknown parameter as `text`, so the first row takes each\n * column's type from a NULL of the table's row type (`COALESCE`, the rule\n * a `UNION` arm met), beside the list, as a one-row FROM item. The NULL is\n * cast to the table's type, never read as `SELECT \"qN\" FROM table AS \"qN\"`:\n * there a column named `qN` would win over the whole-row reference (42809),\n * and the cast reads no relation at all.\n */\n setOperations = createSetOperations(quoteIdent, (typed, rows, alias) => {\n const name = sql.raw(quoteIdent(typed.alias));\n const column = (field: string) => sql.raw(quoteIdent(field));\n const [first, ...rest] = rows;\n const typedFirst = first!.map(\n (value, index) =>\n sql`COALESCE(${value}, (${name}.\"row\").${column(typed.columns[index]!)})`\n );\n return sql`(SELECT NULL::${typed.table} AS \"row\") AS ${name} CROSS JOIN LATERAL (VALUES ${sql.join(\n [typedFirst, ...rest].map(rowValues),\n \", \"\n )}) AS ${sql.raw(quoteIdent(alias))}(${sql.join(typed.columns.map(column), \", \")})`;\n });\n\n capabilities: DatabaseAdapter[\"capabilities\"] = {\n supportsReturning: true,\n supportsCteWithMutations: true,\n supportsFullOuterJoin: true,\n supportsLateralJoins: true,\n supportsVector: false,\n supportsUpsertWhere: true, // PostgreSQL supports WHERE in ON CONFLICT\n supportsTargetedUpsert: true, // ON CONFLICT (cols) arbitrates on those cols\n supportsMutationTargetInSubquery: true,\n supportsMutationRowLimit: false, // PostgreSQL has no UPDATE/DELETE ... LIMIT\n supportsRowLocks: true,\n };\n\n lastInsertId = (): Sql => sql.raw`lastval()`;\n\n readonly #cteBatchRefs = createOnConflictBatchRefs({\n table: sql.raw`\"__viborm_batch_refs\"`,\n batchIdColumn: sql.raw`\"batch_id\"`,\n keyColumn: sql.raw`\"ref_key\"`,\n valueColumn: sql.raw`\"ref_value\"`,\n // The table is not ON COMMIT DROP, so it survives the native batch that\n // created it (D-50); the scratch itself belongs to the dispatched batch —\n // each batch stores its own reference rows, reads back what it stored at\n // its own end and deletes them there (D-58), so a later batch never names\n // a reference an earlier one stored. The table lingers on the session like\n // the SQLite and MySQL scratch tables do.\n createTable: sql.raw`CREATE TEMP TABLE IF NOT EXISTS \"__viborm_batch_refs\" (\"batch_id\" TEXT NOT NULL, \"ref_key\" TEXT NOT NULL, \"ref_value\" TEXT, PRIMARY KEY (\"batch_id\", \"ref_key\"))`,\n castValue: (valueSql) => sql`CAST((${valueSql}) AS TEXT)`,\n // The exact identity of an INSERT, carried by the statement that runs it:\n // the INSERT is the data-modifying CTE, its RETURNING feeds the reference\n // row, and nothing session-global (lastval) is read.\n storeReturning: (batchId, key, insert, column) =>\n sql`WITH \"__viborm_inserted\" AS (${insert} RETURNING ${column}) INSERT INTO \"__viborm_batch_refs\" (\"batch_id\", \"ref_key\", \"ref_value\") SELECT ${batchId}, ${key}, CAST(${column} AS TEXT) FROM \"__viborm_inserted\"`,\n });\n\n // Whether this provider can mutate inside a CTE is the capability's fact,\n // read live: the CTE store and the key store it derives are offered only\n // while `capabilities.supportsCteWithMutations` holds, and a PostgreSQL\n // without it offers no exact key store at all (lastval() is not exact).\n readonly #batchRefs: BatchReferenceSqlAdapter = (() => {\n const withCte = this.#cteBatchRefs;\n const capabilities = this.capabilities;\n return {\n setup: withCte.setup,\n cleanup: withCte.cleanup,\n store: withCte.store,\n read: withCte.read,\n get storeReturning() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeReturning\n : undefined;\n },\n get storeInsertedKey() {\n return capabilities.supportsCteWithMutations\n ? withCte.storeInsertedKey\n : undefined;\n },\n };\n })();\n\n vector = {\n literal: (values: number[]): Sql => {\n if (values.some((value) => !Number.isFinite(Math.fround(value))))\n throw new QueryError(\n \"PostgreSQL vector components must fit a finite float32 value.\",\n { code: VibORMErrorCode.INVALID_INPUT }\n );\n return sql`${`[${values.join(\",\")}]`}::vector`;\n },\n\n l2: (column: Sql, vector: Sql): Sql => sql`${column} <-> ${vector}`,\n\n cosine: (column: Sql, vector: Sql): Sql =>\n sql`NULLIF(${column} <=> ${vector}, 'NaN'::double precision)`,\n };\n\n #createGeoPointSql(): GeoPointSql {\n const longitude = (point: Sql): Sql => sql`ST_X(${point}::geometry)`;\n const latitude = (point: Sql): Sql => sql`ST_Y(${point}::geometry)`;\n return {\n value: (pointLongitude, pointLatitude) =>\n sql`ST_SetSRID(ST_MakePoint(${pointLongitude}, ${pointLatitude}), 4326)::geography`,\n longitude,\n latitude,\n ...createGeoPointCoordinatePredicates(\n longitude,\n latitude,\n this.operators,\n (point, bounds) => {\n const polygons = geoBoundsIndexPolygons(bounds);\n if (polygons.length === 0) return;\n return this.operators.or(\n ...polygons.map(\n (polygon) =>\n sql`${point} && ST_SetSRID(ST_GeomFromGeoJSON(${polygon}), 4326)::geography`\n )\n );\n }\n ),\n withinPolygon: (point, polygon) => {\n const geography = sql`ST_SetSRID(ST_GeomFromGeoJSON(${geoPolygonJson(\n polygon\n )}), 4326)::geography`;\n return sql`ST_Intersects(${geography}, ${point})`;\n },\n distance: (left, right) => {\n const leftLongitude = sql`RADIANS(ST_X(${left}::geometry))`;\n const leftLatitude = sql`RADIANS(ST_Y(${left}::geometry))`;\n const rightLongitude = sql`RADIANS(ST_X(${right}::geometry))`;\n const rightLatitude = sql`RADIANS(ST_Y(${right}::geometry))`;\n const haversine = sql`POWER(SIN((${rightLatitude} - ${leftLatitude}) / 2), 2) + COS(${leftLatitude}) * COS(${rightLatitude}) * POWER(SIN((${rightLongitude} - ${leftLongitude}) / 2), 2)`;\n // PostgreSQL's LEAST/GREATEST ignore NULL operands. The explicit arm is\n // what keeps a nullable source point's distance NULL rather than zero.\n return sql`CASE WHEN ${left} IS NULL OR ${right} IS NULL THEN NULL ELSE CAST(${GEO_POINT_EARTH_RADIUS_METERS} AS double precision) * 2 * ASIN(SQRT(LEAST(1, GREATEST(0, ${haversine})))) END`;\n },\n };\n }\n\n result: DatabaseAdapter[\"result\"] = {\n // PostgreSQL returns native JS scalars and parseField below is a pure\n // passthrough, so the result parser may take the identity fast path for\n // plain string/int/number/boolean columns (byte-identical, guarded).\n nativeScalarPassthrough: true,\n\n // A managed enum's array OID is in no driver's result-type table, so an\n // enum LIST comes back as the array's own text rather than a JS array.\n enumListRepresentation: \"arrayText\",\n\n // The one physical promise an identifier column makes, derived from the\n // ONE storage owner so the column the migration creates, the parameter the\n // write binds and the value this reads back cannot be three decisions.\n idRepresentation: (domain, nativeType) =>\n idStorageOf(domain, nativeType, \"pg\")?.representation ?? \"text\",\n\n // The contract's shape, deciding nothing. This leg used to offer\n // `convertBigIntToNumber(raw)`, but `Queries.decodeResult` hands it the\n // operation's ROW ARRAY, which is never a bigint, and an integer's width\n // is a VALUE's fact that the engine's `int` codec owns - it turns a bigint\n // or an integer text into a number and refuses one outside the safe range\n // (`raptor3/shared/query.ts`). Measured on live PostgreSQL over seven\n // operations and both routes, on `pg` and on `postgres.js`: 40 asks, 40\n // `undefined` (Arnaud's D-40, `g4/rulings/o2/receipts/leg-probe-pg.log`\n // and `leg-probe-postgresjs-2.log`), with `COUNT(*)` arriving as the text\n // `\"2\"` on both transports.\n parseResult: passThroughParseResult,\n\n parseRelation: (\n _value: unknown,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL returns native JSON objects - passthrough\n return next();\n },\n\n parseField: (\n _value: unknown,\n _scalarType: string,\n next: (value?: unknown) => unknown\n ): unknown => {\n // PostgreSQL has native types - passthrough\n return next();\n },\n };\n}\n"],"mappings":"69BA+BA,IAAa,EAAb,MAAa,aAAc,CAEzB,KAEA,YAAoB,EAAc,CAChC,KAAK,KAAO,EACZ,OAAO,OAAO,KAAK,CASrB,OAAO,KAAK,EAA2C,CAGrD,IAAM,EAA2B,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UAAa,GAAoB,CAAG,QAAQ,EAAM,aAClD,SAAY,GAAoB,CAAG,QAAQ,EAAM,aACvD,MAAO,CACL,OAAQ,EAAgB,IACtB,CAAG,2BAA2B,EAAe,IAAI,EAAc,qBACjE,UACA,SACA,GAAG,EACD,UACA,SACA,KAAK,WACJ,EAAO,IAAW,CACjB,IAAM,EAAW,EAAuB,EAAO,CAC3C,KAAS,SAAW,EACxB,OAAO,KAAK,UAAU,GACpB,GAAG,EAAS,IACT,GACC,CAAG,GAAG,EAAM,oCAAoC,EAAQ,qBAC3D,CACF,EAEJ,CACD,eAAgB,EAAO,IAId,CAAG,iBAHQ,CAAG,iCAAiC,EACpD,EACD,CAAC,qBACmC,IAAI,EAAM,GAEjD,UAAW,EAAM,IAAU,CACzB,IAAM,EAAgB,CAAG,gBAAgB,EAAK,cACxC,EAAe,CAAG,gBAAgB,EAAK,cACvC,EAAiB,CAAG,gBAAgB,EAAM,cAC1C,EAAgB,CAAG,gBAAgB,EAAM,cAI/C,MAAO,EAAG,aAAa,EAAK,cAAc,EAAM,+BAA+B,EAA8B,6DAH3F,CAAG,cAAc,EAAc,KAAK,EAAa,mBAAmB,EAAa,UAAU,EAAc,iBAAiB,EAAe,KAAK,EAAc,YAGM,WAEvL,CAGH,OAAoC,CAIlC,wBAAyB,GAIzB,uBAAwB,YAKxB,kBAAmB,EAAQ,IACzB,GAAY,EAAQ,EAAY,KAAK,EAAE,gBAAkB,OAY3D,YAAa,EAEb,eACE,EACA,IAGO,GAAM,CAGf,YACE,EACA,EACA,IAGO,GAAM,CAEhB"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{b as r,c as i,r as a,t as o,u as s,v as c}from"./controls-KQ85SWfT.mjs";import{a as l,i as u,p as d,r as f}from"./chain-7qiFSE8J.mjs";import{S as p,t as m}from"./base-D3m1S7Uc.mjs";import{a as h,h as g,r as _}from"./error-mapping-C9WgitPi.mjs";import{d as v,f as y,p as b,y as x}from"./validation-BamBwne9.mjs";import{t as S}from"./transaction-4dfqals6.mjs";import{t as C}from"./sql-Bhxq9arK.mjs";import{o as w,s as T}from"./builder-s1ySUuMb.mjs";import{t as E}from"./types-C5Oxz9yp.mjs";import{i as D,t as O}from"./observation-Co72iCd1.mjs";import{a as k,o as A,r as j}from"./execution-context-rJXTRVrJ.mjs";import{n as M}from"./transaction-operation-CU1zlxiG.mjs";import{t as N}from"./result-parsing-8wEK3GY1.mjs";const P=new WeakMap,F=new WeakMap;function executePreparedQuery(e,t,n,r,i,a,o){return(e===void 0||t===void 0||t.length===0)&&o===void 0?n():!r&&o===void 0&&e!==void 0&&t!==void 0&&t.length>0?runCompiledQueryInterceptors(e,t,n,discardReadWriteOutcomeRegistration,a?.readCommitCertainty,a?.reportAdmissionFailure):executeInterceptedQuery(e,t,n,r,i,a,o)}function discardReadWriteOutcomeRegistration(){}async function executeInterceptedQuery(e,t,n,r,i,a,o){let s=o===void 0?[]:[o];o!==void 0&&i?.stage(o);let captureWriteOutcome=e=>{s.push(e),i?.stage(e)},c=0,l,u=!1,publish=async e=>{if(i){if(s.length===0||u)return;u=!0,i.confirm(s);return}c+=1,l=e,s.length!==0&&await publishWriteOutcomes(s,{certainty:e})},d=Object.freeze({committed:()=>publish(`committed`),mayHaveCommitted:()=>publish(`may-have-committed`)}),executeChild=async()=>{try{let e=await n(d);return r&&(i!==void 0||c===0)&&await publish(`committed`),e}catch(e){throw i&&!u&&i.discard(s),e}};try{return e===void 0||t===void 0||t.length===0?await executeChild():await runCompiledQueryInterceptors(e,t,executeChild,captureWriteOutcome,()=>l??a?.readCommitCertainty?.(),a?.reportAdmissionFailure)}catch(e){throw i&&!u&&i.discard(s),e}}function runCompiledQueryInterceptors(e,t,n,r,i,a){return t===void 0||t.length===0?n():runInterceptorAt(e,t,0,n,r,i,a)}function runInterceptorAt(e,t,n,r,i,a,o){let s=t[n];return s===void 0?r():runOneInterceptor(e,s,()=>runInterceptorAt(e,t,n+1,r,i,a,o),i,a,o)}async function runOneInterceptor(e,n,r,i,a,o){let s=!0,c,l=!1,u=!0,d,recordProtocolFailure=t=>{if(d)return d;let r=interceptorError(n.extension,e,t);return d=r,o?.(r),r},proceed=()=>{if(!s)throw recordProtocolFailure(`called proceed more than once`);if(l)throw recordProtocolFailure(`called proceed after its handler settled`);u=!1,s=!1;let e=startChild(r);return c=settle(e),e},onWriteOutcome=e=>{if(!t(e))throw recordProtocolFailure(`registered a non-function write-outcome listener`);if(!u||l)throw recordProtocolFailure(`registered a write-outcome listener after proceed`);i(Object.freeze({extension:n.extension,listener:e}))},f=exposeHandlerContext(e,proceed,onWriteOutcome,n.controls),p;try{p=Promise.resolve(Reflect.apply(n.handler,void 0,[f]))}catch(e){p=Promise.reject(e)}let m=await settle(p);l=!0,u=!1;let h=m.status===`fulfilled`?m:{...m,failure:d!==void 0&&m.reason===d?d:interceptorFailure(n.extension,e,m.reason,a?.())};if(c!==void 0&&h.status===`rejected`&&h.reason!==d&&o?.(h.failure),c===void 0){if(d)throw d;if(h.status===`rejected`)throw h.failure;if(requiresProceed(e))throw interceptorError(n.extension,e,`completed without proceed`);return h.value}let g=await c;if(g.status===`rejected`){let e=selectExtensionFailures(d,h,g);throw e?retainSuppressedFailures(g.reason,e):g.reason}let _=selectExtensionFailures(d,h,g);return _&&throwExtensionFailures(_),h.value}function selectExtensionFailures(e,t,n){if(e&&n.status===`rejected`&&n.reason===e)return;if(t.status!==`rejected`||e!==void 0&&t.reason===e||n.status===`rejected`&&t.reason===n.reason)return e?[e]:void 0;let r=t.failure;return e?[e,r]:[r]}function exposeHandlerContext(e,t,n,r){return Object.freeze({mode:e.mode,kind:e.kind,model:e.model,operation:e.operation,input:e.input,...e.kind===`model`&&r!==void 0?{controls:a(e.controls,r)}:{},proceed:t,onWriteOutcome:n})}function startChild(e){try{return Promise.resolve(e())}catch(e){return Promise.reject(e)}}async function settle(e){try{return{status:`fulfilled`,value:await e}}catch(e){return{status:`rejected`,reason:e}}}function requiresProceed(e){return e.mode===`array`||e.kind!==`model`||!s(e.operation)}function interceptorFailure(e,t,n,r){return p(n)?n:interceptorError(e,t,`failed`,Error(`Query interceptor rejected with a non-Error value`),r)}function interceptorError(e,t,n,r,i){let a=`Extension "${e}" query handler for ${describeOperation(t)} ${n}.`,o={method:`query`,model:t.model,operation:String(t.operation),...i===void 0?{}:{commitCertainty:i}};return r?new b(a,{cause:r,meta:o}):new b(a,{meta:o})}function describeOperation(e){return e.kind===`model`?`${e.model}.${e.operation}`:e.operation}function throwExtensionFailures(e){let t=e[0];throw e.length===1?t:AggregateError(e,`Query interceptor protocol and handler both failed.`,{cause:t})}function retainSuppressedFailures(e,t){let n=AggregateError([e,...t],`Query execution and extension post-work both failed.`,{cause:e});return P.set(n,e),n}function decomposeQueryCoordinationFailure(e){if(!(e instanceof AggregateError)||!P.has(e))return;let t=P.get(e);if(!(e.cause!==t||e.errors[0]!==t))return Object.freeze({child:t,postWork:Object.freeze(e.errors.slice(1))})}var TransactionWriteOutcomes=class{#e=[];stage(e){for(let t of this.#e)if(t.registration===e)return;this.#e.push({registration:e,state:`pending`})}confirm(e){this.#t(e,`confirmed`)}discard(e){this.#t(e,`discarded`)}discardAll(){for(let e of this.#e)e.state=`discarded`}promoteTo(e){for(let t of this.#e)t.state===`confirmed`&&e.#e.push({...t}),t.state=`discarded`}publishCommitted(){return this.publish(`committed`)}async publish(e){let t=[];for(let e of this.#e)e.state===`confirmed`&&t.push(e.registration),e.state=`discarded`;await publishWriteOutcomes(t,{certainty:e})}#t(e,t){for(let n of this.#e)n.state===`pending`&&e.includes(n.registration)&&(n.state=t)}};async function publishWriteOutcomes(e,t){let n;for(let r of e)try{await r.listener(t)}catch(e){let i=p(e)?e:void 0,a=r.failurePolicy===`boundary-owned`&&i!==void 0?i:new b(`Extension "${r.extension}" write-outcome listener failed after ${t.certainty}.`,{cause:i??Error(`Write-outcome listener rejected with a non-Error value`),meta:{method:`onWriteOutcome`,commitCertainty:t.certainty}});(n??=[]).push(a)}if(n===void 0)return;let[r]=n;if(n.length===1)throw r;let i=AggregateError(n,`Multiple extension write-outcome listeners failed.`,{cause:r});throw F.set(i,n),i}function decomposeWriteOutcomePublicationFailure(e){return e instanceof AggregateError?F.get(e)??[e]:[e]}function createOperationExecutionContext(e,t,n){let r=O(n)?.diagnostics?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return j({model:e,operation:t},createCorrelationId,n,r)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let n=k(e);if(n===void 0)return t();let r=O(A(e))?.diagnostics,annotate=t=>{throw t instanceof m?h(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n,diagnostics:r}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}function createPendingOperationInstrumentationFacts(e,t,n,r,i,a,o){return createOperationInstrumentationFacts(e,t,n,r,i,a,o)}function createRawOperationInstrumentationFacts(e,t,n){return createOperationInstrumentationFacts(e,t,void 0,n,n,void 0,!1)}function createOperationInstrumentationFacts(e,t,n,i,a,o,s){let c=O(A(t));if(c?.observesLifecycle===!0)return()=>Object.freeze({kind:`operation`,context:t,identity:d(e),model:n,requestedOperation:i,operation:a,collection:o,complete(e){let n=s?r().readCacheExecutionOutcomes(t):void 0,{failure:i}=e,a=e.status===`failure`&&c.wants(`error-log`)&&isUnloggedError(i)?i:void 0,o=e.status===`failure`&&i instanceof Error&&c.wants(`operation`)?i:void 0;if(!(n===void 0&&a===void 0&&o===void 0))return Object.freeze({kind:`operation`,endedAt:Date.now(),...n===void 0?{}:{readCacheOutcomes:n},...(a??o)===void 0?{}:{failure:a??o},...a===void 0?{skipLog:!0}:{}})}})}async function observeTransactionBatchPhase(e,t,n){let r=O(A(e))?.diagnostics;try{return await n()}catch(n){throw _(n,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:k(e),diagnostics:r,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function isUnloggedError(e){return e instanceof Error&&!g(e)}function captureExecution(e){try{return e()}catch(e){return Promise.reject(e)}}var PendingExecution=class{#e=null;#t=null;#n=!1;#r;#i;constructor(e,t){this.#r=e,this.#i=t}executeDefault(e){if(this.#t!==null&&this.#t!==`default`)throw v.alreadyExecutedWithDriver(this.#r,this.#i);return this.#e||=(this.#t=`default`,captureExecution(e)),this.#e}executeWith(e,t){if(this.#n)throw v.alreadyExecutedWithDriver(this.#r,this.#i);if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null&&this.#t!==e)throw v.differentDriverConflict(this.#r,this.#i);return this.#e||=(this.#t=e,captureExecution(t)),this.#e}reserveWith(e){if(this.#t===`default`)throw v.alreadyExecutedDefault(this.#r,this.#i);if(this.#t!==null)throw this.#t===e?v.alreadyExecutedWithDriver(this.#r,this.#i):v.differentDriverConflict(this.#r,this.#i);this.#t=e,this.#n=!0}executeReserved(e){return this.#e||=captureExecution(e),this.#e}};const I=Object.freeze({accessor:opaqueInspectionValue(`accessor`),function:opaqueInspectionValue(`function`),unsupported:opaqueInspectionValue(`unsupported`)}),L=Object.getOwnPropertyDescriptor(C.prototype,`strings`)?.get,R=Object.getOwnPropertyDescriptor(C.prototype,`values`)?.get;function opaqueInspectionValue(e){let t=Object.create(null);return t.opaque=e,Object.freeze(t)}function snapshotQueryInput(e){return snapshotOwn(e,new Map,!1)}function snapshotOwn(e,t,n){let r=n?[]:Object.create(null);t.set(e,r);let i;try{i=Reflect.ownKeys(e)}catch{return t.set(e,I.unsupported),I.unsupported}for(let a of i){let i;try{i=Object.getOwnPropertyDescriptor(e,a)}catch{return t.set(e,I.unsupported),I.unsupported}if(i!==void 0){if(n&&a===`length`){Object.defineProperty(r,a,i);continue}i.enumerable&&Object.defineProperty(r,a,{configurable:!1,enumerable:!0,value:`value`in i?snapshotValue(i.value,t):I.accessor,writable:!1})}}return Object.freeze(r)}function snapshotValue(e,t){if(typeof e==`function`)return I.function;if(typeof e!=`object`||!e)return e;if(t.has(e))return t.get(e);try{if(Array.isArray(e))return snapshotOwn(e,t,!0);let r=Object.getPrototypeOf(e);if(r===C.prototype&&e instanceof C)return snapshotSql(e,t);if(r===Date.prototype&&e instanceof Date){let n=Object.freeze(new Date(Date.prototype.getTime.call(e)));return t.set(e,n),n}if(e instanceof Uint8Array){let n=new Uint8Array(e);return t.set(e,n),n}if(r===ArrayBuffer.prototype&&e instanceof ArrayBuffer){let n=e.slice(0);return t.set(e,n),n}if(r===Map.prototype&&e instanceof Map){let n=new Map;return t.set(e,n),Map.prototype.forEach.call(e,(e,r)=>{n.set(snapshotValue(r,t),snapshotValue(e,t))}),n}if(r===Set.prototype&&e instanceof Set){let n=new Set;return t.set(e,n),Set.prototype.forEach.call(e,e=>{n.add(snapshotValue(e,t))}),n}if(ArrayBuffer.isView(e)){let n=structuredClone(e);return t.set(e,n),n}if((r===Object.prototype||r===null)&&n(e))return snapshotOwn(e,t,!1)}catch{}return t.set(e,I.unsupported),I.unsupported}function snapshotSql(e,t){if(!(L&&R))throw TypeError(`Sql inspection getters are unavailable`);let n=Reflect.apply(L,e,[]),r=Reflect.apply(R,e,[]),i=Array(n.length);for(let e=0;e<n.length;e+=1){let t=Object.getOwnPropertyDescriptor(n,e);if(!(t&&`value`in t&&typeof t.value==`string`))throw TypeError(`Sql inspection strings are not plain data values`);i[e]=t.value}let a=Array(r.length),o=new C(i,a);t.set(e,o);for(let e=0;e<r.length;e+=1){let n=Object.getOwnPropertyDescriptor(r,e);a[e]=n&&`value`in n?snapshotValue(n.value,t):I.accessor}o.toStatement(`?`),o.toStatement(`$n`),o.toStatement(`:n`);for(let e of Reflect.ownKeys(o)){let t=Reflect.get(o,e);typeof t==`object`&&t&&Object.freeze(t)}return Object.freeze(o),o}const z=Symbol.for(`viborm.pendingOperation`);let attachPendingCacheExecutionFriend,readPendingCacheResultFriend;function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,r;try{await e()}catch(e){n=!0,r=e}try{await t()}catch(e){throw n?x(r,e,`Write publication callbacks both failed.`):e}if(n)throw r}}const B=Object.freeze({});let createPendingOperationFriend,V;var H=class PendingOperation{[Symbol.toStringTag]=`Promise`;[z]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=!1;#p;#m;#h;#g;#_;#v=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(B,e,t,n,r,i,void 0,void 0,a===void 0?void 0:{prepare:a,status:`pending`},void 0,o),attachPendingCacheExecutionFriend=(e,t)=>e.#F(t),readPendingCacheResultFriend=e=>({get args(){return e.cacheKeyArgs()},get controls(){return e.#y(),e.#l?.controls},get codec(){return e.#T()},executionContext:e.#e.attribution}),V=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,requiresInterception:e=>{let t=String(e.#o.originalOperation),n=u(e.#t.extensionChain,`request`,e.#i,t),r=n!==void 0&&n.length>0&&(e.#t.extensionChain?.observe.length??0)>0,i=u(e.#t.extensionChain,`query`,e.#i,t);return r||i!==void 0&&i.length>0||e.#u!==void 0},prepareAdmission:(e,t=`input`)=>{e.#C(),t===`plan`&&e.#S()},stagePackageWriteOutcomes:(e,t)=>{let n=e.#b();n!==void 0&&t.stage(n)},startInterception:(e,t,n,r)=>{let i=String(e.#o.originalOperation),a=u(e.#t.extensionChain,`query`,e.#i,i),o=e.#C(),c=e.#b();return(a===void 0||a.length===0)&&c===void 0?t():executePreparedQuery(a===void 0||a.length===0?void 0:e.#w(`array`,o),a,t,!s(i),n,r,c)},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#M(t,n?.committed,n?.mayHaveCommitted)),isWrite:e=>!s(String(e.#o.originalOperation)),hasObservation:e=>(e.#t.extensionChain?.observe.length??0)>0,observe:(e,t,n)=>{let r=e.#t.extensionChain?.observe;return r===void 0||r.length===0?t():D(r,String(e.#o.originalOperation),e.#i,t,n,e.#D())},reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observe;return n===void 0||n.length===0?e.#s.executeWith(t,()=>e.#M(t)):e.#s.executeWith(t,()=>D(n,String(e.#o.originalOperation),e.#i,()=>e.#M(t),()=>e.#m===void 0?void 0:{commitCertainty:e.#m},e.#D()))},prepare:e=>e.#S()?.queries[0],prepareBatch:e=>e.#x().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let n=e.#S();if(!n)throw new y(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return n.parseResult([t])},observeBatchPhase:(e,t,n)=>observeTransactionBatchPhase(e.#e.attribution,t,n)}),M(PendingOperation.prototype,e=>#e in e,V),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,i,a,o,s,c,l,u){if(e!==B)throw new S;this.#t=t,this.#n=n,this.#r=i,this.#c=s,this.#l=c,this.#u=u,this.#p=l,this.#h=t.route;let d=r.endsWith(`OrThrow`);this.#a=d?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new PendingExecution(this.#i,this.#a),this.#o=Object.freeze({...a,throwIfNotFound:d||a?.throwIfNotFound,originalOperation:a?.originalOperation??r}),this.#e=o??createPendingOperationContext(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),Object.freeze(this)}#y(){let e=this.#l;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=f(this.#t.extensionChain,this.#i,String(this.#o.originalOperation)),n=t.length===0?void 0:o(this.#i,this.#a,this.#r,t,this.#t.bound),r=e.prepare(n?.args??this.#r,n?.controls);return e.args=r,e.controls=n?.controls,e.status=`success`,r}catch(t){throw e.error=t,e.status=`failure`,t}}#b(){return this.#f?this.#d:(this.#d=this.#u?.(this.#e.attribution,this.#l?.controls),this.#f=!0,this.#d)}#x(){let e=this.#p?.routed;if(e)return e;if(this.#g)return this.#g;if(!i.has(this.#a))throw new y(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...i].sort().join(`, `)}.`);let t=this.#y(),n=this.#t.extensionChain?.callRows,r=this.#h.operation(this.#n,String(this.#o.originalOperation),t,n&&l(n,this.#i,this.#l?.controls));return this.#g=r,this.#p&&(this.#p.routed=r),r}#S(){if(this.#v)return this.#_;let e=this.#x().prepareSingle(this.#e.attribution);return this.#_=e?.queries.length===1?e:void 0,this.#v=!0,this.#_}#C(){return this.#x().preparedArgs}#w(e,t){let n=this.#l?.controls;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),input:snapshotQueryInput(t),...n===void 0?{}:{controls:n}})}#T(){return this.#x().cacheResultCodec()}#E(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observe;return e===void 0||e.length===0?this.#O():D(e,String(this.#o.originalOperation),this.#i,()=>this.#O(),()=>this.#m===void 0?void 0:{commitCertainty:this.#m},this.#D())})}#D(){return createPendingOperationInstrumentationFacts(this.#t.driver,this.#e.attribution,this.#i,String(this.#o.originalOperation),String(this.#a),this.#n[`~`].names.sql??this.#i,c(this.#o))}#O(e,t,n){return withOperationErrorContext(this.#e.attribution,()=>this.#k(e,t,n))}#k(e,t,n){let r=this.#j(`committed`),i=this.#j(`may-have-committed`),a=String(this.#o.originalOperation),o=u(this.#t.extensionChain,`query`,this.#i,a);return(o===void 0||o.length===0)&&this.#u===void 0?this.#M(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#A(o,a,r,i,e,t,n)}#A(e,t,n,r,i,a,o){let c;try{c=this.#C()}catch(e){return Promise.reject(e)}let l=this.#b();return(e===void 0||e.length===0)&&l===void 0?this.#M(i,combineWriteNotifications(a,n),combineWriteNotifications(o,r)):executePreparedQuery(e===void 0||e.length===0?void 0:this.#w(this.#t.transactionWriteOutcomes?`transaction`:`direct`,c),e,e=>this.#M(i,combineWriteNotifications(a,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(o,combineWriteNotifications(e?.mayHaveCommitted,r))),!s(t),this.#t.transactionWriteOutcomes,void 0,l)}#j(e){if(!(this.#t.transactionWriteOutcomes!==void 0||(this.#t.extensionChain?.observe.length??0)===0))return async()=>{(e===`committed`||this.#m===void 0)&&(this.#m=e)}}#M(e,t,n){return this.#c?this.#c(e,t,n):this.#N(e,t,n)}#N(e,t,n){let r;try{r=this.#x()}catch(e){return Promise.reject(e)}return r.execute({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!s(String(this.#o.originalOperation)),writeMayBeVisible:n})}getArgs(){return this.#r}cacheKeyArgs(){let e=this.#P();if(!e)throw new y(`Operation '${this.#a}' on model '${this.#i}' exposes no validated payload to key a cache entry on.`);return e}#P(){if(s(this.#a))return this.#x().preparedArgs}buildStatement(){return this.#x().buildStatement()}#F(e){let t=this.#p??={routed:this.#g},deferredExecution=(t,n,r)=>e((e,i,a)=>this.#M(e??t,combineWriteNotifications(i,n),combineWriteNotifications(a,r)),t);return new PendingOperation(B,this.#t,this.#n,this.#a,this.#r,this.#o,this.#e,deferredExecution,this.#l,t,this.#u)}then(e,t){return this.#E().then(e,t)}catch(e){return this.#E().catch(e)}finally(e){return this.#E().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function attachPendingCacheExecution(e,t){return attachPendingCacheExecutionFriend(e,t)}function readPendingCacheResult(e){return readPendingCacheResultFriend(e)}function isPendingOperation(e){return typeof e==`object`&&!!e&&z in e&&e[z]===!0}const U=`0viborm_distance`,W=`0viborm_relation_counts`,G=`0viborm_empty_row`,gateResultKey=e=>`0viborm_gate:${e}`,K=`0viborm_cursor_`,q=`0viborm_orphans`;function getAggregateResultKey(e){return`0viborm_aggregate:${e.slice(1)}`}function getAggregateResultName(e){switch(e){case`0viborm_aggregate:count`:return`_count`;case`0viborm_aggregate:avg`:return`_avg`;case`0viborm_aggregate:sum`:return`_sum`;case`0viborm_aggregate:min`:return`_min`;case`0viborm_aggregate:max`:return`_max`;default:return}}function getGroupByFields(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[];if(new Set(t).size!==t.length)throw new y(`GroupBy operation does not allow duplicate fields in 'by'`);return t}const J=new Set([`findFirst`,`findMany`,`findUnique`,`create`,`createManyAndReturn`,`update`,`updateManyAndReturn`,`delete`,`deleteManyAndReturn`,`upsert`]),Y=`Distance select supports only one _distance field per select.`;function selectedArm(e,t,r){let i=n(e)?e:void 0;if(!t)return getOwnValue(i,r)??!0;let a=getOwnValue(i,`only`);if(Array.isArray(a)&&!a.includes(r))return;let o=getOwnValue(i,`variants`);return(n(o)?getOwnValue(o,r):void 0)??!0}const X=[`_count`,`_avg`,`_sum`,`_min`,`_max`];function getOwnValue(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function createShape(e,t=new Map,n=new Map,r=new Set,i=new Map,a){if(new Set(e).size!==e.length)throw new y(`The requested result shape contains colliding output columns.`);return{carrier:`rows`,rawKeys:e,...a?{distanceScalar:a}:{},relations:t,polymorphic:i,aggregates:n,relationCounts:r}}function selectedEntries(e){return n(e)?Object.entries(e).filter(([,e])=>e!==!1&&e!==void 0):[]}function getNestedSelection(e){if(!n(e))return{};let t={},r=getOwnValue(e,`select`),i=getOwnValue(e,`include`);return n(r)&&(t.select=r),n(i)&&(t.include=i),t}function buildModelShape(e,t,r){let i=[],a=new Map,o=new Map,s=e[`~`].state.scalars,c=e[`~`].state.relations,l=getOwnValue(t,`select`),u=getOwnValue(t,`include`),d=n(l)?l:void 0,f=n(u)?u:void 0,p=!1,m;if(d)for(let[e,t]of Object.entries(d)){let r=getOwnValue(s,e);if(r){if(t===!0){i.push(e);continue}if(n(t)&&Object.hasOwn(t,`_distance`)){if(p)throw new y(Y);p=!0,m=r,i.push(U)}}}else for(let t of T(e))i.push(t);addSelectedRelations(e,c,d,i,a,r),addSelectedPolymorphicRelations(e,d,i,o,r),addSelectedRelations(e,c,f,i,a,r),addSelectedPolymorphicRelations(e,f,i,o,r);let h=[getOwnValue(d,`_count`),getOwnValue(f,`_count`)],g=new Set;for(let e of h){if(!n(e))continue;let t=getOwnValue(e,`select`);if(n(t))for(let[e]of selectedEntries(t)){let t=getOwnValue(c,e);if(!t)continue;let n=t[`~`].state;E(n)&&n.cardinality!==`many`||g.add(e)}}return g.size>0&&i.push(W),i.length===0&&i.push(G),createShape(i,a,new Map,g,o,m)}function admittedRecurrence(e){if(n(e))return getOwnValue(e,`recurse`)}function addSelectedRelations(e,t,n,r,i,a){for(let[o,s]of selectedEntries(n)){let n=getOwnValue(t,o);if(!n||E(n[`~`].state))continue;let c=n[`~`].settleTarget();r.push(o);let l=buildModelShape(c,getNestedSelection(s),a),u=a.get(e)?.get(o),d=admittedRecurrence(s);i.set(o,{model:c,shape:l,cardinality:n[`~`].state.cardinality,optional:u!==void 0&&w(u),...d?{recurrence:d}:{}})}}function addSelectedPolymorphicRelations(e,t,n,r,i){let a=e[`~`].state.relations;for(let[o,s]of selectedEntries(t)){let t=getOwnValue(a,o);if(!t)continue;let c=t[`~`].state;if(!E(c))continue;let l=c.cardinality===`many`,u=new Map;for(let e of Object.keys(c.target.entries)){let n=selectedArm(s,l,e);if(n===void 0)continue;let r=t[`~`].settleTarget(e);u.set(e,{model:r,shape:buildModelShape(r,getNestedSelection(n),i)})}n.push(o);let d=i.get(e)?.get(o);r.set(o,{cardinality:c.cardinality,optional:d!==void 0&&w(d),variants:u})}}function buildAggregateShape(e,t=[]){let n=[...t],r=new Set(t),i=new Map;for(let t of X){let a=getOwnValue(e,t);if(a===void 0||a===!1)continue;let o;if(!(t===`_count`&&a===!0)){let e=selectedEntries(a);if(e.length===0)continue;o=new Set(e.map(([e])=>e))}if(r.has(t))throw new y(`GroupBy cannot return both grouped scalar '${t}' and aggregate '${t}' in one result.`);let s=getAggregateResultKey(t);n.push(s),r.add(t),i.set(s,{...o?{fields:o}:{}})}return createShape(n,new Map,i)}function buildCountShape(e){let t=selectedEntries(getOwnValue(e,`select`)).map(([e])=>e);return{...createShape(t.length===0?[N]:t),carrier:`count`}}function buildExpectedResultShape(e,t,n,r){if(t===`count`)return buildCountShape(n);if(t===`exist`)return{...createShape([N]),carrier:`existence`};if(t===`aggregate`)return buildAggregateShape(n);if(t===`groupBy`)return buildAggregateShape(n,getGroupByFields(getOwnValue(n,`by`)));if(J.has(t))return buildModelShape(e,n,r)}export{decomposeQueryCoordinationFailure as C,TransactionWriteOutcomes as S,executePreparedQuery as T,PendingExecution as _,U as a,observeTransactionBatchPhase as b,W as c,H as d,attachPendingCacheExecution as f,snapshotQueryInput as g,readPendingCacheResult as h,K as i,gateResultKey as l,isPendingOperation as m,buildExpectedResultShape as n,G as o,createPendingOperation as p,selectedArm as r,q as s,Y as t,getAggregateResultName as u,createOperationExecutionContext as v,decomposeWriteOutcomePublicationFailure as w,withOperationErrorContext as x,createRawOperationInstrumentationFacts as y};
2
- //# sourceMappingURL=result-shape-B6yWtnx_.mjs.map