viborm 1.9.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/adapters.mjs +1 -1
  3. package/dist/builder-CK7lE3ee.mjs +2 -0
  4. package/dist/builder-CK7lE3ee.mjs.map +1 -0
  5. package/dist/bun-sql.d.mts +1 -1
  6. package/dist/bun-sql.mjs +1 -1
  7. package/dist/bun-sqlite.d.mts +1 -1
  8. package/dist/bun-sqlite.mjs +1 -1
  9. package/dist/cache/cloudflare-kv.d.mts +1 -1
  10. package/dist/cache/memory.d.mts +1 -1
  11. package/dist/cache.d.mts +1 -1
  12. package/dist/cache.mjs +1 -1
  13. package/dist/{chain-DG_4uSjk.mjs → chain-AqwYJpGa.mjs} +2 -2
  14. package/dist/{chain-DG_4uSjk.mjs.map → chain-AqwYJpGa.mjs.map} +1 -1
  15. package/dist/cli.mjs +1 -1
  16. package/dist/{client-CrBKhXo-.d.mts → client-CEaKCIbT.d.mts} +1 -1
  17. package/dist/client-CuBbRKhN.mjs +2 -0
  18. package/dist/client-CuBbRKhN.mjs.map +1 -0
  19. package/dist/client.d.mts +2 -2
  20. package/dist/client.mjs +1 -1
  21. package/dist/config.d.mts +1 -1
  22. package/dist/d1.d.mts +1 -1
  23. package/dist/d1.mjs +1 -1
  24. package/dist/driver.d.mts +1 -1
  25. package/dist/{index-BlBkgxtx.d.mts → index-NcKTpeZg.d.mts} +99 -35
  26. package/dist/index.d.mts +2 -2
  27. package/dist/index.mjs +1 -1
  28. package/dist/instrumentation.d.mts +1 -1
  29. package/dist/instrumentation.mjs +1 -1
  30. package/dist/libsql.d.mts +1 -1
  31. package/dist/libsql.mjs +1 -1
  32. package/dist/migrations/mysql.d.mts +4 -4
  33. package/dist/migrations/postgres.d.mts +4 -4
  34. package/dist/migrations/sqlite.d.mts +4 -4
  35. package/dist/migrations/tenant.d.mts +2 -2
  36. package/dist/migrations.d.mts +4 -4
  37. package/dist/mysql-adapter-BZtZrWeX.mjs +2 -0
  38. package/dist/mysql-adapter-BZtZrWeX.mjs.map +1 -0
  39. package/dist/mysql2.d.mts +1 -1
  40. package/dist/mysql2.mjs +1 -1
  41. package/dist/neon-http.d.mts +1 -1
  42. package/dist/neon-http.mjs +1 -1
  43. package/dist/{object-store-C-VOh0LP.d.mts → object-store-BuOuL61Z.d.mts} +3 -3
  44. package/dist/on.d.mts +1 -1
  45. package/dist/ordering.d.mts +47 -36
  46. package/dist/ordering.mjs +1 -1
  47. package/dist/ordering.mjs.map +1 -1
  48. package/dist/permissions.d.mts +16 -9
  49. package/dist/permissions.mjs +1 -1
  50. package/dist/permissions.mjs.map +1 -1
  51. package/dist/pg.d.mts +1 -1
  52. package/dist/pg.mjs +1 -1
  53. package/dist/pglite.d.mts +1 -1
  54. package/dist/pglite.mjs +1 -1
  55. package/dist/planetscale.d.mts +1 -1
  56. package/dist/planetscale.mjs +1 -1
  57. package/dist/{planner-syQCWHHr.d.mts → planner-CJ321_hX.d.mts} +1 -1
  58. package/dist/{postgres-adapter-CdUHI_lw.mjs → postgres-adapter--PJvhRSM.mjs} +2 -2
  59. package/dist/{postgres-adapter-CdUHI_lw.mjs.map → postgres-adapter--PJvhRSM.mjs.map} +1 -1
  60. package/dist/postgres-adapter-BJcelBCx.mjs +2 -0
  61. package/dist/postgres-adapter-BJcelBCx.mjs.map +1 -0
  62. package/dist/postgres.d.mts +1 -1
  63. package/dist/postgres.mjs +1 -1
  64. package/dist/{result-shape-dG_6HE7s.mjs → result-shape-Beo2WK4y.mjs} +2 -2
  65. package/dist/{result-shape-dG_6HE7s.mjs.map → result-shape-Beo2WK4y.mjs.map} +1 -1
  66. package/dist/rows-AGRWMfWj.mjs +2 -0
  67. package/dist/rows-AGRWMfWj.mjs.map +1 -0
  68. package/dist/schema/json.d.mts +1 -1
  69. package/dist/{schema-introspection-Bu2N__75.mjs → schema-introspection-Dp5vWFBv.mjs} +2 -2
  70. package/dist/{schema-introspection-Bu2N__75.mjs.map → schema-introspection-Dp5vWFBv.mjs.map} +1 -1
  71. package/dist/schema.d.mts +2 -2
  72. package/dist/select-assembly-Dcaqm09G.mjs.map +1 -1
  73. package/dist/soft-delete.d.mts +10 -10
  74. package/dist/soft-delete.mjs.map +1 -1
  75. package/dist/sqlite-adapter-CMRvEsOv.mjs +2 -0
  76. package/dist/sqlite-adapter-CMRvEsOv.mjs.map +1 -0
  77. package/dist/sqlite3.d.mts +1 -1
  78. package/dist/sqlite3.mjs +1 -1
  79. package/dist/validation.d.mts +1 -1
  80. package/dist/validation.mjs +1 -1
  81. package/dist/version-azc2rGHS.mjs +2 -0
  82. package/dist/{version-Cam5kto_.mjs.map → version-azc2rGHS.mjs.map} +1 -1
  83. package/package.json +17 -17
  84. package/dist/builder-CEQ2TIq7.mjs +0 -2
  85. package/dist/builder-CEQ2TIq7.mjs.map +0 -1
  86. package/dist/client-BojZRIyT.mjs +0 -2
  87. package/dist/client-BojZRIyT.mjs.map +0 -1
  88. package/dist/mysql-adapter-CWisQgdc.mjs +0 -2
  89. package/dist/mysql-adapter-CWisQgdc.mjs.map +0 -1
  90. package/dist/postgres-adapter-D4v50VQk.mjs +0 -2
  91. package/dist/postgres-adapter-D4v50VQk.mjs.map +0 -1
  92. package/dist/rows-CEYfrodD.mjs +0 -2
  93. package/dist/rows-CEYfrodD.mjs.map +0 -1
  94. package/dist/sqlite-adapter-BHx--tnz.mjs +0 -2
  95. package/dist/sqlite-adapter-BHx--tnz.mjs.map +0 -1
  96. package/dist/version-Cam5kto_.mjs +0 -2
@@ -1,6 +1,6 @@
1
- import { Ci as MigrationError, wi as isMigrationError } from "../index-BlBkgxtx.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-syQCWHHr.mjs";
1
+ import { Ai as isMigrationError, ki as MigrationError } from "../index-NcKTpeZg.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CJ321_hX.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C-VOh0LP.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CrBKhXo-.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-BuOuL61Z.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CEaKCIbT.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { Ci as MigrationError, wi as isMigrationError } from "../index-BlBkgxtx.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-syQCWHHr.mjs";
1
+ import { Ai as isMigrationError, ki as MigrationError } from "../index-NcKTpeZg.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CJ321_hX.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C-VOh0LP.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CrBKhXo-.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-BuOuL61Z.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CEaKCIbT.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { Ci as MigrationError, wi as isMigrationError } from "../index-BlBkgxtx.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-syQCWHHr.mjs";
1
+ import { Ai as isMigrationError, ki as MigrationError } from "../index-NcKTpeZg.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-CJ321_hX.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-C-VOh0LP.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CrBKhXo-.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-BuOuL61Z.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-CEaKCIbT.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,6 +1,6 @@
1
- import { s as MigrationLimits, t as MigrationClient } from "../planner-syQCWHHr.mjs";
1
+ import { s as MigrationLimits, t as MigrationClient } from "../planner-CJ321_hX.mjs";
2
2
  import { i as Sha256, n as MigrationStorageWriter } from "../contract-CYl0OzhZ.mjs";
3
- import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-CrBKhXo-.mjs";
3
+ import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-CEaKCIbT.mjs";
4
4
 
5
5
  //#region src/migrations/tenant.d.ts
6
6
 
@@ -1,6 +1,6 @@
1
- import { Ci as MigrationError, wi as isMigrationError } from "./index-BlBkgxtx.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-syQCWHHr.mjs";
1
+ import { Ai as isMigrationError, ki as MigrationError } from "./index-NcKTpeZg.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-CJ321_hX.mjs";
3
3
  import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "./contract-CYl0OzhZ.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-C-VOh0LP.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-CrBKhXo-.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-BuOuL61Z.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-CEaKCIbT.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./query-CTna5P9o.mjs";import{O as n,v as r}from"./geo-point-codec-Ggv29hSH.mjs";import{o as i}from"./sql-BsBoKwaf.mjs";import{a}from"./physical-CjG29tya.mjs";import{t as o}from"./geo-area-codec-B3QtKij8.mjs";import{t as s}from"./adapter-result-parser-Bz3WtMBa.mjs";import{r as ee}from"./adapter-internals-DNY4JWFC.mjs";import{n as c}from"./result-parsing-Dkgy-xcy.mjs";import{r as l}from"./datetime-physical-codec-Cdgq6sGs.mjs";import{A as u,C as d,D as f,E as te,M as p,N as m,S as h,T as g,_,a as v,c as y,d as b,f as x,g as S,h as C,i as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as ne,w as P,x as F,y as I}from"./standard-sql-BtzSzrof.mjs";import{n as L}from"./batch-refs-ZHBzfoBC.mjs";import{t as R}from"./adapter-namespace-VikEzb7o.mjs";import{a as z,d as B,f as V,i as H,m as U,n as W,o as G,p as K,r as q,t as J,u as Y}from"./select-assembly-Dcaqm09G.mjs";const X=m("`"),Z=U(()=>`PRIMARY`),Q={quotient:(e,t)=>i`CAST((${e} - MOD(${e}, ${t})) / ${t} AS DECIMAL(65,0))`,remainder:(e,t)=>i`MOD(${e}, ${t})`},mysqlMaximumCoefficient=e=>i.raw(`9`.repeat(e)),re=i`(FIND_IN_SET('STRICT_TRANS_TABLES', @@SESSION.sql_mode) > 0 OR FIND_IN_SET('STRICT_ALL_TABLES', @@SESSION.sql_mode) > 0)`,$=i`JSON_EXTRACT('x', '$')`,decimalCast=(e,t,n)=>i`CAST(${e} AS ${i.raw(`DECIMAL(${t},${n})`)})`,mysqlCoefficient=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`TRUNCATE(${e}, 0)`;return i`(${a} * ${r} + ${decimalCast(i`(${decimalCast(i`(${e} - ${a})`,n+1,n)} * ${r})`,n,0)})`},mysqlLogical=(e,t)=>{let{scale:n}=t;if(n===0)return e;let r=Y(n),a=i`MOD(${e}, ${r})`;return i`((${e} - ${a}) / ${r} + ${decimalCast(a,n,0)} * ${B(n)})`},mysqlGuardedDecimalAssignment=(e,t,n,r)=>{let a=mysqlMaximumCoefficient(n.precision),o=mysqlLogical(t,n);return i`${e} = CASE WHEN ${re} THEN ${o} WHEN ${e} IS NULL THEN NULL WHEN ${r} THEN CASE WHEN ${t} BETWEEN -${a} AND ${a} THEN ${o} ELSE ${$} END ELSE ${$} END`},mysqlDecimalIncrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} <= ${o} - ${a} WHEN ${a} < 0 THEN ${r} >= -${o} - ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} + ${a})`,n,s)},mysqlDecimalDecrement=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(n.precision),s=i`CASE WHEN ${a} > 0 THEN ${r} >= -${o} + ${a} WHEN ${a} < 0 THEN ${r} <= ${o} + ${a} ELSE TRUE END`;return mysqlGuardedDecimalAssignment(e,i`(${r} - ${a})`,n,s)},mysqlDecimalMultiply=(e,t,n)=>{let r=mysqlCoefficient(e,n),a=mysqlCoefficient(t,n),o=mysqlMaximumCoefficient(65);return mysqlGuardedDecimalAssignment(e,G(Q,i`(${r} * ${a})`,Y(n.scale)),n,i`CASE WHEN ${a} = 0 THEN TRUE ELSE ABS(${r}) <= ${Q.quotient(o,i`ABS(${a})`)} END`)},mysqlDecimalDivide=(e,t,n)=>{let r=mysqlCoefficient(t,n);return mysqlGuardedDecimalAssignment(e,G(Q,V(i`(${mysqlCoefficient(e,n)} * ${Y(n.scale)})`,r),i`ABS(${r})`),n,i.raw`TRUE`)},mysqlDecimalAverage=(e,t)=>mysqlLogical(G(Q,i`SUM(${mysqlCoefficient(e,t)})`,i`COUNT(${e})`),t),caseFold=e=>i`LOWER(${e})`,ie=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?$/,naiveDateTimeToIso=e=>{let t=ie.exec(e);if(!t)return;let n=t[3]?t[3].padEnd(4,`0`).slice(0,4):`.000`;return`${t[1]}T${t[2]}${n}Z`},inlineIntegerLiteral=e=>{let t=e.values.length===1?e.values[0]:void 0;return typeof t==`number`&&Number.isInteger(t)?i.raw(String(t)):e},mysqlJsonObject=e=>{if(e.length===0)return i.raw`JSON_OBJECT()`;let t=e.flatMap(([e,t])=>[i`${e}`,t]);return i`JSON_OBJECT(${i.join(t,`, `)})`},mysqlJsonListValue=e=>i`CAST(${p(e)} AS JSON)`;var MySQLAdapter=class{constructor(e){R(this,e,`mysql`),this.identifiers=x(X,this.namespace,!0),K(this,this.geoPoint),ee(this,{batchRefs:this.#t,constraints:Z,select:this.#e.select})}raw=h();identifiers;literals={...te(),true:()=>i.raw`TRUE`,false:()=>i.raw`FALSE`,json:e=>i`${JSON.stringify(e)}`,dateTime:(e,t,n)=>i`${n||e.length===10?e:l(e)}`,decimal:(e,t)=>i`CAST(${n(e,t,`text`)} AS ${i.raw(r(`mysql`,t))})`,id:(e,t)=>i`${e}`};operators={...v(),containsText:(e,t)=>i`LOCATE(BINARY ${t}, BINARY ${e}) > 0`,startsWithText:(e,t)=>i`LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,endsWithText:(e,t)=>i`RIGHT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t}`,insensitiveText:(e,t,n)=>this.operators[`${e}Text`](caseFold(t),caseFold(n)),startsWithPrefix:(e,t)=>i`(${e} LIKE ${`${u(t)}%`} ESCAPE '\\\\' AND LEFT(BINARY ${e}, OCTET_LENGTH(${t})) = BINARY ${t})`,exactTextEq:(e,t)=>i`(${e} = ${t} AND BINARY ${e} = ${t})`,exactTextIn:(e,t)=>i`(${e} IN ${t} AND BINARY ${e} IN ${t})`,...S(),...ne(),...F(),...C(this.literals.true,this.literals.false),...b()};expressions={...w(),caseFold,caseSensitiveText:e=>i`BINARY ${e}`,concat:(...e)=>e.length===0?i.raw`''`:e.length===1?e[0]:i`CONCAT(${i.join(e,`, `)})`,greatest:(...e)=>i`GREATEST(${i.join(e,`, `)})`,least:(...e)=>i`LEAST(${i.join(e,`, `)})`,integerDivide:(e,t)=>i`TRUNCATE(${e} / ${t}, 0)`,decimalCast:(e,t)=>decimalCast(e,t.precision,t.scale),idCast:(e,t)=>t===`bytes`?i`UNHEX(${e})`:i`CAST(${e} AS CHAR)`,cast:A({text:`CHAR`,integer:`SIGNED`,bigint:`SIGNED`,boolean:`UNSIGNED`,numeric:`DECIMAL`}),blobToHex:e=>i`LOWER(HEX(${e}))`};aggregates={...D(),decimalAvg:(e,t)=>mysqlDecimalAverage(e,t),decimalSumOperandPrecision:y(65)};json={equals:(e,t)=>i`${e} = ${t}`,number:e=>e,boolean:e=>i`JSON_EXTRACT(CASE WHEN ${e} THEN 'true' ELSE 'false' END, '$')`,document:e=>e,object:mysqlJsonObject,array:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,emptyArray:()=>i.raw`JSON_ARRAY()`,agg:e=>i`COALESCE(JSON_ARRAYAGG(${e}), JSON_ARRAY())`,objectFromColumns:mysqlJsonObject,extract:(e,t)=>i`JSON_EXTRACT(${e}, ${M(t)})`,extractText:(e,t)=>i`JSON_UNQUOTE(JSON_EXTRACT(${e}, ${M(t)}))`,numberAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) IN ('INTEGER', 'DOUBLE', 'DECIMAL') THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS DOUBLE) END)`},stringAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) AS BINARY) END)`},foldableStringAtPath:(e,t)=>{let n=M(t);return i`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${e}, ${n})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${e}, ${n})) END)`},contains:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,lastElement:e=>i`JSON_EXTRACT(${e}, '$[last]')`,value:e=>i`CAST(${p(e)} AS JSON)`};arrays={literal:e=>e.length===0?i.raw`JSON_ARRAY()`:i`JSON_ARRAY(${i.join(e,`, `)})`,value:mysqlJsonListValue,enumValue:mysqlJsonListValue,has:(e,t)=>i`JSON_CONTAINS(${e}, JSON_ARRAY(${t}))`,hasEvery:(e,t)=>i`JSON_CONTAINS(${e}, ${t})`,hasSome:(e,t)=>i`JSON_OVERLAPS(${e}, ${t})`,isEmpty:e=>i`(JSON_LENGTH(${e}) = 0 OR ${e} IS NULL)`,exactNumericProjection:e=>i`CAST(${e} AS CHAR)`,length:e=>i`JSON_LENGTH(${e})`,get:(e,t)=>i`JSON_EXTRACT(${e}, CONCAT('$[', ${t}, ']'))`,push:(e,t)=>i`JSON_ARRAY_APPEND(${e}, '$', ${t})`,set:(e,t,n)=>i`JSON_SET(${e}, CONCAT('$[', ${t}, ']'), ${n})`};orderBy={...T(),...N()};clauses={...g(),limit:e=>i`LIMIT ${inlineIntegerLiteral(e)}`,offset:e=>i`OFFSET ${inlineIntegerLiteral(e)}`};set={...I(),increment:(e,t,n)=>n?.decimal?mysqlDecimalIncrement(e,t,n.decimal):i`${e} = ${e} + ${t}`,decrement:(e,t,n)=>n?.decimal?mysqlDecimalDecrement(e,t,n.decimal):i`${e} = ${e} - ${t}`,multiply:(e,t,n)=>n?.decimal?mysqlDecimalMultiply(e,t,n.decimal):i`${e} = ${e} * ${t}`,divide:(e,t,n)=>n?.decimal?mysqlDecimalDivide(e,t,n.decimal):n?.integer?i`${e} = TRUNCATE(${e} / ${t}, 0)`:i`${e} = ${e} / ${t}`,push:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(COALESCE(${e}, JSON_ARRAY()), ${t})`,unshift:(e,t)=>i`${e} = JSON_MERGE_PRESERVE(${t}, COALESCE(${e}, JSON_ARRAY()))`};filters=d();subqueries=f(X);noLimitValue=i.raw`18446744073709551615`;#e={select:e=>{let t={...e,limit:e.limit&&inlineIntegerLiteral(e.limit),offset:e.offset&&inlineIntegerLiteral(e.offset)};return t.distinct?J(t,t.distinct,this.identifiers.escape,this.noLimitValue):W(i`SELECT ${t.columns}`,t,{forUpdate:`append`,noLimitValue:this.noLimitValue})}};cte=j(X);mutations={skipDuplicatesStrategy:`recoverableUniqueError`,insert:k(X),insertDefault:e=>i`INSERT INTO ${e} () VALUES ()`,..._(),updateFrom:(e,t,n,r,a)=>i`UPDATE ${e} JOIN ${n} ON ${r} SET ${t}${a?i` WHERE ${a}`:i.empty}`,returning:e=>i.empty,onConflict:(e,t,n)=>i`ON DUPLICATE KEY UPDATE ${t}`,onConflictUpdate:(e,t)=>e,skipDuplicates:e=>{let t=i.raw(X(e));return{prefix:i.empty,suffix:i`ON DUPLICATE KEY UPDATE ${t} = ${t}`}}};assertions={exists:e=>i`SELECT CASE WHEN EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,notExists:e=>i`SELECT CASE WHEN NOT EXISTS (${e}) THEN 1 ELSE JSON_EXTRACT('x', '$') END AS \`__viborm_assert__\``,holds:(e,t)=>i`SELECT CASE WHEN ${e} THEN 1 ELSE JSON_EXTRACT('{}', '__viborm_refused__') END AS \`__viborm_judged__\`${t?i` FROM ${t}`:i``}`};joins={...O(),full:(e,t)=>{throw Error(`MySQL does not support FULL OUTER JOIN. Check adapter.capabilities.supportsFullOuterJoin before calling.`)},...E(X)};setOperations=P(X);capabilities={supportsReturning:!1,supportsCteWithMutations:!1,supportsFullOuterJoin:!1,supportsLateralJoins:!0,supportsVector:!1,supportsUpsertWhere:!1,supportsTargetedUpsert:!1,supportsMutationTargetInSubquery:!1,supportsMutationRowLimit:!0,supportsRowLocks:!0,locksMissingKeys:!0,boundsRecursionIterations:!0};lastInsertId=()=>i.raw`LAST_INSERT_ID()`;#t=L({table:i.raw`\`__viborm_batch_refs\``,batchIdColumn:i.raw`\`batch_id\``,keyColumn:i.raw`\`ref_key\``,valueColumn:i.raw`\`ref_value\``,duplicateValue:i.raw`VALUES(\`ref_value\`)`,createTable:i.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\`))`,castValue:e=>i`CAST((${e}) AS CHAR)`,lastInsertId:()=>this.lastInsertId()});vector=t;geoPoint=(()=>{let longitude=e=>i`ST_Longitude(${e})`,latitude=e=>i`ST_Latitude(${e})`;return{value:(e,t)=>i`ST_GeomFromText(CONCAT('POINT(', ${e}, ' ', ${t}, ')'), 4326, 'axis-order=long-lat')`,longitude,latitude,...q(longitude,latitude,this.operators,(e,t)=>{let n=H(t);if(n.length!==0)return this.operators.or(...n.map(t=>i`MBRIntersects(${e}, ST_GeomFromGeoJSON(${t}, 1, 4326))`))}),withinPolygon:(e,t)=>i`ST_Intersects(${i`ST_GeomFromGeoJSON(${z(t)}, 1, 4326)`}, ${e})`,distance:(e,t)=>i`ST_Distance_Sphere(${e}, ${t}, ${o})`}})();result={decimalListRepresentation:`coefficient`,idRepresentation:(e,t)=>a(e,t,`mysql`)?.representation??`text`,parseResult:s,parseRelation:(e,t)=>t(),parseField:(e,t,n)=>{if(t===`boolean`){let t=c(e===`0`?0:e===`1`?1:e);if(t!==void 0)return n(t)}if(t===`datetime`&&typeof e==`string`){let t=naiveDateTimeToIso(e);if(t!==void 0)return n(t)}return n()}}};export{MySQLAdapter as t};
2
+ //# sourceMappingURL=mysql-adapter-BZtZrWeX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysql-adapter-BZtZrWeX.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 type TextMatch,\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};\n// MySQL's own case folding: `LOWER` maps every letter by the string's\n// character set (Unicode for utf8mb4). It must see the raw text — on a\n// `BINARY` string it does nothing — and its result is compared as bytes, so a\n// case- AND accent-insensitive collation (`utf8mb4_0900_ai_ci`) never decides.\nconst caseFold = (expr: Sql): Sql => sql`LOWER(${expr})`;\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, true);\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 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 insensitiveText: (kind: TextMatch, column: Sql, value: Sql): Sql =>\n this.operators[`${kind}Text`](caseFold(column), caseFold(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 caseFold,\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 foldableStringAtPath: (column: Sql, path: string[]): Sql => {\n const jsonPath = buildJsonPath(path);\n return sql`(CASE WHEN JSON_TYPE(JSON_EXTRACT(${column}, ${jsonPath})) = 'STRING' THEN JSON_UNQUOTE(JSON_EXTRACT(${column}, ${jsonPath})) 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 updateFrom: (table, sets, source, on, where) =>\n sql`UPDATE ${table} JOIN ${source} ON ${on} SET ${sets}${\n where ? sql` WHERE ${where}` : sql.empty\n }`,\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 // InnoDB answers a locking miss on a unique index with a gap lock that\n // concurrent misses share and their INSERTs wait on (`ER_LOCK_DEADLOCK`).\n locksMissingKeys: true,\n boundsRecursionIterations: 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":"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"}
package/dist/mysql2.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, F as LinkedClientConfig, Ft as NoExtraDriverConfigKeys, It as VibORMClient, Nn as DriverTransactionOptions, Pn as TransactionOptionSupport, Rn as QueryExecutionContext, g as MigrationNamespaceAttestation, jt as DriverConfig, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zn as QueryResult } from "./index-BlBkgxtx.mjs";
1
+ import { Bn as TransactionOptionSupport, Bt as VibORMClient, Gn as QueryResult, I as LinkedClientConfig, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, Wn as QueryExecutionContext, g as MigrationNamespaceAttestation, j as Schema, m as PinnedSessionReservation, s as DatabaseAdapter, u as Driver, zn as DriverTransactionOptions } from "./index-NcKTpeZg.mjs";
2
2
  import { Pool, PoolConnection, PoolOptions } from "mysql2/promise";
3
3
 
4
4
  //#region src/drivers/mysql2/index.d.ts
package/dist/mysql2.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-ByvlIQqa.mjs";import{l as i}from"./execution-context-_oajgBi4.mjs";import{i as a}from"./base-wlv81COV.mjs";import{m as o,u as s}from"./error-mapping-D--MVRCY.mjs";import{d as c,t as l}from"./query-CTna5P9o.mjs";import{n as u}from"./transaction-D5LHYn-r.mjs";import{n as d}from"./client-BojZRIyT.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-XlmOJFRH.mjs";import{t as y}from"./mysql-adapter-CWisQgdc.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new l(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new c(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new c(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw a(e)?e:new l(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new l(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new l(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new l(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw s(this.driverName);let a=e,c=await h(()=>a.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),l=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw l=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await c.query(f(d)),await c.beginTransaction()}),callback:()=>t(c),commit:()=>runOrDestroy(()=>c.commit()),rollback:()=>runOrDestroy(()=>c.rollback()),phases:i(n),close:()=>{try{if(l){c.destroy();return}c.release()}catch(e){throw super.transactionCleanupFailed(new u(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw s(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r}from"./normalized-result-ByvlIQqa.mjs";import{l as i}from"./execution-context-_oajgBi4.mjs";import{i as a}from"./base-wlv81COV.mjs";import{m as o,u as s}from"./error-mapping-D--MVRCY.mjs";import{d as c,t as l}from"./query-CTna5P9o.mjs";import{n as u}from"./transaction-D5LHYn-r.mjs";import{n as d}from"./client-CuBbRKhN.mjs";import{a as f,c as p,d as m,i as h,l as g,o as _,t as v}from"./driver-XlmOJFRH.mjs";import{t as y}from"./mysql-adapter-BZtZrWeX.mjs";import{Buffer as b}from"node:buffer";const x=/^(?:ssl|tls)/i;function tlsRefusal(e){return new l(e,{meta:{driver:`mysql2`,operation:`configuration`}})}function parseMySQLUrl(e){let t=new URL(e),n=decodeURIComponent(t.pathname.slice(1)),r={};for(let[e,n]of t.searchParams){if(x.test(e)&&e!==`ssl`&&e!==`sslmode`)throw tlsRefusal(`Unsupported MySQL TLS URL option; configure options.ssl explicitly.`);try{r[e]=JSON.parse(n)}catch{r[e]=n}}let i=t.searchParams.get(`sslmode`);if(i&&i!==`disable`){if(![`require`,`verify-ca`,`verify-full`].includes(i))throw tlsRefusal(`Unsupported MySQL sslmode; configure options.ssl explicitly.`);if(r.ssl!==void 0&&(r.ssl===null||typeof r.ssl!=`object`&&typeof r.ssl!=`string`))throw tlsRefusal(`MySQL sslmode requires a TLS configuration`);r.ssl??={}}Reflect.deleteProperty(r,`sslmode`);let a=decodeURIComponent(t.username),o=decodeURIComponent(t.password);return{host:t.hostname,...t.port?{port:Number.parseInt(t.port,10)}:{},...n===``?{}:{database:n},...a===``?{}:{user:a},...o===``?{}:{password:o},...r}}const S={pool:!0,options:!0,databaseUrl:!0,namespace:!0,migrationNamespaceAttestation:!0};function convertValuesForMySQL(e){return e.map(e=>e instanceof Uint8Array&&!b.isBuffer(e)?b.from(e.buffer,e.byteOffset,e.byteLength):e)}function isMultiStatementFields(e){return Array.isArray(e)&&e.every(e=>e===void 0||Array.isArray(e))}function malformedMySQL2Result(e,t){return new c(`Driver "mysql2" returned a malformed result for operation "${e}": ${t}.`,{meta:{driver:`mysql2`,operation:e}})}const C=/^-[1-9]\d*$/;function normalizeMySQL2InsertId(e,n){if(!(typeof e==`number`&&Number.isSafeInteger(e)&&e<0||typeof e==`string`&&C.test(e)))return t(e,n,{allowNumber:!0})}function toQueryResult(e,t,i){if(isMultiStatementFields(t))throw new c(`Driver "mysql2" returned multiple statement results for operation "${i}"; VibORM requires exactly one statement result.`,{meta:{driver:`mysql2`,operation:i}});if(Array.isArray(e)){if(!Array.isArray(t)||t.some(e=>!n(e)))throw malformedMySQL2Result(i,`row arrays require one flat field metadata array`);return{rows:e,rowCount:e.length}}if(t!==void 0)throw malformedMySQL2Result(i,`mutation results require undefined field metadata`);if(!n(e))throw malformedMySQL2Result(i,`expected a mutation result object`);let a={provider:`mysql2`,operation:i},o=normalizeMySQL2InsertId(e.insertId,a);return{rows:[],rowCount:r(e.affectedRows,a,{allowDecimalString:!0}),...o===void 0?{}:{insertId:o}}}function deriveMySQL2Namespace(e){if(e.suppliedPool)return;let t=e.connectionOptions.database;return t===``?void 0:t}function resolveMySQL2Configuration(e){let t=m(e),n=e.databaseUrl,r={...n?parseMySQL2ConfiguredUrl(n):void 0};for(let[t,n]of Object.entries(e.options??{}))n!==void 0&&Reflect.set(r,t,n);let i={suppliedPool:e.pool,connectionOptions:r};return{namespace:t??deriveMySQL2Namespace(i),...i}}function parseMySQL2ConfiguredUrl(e){try{return parseMySQLUrl(e)}catch(e){throw a(e)?e:new l(`Driver "mysql2" could not parse its databaseUrl.`,{cause:e instanceof Error?e:void 0})}}var MySQL2Driver=class extends v{maxBindParametersPerStatement=65535;suppliedPool;connectionOptions;constructor(e={}){let t=g(e),n=resolveMySQL2Configuration(e);if(super(`mysql`,`mysql2`,{},t),n.connectionOptions.multipleStatements===!0)throw new l(`Driver "mysql2" does not support options.multipleStatements=true because VibORM operations require one result per statement.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.rowsAsArray===!0)throw new l(`Driver "mysql2" does not support options.rowsAsArray=true because VibORM requires row objects keyed by column name.`,{meta:{driver:`mysql2`,operation:`configuration`}});if(n.connectionOptions.nestTables===!0||typeof n.connectionOptions.nestTables==`string`)throw new l(`Driver "mysql2" does not support enabled options.nestTables because VibORM requires flat row objects keyed by result aliases.`,{meta:{driver:`mysql2`,operation:`configuration`}});this.suppliedPool=n.suppliedPool,this.connectionOptions=n.connectionOptions,_(this,`adapter`,new y(n.namespace)),this.suppliedPool&&(this.client=this.suppliedPool)}async initClient(){if(this.suppliedPool!==void 0)return this.suppliedPool;let e=await import(`mysql2/promise`),t={timezone:`Z`,supportBigNumbers:!0,dateStrings:[`DATE`],...this.connectionOptions};return this.adapter.namespace!==void 0&&(t={...t,database:this.adapter.namespace}),e.createPool(t)}async closeClient(e){e!==this.suppliedPool&&await e.end()}async execute(e,t,n,r){let i=r?.operation??`execute`,[a,o]=await e.query({sql:t,values:convertValuesForMySQL(n),typeCast:(e,t)=>[`DATE`,`DATETIME`,`TIMESTAMP`,`LONGLONG`,`NEWDECIMAL`].includes(e.type)?e.string():t()});return toQueryResult(a,o,i)}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,[a,o]=await e.query(t,n&&convertValuesForMySQL(n));return toQueryResult(a,o,i)}transactionOptionSupport(){return{isolationLevel:`pre-begin`,timeout:!0,maxWait:`acquisition`}}async transaction(e,t,n,r){if(!(`getConnection`in e))throw s(this.driverName);let a=e,c=await h(()=>a.getConnection(),e=>e.release(),r?.maxWaitMs,{driverName:this.driverName,form:`callback`}),l=!1,runOrDestroy=async e=>{try{await e()}catch(e){throw l=!0,e}},d=r?.isolationLevel;return o({begin:()=>runOrDestroy(async()=>{d&&await c.query(f(d)),await c.beginTransaction()}),callback:()=>t(c),commit:()=>runOrDestroy(()=>c.commit()),rollback:()=>runOrDestroy(()=>c.rollback()),phases:i(n),close:()=>{try{if(l){c.destroy();return}c.release()}catch(e){throw super.transactionCleanupFailed(new u(`Driver "mysql2" could not release an unsafe transaction connection.`,{meta:{driver:`mysql2`,method:`$transaction`}})),e}}})}transactionCleanupFailed(e){}async pinnedSession(){let e=await this.getClient({operation:`pinnedSession`});if(!(`getConnection`in e))throw s(this.driverName);let t=await e.getConnection();return{session:t,release:()=>(t.destroy(),Promise.resolve())}}};function createClient(e){p(e,`mysql2`,S);let{pool:t,options:n,databaseUrl:r}=e;return d(e,new MySQL2Driver({migrationNamespaceAttestation:g(e),namespace:m(e),pool:t,options:n,databaseUrl:r}))}export{MySQL2Driver,createClient};
2
2
  //# sourceMappingURL=mysql2.mjs.map
@@ -1,4 +1,4 @@
1
- import { A as Schema, F as LinkedClientConfig, Fn as BatchQuery, Ft as NoExtraDriverConfigKeys, In as CommittedBatchNotification, It as VibORMClient, Mn as BatchTransactionOptions, Pn as TransactionOptionSupport, Rn as QueryExecutionContext, jt as DriverConfig, s as DatabaseAdapter, u as Driver, zn as QueryResult } from "./index-BlBkgxtx.mjs";
1
+ import { Bn as TransactionOptionSupport, Bt as VibORMClient, Gn as QueryResult, Hn as CommittedBatchNotification, I as LinkedClientConfig, Pt as DriverConfig, Rn as BatchTransactionOptions, Rt as NoExtraDriverConfigKeys, Vn as BatchQuery, Wn as QueryExecutionContext, j as Schema, s as DatabaseAdapter, u as Driver } from "./index-NcKTpeZg.mjs";
2
2
  import { NeonQueryFunction } from "@neondatabase/serverless";
3
3
 
4
4
  //#region src/drivers/neon-http/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-ByvlIQqa.mjs";import{h as n}from"./error-mapping-D--MVRCY.mjs";import{d as r,t as i}from"./query-CTna5P9o.mjs";import{n as a}from"./client-BojZRIyT.mjs";import{c as o,d as s,t as c}from"./driver-XlmOJFRH.mjs";import{t as l}from"./postgres-result-ehQiy2H-.mjs";import{t as u}from"./postgres-adapter-CdUHI_lw.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t}from"./normalized-result-ByvlIQqa.mjs";import{h as n}from"./error-mapping-D--MVRCY.mjs";import{d as r,t as i}from"./query-CTna5P9o.mjs";import{n as a}from"./client-CuBbRKhN.mjs";import{c as o,d as s,t as c}from"./driver-XlmOJFRH.mjs";import{t as l}from"./postgres-result-ehQiy2H-.mjs";import{t as u}from"./postgres-adapter--PJvhRSM.mjs";const d={databaseUrl:!0,options:!0,pgvector:!0,postgis:!0,sharedRelationBodies:!0,relationsPerStatement:!0,namespace:!0};function malformedNeonResult(e,t){let n=e.operation??`execute`;return new r(`Driver "neon-http" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`neon-http`,...e,operation:n}})}function assertNeonFullResult(e,n){if(!(t(e)&&Array.isArray(e.fields))||typeof e.command!=`string`||!Object.hasOwn(e,`rowCount`)||e.rowCount!==null&&(typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0)||!Array.isArray(e.rows)||!e.rows.every(t)||e.rowAsArray!==!1)throw malformedNeonResult(n,`expected fullResults object with object rows and explicit rowCount`)}var NeonHTTPDriver=class extends c{maxBindParametersPerStatement=65535;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;queryTypes;constructor(e={}){super(`postgresql`,`neon-http`);let t=s(e);this.driverOptions=e,u(this,t,e)}async initClient(){let{neon:e,types:t}=await import(`@neondatabase/serverless`);if(!this.driverOptions.databaseUrl)throw new i(`Neon HTTP driver requires a databaseUrl`,{meta:{driver:this.driverName}});let identityParser=e=>e,getTypeParser=((e,n)=>[1082,1114,1184,1115,1182,1185].includes(e)&&n!==`binary`?identityParser:t.getTypeParser(e,n));return this.queryTypes={getTypeParser},e(this.driverOptions.databaseUrl,{fetchOptions:this.driverOptions.options?.fetchOptions,authToken:this.driverOptions.options?.authToken,fullResults:!0,arrayMode:!1})}async closeClient(e){}async execute(e,t,n,r){return this.executeQuery(e,t,n,r,`execute`)}async executeQuery(e,t,n,r,i){let a=r??{operation:i},o=await e.query(t,n,{arrayMode:!1,fullResults:!0,types:this.queryTypes});return this.parseResult(o,a)}async executeRaw(e,t,n,r){return this.executeQuery(e,t,n??[],r,`executeRaw`)}transactionOptionSupport(){return{isolationLevel:`provider`,timeout:!1,timeoutReason:`Neon HTTP runs a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`Neon HTTP submits the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(n(this.driverName))}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=await e.transaction(t.map(t=>{let n=t.context??a;try{return e.query(t.sql,t.params??[],{types:this.queryTypes})}catch(e){throw this.normalizeStatementFailure(e,t.sql,this.getBatchDiagnosticParameters(t),n,!0)}}),{isolationLevel:i?.isolationLevel,arrayMode:!1,fullResults:!0});if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedNeonResult(a,`expected ${t.length} statement results but received ${e}`)}return o.map((e,n)=>this.parseResult(e,t[n]?.context??a))}parseResult(e,t){let n=t.operation??`execute`;return assertNeonFullResult(e,t),{rows:e.rows,rowCount:l(e.rowCount,e.command,e.rows,{provider:`neon-http`,operation:n,model:t.model,correlationId:t.correlationId})}}};function createClient(e){o(e,`neon-http`,d);let{databaseUrl:t,options:n,pgvector:r,postgis:i}=e,c=s(e);return a(e,new NeonHTTPDriver({databaseUrl:t,options:n,pgvector:r,postgis:i,sharedRelationBodies:e.sharedRelationBodies,relationsPerStatement:e.relationsPerStatement,namespace:c}))}export{NeonHTTPDriver,createClient};
2
2
  //# sourceMappingURL=neon-http.mjs.map
@@ -1,7 +1,7 @@
1
- import { Jn as AnyModel, Ln as Dialect } from "./index-BlBkgxtx.mjs";
2
- import { i as ResolveCallback, t as MigrationClient } from "./planner-syQCWHHr.mjs";
1
+ import { Un as Dialect, er as AnyModel } from "./index-NcKTpeZg.mjs";
2
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-CJ321_hX.mjs";
3
3
  import { i as Sha256, n as MigrationStorageWriter, r as PublishResult } from "./contract-CYl0OzhZ.mjs";
4
- import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-CrBKhXo-.mjs";
4
+ import { B as MigrationCheckInput, V as MigrationDecisionV1 } from "./client-CEaKCIbT.mjs";
5
5
 
6
6
  //#region src/adapters/databases/sqlite/storage/datetime.d.ts
7
7
 
package/dist/on.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { It as VibORMClient, Jn as AnyModel, Lt as VibORMConfig, M as ClientSchema, O as OperationResult, Pt as ExtensionState, Vt as WriteOutcome, _i as QueryError, kt as ClientTypeState } from "./index-BlBkgxtx.mjs";
1
+ import { Bt as VibORMClient, Ci as QueryError, Kt as WriteOutcome, Lt as ExtensionState, N as ClientSchema, Vt as VibORMConfig, er as AnyModel, jt as ClientTypeState, k as OperationResult } from "./index-NcKTpeZg.mjs";
2
2
  import "./client.mjs";
3
3
 
4
4
  //#region src/on/index.d.ts
@@ -1,4 +1,4 @@
1
- import { At as DelegateOperationResult, E as OperationPayload, It as VibORMClient, Lt as VibORMConfig, M as ClientSchema, O as OperationResult, Pt as ExtensionState, Qt as AccumulatedExtensionState, Ut as NoControls, Wt as OrderTerm, an as ResultConsumerContextOf, kt as ClientTypeState, nn as ExtensionContributionState, qt as StampedFields } from "./index-BlBkgxtx.mjs";
1
+ import { Bt as VibORMClient, D as OperationPayload, E as NoExtraOperationKeys, Ft as ExtendedClient, Lt as ExtensionState, Mt as DelegateOperationArgs, N as ClientSchema, Nt as DelegateOperationResult, Vt as VibORMConfig, Yt as OrderTerm, jt as ClientTypeState, k as OperationResult } from "./index-NcKTpeZg.mjs";
2
2
  import "./client.mjs";
3
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
4
4
 
@@ -76,64 +76,75 @@ type UpdateData<C$1 extends VibORMConfig, K$1> = NonNullable<NonNullable<ModelAr
76
76
  * of the model's own fields, but the key and the list's (`to` moves a row
77
77
  * between lists), and no relation. */
78
78
  type MoveData<C$1 extends VibORMConfig, Config extends OrderingConfig, K$1 extends keyof Config> = { readonly [F in Exclude<ScalarsOf<C$1, K$1> & keyof UpdateData<C$1, K$1>, Config[K$1]["key"] | WithinOf<Config, K$1>>]?: UpdateData<C$1, K$1>[F] } & None<Config[K$1]["key"] | WithinOf<Config, K$1>>;
79
- type MoveArgs<M, C$1 extends VibORMConfig, Config extends OrderingConfig, K$1 extends keyof Config> = Projection<C$1, K$1> & {
79
+ type MoveArgs<M$1, C$1 extends VibORMConfig, Config extends OrderingConfig, K$1 extends keyof Config> = Projection<C$1, K$1> & {
80
80
  readonly where: Unique<C$1, K$1>;
81
81
  readonly data?: MoveData<C$1, Config, K$1>;
82
- } & MovePlacement<M, C$1, Config, K$1>;
83
- type FindArg<C$1 extends VibORMConfig, K$1, P extends string> = NonNullable<ModelArgs<C$1, K$1, "findMany">>[P & keyof NonNullable<ModelArgs<C$1, K$1, "findMany">>];
82
+ } & MovePlacement<M$1, C$1, Config, K$1>;
83
+ /** A unique selector a move spells, its keys refused as an update's `where`. */
84
+ type SealedUnique<C$1 extends VibORMConfig, K$1, Given> = NoExtraOperationKeys<"update", {
85
+ readonly where: Given;
86
+ }, NonNullable<ModelArgs<C$1, K$1, "update">>, ClientSchema<C$1>[K$1 & keyof ClientSchema<C$1>]>["where"];
87
+ /** The key `Spelled` names that `Allowed` has not. */
88
+ type Sealed<Spelled, Allowed> = Record<Exclude<keyof NonNullable<Spelled>, keyof Allowed>, never>;
89
+ /**
90
+ * A move's own keys, refused where they name nothing: `where` and the
91
+ * anchors as an update's `where` is, `data` and `to` against the fields they
92
+ * may write. `A` is inferred from the call, so every key it spells is known
93
+ * to `MoveArgs`; demanding `never` for the others refuses them however the
94
+ * argument was written. Three mapped types, not one with a conditional per
95
+ * key: comparing two ordered clients' `move` (two `ordering()` calls) then
96
+ * cost 2.5M instantiations instead of 0.1M.
97
+ */
98
+ type SealedMove<A, C$1 extends VibORMConfig, Config extends OrderingConfig, K$1 extends keyof Config> = { readonly [P in keyof A & ("where" | "after" | "before")]?: SealedUnique<C$1, K$1, A[P]> } & { readonly [P in keyof A & "data"]?: Sealed<A[P], MoveData<C$1, Config, K$1>> } & { readonly [P in keyof A & "to"]?: Sealed<A[P], ListOf<C$1, Config, K$1>> };
99
+ type FindArg<C$1 extends VibORMConfig, K$1, P$1 extends string> = NonNullable<ModelArgs<C$1, K$1, "findMany">>[P$1 & keyof NonNullable<ModelArgs<C$1, K$1, "findMany">>];
84
100
  type RekeyOrder<C$1 extends VibORMConfig, K$1> = { readonly [F in keyof RowOf<C$1, K$1>]?: "asc" | "desc" };
85
101
  type RekeyArgs<C$1 extends VibORMConfig, K$1> = {
86
102
  readonly where?: FindArg<C$1, K$1, "where">;
87
103
  readonly orderBy?: RekeyOrder<C$1, K$1> | readonly RekeyOrder<C$1, K$1>[];
88
104
  };
89
- type OrderingModels<M, C$1 extends VibORMConfig, Config extends OrderingConfig> = { readonly [K in Names<Config>]: (delegate: never, scope: never) => {
90
- move<Self, A extends MoveArgs<M, C$1, Config, K>>(this: Self, args: A): PromiseLike<DelegateOperationResult<Self, "update", A>>;
91
- rekey<A extends RekeyArgs<C$1, K>>(args?: A): PromiseLike<{
105
+ /** One ordered model's methods. Exported so an exported client's
106
+ * declaration names it instead of spelling its arguments out. */
107
+ type OrderingMethods<M$1, C$1 extends VibORMConfig, Config extends OrderingConfig, K$1 extends keyof Config> = {
108
+ move<Self, const A extends DelegateOperationArgs<Self, MoveArgs<M$1, C$1, Config, K$1>>>(this: Self, args: A & SealedMove<A, C$1, Config, K$1>): PromiseLike<DelegateOperationResult<Self, "update", A>>;
109
+ rekey<A extends RekeyArgs<C$1, K$1>>(args?: A): PromiseLike<{
92
110
  count: number;
93
111
  }>;
94
- } };
112
+ };
113
+ type OrderingModels<M$1, C$1 extends VibORMConfig, Config extends OrderingConfig> = { readonly [K in Names<Config>]: (delegate: never, scope: never) => OrderingMethods<M$1, C$1, Config, K> };
95
114
  type Governed<Config extends OrderingConfig> = VibORMConfig & {
96
115
  readonly schema: Record<Names<Config>, AnyModel>;
97
116
  };
98
- declare function apply<Config extends OrderingConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, base: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, OrderingModels<VibORMClient<C$1, X$1>, C$1, Config> extends infer T ? T extends OrderingModels<VibORMClient<C$1, X$1>, C$1, Config> ? T extends object ? { readonly [ModelName in keyof T]: T[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : {} : {} } : {} : never : never, NoControls, never, string extends keyof Config & string & keyof C$1["schema"] ? never : ({ readonly [K in keyof Config & string & keyof C$1["schema"]]: {
99
- readonly create: Record<Config[K]["key"], string>;
100
- } } extends infer T_1 ? { [Model in keyof T_1]: "create" extends keyof T_1[Model] ? T_1[Model] extends infer T_2 ? T_2 extends T_1[Model] ? T_2 extends {
101
- readonly create?: infer Fields;
102
- } ? StampedFields<Model, keyof NonNullable<Fields>> : never : never : never : never } : never)[keyof Config & string & keyof C$1["schema"]], ResultConsumerContextOf<{
117
+ declare function definitionOf<Config extends OrderingConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, client: VibORMClient<C$1, X$1>): {
103
118
  name: string;
104
119
  order: {
105
- models: { readonly [K_1 in keyof Config & string & keyof C$1["schema"]]: readonly OrderTerm[] };
120
+ models: { readonly [K in Names<Config> & keyof C$1["schema"]]: readonly OrderTerm[] };
106
121
  };
107
122
  data: {
108
- models: { readonly [K in keyof Config & string & keyof C$1["schema"]]: {
123
+ models: { readonly [K in Names<Config> & keyof C$1["schema"]]: {
109
124
  readonly create: Record<Config[K]["key"], string>;
110
125
  } };
111
126
  };
112
127
  model: OrderingModels<VibORMClient<C$1, X$1>, C$1, Config>;
113
- }>, Record<never, never>>>>;
114
- declare function keysStep<Config extends OrderingConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, base: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, {}, NoControls, never, string extends keyof Config & string & keyof C$1["schema"] ? never : ({ readonly [K in keyof Config & string & keyof C$1["schema"]]: {
115
- readonly create: Record<Config[K]["key"], string>;
116
- } } extends infer T ? { [Model in keyof T]: "create" extends keyof T[Model] ? T[Model] extends infer T_1 ? T_1 extends T[Model] ? T_1 extends {
117
- readonly create?: infer Fields;
118
- } ? StampedFields<Model, keyof NonNullable<Fields>> : never : never : never : never } : never)[keyof Config & string & keyof C$1["schema"]], "result-independent", Record<never, never>>>>;
119
- declare function methodsStep<Config extends OrderingConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, client: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, OrderingModels<VibORMClient<C$1, X$1>, C$1, Config> extends infer T ? T extends OrderingModels<VibORMClient<C$1, X$1>, C$1, Config> ? T extends object ? { readonly [ModelName in keyof T]: T[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : {} : {} } : {} : never : never, NoControls, never, never, ResultConsumerContextOf<{
120
- readonly name: "viborm.ordering.methods";
121
- readonly model: OrderingModels<VibORMClient<C$1, X$1>, C$1, Config>;
122
- }>, Record<never, never>>>>;
128
+ };
129
+ declare function apply<Config extends OrderingConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, base: VibORMClient<C$1, X$1>): ExtendedClient<VibORMClient<C$1, X$1>, readonly [ReturnType<typeof definitionOf<Config, C$1, X$1>>]>;
130
+ /**
131
+ * A model an entry orders, with the scalar fields the entry names (its key
132
+ * and its list's): a misspelled one is refused at application, as a
133
+ * misspelled model is. Read off the model's own scalars, one level deep.
134
+ */
135
+ type OrderedModel<Fields extends string> = AnyModel & {
136
+ readonly "~": {
137
+ readonly state: {
138
+ readonly scalars: Record<Fields, unknown>;
139
+ };
140
+ };
141
+ };
123
142
  type Receiver<Config extends OrderingConfig> = ClientTypeState<VibORMConfig, ExtensionState> & {
124
- readonly $schema: Record<Names<Config>, AnyModel>;
143
+ readonly $schema: { readonly [M in Names<Config>]: OrderedModel<Config[M]["key"] | WithinOf<Config, M>> };
125
144
  readonly $extends: (...args: never[]) => unknown;
126
145
  };
127
146
  type Applied<Config extends OrderingConfig, Base> = Base extends ClientTypeState<infer C extends Governed<Config>, infer X extends ExtensionState> ? Base extends VibORMClient<C, X> ? ReturnType<typeof apply<Config, C, X>> : never : never;
128
- type Keyed<Config extends OrderingConfig, Base> = Base extends ClientTypeState<infer C extends Governed<Config>, infer X extends ExtensionState> ? Base extends VibORMClient<C, X> ? ReturnType<typeof keysStep<Config, C, X>> : never : never;
129
- type Movable<Config extends OrderingConfig, Base> = Base extends ClientTypeState<infer C extends Governed<Config>, infer X extends ExtensionState> ? Base extends VibORMClient<C, X> ? ReturnType<typeof methodsStep<Config, C, X>> : never : never;
130
- type OrderingExtension<Config extends OrderingConfig> = {
131
- <Base extends Receiver<Config>>(base: Base): NoInfer<Applied<Config, Base>>;
132
- /** The default order and appended keys alone (chains written before 1.8). */
133
- readonly keys: <Base extends Receiver<Config>>(base: Base) => Keyed<Config, Base>;
134
- /** `move` and `rekey` alone (chains written before 1.8). */
135
- readonly methods: <Base extends Receiver<Config>>(client: Base) => Movable<Config, Base>;
136
- };
147
+ type OrderingExtension<Config extends OrderingConfig> = <Base extends Receiver<Config>>(base: Base) => NoInfer<Applied<Config, Base>>;
137
148
  /**
138
149
  * Order the members of lists: `client.$extends(ordering({ models: { card: {
139
150
  * key: "rank", within: ["columnId"] } } }))`. One step, applied in any order
@@ -145,4 +156,4 @@ declare function ordering<const Config extends OrderingConfig>(config: {
145
156
  /** The models as the whole argument, the form before 1.9.1, still accepted: write `ordering({ models: { … } })`, as `softDelete` and `permissions` take theirs. */
146
157
  declare function ordering<const Config extends OrderingConfig>(config: Config): OrderingExtension<Config>;
147
158
  //#endregion
148
- export { MAX_KEY_LENGTH, MovePlacement, OrderingConfig, OrderingModel, isKey, isKeyFormat, keyBetween, ordering, orderingKey };
159
+ export { MAX_KEY_LENGTH, MovePlacement, OrderingConfig, OrderingMethods, OrderingModel, isKey, isKeyFormat, keyBetween, ordering, orderingKey };
package/dist/ordering.mjs CHANGED
@@ -7,5 +7,5 @@ import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t,d as n,t as i}from"./quer
7
7
  WHEN ${u} - ${l} >= 2 THEN ${e.concat(encoded(e,o`${l} + 1`),d)}
8
8
  WHEN substr(${c}, 1, length(${s})) = ${s} THEN ${e.concat(s,o`substr(${b}, 1, ${p})`,d)}
9
9
  ELSE ${e.concat(s,d)}
10
- END`;return o`(SELECT CASE WHEN length(d.k) <= ${o.raw(`64`)} THEN d.k END FROM (SELECT ${m} AS k FROM (SELECT b.lo, b.hi, ${decoded(e,o.raw(`b.lo`))} AS il, ${decoded(e,o.raw(`b.hi`))} AS ih FROM (SELECT (${t}) AS lo, (${n}) AS hi${e.fence}) AS b${e.fence}) AS c${e.fence}) AS d)`}function jitter(){let e=new Uint8Array(8);crypto.getRandomValues(e);let t=[...e].filter(e=>e<250).map(e=>e%10);return`${t[0]??5}${t.slice(1).find(e=>e!==0)??5}`}var Computed=class extends u{expression;constructor(e){super(),this.expression=e}compute(){return[this.expression]}};const C=Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>isKeyFormat(e)&&e[0]!==`9`?{value:e}:{issues:[{message:`must be an ordering key (digits, viborm/ordering) with an integer part below 10^8: leave it out to append, or use move`}]}})}),w=`viborm.ordering`,T=Symbol(`missed`),isRecord=e=>typeof e==`object`&&!!e&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),storedOf=e=>{let t=e[`~`].state.scalars;return Object.fromEntries(Object.keys(t).filter(e=>{let{autoGenerate:n,array:i}=t[e][`~`].state;return n?.kind===`updatedAt`&&!i}).map(e=>[e,new l]))};function refuse(e){throw new i(`ordering: ${e}`,{meta:{extension:w}})}function admit(e,t){return Object.entries(t).map(([t,n])=>{Object.hasOwn(e,t)||refuse(`unknown model "${t}".`);let i=e[t],a=i[`~`].state.scalars,o=s(i).rowKey?.fields;o===void 0&&refuse(`${t} needs a primary or unique key.`);let c=n.key,l=Object.hasOwn(a,c)?a[c][`~`].state:refuse(`${t}.${c} is not a scalar field.`);(l.type!==`string`||l.array||l.nullable)&&refuse(`${t}.${c} must be a required string field.`),(l.autoGenerate!==void 0||l.hasDefault&&typeof l.default!=`string`)&&refuse(`${t}.${c} can only default to a literal string: ordering appends the key.`),o.includes(c)&&refuse(`${t}.${c} cannot be part of the model's key.`);let u=[...n.within??[]];for(let e of u)Object.hasOwn(a,e)||refuse(`${t}.within names "${e}", not a scalar field.`),a[e][`~`].state.array&&refuse(`${t}.within names "${e}", a list field.`);return new Set(u).size!==u.length&&refuse(`${t}.within names a field twice.`),u.includes(c)&&refuse(`${t}.within cannot name the key field "${c}".`),Object.freeze({name:t,key:c,within:u,identity:o,model:i})})}const E=[`after`,`before`,`first`,`last`,`key`],same=(e,t)=>e===t||(e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():e!==null&&t!==null&&e!==void 0&&t!==void 0&&String(e)===String(t)),fieldsOf=(e,t)=>Object.fromEntries(e.map(e=>[e,t[e]??null]));function invalid(e,t){throw new a(`update`,[{message:`${e}.move: ${t}`,path:``}])}function engineOf(e,t){let n;return()=>n??={queries:c.get(e).get(t.adapter),dialect:t.dialect}}const movable=e=>Object.freeze({verb:`update`,writes:Object.freeze([e])}),joined=(e,t)=>e.adapter.identifiers.column(`r`,`0viborm_${t}`);var Respace=class extends d{#e;#t;#n;#r;constructor(e,t,n,i){super(),this.#e=e,this.#t=t,this.#n=n,this.#r=i}compute({queries:e}){return[joined(e,`nk`)]}join(e,t){let{model:n,key:i,within:a,identity:s}=this.#e,c=S[this.#t],l=this.#r.flatMap(e=>Object.entries(e)),column=(t,i)=>e.column(n,t,i),at=(e,t,n)=>Array.from({length:n},(n,i)=>o.raw(`${e}.${t}${i}`)),ids=e=>at(e,`i`,s.length),lists=e=>at(e,`w`,a.length),byList=(e,...t)=>a.length+t.length===0?o.empty:o`PARTITION BY ${o.join([...lists(e),...t],`, `)} `,current=e=>o.join([o.raw(`${e}.k`),...ids(e)],`, `),u=new f(n,`w`,void 0,this.#n),d=a.length>0?o`EXISTS (SELECT 1 FROM ${e.table(n,`w`)} WHERE ${o.join(a.map(e=>c.same(column(e,`w`),column(e,`s`))),` AND `)} AND ${u})`:this.#n===void 0?o`1 = 1`:o`EXISTS (SELECT 1 FROM ${e.table(n,`w`)} WHERE ${u})`,p=o`SELECT ${o.join([...s.map((e,t)=>o`${column(e,`s`)} AS ${o.raw(`i${t}`)}`),...a.map((e,t)=>o`${column(e,`s`)} AS ${o.raw(`w${t}`)}`),o`${column(i,`s`)} AS k`,...l.map(([e],t)=>o`${column(e,`s`)} AS ${o.raw(`o${t}`)}`),o`(CASE WHEN ${new f(n,`s`,movable(i))} THEN 1 ELSE 0 END) AS v`],`, `)} FROM ${e.table(n,`s`)} WHERE ${d}`,m=o`(p.v = 0 AND ${c.digits(o.raw(`p.k`))})`,h=[...l.map(([,e],t)=>o`${o.raw(`p.o${t}`)} ${o.raw(e===`desc`?`DESC`:`ASC`)}`),current(`p`)],_=o.raw(`p.v`),v=o.join([o.raw(`p.k DESC`),...ids(`p`).map(e=>o`${e} DESC`)],`, `),y=o`SELECT p.*, SUM(CASE WHEN ${m} THEN 1 ELSE 0 END) OVER (${byList(`p`)}ORDER BY ${current(`p`)} ROWS UNBOUNDED PRECEDING) AS seg, MAX(CASE WHEN ${m} THEN p.k END) OVER (${byList(`p`)}ORDER BY ${current(`p`)} ROWS UNBOUNDED PRECEDING) AS lo, MIN(CASE WHEN ${m} THEN p.k END) OVER (${byList(`p`)}ORDER BY ${v} ROWS UNBOUNDED PRECEDING) AS hi, ROW_NUMBER() OVER (${byList(`p`,_)}ORDER BY ${current(`p`)}) AS slot, ROW_NUMBER() OVER (${byList(`p`,_)}ORDER BY ${o.join(h,`, `)}) AS pick FROM (${p}) AS p`,b=o.join([...lists(`q`),o.raw(`q.seg`)],`, `),x=o`SELECT q.*, ROW_NUMBER() OVER (PARTITION BY ${b} ORDER BY ${current(`q`)}) AS r, COUNT(*) OVER (PARTITION BY ${b}) AS cnt FROM (${y}) AS q WHERE q.v = 1`,keyOf=e=>{let g=t=>o.raw(`${e}.${t}`),t=o`(${g(`slot`)} - 1)`;return o`CASE WHEN ${g(`lo`)} IS NULL AND ${g(`hi`)} IS NULL THEN ${c.concat(c.text(o`length(${c.text(t)})`),c.text(t))} ELSE ${between(c,g(`lo`),g(`hi`),c.concat(c.pad(c.text(g(`r`)),o`length(${c.text(g(`cnt`))})`),o`'1'`))} END`},C=l.length===0?o`SELECT ${o.join([...ids(`g`),...lists(`g`)],`, `)}, g.k, ${keyOf(`g`)} AS nk FROM (${x}) AS g`:o`WITH g AS (${x}) SELECT ${o.join([...ids(`m`),...lists(`m`)],`, `)}, m.k, ${keyOf(`t`)} AS nk FROM g AS t JOIN g AS m ON ${o.join([...a.map((e,t)=>c.same(o.raw(`t.w${t}`),o.raw(`m.w${t}`))),o`t.slot = m.pick`],` AND `)}`,w=[...s.map((e,t)=>`i${t}`),...a.map((e,t)=>`w${t}`),`k`,`nk`],T=o`SELECT ${o.join(w.map(t=>e.adapter.identifiers.aliased(o.raw(`x.${t}`),`0viborm_${t}`)),`, `)} FROM (${C}) AS x`,r=t=>joined(e,t);return{source:o`(${T}) AS r`,on:o.join([...s.map((e,n)=>o`${r(`i${n}`)} = ${column(e,t)}`),...a.map((e,n)=>c.same(r(`w${n}`),column(e,t))),o`${column(i,t)} = ${r(`k`)}`,o`${r(`nk`)} IS NOT NULL`],` AND `)}}};async function respace(e,t,n,i,a,o=[]){return(await n.updateMany({...i,data:{...storedOf(e.model),[e.key]:new Respace(e,t,a,o)}})).count}function methods(e,i){let{name:c,key:l,within:u,identity:d,model:p}=e,m=p[`~`].state.scalars,h=storedOf(p),_=s(p).rowKey,selectorOf=e=>_.name===void 0?{[_.fields[0]]:e[_.fields[0]]}:{[_.name]:fieldsOf(_.fields,e)},v=u.some(e=>m[e][`~`].state.nullable),y=[l,...d].map(e=>({[e]:`asc`})),b=Object.fromEntries([...d,...u,l].map(e=>[e,!0])),x=[l,...u],places=e=>Object.entries(e).some(([e,t])=>t!==void 0&&(!Object.hasOwn(m,e)||x.includes(e))),named=e=>{let t={},take=(e,n)=>{Object.hasOwn(m,e)&&(n===null||n instanceof Date||typeof n!=`object`)&&(t[e]=n)};for(let[t,n]of Object.entries(e))if(Object.hasOwn(m,t))take(t,n);else if(typeof n==`object`&&n&&![`AND`,`OR`,`NOT`].includes(t))for(let[e,t]of Object.entries(n))take(e,t);return t};async function inStatement(e,n,a,s){let{queries:c,dialect:h}=i();if(h!==`postgresql`&&h!==`sqlite`)return T;let _=e.anchor===void 0?void 0:named(e.anchor);if(Object.keys(a).length===0||_!==void 0&&Object.keys(_).length===0)return T;let v=S[h],y=c.table(p),column=(e,t)=>c.column(p,e,t),matches=(e,t)=>o.join(Object.entries(t).map(([t,n])=>n===null?o`${column(t,e)} IS NULL`:o`${column(t,e)} = ${c.fieldValue(p,t,n)}`),` AND `),other=(e,t)=>o`NOT COALESCE((${matches(e,t)}), 1 = 0)`,seen=e=>new f(p,e),of=(e,t,n)=>o`(SELECT ${column(n,e)} FROM ${y} AS ${o.raw(e)} WHERE ${matches(e,t)}${e===`a`?o` AND ${seen(`a`)}`:o.empty})`,listed=e=>_===void 0?n===void 0?of(`m`,a,e):n[e]===null?o`NULL`:c.fieldValue(p,e,n[e]):of(`a`,_,e),inList=e=>u.length===0?o`1 = 1`:o.join(u.map(t=>n!==void 0&&_===void 0&&n[t]===null?o`${column(t,e)} IS NULL`:m[t][`~`].state.nullable&&n===void 0?v.same(column(t,e),listed(t)):o`${column(t,e)} = ${listed(t)}`),` AND `),b=_&&o`SELECT ${column(l,`a`)} FROM ${y} AS a WHERE ${matches(`a`,_)} AND ${other(`a`,a)} AND ${v.digits(column(l,`a`))} AND ${seen(`a`)}`,nearest=e=>o`SELECT ${o.raw(e)}(${column(l,`n`)}) FROM ${y} AS n WHERE ${inList(`n`)} AND ${other(`n`,a)} AND ${v.digits(column(l,`n`))} AND ${seen(`n`)}${_&&b?o` AND ${column(l,`n`)} ${o.raw(e===`MIN`?`>=`:`<=`)} (${b}) AND ${other(`n`,_)}`:o.empty}`,x=o`NULL`,[C,w]=b===void 0?e.first?[x,nearest(`MIN`)]:[nearest(`MAX`),x]:e.after?[b,nearest(`MIN`)]:[nearest(`MAX`),b],E=between(v,C,w,jitter(),b===void 0?void 0:e.after?`lower`:`upper`),D=o`NOT ((${C}) IS NULL OR ${column(l)} > (${C})) OR NOT ((${w}) IS NULL OR ${column(l)} < (${w}))`,guard=e=>o`CASE WHEN ${E} IS NOT NULL${e===void 0?o.empty:o` AND (${e})`} THEN ${column(l)} END`,O={[l]:new Computed(E)},attempt=async(e,n)=>{try{return await s(guard(e),n)}catch(e){if(e instanceof t)return T;throw e}};if(u.length===0||_===void 0&&n===void 0)return attempt(D,O);let k={...O,...Object.fromEntries(u.map(e=>[e,_===void 0?n[e]:new Computed(listed(e))]))},A=o`NOT (${inList()})`,j=o`${inList()} AND (${D})`;if(n!==void 0){let e=await attempt(A,k);return e===T?attempt(j,O):e}let M=await attempt(j,O);return M===T&&!u.some(e=>d.includes(e))?attempt(A,k):M}return o=>{async function place(a){let{where:s,after:d,before:f,first:p,last:m,key:S,to:C,data:w,select:D,include:O,omit:k,...A}=a,j=E.filter(e=>a[e]!==void 0);if((j.length>1||j.length===0&&C===void 0)&&invalid(c,`give exactly one of after, before, first, last, key, or to.`),C!==void 0&&(d!==void 0||f!==void 0)&&invalid(c,`to goes with first, last or key, not with after or before.`),S!==void 0&&!isKeyFormat(S)&&invalid(c,`key takes an ordering key (isKeyFormat, keyBetween).`),(p!==void 0&&p!==!0||m!==void 0&&m!==!0)&&invalid(c,`first and last take true.`),C!==void 0){let e=Object.keys(C);(e.length!==u.length||!u.every(t=>e.includes(t)))&&invalid(c,`to names the list's fields: ${u.join(`, `)}.`)}let M=isRecord(w)?Object.fromEntries(Object.entries(w).filter(([,e])=>e!==void 0)):{};w!==void 0&&(!isRecord(w)||places(M))&&invalid(c,`data writes the model's own fields beside the key: not ${x.join(`, `)}${u.length===0?``:` (to moves the row between lists)`}, nor a relation.`);let N={...h,...M},P=d??f,F={...D===void 0?{}:{select:D},...O===void 0?{}:{include:O},...k===void 0?{}:{omit:k}};if(S!==void 0)try{return await o.update({...A,where:s,data:{...N,[l]:S,...C??{}},...F})}catch(e){throw e instanceof t?new t(c,`move`):e}let I=named(s),L=Object.keys(I),isMoved=e=>L.length>0&&L.every(t=>same(e[t],I[t])),R={...b,...Object.fromEntries(L.map(e=>[e,!0]))},inPlace=async()=>{if(Object.keys(M).length>0)try{return await o.update({...A,where:s,data:N,...F})}catch(e){throw e instanceof t?new t(c,`move`):e}let e=await o.findUnique({...A,where:s,...F});if(e===null)throw new t(c,`move`);return e},z=await inStatement({where:s,anchor:P,after:d!==void 0,first:p===!0},C,I,(e,t)=>o.update({...A,where:{...s,[l]:{equals:()=>e}},data:{...N,...t},...F}));if(z!==T)return z;for(let a=1;;a++){if(a>3)throw new n(`${c}.move: the list kept changing under concurrent writes; try again.`);let f,m,h,x=u.length===0;if(P!==void 0){let e=v||Object.keys(P).length>1?await o.findUnique({...A,where:P,select:R}):void 0,n=e===null?[]:await o.findMany({...A,...e&&{where:fieldsOf(u,e),orderBy:y},cursor:e?selectorOf(e):P,take:d===void 0?-3:3,select:R}),i=d===void 0?n.at(-1):n[0];if(i===void 0)throw new t(c,`move anchor`);if(e&&!_.fields.every(t=>same(i[t],e[t])))continue;isMoved(i)&&invalid(c,`a row cannot be placed next to itself.`),f=fieldsOf(u,i);let a=(d===void 0?n.slice(0,-1).reverse():n.slice(1)).filter(e=>u.every(t=>same(e[t],i[t])));if(a[0]!==void 0&&isMoved(a[0]))return inPlace();let s=a.find(e=>!isMoved(e))?.[l]??null;[m,h]=d===void 0?[s,i[l]]:[i[l],s]}else{if(C===void 0&&u.length>0){let e=await o.findUnique({...A,where:s,select:b});if(e===null)throw new t(c,`move`);f=fieldsOf(u,e),x=!0}else f=C??{};let e=await o.findMany({...A,where:f,take:p===!0?2:-2,select:R}),n=p===!0?e:[...e].reverse();if(n[0]!==void 0&&isMoved(n[0]))return inPlace();let i=n.find(e=>!isMoved(e))?.[l]??null;[m,h]=p===!0?[null,i]:[i,null]}let S;try{(m===null||isKeyFormat(m))&&(h===null||isKeyFormat(h))&&(m===null||h===null||m<h)&&(S=keyBetween(m,h))}catch{}if(S===void 0||!isKeyFormat(S)){await respace(e,i().dialect,o,A,u.length===0?void 0:f);continue}let w={where:{...s,...f},data:{...N,[l]:S}},join=e=>({where:e?{...s,NOT:s.NOT===void 0?f:[s.NOT,f].flat()}:s,data:{...N,[l]:S,...f}}),T=x?[{where:s,data:{...N,[l]:S}}]:C===void 0?[w,join(!1)]:[join(!0),w];for(let e of T)try{return await o.update({...A,...e,...F})}catch(e){if(!(e instanceof t))throw e}throw new t(c,`move`)}}let lazily=e=>{let t,result=()=>t??=e();return{then:(e,t)=>result().then(e,t),catch:e=>result().catch(e),finally:e=>result().finally(e)}};return{move:e=>lazily(()=>place(e)),rekey:(t={})=>lazily(async()=>{let{where:n,orderBy:s,...l}=t,u=s===void 0?[]:Array.isArray(s)?s:[s];for(let t of u)for(let[n,i]of Object.entries(t))if(!Object.hasOwn(e.model[`~`].state.scalars,n)||i!==`asc`&&i!==`desc`)throw new a(`update`,[{path:`orderBy`,message:`${c}.rekey: orderBy takes { field: "asc" | "desc" } over the model's scalar fields.`}]);return{count:await respace(e,i().dialect,o,l,n,u)}})}}}function definitionOf(e,t){let n=admit(t.$schema,e),{$driver:i}=t,a=engineOf(t.$schema,i);return{name:w,order:{models:Object.fromEntries(n.map(({name:e,key:t,within:n})=>[e,[...n,t].map(e=>({[e]:`asc`}))]))},data:{models:Object.fromEntries(n.map(({name:e,key:t,within:n})=>[e,{create:{[t]:new AppendKey(n)}}]))},model:Object.fromEntries(n.map(e=>[e.name,methods(e,a)]))}}function apply(e,t){return t.$extends(definitionOf(e,t))}function keysStep(e,t){let{model:n,...i}=definitionOf(e,t);return t.$extends(i)}function methodsStep(e,t){let{model:n}=definitionOf(e,t);return t.$extends({name:`${w}.methods`,model:n})}function isEnvelope(e){return Object.keys(e).length===1&&`models`in e&&isRecord(e.models)&&Object.values(e.models).every(isRecord)}function ordering(e){let t=isEnvelope(e)?e.models:e;function extend(e){return apply(t,e)}function keys(e){return keysStep(t,e)}function methodsOf(e){return methodsStep(t,e)}return Object.assign(extend,{keys,methods:methodsOf})}export{p as MAX_KEY_LENGTH,y as isKey,isKeyFormat,keyBetween,ordering,C as orderingKey};
10
+ END`;return o`(SELECT CASE WHEN length(d.k) <= ${o.raw(`64`)} THEN d.k END FROM (SELECT ${m} AS k FROM (SELECT b.lo, b.hi, ${decoded(e,o.raw(`b.lo`))} AS il, ${decoded(e,o.raw(`b.hi`))} AS ih FROM (SELECT (${t}) AS lo, (${n}) AS hi${e.fence}) AS b${e.fence}) AS c${e.fence}) AS d)`}function jitter(){let e=new Uint8Array(8);crypto.getRandomValues(e);let t=[...e].filter(e=>e<250).map(e=>e%10);return`${t[0]??5}${t.slice(1).find(e=>e!==0)??5}`}var Computed=class extends u{expression;constructor(e){super(),this.expression=e}compute(){return[this.expression]}};const C=Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>isKeyFormat(e)&&e[0]!==`9`?{value:e}:{issues:[{message:`must be an ordering key (digits, viborm/ordering) with an integer part below 10^8: leave it out to append, or use move`}]}})}),w=`viborm.ordering`,T=Symbol(`missed`),isRecord=e=>typeof e==`object`&&!!e&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),storedOf=e=>{let t=e[`~`].state.scalars;return Object.fromEntries(Object.keys(t).filter(e=>{let{autoGenerate:n,array:i}=t[e][`~`].state;return n?.kind===`updatedAt`&&!i}).map(e=>[e,new l]))};function refuse(e){throw new i(`ordering: ${e}`,{meta:{extension:w}})}function admit(e,t){return Object.entries(t).map(([t,n])=>{Object.hasOwn(e,t)||refuse(`unknown model "${t}".`);let i=e[t],a=i[`~`].state.scalars,o=s(i).rowKey?.fields;o===void 0&&refuse(`${t} needs a primary or unique key.`);let c=n.key,l=Object.hasOwn(a,c)?a[c][`~`].state:refuse(`${t}.${c} is not a scalar field.`);(l.type!==`string`||l.array||l.nullable)&&refuse(`${t}.${c} must be a required string field.`),(l.autoGenerate!==void 0||l.hasDefault&&typeof l.default!=`string`)&&refuse(`${t}.${c} can only default to a literal string: ordering appends the key.`),o.includes(c)&&refuse(`${t}.${c} cannot be part of the model's key.`);let u=[...n.within??[]];for(let e of u)Object.hasOwn(a,e)||refuse(`${t}.within names "${e}", not a scalar field.`),a[e][`~`].state.array&&refuse(`${t}.within names "${e}", a list field.`);return new Set(u).size!==u.length&&refuse(`${t}.within names a field twice.`),u.includes(c)&&refuse(`${t}.within cannot name the key field "${c}".`),Object.freeze({name:t,key:c,within:u,identity:o,model:i})})}const E=[`after`,`before`,`first`,`last`,`key`],same=(e,t)=>e===t||(e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():e!==null&&t!==null&&e!==void 0&&t!==void 0&&String(e)===String(t)),fieldsOf=(e,t)=>Object.fromEntries(e.map(e=>[e,t[e]??null]));function invalid(e,t){throw new a(`update`,[{message:`${e}.move: ${t}`,path:``}])}function engineOf(e,t){let n;return()=>n??={queries:c.get(e).get(t.adapter),dialect:t.dialect}}const movable=e=>Object.freeze({verb:`update`,writes:Object.freeze([e])}),joined=(e,t)=>e.adapter.identifiers.column(`r`,`0viborm_${t}`);var Respace=class extends d{#e;#t;#n;#r;constructor(e,t,n,i){super(),this.#e=e,this.#t=t,this.#n=n,this.#r=i}compute({queries:e}){return[joined(e,`nk`)]}join(e,t){let{model:n,key:i,within:a,identity:s}=this.#e,c=S[this.#t],l=this.#r.flatMap(e=>Object.entries(e)),column=(t,i)=>e.column(n,t,i),at=(e,t,n)=>Array.from({length:n},(n,i)=>o.raw(`${e}.${t}${i}`)),ids=e=>at(e,`i`,s.length),lists=e=>at(e,`w`,a.length),byList=(e,...t)=>a.length+t.length===0?o.empty:o`PARTITION BY ${o.join([...lists(e),...t],`, `)} `,current=e=>o.join([o.raw(`${e}.k`),...ids(e)],`, `),u=new f(n,`w`,void 0,this.#n),d=a.length>0?o`EXISTS (SELECT 1 FROM ${e.table(n,`w`)} WHERE ${o.join(a.map(e=>c.same(column(e,`w`),column(e,`s`))),` AND `)} AND ${u})`:this.#n===void 0?o`1 = 1`:o`EXISTS (SELECT 1 FROM ${e.table(n,`w`)} WHERE ${u})`,p=o`SELECT ${o.join([...s.map((e,t)=>o`${column(e,`s`)} AS ${o.raw(`i${t}`)}`),...a.map((e,t)=>o`${column(e,`s`)} AS ${o.raw(`w${t}`)}`),o`${column(i,`s`)} AS k`,...l.map(([e],t)=>o`${column(e,`s`)} AS ${o.raw(`o${t}`)}`),o`(CASE WHEN ${new f(n,`s`,movable(i))} THEN 1 ELSE 0 END) AS v`],`, `)} FROM ${e.table(n,`s`)} WHERE ${d}`,m=o`(p.v = 0 AND ${c.digits(o.raw(`p.k`))})`,h=[...l.map(([,e],t)=>o`${o.raw(`p.o${t}`)} ${o.raw(e===`desc`?`DESC`:`ASC`)}`),current(`p`)],_=o.raw(`p.v`),v=o.join([o.raw(`p.k DESC`),...ids(`p`).map(e=>o`${e} DESC`)],`, `),y=o`SELECT p.*, SUM(CASE WHEN ${m} THEN 1 ELSE 0 END) OVER (${byList(`p`)}ORDER BY ${current(`p`)} ROWS UNBOUNDED PRECEDING) AS seg, MAX(CASE WHEN ${m} THEN p.k END) OVER (${byList(`p`)}ORDER BY ${current(`p`)} ROWS UNBOUNDED PRECEDING) AS lo, MIN(CASE WHEN ${m} THEN p.k END) OVER (${byList(`p`)}ORDER BY ${v} ROWS UNBOUNDED PRECEDING) AS hi, ROW_NUMBER() OVER (${byList(`p`,_)}ORDER BY ${current(`p`)}) AS slot, ROW_NUMBER() OVER (${byList(`p`,_)}ORDER BY ${o.join(h,`, `)}) AS pick FROM (${p}) AS p`,b=o.join([...lists(`q`),o.raw(`q.seg`)],`, `),x=o`SELECT q.*, ROW_NUMBER() OVER (PARTITION BY ${b} ORDER BY ${current(`q`)}) AS r, COUNT(*) OVER (PARTITION BY ${b}) AS cnt FROM (${y}) AS q WHERE q.v = 1`,keyOf=e=>{let g=t=>o.raw(`${e}.${t}`),t=o`(${g(`slot`)} - 1)`;return o`CASE WHEN ${g(`lo`)} IS NULL AND ${g(`hi`)} IS NULL THEN ${c.concat(c.text(o`length(${c.text(t)})`),c.text(t))} ELSE ${between(c,g(`lo`),g(`hi`),c.concat(c.pad(c.text(g(`r`)),o`length(${c.text(g(`cnt`))})`),o`'1'`))} END`},C=l.length===0?o`SELECT ${o.join([...ids(`g`),...lists(`g`)],`, `)}, g.k, ${keyOf(`g`)} AS nk FROM (${x}) AS g`:o`WITH g AS (${x}) SELECT ${o.join([...ids(`m`),...lists(`m`)],`, `)}, m.k, ${keyOf(`t`)} AS nk FROM g AS t JOIN g AS m ON ${o.join([...a.map((e,t)=>c.same(o.raw(`t.w${t}`),o.raw(`m.w${t}`))),o`t.slot = m.pick`],` AND `)}`,w=[...s.map((e,t)=>`i${t}`),...a.map((e,t)=>`w${t}`),`k`,`nk`],T=o`SELECT ${o.join(w.map(t=>e.adapter.identifiers.aliased(o.raw(`x.${t}`),`0viborm_${t}`)),`, `)} FROM (${C}) AS x`,r=t=>joined(e,t);return{source:o`(${T}) AS r`,on:o.join([...s.map((e,n)=>o`${r(`i${n}`)} = ${column(e,t)}`),...a.map((e,n)=>c.same(r(`w${n}`),column(e,t))),o`${column(i,t)} = ${r(`k`)}`,o`${r(`nk`)} IS NOT NULL`],` AND `)}}};async function respace(e,t,n,i,a,o=[]){return(await n.updateMany({...i,data:{...storedOf(e.model),[e.key]:new Respace(e,t,a,o)}})).count}function methods(e,i){let{name:c,key:l,within:u,identity:d,model:p}=e,m=p[`~`].state.scalars,h=storedOf(p),_=s(p).rowKey,selectorOf=e=>_.name===void 0?{[_.fields[0]]:e[_.fields[0]]}:{[_.name]:fieldsOf(_.fields,e)},v=u.some(e=>m[e][`~`].state.nullable),y=[l,...d].map(e=>({[e]:`asc`})),b=Object.fromEntries([...d,...u,l].map(e=>[e,!0])),x=[l,...u],places=e=>Object.entries(e).some(([e,t])=>t!==void 0&&(!Object.hasOwn(m,e)||x.includes(e))),named=e=>{let t={},take=(e,n)=>{Object.hasOwn(m,e)&&(n===null||n instanceof Date||typeof n!=`object`)&&(t[e]=n)};for(let[t,n]of Object.entries(e))if(Object.hasOwn(m,t))take(t,n);else if(typeof n==`object`&&n&&![`AND`,`OR`,`NOT`].includes(t))for(let[e,t]of Object.entries(n))take(e,t);return t};async function inStatement(e,n,a,s){let{queries:c,dialect:h}=i();if(h!==`postgresql`&&h!==`sqlite`)return T;let _=e.anchor===void 0?void 0:named(e.anchor);if(Object.keys(a).length===0||_!==void 0&&Object.keys(_).length===0)return T;let v=S[h],y=c.table(p),column=(e,t)=>c.column(p,e,t),matches=(e,t)=>o.join(Object.entries(t).map(([t,n])=>n===null?o`${column(t,e)} IS NULL`:o`${column(t,e)} = ${c.fieldValue(p,t,n)}`),` AND `),other=(e,t)=>o`NOT COALESCE((${matches(e,t)}), 1 = 0)`,seen=e=>new f(p,e),of=(e,t,n)=>o`(SELECT ${column(n,e)} FROM ${y} AS ${o.raw(e)} WHERE ${matches(e,t)}${e===`a`?o` AND ${seen(`a`)}`:o.empty})`,listed=e=>_===void 0?n===void 0?of(`m`,a,e):n[e]===null?o`NULL`:c.fieldValue(p,e,n[e]):of(`a`,_,e),inList=e=>u.length===0?o`1 = 1`:o.join(u.map(t=>n!==void 0&&_===void 0&&n[t]===null?o`${column(t,e)} IS NULL`:m[t][`~`].state.nullable&&n===void 0?v.same(column(t,e),listed(t)):o`${column(t,e)} = ${listed(t)}`),` AND `),b=_&&o`SELECT ${column(l,`a`)} FROM ${y} AS a WHERE ${matches(`a`,_)} AND ${other(`a`,a)} AND ${v.digits(column(l,`a`))} AND ${seen(`a`)}`,nearest=e=>o`SELECT ${o.raw(e)}(${column(l,`n`)}) FROM ${y} AS n WHERE ${inList(`n`)} AND ${other(`n`,a)} AND ${v.digits(column(l,`n`))} AND ${seen(`n`)}${_&&b?o` AND ${column(l,`n`)} ${o.raw(e===`MIN`?`>=`:`<=`)} (${b}) AND ${other(`n`,_)}`:o.empty}`,x=o`NULL`,[C,w]=b===void 0?e.first?[x,nearest(`MIN`)]:[nearest(`MAX`),x]:e.after?[b,nearest(`MIN`)]:[nearest(`MAX`),b],E=between(v,C,w,jitter(),b===void 0?void 0:e.after?`lower`:`upper`),D=o`NOT ((${C}) IS NULL OR ${column(l)} > (${C})) OR NOT ((${w}) IS NULL OR ${column(l)} < (${w}))`,guard=e=>o`CASE WHEN ${E} IS NOT NULL${e===void 0?o.empty:o` AND (${e})`} THEN ${column(l)} END`,O={[l]:new Computed(E)},attempt=async(e,n)=>{try{return await s(guard(e),n)}catch(e){if(e instanceof t)return T;throw e}};if(u.length===0||_===void 0&&n===void 0)return attempt(D,O);let k={...O,...Object.fromEntries(u.map(e=>[e,_===void 0?n[e]:new Computed(listed(e))]))},A=o`NOT (${inList()})`,j=o`${inList()} AND (${D})`;if(n!==void 0){let e=await attempt(A,k);return e===T?attempt(j,O):e}let M=await attempt(j,O);return M===T&&!u.some(e=>d.includes(e))?attempt(A,k):M}return o=>{async function place(a){let{where:s,after:d,before:f,first:p,last:m,key:S,to:C,data:w,select:D,include:O,omit:k,...A}=a,j=E.filter(e=>a[e]!==void 0);if((j.length>1||j.length===0&&C===void 0)&&invalid(c,`give exactly one of after, before, first, last, key, or to.`),C!==void 0&&(d!==void 0||f!==void 0)&&invalid(c,`to goes with first, last or key, not with after or before.`),S!==void 0&&!isKeyFormat(S)&&invalid(c,`key takes an ordering key (isKeyFormat, keyBetween).`),(p!==void 0&&p!==!0||m!==void 0&&m!==!0)&&invalid(c,`first and last take true.`),C!==void 0){let e=Object.keys(C);(e.length!==u.length||!u.every(t=>e.includes(t)))&&invalid(c,`to names the list's fields: ${u.join(`, `)}.`)}let M=isRecord(w)?Object.fromEntries(Object.entries(w).filter(([,e])=>e!==void 0)):{};w!==void 0&&(!isRecord(w)||places(M))&&invalid(c,`data writes the model's own fields beside the key: not ${x.join(`, `)}${u.length===0?``:` (to moves the row between lists)`}, nor a relation.`);let N={...h,...M},P=d??f,F={...D===void 0?{}:{select:D},...O===void 0?{}:{include:O},...k===void 0?{}:{omit:k}};if(S!==void 0)try{return await o.update({...A,where:s,data:{...N,[l]:S,...C??{}},...F})}catch(e){throw e instanceof t?new t(c,`move`):e}let I=named(s),L=Object.keys(I),isMoved=e=>L.length>0&&L.every(t=>same(e[t],I[t])),R={...b,...Object.fromEntries(L.map(e=>[e,!0]))},inPlace=async()=>{if(Object.keys(M).length>0)try{return await o.update({...A,where:s,data:N,...F})}catch(e){throw e instanceof t?new t(c,`move`):e}let e=await o.findUnique({...A,where:s,...F});if(e===null)throw new t(c,`move`);return e},z=await inStatement({where:s,anchor:P,after:d!==void 0,first:p===!0},C,I,(e,t)=>o.update({...A,where:{...s,[l]:{equals:()=>e}},data:{...N,...t},...F}));if(z!==T)return z;for(let a=1;;a++){if(a>3)throw new n(`${c}.move: the list kept changing under concurrent writes; try again.`);let f,m,h,x=u.length===0;if(P!==void 0){let e=v||Object.keys(P).length>1?await o.findUnique({...A,where:P,select:R}):void 0,n=e===null?[]:await o.findMany({...A,...e&&{where:fieldsOf(u,e),orderBy:y},cursor:e?selectorOf(e):P,take:d===void 0?-3:3,select:R}),i=d===void 0?n.at(-1):n[0];if(i===void 0)throw new t(c,`move anchor`);if(e&&!_.fields.every(t=>same(i[t],e[t])))continue;isMoved(i)&&invalid(c,`a row cannot be placed next to itself.`),f=fieldsOf(u,i);let a=(d===void 0?n.slice(0,-1).reverse():n.slice(1)).filter(e=>u.every(t=>same(e[t],i[t])));if(a[0]!==void 0&&isMoved(a[0]))return inPlace();let s=a.find(e=>!isMoved(e))?.[l]??null;[m,h]=d===void 0?[s,i[l]]:[i[l],s]}else{if(C===void 0&&u.length>0){let e=await o.findUnique({...A,where:s,select:b});if(e===null)throw new t(c,`move`);f=fieldsOf(u,e),x=!0}else f=C??{};let e=await o.findMany({...A,where:f,take:p===!0?2:-2,select:R}),n=p===!0?e:[...e].reverse();if(n[0]!==void 0&&isMoved(n[0]))return inPlace();let i=n.find(e=>!isMoved(e))?.[l]??null;[m,h]=p===!0?[null,i]:[i,null]}let S;try{(m===null||isKeyFormat(m))&&(h===null||isKeyFormat(h))&&(m===null||h===null||m<h)&&(S=keyBetween(m,h))}catch{}if(S===void 0||!isKeyFormat(S)){await respace(e,i().dialect,o,A,u.length===0?void 0:f);continue}let w={where:{...s,...f},data:{...N,[l]:S}},join=e=>({where:e?{...s,NOT:s.NOT===void 0?f:[s.NOT,f].flat()}:s,data:{...N,[l]:S,...f}}),T=x?[{where:s,data:{...N,[l]:S}}]:C===void 0?[w,join(!1)]:[join(!0),w];for(let e of T)try{return await o.update({...A,...e,...F})}catch(e){if(!(e instanceof t))throw e}throw new t(c,`move`)}}let lazily=e=>{let t,result=()=>t??=e();return{then:(e,t)=>result().then(e,t),catch:e=>result().catch(e),finally:e=>result().finally(e)}};return{move:e=>lazily(()=>place(e)),rekey:(t={})=>lazily(async()=>{let{where:n,orderBy:s,...l}=t,u=s===void 0?[]:Array.isArray(s)?s:[s];for(let t of u)for(let[n,i]of Object.entries(t))if(!Object.hasOwn(e.model[`~`].state.scalars,n)||i!==`asc`&&i!==`desc`)throw new a(`update`,[{path:`orderBy`,message:`${c}.rekey: orderBy takes { field: "asc" | "desc" } over the model's scalar fields.`}]);return{count:await respace(e,i().dialect,o,l,n,u)}})}}}function definitionOf(e,t){let n=admit(t.$schema,e),{$driver:i}=t,a=engineOf(t.$schema,i);return{name:w,order:{models:Object.fromEntries(n.map(({name:e,key:t,within:n})=>[e,[...n,t].map(e=>({[e]:`asc`}))]))},data:{models:Object.fromEntries(n.map(({name:e,key:t,within:n})=>[e,{create:{[t]:new AppendKey(n)}}]))},model:Object.fromEntries(n.map(e=>[e.name,methods(e,a)]))}}function apply(e,t){return t.$extends(definitionOf(e,t))}function isEnvelope(e){return Object.keys(e).length===1&&`models`in e&&isRecord(e.models)&&Object.values(e.models).every(isRecord)}function ordering(e){let t=isEnvelope(e)?e.models:e;function extend(e){return apply(t,e)}return extend}export{p as MAX_KEY_LENGTH,y as isKey,isKeyFormat,keyBetween,ordering,C as orderingKey};
11
11
  //# sourceMappingURL=ordering.mjs.map