viborm 1.7.0 → 1.8.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/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-Ct1qPFc8.mjs} +2 -2
- package/dist/{builder-B4n-7I7Q.mjs.map → builder-Ct1qPFc8.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--uZ0O7_Y.mjs} +2 -2
- package/dist/{chain-DVuRxjPO.mjs.map → chain--uZ0O7_Y.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/client-BAxU6jnw.mjs +2 -0
- package/dist/client-BAxU6jnw.mjs.map +1 -0
- package/dist/{client-7ApJka0M.d.mts → client-DP6gM_tf.d.mts} +2 -2
- package/dist/{client-l7dSOul5.mjs → client-mQcOvDdK.mjs} +3 -3
- package/dist/client-mQcOvDdK.mjs.map +1 -0
- 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/{driver-DaBNytbz.mjs → driver-NtekjA3W.mjs} +2 -2
- package/dist/{driver-DaBNytbz.mjs.map → driver-NtekjA3W.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-Xql4tHDz.mjs +2 -0
- package/dist/{every-6VrIclsx.mjs.map → every-Xql4tHDz.mjs.map} +1 -1
- package/dist/{hydration-BUBkHlCK.mjs → hydration-BNEFeV5v.mjs} +2 -2
- package/dist/{hydration-BUBkHlCK.mjs.map → hydration-BNEFeV5v.mjs.map} +1 -1
- package/dist/{identifier-conversion-BXrBYgAq.mjs → identifier-conversion-C_XCo9es.mjs} +2 -2
- package/dist/{identifier-conversion-BXrBYgAq.mjs.map → identifier-conversion-C_XCo9es.mjs.map} +1 -1
- package/dist/{index-CsO6vG2h.d.mts → index-DBhpNR0X.d.mts} +70 -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-QgLg2Kve.mjs} +2 -2
- package/dist/{key-Cz83fdLO.mjs.map → key-QgLg2Kve.mjs.map} +1 -1
- package/dist/{keys-EP1Eq2eD.mjs → keys-D5hv9EaJ.mjs} +2 -2
- package/dist/{keys-EP1Eq2eD.mjs.map → keys-D5hv9EaJ.mjs.map} +1 -1
- package/dist/{libsql-ClGi2zY2.mjs → libsql-BsJdPDES.mjs} +2 -2
- package/dist/{libsql-ClGi2zY2.mjs.map → libsql-BsJdPDES.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-B1GnzgZr.mjs → memory-BEaJ0-FU.mjs} +2 -2
- package/dist/{memory-B1GnzgZr.mjs.map → memory-BEaJ0-FU.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-D94xU8jq.mjs} +2 -2
- package/dist/{model-DsXZ_pHE.mjs.map → model-D94xU8jq.mjs.map} +1 -1
- package/dist/{mysql-hoo290Dd.mjs → mysql-DT_dTWDi.mjs} +2 -2
- package/dist/{mysql-hoo290Dd.mjs.map → mysql-DT_dTWDi.mjs.map} +1 -1
- package/dist/{mysql-adapter-D-Dq2FN9.mjs → mysql-adapter-BUwzKlbt.mjs} +2 -2
- package/dist/{mysql-adapter-D-Dq2FN9.mjs.map → mysql-adapter-BUwzKlbt.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-35LjwOS-.d.mts} +3 -3
- package/dist/on.d.mts +1 -1
- package/dist/ordering.d.mts +41 -19
- package/dist/ordering.mjs +8 -8
- package/dist/ordering.mjs.map +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +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/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-Cc3ABIUU.d.mts → planner-CmDw5jPb.d.mts} +1 -1
- package/dist/{postgres-CqcP_qv-.mjs → postgres-Do0nq95P.mjs} +2 -2
- package/dist/{postgres-CqcP_qv-.mjs.map → postgres-Do0nq95P.mjs.map} +1 -1
- package/dist/{postgres-adapter-_o6EWuxW.mjs → postgres-adapter-DFzjbAP7.mjs} +2 -2
- package/dist/{postgres-adapter-_o6EWuxW.mjs.map → postgres-adapter-DFzjbAP7.mjs.map} +1 -1
- package/dist/{postgres-adapter-CYZAL2uo.mjs → postgres-adapter-Dvt16rbl.mjs} +2 -2
- package/dist/{postgres-adapter-CYZAL2uo.mjs.map → postgres-adapter-Dvt16rbl.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/{result-shape-uaCsF_SZ.mjs → result-shape-DwoSyWnq.mjs} +2 -2
- package/dist/{result-shape-uaCsF_SZ.mjs.map → result-shape-DwoSyWnq.mjs.map} +1 -1
- package/dist/{rows-AtX0guAb.mjs → rows-ig1gjVRb.mjs} +2 -2
- package/dist/{rows-AtX0guAb.mjs.map → rows-ig1gjVRb.mjs.map} +1 -1
- package/dist/rows-of-Djavcb19.mjs +2 -0
- package/dist/rows-of-Djavcb19.mjs.map +1 -0
- package/dist/{scalar-CZ_q89Hc.mjs → scalar-BgxfbRLw.mjs} +2 -2
- package/dist/{scalar-CZ_q89Hc.mjs.map → scalar-BgxfbRLw.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-CT57uls5.mjs +2 -0
- package/dist/{schema-CZTCxG2p.mjs.map → schema-CT57uls5.mjs.map} +1 -1
- package/dist/{schema-introspection-DoZHc1o7.mjs → schema-introspection-BFDAX5Ol.mjs} +2 -2
- package/dist/{schema-introspection-DoZHc1o7.mjs.map → schema-introspection-BFDAX5Ol.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-eGsbASDR.mjs} +2 -2
- package/dist/{sqlite-adapter-CnAwmszh.mjs.map → sqlite-adapter-eGsbASDR.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-CJ-8_caR.mjs} +2 -2
- package/dist/{to-many-BtLpp5cW.mjs.map → to-many-CJ-8_caR.mjs.map} +1 -1
- package/dist/{utils-CAACs9Jw.mjs → utils-DYz-Xm59.mjs} +2 -2
- package/dist/{utils-CAACs9Jw.mjs.map → utils-DYz-Xm59.mjs.map} +1 -1
- package/dist/{v-Pb_jJOjC.mjs → v-C2XN11Gy.mjs} +2 -2
- package/dist/{v-Pb_jJOjC.mjs.map → v-C2XN11Gy.mjs.map} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-Dthaj1Hz.mjs → validator-DqI5RlVU.mjs} +2 -2
- package/dist/{validator-Dthaj1Hz.mjs.map → validator-DqI5RlVU.mjs.map} +1 -1
- package/dist/version-DyH_HopX.mjs +2 -0
- package/dist/{version-DvynkoaW.mjs.map → version-DyH_HopX.mjs.map} +1 -1
- package/package.json +21 -21
- 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/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
package/dist/driver.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Di as NotNullConstraintError, Ei as ForeignKeyError, Fn as BatchQuery, Hi as isRetryableError, Ln as Dialect, Oi as UniqueConstraintError, Rn as QueryExecutionContext, Ti as CheckConstraintError, _i as QueryError, f as SQLITE_MIGRATION_CAPABILITY, h as DriverResultParser, jn as sqliteResultParser, l as AnyDriver, li as ConnectionError, p as SqliteMigrationCapability, si as TransactionError, u as Driver, ui as FeatureNotSupportedError, zn as QueryResult } from "./index-DBhpNR0X.mjs";
|
|
2
2
|
export { type AnyDriver, type BatchQuery, CheckConstraintError, ConnectionError, type Dialect, Driver, type DriverResultParser, FeatureNotSupportedError, ForeignKeyError, NotNullConstraintError, QueryError, type QueryExecutionContext, type QueryResult, SQLITE_MIGRATION_CAPABILITY, type SqliteMigrationCapability, TransactionError, UniqueConstraintError, isRetryableError, sqliteResultParser };
|
package/dist/driver.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./base-wlv81COV.mjs";import{S as t,b as n,x as r,y as i}from"./error-mapping-D--MVRCY.mjs";import{d as a,n as o,r as s}from"./query-CTna5P9o.mjs";import{n as c}from"./transaction-D5LHYn-r.mjs";import{n as l,t as u}from"./driver-
|
|
1
|
+
import{r as e}from"./base-wlv81COV.mjs";import{S as t,b as n,x as r,y as i}from"./error-mapping-D--MVRCY.mjs";import{d as a,n as o,r as s}from"./query-CTna5P9o.mjs";import{n as c}from"./transaction-D5LHYn-r.mjs";import{n as l,t as u}from"./driver-XlmOJFRH.mjs";import{l as d}from"./sqlite-utils-DztTzv08.mjs";export{i as CheckConstraintError,o as ConnectionError,u as Driver,s as FeatureNotSupportedError,n as ForeignKeyError,r as NotNullConstraintError,a as QueryError,l as SQLITE_MIGRATION_CAPABILITY,c as TransactionError,t as UniqueConstraintError,e as isRetryableError,d as sqliteResultParser};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./client-mQcOvDdK.mjs";import{n,t as r}from"./libsql-BsJdPDES.mjs";import{t as i}from"./mysql-DT_dTWDi.mjs";import{t as a}from"./postgres-Do0nq95P.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i)}export{registerEveryMigrationDriver as t};
|
|
2
|
+
//# sourceMappingURL=every-Xql4tHDz.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"every-
|
|
1
|
+
{"version":3,"file":"every-Xql4tHDz.mjs","names":[],"sources":["../src/migrations/dialects/every.ts"],"sourcesContent":["/**\n * Every dialect's migration driver. Callers register from their own entry\n * statement (`viborm/migrations`, the CLI), so the registration stays with\n * the entry a bundler keeps.\n */\n\nimport { registerMigrationDriver } from \"../drivers\";\nimport { libsqlMigrationDriver } from \"../drivers/libsql\";\nimport { mysqlMigrationDriver } from \"../drivers/mysql\";\nimport { postgresMigrationDriver } from \"../drivers/postgres\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n}\n"],"mappings":"oNAYA,SAAgB,8BAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-CIZxuIvE.mjs";import{d as n,m as r}from"./scalar-
|
|
2
|
-
//# sourceMappingURL=hydration-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{Pt as t}from"./geo-point-codec-CIZxuIvE.mjs";import{d as n,m as r}from"./scalar-BgxfbRLw.mjs";function hydrateSchemaNames(e,t=!1){let i=Object.entries(e);if(t){for(let[e,t]of i)bindModelNames(e,t);return}let a=r(i);if(a)throw new n([a]);for(let[e,t]of i)preflightModelIdentifiers(e,t);for(let[e,t]of i)bindModelNames(e,t)}function preflightModelIdentifiers(e,t){let n=t[`~`].state;assertValidIdentifier(`Model`,e),n.tableName!==void 0&&assertValidIdentifier(`Mapped table`,n.tableName,e);for(let t of Object.keys(n.shape))assertValidIdentifier(`Field`,t,e);for(let t of Object.values(n.scalars))t[`~`].state.columnName!==void 0&&assertValidIdentifier(`Mapped column`,t[`~`].state.columnName,e)}function bindModelNames(e,t){let n=t[`~`].names,r=t[`~`].state,i=t[`~`].nameRegistry;n.ts=e,n.sql=r.tableName??e;for(let[e,t]of Object.entries(r.scalars)){let n={ts:e,sql:t[`~`].state.columnName??e};i.fields.set(e,n)}}function assertValidIdentifier(e,n,r){if(t(n))return;let i=r?` in '${r}'`:``,a=String(n);throw Error(`${e} '${a}'${i} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`)}export{hydrateSchemaNames as t};
|
|
2
|
+
//# sourceMappingURL=hydration-BNEFeV5v.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-
|
|
1
|
+
{"version":3,"file":"hydration-BNEFeV5v.mjs","names":[],"sources":["../src/schema/hydration.ts"],"sourcesContent":["/**\n * Schema Hydration\n *\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"8IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CACjC,OAKF,IAAM,EAAgB,EAAmC,EAAc,CACvE,GAAI,EAAe,MAAM,IAAI,EAAsB,CAAC,EAAc,CAAC,CACnE,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,0BAA0B,EAAU,EAAM,CAE5C,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CAenC,SAAS,0BAA0B,EAAkB,EAAyB,CAC5E,IAAM,EAAQ,EAAM,KAAK,MAEzB,sBAAsB,QAAS,EAAS,CACpC,EAAM,YAAc,IAAA,IACtB,sBAAsB,eAAgB,EAAM,UAAW,EAAS,CAElE,IAAK,IAAM,KAAY,OAAO,KAAK,EAAM,MAAM,CAC7C,sBAAsB,QAAS,EAAU,EAAS,CAEpD,IAAK,IAAM,KAAU,OAAO,OAAO,EAAM,QAAkC,CACrE,EAAO,KAAK,MAAM,aAAe,IAAA,IACnC,sBACE,gBACA,EAAO,KAAK,MAAM,WAClB,EACD,CAaP,SAAS,eAAe,EAAkB,EAAyB,CACjE,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAQ,EAAM,KAAK,MACnB,EAAW,EAAM,KAAK,aAE5B,EAAM,GAAK,EACX,EAAM,IAAM,EAAM,WAAa,EAE/B,IAAK,GAAM,CAAC,EAAU,KAAW,OAAO,QACtC,EAAM,QACP,CAAE,CACD,IAAM,EAA0B,CAC9B,GAAI,EACJ,IAAK,EAAO,KAAK,MAAM,YAAc,EACtC,CACD,EAAS,OAAO,IAAI,EAAU,EAAW,EAM7C,SAAS,sBACP,EACA,EACA,EACM,CACN,GAAI,EAAwB,EAAW,CAAE,OACzC,IAAM,EAAW,EAAY,QAAQ,EAAU,GAAK,GAC9C,EAAqB,OAAO,EAAW,CAC7C,MAAU,MACR,GAAG,EAAK,IAAI,EAAmB,GAAG,EAAS,4HAC5C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{it as r,st as i}from"./geo-point-codec-CIZxuIvE.mjs";import{o as a}from"./sql-
|
|
2
|
-
//# sourceMappingURL=identifier-conversion-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{it as r,st as i}from"./geo-point-codec-CIZxuIvE.mjs";import{o as a}from"./sql-BsBoKwaf.mjs";import{n as o,r as s}from"./model-D94xU8jq.mjs";import{i as c}from"./keys-D5hv9EaJ.mjs";import{t as l}from"./hydration-BNEFeV5v.mjs";import{l as u,n as d,u as f}from"./validator-DqI5RlVU.mjs";import{N as p}from"./standard-sql-BtzSzrof.mjs";function mapReferentialAction(e){switch(e.toUpperCase()){case`CASCADE`:return`cascade`;case`SET NULL`:return`setNull`;case`RESTRICT`:return`restrict`;case`SET DEFAULT`:return`setDefault`;default:return`noAction`}}function groupBy(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function groupByNested(e,t,n){let r=new Map;for(let i of e){let e=t(i),a=n(i),o=r.get(e);o||(o=new Map,r.set(e,o));let s=o.get(a);s?s.push(i):o.set(a,[i])}return r}const m=`[0-9a-fA-F]`,h=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,g=`[0-9A-Za-z]`,_={uuid:{length:36,regex:`^${m}{8}-${m}{4}-${m}{4}-${m}{4}-${m}{12}$`,glob:`${m.repeat(8)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,regex:`^[0-7]${h}{25}$`,glob:`[0-7]${h.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,regex:`^${g}{27}$`,glob:g.repeat(27),fold:void 0,max:i}};function patternOf(e){return e.format===`ulid`?_.ulid:e.format===`ksuid`?_.ksuid:_.uuid}const int=e=>a.raw(String(e));function fromSql(e,t,n,r){let i=p(t===`mysql`?"`":`"`),o=t===`postgresql`&&n?`${i(n)}.`:``;return a.raw(`${o+i(s(e))} AS ${r}`)}function columnSql(e,t,n,r){let i=p(n===`mysql`?"`":`"`);return a.raw(`${r}.${i(o(e,t))}`)}function payloadSql(e,t){let n=t.prefix;return n?a`substr(${e}, ${int(n.length+2)})`:e}function bytesSql(e,t){return t===`mysql`?a`CAST(${e} AS BINARY)`:e}function orderedSql(e,t){return t===`postgresql`?a`CAST(${e} AS text) COLLATE "C"`:bytesSql(e,t)}function admitsSql(e,t,n){let r=patternOf(t),i=payloadSql(e,t),o=n===`postgresql`?a`${i} ~ ${r.regex}`:n===`mysql`?a`${i} REGEXP ${r.regex}`:a`${i} GLOB ${r.glob}`,s=a`${a.raw(n===`mysql`?`CHAR_LENGTH`:`length`)}(${i}) = ${int(r.length)} AND ${o}`,c=r.max===void 0?s:a`${s} AND ${orderedSql(i,n)} <= ${r.max}`,l=t.prefix;return l?a`${bytesSql(a`substr(${e}, 1, ${int(l.length+1)})`,n)} = ${`${l}-`} AND ${c}`:c}function foldSql(e,t,n){let r=patternOf(t).fold,i=payloadSql(e,t);return bytesSql(r===void 0?i:a`${a.raw(r)}(${i})`,n)}function foldCollisionCheck(e,t,n,r){return{kind:`trusted-read`,query:a`SELECT COUNT(${t}) = COUNT(DISTINCT ${foldSql(t,n,r)}) AS ok FROM ${e}`,equals:!0}}function isSingleColumnKey(e,t){return c(e).referenceableKeys.some(e=>e.length===1&&e[0]===t)}const noRowWhere=(e,t)=>({kind:`trusted-read`,query:a`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${t}) AS ok`,equals:!0});function referencingColumns(e,t){let n=[];for(let r of u(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.referencedField===e.field&&n.push({model:r.owner.source,field:t.foreignField});return n}function identifierConversionChecks(e){let{model:i,field:c,dialect:u,namespace:p}=e;l(e.schema);let m=d(e.schema),h=f(i,c,m);if(h===void 0||!r(h.format))throw new n(`'${s(i)}.${o(i,c)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,t.INVALID_INPUT);let g=fromSql(i,u,p,`p`),_=columnSql(i,c,u,`p`),v=[noRowWhere(g,a`${_} IS NOT NULL AND NOT (${admitsSql(_,h,u)})`)],y=patternOf(h).fold!==void 0;y&&v.push(foldCollisionCheck(g,_,h,u));for(let t of referencingColumns(e,m)){let e=fromSql(t.model,u,p,`c`),n=columnSql(t.model,t.field,u,`c`);v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT (${admitsSql(n,h,u)})`)),y&&isSingleColumnKey(t.model,t.field)&&v.push(foldCollisionCheck(e,n,h,u)),v.push(noRowWhere(e,a`${n} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${g} WHERE ${foldSql(_,h,u)} = ${foldSql(n,h,u)})`))}return v}const v=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function postgresTextToUuidGuard(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${literal(_.uuid.regex)}; IF invalid > 0 THEN RAISE EXCEPTION ${literal(`VibORM: % row(s) of ${n} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; END IF; END \$viborm\$`}function isPostgresTextToUuid(e,t){return t.toLowerCase()===`uuid`&&v.test(e.trim())}export{groupByNested as a,groupBy as i,isPostgresTextToUuid as n,mapReferentialAction as o,postgresTextToUuidGuard as r,identifierConversionChecks as t};
|
|
2
|
+
//# sourceMappingURL=identifier-conversion-C_XCo9es.mjs.map
|
package/dist/{identifier-conversion-BXrBYgAq.mjs.map → identifier-conversion-C_XCo9es.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identifier-conversion-BXrBYgAq.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"kdASA,SAAgB,qBAAqB,EAAiC,CACpE,OAAQ,EAAK,aAAa,CAA1B,CACE,IAAK,UACH,MAAO,UACT,IAAK,WACH,MAAO,UACT,IAAK,WACH,MAAO,WACT,IAAK,cACH,MAAO,aACT,QACE,MAAO,YAWb,SAAgB,QACd,EACA,EACkB,CAClB,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAM,EAAM,EAAK,CACjB,EAAW,EAAI,IAAI,EAAI,CACzB,EACF,EAAS,KAAK,EAAK,CAEnB,EAAI,IAAI,EAAK,CAAC,EAAK,CAAC,CAGxB,OAAO,EAWT,SAAgB,cACd,EACA,EACA,EAC+B,CAC/B,IAAM,EAAM,IAAI,IAChB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAK,EAAa,EAAK,CACvB,EAAK,EAAe,EAAK,CAE3B,EAAY,EAAI,IAAI,EAAG,CACtB,IACH,EAAY,IAAI,IAChB,EAAI,IAAI,EAAI,EAAU,EAGxB,IAAM,EAAW,EAAU,IAAI,EAAG,CAC9B,EACF,EAAS,KAAK,EAAK,CAEnB,EAAU,IAAI,EAAI,CAAC,EAAK,CAAC,CAG7B,OAAO,ECiBT,MAAM,EAAM,cACN,EAAY,kCACZ,EAAS,cAYT,EAAW,CACf,KAAM,CACJ,OAAQ,GACR,MAAO,IAAI,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,OACvD,KAAM,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,GAAG,GAC3F,KAAM,QACN,IAAK,IAAA,GACN,CACD,KAAM,CACJ,OAAQ,GACR,MAAO,SAAS,EAAU,OAC1B,KAAM,QAAQ,EAAU,OAAO,GAAG,GAClC,KAAM,QACN,IAAK,IAAA,GACN,CACD,MAAO,CACL,OAAQ,GACR,MAAO,IAAI,EAAO,OAClB,KAAM,EAAO,OAAO,GAAG,CACvB,KAAM,IAAA,GACN,IAAK,EACN,CACF,CAGD,SAAS,UAAU,EAAkB,CAGnC,OAFI,EAAO,SAAW,OAAe,EAAS,KAC1C,EAAO,SAAW,QAAgB,EAAS,MACxC,EAAS,KAIlB,MAAM,IAAO,GAAuBA,EAAI,IAAI,OAAO,EAAM,CAAC,CAG1D,SAAS,QACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CAC/D,EACJ,IAAY,cAAgB,EAAY,GAAG,EAAM,EAAU,CAAC,GAAK,GACnE,OAAOA,EAAI,IAAI,GAAG,EAAY,EAAM,EAAa,EAAM,CAAC,CAAC,MAAM,IAAQ,CAUzE,SAAS,UACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CACrE,OAAOA,EAAI,IAAI,GAAG,EAAM,GAAG,EAAM,EAAc,EAAO,EAAM,CAAC,GAAG,CAIlE,SAAS,WAAW,EAAa,EAAuB,CACtD,IAAM,EAAS,EAAO,OAEtB,OADK,EACE,CAAG,UAAU,EAAO,IAAI,IAAI,EAAO,OAAS,EAAE,CAAC,GADlC,EAWtB,SAAS,SAAS,EAAiB,EAAuB,CACxD,OAAO,IAAY,QAAU,CAAG,QAAQ,EAAW,aAAe,EAcpE,SAAS,WAAW,EAAiB,EAAuB,CAI1D,OAHI,IAAY,aACP,CAAG,QAAQ,EAAW,uBAExB,SAAS,EAAY,EAAQ,CAItC,SAAS,UAAU,EAAa,EAAkB,EAAuB,CACvE,IAAM,EAAU,UAAU,EAAO,CAC3B,EAAU,WAAW,EAAQ,EAAO,CACpC,EACJ,IAAY,aACR,CAAG,GAAG,EAAQ,KAAK,EAAQ,QAC3B,IAAY,QACV,CAAG,GAAG,EAAQ,UAAU,EAAQ,QAChC,CAAG,GAAG,EAAQ,QAAQ,EAAQ,OAEhC,EAAU,CAAG,GADLA,EAAI,IAAI,IAAY,QAAU,cAAgB,SAAS,CACzC,GAAG,EAAQ,MAAM,IAAI,EAAQ,OAAO,CAAC,OAAO,IAClE,EACJ,EAAQ,MAAQ,IAAA,GACZ,EACA,CAAG,GAAG,EAAQ,OAAO,WAAW,EAAS,EAAQ,CAAC,MAAM,EAAQ,MAChE,EAAS,EAAO,OAMtB,OALK,EAKE,CAAG,GAJM,SACd,CAAG,UAAU,EAAO,OAAO,IAAI,EAAO,OAAS,EAAE,CAAC,GAClD,EACD,CACoB,KAAK,GAAG,EAAO,GAAG,OAAO,IAL1B,EAYtB,SAAS,QAAQ,EAAa,EAAkB,EAAuB,CACrE,IAAM,EAAO,UAAU,EAAO,CAAC,KACzB,EAAU,WAAW,EAAQ,EAAO,CAC1C,OAAO,SACL,IAAS,IAAA,GAAY,EAAU,CAAG,GAAGA,EAAI,IAAI,EAAK,CAAC,GAAG,EAAQ,GAC9D,EACD,CAOH,SAAS,mBACP,EACA,EACA,EACA,EACqB,CACrB,MAAO,CACL,KAAM,eACN,MAAO,CAAG,gBAAgB,EAAO,qBAAqB,QAAQ,EAAQ,EAAQ,EAAQ,CAAC,eAAe,IACtG,OAAQ,GACT,CAgBH,SAAS,kBAAkB,EAAiB,EAAwB,CAClE,OAAO,EAAmB,EAAM,CAAC,kBAAkB,KAChD,GAAQ,EAAI,SAAW,GAAK,EAAI,KAAO,EACzC,CAIH,MAAM,YAAc,EAAW,KAAyC,CACtE,KAAM,eACN,MAAO,CAAG,oCAAoC,EAAK,SAAS,EAAU,SACtE,OAAQ,GACT,EAGD,SAAS,mBACP,EACA,EACsC,CACtC,IAAM,EAAgD,EAAE,CACxD,IAAK,IAAM,KAAQ,EAAc,EAAM,CACjC,KAAK,OAAS,eAEhB,EAAK,UAAU,KAAO,EAAK,MAAQ,EAAK,UAAU,GAAK,EAAK,UAAU,IAC9D,SAAW,EAAQ,MAC7B,IAAK,IAAM,KAAU,EAAK,UAAU,QAC9B,EAAO,kBAAoB,EAAQ,OACvC,EAAQ,KAAK,CAAE,MAAO,EAAK,MAAM,OAAQ,MAAO,EAAO,aAAc,CAAC,CAG1E,OAAO,EAWT,SAAgB,2BACd,EACgC,CAChC,GAAM,CAAE,QAAO,QAAO,UAAS,aAAc,EAC7C,EAAmB,EAAQ,OAAO,CAClC,IAAM,EAAQ,EAAqB,EAAQ,OAAO,CAC5C,EAAS,EAAW,EAAO,EAAO,EAAM,CAC9C,GAAI,IAAW,IAAA,IAAa,CAAC,EAAkB,EAAO,OAAO,CAC3D,MAAM,IAAI,EACR,IAAI,EAAa,EAAM,CAAC,GAAG,EAAc,EAAO,EAAM,CAAC,uIACvD,EAAgB,cACjB,CAEH,IAAM,EAAS,QAAQ,EAAO,EAAS,EAAW,IAAI,CAChD,EAAM,UAAU,EAAO,EAAO,EAAS,IAAI,CAC3C,EAAgC,CACpC,WACE,EACA,CAAG,GAAG,EAAI,wBAAwB,UAAU,EAAK,EAAQ,EAAQ,CAAC,GACnE,CACF,CACK,EAAQ,UAAU,EAAO,CAAC,OAAS,IAAA,GACrC,GACF,EAAO,KAAK,mBAAmB,EAAQ,EAAK,EAAQ,EAAQ,CAAC,CAE/D,IAAK,IAAM,KAAa,mBAAmB,EAAS,EAAM,CAAE,CAC1D,IAAM,EAAQ,QAAQ,EAAU,MAAO,EAAS,EAAW,IAAI,CACzD,EAAK,UAAU,EAAU,MAAO,EAAU,MAAO,EAAS,IAAI,CACpE,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,wBAAwB,UAAU,EAAI,EAAQ,EAAQ,CAAC,GACjE,CACF,CACG,GAAS,kBAAkB,EAAU,MAAO,EAAU,MAAM,EAC9D,EAAO,KAAK,mBAAmB,EAAO,EAAI,EAAQ,EAAQ,CAAC,CAE7D,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,6CAA6C,EAAO,SAAS,QAAQ,EAAK,EAAQ,EAAQ,CAAC,KAAK,QAAQ,EAAI,EAAQ,EAAQ,CAAC,GACvI,CACF,CAEH,OAAO,EAQT,MAAM,EAAiB,wDAGjB,QAAW,GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"identifier-conversion-C_XCo9es.mjs","names":["sql"],"sources":["../src/migrations/drivers/utils.ts","../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\nimport type { ReferentialAction } from \"../types\";\n\n/** A catalog's `ON DELETE` / `ON UPDATE` spelling, as a ReferentialAction. */\nexport function mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as sqlTag, n as Sql } from "./sql-
|
|
1
|
+
import { c as sqlTag, n as Sql } from "./sql-D7JnXgUh.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema/scalars/native-types.d.ts
|
|
@@ -5454,13 +5454,33 @@ type EnableExtensionCache<X$1 extends ExtensionStateConstraint> = ClientExtensio
|
|
|
5454
5454
|
}>, X$1["rows"], X$1["data"], X$1["result"]>;
|
|
5455
5455
|
/** Whether an earlier extension was typed against result-bearing delegates. */
|
|
5456
5456
|
type HasResultConsumingExtension<X$1 extends ExtensionStateConstraint> = [X$1["resultConsumer"]] extends [undefined] ? false : [X$1["resultConsumer"]] extends [ExtensionResultConsumerState] ? true : false;
|
|
5457
|
+
declare const delegateState: unique symbol;
|
|
5458
|
+
/**
|
|
5459
|
+
* Declaration-only: what a result read on a delegate of a chain that adds
|
|
5460
|
+
* model methods depends on (its client's config, the models the chain's
|
|
5461
|
+
* `rows` can hide, its computed fields, the model), so a method typed with a
|
|
5462
|
+
* `this` parameter reads its result from the client it is called on
|
|
5463
|
+
* (`DelegateOperationResult`), whatever the chain added after it. Nothing
|
|
5464
|
+
* else of the extension state: a later step that changes none of these (the
|
|
5465
|
+
* cache) keeps the client assignable to the one before it. No property is
|
|
5466
|
+
* installed at runtime.
|
|
5467
|
+
*/
|
|
5468
|
+
interface DelegateState<C$1, Rows$1, Result$1, ModelName$1> {
|
|
5469
|
+
readonly [delegateState]?: readonly [C$1, Rows$1, Result$1, ModelName$1];
|
|
5470
|
+
}
|
|
5457
5471
|
type MethodsForModel<X$1 extends ExtensionStateConstraint, ModelName$1 extends PropertyKey> = ModelName$1 extends keyof X$1["models"] ? X$1["models"][ModelName$1] : NoMethods;
|
|
5472
|
+
/**
|
|
5473
|
+
* The link, on every delegate of a chain that adds model methods: decided by
|
|
5474
|
+
* the extension state alone, so a client generic over its schema without
|
|
5475
|
+
* them (the empty state) compares as before.
|
|
5476
|
+
*/
|
|
5477
|
+
type DelegateLink<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends PropertyKey> = [keyof X$1["models"]] extends [never] ? unknown : DelegateState<C$1, X$1["rows"], X$1["result"], ModelName$1>;
|
|
5458
5478
|
/**
|
|
5459
5479
|
* One model's delegate after the chain's methods and controls. On a chain
|
|
5460
5480
|
* that declares create `data`, its writes may leave out the fields the chain
|
|
5461
5481
|
* writes on a create.
|
|
5462
5482
|
*/
|
|
5463
|
-
type ExtensionModelDelegate<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends keyof ClientSchema<C$1>> = ([X$1["data"]] extends [never] ? Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1] : Omit<Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1], StampedOperation> & StampedOperations<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"], X$1["data"], ModelName$1>) & MethodsForModel<X$1, ModelName$1>;
|
|
5483
|
+
type ExtensionModelDelegate<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends keyof ClientSchema<C$1>> = ([X$1["data"]] extends [never] ? Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1] : Omit<Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1], StampedOperation> & StampedOperations<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"], X$1["data"], ModelName$1>) & MethodsForModel<X$1, ModelName$1> & DelegateLink<C$1, X$1, ModelName$1>;
|
|
5464
5484
|
/**
|
|
5465
5485
|
* One model's delegate on a chain that declares `result`: its projecting
|
|
5466
5486
|
* operations rebuilt so `select` and `omit` name the computed fields and the
|
|
@@ -5531,11 +5551,30 @@ type ModelMethodsOf<Definition$1> = Definition$1 extends {
|
|
|
5531
5551
|
readonly model: infer Factories;
|
|
5532
5552
|
} ? Factories extends object ? { readonly [ModelName in keyof Factories]: Factories[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : NoMethods : NoMethods } : NoMethods : NoMethods;
|
|
5533
5553
|
type MergeModelMethods<Left extends object, Right extends object> = { readonly [ModelName in keyof Left | keyof Right]: (ModelName extends keyof Left ? Left[ModelName] : NoMethods) & (ModelName extends keyof Right ? Right[ModelName] : NoMethods) };
|
|
5534
|
-
|
|
5535
|
-
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5554
|
+
/** Whether one parameter list holds an argument typed other than `never` or `unknown` (`any` counts as typed). */
|
|
5555
|
+
type TypedParameters<Given extends readonly unknown[]> = true extends { [Index in keyof Given]: 0 extends 1 & Given[Index] ? true : [Given[Index]] extends [never] ? false : unknown extends Given[Index] ? false : true }[number] ? true : false;
|
|
5556
|
+
/**
|
|
5557
|
+
* Whether a client or model factory is typed against the client it is
|
|
5558
|
+
* applied to: one of its signatures takes an argument typed other than
|
|
5559
|
+
* `never` or `unknown`. A factory that takes none reads nothing typed at its
|
|
5560
|
+
* step, so a later `rows` or `defaultOmit` cannot make its types lie: its
|
|
5561
|
+
* methods type their results from the client they are called on (a `this`
|
|
5562
|
+
* parameter), and it is no result consumer. Matched against four
|
|
5563
|
+
* signatures, so an overloaded factory is read by its last four (one
|
|
5564
|
+
* signature repeats).
|
|
5565
|
+
*/
|
|
5566
|
+
type ReadsTyped<Factory$1> = Factory$1 extends {
|
|
5567
|
+
(...args: infer First): unknown;
|
|
5568
|
+
(...args: infer Second): unknown;
|
|
5569
|
+
(...args: infer Third): unknown;
|
|
5570
|
+
(...args: infer Fourth): unknown;
|
|
5571
|
+
} ? true extends TypedParameters<First> | TypedParameters<Second> | TypedParameters<Third> | TypedParameters<Fourth> ? true : false : true;
|
|
5572
|
+
type TypedFactories<Definition$1> = (Definition$1 extends {
|
|
5573
|
+
readonly client: infer Factory;
|
|
5574
|
+
} ? ReadsTyped<Factory> : false) | (Definition$1 extends {
|
|
5575
|
+
readonly model: infer Factories;
|
|
5576
|
+
} ? Factories extends object ? { [ModelName in keyof Factories]: ReadsTyped<Factories[ModelName]> }[keyof Factories] : true : false);
|
|
5577
|
+
type ResultConsumerContextOf<Definition$1> = true extends TypedFactories<Definition$1> ? "result-consuming" : Definition$1 extends {
|
|
5539
5578
|
readonly query: infer Query;
|
|
5540
5579
|
} ? Query extends CallableFunction ? "result-independent" : "result-consuming" : "result-independent";
|
|
5541
5580
|
/** Incoming facts keep their nominal bit derivation inside this named state. */
|
|
@@ -6444,6 +6483,20 @@ type ExtensionState = ExtensionStateConstraint;
|
|
|
6444
6483
|
* `M[K & keyof M]` in a plugin generic over it.
|
|
6445
6484
|
*/
|
|
6446
6485
|
type ExtendedOperationResult<Client$1, ModelName$1, O$1 extends Operations, Args> = typeof clientTypeState extends keyof Client$1 ? Client$1 extends ClientTypeState<infer C, infer X> ? Client$1 extends VibORMClient<C, X> ? ContextualOperationResult<C, ModelName$1 & keyof ClientSchema<C>, O$1, Args, ClientRowsContext<C, X["rows"]>> : never : never : never;
|
|
6486
|
+
/**
|
|
6487
|
+
* One operation's result on the model delegate `Delegate` it would run on,
|
|
6488
|
+
* as `ExtendedOperationResult` types it for that delegate's client. A model
|
|
6489
|
+
* method declared with a `this` parameter types its result with it, so the
|
|
6490
|
+
* result follows every extension applied after the method's own:
|
|
6491
|
+
* `restore<Self, A>(this: Self, args: A): PendingOperation<
|
|
6492
|
+
* DelegateOperationResult<Self, "update", A>>`.
|
|
6493
|
+
*/
|
|
6494
|
+
type DelegateOperationResult<Delegate, O$1 extends Operations, Args> = Delegate extends DelegateState<infer C extends VibORMConfig, infer Rows extends string, infer Result extends object, infer K> ? [keyof Result] extends [never] ? DelegateRow<C, Rows, K & keyof ClientSchema<C>, O$1, Args> : O$1 extends Exclude<Operations, ComputedOperation> ? DelegateRow<C, Rows, K & keyof ClientSchema<C>, O$1, Args> : WithComputedResult<DelegateRow<C, Rows, K & keyof ClientSchema<C>, O$1, Args>, ClientSchema<C>[K & keyof ClientSchema<C>], Args, ComputedResultContext<Result, ClientSchema<C>, K>> : unknown;
|
|
6495
|
+
type DelegateRow<C$1 extends VibORMConfig, Rows$1 extends string, K$1 extends keyof ClientSchema<C$1>, O$1 extends Operations, Args> = ContextualOperationResult<C$1, K$1, O$1, Args, ClientRowsContext<C$1, Rows$1>>;
|
|
6496
|
+
/**
|
|
6497
|
+
* VibORM Client
|
|
6498
|
+
*/
|
|
6499
|
+
|
|
6447
6500
|
/**
|
|
6448
6501
|
* Create a VibORM client
|
|
6449
6502
|
*
|
|
@@ -13369,6 +13422,12 @@ interface DatabaseAdapter {
|
|
|
13369
13422
|
insertDefault: (table: Sql) => Sql;
|
|
13370
13423
|
/** UPDATE table SET ... WHERE ... */
|
|
13371
13424
|
update: (table: Sql, sets: Sql, where?: Sql) => Sql;
|
|
13425
|
+
/**
|
|
13426
|
+
* UPDATE table SET ... from `source` (a derived table, aliased) joined
|
|
13427
|
+
* `on` the row written, WHERE ...: `UPDATE … FROM` (PostgreSQL, SQLite),
|
|
13428
|
+
* `UPDATE … JOIN` (MySQL).
|
|
13429
|
+
*/
|
|
13430
|
+
updateFrom: (table: Sql, sets: Sql, source: Sql, on: Sql, where?: Sql) => Sql;
|
|
13372
13431
|
/** DELETE FROM table WHERE ... */
|
|
13373
13432
|
delete: (table: Sql, where?: Sql) => Sql;
|
|
13374
13433
|
/** RETURNING clause (PG/SQLite) or empty (MySQL) */
|
|
@@ -13713,6 +13772,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
|
|
|
13713
13772
|
recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
|
|
13714
13773
|
};
|
|
13715
13774
|
mutations: {
|
|
13775
|
+
updateFrom: (table: any, sets: any, source: any, on: any, where: any) => Sql;
|
|
13716
13776
|
returning: (_columns: Sql) => Sql;
|
|
13717
13777
|
onConflict: (_target: Sql | null, action: Sql, _targetWhere?: Sql) => Sql;
|
|
13718
13778
|
onConflictUpdate: (sets: Sql, _setWhere?: Sql) => Sql;
|
|
@@ -13966,6 +14026,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
|
|
|
13966
14026
|
upserted: Sql;
|
|
13967
14027
|
update: (table: Sql, sets: Sql, where?: Sql) => Sql;
|
|
13968
14028
|
delete: (table: Sql, where?: Sql) => Sql;
|
|
14029
|
+
updateFrom: (table: Sql, sets: Sql, source: Sql, on: Sql, where?: Sql) => Sql;
|
|
13969
14030
|
skipDuplicatesStrategy: "sql";
|
|
13970
14031
|
insert: (table: Sql, columns: string[], source: Sql[][] | {
|
|
13971
14032
|
readonly select: Sql;
|
|
@@ -14281,6 +14342,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
|
|
|
14281
14342
|
returning: (columns: Sql) => Sql;
|
|
14282
14343
|
update: (table: Sql, sets: Sql, where?: Sql) => Sql;
|
|
14283
14344
|
delete: (table: Sql, where?: Sql) => Sql;
|
|
14345
|
+
updateFrom: (table: Sql, sets: Sql, source: Sql, on: Sql, where?: Sql) => Sql;
|
|
14284
14346
|
skipDuplicatesStrategy: "sql";
|
|
14285
14347
|
insert: (table: Sql, columns: string[], source: Sql[][] | {
|
|
14286
14348
|
readonly select: Sql;
|
|
@@ -14330,4 +14392,4 @@ declare const mysqlAdapter: MySQLAdapter;
|
|
|
14330
14392
|
declare const postgresAdapter: PostgresAdapter;
|
|
14331
14393
|
declare const sqliteAdapter: SQLiteAdapter;
|
|
14332
14394
|
//#endregion
|
|
14333
|
-
export { ModelOperationInput as $,
|
|
14395
|
+
export { ModelOperationInput as $, MYSQL as $i, Model$1 as $n, JunctionReferentialAction as $r, ClientExtensionState as $t, Schema$1 as A, isCheckConstraintError as Ai, WithCacheOptions as An, IsoTimestampSchema as Ar, DelegateOperationResult as At, VariantToOneRelation as B, VibORMError as Bi, V$1 as Bn, toJsonSchema as Br, OfficialCacheExtension as Bt, Client as C, MigrationError as Ci, UnwrapPendingOperations as Cn, JsonSchema as Cr, s as Ct, OperationPayloadSchema as D, NotNullConstraintError as Di, CacheSetOptions as Dn, BaseIsoTimestampSchema as Dr, renderSchemaType as Dt, OperationPayload as E, ForeignKeyError as Ei, CacheEntry as En, BaseIsoTimeSchema as Er, renderOperationResultType as Et, LinkedClientConfig as F, CacheConfigurationError as Fi, BatchQuery as Fn, BaseBlobSchema as Fr, NoExtraDriverConfigKeys as Ft, ParseResult as G, wrapError as Gi, ModelFieldRefs as Gn, JsonNull as Gr, PlacedControl as Gt, BigIntScalar as H, isRetryableError as Hi, StringSchema as Hn, AnyJsonNullSentinel as Hr, DefinitionControls as Ht, Links$1 as I, CacheInvalidKeyError as Ii, CommittedBatchNotification as In, BlobSchema as Ir, VibORMClient as It, SchemaRegistryOperation as J, GeoBounds as Ji, AnyModel as Jn, isJsonNullSentinel as Jr, ClientExtension as Jt, Prettify as K, DiagnosticDisclosure as Ki, createModelFieldRefs as Kn, JsonNullKind as Kr, RowsVerbs as Kt, RelationLinks as L, CacheInvalidTTLError as Li, Dialect as Ln, BaseBigIntSchema as Lr, VibORMConfig as Lt, ClientSchema as M, isNotNullConstraintError as Mi, BatchTransactionOptions as Mn, EnumSchema as Mr, ExtendedClient as Mt, FlatSchema as N, isUniqueConstraintError as Ni, DriverTransactionOptions as Nn, BaseBooleanSchema as Nr, ExtendedOperationResult as Nt, OperationResult as O, UniqueConstraintError as Oi, WaitUntilFn as On, IsoDateSchema as Or, validateOperationPayload as Ot, Linked as P, isValueTooLongError as Pi, TransactionOptionSupport as Pn, BooleanSchema as Pr, ExtensionState as Pt, ModelCoreSchemas as Q, Decimal as Qi, InitialModelState as Qn, Getter as Qr, AccumulatedExtensionState as Qt, ModelShape as R, CacheOperationNotCacheableError as Ri, QueryExecutionContext as Rn, BigIntSchema as Rr, createClient as Rt, CachedClient as S, isUnsupportedOperationError as Si, UnwrapPendingOperation as Sn, InputJsonValue as Sr, ModelToManyRelation as St, MutationOperations as T, CheckConstraintError as Ti, CacheDriver as Tn, BaseIsoDateSchema as Tr, getOperationPayloadSchema as Tt, InferInput as U, isVibORMError as Ui, AnyFieldRef as Un, AnyNull as Ur, NoControls as Ut, type Scalar as V, VibORMErrorCode as Vi, v as Vn, createSchemaRegistry as Vr, WriteOutcome as Vt, InferOutput as W, toPrismaErrorCode as Wi, FieldRef as Wn, DbNull as Wr, OrderTerm as Wt, ModelArgsSchemas as X, GeoPolygon as Xi, IndexOptions as Xn, inferred as Xr, StatementContext as Xt, VibSchema as Y, GeoPoint as Yi, IndexDefinition as Yn, JsonSchema$1 as Yr, defineExtension as Yt, ModelCoreInput as Z, DecimalDescriptor as Zi, IndexType as Zn, AnyRelation as Zr, StatementHandler as Zt, ObservationCompletion as _, QueryError as _i, Severity as _n, BaseIntegerSchema as _r, DateScalar as _t, PostgresAdapter as a, isValidationError as ai, ResultConsumerContextOf as an, AutoGenerateType as ar, CoreSchemas as at, OFFICIAL_INSTRUMENTATION_NAME as b, isNotFoundError as bi, Schema$3 as bn, NumberSchema as br, ModelToOneRelation as bt, Operation as c, ClientInitializationError as ci, CountResultType as cn, ScalarState as cr, StringScalar as ct, MigrationSessionAttestation as d, ForbiddenError as di, RawOperation as dn, parse as dr, JsonScalar as dt, NativeType as ea, ReferentialAction as ei, EmptyClientExtensionState as en, ModelInternal as er, ModelRelationNestedInput as et, SQLITE_MIGRATION_CAPABILITY as f, NestedWriteAssertionError as fi, validateSchema as fn, BaseVectorSchema as fr, IntScalar as ft, MigrationNamespaceAttestation as g, QueryEngineError as gi, SchemaValidationIssue as gn, ObjectSchema as gr, DateTimeScalar as gt, DriverResultParser as h, PendingOperationError as hi, isSchemaValidationError as hn, PointSchema as hr, TimeScalar as ht, SQLiteAdapter as i, ValidationErrorSource as ii, MergeExtensionState as in, AutoGenerate as ir, ArgsSchemas as it, ValidatedOperationPayload as j, isForeignKeyError as ji, sqliteResultParser as jn, BaseEnumSchema as jr, DriverConfig as jt, Operations as k, ValueTooLongError as ki, CacheInvalidationOptions as kn, IsoTimeSchema as kr, ClientTypeState as kt, AnyDriver as l, ConnectionError as li, GroupByResultType as ln, ScalarType as lr, PointScalar as lt, PinnedSessionReservation as m, NotFoundError as mi, SchemaValidationError as mn, BasePointSchema as mr, DecimalScalar as mt, postgresAdapter as n, PG as na, RelationSlot as ni, ExtensionContributionState as nn, UpdateState as nr, ModelStateSchemas as nt, MySQLAdapter as o, InvalidTransactionInputError as oi, AggregateResultType as on, GeneratorDefaultBrand as or, NumericScalar as ot, SqliteMigrationCapability as p, NestedWriteError as pi, validateSchemaOrThrow as pn, VectorSchema as pr, EnumScalar as pt, SchemaRegistryLookup as q, GeoArea as qi, isFieldRef as qn, JsonNullSentinel as qr, StampedFields as qt, sqliteAdapter as r, SQLITE as ra, ValidationError as ri, ExtensionResultConsumerState as rn, DecimalSchema as rr, ScalarSchemas as rt, DatabaseAdapter as s, TransactionError as si, BatchPayload as sn, InitialScalarState as sr, VectorScalar as st, mysqlAdapter as t, NativeTypeMap as ta, RelationCardinality as ti, ExtensionCacheState as tn, ModelState as tr, ModelSchemas as tt, Driver as u, FeatureNotSupportedError as ui, InferSelectInclude as un, UpdateState$1 as ur, NumberScalar as ut, ObservationUnit as v, UnsupportedOperationError as vi, ValidationResult$1 as vn, BaseNumberSchema as vr, BooleanScalar as vt, InferDatabase as w, isMigrationError as wi, isPendingOperation as wn, JsonValue as wr, getSchemas as wt, CacheableOperations as x, isPendingOperationError as xi, PendingOperation as xn, BaseJsonSchema as xr, ReferencesStage as xt, ObserveHandler as y, isClientInitializationError as yi, DateTimePhysicalForm as yn, IntegerSchema as yr, BlobScalar as yt, VariantToManyRelation as z, PrismaErrorCode as zi, QueryResult as zn, createJsonSchemaConverter as zr, defaultOmit as zt };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $n as
|
|
2
|
-
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-
|
|
3
|
-
export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, type ClientTypeState, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
|
|
1
|
+
import { $n as Model, $t as ClientExtensionState, Ai as isCheckConstraintError, Ar as IsoTimestampSchema, At as DelegateOperationResult, B as VariantToOneRelation, Bi as VibORMError, Ci as MigrationError, Cn as UnwrapPendingOperations, Cr as JsonSchema, Ct as s, Di as NotNullConstraintError, Dt as renderSchemaType, Ei as ForeignKeyError, Et as renderOperationResultType, F as LinkedClientConfig, Fi as CacheConfigurationError, Gi as wrapError, Gn as ModelFieldRefs, Gr as JsonNull, Gt as PlacedControl, H as BigIntScalar, Hi as isRetryableError, Hn as StringSchema, Hr as AnyJsonNullSentinel, I as Links, Ii as CacheInvalidKeyError, Ir as BlobSchema, It as VibORMClient, Ji as GeoBounds, Jn as AnyModel, Jr as isJsonNullSentinel, Jt as ClientExtension, Ki as DiagnosticDisclosure, Kn as createModelFieldRefs, Kr as JsonNullKind, L as RelationLinks, Li as CacheInvalidTTLError, Lt as VibORMConfig, M as ClientSchema, Mi as isNotNullConstraintError, Mr as EnumSchema, Mt as ExtendedClient, N as FlatSchema, Ni as isUniqueConstraintError, Nt as ExtendedOperationResult, Oi as UniqueConstraintError, Or as IsoDateSchema, Ot as validateOperationPayload, P as Linked, Pi as isValueTooLongError, Pr as BooleanSchema, Pt as ExtensionState, Qi as Decimal, Qn as InitialModelState, Qr as Getter, Qt as AccumulatedExtensionState, R as ModelShape, Ri as CacheOperationNotCacheableError, Rr as BigIntSchema, Rt as createClient, Si as isUnsupportedOperationError, Sn as UnwrapPendingOperation, Sr as InputJsonValue, St as ModelToManyRelation, Ti as CheckConstraintError, Tt as getOperationPayloadSchema, Ui as isVibORMError, Un as AnyFieldRef, Ur as AnyNull, Ut as NoControls, V as Scalar, Vi as VibORMErrorCode, Wi as toPrismaErrorCode, Wn as FieldRef, Wr as DbNull, Xi as GeoPolygon, Xn as IndexOptions, Xt as StatementContext, Y as VibSchema, Yi as GeoPoint, Yn as IndexDefinition, Yt as defineExtension, Zi as DecimalDescriptor, Zr as AnyRelation, Zt as StatementHandler, _ as ObservationCompletion, _i as QueryError, _n as Severity, _t as DateScalar, ai as isValidationError, bi as isNotFoundError, br as NumberSchema, bt as ModelToOneRelation, ci as ClientInitializationError, cr as ScalarState, ct as StringScalar, di as ForbiddenError, dn as RawOperation, dt as JsonScalar, ei as ReferentialAction, en as EmptyClientExtensionState, er as ModelInternal, fi as NestedWriteAssertionError, fn as validateSchema, ft as IntScalar, gi as QueryEngineError, gn as SchemaValidationIssue, gr as ObjectSchema, gt as DateTimeScalar, hi as PendingOperationError, hn as isSchemaValidationError, hr as PointSchema, ht as TimeScalar, ii as ValidationErrorSource, in as MergeExtensionState, ir as AutoGenerate, ji as isForeignKeyError, ki as ValueTooLongError, kr as IsoTimeSchema, kt as ClientTypeState, li as ConnectionError, lt as PointScalar, mi as NotFoundError, mn as SchemaValidationError, mt as DecimalScalar, ni as RelationSlot, nn as ExtensionContributionState, nr as UpdateState, oi as InvalidTransactionInputError, or as GeneratorDefaultBrand, ot as NumericScalar, pi as NestedWriteError, pn as validateSchemaOrThrow, pr as VectorSchema, pt as EnumScalar, qi as GeoArea, qn as isFieldRef, qr as JsonNullSentinel, ri as ValidationError, rn as ExtensionResultConsumerState, rr as DecimalSchema, si as TransactionError, sr as InitialScalarState, st as VectorScalar, ti as RelationCardinality, tn as ExtensionCacheState, tr as ModelState, ui as FeatureNotSupportedError, ur as UpdateState$1, ut as NumberScalar, v as ObservationUnit, vi as UnsupportedOperationError, vn as ValidationResult, vt as BooleanScalar, wi as isMigrationError, wn as isPendingOperation, wr as JsonValue, wt as getSchemas, xi as isPendingOperationError, xn as PendingOperation, xt as ReferencesStage, y as ObserveHandler, yi as isClientInitializationError, yr as IntegerSchema, yt as BlobScalar, z as VariantToManyRelation, zi as PrismaErrorCode } from "./index-DBhpNR0X.mjs";
|
|
2
|
+
import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-D7JnXgUh.mjs";
|
|
3
|
+
export { type AccumulatedExtensionState, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, type AutoGenerate, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CheckConstraintError, type ClientExtension, type ClientExtensionState, ClientInitializationError, type ClientSchema, type ClientTypeState, ConnectionError, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DelegateOperationResult, type DiagnosticDisclosure, type EmptyClientExtensionState, type EnumScalar, type EnumSchema, type ExtendedClient, type ExtendedOperationResult, type ExtensionCacheState, type ExtensionContributionState, type ExtensionResultConsumerState, type ExtensionState, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, type MergeExtensionState, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoControls, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, PendingOperation, PendingOperationError, type PlacedControl, type PointScalar, type PointSchema, type PrismaErrorCode, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type Scalar, type ScalarState, type UpdateState$1 as ScalarUpdateState, SchemaValidationError, type SchemaValidationIssue, type Severity, Sql, type StatementContext, type StatementHandler, type StringScalar, type StringSchema, type TimeScalar, TransactionError, UniqueConstraintError, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, createClient, createModelFieldRefs, defineExtension, empty, getOperationPayloadSchema, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, raw, renderOperationResultType, renderSchemaType, s, sqlTag as sql, toPrismaErrorCode, validateOperationPayload, validateSchema, validateSchemaOrThrow, wrapError };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./chain--uZ0O7_Y.mjs";import{a as n,i as r,n as i,o as a,r as o,t as s}from"./base-wlv81COV.mjs";import{g as c,h as l,m as u,p as d}from"./observation-BcT8Cs3d.mjs";import{C as f,D as p,E as m,O as h,S as g,T as _,b as v,w as y,x as b,y as x}from"./error-mapping-D--MVRCY.mjs";import{n as S,t as C}from"./migrations-OE5D32qo.mjs";import{c as w,d as T,f as E,g as D,h as O,i as k,l as A,m as j,n as M,o as N,p as P,r as F,s as I,t as L,u as R}from"./query-CTna5P9o.mjs";import{n as z,t as B}from"./transaction-D5LHYn-r.mjs";import{n as V,t as H}from"./validation-pfpKPPZ_.mjs";import{D as U,E as W,O as G,P as K,T as q,j as J,k as Y}from"./v-C2XN11Gy.mjs";import{L as X}from"./geo-point-codec-CIZxuIvE.mjs";import{a as Z,i as Q,n as $,o as ee,r as te,t as ne}from"./sql-BsBoKwaf.mjs";import{d as re,f as ie}from"./scalar-BgxfbRLw.mjs";import{a as ae,i as oe}from"./validator-DqI5RlVU.mjs";import{n as se}from"./builder-Ct1qPFc8.mjs";import{d as ce,m as le}from"./result-shape-DwoSyWnq.mjs";import{t as ue}from"./client-BAxU6jnw.mjs";import{i as de,n as fe,r as pe,t as me}from"./schema-introspection-BFDAX5Ol.mjs";import{t as he}from"./schema-CT57uls5.mjs";const getSchemas=e=>se(e).proxy;export{q as AnyNull,d as CacheConfigurationError,u as CacheInvalidKeyError,l as CacheInvalidTTLError,c as CacheOperationNotCacheableError,x as CheckConstraintError,L as ClientInitializationError,M as ConnectionError,W as DbNull,X as Decimal,F as FeatureNotSupportedError,k as ForbiddenError,v as ForeignKeyError,B as InvalidTransactionInputError,U as JsonNull,G as JsonNullSentinel,C as MigrationError,N as NestedWriteAssertionError,I as NestedWriteError,w as NotFoundError,b as NotNullConstraintError,ce as PendingOperation,A as PendingOperationError,R as QueryEngineError,T as QueryError,re as SchemaValidationError,ne as Sql,z as TransactionError,g as UniqueConstraintError,E as UnsupportedOperationError,H as ValidationError,f as ValueTooLongError,s as VibORMError,i as VibORMErrorCode,ue as createClient,J as createModelFieldRefs,t as defineExtension,$ as empty,me as getOperationPayloadSchema,getSchemas,y as isCheckConstraintError,P as isClientInitializationError,K as isFieldRef,_ as isForeignKeyError,Y as isJsonNullSentinel,S as isMigrationError,j as isNotFoundError,m as isNotNullConstraintError,le as isPendingOperation,O as isPendingOperationError,o as isRetryableError,ie as isSchemaValidationError,te as isSql,p as isUniqueConstraintError,D as isUnsupportedOperationError,V as isValidationError,h as isValueTooLongError,r as isVibORMError,Q as join,Z as raw,fe as renderOperationResultType,pe as renderSchemaType,he as s,ee as sql,n as toPrismaErrorCode,de as validateOperationPayload,oe as validateSchema,ae as validateSchemaOrThrow,a as wrapError};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Bi as VibORMError, Ki as DiagnosticDisclosure, b as OFFICIAL_INSTRUMENTATION_NAME, c as Operation, y as ObserveHandler } from "./index-DBhpNR0X.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/instrumentation/types.d.ts
|
|
4
4
|
|
package/dist/instrumentation.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain-DVuRxjPO.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-wlv81COV.mjs";import{c as g,s as _,u as ee}from"./observation-BcT8Cs3d.mjs";import{t as te}from"./version-DvynkoaW.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,s as n}from"./value-guards-CK9guf2Z.mjs";import{f as r,t as i}from"./chain--uZ0O7_Y.mjs";import{C as a,D as o,E as s,S as c,T as l,g as u,m as d,p as f,s as p,x as m,y as h}from"./base-wlv81COV.mjs";import{c as g,s as _,u as ee}from"./observation-BcT8Cs3d.mjs";import{t as te}from"./version-DyH_HopX.mjs";const v=new Set([`deprecation`,`event`,`notice`,`status`]);function sanitizeLogMetadata(e,t){return f(e,v,t,!0)}function prettyLog(e){let t=e.timestamp.toISOString(),r=e.duration===void 0?``:`${e.duration}ms`,i=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,i||`query`,r].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,n(e.meta?.event)?e.meta.event:`unknown`,n(e.meta?.status)?`(${e.meta.status})`:``);break;case`warning`:console.warn(`[WARN]`,t,i,formatDiagnostic(e.meta));break;case`error`:console.error(`[ERROR]`,t,i,r),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function formatDiagnostic(e){return e===void 0?``:String(JSON.stringify(e))}function getHandler(e,t){let n=e[t];return n===void 0?e.all:n}function createLogger(e){let t=Object.freeze({includeParams:e.includeParams===!0,includeSql:e.includeSql===!0}),n=Object.freeze({cache:getHandler(e,`cache`),error:getHandler(e,`error`),query:getHandler(e,`query`),warning:getHandler(e,`warning`)});function sanitizeEvent(e,n){let r=t.includeParams&&e.params?d(e.params,t):void 0;return{level:n,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:t.includeSql?e.sql:void 0,params:r,error:e.error?u(e.error,t):void 0,meta:e.meta?sanitizeLogMetadata(e.meta,t):void 0}}function emit(e,t){try{let r=n[t];if(!r)return;let i=sanitizeEvent(e,t),defaultLog=()=>{try{prettyLog(i)}catch{}};r===!0?defaultLog():Promise.resolve(r(i,defaultLog)).catch(()=>void 0)}catch{}}return Object.freeze({log(e){emit(e,e.level)},query(e){emit(e,`query`)},cache(e){emit(e,`cache`)},warn(e){emit(e,`warning`)},error(e){emit(e,`error`)},isLevelEnabled(e){return n[e]!==void 0}})}const y=`viborm.operation`,b=`viborm.execute`,x=`viborm.transaction`,S=`viborm.connect`,C=`viborm.disconnect`,w=`db.system.name`,T=`db.namespace`,E=`db.collection.name`,D=`db.operation.name`,O=`db.query.text`,k=`db.query.summary`,A=`db.operation.batch.size`,j=`server.address`,M=`server.port`,N=`db.response.returned_rows`,P=`error.type`,F=`db.system.driver`,I=`viborm.correlation.id`,L=`db.query.parameter`,R=`viborm.cache.get`,z=`viborm.cache.set`,B=`viborm.cache.delete`,V=`viborm.cache.clear`,H=`viborm.cache.invalidate`,U=`cache.driver`,W=`cache.result`,G=`cache.ttl`,K={SpanStatusCode:{OK:1,ERROR:2}},q=te,J=Symbol(`viborm.shouldTraceSpan`),Y=new WeakMap,X=new WeakSet,Z={async startActiveSpan(e,t){return t()},isEnabled(){return!1}};Object.defineProperty(Z,J,{value:()=>!1}),Object.freeze(Z);function createTracerWrapper(e){let t=Object.freeze((e?.ignoreSpanTypes??[]).map(e=>n(e)?e:new RegExp(e.source,e.flags))),r=e?.includeSql===!0,i=e?.includeParams===!0;function shouldIgnoreSpan(e){return t.some(t=>n(t)?t===e:new RegExp(t.source,t.flags).test(e))}function buildAttributes(e){let t={...e.attributes};if(e.sql&&(r&&e.sql.query!==void 0&&(t[O]=e.sql.query),i&&e.sql.params)){let n=d(e.sql.params,{includeParams:!0,includeSql:r});for(let e=0;e<n.length;e++){let r=n[e];t[`${L}.${e}`]=formatSanitizedSpanParameter(r)}}return t}function presentThrough(e){return{async startActiveSpan(t,n){if(shouldIgnoreSpan(t.name))return n();let r=createExecution(n,K);try{let n=buildAttributes(t);Promise.resolve(e.startActiveSpan(t.name,e=>(setSpanAttributes(e,n),r(e)))).catch(()=>void 0)}catch{}return r()},isEnabled(){return!0}}}function autoDetect(){let e=null,t=null,n=!1;async function tryLoadOtel(){try{return e=await import(`@opentelemetry/api`),e}catch{return null}}function getTracer(e){return t||=e.trace.getTracer(`viborm`,q),t}let r=tryLoadOtel().then(e=>(n=!0,e)),i={async startActiveSpan(t,i){if(n||await r,!e||shouldIgnoreSpan(t.name))return i();let a,o;try{let n=buildAttributes(t),r=t.kind??e.SpanKind.INTERNAL,i=t.root?e.ROOT_CONTEXT:e.context.active();a=getTracer(e).startSpan(t.name,{kind:r,attributes:n},i),o=e.trace.setSpan(i,a)}catch{return i()}let s=createExecution(i,e);try{Promise.resolve(e.context.with(o,()=>s(a))).catch(()=>void 0)}catch{}return s(a)},isEnabled(){return e!==null}},a=r.then(()=>void 0);return Y.set(i,a),a.then(()=>Y.delete(i)),i}let a=e?.tracer,o=a===void 0?autoDetect():presentThrough(a);return Object.defineProperty(o,J,{value:e=>!shouldIgnoreSpan(e)}),Object.freeze(o)}function createExecution(e,t){let n=new Set,r,i,settle=(e,a)=>{r=e,i=a;for(let r of n)endSpan(r,e,t,a)},a,o=!1;return s=>{if(s!==void 0&&(n.add(s),r!==void 0&&endSpan(s,r,t,i)),a)return a;if(o)return Promise.reject(createTraceError());o=!0;try{return a=new Promise((t,n)=>{try{Promise.resolve(e(s)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),n(e)})}catch(e){settle(!0,e),n(e)}}),a}finally{o=!1}}}function endSpan(e,t,n,r){if(!X.has(e)){if(X.add(e),t){let t=c(r)?h(r):void 0,i=typeof t?.name==`string`?t.name:`Error`;safely(()=>e.setAttribute(`error.type`,i));let a=t?.code;typeof a==`string`&&safely(()=>e.setAttribute(`viborm.error.code`,a));let o=t?.meta;if(typeof o==`object`&&o&&`providerSqlState`in o&&typeof o.providerSqlState==`string`){let t=o.providerSqlState;safely(()=>e.setAttribute(`db.response.sqlstate`,t))}safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function prewarmTracer(e){return Y.get(e)}function shouldTraceSpan(e,t){try{let n=Reflect.get(e,J);return typeof n!=`function`||n(t)!==!1}catch{return!0}}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function formatSanitizedSpanParameter(e){return n(e)?e:String(JSON.stringify(e))}function getNoopTracer(){return Z}function createInstrumentationContext(e){let t=snapshotInstrumentationConfig(e),n;if(t.tracing){let e=t.tracing===!0?{}:t.tracing;n=createTracerWrapper({includeSql:e.includeSql,includeParams:e.includeParams,ignoreSpanTypes:e.ignoreSpanTypes,tracer:e.tracer})}else n=getNoopTracer();let r={config:t,tracer:n};return t.logging&&(r.logger=createLogger(t.logging===!0?{all:!0}:t.logging)),Object.freeze(r)}function snapshotInstrumentationConfig(e){let t=snapshotDisclosure(o(e,`diagnostics`)),n=o(e,`tracing`),r=o(e,`logging`),i=n===!0?!0:a(n)?snapshotTracingConfig(n):void 0,s=r===!0?!0:a(r)?snapshotLoggingConfig(r):void 0;return Object.freeze({diagnostics:t,tracing:i,logging:s})}function snapshotDisclosure(e){return Object.freeze({includeParams:a(e)&&o(e,`includeParams`)===!0,includeSql:a(e)&&o(e,`includeSql`)===!0,includeProviderDetails:a(e)&&o(e,`includeProviderDetails`)===!0,includeCallsite:a(e)&&o(e,`includeCallsite`)===!0})}function snapshotTracingConfig(e){let t=snapshotIgnorePatterns(o(e,`ignoreSpanTypes`)),n=o(e,`tracer`);return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,...t.length>0?{ignoreSpanTypes:t}:{},...isPlatformTracer(n)?{tracer:n}:{}})}function isPlatformTracer(e){return a(e)&&t(o(e,`startActiveSpan`))}function snapshotIgnorePatterns(e){if(!m(e))return Object.freeze([]);let t=[],r=Math.min(l(e),128);for(let i=0;i<r;i+=1){let r=s(e,String(i));if(!(r&&`value`in r))continue;let a=r.value;if(n(a)){t.push(a);continue}try{a instanceof RegExp&&t.push(Object.freeze(new RegExp(a.source,a.flags)))}catch{}}return Object.freeze(t)}function snapshotLoggingConfig(e){let t=readLogHandler(e,`all`),n=readLogHandler(e,`cache`),r=readLogHandler(e,`error`),i=readLogHandler(e,`query`),a=readLogHandler(e,`warning`);if(![t,n,r,i,a].every(e=>!e))return Object.freeze({includeParams:o(e,`includeParams`)===!0,includeSql:o(e,`includeSql`)===!0,all:t,cache:n,error:r,query:i,warning:a})}function readLogHandler(e,n){let r=o(e,n);return r===!0||t(r)?r:void 0}const ne={connect:S,disconnect:C,savepoint:x,transaction:x},Q={clear:V,delete:B,get:R,invalidate:H,revalidate:y,set:z};function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[w]:t,[F]:n,...r===void 0?{}:{[T]:r}}}function createCorrelationAttributes(e){let t=e?.correlationId;return t===void 0?{}:{[I]:t}}function createCacheSpanOptions(e,t){if(t.kind===`cache-backend`)return{name:Q[t.boundary],attributes:{[U]:t.driverName}};let{driverName:n,read:r,ttl:i}=t;return{name:Q[e],attributes:{...n===void 0?{}:{[U]:n},...i===void 0?{}:{[G]:String(i)},...r===void 0?{}:{...createDriverAttributes(r.identity),[E]:r.model,[D]:r.operation},...createCorrelationAttributes(t.context)},...r===void 0?{}:{root:!0}}}function presentCacheOutcome(e,t){let{error:n}=t;return Object.freeze({timestamp:new Date(t.at),model:e?.model,operation:e?.operation,correlationId:e?.correlationId,error:n instanceof Error?u(n):void 0,meta:Object.freeze({event:t.event,status:t.status})})}function createOperationSpanOptions(e){let{collection:t}=e;return{name:y,attributes:{...createDriverAttributes(e.identity),...t===void 0?{}:{[E]:t},[D]:e.requestedOperation,...createCorrelationAttributes(e.context)}}}function createOperationErrorLogEvent(e,t,n,r,i){return Object.freeze({timestamp:new Date(r),error:u(n),model:e.model,operation:e.operation,correlationId:t,duration:i})}function readChannelDisclosure(e){return e&&e!==!0?e:p}function createContextAttributes(e,t){let{model:n,operation:i,correlationId:a}=t;return{...createDriverAttributes(r(e)),...n?{[E]:n}:{},...i?{[D]:i}:{},...a?{[I]:a}:{}}}function createStatementSpanOptions(e,t){let{includeParams:n,includeSql:r}=readChannelDisclosure(e);return{name:b,attributes:createContextAttributes(t.driver,t.context),...r||n?{sql:{...r?{query:t.sql}:{},...n?{params:t.params}:{}}}:{}}}function createLifecycleSpanOptions(e){return{name:ne[e.boundary],attributes:createContextAttributes(e.driver,e.context)}}function createStatementLogEvent(e,t,n){let{context:r,endedAt:i,failure:a}=e,o=readChannelDisclosure(n);return Object.freeze({timestamp:new Date(i),duration:i-t,model:r.model,operation:r.operation,correlationId:r.correlationId,sql:o.includeSql?e.sql:void 0,params:o.includeParams?e.params:void 0,error:a===void 0?void 0:u(a,o)})}const $=new WeakMap;function instrumentation(e){let t=createInstrumentationContext(e),n=Object.freeze({observesLifecycle:t.config.tracing!==void 0||t.config.logging!==void 0,...t.config.tracing===void 0?{}:{prewarm:()=>prewarmTracer(t.tracer)},diagnostics:t.config.diagnostics,wants:e=>wants(t,e),warn:e=>warn(t,e)}),r=function officialInstrumentationObserver(){};return $.set(n,t),ee(r,n,(e,n)=>observeOfficialInstrumentation(t,e,n)),Object.freeze({name:i,observe:r})}function wants(e,t){switch(t){case`operation`:return traces(e,y);case`statement`:return traces(e,b);case`transaction`:case`savepoint`:return traces(e,x);case`connect`:return traces(e,S);case`disconnect`:return traces(e,C);case`cache`:return e.config.tracing!==void 0;case`cache-outcomes`:return logs(e,`cache`);case`query-log`:return logs(e,`query`);case`error-log`:return logs(e,`error`);default:return disclosesParameters(e)}}function traces(e,t){return e.config.tracing!==void 0&&shouldTraceSpan(e.tracer,t)}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function disclosesParameters(e){let{logging:t,tracing:n}=e.config;return t!==void 0&&t!==!0&&t.includeParams===!0&&(logs(e,`query`)||logs(e,`error`))?!0:n!==void 0&&n!==!0&&n.includeParams===!0&&shouldTraceSpan(e.tracer,b)}function warn(e,t){let n=e.logger;return n?.isLevelEnabled(`warning`)===!0?(n.warn({timestamp:new Date,model:t.model,operation:t.operation,correlationId:t.correlationId,meta:{notice:t.message}}),!0):!1}function observeOfficialInstrumentation(e,t,n){let r=g(t);if(t.kind===`cache`&&(r?.kind===`cache`||r?.kind===`cache-backend`))return observeCacheInstrumentation(e,t.operation,t,r,n);if(r?.kind===`statement`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,wants(e,`statement`)?createStatementSpanOptions(e.config.tracing,n):void 0,()=>observeStatementCompletion(t,i,n.startedAt)))}if(r?.kind===`driver-lifecycle`){let i=n();return r.dispatch.then(n=>n===void 0?observeLifecycleCompletion(i):presentDispatch(e,n.start,createLifecycleSpanOptions(n),()=>observeLifecycleCompletion(i,t)))}if(r?.kind!==`operation`)return n();let i=r.context.correlationId,observeCompletion=()=>n().then(n=>{let a=_(t);if(a?.kind===`operation`){let{failure:t,readCacheOutcomes:o}=a;if(o!==void 0)for(let t of o())e.logger?.cache(presentCacheOutcome(r.context,t));t!==void 0&&a.skipLog!==!0&&e.logger?.error(createOperationErrorLogEvent(r,i,t,a.endedAt,n.durationMs))}if(n.status===`failure`)throw createObservedFailure(a?.kind===`operation`?a.failure:void 0)});return e.config.tracing===void 0?observeCompletion():e.tracer.startActiveSpan(createOperationSpanOptions(r),observeCompletion)}function observeCacheInstrumentation(e,t,n,r,i){let{logger:a,tracer:o}=e,s=wants(e,`cache`),c=r.kind===`cache`?r.context:void 0,l=r.kind===`cache`&&wants(e,`cache-outcomes`),u=Date.now(),observeCompletion=async e=>{l&&t===`revalidate`&&a?.cache(presentCacheOutcome(c,{event:`revalidate`,status:`start`,at:u}));let r=await i(),o=_(n);if(o?.kind===`cache`&&(s&&o.result!==void 0&&setSpanAttributes(e,{[W]:o.result}),l&&o.outcomes!==void 0))for(let e of o.outcomes)a?.cache(presentCacheOutcome(c,e));if(r.status===`failure`)throw createObservedFailure()};return s?o.startActiveSpan(createCacheSpanOptions(t,r),observeCompletion):observeCompletion()}async function presentDispatch(e,t,n,r){if(n===void 0)return t(),r();try{return await e.tracer.startActiveSpan(n,()=>(t(),r()))}finally{t()}}async function observeStatementCompletion(e,t,n){let r=await t,i=_(e);if(i?.kind===`statement`&&i.skipLog!==!0){let e=$.get(i.capability),t=createStatementLogEvent(i,n,e?.config.logging);i.failure===void 0?e?.logger?.query(t):e?.logger?.error(t)}if(r.status===`failure`&&!(i?.kind===`statement`&&i.recovered))throw createObservedFailure(i?.kind===`statement`?i.failure:void 0)}async function observeLifecycleCompletion(e,t){let n=await e,r=t&&_(t);if(n.status===`failure`)throw createObservedFailure(r?.kind===`driver-lifecycle`?r.failure:void 0)}function createObservedFailure(e){if(e)return u(e);let t=Error(`Operation failed`);return t.stack=void 0,t}export{U as ATTR_CACHE_DRIVER,W as ATTR_CACHE_RESULT,G as ATTR_CACHE_TTL,A as ATTR_DB_BATCH_SIZE,E as ATTR_DB_COLLECTION,F as ATTR_DB_DRIVER,T as ATTR_DB_NAMESPACE,D as ATTR_DB_OPERATION_NAME,L as ATTR_DB_QUERY_PARAMETER_PREFIX,k as ATTR_DB_QUERY_SUMMARY,O as ATTR_DB_QUERY_TEXT,N as ATTR_DB_ROWS_RETURNED,w as ATTR_DB_SYSTEM,P as ATTR_ERROR_TYPE,j as ATTR_SERVER_ADDRESS,M as ATTR_SERVER_PORT,I as ATTR_VIBORM_CORRELATION_ID,V as SPAN_CACHE_CLEAR,B as SPAN_CACHE_DELETE,R as SPAN_CACHE_GET,H as SPAN_CACHE_INVALIDATE,z as SPAN_CACHE_SET,S as SPAN_CONNECT,C as SPAN_DISCONNECT,b as SPAN_EXECUTE,y as SPAN_OPERATION,x as SPAN_TRANSACTION,instrumentation};
|
|
2
2
|
//# sourceMappingURL=instrumentation.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BuuaeEvq.mjs";import{m as t}from"./observation-BcT8Cs3d.mjs";import{M as n,P as r,_ as i,k as a}from"./v-
|
|
2
|
-
//# sourceMappingURL=key-
|
|
1
|
+
import{n as e}from"./chunk-BuuaeEvq.mjs";import{m as t}from"./observation-BcT8Cs3d.mjs";import{M as n,P as r,_ as i,k as a}from"./v-C2XN11Gy.mjs";import{r as o}from"./sql-BsBoKwaf.mjs";const s=`viborm`,c=`${s}:cache`;function encodeText(e){let t=``;for(let n=0;n<e.length;n+=1)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t}function encodeVersion(e){if(e===void 0)return`u`;if(typeof e==`number`){let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e,!1);let n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return`n:${n}`}return`s:${encodeText(e)}`}function encodeNamespace(e){return e===void 0?`x`:`k:${encodeText(e)}`}function createOfficialCacheNamespace(e){return[c,`r4`,`d:${encodeText(e.dialect)}`,encodeNamespace(e.namespace),encodeVersion(e.version)].join(`:`)}function cacheLookupOf(e,t,n){let r=stableStringify(n);return{key:`${e}:${t}:${fastHash(r)}`,identity:JSON.stringify([e,t,r])}}function brandToken(e,t){return`viborm.${e}:${t}`}function stableStringify(e,i=new WeakSet){if(e===null)return`null`;if(e===void 0)return``;let s=typeof e;if(s===`boolean`||s===`number`)return String(e);if(s===`string`)return JSON.stringify(e);if(s===`bigint`)return brandToken(`bigint`,String(e));if(s!==`object`)throw new t(`Uncacheable value type: ${s}`);if(o(e)&&typeof e.toStatement==`function`)return brandToken(`sql`,`${JSON.stringify(e.toStatement(`?`))}:${stableStringify(e.values,i)}`);if(r(e)){let t=n(e);return brandToken(`field-ref`,`${JSON.stringify(t.model)}:${JSON.stringify(t.field)}`)}if(a(e))return brandToken(`json-null`,e.kind);if(e instanceof Date)return brandToken(`date`,e.toISOString());if(e instanceof Uint8Array){let t;if(typeof Buffer<`u`)t=Buffer.from(e).toString(`base64`);else{let n=``;for(let t of e)n+=String.fromCharCode(t);t=btoa(n)}return brandToken(`bytes`,t)}if(i.has(e))throw new t(`Circular reference in cache key args`);i.add(e);let c;if(Array.isArray(e))c=`[${e.map(e=>stableStringify(e,i)).join(`,`)}]`;else{let t=e;c=`{${Object.keys(t).sort().filter(e=>t[e]!==void 0).map(e=>`${JSON.stringify(e)}:${stableStringify(t[e],i)}`).join(`,`)}}`}return i.delete(e),c}function isCanonicalKeyData(e){try{return hasCanonicalForm(e,new Set)}catch{return!1}}function hasCanonicalForm(e,t){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:case`bigint`:return!0;case`number`:return Number.isFinite(e);case`object`:break;default:return!1}if(e instanceof Date)return!Number.isNaN(e.getTime());if(e instanceof Uint8Array)return!0;if(t.has(e)||!(Array.isArray(e)||i(e)))return!1;t.add(e);let n=Object.values(e).every(e=>hasCanonicalForm(e,t));return t.delete(e),n}function fastHash(e){let t=3735928559,n=1103547991;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=Math.imul(t^i,2654435761),n=Math.imul(n^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),(n>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}export{isCanonicalKeyData as a,createOfficialCacheNamespace as i,c as n,stableStringify as o,cacheLookupOf as r,s as t};
|
|
2
|
+
//# sourceMappingURL=key-QgLg2Kve.mjs.map
|