viborm 1.7.0 → 1.9.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.
- package/dist/{adapter-namespace-BMss0hKo.mjs → adapter-namespace-VikEzb7o.mjs} +2 -2
- package/dist/{adapter-namespace-BMss0hKo.mjs.map → adapter-namespace-VikEzb7o.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-DWMYN0fw.mjs → batch-refs-ZHBzfoBC.mjs} +2 -2
- package/dist/{batch-refs-DWMYN0fw.mjs.map → batch-refs-ZHBzfoBC.mjs.map} +1 -1
- package/dist/{builder-B4n-7I7Q.mjs → builder-CEQ2TIq7.mjs} +2 -2
- package/dist/{builder-B4n-7I7Q.mjs.map → builder-CEQ2TIq7.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/{chain-DVuRxjPO.mjs → chain-DG_4uSjk.mjs} +2 -2
- package/dist/{chain-DVuRxjPO.mjs.map → chain-DG_4uSjk.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-l7dSOul5.mjs → client-BJuTpcYj.mjs} +20 -20
- package/dist/client-BJuTpcYj.mjs.map +1 -0
- package/dist/client-BpQs13Fn.mjs +2 -0
- package/dist/client-BpQs13Fn.mjs.map +1 -0
- package/dist/{client-7ApJka0M.d.mts → client-CrBKhXo-.d.mts} +2 -2
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{datetime-physical-codec-DTdvABny.mjs → datetime-physical-codec-Cdgq6sGs.mjs} +2 -2
- package/dist/{datetime-physical-codec-DTdvABny.mjs.map → datetime-physical-codec-Cdgq6sGs.mjs.map} +1 -1
- package/dist/{driver-DaBNytbz.mjs → driver-DX8GWgGf.mjs} +2 -2
- package/dist/{driver-DaBNytbz.mjs.map → driver-DX8GWgGf.mjs.map} +1 -1
- package/dist/{driver-CK_IKqDa.mjs → driver-XlmOJFRH.mjs} +2 -2
- package/dist/{driver-CK_IKqDa.mjs.map → driver-XlmOJFRH.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/every-CyllpuCG.mjs +2 -0
- package/dist/{every-6VrIclsx.mjs.map → every-CyllpuCG.mjs.map} +1 -1
- package/dist/{geo-area-codec-DvHcWF3g.mjs → geo-area-codec-B3QtKij8.mjs} +2 -2
- package/dist/{geo-area-codec-DvHcWF3g.mjs.map → geo-area-codec-B3QtKij8.mjs.map} +1 -1
- package/dist/{geo-point-codec-CIZxuIvE.mjs → geo-point-codec-Ggv29hSH.mjs} +2 -2
- package/dist/{geo-point-codec-CIZxuIvE.mjs.map → geo-point-codec-Ggv29hSH.mjs.map} +1 -1
- package/dist/{hydration-BUBkHlCK.mjs → hydration-Dd2H4EyY.mjs} +2 -2
- package/dist/{hydration-BUBkHlCK.mjs.map → hydration-Dd2H4EyY.mjs.map} +1 -1
- package/dist/{identifier-conversion-BXrBYgAq.mjs → identifier-conversion-BVE8cfFA.mjs} +2 -2
- package/dist/{identifier-conversion-BXrBYgAq.mjs.map → identifier-conversion-BVE8cfFA.mjs.map} +1 -1
- package/dist/{index-CsO6vG2h.d.mts → index-BlBkgxtx.d.mts} +82 -8
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-Cz83fdLO.mjs → key-B4B1etH3.mjs} +2 -2
- package/dist/{key-Cz83fdLO.mjs.map → key-B4B1etH3.mjs.map} +1 -1
- package/dist/{keys-EP1Eq2eD.mjs → keys-CyfjT6uC.mjs} +2 -2
- package/dist/{keys-EP1Eq2eD.mjs.map → keys-CyfjT6uC.mjs.map} +1 -1
- package/dist/{libsql-ClGi2zY2.mjs → libsql-CcKrXiun.mjs} +2 -2
- package/dist/{libsql-ClGi2zY2.mjs.map → libsql-CcKrXiun.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-B1GnzgZr.mjs → memory-B0HOEpPu.mjs} +2 -2
- package/dist/{memory-B1GnzgZr.mjs.map → memory-B0HOEpPu.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{model-DsXZ_pHE.mjs → model-u8Ug971J.mjs} +2 -2
- package/dist/{model-DsXZ_pHE.mjs.map → model-u8Ug971J.mjs.map} +1 -1
- package/dist/{mysql-adapter-D-Dq2FN9.mjs → mysql-adapter-CWisQgdc.mjs} +2 -2
- package/dist/{mysql-adapter-D-Dq2FN9.mjs.map → mysql-adapter-CWisQgdc.mjs.map} +1 -1
- package/dist/{mysql-hoo290Dd.mjs → mysql-sGTzkV2q.mjs} +2 -2
- package/dist/{mysql-hoo290Dd.mjs.map → mysql-sGTzkV2q.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{normalized-result-23DWxZVY.mjs → normalized-result-ByvlIQqa.mjs} +2 -2
- package/dist/{normalized-result-23DWxZVY.mjs.map → normalized-result-ByvlIQqa.mjs.map} +1 -1
- package/dist/{object-store-9VfS-3sY.d.mts → object-store-C-VOh0LP.d.mts} +3 -3
- package/dist/on.d.mts +1 -1
- package/dist/ordering.d.mts +55 -19
- package/dist/ordering.mjs +8 -8
- package/dist/ordering.mjs.map +1 -1
- package/dist/permissions.d.mts +22 -3
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{physical-t_gDjUCD.mjs → physical-CjG29tya.mjs} +2 -2
- package/dist/{physical-t_gDjUCD.mjs.map → physical-CjG29tya.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-Cc3ABIUU.d.mts → planner-syQCWHHr.d.mts} +1 -1
- package/dist/{postgres-CqcP_qv-.mjs → postgres-C2uUUh0t.mjs} +2 -2
- package/dist/{postgres-CqcP_qv-.mjs.map → postgres-C2uUUh0t.mjs.map} +1 -1
- package/dist/{postgres-adapter-CYZAL2uo.mjs → postgres-adapter-CdUHI_lw.mjs} +2 -2
- package/dist/{postgres-adapter-CYZAL2uo.mjs.map → postgres-adapter-CdUHI_lw.mjs.map} +1 -1
- package/dist/{postgres-adapter-_o6EWuxW.mjs → postgres-adapter-D4v50VQk.mjs} +2 -2
- package/dist/{postgres-adapter-_o6EWuxW.mjs.map → postgres-adapter-D4v50VQk.mjs.map} +1 -1
- package/dist/{postgres-result-D94PyZ78.mjs → postgres-result-ehQiy2H-.mjs} +2 -2
- package/dist/{postgres-result-D94PyZ78.mjs.map → postgres-result-ehQiy2H-.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/{provider-limits-kO9B3KCF.mjs → provider-limits-DolYOv3_.mjs} +2 -2
- package/dist/{provider-limits-kO9B3KCF.mjs.map → provider-limits-DolYOv3_.mjs.map} +1 -1
- package/dist/{result-shape-uaCsF_SZ.mjs → result-shape-dG_6HE7s.mjs} +2 -2
- package/dist/{result-shape-uaCsF_SZ.mjs.map → result-shape-dG_6HE7s.mjs.map} +1 -1
- package/dist/{rows-AtX0guAb.mjs → rows-CEYfrodD.mjs} +2 -2
- package/dist/rows-CEYfrodD.mjs.map +1 -0
- package/dist/rows-of-Djavcb19.mjs +2 -0
- package/dist/rows-of-Djavcb19.mjs.map +1 -0
- package/dist/{scalar-CZ_q89Hc.mjs → scalar-DNshDNz3.mjs} +2 -2
- package/dist/{scalar-CZ_q89Hc.mjs.map → scalar-DNshDNz3.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DYPfTOQl.mjs +2 -0
- package/dist/{schema-CZTCxG2p.mjs.map → schema-DYPfTOQl.mjs.map} +1 -1
- package/dist/{schema-introspection-DoZHc1o7.mjs → schema-introspection-Bu2N__75.mjs} +2 -2
- package/dist/{schema-introspection-DoZHc1o7.mjs.map → schema-introspection-Bu2N__75.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-BtNtBsUh.mjs → select-assembly-Dcaqm09G.mjs} +2 -2
- package/dist/{select-assembly-BtNtBsUh.mjs.map → select-assembly-Dcaqm09G.mjs.map} +1 -1
- package/dist/soft-delete.d.mts +116 -14
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/sql-BsBoKwaf.mjs +2 -0
- package/dist/sql-BsBoKwaf.mjs.map +1 -0
- package/dist/{sql-BnXk8adi.d.mts → sql-D7JnXgUh.d.mts} +5 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/{sqlite-adapter-CnAwmszh.mjs → sqlite-adapter-BHx--tnz.mjs} +2 -2
- package/dist/{sqlite-adapter-CnAwmszh.mjs.map → sqlite-adapter-BHx--tnz.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-Ci8ROrql.mjs → standard-sql-BtzSzrof.mjs} +2 -2
- package/dist/standard-sql-BtzSzrof.mjs.map +1 -0
- package/dist/{to-many-BtLpp5cW.mjs → to-many-5gt2AWLE.mjs} +2 -2
- package/dist/{to-many-BtLpp5cW.mjs.map → to-many-5gt2AWLE.mjs.map} +1 -1
- package/dist/{utils-CAACs9Jw.mjs → utils-CmNRGkRq.mjs} +2 -2
- package/dist/{utils-CAACs9Jw.mjs.map → utils-CmNRGkRq.mjs.map} +1 -1
- package/dist/{v-Pb_jJOjC.mjs → v-CWY9ntMb.mjs} +2 -2
- package/dist/{v-Pb_jJOjC.mjs.map → v-CWY9ntMb.mjs.map} +1 -1
- package/dist/{validation-BSpO4DjI.mjs → validation-CMvAxrIo.mjs} +2 -2
- package/dist/{validation-BSpO4DjI.mjs.map → validation-CMvAxrIo.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-Dthaj1Hz.mjs → validator-CYKdGTvX.mjs} +2 -2
- package/dist/{validator-Dthaj1Hz.mjs.map → validator-CYKdGTvX.mjs.map} +1 -1
- package/dist/version-B7NRPl4T.mjs +2 -0
- package/dist/{version-DvynkoaW.mjs.map → version-B7NRPl4T.mjs.map} +1 -1
- package/package.json +23 -23
- package/dist/client-Yqn0LqmI.mjs +0 -2
- package/dist/client-Yqn0LqmI.mjs.map +0 -1
- package/dist/client-l7dSOul5.mjs.map +0 -1
- package/dist/every-6VrIclsx.mjs +0 -2
- package/dist/insert-value-Cbp_bNxj.mjs +0 -2
- package/dist/insert-value-Cbp_bNxj.mjs.map +0 -1
- package/dist/rows-AtX0guAb.mjs.map +0 -1
- package/dist/schema-CZTCxG2p.mjs +0 -2
- package/dist/sql-DGtEeP8z.mjs +0 -2
- package/dist/sql-DGtEeP8z.mjs.map +0 -1
- package/dist/standard-sql-Ci8ROrql.mjs.map +0 -1
- package/dist/version-DvynkoaW.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-assembly-BtNtBsUh.mjs","names":["sql","sql"],"sources":["../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\n/** The three substring filters, as `insensitiveText` names them. */\nexport type TextMatch = \"contains\" | \"startsWith\" | \"endsWith\";\n\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n like: (column: Sql, pattern: Sql) => Sql;\n notLike: (column: Sql, pattern: Sql) => Sql;\n /** Case-insensitive LIKE. */\n ilike: (column: Sql, pattern: Sql) => Sql;\n notIlike: (column: Sql, pattern: Sql) => Sql;\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * The same three predicates under `mode: \"insensitive\"`: letter case is\n * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the\n * answer for a non-ASCII letter follows the database and its locale.\n * Accents and every other difference still count.\n *\n * Both operands arrive raw: neither folded nor wrapped in\n * `caseSensitiveText`. A plain string `value` is a bare bound parameter,\n * which an adapter matching with `LIKE` escapes client-side.\n */\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /**\n * Fold letter case the way this database does natively (its own `LOWER`),\n * for `mode: \"insensitive\"` equality, membership and ranges. The caller\n * compares the result under `caseSensitiveText`, so case is the only\n * difference it ignores. `expr` arrives raw, never wrapped in\n * `caseSensitiveText`, with the native type of the column it reads.\n */\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and so does a bytes list longer than `literals.list` keeps\n * parenthesized; nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * `stringAtPath` in the database's own text type and collation, for\n * `mode: \"insensitive\"`: the byte-ordered pin stops a database folding\n * case (`LOWER`/`ILIKE` under PG `COLLATE \"C\"` fold `A`-`Z` only, and\n * MySQL's `LOWER` leaves a binary string as it is).\n */\n foldableStringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** EXISTS wrapper for \"some\" relation filter (to-many) */\n some: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"every\" - negated condition (to-many) */\n every: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"none\" (to-many) */\n none: (subquery: Sql) => Sql;\n /** EXISTS wrapper for \"is\" relation filter (to-one) */\n is: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"isNot\" relation filter (to-one) */\n isNot: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n /**\n * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`\n * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).\n * Absent where the statement cannot say: an upsert that must report its\n * arm then reads the row first.\n */\n upserted?: Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n /**\n * A one-column SELECT answering 1 where `condition` holds (over `from`'s\n * row when given), aborting the statement it is part of otherwise, NULL\n * included: the guard a write carries for the row it produces, read as a\n * scalar inside that write.\n */\n holds: (condition: Sql, from?: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /** UNION ALL (keeps duplicates). */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n /**\n * `rows` as ONE FROM item `alias` whose columns are `typed.columns`,\n * each typed as that column of the table `typed.from` reads under\n * `typed.alias`: the rows a judged write produces, read before it writes\n * them. `typed.head` is the empty read of those columns (`… WHERE\n * FALSE`); a row lists its values in `columns`' order and may refer to\n * the enclosing query. The form is the dialect's, because every one\n * spends a different limit on the row count first: one `UNION ALL\n * SELECT` arm per row (the default, MySQL: 65,535 arms measured) is a\n * compound term each, refused past `SQLITE_MAX_COMPOUND_SELECT` (500) on\n * SQLite, and one parser recursion each on PostgreSQL (`54001` at 8,000\n * rows), where a `VALUES` list is neither. The bind budget stays the\n * only bound on a chunk (ENG-3, review 2).\n */\n typedRows: (\n typed: {\n readonly head: Sql;\n readonly from: Sql;\n /** The table itself, unaliased: its row type names the columns' types. */\n readonly table: Sql;\n readonly alias: string;\n readonly columns: readonly string[];\n },\n rows: readonly (readonly Sql[])[],\n alias: string\n ) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * Matches filter schema: { l2, cosine }\n * Drivers that don't support vector operations can override\n * this property with an object that throws FeatureNotSupportedError.\n *\n * Reserved — the query engine does not call these yet; vector filters are\n * rejected in the where-builder today.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance operator for ORDER BY: column <-> vector */\n l2: (column: Sql, vector: Sql) => Sql;\n /** Cosine distance operator for ORDER BY: column <=> vector */\n cosine: (column: Sql, vector: Sql) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n appendFilterParts(fragments, parts);\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (fragments: Sql[], parts: QueryParts): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n appendFilterParts(innerFragments, parts);\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outerFragments: Sql[] = [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (order) {\n outerFragments.push(sql`ORDER BY ${order.orderBy}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFA0BA,SAAgB,gCACd,EACsB,CACtB,IAAM,UAAY,EAAmB,KAAsC,CACzE,OACA,gBAAiB,CAAE,MAAO,EAAW,WAAY,EAAM,CACxD,EACD,MAAO,CACL,WAAa,GAAc,SAAS,EAAW,EAAe,EAAU,CAAC,CACzE,QAAS,EAAW,IAClB,SAAS,EAAW,GAAG,EAAU,GAAG,EAAQ,MAAM,CACrD,CAIH,MAAa,EAAmD,CAC9D,YAAa,EAAW,KAAa,CACnC,KAAM,GAAG,EAAU,OACnB,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAA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AAW,EAC3D,EAAQ,EAAM,cAEd,EAAuB,CAAC,EAAM,QAAQ,CACxC,GACF,EAAc,KAAK,EAAM,KAAK,CAEhC,EAAc,KACZ,CAAG,mCAAmC,EAAS,YAAY,EAAe,OAAO,EAAiB,MAAM,GACzG,CAGD,IAAM,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAe,KAAK,GAC1C,CAAG,QAAQ,EAAM,OAClB,CAED,kBAAkB,EAAgB,EAAM,CAExC,IAAM,EAAaA,EAAI,KAAK,EAAgB,IAAI,CAK1C,EAAe,EAAM,sBAAuB,IAAI,EAAiB,CACjE,EAAwB,CAC5B,CAAG,UAAUA,EAAI,KAAK,EAAc,KAAK,CAAC,SAAS,EAAW,OAAO,EAAiB,qBAAqB,GAC3G,CAAG,SAAS,EAAiB,MAAM,CAAC,MACrC,CAQD,OANI,GACF,EAAe,KAAK,CAAG,YAAY,EAAM,UAAU,CAGrD,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
|
|
1
|
+
{"version":3,"file":"select-assembly-Dcaqm09G.mjs","names":["sql","sql"],"sources":["../src/adapters/constraint-identity.ts","../src/adapters/database-adapter.ts","../src/adapters/shared/decimal-arithmetic.ts","../src/adapters/shared/geo-point.ts","../src/adapters/shared/select-assembly.ts"],"sourcesContent":["/** The exact normalized provider evidence that identifies one constraint. */\nexport interface NormalizedConstraintDescriptor {\n readonly table?: string;\n readonly constraint?: string;\n readonly columns?: readonly string[];\n}\n\nexport interface ConstraintIdentity {\n readonly name: string;\n readonly normalizedError: NormalizedConstraintDescriptor;\n}\n\n/** Private adapter projection from a schema key to its physical identity. */\nexport interface ConstraintIdentities {\n readonly primaryKey: (\n tableName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n readonly unique: (\n tableName: string,\n keyName: string,\n columns: readonly string[]\n ) => ConstraintIdentity;\n}\n\n/** PostgreSQL/MySQL errors identify named constraints and their table. */\nexport function createNamedConstraintIdentities(\n primaryKeyName: (tableName: string) => string\n): ConstraintIdentities {\n const identity = (tableName: string, name: string): ConstraintIdentity => ({\n name,\n normalizedError: { table: tableName, constraint: name },\n });\n return {\n primaryKey: (tableName) => identity(tableName, primaryKeyName(tableName)),\n unique: (tableName, keyName) =>\n identity(tableName, `${tableName}_${keyName}_key`),\n };\n}\n\n/** Driver normalization separates SQLite's physical table and columns. */\nexport const sqliteConstraintIdentities: ConstraintIdentities = {\n primaryKey: (tableName, columns) => ({\n name: `${tableName}_pkey`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n unique: (tableName, keyName, columns) => ({\n name: `${tableName}_${keyName}_key`,\n normalizedError: {\n table: tableName,\n columns: [...columns],\n },\n }),\n};\n","import type { NativeTypeDeclaration } from \"@schema/scalars/native-types\";\nimport type { Sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type {\n GeoBounds,\n GeoPoint,\n GeoPolygon,\n} from \"@validation/primitives/geo-values\";\nimport type { IdRepresentation } from \"@validation/primitives/id-codec\";\nimport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nimport type { ArithmeticTarget, CastType } from \"./adapter-core-types\";\nimport type { AdapterResultParser } from \"./adapter-result-parser\";\n\nexport type { DatabaseAdapterCapabilities } from \"./adapter-capabilities\";\nexport type {\n ArithmeticTarget,\n CastType,\n} from \"./adapter-core-types\";\nexport type { AdapterResultParser } from \"./adapter-result-parser\";\n\n/** The one physical SQL vocabulary for a logical EPSG:4326 GeoPoint. */\nexport interface GeoPointSql {\n /** Construct a stored point from already-bound longitude and latitude. */\n readonly value: (longitude: Sql, latitude: Sql) => Sql;\n /** Project the logical longitude from a stored point. */\n readonly longitude: (point: Sql) => Sql;\n /** Project the logical latitude from a stored point. */\n readonly latitude: (point: Sql) => Sql;\n /** Exact canonical coordinate equality. */\n readonly equals: (point: Sql, expected: GeoPoint) => Sql;\n /** Inclusive coordinate bounds, including antimeridian-crossing bounds. */\n readonly withinBounds: (point: Sql, bounds: GeoBounds) => Sql;\n /** Inclusive geographic polygon membership on full-tier providers. */\n readonly withinPolygon?: (point: Sql, polygon: GeoPolygon) => Sql;\n /** Fixed-radius spherical distance in meters on full-tier providers. */\n readonly distance?: (left: Sql, right: Sql) => Sql;\n}\n\n/** Install the adapter's settled GeoPoint protocol as one immutable fact. */\nexport function installGeoPointSql(\n adapter: object,\n geoPoint: GeoPointSql | undefined\n): void {\n let installed: GeoPointSql | undefined;\n if (geoPoint) {\n const withinPolygon = geoPoint.withinPolygon;\n const distance = geoPoint.distance;\n installed = Object.freeze<GeoPointSql>({\n value: geoPoint.value,\n longitude: geoPoint.longitude,\n latitude: geoPoint.latitude,\n equals: geoPoint.equals,\n withinBounds: geoPoint.withinBounds,\n ...(withinPolygon ? { withinPolygon } : {}),\n ...(distance ? { distance } : {}),\n });\n }\n Object.defineProperty(adapter, \"geoPoint\", {\n value: installed,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n\n/**\n * DatabaseAdapter Interface\n *\n * A monadic, composable interface for database-specific SQL generation.\n * Each method is a pure function that transforms Sql fragments or primitives\n * into new Sql fragments, enabling clean composition without side effects.\n *\n * DESIGN PRINCIPLES:\n * - Pure functions: Same inputs always produce same outputs\n * - Composable: Outputs can be inputs to other methods\n * - Database-agnostic inputs: Query engine speaks neutral language\n * - Database-specific outputs: Adapter handles syntax differences\n *\n * USAGE:\n * The query engine calls adapter methods to build SQL fragments,\n * then composes them into complete queries. The adapter never\n * needs to understand query semantics - just SQL syntax.\n */\n/** The three substring filters, as `insensitiveText` names them. */\nexport type TextMatch = \"contains\" | \"startsWith\" | \"endsWith\";\n\nexport interface DatabaseAdapter {\n /**\n * NAMESPACE\n * The one normalized SQL qualification value for this adapter's persistent\n * objects — a PostgreSQL schema, a MySQL database, or a requested Vitess\n * keyspace qualifier. `undefined` means deliberately unqualified: unbound\n * MySQL and every SQLite adapter. It is selected once at construction and\n * installed non-writable, and THAT INSTALL is where its immutability lives —\n * not a ban on copies: the two readers that capture it once, the bound\n * migration driver at bind time and the `readDriverIdentity` snapshot a cached\n * read takes, cannot go stale because the property they read can never be\n * reassigned.\n */\n readonly namespace?: string;\n\n /**\n * RAW\n * Escape hatch for raw SQL strings (use sparingly)\n */\n raw: (sqlString: string) => Sql;\n\n /**\n * IDENTIFIERS\n * Database-specific identifier escaping (table names, column names, aliases)\n */\n identifiers: {\n /** Escape a single identifier: \"name\" or `name` */\n escape: (name: string) => Sql;\n /** Create qualified column reference: \"alias\".\"field\" */\n column: (alias: string, field: string) => Sql;\n /**\n * The one renderer for a persistent model or junction table: applies the\n * adapter's namespace and, when an alias is given, the `AS` clause.\n * Statement-local names — CTEs, aliases, columns, constraints — use\n * `escape` instead, and an omitted alias is for a site that splices its own.\n */\n table: (tableName: string, alias?: string) => Sql;\n /** Create aliased expression: expr AS \"alias\" */\n aliased: (expression: Sql, alias: string) => Sql;\n };\n\n /**\n * LITERALS\n * Value wrapping with proper parameterization\n */\n literals: {\n /** Wrap a value as parameterized SQL */\n value: (v: unknown) => Sql;\n /** NULL keyword */\n null: () => Sql;\n /** TRUE literal (database-specific: TRUE vs 1) */\n true: () => Sql;\n /** FALSE literal (database-specific: FALSE vs 0) */\n false: () => Sql;\n /**\n * Returns the dialect's membership operand, valid only as `operators.in` /\n * `notIn` input: a parenthesized list, a PostgreSQL array parameter, or,\n * past 25 members, a SQLite `json_each` subquery.\n */\n list: (values: Sql[]) => Sql;\n /** JSON value (PG: native, MySQL/SQLite: JSON.stringify) */\n json: (v: unknown) => Sql;\n /**\n * Datetime operand from a validated ISO-8601 string, in the PHYSICAL form\n * the destination column holds (PG: as-is, MySQL: naive UTC\n * 'YYYY-MM-DD HH:MM:SS.mmm').\n *\n * `nativeType` is the field's own declaration, threaded because SQLite has\n * no temporal type: a `s.dateTime(SQLITE.DATETIME.INTEGER)` column holds\n * epoch milliseconds and a `REAL` one holds a Julian day, so an ISO string\n * bound into either compares against nothing and stores text the typed read\n * then refuses. The dialects that DO have a temporal type ignore it — their\n * own native types all name a column that accepts this same spelling.\n */\n dateTime: (\n iso: string,\n nativeType?: NativeTypeDeclaration,\n member?: boolean\n ) => Sql;\n /**\n * Decimal operand from a canonical decimal string, in the DOMAIN it is\n * being compared or assigned against.\n *\n * The value binds as text and the DIALECT decides how to read it, because\n * the reading is where precision is won or lost. PostgreSQL and MySQL cast\n * it into their exact decimal type — MySQL in particular compares a\n * `DECIMAL` column against an uncast string operand as a *double*, which\n * would make an exact column compare inexactly with nothing to show for it.\n * SQLite has no exact decimal type and stores the unscaled integer\n * coefficient, so there the operand becomes that same coefficient.\n *\n * The descriptor is the operand's domain, which is USUALLY the field's and\n * deliberately not always: a `having: { _sum: ... }` operand is compared\n * against a sum that may legitimately be wider than any single row's\n * column, so the aggregate's caller widens the precision it passes. The\n * scale is the field's on every path — it is what makes the operand and the\n * column the same physical kind of number.\n */\n decimal: (canonical: string, descriptor: DecimalDescriptor) => Sql;\n /**\n * Identifier operand, in the PHYSICAL representation its column holds.\n *\n * The value arrives already encoded by the codec — canonical public text,\n * canonical UUID text, or the payload's own bytes — so nothing here reads a\n * format, a prefix or an alphabet. What the dialect owns is the BINDING: a\n * PostgreSQL `uuid` column takes text and wants the operand typed as\n * `uuid`, because an untyped text operand against a `uuid` column is\n * `operator does not exist: uuid = text`; a `bytea`, `BINARY(n)` or `BLOB`\n * column takes the bytes as an ordinary binary parameter, which every\n * driver already serializes for blob scalars.\n *\n * Separate from {@link DatabaseAdapter.literals.value} for the reason\n * `decimal` is: the operand and the column have to be ONE physical kind, and\n * a generic parameter leaves that to inference at every site.\n */\n id: (\n physical: string | Uint8Array,\n representation: IdRepresentation\n ) => Sql;\n };\n\n /**\n * OPERATORS\n * Comparison and logical operators (pure Sql -> Sql)\n */\n operators: {\n // Comparison\n eq: (left: Sql, right: Sql) => Sql;\n neq: (left: Sql, right: Sql) => Sql;\n lt: (left: Sql, right: Sql) => Sql;\n lte: (left: Sql, right: Sql) => Sql;\n gt: (left: Sql, right: Sql) => Sql;\n gte: (left: Sql, right: Sql) => Sql;\n\n // Pattern matching\n like: (column: Sql, pattern: Sql) => Sql;\n notLike: (column: Sql, pattern: Sql) => Sql;\n /** Case-insensitive LIKE. */\n ilike: (column: Sql, pattern: Sql) => Sql;\n notIlike: (column: Sql, pattern: Sql) => Sql;\n /** Case-sensitive substring predicates, independent of database collation. */\n containsText: (column: Sql, value: Sql) => Sql;\n startsWithText: (column: Sql, value: Sql) => Sql;\n endsWithText: (column: Sql, value: Sql) => Sql;\n /**\n * The same three predicates under `mode: \"insensitive\"`: letter case is\n * ignored the way THIS database folds it (its own `LOWER`/`ILIKE`), so the\n * answer for a non-ASCII letter follows the database and its locale.\n * Accents and every other difference still count.\n *\n * Both operands arrive raw: neither folded nor wrapped in\n * `caseSensitiveText`. A plain string `value` is a bare bound parameter,\n * which an adapter matching with `LIKE` escapes client-side.\n */\n insensitiveText: (\n kind: TextMatch,\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n /**\n * `startsWithText` for a plain string operand, spelled so the dialect's\n * planner can turn it into an index range.\n *\n * Same answer as `startsWithText` on every input — it exists only because\n * `startsWithText` wraps the COLUMN in a function (`LEFT`/`substr`), which\n * no planner can range on. This one takes the raw JS string instead of a\n * bound `Sql` so the adapter can escape it into its own pattern language\n * and bind the finished pattern; a pattern assembled in SQL from the\n * operand would be non-constant and lose the range again.\n *\n * Only the where-builder's default-mode, plain-string, `string`-scalar path\n * reaches it. A field-reference operand, a JSON path, an enum column and\n * `mode: \"insensitive\"` all keep `startsWithText`: each of those either has\n * no client-side string to escape, or already wraps the column in a fold\n * that forecloses the range anyway.\n *\n * Each dialect's implementation must hold the case-sensitivity contract\n * `startsWithText` documents. See the per-adapter comments — the three\n * answers are not the same shape, and the measurements that forced that\n * are recorded in `docs/architecture/query-performance-plan.md`, §7.3.\n */\n startsWithPrefix: (\n column: Sql,\n value: string,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n /**\n * `column = value` and `column IN (values)` on a TEXT column, under the\n * case-sensitive semantics `caseSensitiveText` spells, written so the\n * dialect's planner can still use an index.\n *\n * `column` arrives unwrapped: each adapter applies its own\n * `caseSensitiveText` where its own semantics need it, and is free to put\n * an index-usable conjunct in front of it. On PostgreSQL and SQLite that\n * is exactly `caseSensitiveText(column) <op> …` and nothing more — their\n * case-sensitive spellings are already index-usable. MySQL's is not: the\n * `BINARY` cast is a function of the column, so the planner drops to a full\n * scan, and MySQL adds a collation-native conjunct in front. See\n * `docs/architecture/query-performance-plan.md`, §10.2 for the plans.\n *\n * The operands are BOUND values, never referenced columns — the caller\n * routes a reference to the plain comparison, which has no index lookup to\n * preserve.\n */\n exactTextEq: (\n column: Sql,\n value: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n exactTextIn: (\n column: Sql,\n values: Sql,\n nativeType?: NativeTypeDeclaration\n ) => Sql;\n\n // Set membership\n in: (column: Sql, values: Sql) => Sql;\n notIn: (column: Sql, values: Sql) => Sql;\n\n // Null checks\n isNull: (expr: Sql) => Sql;\n isNotNull: (expr: Sql) => Sql;\n\n // Range\n between: (column: Sql, min: Sql, max: Sql) => Sql;\n notBetween: (column: Sql, min: Sql, max: Sql) => Sql;\n\n // Logical\n and: (...conditions: Sql[]) => Sql;\n or: (...conditions: Sql[]) => Sql;\n not: (condition: Sql) => Sql;\n\n // Subquery existence\n exists: (subquery: Sql) => Sql;\n notExists: (subquery: Sql) => Sql;\n };\n\n /**\n * EXPRESSIONS\n * Computed values and functions\n */\n expressions: {\n /** Portable searched CASE expression. */\n caseWhen: (\n branches: readonly { readonly when: Sql; readonly then: Sql }[],\n otherwise: Sql\n ) => Sql;\n\n // Arithmetic\n add: (left: Sql, right: Sql) => Sql;\n subtract: (left: Sql, right: Sql) => Sql;\n multiply: (left: Sql, right: Sql) => Sql;\n divide: (left: Sql, right: Sql) => Sql;\n /**\n * The integer quotient of two integer operands, truncated toward zero.\n *\n * The same fact {@link DatabaseAdapter.set.divide}'s `target.integer` flag\n * already carries, as an EXPRESSION rather than an assignment: naming the\n * value an integer column will hold after `{ divide }` needs the dialect's\n * own truncation, and `/` does not agree across dialects. SQLite and\n * PostgreSQL truncate natively once both operands are integers, while MySQL\n * `/` yields a DECIMAL quotient and needs `TRUNCATE(…, 0)`. Casting the\n * quotient afterwards is not a substitute: MySQL and PostgreSQL ROUND on\n * cast, only SQLite truncates.\n */\n integerDivide: (left: Sql, right: Sql) => Sql;\n\n // String operations\n concat: (...parts: Sql[]) => Sql;\n upper: (expr: Sql) => Sql;\n lower: (expr: Sql) => Sql;\n /**\n * Fold letter case the way this database does natively (its own `LOWER`),\n * for `mode: \"insensitive\"` equality, membership and ranges. The caller\n * compares the result under `caseSensitiveText`, so case is the only\n * difference it ignores. `expr` arrives raw, never wrapped in\n * `caseSensitiveText`, with the native type of the column it reads.\n */\n caseFold: (expr: Sql, nativeType?: NativeTypeDeclaration) => Sql;\n /** Force exact text comparison semantics independent of column/database collation. */\n caseSensitiveText: (\n expr: Sql,\n nativeType?: NativeTypeDeclaration,\n textOperation?: boolean\n ) => Sql;\n\n /** Cast a deferred value into one fixed-decimal field's exact domain. */\n decimalCast: (expr: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * Bind a DEFERRED identifier back into its column's physical type — the\n * INVERSE of the transport spelling a byte column travels in (lowercase\n * hex, `query-engine/raptor3/shared/identifier.ts`\n * `transportedIdentifier`).\n *\n * NO ENGINE CALLER since the Raptor 3 port: that engine has no deferred\n * identifier — a located key is a raw column sub-select, already physical,\n * and the batch scratch carries integers only. The member stays declared\n * and pinned (`tests/contracts/adapters/identifier-storage.core.test.ts`)\n * until its owner retires or re-adopts it; the provenance below is the\n * retired engine's.\n *\n * The sibling of {@link DatabaseAdapter.expressions.decimalCast}, and\n * needed for the same reason: a relation key whose value does not exist at\n * build time — a `Ref` into a located parent's captured column — cannot go\n * through `literals.id`, and the generic `text` cast names a type the\n * column does not have. `CAST($1 AS TEXT)` against a PostgreSQL `uuid`\n * column is the 42804 this exists to avoid.\n *\n * A deferred value has exactly ONE provenance — a step output, which is a\n * row the driver returned — so it arrives in the spelling that projection\n * published: LOWERCASE HEX for a `bytes` column, canonical text for a\n * `uuid` or text-stored one. A plain cast of that hex into the binary type\n * would bind the hex text's own bytes, so the binary arm decodes it\n * (`decode(…, 'hex')`, `UNHEX`, `unhex`). SQLite's `unhex()` arrived in\n * 3.41, above this adapter's 3.35 floor: a compact identifier on SQLite\n * needs 3.41, and so does a bytes list longer than `literals.list` keeps\n * parenthesized; nothing else here does.\n */\n idCast: (expr: Sql, representation: IdRepresentation) => Sql;\n\n // Utility\n coalesce: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n greatest: (...exprs: Sql[]) => Sql;\n /** Reserved — not called by the query engine yet. */\n least: (...exprs: Sql[]) => Sql;\n cast: (expr: Sql, type: CastType) => Sql;\n /**\n * Hex-encode a binary column for JSON embedding — JSON can't hold binary\n * (PG: encode(x, 'hex'), MySQL/SQLite: lower(hex(x))).\n * The result parser decodes hex back to Uint8Array.\n */\n blobToHex: (expr: Sql) => Sql;\n };\n\n /**\n * AGGREGATES\n * Aggregate functions\n */\n aggregates: {\n count: (expr?: Sql) => Sql;\n countDistinct: (expr: Sql) => Sql;\n sum: (expr: Sql) => Sql;\n /**\n * A double column's sum as two `SUM`s no row count can overflow: its\n * members of magnitude at least 1e-288 divided by 2^64, and the smaller\n * ones as they are. Dividing such a double by 2^64 is exact, so the first\n * part is the plain sum scaled exactly, and the reader's\n * `high * 2^64 + low` is that sum — `±Infinity` past the double range,\n * where PostgreSQL's own `SUM` raises and MySQL's answers 0 (engine-10).\n *\n * `having` compares `value` and a grouped `orderBy` sorts by `order`, so\n * a group is kept and placed by the sum the projection publishes.\n */\n numberSum: (expr: Sql) => {\n readonly parts: readonly [high: Sql, low: Sql];\n /** The joined sum as one comparable expression. */\n readonly value: Sql;\n /** Sort keys, most significant first, ordering by the joined sum. */\n readonly order: readonly Sql[];\n };\n /**\n * Stated only where an integer `SUM` is int64 and raises past it\n * (SQLite): an int64 column's sum as two `SUM`s no realistic row count\n * can overflow — each member's high 32 bits and the rest — read back\n * exactly as `high * 2^32 + low` (engine-10), compared and sorted as\n * `numberSum` states. PostgreSQL and MySQL already sum integers as exact\n * numerics.\n */\n integerSum?: DatabaseAdapter[\"aggregates\"][\"numberSum\"];\n avg: (expr: Sql) => Sql;\n min: (expr: Sql, boolean?: boolean) => Sql;\n max: (expr: Sql, boolean?: boolean) => Sql;\n /**\n * The average of an EXACT decimal column, in the column's own physical\n * domain and quantized to the field's scale with round-half-to-even.\n *\n * Separate from {@link DatabaseAdapter.aggregates.avg} because `AVG()` is a\n * different function on a decimal: SQLite computes it in a double, and\n * PostgreSQL/MySQL choose the result's scale themselves. This one is\n * derived from the exact `SUM` and `COUNT(column)` — so it is NULL for an\n * empty or all-null group — and rounds by the one shared rule rather than\n * by a provider default.\n */\n decimalAvg: (column: Sql, descriptor: DecimalDescriptor) => Sql;\n\n /**\n * The widened precision needed to cast this exact coefficient as a\n * `having _sum` operand, or `undefined` when the dialect cannot represent\n * that value exactly.\n *\n * `_sum` may exceed one row's precision, but its comparison domain is not\n * unbounded. PostgreSQL and MySQL admit by their exact decimal precision;\n * SQLite admits by signed-int64 VALUE, whose valid range contains some but\n * not all 19-digit coefficients. The adapter owns that provider fact so the\n * query engine never branches on a dialect or silently binds a saturated\n * value.\n */\n decimalSumOperandPrecision: (coefficient: string) => number | undefined;\n };\n\n /**\n * JSON\n * Database-specific JSON building and extraction\n */\n json: {\n /** Structural JSON equality: object key order is insignificant. */\n equals: (left: Sql, right: Sql) => Sql;\n /** Convert a SQL predicate into a JSON boolean value. */\n boolean: (condition: Sql) => Sql;\n /** Preserve a SQL expression as a JSON document when embedding it in JSON. */\n document: (expression: Sql) => Sql;\n /** Carry a finite number through JSON without losing binary precision. */\n number: (expression: Sql) => Sql;\n /** Build JSON object from key-value pairs */\n object: (pairs: [string, Sql][]) => Sql;\n /** Build JSON array from items */\n array: (items: Sql[]) => Sql;\n /** Empty JSON array literal: '[]'::json (PG), JSON_ARRAY() (MySQL), '[]' (SQLite) */\n emptyArray: () => Sql;\n /**\n * Aggregate rows into a JSON array. An empty aggregate is the empty array,\n * never SQL NULL, so no caller wraps it in its own COALESCE. `expr` is a\n * JSON value as built here (`object`, `array`): one read back through a\n * subquery column goes through `document` first, which SQLite needs to\n * keep it a JSON value rather than a quoted string.\n */\n agg: (expr: Sql) => Sql;\n /** Build JSON object from explicit column list (works on all databases) */\n objectFromColumns: (columns: [string, Sql][]) => Sql;\n /**\n * Extract the JSON value at a path (empty path = document root) in a\n * form comparable against `json.value` params. Integer segments address\n * array elements. Used by JSON path filters in the where-builder.\n */\n extract: (column: Sql, path: string[]) => Sql;\n /**\n * Extract the value at a path as text (strings unquoted; empty path =\n * document root). Used by JSON string_contains/starts_with/ends_with.\n */\n extractText: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as a double-precision number, or SQL NULL when the\n * path is absent or the JSON value there is NOT a JSON number. Every\n * dialect gates the cast behind its own JSON type test (PG jsonb_typeof,\n * MySQL JSON_TYPE, SQLite json_type) so a non-numeric value yields NULL\n * instead of a cast error. Used by JSON lt/lte/gt/gte with number\n * operands: NULL never satisfies a comparison, so mismatched types and\n * absent paths never match and never error.\n */\n numberAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * The value at `path` as unquoted text under a byte-ordered collation\n * (PG COLLATE \"C\", MySQL VARBINARY, SQLite COLLATE BINARY), or SQL NULL\n * when the path is absent or the JSON value there is NOT a JSON string.\n * The forced collation makes `<`/`>` code-point ordering on every\n * dialect instead of the database's default (locale) collation. Used by\n * JSON lt/lte/gt/gte with string operands.\n */\n stringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * `stringAtPath` in the database's own text type and collation, for\n * `mode: \"insensitive\"`: the byte-ordered pin stops a database folding\n * case (`LOWER`/`ILIKE` under PG `COLLATE \"C\"` fold `A`-`Z` only, and\n * MySQL's `LOWER` leaves a binary string as it is).\n */\n foldableStringAtPath: (column: Sql, path: string[]) => Sql;\n /**\n * JSON array containment: target is an array containing every element\n * of the candidate JSON array value (PG @>, MySQL JSON_CONTAINS,\n * SQLite json_each). Used by the array_contains filter.\n */\n contains: (target: Sql, value: Sql) => Sql;\n /**\n * Last element of a JSON array (PG -> -1, MySQL $[last],\n * SQLite $[#-1]). Used by the array_ends_with filter.\n */\n lastElement: (target: Sql) => Sql;\n /**\n * Parameterized JSON value usable in comparisons against a JSON column.\n * PG: plain param (jsonb), MySQL: CAST(? AS JSON) so equality compares\n * JSON documents instead of coercing to a JSON string scalar,\n * SQLite: canonical JSON text param.\n */\n value: (v: unknown) => Sql;\n };\n\n /**\n * ARRAYS\n * Array operations (PG: native arrays, MySQL/SQLite: JSON-based)\n */\n arrays: {\n /**\n * Create array literal. Reserved — not called by the query engine yet.\n */\n literal: (items: Sql[]) => Sql;\n /**\n * Parameterized value for a complete list in the dialect's storage\n * format: native array param (PG), CAST(? AS JSON) (MySQL), canonical\n * JSON text param (SQLite). Used for list writes and equals/not filters.\n */\n value: (values: unknown[], temporal?: \"date\" | \"datetime\") => Sql;\n /**\n * Parameterized value for a complete ENUM list.\n *\n * The one list whose element type no driver can serialize: a PostgreSQL\n * managed enum is created by the estate, so its array OID is in no driver's\n * serializer table and the native array parameter above reaches the server\n * as `ADMIN,USER` (22P02). PostgreSQL binds the array literal as ONE\n * untyped parameter and lets the column or operand it meets resolve the\n * type, so the enum's NAME stays with the migration driver that generated\n * it and never appears in runtime SQL. The JSON-backed dialects answer with\n * the same container every other list uses — there, an enum list has no\n * element type to spell at all.\n */\n enumValue: (values: unknown[]) => Sql;\n /**\n * The values a one-column `query` answers, as one array, empty where it\n * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this\n * way by {@link has} rather than by joining it: the array is computed once\n * per statement, where a joined set is read again for each row of a\n * correlated subquery. Absent where the dialect has no array value.\n */\n ofRows?: (query: Sql) => Sql;\n /** Check if array contains value */\n has: (column: Sql, value: Sql) => Sql;\n /** Check if array contains all values */\n hasEvery: (column: Sql, values: Sql) => Sql;\n /** Check if array contains any value */\n hasSome: (column: Sql, values: Sql) => Sql;\n /** Check if array is empty */\n isEmpty: (column: Sql) => Sql;\n /**\n * Project a numeric list without a provider/JSON carrier rounding members.\n *\n * Decimal, bigint and floating-point lists share this transport boundary.\n * On a native-array dialect the members are exact text, and\n * the whole-column TEXT cast every other decimal projection uses yields the\n * dialect's own array literal (`{1.20,-0.03}`) rather than an array of\n * members — while embedding the column in a JSON carrier uncast yields JSON\n * NUMBERS, which round past 2^53. Casting ELEMENT-WISE answers both: the\n * flat read gets an array of exact text and the carrier gets a JSON array of\n * strings. On a JSON-backed dialect the container is already an array of\n * coefficient strings and what this owns is that it arrives as TEXT rather\n * than as a driver-parsed document.\n *\n * One name, one meaning, three dialect spellings — the query engine asks for\n * a readable numeric list and never for a dialect cast.\n */\n exactNumericProjection: (column: Sql) => Sql;\n /** Get array length. Reserved — not called by the query engine yet. */\n length: (column: Sql) => Sql;\n /** Get element at index. Reserved — not called by the query engine yet. */\n get: (column: Sql, index: Sql) => Sql;\n /**\n * Append value to array. Reserved — not called by the query engine yet.\n */\n push: (column: Sql, value: Sql) => Sql;\n /** Set value at index. Reserved — not called by the query engine yet. */\n set: (column: Sql, index: Sql, value: Sql) => Sql;\n };\n\n /**\n * ORDER BY\n * Ordering helpers\n */\n orderBy: {\n asc: (column: Sql) => Sql;\n desc: (column: Sql) => Sql;\n /** Directed order placing NULLs first (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsFirst: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n /** Directed order placing NULLs last (native on PG, IS NULL sort-key emulation on MySQL/SQLite) */\n nullsLast: (column: Sql, direction: \"asc\" | \"desc\") => Sql;\n };\n\n /**\n * CLAUSES\n * SQL clause keywords\n */\n /**\n * LIMIT value meaning \"no limit\", for dialects that reject OFFSET without\n * LIMIT (MySQL: 18446744073709551615, SQLite: -1).\n * Omit when the dialect supports bare OFFSET (PostgreSQL).\n *\n * It is also the bound an ORDERED derived table states when its caller asked\n * for no window: MySQL merges an unlimited derived table into the query that\n * reads it and the merge takes the ORDER BY with it, so a page whose order a\n * reader consumes (the to-many include's aggregate) spells this value rather\n * than losing it. A dialect that keeps a derived order unbounded declares\n * none and emits nothing.\n */\n noLimitValue?: Sql;\n\n clauses: {\n select: (columns: Sql) => Sql;\n selectDistinct: (columns: Sql) => Sql;\n from: (table: Sql) => Sql;\n where: (condition: Sql) => Sql;\n orderBy: (orders: Sql) => Sql;\n limit: (count: Sql) => Sql;\n offset: (count: Sql) => Sql;\n groupBy: (columns: Sql) => Sql;\n having: (condition: Sql) => Sql;\n };\n\n /**\n * SET\n * UPDATE SET operations\n */\n set: {\n /** Simple assignment: \"col\" = value */\n assign: (column: Sql, value: Sql) => Sql;\n /** Increment: \"col\" = \"col\" + value */\n increment: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /** Decrement: \"col\" = \"col\" - value */\n decrement: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Multiply: \"col\" = \"col\" * value.\n * A decimal target rounds the product back to its scale (see\n * {@link ArithmeticTarget}); every other target multiplies natively.\n */\n multiply: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Divide: \"col\" = \"col\" / value.\n * `target.integer` tells the adapter the target column is integer-typed\n * so it can force integer division where the dialect would otherwise do\n * real division. SQLite binds the operand as REAL, while MySQL `/` returns\n * a decimal quotient even for integer columns; both adapters use the flag\n * to preserve truncation toward zero. PostgreSQL integer division already\n * has that behavior and ignores the flag. A decimal target instead rounds\n * the quotient to its scale.\n */\n divide: (column: Sql, by: Sql, target?: ArithmeticTarget) => Sql;\n /**\n * Array push: append the complete provider-encoded `values` container.\n * The query engine selects the scalar's list vocabulary once; the adapter\n * owns only how its dialect concatenates two containers.\n */\n push: (column: Sql, values: Sql) => Sql;\n /** Array unshift: prepend the complete provider-encoded container. */\n unshift: (column: Sql, values: Sql) => Sql;\n };\n\n /**\n * FILTERS\n * Relation filter wrappers for subqueries\n */\n filters: {\n /** EXISTS wrapper for \"some\" relation filter (to-many) */\n some: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"every\" - negated condition (to-many) */\n every: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"none\" (to-many) */\n none: (subquery: Sql) => Sql;\n /** EXISTS wrapper for \"is\" relation filter (to-one) */\n is: (subquery: Sql) => Sql;\n /** NOT EXISTS wrapper for \"isNot\" relation filter (to-one) */\n isNot: (subquery: Sql) => Sql;\n };\n\n /**\n * SUBQUERIES\n * Subquery wrappers\n */\n subqueries: {\n /** Scalar subquery: (SELECT ...) */\n scalar: (query: Sql) => Sql;\n /** Correlated subquery with alias */\n correlate: (query: Sql, alias: string) => Sql;\n /** Build EXISTS-style subquery: SELECT 1 FROM table WHERE condition */\n existsCheck: (from: Sql, where: Sql) => Sql;\n /**\n * `condition`, a conjunct of a `WHERE` (a NULL and a false refuse its\n * row alike), placed where its own depth is not added to the\n * expression that holds it: the identity, except where the transport\n * bounds expression depth and the dialect sums nested heights.\n */\n isolated: (condition: Sql) => Sql;\n };\n\n /**\n * CTE\n * Common Table Expressions\n */\n cte: {\n /**\n * Build WITH clause: WITH name AS (query), ... A member `inlined` is read\n * correlated to each outer row through its own columns: PostgreSQL would\n * materialize a member read twice and scan it, without an index, once\n * per row, so it is written `NOT MATERIALIZED` there. A member\n * `inlined: false` is computed once: SQLite would inline it at every\n * use, so it is written `MATERIALIZED` there. Without `inlined`, the\n * database decides. A `recursive` member's query is its two terms,\n * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.\n */\n with: (\n definitions: {\n name: string;\n query: Sql;\n inlined?: boolean;\n recursive?: boolean;\n }[]\n ) => Sql;\n /**\n * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).\n * The query engine calls only the `\"distinct\"` mode (`UNION`); the default\n * `\"all\"` mode is reserved — not called by the query engine yet.\n */\n recursive: (\n name: string,\n anchor: Sql,\n recursive: Sql,\n union?: \"all\" | \"distinct\"\n ) => Sql;\n };\n\n /**\n * MUTATIONS\n * Insert, Update, Delete operations\n */\n mutations: {\n /** How top-level bulk create realizes duplicate-only skipping. */\n skipDuplicatesStrategy: \"sql\" | \"recoverableUniqueError\";\n /** INSERT INTO table (cols) from literal rows or a SELECT source. */\n insert: (\n table: Sql,\n columns: string[],\n source: Sql[][] | { readonly select: Sql },\n prefix?: Sql\n ) => Sql;\n /** Insert one row using only database defaults. */\n insertDefault: (table: Sql) => Sql;\n /** UPDATE table SET ... WHERE ... */\n update: (table: Sql, sets: Sql, where?: Sql) => Sql;\n /**\n * UPDATE table SET ... from `source` (a derived table, aliased) joined\n * `on` the row written, WHERE ...: `UPDATE … FROM` (PostgreSQL, SQLite),\n * `UPDATE … JOIN` (MySQL).\n */\n updateFrom: (\n table: Sql,\n sets: Sql,\n source: Sql,\n on: Sql,\n where?: Sql\n ) => Sql;\n /** DELETE FROM table WHERE ... */\n delete: (table: Sql, where?: Sql) => Sql;\n /** RETURNING clause (PG/SQLite) or empty (MySQL) */\n returning: (columns: Sql) => Sql;\n /**\n * A `RETURNING` expression true where an `INSERT … ON CONFLICT DO UPDATE`\n * inserted its row rather than updated it (PostgreSQL: `xmax = 0`).\n * Absent where the statement cannot say: an upsert that must report its\n * arm then reads the row first.\n */\n upserted?: Sql;\n /**\n * ON CONFLICT / ON DUPLICATE KEY\n * @param target - Conflict target columns (e.g., \"id\")\n * @param action - Action to take (e.g., UPDATE SET ...)\n * @param targetWhere - Optional WHERE for partial unique index matching\n * PostgreSQL: ON CONFLICT (id) WHERE <targetWhere> DO UPDATE ...\n */\n onConflict: (target: Sql | null, action: Sql, targetWhere?: Sql) => Sql;\n /**\n * Build update action for ON CONFLICT (PG/SQLite: UPDATE SET ..., MySQL: just the SET part)\n * @param sets - SET clause assignments\n * @param setWhere - Optional WHERE for conditional updates\n * PostgreSQL: ... DO UPDATE SET x = y WHERE <setWhere>\n */\n onConflictUpdate: (sets: Sql, setWhere?: Sql) => Sql;\n /**\n * Skip duplicate key errors (for createMany with skipDuplicates: true)\n * PostgreSQL/SQLite: ON CONFLICT DO NOTHING (suffix)\n * MySQL: duplicate-key-only no-op update (suffix)\n *\n * UNTARGETED ON PURPOSE, and that is the whole distinction from\n * {@link DatabaseAdapter.mutations.onConflict}: `createMany({\n * skipDuplicates: true })` promises to skip a row that collides with ANY\n * unique constraint, so naming one would be the wrong answer. A JUNCTION\n * membership insert asks the opposite question — skip only an exact repeat\n * of this complete `(owner, target)` key, and let a target-side UNIQUE\n * (a singular polymorphic member's occupied slot) raise — so it goes\n * through the targeted door instead. See `junctionDuplicateSkip` in\n * `query-engine/builders/many-to-many-utils.ts`; do not route it back here.\n */\n skipDuplicates: (duplicateNoopColumn: string) => {\n prefix: Sql;\n suffix: Sql;\n };\n };\n\n /**\n * ASSERTIONS\n * Dialect-specific statements that abort a batch when a precondition fails.\n */\n assertions: {\n /** Abort unless the provided SELECT returns at least one row. */\n exists: (query: Sql) => Sql;\n /** Abort unless the provided SELECT returns no rows. */\n notExists: (query: Sql) => Sql;\n /**\n * A one-column SELECT answering 1 where `condition` holds (over `from`'s\n * row when given), aborting the statement it is part of otherwise, NULL\n * included: the guard a write carries for the row it produces, read as a\n * scalar inside that write.\n */\n holds: (condition: Sql, from?: Sql) => Sql;\n };\n\n capabilities: DatabaseAdapterCapabilities;\n\n /**\n * LAST INSERT ID\n * Returns SQL for getting the last auto-generated ID.\n * Used only where the provider exposes an exact statement-local identity.\n *\n * PostgreSQL: lastval() exists for legacy/direct SQL uses, but batchRefs does not\n * expose it because another generated column or trigger can change the session value\n * SQLite: last_insert_rowid() - returns last ROWID inserted\n * MySQL: LAST_INSERT_ID() - returns last AUTO_INCREMENT value\n */\n lastInsertId: () => Sql;\n\n /**\n * JOINS\n * Join operations\n */\n joins: {\n inner: (table: Sql, condition: Sql) => Sql;\n left: (table: Sql, condition: Sql) => Sql;\n right: (table: Sql, condition: Sql) => Sql;\n full: (table: Sql, condition: Sql) => Sql;\n cross: (table: Sql) => Sql;\n /**\n * LATERAL subquery join (PostgreSQL 9.3+, MySQL 8.0.14+)\n * Allows referencing columns from preceding tables in the subquery.\n * Used for efficient nested includes.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns JOIN LATERAL (subquery) AS alias ON true\n */\n lateral: (subquery: Sql, alias: string) => Sql;\n /**\n * LEFT JOIN LATERAL - same as lateral but with LEFT JOIN semantics\n * Returns NULL for the joined columns when subquery returns no rows.\n *\n * @param subquery - The lateral subquery (must be a complete SELECT)\n * @param alias - Alias for the lateral result\n * @returns LEFT JOIN LATERAL (subquery) AS alias ON true\n */\n lateralLeft: (subquery: Sql, alias: string) => Sql;\n };\n\n /**\n * SET OPERATIONS\n * UNION, INTERSECT, EXCEPT operations\n */\n setOperations: {\n /** UNION (removes duplicates) */\n union: (...queries: Sql[]) => Sql;\n /** UNION ALL (keeps duplicates). */\n unionAll: (...queries: Sql[]) => Sql;\n /** INTERSECT */\n intersect: (...queries: Sql[]) => Sql;\n /** EXCEPT / MINUS */\n except: (left: Sql, right: Sql) => Sql;\n /**\n * `rows` as ONE FROM item `alias` whose columns are `typed.columns`,\n * each typed as that column of the table `typed.from` reads under\n * `typed.alias`: the rows a judged write produces, read before it writes\n * them. `typed.head` is the empty read of those columns (`… WHERE\n * FALSE`); a row lists its values in `columns`' order and may refer to\n * the enclosing query. The form is the dialect's, because every one\n * spends a different limit on the row count first: one `UNION ALL\n * SELECT` arm per row (the default, MySQL: 65,535 arms measured) is a\n * compound term each, refused past `SQLITE_MAX_COMPOUND_SELECT` (500) on\n * SQLite, and one parser recursion each on PostgreSQL (`54001` at 8,000\n * rows), where a `VALUES` list is neither. The bind budget stays the\n * only bound on a chunk (ENG-3, review 2).\n */\n typedRows: (\n typed: {\n readonly head: Sql;\n readonly from: Sql;\n /** The table itself, unaliased: its row type names the columns' types. */\n readonly table: Sql;\n readonly alias: string;\n readonly columns: readonly string[];\n },\n rows: readonly (readonly Sql[])[],\n alias: string\n ) => Sql;\n };\n\n /**\n * VECTOR\n * Vector operations for similarity search (pgvector)\n *\n * Matches filter schema: { l2, cosine }\n * Drivers that don't support vector operations can override\n * this property with an object that throws FeatureNotSupportedError.\n *\n * Reserved — the query engine does not call these yet; vector filters are\n * rejected in the where-builder today.\n */\n vector: {\n /** Create a vector literal from number array: '[1,2,3]'::vector */\n literal: (values: number[]) => Sql;\n /** L2 (Euclidean) distance operator for ORDER BY: column <-> vector */\n l2: (column: Sql, vector: Sql) => Sql;\n /** Cosine distance operator for ORDER BY: column <=> vector */\n cosine: (column: Sql, vector: Sql) => Sql;\n };\n\n /**\n * Exact EPSG:4326 point SQL. Absence means this adapter has no physical\n * GeoPoint tier; optional members distinguish the full polygon/distance tier.\n */\n readonly geoPoint?: GeoPointSql;\n\n result: AdapterResultParser;\n}\n","/**\n * The ONE round-half-to-even rule, spelled in each dialect's exact integer\n * vocabulary.\n *\n * Multiply, divide and average are the only operations that can create digits\n * beyond a decimal field's scale, so they are the only ones that round — and\n * they round the same way everywhere, because a rounding mode that came from\n * the provider would make the same query answer differently per database.\n * Nothing here consults a provider default: quotient, remainder and parity are\n * exact integer facts, and the arms are composed from them.\n *\n * WHY A QUOTIENT RULE AND NOT A ROUNDING FUNCTION. `ROUND()` is half-up on\n * MySQL, half-even-ish on PostgreSQL numerics, and absent on SQLite; every one\n * of them would have to be trusted at the exact tie this rule exists to decide.\n * Quotient/remainder/parity are the same three integers on all three.\n *\n * NO PATH CASTS THROUGH REAL. Every operand below is an integer or an exact\n * decimal, and every operator applied to them is exact in its dialect.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\n\n/**\n * How one dialect spells EXACT truncated division and its remainder.\n *\n * `quotient(n, d)` truncates toward zero and `remainder(n, d)` carries the sign\n * of `n`, which is C semantics and what all three dialects already do — but\n * they spell it three ways, and one of the three (`n / d`) is only integer\n * division when both operands are integers. Each adapter declares its own pair\n * so this file never asks which database it is running against.\n */\nexport interface ExactIntegerArithmetic {\n /** `n / d` truncated toward zero. `d` is never zero unless `n` is NULL. */\n readonly quotient: (n: Sql, d: Sql) => Sql;\n /** `n - quotient(n, d) * d`; sign follows `n`. */\n readonly remainder: (n: Sql, d: Sql) => Sql;\n}\n\n/** `10^scale`, the factor between a logical value and its coefficient. */\nexport const scaleFactorSql = (scale: number): Sql =>\n sql.raw(`1${\"0\".repeat(scale)}`);\n\n/**\n * `10^-scale`: one unit in the last place of the field's domain, as an exact\n * decimal literal. Multiplying a coefficient by it is exact on PostgreSQL and\n * MySQL (scales add); DIVIDING by `10^scale` is not — MySQL computes a quotient\n * to `div_precision_increment` extra digits and rounds there, which would put a\n * provider default back in charge of the last digit.\n */\nexport const scaleUnitSql = (scale: number): Sql =>\n sql.raw(scale === 0 ? \"1\" : `0.${\"0\".repeat(scale - 1)}1`);\n\n/**\n * `n / d` rounded half to even, for `d > 0` and any sign of `n`.\n *\n * The three facts: `q` is the truncated quotient, `r` the remainder, and the\n * decision compares `|r|` against `d - |r|` — below is down, above is away from\n * zero, and EQUAL is the tie, resolved by `q`'s parity so the even neighbour\n * wins.\n *\n * WHY `|r| vs d - |r|` AND NOT `2|r| vs d`. They decide identically (`|r| >\n * d - |r|` is `2|r| > d` rearranged), but the doubled form is the only one that\n * can leave the dialect's exact domain: `|r| < d`, so `d - |r|` is bounded by\n * the divisor while `2|r|` needs one digit MORE than it. That extra digit is\n * the whole domain on the two dialects with a finite one — a 65-digit MySQL\n * divisor doubles to 66, and an int64 count doubles past int64 — so the\n * comparison is written in the form that never widens.\n *\n * The sign of the step reads `r`, not `n`: the step is taken only when `r <> 0`\n * (`|r| > d - |r| >= 0`, or `|r| = d - |r|` which needs `r <> 0` for a non-zero\n * `d`), and a non-zero remainder has exactly the sign of the dividend. Reading\n * `r` keeps one fewer copy of `n` in the emitted statement.\n *\n * `d` MUST be positive. A negative divisor would flip which neighbour is\n * \"away\", so the callers below normalize the sign onto the numerator instead.\n */\nexport const halfEvenQuotient = (\n integers: ExactIntegerArithmetic,\n n: Sql,\n d: Sql\n): Sql => {\n const q = integers.quotient(n, d);\n const r = integers.remainder(n, d);\n const parity = integers.remainder(q, sql.raw`2`);\n return sql`(${q} + (CASE WHEN ABS(${r}) > ${d} - ABS(${r}) OR (ABS(${r}) = ${d} - ABS(${r}) AND ${parity} <> 0) THEN (CASE WHEN ${r} < 0 THEN -1 ELSE 1 END) ELSE 0 END))`;\n};\n\n/**\n * `n` with the divisor's sign folded in, so the half-even rule always sees a\n * positive divisor. `n x sign(d)` and `|d|` name the same quotient as `n / d`.\n */\nexport const signedNumerator = (n: Sql, d: Sql): Sql =>\n sql`(CASE WHEN ${d} < 0 THEN -${n} ELSE ${n} END)`;\n\n/**\n * `column = halfEven(column x by)` where the column holds the LOGICAL decimal\n * in a dialect whose exact decimal domain is UNBOUNDED — PostgreSQL's\n * `NUMERIC`, which computes an expression at whatever width the value needs.\n *\n * The rule is stated on the COEFFICIENT, so the product is scaled up by `10^s`\n * — leaving a value whose integer part is the answer's coefficient and whose\n * fraction is what has to be rounded away — rounded to an integer against a\n * divisor of one, and scaled back by one exact multiplication.\n *\n * The widest intermediate is `column x by x 10^s`, which needs `2p + s` digits.\n * That is why MySQL does NOT use this form: its exact domain stops at 65\n * digits, and past it MySQL rounds an over-scaled product to 30 fractional\n * digits or answers ZERO without a warning. MySQL spells the same rule in its\n * own bounded, coefficient-space form (`mysql-adapter.ts`); this one is\n * PostgreSQL's, where no such ceiling exists.\n */\nexport const logicalDecimalMultiply = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const scaled = sql`(${column} * ${by} * ${scaleFactorSql(descriptor.scale)})`;\n const coefficient = halfEvenQuotient(integers, scaled, sql.raw`1`);\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * `column = halfEven(column / by)` where the column holds the LOGICAL decimal\n * in an unbounded exact domain ({@link logicalDecimalMultiply}'s PostgreSQL).\n *\n * The quotient is never computed by the dialect's `/`: the answer's coefficient\n * is `halfEven((column x 10^s) / by)`, which is a quotient of an exact integer\n * by an exact decimal, so remainder and parity decide the last digit instead of\n * `div_precision_increment` or a numeric division's chosen scale.\n *\n * `by` is non-zero: division by canonical zero is refused before I/O, where the\n * operand's canonical text is still in hand (`set-builder.ts`).\n */\nexport const logicalDecimalDivide = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n by: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n signedNumerator(sql`(${column} * ${scaleFactorSql(descriptor.scale)})`, by),\n sql`ABS(${by})`\n );\n return sql`${column} = ${coefficient} * ${scaleUnitSql(descriptor.scale)}`;\n};\n\n/**\n * The exact decimal average of a LOGICAL decimal column in an unbounded exact\n * domain ({@link logicalDecimalMultiply}'s PostgreSQL): the exact `SUM` over\n * `COUNT(column)`, quantized to the field's scale half to even.\n *\n * `COUNT(column)` counts NON-NULL values, which is what makes the empty and\n * all-null cases answer NULL rather than divide by zero: `SUM` of no non-null\n * rows is NULL, every operator below is null-strict, and the zero divisor is\n * therefore never reached with a non-null numerator.\n *\n * `AVG()` is deliberately unused. It is a double on SQLite, and on the other\n * two its result scale is the provider's choice rather than the field's.\n */\nexport const logicalDecimalAverage = (\n integers: ExactIntegerArithmetic,\n column: Sql,\n descriptor: DecimalDescriptor\n): Sql => {\n const coefficient = halfEvenQuotient(\n integers,\n sql`(SUM(${column}) * ${scaleFactorSql(descriptor.scale)})`,\n sql`COUNT(${column})`\n );\n return sql`(${coefficient} * ${scaleUnitSql(descriptor.scale)})`;\n};\n","import type { GeoPointSql } from \"@adapters/database-adapter\";\nimport { type Sql, sql } from \"@sql\";\nimport type {\n GeoBounds,\n GeoPolygon,\n} from \"@validation/primitives/geo-area-codec\";\n\ntype CoordinateOperations = {\n readonly and: (...conditions: Sql[]) => Sql;\n readonly or: (...conditions: Sql[]) => Sql;\n readonly eq: (left: Sql, right: Sql) => Sql;\n readonly gte: (left: Sql, right: Sql) => Sql;\n readonly lte: (left: Sql, right: Sql) => Sql;\n};\n\ntype IndexableBounds = (point: Sql, bounds: GeoBounds) => Sql | undefined;\n\n/**\n * Coordinate equality and inclusive bounds are one logical contract on every\n * provider. Only coordinate extraction differs, so this is their single owner.\n */\nexport function createGeoPointCoordinatePredicates(\n longitude: GeoPointSql[\"longitude\"],\n latitude: GeoPointSql[\"latitude\"],\n operators: CoordinateOperations,\n indexableBounds?: IndexableBounds\n): Pick<GeoPointSql, \"equals\" | \"withinBounds\"> {\n return {\n equals(point, expected) {\n const pointLongitude = longitude(point);\n let longitudeCondition = operators.eq(\n pointLongitude,\n sql`${expected.longitude}`\n );\n // -180 and +180 are one canonical meridian. Storage written outside the\n // ORM may still contain the physical -180 spelling that the value codec\n // presents as +180.\n if (expected.longitude === 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n return operators.and(\n longitudeCondition,\n operators.eq(latitude(point), sql`${expected.latitude}`)\n );\n },\n withinBounds(point, bounds) {\n const pointLongitude = longitude(point);\n const latitudeCondition = operators.and(\n operators.gte(latitude(point), sql`${bounds.south}`),\n operators.lte(latitude(point), sql`${bounds.north}`)\n );\n\n let exactCondition: Sql;\n if (bounds.west === -180 && bounds.east === 180) {\n exactCondition = latitudeCondition;\n } else {\n const westArm = operators.gte(pointLongitude, sql`${bounds.west}`);\n const eastArm = operators.lte(pointLongitude, sql`${bounds.east}`);\n let longitudeCondition =\n bounds.west > bounds.east\n ? operators.or(westArm, eastArm)\n : operators.and(westArm, eastArm);\n\n // GeoPoint canonicalizes -180 to +180. A normal interval whose western\n // boundary is -180 still contains that one physical meridian.\n if (bounds.west === -180 && bounds.east < 180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${180}`)\n );\n }\n // The inverse endpoint is the same canonical meridian: an external\n // writer may have stored -180 while the logical interval ends at +180.\n if (bounds.east === 180 && bounds.west > -180) {\n longitudeCondition = operators.or(\n longitudeCondition,\n operators.eq(pointLongitude, sql`${-180}`)\n );\n }\n exactCondition = operators.and(latitudeCondition, longitudeCondition);\n }\n const indexCondition = indexableBounds?.(point, bounds);\n return indexCondition\n ? operators.and(indexCondition, exactCondition)\n : exactCondition;\n },\n };\n}\n\n/**\n * GeoJSON rectangles safe to use only as conservative spatial-index probes.\n * Empty means the exact coordinate predicate is the only portable shape for\n * this boundary (world, pole, zero-area, or the canonical -180 meridian case).\n */\nexport function geoBoundsIndexPolygons(bounds: GeoBounds): readonly string[] {\n if (\n bounds.south === -90 ||\n bounds.north === 90 ||\n bounds.south === bounds.north ||\n bounds.west === bounds.east ||\n bounds.west > bounds.east ||\n bounds.west === -180 ||\n bounds.east === 180\n ) {\n return [];\n }\n return [\n boundsPolygonJson(bounds.west, bounds.east, bounds.south, bounds.north),\n ];\n}\n\nfunction boundsPolygonJson(\n west: number,\n east: number,\n south: number,\n north: number\n): string {\n // Geography edges are great-circle arcs. Include every axis meridian so\n // their geocentric bounding box encloses the full coordinate rectangle.\n const meridians = [\n west,\n ...[-90, 0, 90].filter((x) => west < x && x < east),\n east,\n ];\n const southEdge = meridians.map((longitude) => [longitude, south]);\n const northEdge = [...meridians]\n .reverse()\n .map((longitude) => [longitude, north]);\n return JSON.stringify({\n type: \"Polygon\",\n coordinates: [[...southEdge, ...northEdge, southEdge[0]]],\n });\n}\n\n/** One bound GeoJSON document; callers never contribute SQL or WKT text. */\nexport function geoPolygonJson(polygon: GeoPolygon): string {\n const rings: number[][][] = [closedRing(polygon.outer)];\n if (polygon.holes) {\n for (const hole of polygon.holes) rings.push(closedRing(hole));\n }\n return JSON.stringify({ type: \"Polygon\", coordinates: rings });\n}\n\nfunction closedRing(ring: GeoPolygon[\"outer\"]): number[][] {\n const result = new Array<number[]>(ring.length + 1);\n for (let index = 0; index < ring.length; index += 1) {\n const point = ring[index]!;\n result[index] = [point.longitude, point.latitude];\n }\n const first = ring[0]!;\n result[ring.length] = [first.longitude, first.latitude];\n return result;\n}\n","import { type Sql, sql } from \"@sql\";\nimport type { QueryParts } from \"../adapter-query-parts\";\n\ninterface SelectAssemblyOptions {\n forUpdate: \"append\" | \"omit\";\n /** LIMIT value meaning \"no limit\", for dialects that reject OFFSET without LIMIT */\n noLimitValue?: Sql;\n}\n\nexport const assembleSelectQuery = (\n selectClause: Sql,\n parts: QueryParts,\n options: SelectAssemblyOptions\n): Sql => {\n const fragments: Sql[] = [selectClause, sql`FROM ${parts.from}`];\n\n appendSelectParts(fragments, parts, options);\n\n if (options.forUpdate === \"append\" && parts.forUpdate) {\n fragments.push(sql.raw`FOR UPDATE`);\n }\n\n return sql.join(fragments, \" \");\n};\n\nconst appendSelectParts = (\n fragments: Sql[],\n parts: QueryParts,\n options: SelectAssemblyOptions\n): void => {\n appendFilterParts(fragments, parts);\n\n if (parts.orderBy) {\n fragments.push(sql`ORDER BY ${parts.orderBy}`);\n }\n\n appendLimitOffset(fragments, parts.limit, parts.offset, options.noLimitValue);\n};\n\n/** Joins, WHERE, GROUP BY and HAVING: shared by the plain and the emulated-DISTINCT select. */\nconst appendFilterParts = (fragments: Sql[], parts: QueryParts): void => {\n if (parts.joins && parts.joins.length > 0) {\n fragments.push(...parts.joins);\n }\n\n if (parts.where) {\n fragments.push(sql`WHERE ${parts.where}`);\n }\n\n if (parts.groupBy) {\n fragments.push(sql`GROUP BY ${parts.groupBy}`);\n }\n\n if (parts.having) {\n fragments.push(sql`HAVING ${parts.having}`);\n }\n};\n\nconst appendLimitOffset = (\n fragments: Sql[],\n limit: Sql | undefined,\n offset: Sql | undefined,\n noLimitValue: Sql | undefined\n): void => {\n if (limit) {\n fragments.push(sql`LIMIT ${limit}`);\n } else if (offset && noLimitValue) {\n // Dialects like MySQL/SQLite have no bare OFFSET; emit their \"no limit\" sentinel\n fragments.push(sql`LIMIT ${noLimitValue}`);\n }\n\n if (offset) {\n fragments.push(sql`OFFSET ${offset}`);\n }\n};\n\n/**\n * Simulate `SELECT DISTINCT ON` using one ROW_NUMBER() window.\n *\n * Used by MySQL/SQLite (no DISTINCT ON support) and by PostgreSQL when an\n * ORDER BY is present: DISTINCT ON would require the ORDER BY to lead with\n * the distinct columns, which changes result ordering. This emulation keeps\n * Prisma semantics — rows are ordered by the user's ORDER BY, then the first\n * row of each distinct group is kept, preserving that order.\n *\n * Generates:\n * SELECT col1, col2, ... FROM (\n * SELECT columns,\n * order_term_1 AS _ord0, ... -- only when ORDER BY present\n * ROW_NUMBER() OVER (PARTITION BY distinct_cols ORDER BY order_cols) AS _rn\n * FROM table\n * WHERE ...\n * ) AS _distinct_subquery\n * WHERE _rn = 1\n * ORDER BY _ord0, ...\n * LIMIT ... OFFSET ...\n *\n * The outer ORDER BY reads the projected `_ordN` terms because the user's\n * ORDER BY references inner table aliases (and relation-order joins) that\n * are out of scope outside the subquery. Ordering the kept rows by those\n * values (and not by a second window ranking every row) spares one sort.\n */\nexport const assembleDistinctOnEmulation = (\n parts: QueryParts,\n distinct: Sql,\n escapeIdentifier: (name: string) => Sql,\n noLimitValue?: Sql\n): Sql => {\n // ORDER BY for ROW_NUMBER() - use provided orderBy or default to distinct columns\n const rowNumberOrder = parts.distinctOrderBy ?? parts.orderBy ?? distinct;\n const order = parts.distinctOrder;\n\n const selectColumns: Sql[] = [parts.columns];\n if (order) {\n selectColumns.push(order.keys);\n }\n selectColumns.push(\n sql`ROW_NUMBER() OVER (PARTITION BY ${distinct} ORDER BY ${rowNumberOrder}) AS ${escapeIdentifier(\"_rn\")}`\n );\n\n // Inner query with ROW_NUMBER()\n const innerFragments: Sql[] = [\n sql`SELECT ${sql.join(selectColumns, \", \")}`,\n sql`FROM ${parts.from}`,\n ];\n\n appendFilterParts(innerFragments, parts);\n\n const innerQuery = sql.join(innerFragments, \" \");\n\n // Outer query that filters for first row of each partition. It names the\n // output columns so _rn/_ordN stay inside: every engine DISTINCT carrier\n // states its aliases.\n const aliasColumns = parts.distinctColumnAliases!.map(escapeIdentifier);\n const outerFragments: Sql[] = [\n sql`SELECT ${sql.join(aliasColumns, \", \")} FROM (${innerQuery}) AS ${escapeIdentifier(\"_distinct_subquery\")}`,\n sql`WHERE ${escapeIdentifier(\"_rn\")} = 1`,\n ];\n\n if (order) {\n outerFragments.push(sql`ORDER BY ${order.orderBy}`);\n }\n\n appendLimitOffset(outerFragments, parts.limit, parts.offset, noLimitValue);\n\n return sql.join(outerFragments, \" \");\n};\n"],"mappings":"gFA0BA,SAAgB,gCACd,EACsB,CACtB,IAAM,UAAY,EAAmB,KAAsC,CACzE,OACA,gBAAiB,CAAE,MAAO,EAAW,WAAY,EAAM,CACxD,EACD,MAAO,CACL,WAAa,GAAc,SAAS,EAAW,EAAe,EAAU,CAAC,CACzE,QAAS,EAAW,IAClB,SAAS,EAAW,GAAG,EAAU,GAAG,EAAQ,MAAM,CACrD,CAIH,MAAa,EAAmD,CAC9D,YAAa,EAAW,KAAa,CACnC,KAAM,GAAG,EAAU,OACnB,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,EACD,QAAS,EAAW,EAAS,KAAa,CACxC,KAAM,GAAG,EAAU,GAAG,EAAQ,MAC9B,gBAAiB,CACf,MAAO,EACP,QAAS,CAAC,GAAG,EAAQ,CACtB,CACF,EACF,CCjBD,SAAgB,mBACd,EACA,EACM,CACN,IAAI,EACJ,GAAI,EAAU,CACZ,IAAM,EAAgB,EAAS,cACzB,EAAW,EAAS,SAC1B,EAAY,OAAO,OAAoB,CACrC,MAAO,EAAS,MAChB,UAAW,EAAS,UACpB,SAAU,EAAS,SACnB,OAAQ,EAAS,OACjB,aAAc,EAAS,aACvB,GAAI,EAAgB,CAAE,gBAAe,CAAG,EAAE,CAC1C,GAAI,EAAW,CAAE,WAAU,CAAG,EAAE,CACjC,CAAC,CAEJ,OAAO,eAAe,EAAS,WAAY,CACzC,MAAO,EAC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,CAQD,OANI,GACF,EAAe,KAAK,CAAG,YAAY,EAAM,UAAU,CAGrD,kBAAkB,EAAgB,EAAM,MAAO,EAAM,OAAQ,EAAa,CAEnEA,EAAI,KAAK,EAAgB,IAAI"}
|
package/dist/soft-delete.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { At as DelegateOperationResult, E as OperationPayload, Ht as DefinitionControls, It as VibORMClient, Lt as VibORMConfig, M as ClientSchema, Pt as ExtensionState, Qt as AccumulatedExtensionState, Ut as NoControls, an as ResultConsumerContextOf, kt as ClientTypeState, nn as ExtensionContributionState, xn as PendingOperation } from "./index-BlBkgxtx.mjs";
|
|
2
2
|
import "./client.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/soft-delete/index.d.ts
|
|
@@ -13,19 +13,20 @@ interface SoftDeleteConfig {
|
|
|
13
13
|
type Schema = VibORMConfig["schema"];
|
|
14
14
|
type AnyModel = Schema[string];
|
|
15
15
|
type Names<Config extends SoftDeleteConfig> = keyof Config["models"] & string;
|
|
16
|
-
type
|
|
16
|
+
type ArgsOf<C$1 extends VibORMConfig, K$1, O extends "update" | "updateMany" | "delete" | "deleteMany"> = OperationPayload<O, ClientSchema<C$1>[K$1 & keyof ClientSchema<C$1>]>;
|
|
17
|
+
type RestoreArgs<C$1 extends VibORMConfig, K$1, O extends "update" | "updateMany"> = Omit<ArgsOf<C$1, K$1, O>, "data">;
|
|
18
|
+
type PurgeManyArgs<C$1 extends VibORMConfig, K$1> = NonNullable<ArgsOf<C$1, K$1, "deleteMany">>;
|
|
17
19
|
type NoExtra<A, R> = A & Record<Exclude<keyof A, keyof R>, never>;
|
|
18
|
-
type
|
|
19
|
-
restore<A extends RestoreArgs<C$1, K, "update">>(args: NoExtra<A, RestoreArgs<C$1, K, "update">>): PendingOperation<
|
|
20
|
-
restoreMany<A extends RestoreArgs<C$1, K, "updateMany">>(args: NoExtra<A, RestoreArgs<C$1, K, "updateMany">>): PendingOperation<
|
|
21
|
-
|
|
20
|
+
type Methods<C$1 extends VibORMConfig, K$1> = {
|
|
21
|
+
restore<Self, A extends RestoreArgs<C$1, K$1, "update">>(this: Self, args: NoExtra<A, RestoreArgs<C$1, K$1, "update">>): PendingOperation<DelegateOperationResult<Self, "update", A>>;
|
|
22
|
+
restoreMany<Self, A extends RestoreArgs<C$1, K$1, "updateMany">>(this: Self, args: NoExtra<A, RestoreArgs<C$1, K$1, "updateMany">>): PendingOperation<DelegateOperationResult<Self, "updateMany", A>>;
|
|
23
|
+
purge<Self, A extends ArgsOf<C$1, K$1, "delete">>(this: Self, args: NoExtra<A, ArgsOf<C$1, K$1, "delete">>): PendingOperation<DelegateOperationResult<Self, "delete", A>>;
|
|
24
|
+
purgeMany<Self, A extends PurgeManyArgs<C$1, K$1> = PurgeManyArgs<C$1, K$1>>(this: Self, args?: NoExtra<A, PurgeManyArgs<C$1, K$1>>): PendingOperation<DelegateOperationResult<Self, "deleteMany", A>>;
|
|
25
|
+
};
|
|
22
26
|
type Governed<Config extends SoftDeleteConfig> = VibORMConfig & {
|
|
23
27
|
readonly schema: Record<Names<Config>, AnyModel>;
|
|
24
28
|
};
|
|
25
|
-
|
|
26
|
-
readonly resultConsumer: undefined;
|
|
27
|
-
};
|
|
28
|
-
declare function rowsStep<Config extends SoftDeleteConfig, C$1 extends Governed<Config>, X$1 extends BeforeConsumers>(config: Config, base: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, {}, DefinitionControls<{
|
|
29
|
+
declare function apply<Config extends SoftDeleteConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, base: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> } extends infer T ? T extends { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> } ? T extends object ? { readonly [ModelName in keyof T]: T[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : {} : {} } : {} : never : never, DefinitionControls<{
|
|
29
30
|
readonly name: "viborm.softDelete";
|
|
30
31
|
readonly controls: {
|
|
31
32
|
readonly mode: {
|
|
@@ -35,7 +36,51 @@ declare function rowsStep<Config extends SoftDeleteConfig, C$1 extends Governed<
|
|
|
35
36
|
readonly rows: {
|
|
36
37
|
readonly control: "deleted";
|
|
37
38
|
readonly default: "without";
|
|
38
|
-
readonly models: { readonly [
|
|
39
|
+
readonly models: { readonly [K_1 in keyof Config["models"] & string & keyof C$1["schema"]]: {
|
|
40
|
+
without: {
|
|
41
|
+
root: {
|
|
42
|
+
[x: string]: null;
|
|
43
|
+
};
|
|
44
|
+
related: {
|
|
45
|
+
[x: string]: null;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
with: {};
|
|
49
|
+
only: {
|
|
50
|
+
root: {
|
|
51
|
+
[x: string]: {
|
|
52
|
+
not: null;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
related: {
|
|
56
|
+
[x: string]: null;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
} };
|
|
60
|
+
};
|
|
61
|
+
readonly deletion: {
|
|
62
|
+
readonly removeWhen: {
|
|
63
|
+
readonly mode: "hard";
|
|
64
|
+
};
|
|
65
|
+
readonly models: { readonly [K_2 in keyof Config["models"] & string & keyof C$1["schema"]]: {
|
|
66
|
+
at: string;
|
|
67
|
+
assign: {
|
|
68
|
+
[x: string]: string | number | bigint | null;
|
|
69
|
+
};
|
|
70
|
+
} };
|
|
71
|
+
};
|
|
72
|
+
readonly model: { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> };
|
|
73
|
+
}>, Extract<keyof Config["models"] & string & keyof C$1["schema"], string>, never, ResultConsumerContextOf<{
|
|
74
|
+
readonly name: "viborm.softDelete";
|
|
75
|
+
readonly controls: {
|
|
76
|
+
readonly mode: {
|
|
77
|
+
readonly oneOf: readonly ["soft", "hard"];
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
readonly rows: {
|
|
81
|
+
readonly control: "deleted";
|
|
82
|
+
readonly default: "without";
|
|
83
|
+
readonly models: { readonly [K_1 in keyof Config["models"] & string & keyof C$1["schema"]]: {
|
|
39
84
|
without: {
|
|
40
85
|
root: {
|
|
41
86
|
[x: string]: null;
|
|
@@ -58,6 +103,51 @@ declare function rowsStep<Config extends SoftDeleteConfig, C$1 extends Governed<
|
|
|
58
103
|
} };
|
|
59
104
|
};
|
|
60
105
|
readonly deletion: {
|
|
106
|
+
readonly removeWhen: {
|
|
107
|
+
readonly mode: "hard";
|
|
108
|
+
};
|
|
109
|
+
readonly models: { readonly [K_2 in keyof Config["models"] & string & keyof C$1["schema"]]: {
|
|
110
|
+
at: string;
|
|
111
|
+
assign: {
|
|
112
|
+
[x: string]: string | number | bigint | null;
|
|
113
|
+
};
|
|
114
|
+
} };
|
|
115
|
+
};
|
|
116
|
+
readonly model: { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> };
|
|
117
|
+
}>, Record<never, never>>>>;
|
|
118
|
+
declare function rowsStep<Config extends SoftDeleteConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, base: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, {}, DefinitionControls<{
|
|
119
|
+
name: "viborm.softDelete";
|
|
120
|
+
controls: {
|
|
121
|
+
readonly mode: {
|
|
122
|
+
readonly oneOf: readonly ["soft", "hard"];
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
rows: {
|
|
126
|
+
readonly control: "deleted";
|
|
127
|
+
readonly default: "without";
|
|
128
|
+
readonly models: { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: {
|
|
129
|
+
without: {
|
|
130
|
+
root: {
|
|
131
|
+
[x: string]: null;
|
|
132
|
+
};
|
|
133
|
+
related: {
|
|
134
|
+
[x: string]: null;
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
with: {};
|
|
138
|
+
only: {
|
|
139
|
+
root: {
|
|
140
|
+
[x: string]: {
|
|
141
|
+
not: null;
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
related: {
|
|
145
|
+
[x: string]: null;
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
} };
|
|
149
|
+
};
|
|
150
|
+
deletion: {
|
|
61
151
|
readonly removeWhen: {
|
|
62
152
|
readonly mode: "hard";
|
|
63
153
|
};
|
|
@@ -69,18 +159,30 @@ declare function rowsStep<Config extends SoftDeleteConfig, C$1 extends Governed<
|
|
|
69
159
|
} };
|
|
70
160
|
};
|
|
71
161
|
}>, Extract<keyof Config["models"] & string & keyof C$1["schema"], string>, never, "result-independent", Record<never, never>>>>;
|
|
72
|
-
declare function methodsStep<Config extends SoftDeleteConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, client: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{},
|
|
162
|
+
declare function methodsStep<Config extends SoftDeleteConfig, C$1 extends Governed<Config>, X$1 extends ExtensionState>(config: Config, client: VibORMClient<C$1, X$1>): VibORMClient<C$1, AccumulatedExtensionState<X$1, ExtensionContributionState<{}, { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> } extends infer T ? T extends { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> } ? 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<{
|
|
163
|
+
readonly name: "viborm.softDelete.restore";
|
|
164
|
+
readonly model: { readonly [K in keyof Config["models"] & string & keyof C$1["schema"]]: (delegate: never) => Methods<C$1, K> };
|
|
165
|
+
}>, Record<never, never>>>>;
|
|
73
166
|
type Receiver<Config extends SoftDeleteConfig> = ClientTypeState<VibORMConfig, ExtensionState> & {
|
|
74
167
|
readonly $schema: Record<Names<Config>, AnyModel>;
|
|
75
168
|
readonly $extends: (...args: never[]) => unknown;
|
|
76
169
|
};
|
|
77
|
-
type
|
|
170
|
+
type BeforeConsumers<X$1 extends ExtensionState, Client> = [X$1["resultConsumer"]] extends [undefined] ? Client : never;
|
|
171
|
+
type Applied<Config extends SoftDeleteConfig, Base> = Base extends ClientTypeState<infer C extends Governed<Config>, infer X extends ExtensionState> ? Base extends VibORMClient<C, X> ? BeforeConsumers<X, ReturnType<typeof apply<Config, C, X>>> : never : never;
|
|
172
|
+
type Rowed<Config extends SoftDeleteConfig, Base> = Base extends ClientTypeState<infer C extends Governed<Config>, infer X extends ExtensionState> ? Base extends VibORMClient<C, X> ? BeforeConsumers<X, ReturnType<typeof rowsStep<Config, C, X>>> : never : never;
|
|
78
173
|
type Restorable<Config extends SoftDeleteConfig, 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;
|
|
79
174
|
type SoftDeleteExtension<Config extends SoftDeleteConfig> = {
|
|
80
|
-
<Base extends Receiver<Config>>(base: Base): NoInfer<
|
|
175
|
+
<Base extends Receiver<Config>>(base: Base): NoInfer<Applied<Config, Base>>;
|
|
176
|
+
/** The controls, rows and deletion alone (chains written before 1.8). */
|
|
81
177
|
readonly rows: <Base extends Receiver<Config>>(base: Base) => Rowed<Config, Base>;
|
|
178
|
+
/** The methods alone (chains written before 1.8). */
|
|
82
179
|
readonly methods: <Base extends Receiver<Config>>(client: Base) => Restorable<Config, Base>;
|
|
83
180
|
};
|
|
181
|
+
/**
|
|
182
|
+
* Keep deleted rows as tombstones: `client.$extends(softDelete({ models: {
|
|
183
|
+
* post: { deletedAt: "deletedAt" } } }))`. One step, applied in any order
|
|
184
|
+
* with the other extensions.
|
|
185
|
+
*/
|
|
84
186
|
declare function softDelete<const Config extends SoftDeleteConfig>(config: Config): SoftDeleteExtension<Config>;
|
|
85
187
|
//#endregion
|
|
86
188
|
export { SoftDeleteConfig, SoftDeleteModel, softDelete };
|
package/dist/soft-delete.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./query-CTna5P9o.mjs";const n=`viborm.softDelete`;function perModel(e,t,n){return Object.fromEntries(Object.entries(e.models).map(([e,n])=>[e,t(n)]))}function admitMarkers(e,r){for(let[i,{deletedAt:a}]of Object.entries(r.models)){let r=Object.hasOwn(e,i)?e[i][`~`].state.scalars:void 0;if(!(r&&Object.hasOwn(r,a)))continue;let o=r[a][`~`].state;if(o.type!==`datetime`||o.array||!o.nullable)throw new t(`softDelete: ${i}.${a} must be a nullable DateTime field (s.dateTime().nullable()): a live row holds null there.`,{meta:{extension:n}})}}function definitionOf(e,t){return{name:n,controls:{mode:{oneOf:[`soft`,`hard`]}},rows:{control:`deleted`,default:`without`,models:perModel(e,({deletedAt:e})=>({without:{root:{[e]:null},related:{[e]:null}},with:{},only:{root:{[e]:{not:null}},related:{[e]:null}}}),t)},deletion:{removeWhen:{mode:`hard`},models:perModel(e,({deletedAt:t,deletedBy:n})=>({at:t,assign:n?{[n]:e.actor??null}:{}}),t)},model:perModel(e,({deletedAt:e,deletedBy:t})=>n=>{let r={[e]:null,...t?{[t]:null}:{}},{update:i,updateMany:a,delete:o,deleteMany:s}=n,c={deleted:`only`,mode:`hard`};return{restore:e=>i({...e,data:r,deleted:`only`}),restoreMany:e=>a({...e,data:r,deleted:`only`}),purge:e=>o({...e,...c}),purgeMany:(e={})=>s({...e,...c})}},t)}}function apply(e,t){return admitMarkers(t.$schema,e),t.$extends(definitionOf(e,t.$schema))}function rowsStep(e,t){let{model:n,...r}=definitionOf(e,t.$schema);return admitMarkers(t.$schema,e),t.$extends(r)}function methodsStep(e,t){let{model:r}=definitionOf(e,t.$schema);return t.$extends({name:`${n}.restore`,model:r})}function softDelete(e){function extend(t){return apply(e,t)}function rows(t){return rowsStep(e,t)}function methods(t){return methodsStep(e,t)}return Object.assign(extend,{rows,methods})}export{softDelete};
|
|
2
2
|
//# sourceMappingURL=soft-delete.mjs.map
|
package/dist/soft-delete.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"soft-delete.mjs","names":[],"sources":["../src/soft-delete/index.ts"],"sourcesContent":["// viborm/soft-delete: the entire extension.\n\nimport type { OperationPayload } from \"../client/exports\"; // public today\nimport type {\n ClientSchema,\n ClientTypeState,\n ExtendedOperationResult,\n ExtensionState,\n PendingOperation,\n VibORMClient,\n VibORMConfig,\n} from \"../index\";\n\nexport interface SoftDeleteModel {\n readonly deletedAt: string; // a DateTime field of this model\n readonly deletedBy?: string; // optional scalar field for the actor\n}\nexport interface SoftDeleteConfig {\n readonly models: Readonly<Record<string, SoftDeleteModel>>;\n readonly actor?: string | number | bigint; // bound per derived client\n}\ntype Schema = VibORMConfig[\"schema\"];\ntype AnyModel = Schema[string];\ntype Names<Config extends SoftDeleteConfig> = keyof Config[\"models\"] & string;\n\n// One value per configured model, keys kept: step B types `db.post.restore`\n// from them. The cast is TypeScript's own limit: Object.fromEntries forgets keys.\nfunction perModel<\n Config extends SoftDeleteConfig,\n T,\n S extends Schema = Schema,\n>(config: Config, build: (m: SoftDeleteModel) => T, _schema?: S) {\n return Object.fromEntries(\n Object.entries(config.models).map(([k, m]) => [k, build(m)])\n ) as { readonly [K in Names<Config> & keyof S]: T };\n}\n\n// restore takes the model's own update arguments, minus `data`; other keys are flagged.\ntype RestoreArgs<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\",\n> = Omit<\n OperationPayload<O, ClientSchema<C>[K & keyof ClientSchema<C>]>,\n \"data\"\n>;\ntype NoExtra<A, R> = A & Record<Exclude<keyof A, keyof R>, never>; // flags data and typos\ntype RestoreModels<\n M,\n C extends VibORMConfig,\n Config extends SoftDeleteConfig,\n> = {\n // The delegate of a client generic over its state stays deferred: untyped.\n readonly [K in Names<Config>]: (delegate: never) => {\n restore<A extends RestoreArgs<C, K, \"update\">>(\n args: NoExtra<A, RestoreArgs<C, K, \"update\">>\n ): PendingOperation<ExtendedOperationResult<M, K, \"update\", A>>;\n restoreMany<A extends RestoreArgs<C, K, \"updateMany\">>(\n args: NoExtra<A, RestoreArgs<C, K, \"updateMany\">>\n ): PendingOperation<ExtendedOperationResult<M, K, \"updateMany\", A>>;\n };\n};\n\ntype Governed<Config extends SoftDeleteConfig> = VibORMConfig & {\n readonly schema: Record<Names<Config>, AnyModel>;\n};\n// A rows step goes before every result-consuming step.\ntype BeforeConsumers = ExtensionState & { readonly resultConsumer: undefined };\n\n// Step A: controls, rows and deletion, checked against base's schema.\nfunction rowsStep<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n X extends BeforeConsumers,\n>(config: Config, base: VibORMClient<C, X>) {\n return base.$extends({\n name: \"viborm.softDelete\",\n controls: { mode: { oneOf: [\"soft\", \"hard\"] } }, // deletion places it on managed deletes\n rows: {\n control: \"deleted\", // the call argument that picks a mode\n default: \"without\",\n models: perModel(\n config,\n ({ deletedAt }) => ({\n without: {\n root: { [deletedAt]: null },\n related: { [deletedAt]: null },\n },\n with: {},\n only: {\n root: { [deletedAt]: { not: null } },\n related: { [deletedAt]: null },\n },\n }),\n base.$schema\n ),\n },\n deletion: {\n removeWhen: { mode: \"hard\" }, // this call deletes physically\n models: perModel(\n config,\n ({ deletedAt, deletedBy }) => ({\n at: deletedAt, // receives the call's one timestamp\n assign: deletedBy ? { [deletedBy]: config.actor ?? null } : {},\n }),\n base.$schema\n ),\n },\n });\n}\n\n// Step B: restore methods, typed against the client they are given, which\n// carries step A.\nfunction methodsStep<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n X extends ExtensionState,\n>(config: Config, client: VibORMClient<C, X>) {\n const model: RestoreModels<VibORMClient<C, X>, C, Config> = perModel(\n config,\n ({ deletedAt, deletedBy }) =>\n (delegate: { update: unknown; updateMany: unknown }) => {\n const data = {\n [deletedAt]: null,\n ...(deletedBy ? { [deletedBy]: null } : {}),\n };\n const update = delegate.update as (args: object) => never; // one cast\n const updateMany = delegate.updateMany as (args: object) => never; // one cast\n return {\n restore: (args: object) => update({ ...args, data, deleted: \"only\" }),\n restoreMany: (args: object) =>\n updateMany({ ...args, data, deleted: \"only\" }),\n };\n }\n );\n return client.$extends({ name: \"viborm.softDelete.restore\", model });\n}\n\n// A step takes its receiver whole and reads its C and X once from\n// ClientTypeState, so `$extends(step)` never infers them against a generic\n// client. The result names the step's own return type: declarations reference\n// one instantiation instead of inlining its definition per use (each inline\n// copy a distinct type, compared member by member: TS2589 from 25 models).\ntype Receiver<Config extends SoftDeleteConfig> = ClientTypeState<\n VibORMConfig,\n ExtensionState\n> & {\n readonly $schema: Record<Names<Config>, AnyModel>;\n readonly $extends: (...args: never[]) => unknown;\n};\ntype Rowed<\n Config extends SoftDeleteConfig,\n Base,\n> = Base extends ClientTypeState<\n infer C extends Governed<Config>,\n infer X extends BeforeConsumers\n>\n ? Base extends VibORMClient<C, X>\n ? ReturnType<typeof rowsStep<Config, C, X>>\n : never\n : never;\ntype Restorable<\n Config extends SoftDeleteConfig,\n Base,\n> = Base extends ClientTypeState<\n infer C extends Governed<Config>,\n infer X extends ExtensionState\n>\n ? Base extends VibORMClient<C, X>\n ? ReturnType<typeof methodsStep<Config, C, X>>\n : never\n : never;\n// The whole factory's NoInfer keeps `$extends(softDelete(config))` from\n// inferring between two client types (which measures the client alias's\n// variance, ~650k instantiations once per program). The steps go without: a\n// step written over `VibORMClient<C, X>` infers C and X from their result.\ntype SoftDeleteExtension<Config extends SoftDeleteConfig> = {\n <Base extends Receiver<Config>>(\n base: Base\n ): NoInfer<Restorable<Config, Rowed<Config, Base>>>;\n readonly rows: <Base extends Receiver<Config>>(\n base: Base\n ) => Rowed<Config, Base>;\n readonly methods: <Base extends Receiver<Config>>(\n client: Base\n ) => Restorable<Config, Base>;\n};\n\n// Every `rows` step of a chain goes before every method step (a method typed\n// against a client whose rows a later step widens would lie), so the entry\n// is both steps, `softDelete(config)(base)`, and each alone: `rows` and\n// `methods`, to apply around another entry's steps.\nexport function softDelete<const Config extends SoftDeleteConfig>(\n config: Config\n): SoftDeleteExtension<Config> {\n function rows<Base extends Receiver<Config>>(base: Base): Rowed<Config, Base>;\n function rows<C extends Governed<Config>, X extends BeforeConsumers>(\n base: VibORMClient<C, X>\n ) {\n return rowsStep(config, base);\n }\n function methods<Base extends Receiver<Config>>(\n client: Base\n ): Restorable<Config, Base>;\n function methods<C extends Governed<Config>, X extends ExtensionState>(\n client: VibORMClient<C, X>\n ) {\n return methodsStep(config, client);\n }\n function extend<Base extends Receiver<Config>>(\n base: Base\n ): NoInfer<Restorable<Config, Rowed<Config, Base>>>;\n function extend<C extends Governed<Config>, X extends BeforeConsumers>(\n base: VibORMClient<C, X>\n ) {\n return methodsStep(config, rowsStep(config, base));\n }\n return Object.assign(extend, { rows, methods });\n}\n"],"mappings":"AA2BA,SAAS,EAIP,EAAgB,EAAkC,EAAa,CAC/D,OAAO,OAAO,YACZ,OAAO,QAAQ,EAAO,OAAO,CAAC,KAAK,CAAC,EAAG,KAAO,CAAC,EAAG,EAAM,EAAE,CAAC,CAAC,CAC7D,CAoCH,SAAS,EAIP,EAAgB,EAA0B,CAC1C,OAAO,EAAK,SAAS,CACnB,KAAM,oBACN,SAAU,CAAE,KAAM,CAAE,MAAO,CAAC,OAAQ,OAAO,CAAE,CAAE,CAC/C,KAAM,CACJ,QAAS,UACT,QAAS,UACT,OAAQ,EACN,GACC,CAAE,gBAAiB,CAClB,QAAS,CACP,KAAM,EAAG,GAAY,KAAM,CAC3B,QAAS,EAAG,GAAY,KAAM,CAC/B,CACD,KAAM,EAAE,CACR,KAAM,CACJ,KAAM,EAAG,GAAY,CAAE,IAAK,KAAM,CAAE,CACpC,QAAS,EAAG,GAAY,KAAM,CAC/B,CACF,EACD,EAAK,QACN,CACF,CACD,SAAU,CACR,WAAY,CAAE,KAAM,OAAQ,CAC5B,OAAQ,EACN,GACC,CAAE,YAAW,gBAAiB,CAC7B,GAAI,EACJ,OAAQ,EAAY,EAAG,GAAY,EAAO,OAAS,KAAM,CAAG,EAAE,CAC/D,EACD,EAAK,QACN,CACF,CACF,CAAC,CAKJ,SAAS,EAIP,EAAgB,EAA4B,CAC5C,IAAM,EAAsD,EAC1D,GACC,CAAE,YAAW,eACX,GAAuD,CACtD,IAAM,EAAO,EACV,GAAY,KACb,GAAI,EAAY,EAAG,GAAY,KAAM,CAAG,EAAE,CAC3C,CACK,EAAS,EAAS,OAClB,EAAa,EAAS,WAC5B,MAAO,CACL,QAAU,GAAiB,EAAO,CAAE,GAAG,EAAM,OAAM,QAAS,OAAQ,CAAC,CACrE,YAAc,GACZ,EAAW,CAAE,GAAG,EAAM,OAAM,QAAS,OAAQ,CAAC,CACjD,EAEN,CACD,OAAO,EAAO,SAAS,CAAE,KAAM,4BAA6B,QAAO,CAAC,CAyDtE,SAAgB,EACd,EAC6B,CAE7B,SAAS,EACP,EACA,CACA,OAAO,EAAS,EAAQ,EAAK,CAK/B,SAAS,EACP,EACA,CACA,OAAO,EAAY,EAAQ,EAAO,CAKpC,SAAS,EACP,EACA,CACA,OAAO,EAAY,EAAQ,EAAS,EAAQ,EAAK,CAAC,CAEpD,OAAO,OAAO,OAAO,EAAQ,CAAE,OAAM,UAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"soft-delete.mjs","names":[],"sources":["../src/soft-delete/index.ts"],"sourcesContent":["// viborm/soft-delete: the entire extension.\n\nimport type { OperationPayload } from \"../client/exports\"; // public today\nimport { ClientInitializationError } from \"../errors\"; // viborm's own class\nimport type {\n ClientSchema,\n ClientTypeState,\n DelegateOperationResult,\n ExtensionState,\n PendingOperation,\n VibORMClient,\n VibORMConfig,\n} from \"../index\";\n\nexport interface SoftDeleteModel {\n readonly deletedAt: string; // a nullable DateTime field of this model\n readonly deletedBy?: string; // optional scalar field for the actor\n}\nexport interface SoftDeleteConfig {\n readonly models: Readonly<Record<string, SoftDeleteModel>>;\n readonly actor?: string | number | bigint; // bound per derived client\n}\ntype Schema = VibORMConfig[\"schema\"];\ntype AnyModel = Schema[string];\ntype Names<Config extends SoftDeleteConfig> = keyof Config[\"models\"] & string;\n\nconst NAME = \"viborm.softDelete\";\n\n// One value per configured model, keys kept: the methods are typed from\n// them. The cast is TypeScript's own limit: Object.fromEntries forgets keys.\nfunction perModel<\n Config extends SoftDeleteConfig,\n T,\n S extends Schema = Schema,\n>(config: Config, build: (m: SoftDeleteModel) => T, _schema?: S) {\n return Object.fromEntries(\n Object.entries(config.models).map(([k, m]) => [k, build(m)])\n ) as { readonly [K in Names<Config> & keyof S]: T };\n}\n\n// restore and purge take the model's own update and delete arguments\n// (restore minus `data`); other keys are flagged.\ntype ArgsOf<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\" | \"delete\" | \"deleteMany\",\n> = OperationPayload<O, ClientSchema<C>[K & keyof ClientSchema<C>]>;\ntype RestoreArgs<\n C extends VibORMConfig,\n K,\n O extends \"update\" | \"updateMany\",\n> = Omit<ArgsOf<C, K, O>, \"data\">;\ntype PurgeManyArgs<C extends VibORMConfig, K> = NonNullable<\n ArgsOf<C, K, \"deleteMany\">\n>;\ntype NoExtra<A, R> = A & Record<Exclude<keyof A, keyof R>, never>; // flags data and typos\n\n// Each result is typed from the delegate the method is called on (`Self`),\n// so it follows every extension applied after this one: a later `rows`\n// step types a to-one relation `| null`, a later `defaultOmit` drops a\n// field. Called off its delegate (destructured), its result is `unknown`:\n// using it is a type error, not a silent `never`. A type alias, not an interface: a method record.\ntype Methods<C extends VibORMConfig, K> = {\n restore<Self, A extends RestoreArgs<C, K, \"update\">>(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"update\">>\n ): PendingOperation<DelegateOperationResult<Self, \"update\", A>>;\n restoreMany<Self, A extends RestoreArgs<C, K, \"updateMany\">>(\n this: Self,\n args: NoExtra<A, RestoreArgs<C, K, \"updateMany\">>\n ): PendingOperation<DelegateOperationResult<Self, \"updateMany\", A>>;\n purge<Self, A extends ArgsOf<C, K, \"delete\">>(\n this: Self,\n args: NoExtra<A, ArgsOf<C, K, \"delete\">>\n ): PendingOperation<DelegateOperationResult<Self, \"delete\", A>>;\n purgeMany<Self, A extends PurgeManyArgs<C, K> = PurgeManyArgs<C, K>>(\n this: Self,\n args?: NoExtra<A, PurgeManyArgs<C, K>>\n ): PendingOperation<DelegateOperationResult<Self, \"deleteMany\", A>>;\n};\n\ntype Governed<Config extends SoftDeleteConfig> = VibORMConfig & {\n readonly schema: Record<Names<Config>, AnyModel>;\n};\n\n/**\n * Refuse a marker that is not a nullable, single DateTime field, before the\n * definition is applied (its rows predicates would refuse a required field\n * less clearly; a string field would fail at the first delete). A model or\n * field the schema lacks is left to core, which names it.\n */\nfunction admitMarkers(schema: Schema, config: SoftDeleteConfig): void {\n for (const [name, { deletedAt }] of Object.entries(config.models)) {\n const scalars = Object.hasOwn(schema, name)\n ? schema[name]![\"~\"].state.scalars\n : undefined;\n if (!(scalars && Object.hasOwn(scalars, deletedAt))) continue;\n const state = scalars[deletedAt]![\"~\"].state;\n if (state.type !== \"datetime\" || state.array || !state.nullable)\n throw new ClientInitializationError(\n `softDelete: ${name}.${deletedAt} must be a nullable DateTime field (s.dateTime().nullable()): a live row holds null there.`,\n { meta: { extension: NAME } }\n );\n }\n}\n\n// One definition: the `mode` control, the rows each `deleted` value\n// selects, what a delete writes, and the methods, checked against base's\n// schema. A factory takes its delegate as `never` (it reads nothing typed at\n// this step), so later steps may add `rows` or `defaultOmit` freely.\nfunction definitionOf<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n>(config: Config, schema: ClientSchema<C>) {\n return {\n name: NAME,\n controls: { mode: { oneOf: [\"soft\", \"hard\"] } }, // deletion places it on managed deletes\n rows: {\n control: \"deleted\", // the call argument that picks a mode\n default: \"without\",\n models: perModel(\n config,\n ({ deletedAt }) => ({\n without: {\n root: { [deletedAt]: null },\n related: { [deletedAt]: null },\n },\n with: {},\n only: {\n root: { [deletedAt]: { not: null } },\n related: { [deletedAt]: null },\n },\n }),\n schema\n ),\n },\n deletion: {\n removeWhen: { mode: \"hard\" }, // this call deletes physically\n models: perModel(\n config,\n ({ deletedAt, deletedBy }) => ({\n at: deletedAt, // receives the call's one timestamp\n assign: deletedBy ? { [deletedBy]: config.actor ?? null } : {},\n }),\n schema\n ),\n },\n model: perModel(\n config,\n ({ deletedAt, deletedBy }) =>\n (delegate: never) => {\n const data = {\n [deletedAt]: null,\n ...(deletedBy ? { [deletedBy]: null } : {}),\n };\n const {\n update,\n updateMany,\n delete: remove,\n deleteMany,\n } = delegate as Record<string, (args: object) => never>; // one cast\n // Tombstones only: `deleted: \"only\"` overrides a caller's value.\n const tombstones = { deleted: \"only\", mode: \"hard\" };\n return {\n restore: (args: object) =>\n update!({ ...args, data, deleted: \"only\" }),\n restoreMany: (args: object) =>\n updateMany!({ ...args, data, deleted: \"only\" }),\n purge: (args: object) => remove!({ ...args, ...tombstones }),\n purgeMany: (args: object = {}) =>\n deleteMany!({ ...args, ...tombstones }),\n };\n },\n schema\n ) as unknown as {\n readonly [K in Names<Config> & keyof ClientSchema<C>]: (\n delegate: never\n ) => Methods<C, K>;\n },\n } as const; // the literals `$extends` reads: names, modes, values\n}\n\nfunction apply<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n X extends ExtensionState,\n>(config: Config, base: VibORMClient<C, X>) {\n admitMarkers(base.$schema, config);\n return base.$extends(definitionOf<Config, C>(config, base.$schema));\n}\n\n// The two steps a chain written before 1.8 applies around another entry's\n// (`rows` then `methods`): the definition without its methods, and the\n// methods alone, under the name they had.\nfunction rowsStep<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n X extends ExtensionState,\n>(config: Config, base: VibORMClient<C, X>) {\n const { model: _methods, ...rows } = definitionOf<Config, C>(\n config,\n base.$schema\n );\n admitMarkers(base.$schema, config);\n return base.$extends(rows);\n}\nfunction methodsStep<\n Config extends SoftDeleteConfig,\n C extends Governed<Config>,\n X extends ExtensionState,\n>(config: Config, client: VibORMClient<C, X>) {\n const { model } = definitionOf<Config, C>(config, client.$schema);\n return client.$extends({ name: `${NAME}.restore`, model });\n}\n\n// A step takes its receiver whole and reads its C and X once from\n// ClientTypeState, so `$extends(softDelete(config))` never infers them\n// against a generic client. The result names the step's own return type:\n// declarations reference one instantiation instead of inlining its\n// definition per use (each inline copy a distinct type, compared member by\n// member: TS2589 from 25 models).\ntype Receiver<Config extends SoftDeleteConfig> = ClientTypeState<\n VibORMConfig,\n ExtensionState\n> & {\n readonly $schema: Record<Names<Config>, AnyModel>;\n readonly $extends: (...args: never[]) => unknown;\n};\n// A step with `rows` follows no result consumer: no factory typed against\n// the client it extends (TypeScript's order rule; the official extensions'\n// factories read nothing typed, so they never are one).\ntype BeforeConsumers<X extends ExtensionState, Client> = [\n X[\"resultConsumer\"],\n] extends [undefined]\n ? Client\n : never;\ntype Applied<\n Config extends SoftDeleteConfig,\n Base,\n> = Base extends ClientTypeState<\n infer C extends Governed<Config>,\n infer X extends ExtensionState\n>\n ? Base extends VibORMClient<C, X>\n ? BeforeConsumers<X, ReturnType<typeof apply<Config, C, X>>>\n : never\n : never;\ntype Rowed<\n Config extends SoftDeleteConfig,\n Base,\n> = Base extends ClientTypeState<\n infer C extends Governed<Config>,\n infer X extends ExtensionState\n>\n ? Base extends VibORMClient<C, X>\n ? BeforeConsumers<X, ReturnType<typeof rowsStep<Config, C, X>>>\n : never\n : never;\ntype Restorable<\n Config extends SoftDeleteConfig,\n Base,\n> = Base extends ClientTypeState<\n infer C extends Governed<Config>,\n infer X extends ExtensionState\n>\n ? Base extends VibORMClient<C, X>\n ? ReturnType<typeof methodsStep<Config, C, X>>\n : never\n : never;\n// The whole factory's NoInfer keeps `$extends(softDelete(config))` from\n// inferring between two client types (which measures the client alias's\n// variance, ~650k instantiations once per program).\ntype SoftDeleteExtension<Config extends SoftDeleteConfig> = {\n <Base extends Receiver<Config>>(base: Base): NoInfer<Applied<Config, Base>>;\n /** The controls, rows and deletion alone (chains written before 1.8). */\n readonly rows: <Base extends Receiver<Config>>(\n base: Base\n ) => Rowed<Config, Base>;\n /** The methods alone (chains written before 1.8). */\n readonly methods: <Base extends Receiver<Config>>(\n client: Base\n ) => Restorable<Config, Base>;\n};\n\n/**\n * Keep deleted rows as tombstones: `client.$extends(softDelete({ models: {\n * post: { deletedAt: \"deletedAt\" } } }))`. One step, applied in any order\n * with the other extensions.\n */\nexport function softDelete<const Config extends SoftDeleteConfig>(\n config: Config\n): SoftDeleteExtension<Config> {\n function extend<Base extends Receiver<Config>>(\n base: Base\n ): NoInfer<Applied<Config, Base>>;\n function extend<C extends Governed<Config>, X extends ExtensionState>(\n base: VibORMClient<C, X>\n ) {\n return apply(config, base);\n }\n function rows<Base extends Receiver<Config>>(base: Base): Rowed<Config, Base>;\n function rows<C extends Governed<Config>, X extends ExtensionState>(\n base: VibORMClient<C, X>\n ) {\n return rowsStep(config, base);\n }\n function methods<Base extends Receiver<Config>>(\n client: Base\n ): Restorable<Config, Base>;\n function methods<C extends Governed<Config>, X extends ExtensionState>(\n client: VibORMClient<C, X>\n ) {\n return methodsStep(config, client);\n }\n return Object.assign(extend, { rows, methods });\n}\n"],"mappings":"6EA0BA,MAAM,EAAO,oBAIb,SAAS,SAIP,EAAgB,EAAkC,EAAa,CAC/D,OAAO,OAAO,YACZ,OAAO,QAAQ,EAAO,OAAO,CAAC,KAAK,CAAC,EAAG,KAAO,CAAC,EAAG,EAAM,EAAE,CAAC,CAAC,CAC7D,CAsDH,SAAS,aAAa,EAAgB,EAAgC,CACpE,IAAK,GAAM,CAAC,EAAM,CAAE,gBAAgB,OAAO,QAAQ,EAAO,OAAO,CAAE,CACjE,IAAM,EAAU,OAAO,OAAO,EAAQ,EAAK,CACvC,EAAO,GAAO,KAAK,MAAM,QAC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