viborm 1.14.1 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/adapters.d.mts +1 -1
  2. package/dist/bun-sql.d.mts +1 -1
  3. package/dist/bun-sqlite.d.mts +1 -1
  4. package/dist/cache/cloudflare-kv.d.mts +1 -1
  5. package/dist/cache/memory.d.mts +1 -1
  6. package/dist/cache.d.mts +2 -2
  7. package/dist/cli.mjs +1 -1
  8. package/dist/{client-D1shn5AL.d.mts → client-CRxfhw2y.d.mts} +1 -1
  9. package/dist/{client-DzXpmSNi.mjs → client-y7TV0PRZ.mjs} +2 -2
  10. package/dist/client-y7TV0PRZ.mjs.map +1 -0
  11. package/dist/client.d.mts +2 -2
  12. package/dist/config.d.mts +1 -1
  13. package/dist/d1.d.mts +1 -1
  14. package/dist/{database-adapter-BD_htd5h.d.mts → database-adapter-BGqvjeEy.d.mts} +1 -1
  15. package/dist/{document-rMfLKZP5.d.mts → document-BVTQ-cF-.d.mts} +1 -1
  16. package/dist/{driver-CH9qAuft.d.mts → driver-BBEmaJZy.d.mts} +1 -1
  17. package/dist/driver.d.mts +1 -1
  18. package/dist/durable-object.d.mts +1 -1
  19. package/dist/{every-KV5yuSVT.mjs → every-tOgQmaIE.mjs} +2 -2
  20. package/dist/{every-KV5yuSVT.mjs.map → every-tOgQmaIE.mjs.map} +1 -1
  21. package/dist/{exports-nYDS0SZ7.d.mts → exports-COCJ8f2f.d.mts} +1 -1
  22. package/dist/index.d.mts +1 -1
  23. package/dist/index.mjs +1 -1
  24. package/dist/instrumentation.d.mts +1 -1
  25. package/dist/instrumentation.mjs +1 -1
  26. package/dist/{introspect-DD_5FEl0.mjs → introspect-Bm6xnXcG.mjs} +2 -2
  27. package/dist/{introspect-DD_5FEl0.mjs.map → introspect-Bm6xnXcG.mjs.map} +1 -1
  28. package/dist/libsql.d.mts +1 -1
  29. package/dist/migrations/mysql.d.mts +4 -4
  30. package/dist/migrations/mysql.mjs +1 -1
  31. package/dist/migrations/postgres.d.mts +4 -4
  32. package/dist/migrations/postgres.mjs +1 -1
  33. package/dist/migrations/snowflake.d.mts +4 -4
  34. package/dist/migrations/snowflake.mjs +1 -1
  35. package/dist/migrations/sqlite.d.mts +4 -4
  36. package/dist/migrations/sqlite.mjs +1 -1
  37. package/dist/migrations/surrealdb.d.mts +4 -4
  38. package/dist/migrations/surrealdb.mjs +1 -1
  39. package/dist/migrations/tenant.d.mts +2 -2
  40. package/dist/migrations/tenant.mjs +1 -1
  41. package/dist/migrations.d.mts +4 -4
  42. package/dist/migrations.mjs +1 -1
  43. package/dist/mysql2.d.mts +1 -1
  44. package/dist/neon-http.d.mts +1 -1
  45. package/dist/{object-store-0zc3XYcO.d.mts → object-store-B_YMoW8u.d.mts} +3 -3
  46. package/dist/on.d.mts +1 -1
  47. package/dist/ordering.d.mts +1 -1
  48. package/dist/permissions.d.mts +1 -1
  49. package/dist/pg.d.mts +1 -1
  50. package/dist/pglite.d.mts +1 -1
  51. package/dist/planetscale.d.mts +1 -1
  52. package/dist/{planner-uYQS0hif.d.mts → planner-DHjdvjwk.d.mts} +1 -1
  53. package/dist/postgres.d.mts +1 -1
  54. package/dist/schema/introspect.d.mts +2 -2
  55. package/dist/schema/introspect.mjs +1 -1
  56. package/dist/schema/json.d.mts +2 -2
  57. package/dist/schema.d.mts +1 -1
  58. package/dist/snowflake.d.mts +1 -1
  59. package/dist/soft-delete.d.mts +1 -1
  60. package/dist/sqlite3.d.mts +1 -1
  61. package/dist/surrealdb.d.mts +1 -1
  62. package/dist/surrealdb.mjs +1 -1
  63. package/dist/surrealdb.mjs.map +1 -1
  64. package/dist/{surrealql-DpipDgMB.mjs → surrealql-C1dp1sWw.mjs} +2 -2
  65. package/dist/surrealql-C1dp1sWw.mjs.map +1 -0
  66. package/dist/validation.d.mts +1 -1
  67. package/dist/version-CXGIA82S.mjs +2 -0
  68. package/dist/{version-DRfmNoR1.mjs.map → version-CXGIA82S.mjs.map} +1 -1
  69. package/package.json +1 -1
  70. package/dist/client-DzXpmSNi.mjs.map +0 -1
  71. package/dist/surrealql-DpipDgMB.mjs.map +0 -1
  72. package/dist/version-DRfmNoR1.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $r as OperationPayloadSchema, B as StampedFields, Cr as renderSchemaType, Dr as UnwrapPendingOperation, Er as PendingOperation, J as AddedProjectedState, Jr as Client, Kr as CacheableOperations, L as PlacedArgument, Li as IndexDefinition, Or as UnwrapPendingOperations, Qr as OperationPayload, Ri as IndexOptions, Sr as renderOperationResultType, Tr as ProjectedModelOperations, Vt as VibSchema, X as ClientTypeState, Xr as MutationOperations, Y as CachedClientOf, Yr as InferDatabase, Zr as NoExtraOperationKeys, _t as RowsFragment, aa as ObjectSchema, ai as BatchPayload, ci as GroupByResultType, di as FlatSchema, ei as OperationResult, fi as Linked, gt as RawOperation, hi as RelationLinks, ii as AggregateResultType, kr as isPendingOperation, li as InferSelectInclude, mi as Links, mt as ExtensionResultConsumerState, ni as Schema, nt as ExtendedClient, oi as ClientHiddenContext, pi as LinkedClientConfig, qr as CachedClient, ri as ValidatedOperationPayload, si as CountResultType, ti as Operations, ui as ClientSchema, wr as validateOperationPayload, xr as getOperationPayloadSchema } from "./database-adapter-BD_htd5h.mjs";
2
- import { n as ClientOmitConfig, r as ExactClientOmitConfig, t as defaultOmit } from "./exports-nYDS0SZ7.mjs";
1
+ import { $r as OperationPayloadSchema, B as StampedFields, Cr as renderSchemaType, Dr as UnwrapPendingOperation, Er as PendingOperation, J as AddedProjectedState, Jr as Client, Kr as CacheableOperations, L as PlacedArgument, Li as IndexDefinition, Or as UnwrapPendingOperations, Qr as OperationPayload, Ri as IndexOptions, Sr as renderOperationResultType, Tr as ProjectedModelOperations, Vt as VibSchema, X as ClientTypeState, Xr as MutationOperations, Y as CachedClientOf, Yr as InferDatabase, Zr as NoExtraOperationKeys, _t as RowsFragment, aa as ObjectSchema, ai as BatchPayload, ci as GroupByResultType, di as FlatSchema, ei as OperationResult, fi as Linked, gt as RawOperation, hi as RelationLinks, ii as AggregateResultType, kr as isPendingOperation, li as InferSelectInclude, mi as Links, mt as ExtensionResultConsumerState, ni as Schema, nt as ExtendedClient, oi as ClientHiddenContext, pi as LinkedClientConfig, qr as CachedClient, ri as ValidatedOperationPayload, si as CountResultType, ti as Operations, ui as ClientSchema, wr as validateOperationPayload, xr as getOperationPayloadSchema } from "./database-adapter-BGqvjeEy.mjs";
2
+ import { n as ClientOmitConfig, r as ExactClientOmitConfig, t as defaultOmit } from "./exports-COCJ8f2f.mjs";
3
3
  export { type AddedProjectedState, type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type CachedClientOf, type Client, type ClientHiddenContext, type ClientOmitConfig, type ClientSchema, type ClientTypeState, type CountResultType, type ExactClientOmitConfig, type ExtendedClient, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type NoExtraOperationKeys, type ObjectSchema, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedArgument, type ProjectedModelOperations, type RawOperation, type RelationLinks, type RowsFragment, type Schema, type StampedFields, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-uYQS0hif.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-DHjdvjwk.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-CrIB-3ZJ.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Fa as BatchQuery, Ia as CommittedBatchNotification, Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, it as NoExtraDriverConfigKeys, l as Driver, m as SqliteMigrationCapability, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, za as QueryResult } from "./database-adapter-BD_htd5h.mjs";
1
+ import { Fa as BatchQuery, Ia as CommittedBatchNotification, Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, it as NoExtraDriverConfigKeys, l as Driver, m as SqliteMigrationCapability, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
@@ -8038,7 +8038,7 @@ declare class DecimalScalar<out State$1 extends ScalarState<"decimal">> extends
8038
8038
  * a schema document round-trips to the same declaration. A value outside the
8039
8039
  * declared domain fails at the call that wrote it, not at the first write.
8040
8040
  */
8041
- default<V$2 extends DefaultValueInput<State$1>>(value: V$2): DecimalScalar<Omit<DecimalScalarState<State$1>, "default" | "optional" | "hasDefault"> & {
8041
+ default<V$2 extends DefaultValueInput<State$1>>(value: V$2): DecimalScalar<Omit<DecimalScalarState<State$1>, "optional" | "hasDefault" | "default"> & {
8042
8042
  readonly hasDefault: true;
8043
8043
  readonly default: unknown;
8044
8044
  readonly optional: true;
@@ -1,4 +1,4 @@
1
- import { Bo as NativeType, Da as ReferentialAction, Ea as JunctionReferentialAction, Ho as NativeTypeMap, Qi as JsonValue, Tt as AutoGenerateType, kt as ScalarType, zi as IndexType } from "./database-adapter-BD_htd5h.mjs";
1
+ import { Bo as NativeType, Da as ReferentialAction, Ea as JunctionReferentialAction, Ho as NativeTypeMap, Qi as JsonValue, Tt as AutoGenerateType, kt as ScalarType, zi as IndexType } from "./database-adapter-BGqvjeEy.mjs";
2
2
 
3
3
  //#region src/schema/json/document.d.ts
4
4
 
@@ -1,4 +1,4 @@
1
- import { lr as Database, wi as V } from "./database-adapter-BD_htd5h.mjs";
1
+ import { lr as Database, wi as V } from "./database-adapter-BGqvjeEy.mjs";
2
2
 
3
3
  //#region src/cache/cache-background.d.ts
4
4
 
package/dist/driver.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { Aa as sqliteResultParser, Fa as BatchQuery, Ka as ConnectionError, La as Dialect, Ra as QueryExecutionContext, To as isRetryableError, Wa as TransactionError, _ as DriverResultParser, co as CheckConstraintError, d as MigrationFrameDriver, do as UniqueConstraintError, eo as QueryError, l as Driver, lo as ForeignKeyError, m as SqliteMigrationCapability, p as SQLITE_MIGRATION_CAPABILITY, qa as FeatureNotSupportedError, s as AnyDriver, u as MigrationFrame, uo as NotNullConstraintError, za as QueryResult } from "./database-adapter-BD_htd5h.mjs";
1
+ import { Aa as sqliteResultParser, Fa as BatchQuery, Ka as ConnectionError, La as Dialect, Ra as QueryExecutionContext, To as isRetryableError, Wa as TransactionError, _ as DriverResultParser, co as CheckConstraintError, d as MigrationFrameDriver, do as UniqueConstraintError, eo as QueryError, l as Driver, lo as ForeignKeyError, m as SqliteMigrationCapability, p as SQLITE_MIGRATION_CAPABILITY, qa as FeatureNotSupportedError, s as AnyDriver, u as MigrationFrame, uo as NotNullConstraintError, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
2
2
  export { type AnyDriver, type BatchQuery, CheckConstraintError, ConnectionError, type Dialect, Driver, type DriverResultParser, FeatureNotSupportedError, ForeignKeyError, type MigrationFrame, type MigrationFrameDriver, NotNullConstraintError, QueryError, type QueryExecutionContext, type QueryResult, SQLITE_MIGRATION_CAPABILITY, type SqliteMigrationCapability, TransactionError, UniqueConstraintError, isRetryableError, sqliteResultParser };
@@ -1,4 +1,4 @@
1
- import { Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, h as TransactionBoundDriver, it as NoExtraDriverConfigKeys, l as Driver, m as SqliteMigrationCapability, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, u as MigrationFrame, za as QueryResult } from "./database-adapter-BD_htd5h.mjs";
1
+ import { Na as TransactionOptionSupport, Ra as QueryExecutionContext, _ as DriverResultParser, h as TransactionBoundDriver, it as NoExtraDriverConfigKeys, l as Driver, m as SqliteMigrationCapability, ni as Schema, pi as LinkedClientConfig, st as VibORMClient, t as DatabaseAdapter, tt as DriverConfig, u as MigrationFrame, za as QueryResult } from "./database-adapter-BGqvjeEy.mjs";
2
2
  import { DurableObjectStorage as DurableObjectStorage$1 } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/durable-object/index.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./serializer-rBq3v1xr.mjs";import{n,t as r}from"./libsql-DuGR904j.mjs";import{t as i}from"./mysql-BNXWfTOo.mjs";import{t as a}from"./postgres-CDdh5dSP.mjs";import{t as o}from"./snowflake-UOCC820W.mjs";import{t as s}from"./surrealql-DpipDgMB.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i),t(s),t(o)}export{registerEveryMigrationDriver as t};
2
- //# sourceMappingURL=every-KV5yuSVT.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./serializer-rBq3v1xr.mjs";import{n,t as r}from"./libsql-DuGR904j.mjs";import{t as i}from"./mysql-BNXWfTOo.mjs";import{t as a}from"./postgres-CDdh5dSP.mjs";import{t as o}from"./snowflake-UOCC820W.mjs";import{t as s}from"./surrealql-C1dp1sWw.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i),t(s),t(o)}export{registerEveryMigrationDriver as t};
2
+ //# sourceMappingURL=every-tOgQmaIE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"every-KV5yuSVT.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 { snowflakeMigrationDriver } from \"../drivers/snowflake\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\nimport { surrealMigrationDriver } from \"../drivers/surrealql\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n registerMigrationDriver(surrealMigrationDriver);\n registerMigrationDriver(snowflakeMigrationDriver);\n}\n"],"mappings":"kTAcA,SAAgB,8BAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB,CAC7C,EAAwB,EAAuB,CAC/C,EAAwB,EAAyB"}
1
+ {"version":3,"file":"every-tOgQmaIE.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 { snowflakeMigrationDriver } from \"../drivers/snowflake\";\nimport { sqlite3MigrationDriver } from \"../drivers/sqlite\";\nimport { surrealMigrationDriver } from \"../drivers/surrealql\";\n\nexport function registerEveryMigrationDriver(): void {\n registerMigrationDriver(postgresMigrationDriver);\n registerMigrationDriver(sqlite3MigrationDriver);\n registerMigrationDriver(libsqlMigrationDriver);\n registerMigrationDriver(mysqlMigrationDriver);\n registerMigrationDriver(surrealMigrationDriver);\n registerMigrationDriver(snowflakeMigrationDriver);\n}\n"],"mappings":"kTAcA,SAAgB,8BAAqC,CACnD,EAAwB,EAAwB,CAChD,EAAwB,EAAuB,CAC/C,EAAwB,EAAsB,CAC9C,EAAwB,EAAqB,CAC7C,EAAwB,EAAuB,CAC/C,EAAwB,EAAyB"}
@@ -1,4 +1,4 @@
1
- import { A as Extension, Ii as AnyModel, S as AnyTarget, j as Facts, ui as ClientSchema } from "./database-adapter-BD_htd5h.mjs";
1
+ import { A as Extension, Ii as AnyModel, S as AnyTarget, j as Facts, ui as ClientSchema } from "./database-adapter-BGqvjeEy.mjs";
2
2
 
3
3
  //#region src/client/omit.d.ts
4
4
 
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as DelegateOperationPayload, $a as QueryEngineError, $n as row, $t as VectorScalar, A as Extension, Ai as PointSchema, An as rule, Ar as WriteOutcome, At as UpdateState$1, B as StampedFields, Ba as ValidationError, Bi as InitialModelState, Bn as modelMethods, Br as SchemaValidationError, C as ArgTest, Ci as BlobScalar, Cn as run, Co as VibORMError, Cr as renderSchemaType, Ct as BigIntScalar, D as ConfiguredBy, Da as ReferentialAction, Di as VectorSchema, Dn as text, Do as toPrismaErrorCode, Dr as UnwrapPendingOperation, Dt as InitialScalarState, E as CallResult, En as table, Eo as isVibORMError, Er as PendingOperation, Et as GeneratorDefaultBrand, F as Part, Fi as isFieldRef, Fn as selecting, Fo as GeoPoint, G as UnitOutcome, Ga as ClientInitializationError, Gn as keep, H as TargetOf, Ha as isValidationError, Hi as ModelInternal, Hn as check, Hr as SchemaValidationIssue, I as Parts, Ii as AnyModel, In as target, Io as GeoPolygon, Ir as InsertValueContext, J as AddedProjectedState, Ja as ForbiddenError, Ji as NumberSchema, Jn as arg, K as Watcher, Ka as ConnectionError, Kn as lazy, L as PlacedArgument, Li as IndexDefinition, Ln as writes, Lo as DecimalDescriptor, Lr as ModelSql, M as NoArguments, Mi as FieldRef, Mn as deletes, Mr as around, N as OperationSet, Ni as ModelFieldRefs, Nn as models, No as GeoArea, Nr as call, O as EmptyFacts, Oa as RelationCardinality, Oi as StringSchema, On as unit, Oo as wrapError, Or as UnwrapPendingOperations, Ot as ScalarState, P as Outcome, Pi as createModelFieldRefs, Pn as reads, Po as GeoBounds, Q as DelegateOperationArgs, Qa as PendingOperationError, Qi as JsonValue, Qn as provided, Qt as NumericScalar, R as Run, Ri as IndexOptions, Rn as work, Ro as Decimal, Rr as validateSchema, S as AnyTarget, Si as BooleanScalar, Sn as parameters, So as PrismaErrorCode, Sr as renderOperationResultType, St as Scalar, T as CallContext, Ta as Getter, Tn as statements, To as isRetryableError, Tr as ProjectedModelOperations, U as UnitContext, Ua as InvalidTransactionInputError, Ui as ModelState, Un as facts, Ur as Severity, V as Target, Va as ValidationErrorSource, Vi as Model, Vn as key, Vr as isSchemaValidationError, Vt as VibSchema, W as UnitKind, Wa as TransactionError, Wi as UpdateState, Wn as gate, Wr as ValidationResult, X as ClientTypeState, Xa as NestedWriteError, Xi as InputJsonValue, Xn as nothing, Ya as NestedWriteAssertionError, Yn as exists, Z as DelegateConfig, Za as NotFoundError, Zi as JsonSchema, Zn as now, _a as DbNull, _i as ReferencesStage, _n as driver, _o as isValueTooLongError, _r as accepts, _t as RowsFragment, aa as ObjectSchema, an as EnumScalar, ao as isUnsupportedOperationError, ar as DisclosurePolicy, at as TransactionClient, b as AnyCallContext, ba as JsonNullSentinel, bi as DateTimeScalar, bn as notes, bo as CacheInvalidTTLError, br as oneOf, bt as VariantToManyRelation, ca as DecimalSchema, cn as getSchemas, co as CheckConstraintError, cr as omitted, ct as VibORMConfig, di as FlatSchema, dn as JoinedSource, do as UniqueConstraintError, dr as within, dt as ChainedExtensionState, en as StringScalar, eo as QueryError, er as unless, et as DelegateOperationResult, fa as BlobSchema, fi as Linked, fn as computed, fo as ValueTooLongError, fr as Codec, ft as ClientExtensionState, ga as AnyNull, gi as ModelToOneRelation, gn as correlation, go as isUniqueConstraintError, gr as watch, gt as RawOperation, ha as AnyJsonNullSentinel, hi as RelationLinks, hn as BatchMember, ho as isNotNullConstraintError, hr as via, ht as ExtensionStateConstraint, ia as IsoTimestampSchema, in as IntScalar, io as isPendingOperationError, ir as disclosed, j as Facts, ji as AnyFieldRef, jn as parts, jr as WriteKind, k as Exact, ka as RelationSlot, kn as settled, ko as DiagnosticDisclosure, kr as isPendingOperation, ln as getRowKey, lo as ForeignKeyError, lr as Database, lt as createClient, ma as BigIntSchema, mi as Links, mn as stored, mo as isForeignKeyError, mr as again, mt as ExtensionResultConsumerState, na as IsoDateSchema, ni as Schema, nn as NumberScalar, no as isClientInitializationError, nr as fields, nt as ExtendedClient, oi as ClientHiddenContext, on as DecimalScalar, oo as MigrationError, or as disclosure, ot as TransactionClientOf, pi as LinkedClientConfig, pn as joined, po as isCheckConstraintError, pr as codec, pt as EmptyClientExtensionState, q as With, qa as FeatureNotSupportedError, qi as IntegerSchema, qn as only, ra as IsoTimeSchema, rn as JsonScalar, ro as isNotFoundError, rr as extension, rt as ExtendedOperationResult, sa as EnumSchema, sn as s, so as isMigrationError, sr as defaults, st as VibORMClient, tn as PointScalar, to as UnsupportedOperationError, tr as when, ua as BooleanSchema, ui as ClientSchema, un as VIBORM_VERSION, uo as NotNullConstraintError, ur as database, ut as AddedExtensionState, va as JsonNull, vi as ModelToManyRelation, vn as failure, vo as CacheConfigurationError, vr as args, vt as ModelShape, w as BoundAccepted, wa as AnyRelation, wn as statement, wo as VibORMErrorCode, wr as validateOperationPayload, wt as AutoGenerate, x as AnyFacts, xa as isJsonNullSentinel, xi as DateScalar, xn as origin, xo as CacheOperationNotCacheableError, xr as getOperationPayloadSchema, xt as VariantToOneRelation, y as Accepted, ya as JsonNullKind, yi as TimeScalar, yn as note, yo as CacheInvalidKeyError, yr as bound, yt as ScalarKeys, z as Selection, zn as methods, zr as validateSchemaOrThrow } from "./database-adapter-BD_htd5h.mjs";
1
+ import { $ as DelegateOperationPayload, $a as QueryEngineError, $n as row, $t as VectorScalar, A as Extension, Ai as PointSchema, An as rule, Ar as WriteOutcome, At as UpdateState$1, B as StampedFields, Ba as ValidationError, Bi as InitialModelState, Bn as modelMethods, Br as SchemaValidationError, C as ArgTest, Ci as BlobScalar, Cn as run, Co as VibORMError, Cr as renderSchemaType, Ct as BigIntScalar, D as ConfiguredBy, Da as ReferentialAction, Di as VectorSchema, Dn as text, Do as toPrismaErrorCode, Dr as UnwrapPendingOperation, Dt as InitialScalarState, E as CallResult, En as table, Eo as isVibORMError, Er as PendingOperation, Et as GeneratorDefaultBrand, F as Part, Fi as isFieldRef, Fn as selecting, Fo as GeoPoint, G as UnitOutcome, Ga as ClientInitializationError, Gn as keep, H as TargetOf, Ha as isValidationError, Hi as ModelInternal, Hn as check, Hr as SchemaValidationIssue, I as Parts, Ii as AnyModel, In as target, Io as GeoPolygon, Ir as InsertValueContext, J as AddedProjectedState, Ja as ForbiddenError, Ji as NumberSchema, Jn as arg, K as Watcher, Ka as ConnectionError, Kn as lazy, L as PlacedArgument, Li as IndexDefinition, Ln as writes, Lo as DecimalDescriptor, Lr as ModelSql, M as NoArguments, Mi as FieldRef, Mn as deletes, Mr as around, N as OperationSet, Ni as ModelFieldRefs, Nn as models, No as GeoArea, Nr as call, O as EmptyFacts, Oa as RelationCardinality, Oi as StringSchema, On as unit, Oo as wrapError, Or as UnwrapPendingOperations, Ot as ScalarState, P as Outcome, Pi as createModelFieldRefs, Pn as reads, Po as GeoBounds, Q as DelegateOperationArgs, Qa as PendingOperationError, Qi as JsonValue, Qn as provided, Qt as NumericScalar, R as Run, Ri as IndexOptions, Rn as work, Ro as Decimal, Rr as validateSchema, S as AnyTarget, Si as BooleanScalar, Sn as parameters, So as PrismaErrorCode, Sr as renderOperationResultType, St as Scalar, T as CallContext, Ta as Getter, Tn as statements, To as isRetryableError, Tr as ProjectedModelOperations, U as UnitContext, Ua as InvalidTransactionInputError, Ui as ModelState, Un as facts, Ur as Severity, V as Target, Va as ValidationErrorSource, Vi as Model, Vn as key, Vr as isSchemaValidationError, Vt as VibSchema, W as UnitKind, Wa as TransactionError, Wi as UpdateState, Wn as gate, Wr as ValidationResult, X as ClientTypeState, Xa as NestedWriteError, Xi as InputJsonValue, Xn as nothing, Ya as NestedWriteAssertionError, Yn as exists, Z as DelegateConfig, Za as NotFoundError, Zi as JsonSchema, Zn as now, _a as DbNull, _i as ReferencesStage, _n as driver, _o as isValueTooLongError, _r as accepts, _t as RowsFragment, aa as ObjectSchema, an as EnumScalar, ao as isUnsupportedOperationError, ar as DisclosurePolicy, at as TransactionClient, b as AnyCallContext, ba as JsonNullSentinel, bi as DateTimeScalar, bn as notes, bo as CacheInvalidTTLError, br as oneOf, bt as VariantToManyRelation, ca as DecimalSchema, cn as getSchemas, co as CheckConstraintError, cr as omitted, ct as VibORMConfig, di as FlatSchema, dn as JoinedSource, do as UniqueConstraintError, dr as within, dt as ChainedExtensionState, en as StringScalar, eo as QueryError, er as unless, et as DelegateOperationResult, fa as BlobSchema, fi as Linked, fn as computed, fo as ValueTooLongError, fr as Codec, ft as ClientExtensionState, ga as AnyNull, gi as ModelToOneRelation, gn as correlation, go as isUniqueConstraintError, gr as watch, gt as RawOperation, ha as AnyJsonNullSentinel, hi as RelationLinks, hn as BatchMember, ho as isNotNullConstraintError, hr as via, ht as ExtensionStateConstraint, ia as IsoTimestampSchema, in as IntScalar, io as isPendingOperationError, ir as disclosed, j as Facts, ji as AnyFieldRef, jn as parts, jr as WriteKind, k as Exact, ka as RelationSlot, kn as settled, ko as DiagnosticDisclosure, kr as isPendingOperation, ln as getRowKey, lo as ForeignKeyError, lr as Database, lt as createClient, ma as BigIntSchema, mi as Links, mn as stored, mo as isForeignKeyError, mr as again, mt as ExtensionResultConsumerState, na as IsoDateSchema, ni as Schema, nn as NumberScalar, no as isClientInitializationError, nr as fields, nt as ExtendedClient, oi as ClientHiddenContext, on as DecimalScalar, oo as MigrationError, or as disclosure, ot as TransactionClientOf, pi as LinkedClientConfig, pn as joined, po as isCheckConstraintError, pr as codec, pt as EmptyClientExtensionState, q as With, qa as FeatureNotSupportedError, qi as IntegerSchema, qn as only, ra as IsoTimeSchema, rn as JsonScalar, ro as isNotFoundError, rr as extension, rt as ExtendedOperationResult, sa as EnumSchema, sn as s, so as isMigrationError, sr as defaults, st as VibORMClient, tn as PointScalar, to as UnsupportedOperationError, tr as when, ua as BooleanSchema, ui as ClientSchema, un as VIBORM_VERSION, uo as NotNullConstraintError, ur as database, ut as AddedExtensionState, va as JsonNull, vi as ModelToManyRelation, vn as failure, vo as CacheConfigurationError, vr as args, vt as ModelShape, w as BoundAccepted, wa as AnyRelation, wn as statement, wo as VibORMErrorCode, wr as validateOperationPayload, wt as AutoGenerate, x as AnyFacts, xa as isJsonNullSentinel, xi as DateScalar, xn as origin, xo as CacheOperationNotCacheableError, xr as getOperationPayloadSchema, xt as VariantToOneRelation, y as Accepted, ya as JsonNullKind, yi as TimeScalar, yn as note, yo as CacheInvalidKeyError, yr as bound, yt as ScalarKeys, z as Selection, zn as methods, zr as validateSchemaOrThrow } from "./database-adapter-BGqvjeEy.mjs";
2
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-BVZ8QefY.mjs";
3
3
  export { Accepted, type AddedExtensionState, type AddedProjectedState, AnyCallContext, AnyFacts, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, AnyTarget, ArgTest, type AutoGenerate, BatchMember, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, BoundAccepted, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CallContext, CallResult, type ChainedExtensionState, CheckConstraintError, type ClientExtensionState, type ClientHiddenContext, ClientInitializationError, type ClientSchema, type ClientTypeState, Codec, type InsertValueContext as ComputedContext, ConfiguredBy, ConnectionError, Database, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DelegateConfig, type DelegateOperationArgs, type DelegateOperationPayload, type DelegateOperationResult, type DiagnosticDisclosure, DisclosurePolicy, type EmptyClientExtensionState, EmptyFacts, type EnumScalar, type EnumSchema, Exact, type ExtendedClient, type ExtendedOperationResult, Extension, type ExtensionResultConsumerState, type ExtensionStateConstraint as ExtensionState, Facts, 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, type JoinedSource, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelSql, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoArguments, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, OperationSet, Outcome, Part, Parts, PendingOperation, PendingOperationError, type PlacedArgument, type PointScalar, type PointSchema, type PrismaErrorCode, type ProjectedModelOperations, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type RowsFragment, Run, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type Schema, SchemaValidationError, type SchemaValidationIssue, Selection, type Severity, Sql, type StampedFields, type StringScalar, type StringSchema, Target, TargetOf, type TimeScalar, type TransactionClient, type TransactionClientOf, TransactionError, UniqueConstraintError, UnitContext, UnitKind, UnitOutcome, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, VIBORM_VERSION, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, Watcher, With, WriteKind, WriteOutcome, accepts, again, arg, args, around, bound, call, check, codec, computed, correlation, createClient, createModelFieldRefs, database, defaults, deletes, disclosed, disclosure, driver, empty, exists, extension, facts, failure, fields, gate, getOperationPayloadSchema, getRowKey, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, joined, keep, key, lazy, methods, modelMethods, models, note, notes, nothing, now, omitted, oneOf, only, origin, parameters, parts, provided, raw, reads, renderOperationResultType, renderSchemaType, row, rule, run, s, selecting, settled, sqlTag as sql, statement, statements, stored, table, target, text, toPrismaErrorCode, unit, unless, validateOperationPayload, validateSchema, validateSchemaOrThrow, via, watch, when, within, work, wrapError, writes };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,C as n,D as r,E as i,O as a,S as o,T as s,b as c,j as l,k as u,v as d,w as f,x as p,y as m}from"./error-mapping-B1-IWkCQ.mjs";import{a as h,i as g,n as _,o as v,s as y,t as b}from"./base-z-cH5ZBI.mjs";import{n as ee,t as te}from"./migrations-BMiRjR-N.mjs";import{_ as ne,a as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,l as ue,m as de,n as fe,o as pe,p as x,r as S,t as C,u as w,v as T}from"./validation--qS7OPmg.mjs";import{n as E,t as D}from"./transaction-BNomMtme.mjs";import{a as O,i as k,n as A,o as j,r as M,t as N}from"./sql-3o4DOKm9.mjs";import{o as P}from"./value-guards-CBuxSC66.mjs";import{r as F,t as I}from"./extension-CGepsF-p.mjs";import{H as L}from"./native-types-DgjMUikz.mjs";import{J as R,Q as z,X as B,Y as me,Z as he,_ as ge,et as _e,rt as ve,v as ye}from"./scalar-BHCh7aUz.mjs";import{a as be,g as xe,i as Se}from"./validator-CZLW7aR3.mjs";import{r as Ce,t as we}from"./pending-operation-C_eOFOBE.mjs";import{a as Te,i as Ee,r as De,t as Oe}from"./client-DRpX3-vw.mjs";import{c as V,i as ke}from"./validation-CYaJ8ndO.mjs";import{i as Ae,n as je,r as Me,t as Ne}from"./schema-introspection-D0f8cti4.mjs";import{n as H,t as U}from"./methods-part-ZY0f2AV_.mjs";import{a as Pe,c as W,l as Fe,n as Ie,o as Le,r as Re}from"./on-ylYaKuRu.mjs";import{i as ze,n as G,r as Be,t as Ve}from"./args-764KdWMr.mjs";import{n as K,t as q}from"./call-Cz8XUmrl.mjs";import{i as He,n as Ue,r as We,t as Ge}from"./settled-BjyuA76m.mjs";import{n as Ke,r as qe,t as Je}from"./key-hxFFCKed.mjs";import{a as Ye,c as Xe,d as Ze,i as Qe,o as $e,r as et,s as tt,u as nt}from"./rule-words-ZIGm7cDm.mjs";import{a as rt,c as J,i as it,n as at,o as ot,r as st,s as ct}from"./judge-words-CzUyXtJ6.mjs";import{t as lt}from"./confine-DqFBTUw6.mjs";import{n as ut,t as Y}from"./defaults-DwOHWI_M.mjs";import{n as X,r as dt,t as Z}from"./unit-BhHbZyuJ.mjs";import{a as ft,c as pt,d as mt,f as ht,h as gt,i as _t,l as vt,n as yt,o as bt,r as Q,s as xt,t as St,u as Ct}from"./unit-words-CT0yeqfZ.mjs";import{n as wt,r as Tt,t as Et}from"./values-B4aj1i1f.mjs";import{t as Dt}from"./schema-CFIaebgi.mjs";import{t as Ot}from"./version-DRfmNoR1.mjs";const $=`$allModels`,kt=new Set([`createMany`,`updateMany`,`deleteMany`]);function planNode(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=P(r?.select)?r.select:void 0,o=P(r?.include)?r.include:void 0,s=P(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let i of Object.keys(l)){let a=r?.get(i),o=l[i];if(!a||Ee(a)||o!==!0&&!P(o))continue;let s=Te(a,n),d=o===!0?void 0:o,f=planNode(e,t,s,d);f!==void 0&&(c.push([i,f.node]),d?.recurse!==void 0&&f.node.relations.push([i,f.node]),f.args!==d&&(u={...u,[i]:f.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let kept=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,f=[],p=!1;for(let[e,t]of d)p||=(a??s)?.[e]!==void 0,kept(e)&&f.push(t);if(f.length===0&&c.length===0&&!p)return;let m=new Set,h=new Set,close=e=>{if(!m.has(e)){m.add(e);for(let t of i[e].needs)typeof t==`number`?close(t):h.add(t)}};for(let e of f)close(e);let g=new Set;for(let e of h)kept(e)||g.add(e);let _=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of h)s[t]===!0&&(e[t]=!1);_={..._,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of h)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=V(n);t!==void 0&&(e[t]=!0,kept(t)||g.add(t))}_={..._,select:e}}else u!==l&&(_={..._,include:u});return{args:_,node:{fields:i,outputs:f,reads:[...h],strip:[...g],relations:c}}}function finishValue(e,t){return Array.isArray(e)?e.map(e=>finishRow(e,t)):finishRow(e,t)}function finishRow(t,n){if(!P(t))return t;let r={...t};for(let[e,t]of n.relations)r[e]!==void 0&&(r[e]=finishValue(r[e],t));for(let e of n.strip)delete r[e];let i=t;for(let e of n.reads){let n=t[e];typeof n!=`object`||!n||(i===t&&(i={...t}),i[e]=detached(n))}let a=new Map,o=e(e=>{if(a.has(e))return a.get(e);let t=n.fields[e],r={};for(let e of t.needs)typeof e==`number`?r[n.fields[e].name]=o(e):r[e]=i[e];let s=t.compute(r);return a.set(e,s),s},`computed`);for(let e of n.outputs){let t=n.fields[e].name,settle=e=>(Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(r,t,{get:()=>settle(o(e)),set:settle,enumerable:!0,configurable:!0})}return r}function detached(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(detached);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=detached(e[t]);return n}function fieldsPart(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==$&&!Object.hasOwn(r,t)&&F(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(V(a));for(let r of[$,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||Object.hasOwn(a[`~`].state.relations,i))&&F(`${e} cannot be computed: "${i}" is a relation of model "${t}".`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:F(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(De.has(n)||kt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=planNode(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>finishValue(e,o)}}}}}}function fields(e){return fieldsPart(e)}function parts(){return{extension:I,call:K,around:q,target:W,unit:Z,rule:J,defaults:Y,disclosure:X,args:G,methods:U,modelMethods:H,fields}}const getSchemas=e=>ke(e).proxy;export{R as AnyNull,a as CacheConfigurationError,u as CacheInvalidKeyError,t as CacheInvalidTTLError,l as CacheOperationNotCacheableError,d as CheckConstraintError,S as ClientInitializationError,le as ConnectionError,me as DbNull,L as Decimal,re as FeatureNotSupportedError,pe as ForbiddenError,m as ForeignKeyError,D as InvalidTransactionInputError,B as JsonNull,he as JsonNullSentinel,te as MigrationError,ie as NestedWriteAssertionError,ue as NestedWriteError,w as NotFoundError,c as NotNullConstraintError,we as PendingOperation,ae as PendingOperationError,oe as QueryEngineError,x as QueryError,ge as SchemaValidationError,N as Sql,E as TransactionError,p as UniqueConstraintError,de as UnsupportedOperationError,Ot as VIBORM_VERSION,C as ValidationError,o as ValueTooLongError,b as VibORMError,_ as VibORMErrorCode,Ve as accepts,Ue as again,et as arg,G as args,q as around,Be as bound,K as call,at as check,qe as codec,Et as computed,St as correlation,Oe as createClient,_e as createModelFieldRefs,Ke as database,Y as defaults,Ie as deletes,dt as disclosed,X as disclosure,yt as driver,A as empty,Qe as exists,I as extension,st as facts,Q as failure,fields,it as gate,Ne as getOperationPayloadSchema,xe as getRowKey,getSchemas,n as isCheckConstraintError,ce as isClientInitializationError,ve as isFieldRef,f as isForeignKeyError,z as isJsonNullSentinel,ee as isMigrationError,se as isNotFoundError,s as isNotNullConstraintError,Ce as isPendingOperation,ne as isPendingOperationError,g as isRetryableError,ye as isSchemaValidationError,M as isSql,i as isUniqueConstraintError,T as isUnsupportedOperationError,fe as isValidationError,r as isValueTooLongError,h as isVibORMError,k as join,wt as joined,rt as keep,Je as key,ot as lazy,U as methods,H as modelMethods,Re as models,_t as note,ft as notes,Ye as nothing,$e as now,ut as omitted,ze as oneOf,ct as only,bt as origin,xt as parameters,parts,tt as provided,O as raw,Pe as reads,je as renderOperationResultType,Me as renderSchemaType,Xe as row,J as rule,pt as run,Dt as s,Le as selecting,Ge as settled,j as sql,vt as statement,Ct as statements,Tt as stored,mt as table,W as target,ht as text,v as toPrismaErrorCode,Z as unit,nt as unless,Ae as validateOperationPayload,Se as validateSchema,be as validateSchemaOrThrow,We as via,He as watch,Ze as when,lt as within,gt as work,y as wrapError,Fe as writes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,C as n,D as r,E as i,O as a,S as o,T as s,b as c,j as l,k as u,v as d,w as f,x as p,y as m}from"./error-mapping-B1-IWkCQ.mjs";import{a as h,i as g,n as _,o as v,s as y,t as b}from"./base-z-cH5ZBI.mjs";import{n as ee,t as te}from"./migrations-BMiRjR-N.mjs";import{_ as ne,a as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,l as ue,m as de,n as fe,o as pe,p as x,r as S,t as C,u as w,v as T}from"./validation--qS7OPmg.mjs";import{n as E,t as D}from"./transaction-BNomMtme.mjs";import{a as O,i as k,n as A,o as j,r as M,t as N}from"./sql-3o4DOKm9.mjs";import{o as P}from"./value-guards-CBuxSC66.mjs";import{r as F,t as I}from"./extension-CGepsF-p.mjs";import{H as L}from"./native-types-DgjMUikz.mjs";import{J as R,Q as z,X as B,Y as me,Z as he,_ as ge,et as _e,rt as ve,v as ye}from"./scalar-BHCh7aUz.mjs";import{a as be,g as xe,i as Se}from"./validator-CZLW7aR3.mjs";import{r as Ce,t as we}from"./pending-operation-C_eOFOBE.mjs";import{a as Te,i as Ee,r as De,t as Oe}from"./client-DRpX3-vw.mjs";import{c as V,i as ke}from"./validation-CYaJ8ndO.mjs";import{i as Ae,n as je,r as Me,t as Ne}from"./schema-introspection-D0f8cti4.mjs";import{n as H,t as U}from"./methods-part-ZY0f2AV_.mjs";import{a as Pe,c as W,l as Fe,n as Ie,o as Le,r as Re}from"./on-ylYaKuRu.mjs";import{i as ze,n as G,r as Be,t as Ve}from"./args-764KdWMr.mjs";import{n as K,t as q}from"./call-Cz8XUmrl.mjs";import{i as He,n as Ue,r as We,t as Ge}from"./settled-BjyuA76m.mjs";import{n as Ke,r as qe,t as Je}from"./key-hxFFCKed.mjs";import{a as Ye,c as Xe,d as Ze,i as Qe,o as $e,r as et,s as tt,u as nt}from"./rule-words-ZIGm7cDm.mjs";import{a as rt,c as J,i as it,n as at,o as ot,r as st,s as ct}from"./judge-words-CzUyXtJ6.mjs";import{t as lt}from"./confine-DqFBTUw6.mjs";import{n as ut,t as Y}from"./defaults-DwOHWI_M.mjs";import{n as X,r as dt,t as Z}from"./unit-BhHbZyuJ.mjs";import{a as ft,c as pt,d as mt,f as ht,h as gt,i as _t,l as vt,n as yt,o as bt,r as Q,s as xt,t as St,u as Ct}from"./unit-words-CT0yeqfZ.mjs";import{n as wt,r as Tt,t as Et}from"./values-B4aj1i1f.mjs";import{t as Dt}from"./schema-CFIaebgi.mjs";import{t as Ot}from"./version-CXGIA82S.mjs";const $=`$allModels`,kt=new Set([`createMany`,`updateMany`,`deleteMany`]);function planNode(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=P(r?.select)?r.select:void 0,o=P(r?.include)?r.include:void 0,s=P(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let i of Object.keys(l)){let a=r?.get(i),o=l[i];if(!a||Ee(a)||o!==!0&&!P(o))continue;let s=Te(a,n),d=o===!0?void 0:o,f=planNode(e,t,s,d);f!==void 0&&(c.push([i,f.node]),d?.recurse!==void 0&&f.node.relations.push([i,f.node]),f.args!==d&&(u={...u,[i]:f.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let kept=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,f=[],p=!1;for(let[e,t]of d)p||=(a??s)?.[e]!==void 0,kept(e)&&f.push(t);if(f.length===0&&c.length===0&&!p)return;let m=new Set,h=new Set,close=e=>{if(!m.has(e)){m.add(e);for(let t of i[e].needs)typeof t==`number`?close(t):h.add(t)}};for(let e of f)close(e);let g=new Set;for(let e of h)kept(e)||g.add(e);let _=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of h)s[t]===!0&&(e[t]=!1);_={..._,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of h)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=V(n);t!==void 0&&(e[t]=!0,kept(t)||g.add(t))}_={..._,select:e}}else u!==l&&(_={..._,include:u});return{args:_,node:{fields:i,outputs:f,reads:[...h],strip:[...g],relations:c}}}function finishValue(e,t){return Array.isArray(e)?e.map(e=>finishRow(e,t)):finishRow(e,t)}function finishRow(t,n){if(!P(t))return t;let r={...t};for(let[e,t]of n.relations)r[e]!==void 0&&(r[e]=finishValue(r[e],t));for(let e of n.strip)delete r[e];let i=t;for(let e of n.reads){let n=t[e];typeof n!=`object`||!n||(i===t&&(i={...t}),i[e]=detached(n))}let a=new Map,o=e(e=>{if(a.has(e))return a.get(e);let t=n.fields[e],r={};for(let e of t.needs)typeof e==`number`?r[n.fields[e].name]=o(e):r[e]=i[e];let s=t.compute(r);return a.set(e,s),s},`computed`);for(let e of n.outputs){let t=n.fields[e].name,settle=e=>(Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(r,t,{get:()=>settle(o(e)),set:settle,enumerable:!0,configurable:!0})}return r}function detached(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(detached);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=detached(e[t]);return n}function fieldsPart(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==$&&!Object.hasOwn(r,t)&&F(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(V(a));for(let r of[$,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||Object.hasOwn(a[`~`].state.relations,i))&&F(`${e} cannot be computed: "${i}" is a relation of model "${t}".`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:F(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(De.has(n)||kt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=planNode(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>finishValue(e,o)}}}}}}function fields(e){return fieldsPart(e)}function parts(){return{extension:I,call:K,around:q,target:W,unit:Z,rule:J,defaults:Y,disclosure:X,args:G,methods:U,modelMethods:H,fields}}const getSchemas=e=>ke(e).proxy;export{R as AnyNull,a as CacheConfigurationError,u as CacheInvalidKeyError,t as CacheInvalidTTLError,l as CacheOperationNotCacheableError,d as CheckConstraintError,S as ClientInitializationError,le as ConnectionError,me as DbNull,L as Decimal,re as FeatureNotSupportedError,pe as ForbiddenError,m as ForeignKeyError,D as InvalidTransactionInputError,B as JsonNull,he as JsonNullSentinel,te as MigrationError,ie as NestedWriteAssertionError,ue as NestedWriteError,w as NotFoundError,c as NotNullConstraintError,we as PendingOperation,ae as PendingOperationError,oe as QueryEngineError,x as QueryError,ge as SchemaValidationError,N as Sql,E as TransactionError,p as UniqueConstraintError,de as UnsupportedOperationError,Ot as VIBORM_VERSION,C as ValidationError,o as ValueTooLongError,b as VibORMError,_ as VibORMErrorCode,Ve as accepts,Ue as again,et as arg,G as args,q as around,Be as bound,K as call,at as check,qe as codec,Et as computed,St as correlation,Oe as createClient,_e as createModelFieldRefs,Ke as database,Y as defaults,Ie as deletes,dt as disclosed,X as disclosure,yt as driver,A as empty,Qe as exists,I as extension,st as facts,Q as failure,fields,it as gate,Ne as getOperationPayloadSchema,xe as getRowKey,getSchemas,n as isCheckConstraintError,ce as isClientInitializationError,ve as isFieldRef,f as isForeignKeyError,z as isJsonNullSentinel,ee as isMigrationError,se as isNotFoundError,s as isNotNullConstraintError,Ce as isPendingOperation,ne as isPendingOperationError,g as isRetryableError,ye as isSchemaValidationError,M as isSql,i as isUniqueConstraintError,T as isUnsupportedOperationError,fe as isValidationError,r as isValueTooLongError,h as isVibORMError,k as join,wt as joined,rt as keep,Je as key,ot as lazy,U as methods,H as modelMethods,Re as models,_t as note,ft as notes,Ye as nothing,$e as now,ut as omitted,ze as oneOf,ct as only,bt as origin,xt as parameters,parts,tt as provided,O as raw,Pe as reads,je as renderOperationResultType,Me as renderSchemaType,Xe as row,J as rule,pt as run,Dt as s,Le as selecting,Ge as settled,j as sql,vt as statement,Ct as statements,Tt as stored,mt as table,W as target,ht as text,v as toPrismaErrorCode,Z as unit,nt as unless,Ae as validateOperationPayload,Se as validateSchema,be as validateSchemaOrThrow,We as via,He as watch,Ze as when,lt as within,gt as work,y as wrapError,Fe as writes};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,4 +1,4 @@
1
- import { A as Extension, Co as VibORMError, O as EmptyFacts, S as AnyTarget, ko as DiagnosticDisclosure } from "./database-adapter-BD_htd5h.mjs";
1
+ import { A as Extension, Co as VibORMError, O as EmptyFacts, S as AnyTarget, ko as DiagnosticDisclosure } from "./database-adapter-BGqvjeEy.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./extension-CGepsF-p.mjs";import{n as r,r as i,t as a}from"./unit-BhHbZyuJ.mjs";import{a as o,d as s,f as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./unit-words-CT0yeqfZ.mjs";import{t as h}from"./version-DRfmNoR1.mjs";import{C as g,D as _,E as v,S as y,T as b,_ as x,a as S,b as C,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,v as z,w as B,x as V,y as H}from"./spans-XDUFeTzC.mjs";const U=new Set([`bypass`,`hit`,`miss`,`revalidate`]),W=new Set([`cache-set-failed`,`error`,`fresh`,`stale`,`start`,`success`]);function presentLogMetadata(e){let{event:t,status:n}=e;return{...U.has(t)?{event:t}:{},...W.has(n)?{status:n}:{}}}function prettyLog(e){let t=e.timestamp.toISOString(),n=e.duration===void 0?``:`${e.duration}ms`,r=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,r||`query`,n].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,typeof e.meta?.event==`string`?e.meta.event:`unknown`,typeof e.meta?.status==`string`?`(${e.meta.status})`:``);break;case`error`:console.error(`[ERROR]`,t,r,n),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function createLogger(e){let handlerOf=t=>e[t]??e.all;return Object.freeze({log(e){try{let t=handlerOf(e.level);if(!t)return;let n={level:e.level,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:e.sql,params:e.params,error:e.error,meta:e.meta},defaultLog=()=>{try{prettyLog(n)}catch{}};t===!0?defaultLog():Promise.resolve(t(n,defaultLog)).catch(()=>void 0)}catch{}},isLevelEnabled(e){return handlerOf(e)!==void 0}})}const G={SpanStatusCode:{OK:1,ERROR:2}},K=h,q=new WeakSet;function createTracerWrapper(t={}){let{tracer:n}=t,r=Object.freeze((t.ignoreSpanTypes??[]).map(e=>typeof e==`string`?e:new RegExp(e.source,e.flags)));function traces$1(e){return!r.some(t=>typeof t==`string`?t===e:new RegExp(t.source,t.flags).test(e))}e(traces$1,`traces`);let i,a,o=n===void 0?import(`@opentelemetry/api`).then(e=>{i=e},()=>{i=null}):void 0;return Object.freeze({traces:traces$1,async startActiveSpan(e,t){if(n!==void 0)return traces$1(e.name)?runOnce(t,G,t=>n.startActiveSpan(e.name,n=>(setSpanAttributes(n,e.attributes??{}),t(n)))):t();if(i===void 0&&await o,!(i&&traces$1(e.name)))return t();let r,s;try{let t={...e.attributes},n=i.SpanKind.INTERNAL,o=e.root?i.ROOT_CONTEXT:i.context.active();a??=i.trace.getTracer(`viborm`,K),r=a.startSpan(e.name,{kind:n,attributes:t},o),s=i.trace.setSpan(o,r)}catch{return t()}let c=i;return runOnce(t,c,e=>c.context.with(s,()=>e(r)),r)}})}function runOnce(e,t,n,r){let i=new Set,a,o,settle=(e,n)=>{a=e,o=n;for(let r of i)endSpan(r,e,t,n)},s,c=!1,run=n=>{if(n!==void 0&&(i.add(n),a!==void 0&&endSpan(n,a,t,o)),s)return s;if(c)return Promise.reject(createTraceError());c=!0;try{return s=new Promise((t,r)=>{try{Promise.resolve(e(n)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),r(e)})}catch(e){settle(!0,e),r(e)}}),s}finally{c=!1}};try{Promise.resolve(n(run)).catch(ignoreRejection)}catch{}return run(r)}function endSpan(e,t,n,r){if(!q.has(e)){if(q.add(e),t){let t=r instanceof Error?r:{},i=typeof t.name==`string`?t.name:`Error`,{code:a}=t,o=t.meta?.providerSqlState;setSpanAttributes(e,{"error.type":i,...typeof a==`string`&&i!==`Error`?{"viborm.error.code":a}:{},...typeof o==`string`?{"db.response.sqlstate":o}:{}}),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 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 createInstrumentationContext({tracing:e,logging:t}){let n=Object.freeze({tracing:e===!0||e===void 0?e:snapshotTracingConfig(e),logging:t===!0||t===void 0?t:snapshotLoggingConfig(t)});return Object.freeze({config:n,tracer:n.tracing&&createTracerWrapper(n.tracing===!0?{}:n.tracing),logger:n.logging&&createLogger(n.logging===!0?{all:!0}:n.logging),logged:new WeakSet})}function snapshotTracingConfig({includeParams:e,includeSql:t,ignoreSpanTypes:n,tracer:r}){return Object.freeze({includeParams:e===!0,includeSql:t===!0,ignoreSpanTypes:n,tracer:r})}function snapshotLoggingConfig({all:e,cache:t,error:n,query:r,includeParams:i,includeSql:a}){if(e||t||n||r)return Object.freeze({includeParams:i===!0,includeSql:a===!0,all:e,cache:t,error:n,query:r})}const J=/OrThrow$/;function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[P]:t,[N]:n,...r===void 0?{}:{[I]:r}}}function createCorrelationAttributes(e){return e?{[x]:e}:{}}function resolvedOperation(e){return e.operation?.replace(J,``)}const noteOf=e=>typeof e==`object`&&e?e:void 0,Y=new Set([v,b,_,g,B]),tracesAs=e=>!Y.has(e.span)||e.span===v&&e.root===!0;function notedAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!n.startsWith(`db.query.`)&&(t[n]=r);return t}function createNotedSpanOptions(e,t){return{name:t.span,attributes:notedAttributes({...createDriverAttributes(t.database),...createCorrelationAttributes(p(e)),...t.attributes}),root:t.root===!0}}function presentNoteLog(e,t,n){let{error:r}=n;return{level:t,timestamp:new Date(n.at??Date.now()),model:n.model??e.model,operation:n.operation??resolvedOperation(e),correlationId:p(e),error:r instanceof Error?i(r):void 0,meta:n.meta===void 0?void 0:presentLogMetadata(n.meta)}}function createOperationSpanOptions(e){return{name:v,attributes:createUnitAttributes(e,s(e))}}function createUnitAttributes(e,t){let{operation:n}=e;return{...createDriverAttributes(l(e)),...t?{[S]:t}:{},...n?{[w]:n}:{},...createCorrelationAttributes(p(e))}}function createStatementSpanOptions(e,t,n,r){let{includeParams:i,includeSql:a}=channelOf(e),o=createUnitAttributes(t,t.model);if(a&&n!==void 0&&(o[T]=n),i)for(let[e,t]of(r??[]).entries())o[`${A}.${e}`]=typeof t==`string`?t:String(JSON.stringify(t));return{name:b,attributes:o}}function channelOf(e){return e&&e!==!0?e:{}}function createLifecycleSpanOptions(e,t){return{name:e,attributes:createUnitAttributes(t,t.model)}}function statementIndexOf(e){let n=t(e)?e.meta.statementIndex:void 0;return typeof n==`number`?n:void 0}function createStatementLogEvent(e,t,n,r,a,o){let s=channelOf(e),l=o===void 0?void 0:statementIndexOf(o),u=l===void 0?void 0:m(t)?.[l],d=u?.sql??c(t),f=u===void 0||l===void 0?a:batchMemberParameters(a,l);return{level:o===void 0?`query`:`error`,timestamp:new Date(n+r),duration:r,model:u===void 0?t.model:u.model,operation:u===void 0?t.operation:u.operation,correlationId:u===void 0?p(t):u.correlation,sql:s.includeSql?d:void 0,params:s.includeParams?[...f??[]]:void 0,error:o===void 0?void 0:i(o,{sql:s.includeSql,parameters:s.includeParams})}}function batchMemberParameters(e,t){let n=e?.[t];return Array.isArray(n)?n:void 0}const X=`viborm.instrumentation`,ignore=()=>void 0;function instrumentation(e){let t=createInstrumentationContext(e),{logging:i,tracing:o}=t.config,{diagnostics:s={}}=e,c=r({sql:s.includeSql,parameters:s.includeParams,providerDetails:s.includeProviderDetails,callsite:s.includeCallsite});return o===void 0&&i===void 0?n(X,c):n(X,a((e,n)=>observe(t,e,n)),c)}function observe(e,t,n){let r,once=()=>(r??=n(),r);return Promise.resolve(present(e,t,once)).then(ignore,ignore).then(()=>r===void 0?once().then(ignore):void 0)}function traces(e,t){return e.tracer?.traces(t)===!0}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function present(e,t,n){switch(t.kind){case`operation`:return presentOperation(e,t,n);case`statement`:return presentStatement(e,t,n);case`transaction`:case`savepoint`:case`connection`:return presentLifecycle(e,t,n);case`batch`:return;default:return presentNoted(e,t,n)}}function spanned(e,t,n,r,a){let settle=e=>{let t=Date.now();return r().then(r=>{if(a?.(r,t,e),r.status===`failure`&&r.recovered!==!0)throw i(d(n))})};return e.tracer&&t?e.tracer.startActiveSpan(t,settle):settle()}function presentOperation(e,t,n){return spanned(e,traces(e,v)?createOperationSpanOptions(t):void 0,t,n,(n,r)=>{for(let n of o(t)){let r=noteOf(n);r?.log===`cache`&&log(e,t,r)}let i=d(t);n.status===`failure`&&i instanceof Error&&logs(e,`error`)&&!e.logged.has(u(i))&&e.logger?.log({...presentNoteLog(t,`error`,{at:r+n.duration,error:i}),duration:n.duration})})}function presentStatement(e,t,n){let r=traces(e,b),i=logs(e,`query`),a=logs(e,`error`);if(!(r||i||a))return;let{logging:o,tracing:s}=e.config,l=(i||a)&&channelOf(o).includeParams||r&&channelOf(s).includeParams?f(t):void 0,p=Date.now();return spanned(e,r?createStatementSpanOptions(s,t,c(t),l):void 0,t,n,({duration:n,recovered:r,status:s})=>{let c=d(t),f=s===`failure`&&c instanceof Error;r===!0||!(f?a:s===`success`&&i)||(f&&e.logged.add(u(c)),e.logger?.log(createStatementLogEvent(o,t,p,n,l,f?c:void 0)))})}function presentLifecycle(e,t,n){let r=t.kind===`connection`?t.operation===`$disconnect`||t.operation===`disconnect`?B:g:_;if(traces(e,r))return spanned(e,createLifecycleSpanOptions(r,t),t,n)}function log(e,t,n){n?.log!==void 0&&logs(e,n.log)&&e.logger?.log(presentNoteLog(t,n.log,n))}function presentNoted(e,t,n){let r=o(t).length,i;for(let n of o(t)){let r=noteOf(n);i===void 0&&r?.span!==void 0&&(i={...r,span:r.span}),log(e,t,r)}return spanned(e,i!==void 0&&e.tracer!==void 0&&tracesAs(i)?createNotedSpanOptions(t,i):void 0,t,n,(n,i,a)=>{for(let n of o(t).slice(r)){let r=noteOf(n);r?.attributes!==void 0&&setSpanAttributes(a,notedAttributes(r.attributes)),log(e,t,r)}})}export{L as ATTR_CACHE_DRIVER,M as ATTR_CACHE_RESULT,F as ATTR_CACHE_TTL,k as ATTR_DB_BATCH_SIZE,S as ATTR_DB_COLLECTION,N as ATTR_DB_DRIVER,I as ATTR_DB_NAMESPACE,w as ATTR_DB_OPERATION_NAME,A as ATTR_DB_QUERY_PARAMETER_PREFIX,R as ATTR_DB_QUERY_SUMMARY,T as ATTR_DB_QUERY_TEXT,E as ATTR_DB_ROWS_RETURNED,P as ATTR_DB_SYSTEM,j as ATTR_ERROR_TYPE,O as ATTR_SERVER_ADDRESS,D as ATTR_SERVER_PORT,x as ATTR_VIBORM_CORRELATION_ID,z as SPAN_CACHE_CLEAR,H as SPAN_CACHE_DELETE,C as SPAN_CACHE_GET,V as SPAN_CACHE_INVALIDATE,y as SPAN_CACHE_SET,g as SPAN_CONNECT,B as SPAN_DISCONNECT,b as SPAN_EXECUTE,v as SPAN_OPERATION,_ as SPAN_TRANSACTION,instrumentation};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./extension-CGepsF-p.mjs";import{n as r,r as i,t as a}from"./unit-BhHbZyuJ.mjs";import{a as o,d as s,f as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./unit-words-CT0yeqfZ.mjs";import{t as h}from"./version-CXGIA82S.mjs";import{C as g,D as _,E as v,S as y,T as b,_ as x,a as S,b as C,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,v as z,w as B,x as V,y as H}from"./spans-XDUFeTzC.mjs";const U=new Set([`bypass`,`hit`,`miss`,`revalidate`]),W=new Set([`cache-set-failed`,`error`,`fresh`,`stale`,`start`,`success`]);function presentLogMetadata(e){let{event:t,status:n}=e;return{...U.has(t)?{event:t}:{},...W.has(n)?{status:n}:{}}}function prettyLog(e){let t=e.timestamp.toISOString(),n=e.duration===void 0?``:`${e.duration}ms`,r=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,r||`query`,n].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,typeof e.meta?.event==`string`?e.meta.event:`unknown`,typeof e.meta?.status==`string`?`(${e.meta.status})`:``);break;case`error`:console.error(`[ERROR]`,t,r,n),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function createLogger(e){let handlerOf=t=>e[t]??e.all;return Object.freeze({log(e){try{let t=handlerOf(e.level);if(!t)return;let n={level:e.level,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:e.sql,params:e.params,error:e.error,meta:e.meta},defaultLog=()=>{try{prettyLog(n)}catch{}};t===!0?defaultLog():Promise.resolve(t(n,defaultLog)).catch(()=>void 0)}catch{}},isLevelEnabled(e){return handlerOf(e)!==void 0}})}const G={SpanStatusCode:{OK:1,ERROR:2}},K=h,q=new WeakSet;function createTracerWrapper(t={}){let{tracer:n}=t,r=Object.freeze((t.ignoreSpanTypes??[]).map(e=>typeof e==`string`?e:new RegExp(e.source,e.flags)));function traces$1(e){return!r.some(t=>typeof t==`string`?t===e:new RegExp(t.source,t.flags).test(e))}e(traces$1,`traces`);let i,a,o=n===void 0?import(`@opentelemetry/api`).then(e=>{i=e},()=>{i=null}):void 0;return Object.freeze({traces:traces$1,async startActiveSpan(e,t){if(n!==void 0)return traces$1(e.name)?runOnce(t,G,t=>n.startActiveSpan(e.name,n=>(setSpanAttributes(n,e.attributes??{}),t(n)))):t();if(i===void 0&&await o,!(i&&traces$1(e.name)))return t();let r,s;try{let t={...e.attributes},n=i.SpanKind.INTERNAL,o=e.root?i.ROOT_CONTEXT:i.context.active();a??=i.trace.getTracer(`viborm`,K),r=a.startSpan(e.name,{kind:n,attributes:t},o),s=i.trace.setSpan(o,r)}catch{return t()}let c=i;return runOnce(t,c,e=>c.context.with(s,()=>e(r)),r)}})}function runOnce(e,t,n,r){let i=new Set,a,o,settle=(e,n)=>{a=e,o=n;for(let r of i)endSpan(r,e,t,n)},s,c=!1,run=n=>{if(n!==void 0&&(i.add(n),a!==void 0&&endSpan(n,a,t,o)),s)return s;if(c)return Promise.reject(createTraceError());c=!0;try{return s=new Promise((t,r)=>{try{Promise.resolve(e(n)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),r(e)})}catch(e){settle(!0,e),r(e)}}),s}finally{c=!1}};try{Promise.resolve(n(run)).catch(ignoreRejection)}catch{}return run(r)}function endSpan(e,t,n,r){if(!q.has(e)){if(q.add(e),t){let t=r instanceof Error?r:{},i=typeof t.name==`string`?t.name:`Error`,{code:a}=t,o=t.meta?.providerSqlState;setSpanAttributes(e,{"error.type":i,...typeof a==`string`&&i!==`Error`?{"viborm.error.code":a}:{},...typeof o==`string`?{"db.response.sqlstate":o}:{}}),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 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 createInstrumentationContext({tracing:e,logging:t}){let n=Object.freeze({tracing:e===!0||e===void 0?e:snapshotTracingConfig(e),logging:t===!0||t===void 0?t:snapshotLoggingConfig(t)});return Object.freeze({config:n,tracer:n.tracing&&createTracerWrapper(n.tracing===!0?{}:n.tracing),logger:n.logging&&createLogger(n.logging===!0?{all:!0}:n.logging),logged:new WeakSet})}function snapshotTracingConfig({includeParams:e,includeSql:t,ignoreSpanTypes:n,tracer:r}){return Object.freeze({includeParams:e===!0,includeSql:t===!0,ignoreSpanTypes:n,tracer:r})}function snapshotLoggingConfig({all:e,cache:t,error:n,query:r,includeParams:i,includeSql:a}){if(e||t||n||r)return Object.freeze({includeParams:i===!0,includeSql:a===!0,all:e,cache:t,error:n,query:r})}const J=/OrThrow$/;function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[P]:t,[N]:n,...r===void 0?{}:{[I]:r}}}function createCorrelationAttributes(e){return e?{[x]:e}:{}}function resolvedOperation(e){return e.operation?.replace(J,``)}const noteOf=e=>typeof e==`object`&&e?e:void 0,Y=new Set([v,b,_,g,B]),tracesAs=e=>!Y.has(e.span)||e.span===v&&e.root===!0;function notedAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!n.startsWith(`db.query.`)&&(t[n]=r);return t}function createNotedSpanOptions(e,t){return{name:t.span,attributes:notedAttributes({...createDriverAttributes(t.database),...createCorrelationAttributes(p(e)),...t.attributes}),root:t.root===!0}}function presentNoteLog(e,t,n){let{error:r}=n;return{level:t,timestamp:new Date(n.at??Date.now()),model:n.model??e.model,operation:n.operation??resolvedOperation(e),correlationId:p(e),error:r instanceof Error?i(r):void 0,meta:n.meta===void 0?void 0:presentLogMetadata(n.meta)}}function createOperationSpanOptions(e){return{name:v,attributes:createUnitAttributes(e,s(e))}}function createUnitAttributes(e,t){let{operation:n}=e;return{...createDriverAttributes(l(e)),...t?{[S]:t}:{},...n?{[w]:n}:{},...createCorrelationAttributes(p(e))}}function createStatementSpanOptions(e,t,n,r){let{includeParams:i,includeSql:a}=channelOf(e),o=createUnitAttributes(t,t.model);if(a&&n!==void 0&&(o[T]=n),i)for(let[e,t]of(r??[]).entries())o[`${A}.${e}`]=typeof t==`string`?t:String(JSON.stringify(t));return{name:b,attributes:o}}function channelOf(e){return e&&e!==!0?e:{}}function createLifecycleSpanOptions(e,t){return{name:e,attributes:createUnitAttributes(t,t.model)}}function statementIndexOf(e){let n=t(e)?e.meta.statementIndex:void 0;return typeof n==`number`?n:void 0}function createStatementLogEvent(e,t,n,r,a,o){let s=channelOf(e),l=o===void 0?void 0:statementIndexOf(o),u=l===void 0?void 0:m(t)?.[l],d=u?.sql??c(t),f=u===void 0||l===void 0?a:batchMemberParameters(a,l);return{level:o===void 0?`query`:`error`,timestamp:new Date(n+r),duration:r,model:u===void 0?t.model:u.model,operation:u===void 0?t.operation:u.operation,correlationId:u===void 0?p(t):u.correlation,sql:s.includeSql?d:void 0,params:s.includeParams?[...f??[]]:void 0,error:o===void 0?void 0:i(o,{sql:s.includeSql,parameters:s.includeParams})}}function batchMemberParameters(e,t){let n=e?.[t];return Array.isArray(n)?n:void 0}const X=`viborm.instrumentation`,ignore=()=>void 0;function instrumentation(e){let t=createInstrumentationContext(e),{logging:i,tracing:o}=t.config,{diagnostics:s={}}=e,c=r({sql:s.includeSql,parameters:s.includeParams,providerDetails:s.includeProviderDetails,callsite:s.includeCallsite});return o===void 0&&i===void 0?n(X,c):n(X,a((e,n)=>observe(t,e,n)),c)}function observe(e,t,n){let r,once=()=>(r??=n(),r);return Promise.resolve(present(e,t,once)).then(ignore,ignore).then(()=>r===void 0?once().then(ignore):void 0)}function traces(e,t){return e.tracer?.traces(t)===!0}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function present(e,t,n){switch(t.kind){case`operation`:return presentOperation(e,t,n);case`statement`:return presentStatement(e,t,n);case`transaction`:case`savepoint`:case`connection`:return presentLifecycle(e,t,n);case`batch`:return;default:return presentNoted(e,t,n)}}function spanned(e,t,n,r,a){let settle=e=>{let t=Date.now();return r().then(r=>{if(a?.(r,t,e),r.status===`failure`&&r.recovered!==!0)throw i(d(n))})};return e.tracer&&t?e.tracer.startActiveSpan(t,settle):settle()}function presentOperation(e,t,n){return spanned(e,traces(e,v)?createOperationSpanOptions(t):void 0,t,n,(n,r)=>{for(let n of o(t)){let r=noteOf(n);r?.log===`cache`&&log(e,t,r)}let i=d(t);n.status===`failure`&&i instanceof Error&&logs(e,`error`)&&!e.logged.has(u(i))&&e.logger?.log({...presentNoteLog(t,`error`,{at:r+n.duration,error:i}),duration:n.duration})})}function presentStatement(e,t,n){let r=traces(e,b),i=logs(e,`query`),a=logs(e,`error`);if(!(r||i||a))return;let{logging:o,tracing:s}=e.config,l=(i||a)&&channelOf(o).includeParams||r&&channelOf(s).includeParams?f(t):void 0,p=Date.now();return spanned(e,r?createStatementSpanOptions(s,t,c(t),l):void 0,t,n,({duration:n,recovered:r,status:s})=>{let c=d(t),f=s===`failure`&&c instanceof Error;r===!0||!(f?a:s===`success`&&i)||(f&&e.logged.add(u(c)),e.logger?.log(createStatementLogEvent(o,t,p,n,l,f?c:void 0)))})}function presentLifecycle(e,t,n){let r=t.kind===`connection`?t.operation===`$disconnect`||t.operation===`disconnect`?B:g:_;if(traces(e,r))return spanned(e,createLifecycleSpanOptions(r,t),t,n)}function log(e,t,n){n?.log!==void 0&&logs(e,n.log)&&e.logger?.log(presentNoteLog(t,n.log,n))}function presentNoted(e,t,n){let r=o(t).length,i;for(let n of o(t)){let r=noteOf(n);i===void 0&&r?.span!==void 0&&(i={...r,span:r.span}),log(e,t,r)}return spanned(e,i!==void 0&&e.tracer!==void 0&&tracesAs(i)?createNotedSpanOptions(t,i):void 0,t,n,(n,i,a)=>{for(let n of o(t).slice(r)){let r=noteOf(n);r?.attributes!==void 0&&setSpanAttributes(a,notedAttributes(r.attributes)),log(e,t,r)}})}export{L as ATTR_CACHE_DRIVER,M as ATTR_CACHE_RESULT,F as ATTR_CACHE_TTL,k as ATTR_DB_BATCH_SIZE,S as ATTR_DB_COLLECTION,N as ATTR_DB_DRIVER,I as ATTR_DB_NAMESPACE,w as ATTR_DB_OPERATION_NAME,A as ATTR_DB_QUERY_PARAMETER_PREFIX,R as ATTR_DB_QUERY_SUMMARY,T as ATTR_DB_QUERY_TEXT,E as ATTR_DB_ROWS_RETURNED,P as ATTR_DB_SYSTEM,j as ATTR_ERROR_TYPE,O as ATTR_SERVER_ADDRESS,D as ATTR_SERVER_PORT,x as ATTR_VIBORM_CORRELATION_ID,z as SPAN_CACHE_CLEAR,H as SPAN_CACHE_DELETE,C as SPAN_CACHE_GET,V as SPAN_CACHE_INVALIDATE,y as SPAN_CACHE_SET,g as SPAN_CONNECT,B as SPAN_DISCONNECT,b as SPAN_EXECUTE,v as SPAN_OPERATION,_ as SPAN_TRANSACTION,instrumentation};
2
2
  //# sourceMappingURL=instrumentation.mjs.map
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,n}from"./base-z-cH5ZBI.mjs";import{t as r}from"./migrations-BMiRjR-N.mjs";import{s as i}from"./native-types-DgjMUikz.mjs";import{t as a}from"./hydration-A3zffFWP.mjs";import{$ as o,Ln as s,Q as c,Wn as l,_ as u,k as d,n as f,nn as p}from"./serializer-rBq3v1xr.mjs";import{n as m}from"./array-literal-DHinAnVs.mjs";import{t as h}from"./every-KV5yuSVT.mjs";import{a as g,n as _,r as v}from"./json-DgMc8-GU.mjs";const y=/^([a-z][a-z0-9+.-]*):/i,b=/\.(?:db|sqlite3?|db3)$/i;function sqlitePath(e){for(let t of[`sqlite://`,`sqlite:`,`file://`,`file:`])if(e.startsWith(t))return e.slice(t.length);return y.test(e)?void 0:e}async function openDriver(e){let t=y.exec(e)?.[1]?.toLowerCase();if(t===`postgres`||t===`postgresql`){let{PgDriver:t}=await import(`./pg.mjs`);return{driver:new t({databaseUrl:e,options:{}}),dialect:`postgresql`}}if(t===`libsql`||t===`http`||t===`https`||t===`ws`||t===`wss`){let{LibSQLDriver:t}=await import(`./libsql.mjs`),n=new URL(e),r=n.searchParams.get(`authToken`)??void 0;return n.searchParams.delete(`authToken`),{driver:new t({databaseUrl:n.href,...r===void 0?{}:{authToken:r}}),dialect:`sqlite`}}if(t===`mysql`){let{MySQL2Driver:t}=await import(`./mysql2.mjs`);return{driver:new t({databaseUrl:e}),dialect:`mysql`}}if(t===`snowflake`)throw new r(`A snowflake:// URL carries no key or token. Pass the driver instead: introspectSchema({ driver: new SnowflakeDriver({ databaseUrl, privateKey }) }) with SnowflakeDriver from "viborm/snowflake".`,n.INVALID_INPUT,{meta:{feature:`introspect-url`}});if(t===`surrealdb`||t===`surreal`)throw new r(`introspectSchema does not translate SurrealDB yet; PostgreSQL, SQLite and MySQL are supported.`,n.FEATURE_NOT_SUPPORTED,{meta:{feature:`introspect-schema`}});let i=sqlitePath(e);if(i!==void 0&&(t!==void 0||b.test(i)||i===`:memory:`)){let{SQLite3Driver:e}=await import(`./sqlite3.mjs`);return{driver:new e({dataDir:i,options:{readonly:!0,fileMustExist:!0}}),dialect:`sqlite`}}throw new r(`introspectSchema cannot tell which database "${t??e}" names. Use postgres:// or postgresql:// for PostgreSQL, mysql:// for MySQL, file: or sqlite: (or a .db / .sqlite file) for SQLite, and libsql:// for libSQL; or pass a driver.`,n.INVALID_INPUT,{meta:{feature:`introspect-url`}})}const x=new Set([d.state,d.log]);function refusedTable(e){if(!t(e))return;let n=e.meta?.table;return typeof n==`string`?n:void 0}async function introspectScope(e,t){let n=u(e,t);return await Object.getPrototypeOf(n).introspect.call(n,(t,n)=>e._executeRaw(t,n))}async function rows(e,t,n){return(await e._executeRaw(t,n)).rows}async function readCatalog(e,t,n){let r=u(e),i=[],a=new Map,o,s;for(;;){let t=a.size===0?n:(n??o??[]).filter(e=>!a.has(e));try{s=await introspectScope(e,t);break}catch(t){let i=refusedTable(t);if(i===void 0||a.has(i))throw t;if(a.set(i,t instanceof Error?t.message:`introspection refused it`),n===void 0&&o===void 0){let t=r.generateInventoryTables();o=(await rows(e,t.sql,t.params)).map(e=>e.name)}}}for(let[e,t]of a)i.push({kind:`table`,name:e,reason:t});let selected=e=>!(a.has(e)||x.has(e))&&(n===void 0||n.includes(e));for(let e of s.tables)x.has(e.name)&&i.push({kind:`table`,name:e.name,reason:`it is VibORM's migration control table`});let c=new Set;if(t===`postgresql`){let t=r.namespace;for(let n of await rows(e,`SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = $1 AND is_identity = 'YES'`,[t]))c.add(`${n.table_name}\0${n.column_name}`);for(let n of await rows(e,`SELECT table_name AS name, 'view' AS kind FROM information_schema.views WHERE table_schema = $1 UNION ALL SELECT matviewname AS name, 'materialized view' AS kind FROM pg_catalog.pg_matviews WHERE schemaname = $1 ORDER BY 1`,[t]))i.push({kind:`view`,name:n.name,reason:`it is a ${n.kind}, and a document declares tables only`});for(let n of await rows(e,`SELECT rel.relname AS table_name, con.conname AS name, pg_catalog.pg_get_constraintdef(con.oid) AS definition FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace ns ON ns.oid = rel.relnamespace WHERE ns.nspname = $1 AND con.contype = 'c' ORDER BY 1, 2`,[t]))selected(n.table_name)&&i.push({kind:`check`,table:n.table_name,name:n.name,reason:`a document has no CHECK constraint (${n.definition}); the database keeps enforcing it`})}else if(t===`mysql`){let t=r.namespace;for(let n of await rows(e,`SELECT TABLE_NAME AS name FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME`,[t]))i.push({kind:`view`,name:n.name,reason:`it is a view, and a document declares tables only`});for(let n of await rows(e,`SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS name, cc.CHECK_CLAUSE AS definition FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.CHECK_CONSTRAINTS cc ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK' ORDER BY 1, 2`,[t]))selected(n.table_name)&&i.push({kind:`check`,table:n.table_name,name:n.name,reason:`a document has no CHECK constraint (${n.definition}); the database keeps enforcing it`})}else if(t===`snowflake`){let t=r.namespace;for(let n of await rows(e,t===void 0?`SELECT TABLE_NAME AS "name" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = CURRENT_SCHEMA() ORDER BY TABLE_NAME`:`SELECT TABLE_NAME AS "name" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME`,t===void 0?[]:[t]))i.push({kind:`view`,name:n.name,reason:`it is a view, and a document declares tables only`})}else for(let t of await rows(e,`SELECT name FROM sqlite_master WHERE type = 'view' ORDER BY name`,[]))i.push({kind:`view`,name:t.name,reason:`it is a view, and a document declares tables only`});let l=s.tables.filter(e=>selected(e.name));return{snapshot:{...s,tables:l},skipped:i,identityColumns:c,hazards:await r.adoptionHazards(l.map(e=>e.name),async(t,n)=>({rows:await rows(e,t,n??[])})),migrationDriver:r}}const S=new Set([`string`,`int`,`number`,`decimal`,`boolean`,`datetime`,`date`,`time`,`bigint`,`blob`,`enum`]),C=/^'([\s\S]*)'$/,w=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,T=/^[+-]?\d+$/,E=new Set([`now()`,`now() at time zone 'utc'`,`date_trunc('milliseconds',now())`,`date_trunc('milliseconds',now() at time zone 'utc')`,`current_date`,`current_time`,`localtimestamp`,`localtime`,`timezone('utc',current_time)`,`timezone('utc',current_time(3))`,`strftime('%Y-%m-%dT%H:%M:%fZ','now')`,`current_timestamp(3)`,`current_timestamp(6)`,`(current_timestamp(3))`]),D=/^\d{4}-\d{2}-\d{2}$/,ee=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-]\d{2}(?::?\d{2})?|Z)?$/;function jsonDefault(e){return typeof e==`object`&&e&&!Array.isArray(e)&&Object.keys(e).length===1&&Object.keys(e)[0]?.startsWith(`$`)?{$raw:e}:e}const O=/^\(('[\s\S]*')\)$/,k=/\\(.)/g;function unquote(e,t){let n=e.replaceAll(`''`,`'`);if(t!==`mysql`)return n;let r=!0,i=n.replace(k,(e,t)=>{let n=l.get(t);return n===void 0&&(r=!1),n??t});return r?i:void 0}function coefficientText(e,t){if(t===0)return BigInt(e).toString();let n=e.startsWith(`-`),r=BigInt(n?e.slice(1):e).toString().padStart(t+1,`0`);return`${n?`-`:``}${r.slice(0,-t)}.${r.slice(-t)}`}function isCalendarDate(e,t){let[n,r,i]=e.split(`-`).map(Number),[a,o,s]=t.split(`:`).map(Number),c=new Date(0);return c.setUTCFullYear(n,r-1,i),c.setUTCHours(a,o,Math.trunc(s)),c.getUTCFullYear()===n&&c.getUTCMonth()===r-1&&c.getUTCDate()===i&&c.getUTCHours()===a&&c.getUTCMinutes()===o&&c.getUTCSeconds()===Math.trunc(s)}function literalValue(e,t,n){switch(e.type){case`string`:return n?t:void 0;case`enum`:return Array.isArray(e.enum)&&e.enum.includes(t)?t:void 0;case`int`:case`number`:return w.test(t)&&(e.type===`number`||T.test(t))?Number(t):void 0;case`bigint`:return T.test(t)?{$bigint:BigInt(t).toString()}:void 0;case`decimal`:return w.test(t)?t:void 0;case`boolean`:{let e=t.toLowerCase();return e===`true`||e===`t`||e===`1`?!0:e===`false`||e===`f`||e===`0`?!1:void 0}case`json`:try{return jsonDefault(JSON.parse(t))}catch{return}case`datetime`:{let e=ee.exec(t);if(!e||!isCalendarDate(e[1],e[2]))return;let n=e[3]??`Z`,r=n.length===3?`${n}:00`:n,i=new Date(`${e[1]}T${e[2]}${r}`);return Number.isNaN(i.getTime())?void 0:i.toISOString()}case`date`:return D.test(t)&&isCalendarDate(t,`00:00:00`)?t:void 0;default:return}}function readDefault(e,t,n,r){let i=c(n,t.type);if(i===void 0)return;let a=`the default \`${n}\` has no document spelling`;if(E.has(i)||E.has(i.toLowerCase())){if(e.type===`datetime`||e.type===`date`||e.type===`time`){if(e.array)return a;e.generate={kind:`now`};return}return a}if(i===`gen_random_uuid()`||i===`uuidv7()`){if(e.type!==`string`||e.array)return a;e.generate={kind:i===`gen_random_uuid()`?`uuid`:`uuidv7`};return}let o=n.trim(),s=r===`mysql`?O.exec(o)?.[1]:void 0,l=C.exec(s??o),u=l?unquote(l[1],r):n.trim();if(u===void 0)return a;if(e.array){if(!(l&&r===`postgresql`)){if(!l)return a;try{let t=JSON.parse(u);if(!Array.isArray(t))return a;let n=[];for(let r of t){let t=r===null?null:literalValue(e,typeof r==`string`?r:JSON.stringify(r),typeof r==`string`);if(t===void 0)return a;n.push(t)}e.default=n;return}catch{return a}}let t=m(u);if(t===void 0)return a;let n=[];for(let r of t){let t=r===null?null:literalValue(e,r,!0);if(t===void 0)return a;n.push(t)}e.default=n;return}let d=literalValue(e,e.type===`decimal`&&r===`sqlite`&&T.test(u)?coefficientText(u,e.scale):u,l!==null);if(d===void 0)return a;e.default=d}const A=/^varchar\((\d+)\)$/,j=/^char\((\d+)\)$/,M=/^(bit|varbit)(\((\d+)\))?$/,N=/^numeric\((\d+),(\d+)\)$/,P=/^timestamp(?:\((\d)\))?( with time zone)?$/,F=/^time(?:\((\d)\))?( with time zone)?$/,I=new Set([`citext`,`xml`,`inet`,`cidr`,`macaddr`,`macaddr8`,`tsvector`,`tsquery`]);function pgNative(e){return{db:`pg`,type:e}}function postgresBase(e,t,n){if(e===`text`)return{type:`string`};if(A.test(e)||j.test(e)||I.has(e)||M.exec(e))return{type:`string`,native:pgNative(e)};if(e===`uuid`)return n?{type:`string`,native:pgNative(`uuid`)}:{type:`string`,generate:{kind:`uuid`,generate:!1}};if(e===`integer`)return{type:`int`};if(e===`smallint`||e===`oid`)return{type:`int`,native:pgNative(e)};if(e===`bigint`)return{type:`bigint`};if(e===`real`)return{type:`number`,native:pgNative(`real`)};if(e===`double precision`)return{type:`number`};if(e===`boolean`)return{type:`boolean`};if(e===`date`)return{type:`date`};if(e===`bytea`)return{type:`blob`};if(e===`jsonb`)return{type:`json`};if(e===`json`)return{type:`json`,native:pgNative(`json`)};let r=N.exec(e);if(r){let e=t.decimal;return e===void 0?`numeric(${r[1]},${r[2]}) is outside VibORM's fixed-decimal domain`:{type:`decimal`,precision:e.precision,scale:e.scale}}if(e===`numeric`)return"an unconstrained `numeric` has no precision and scale, and a VibORM decimal declares both";if(e===`varchar`)return"`varchar` without a length has no document spelling (use `text`, or a length)";let i=P.exec(e);if(i){let e=i[1],t=i[2]!==void 0,n={type:`datetime`};if(t||(n.withoutTimezone=!0),e!==`3`){let r=t?`timestamptz`:`timestamp`;n.native=pgNative(e===void 0?r:`${r}(${e})`)}return n}let a=F.exec(e);if(a){let e=a[1],t=a[2]!==void 0,n={type:`time`};if(t||e!==`3`){let r=t?`timetz`:`time`;n.native=pgNative(e===void 0?r:`${r}(${e})`)}return n}return`the type \`${t.type}\` has no VibORM scalar`}function translatePostgresColumn(e){let{column:t}=e,n=t.type.endsWith(`[]`),r=n?t.type.slice(0,-2):t.type,i=e.enums.get(r),a;if(i)a={type:`enum`,enum:[...i.values]};else{let e=postgresBase(o(r),t,n);if(typeof e==`string`)return{skip:e};a=e}return finish(a,e,n,`postgresql`,i?.name)}function finish(e,t,n,r,i,a){let{column:o}=t;if(n){if(!S.has(e.type))return{skip:`a list of ${e.type} has no VibORM scalar`};e.array=!0}o.nullable&&(e.nullable=!0);let s;return t.identity||o.autoIncrement?e.type===`int`||e.type===`bigint`?e.generate={kind:`increment`}:s=`an auto-increment ${e.type} has no document spelling`:o.default!==void 0&&(s=readDefault(e,o,o.default,r)),{field:e,enumType:i,skippedDefault:s,approximated:a}}const L=/^TEXT CHECK\(/,R=/'((?:[^']|'')*)'/g;function sqliteEnumValues(e){let{type:t}=e.column,n=t.indexOf(` IN (`);if(n===-1)return;let r=[...t.slice(n).matchAll(R)].map(e=>e[1].replaceAll(`''`,`'`));return e.enumColumnType(r)===t?r:void 0}function sqliteAffinity(e){return e.includes(`INT`)?{type:`int`}:e.includes(`CHAR`)||e.includes(`CLOB`)||e.includes(`TEXT`)?{type:`string`}:e===``||e.includes(`BLOB`)?{type:`blob`}:e.includes(`REAL`)||e.includes(`FLOA`)||e.includes(`DOUB`)?{type:`number`}:e.includes(`BOOL`)?{type:`boolean`}:e.includes(`DATETIME`)||e.includes(`TIMESTAMP`)?{type:`datetime`}:e===`DATE`?{type:`date`}:{type:`number`}}function translateSqliteColumn(e){let{column:t}=e,n=t.type.trim().toUpperCase();if(t.decimal)return finish({type:`decimal`,precision:t.decimal.precision,scale:t.decimal.scale},e,n===`TEXT`,`sqlite`);if(L.test(t.type)){let n=sqliteEnumValues(e);return n===void 0?{skip:`the CHECK in \`${t.type}\` is not a VibORM enum`}:finish({type:`enum`,enum:n},e,!1,`sqlite`)}let r,i;switch(n){case`TEXT`:r=t.default?.trim()===`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`?{type:`datetime`}:{type:`string`};break;case`INTEGER`:r={type:`int`};break;case`REAL`:r={type:`number`};break;case`BLOB`:e.binaryKey?(r={type:`string`,generate:{kind:`uuid`,generate:!1}},i=`a BLOB key is read as a UUID, the key VibORM stores as sixteen bytes on SQLite; a key holding other bytes does not decode`):r={type:`blob`};break;case`JSON`:r={type:`json`};break;default:r=sqliteAffinity(n),i=`the declared type \`${t.type}\` is read by SQLite's affinity rules as ${r.type}, which VibORM spells \`${r.type===`string`?`TEXT`:r.type===`number`?`REAL`:r.type===`blob`?`BLOB`:r.type===`datetime`||r.type===`date`?`TEXT`:`INTEGER`}\``}return finish(r,e,!1,`sqlite`,void 0,i)}const z=/^(varchar|char|binary|varbinary|bit)\((\d+)\)$/,B=/^(datetime|timestamp|time)(?:\((\d)\))?$/,V=new Set([`tinyint`,`tinyint unsigned`,`smallint`,`smallint unsigned`,`mediumint`,`mediumint unsigned`,`int unsigned`,`year`]),H=new Set([`tinytext`,`mediumtext`,`longtext`]),U=new Set([`tinyblob`,`mediumblob`,`longblob`]),W=/^(tinyint|smallint|mediumint|int|bigint)\(\d+\)/;function mysqlNative(e){return{db:`mysql`,type:e}}function mysqlBase(e,t){let{column:n}=t;if(e===`text`)return{type:`string`};if(e===`tinyint(1)`)return{type:`boolean`};let r=e.replace(W,`$1`);if(r===`int`)return{type:`int`};if(r===`bigint`)return{type:`bigint`};if(r===`bigint unsigned`)return{type:`bigint`,native:mysqlNative(`BIGINT UNSIGNED`)};if(V.has(r))return{type:`int`,native:mysqlNative(r.toUpperCase())};if(r===`double`)return{type:`number`};if(r===`float`)return{type:`number`,native:mysqlNative(`FLOAT`)};if(r===`json`)return{type:`json`};if(r===`blob`)return{type:`blob`};if(U.has(r))return{type:`blob`,native:mysqlNative(r.toUpperCase())};if(H.has(r))return{type:`string`,native:mysqlNative(r.toUpperCase())};if(r===`date`)return{type:`date`};if(r.startsWith(`decimal(`)){let e=n.decimal;return e===void 0?`${n.type} is outside VibORM's fixed-decimal domain`:{type:`decimal`,precision:e.precision,scale:e.scale}}let i=z.exec(r);if(i){let[,e,n]=i;if(e===`binary`&&n===`16`&&t.binaryKey)return{type:`string`,generate:{kind:`uuid`,generate:!1}};if(e===`varchar`&&n===`191`&&t.keyed)return{type:`string`};let r=mysqlNative(`${e.toUpperCase()}(${n})`);return e===`binary`||e===`varbinary`?{type:`blob`,native:r}:{type:`string`,native:r}}let a=B.exec(r);if(a){let[,e,t]=a,n={type:e===`time`?`time`:`datetime`};return(e===`timestamp`||t!==`3`)&&(n.native=mysqlNative(t===void 0?e.toUpperCase():`${e.toUpperCase()}(${t})`)),n}return`the type \`${n.type}\` has no VibORM scalar`}function translateMysqlColumn(e){let{column:t}=e;if(t.type.toUpperCase().startsWith(`ENUM(`)){let n=e.enums.get(t.type);return n===void 0||e.enumColumnType(n.values)!==t.type?{skip:`the enum \`${t.type}\` is not one VibORM spells`}:finish({type:`enum`,enum:[...n.values]},e,!1,`mysql`)}let n=mysqlBase(t.type.trim().toLowerCase(),e);return typeof n==`string`?{skip:n}:finish(n,e,!1,`mysql`,void 0,n.type===`string`&&n.generate?.kind===`uuid`?`a BINARY(16) key is read as a UUID, the key VibORM stores as sixteen bytes on MySQL; a key holding other bytes does not decode`:void 0)}const G=/^number\((\d+),(\d+)\)$/,K=/\(.*\)$/,q=/^vector\((float|int), (\d+)\)$/,J=/^(?:current_timestamp|sysdate|systimestamp|localtimestamp|current_date|current_time|getdate)(?:\(\d*\))?$/i;function snowflakeBase(e){let t=e.type.toLowerCase(),n=G.exec(t);if(n){let e=Number(n[1]),t=Number(n[2]);return t===0?{type:e<=9?`int`:`bigint`}:{type:`decimal`,precision:e,scale:t}}switch(t.replace(K,``)){case`float`:return{type:`number`};case`varchar`:return{type:`string`};case`boolean`:return{type:`boolean`};case`date`:return{type:`date`};case`time`:return{type:`time`};case`timestamp_ntz`:case`timestamp_ltz`:case`timestamp_tz`:return{type:`datetime`};case`binary`:return{type:`blob`};case`variant`:case`object`:case`array`:return{type:`json`};case`geography`:return{type:`point`};case`geometry`:return`a GEOMETRY is planar, in any SRID: VibORM's point is a geographic EPSG:4326 point (a GEOGRAPHY)`;default:break}let r=q.exec(t);return r?.[1]===`float`?{type:`vector`,dimension:Number(r[2])}:r?"a VECTOR(INT) has no VibORM scalar: `s.vector()` holds floats":`the type \`${e.type.toUpperCase()}\` has no VibORM scalar`}function translateSnowflakeColumn(e){let{column:t}=e,n=snowflakeBase(t);if(typeof n==`string`)return{skip:n};let r=t.type.toLowerCase().replace(K,``),i=r===`timestamp_ntz`?`a TIMESTAMP_NTZ holds a wall clock with no zone; VibORM reads it as UTC`:r===`geography`?`a GEOGRAPHY may hold any shape; VibORM reads it as a point, and a row holding another shape does not decode`:void 0;if(t.default!==void 0&&J.test(t.default.trim())&&(n.type===`datetime`||n.type===`date`||n.type===`time`)){n.generate={kind:`now`};let{default:r,...a}=t;return finish(n,{...e,column:a},!1,`snowflake`,void 0,i)}return finish(n,e,!1,`snowflake`,void 0,i)}const Y=new Set([`_count`,`_distance`]),X=/[^a-zA-Z0-9_]/g,Z=/^[0-9]/;function keyCandidate(e){let t=e.replace(X,`_`);return(t===``||Z.test(t))&&(t=`_${t}`),t.slice(0,60)}var KeyAllocator=class{#e=new Set;#t;constructor(e=new Set){this.#t=e}#n(e){return!(this.#e.has(e)||this.#t.has(e))&&i(e)}claimName(e){return this.#n(e)?(this.#e.add(e),e):this.claim(keyCandidate(e))}claim(e){let t=keyCandidate(e),n=t;for(let e=2;!this.#n(n);e++)n=`${t}_${e}`;return this.#e.add(n),n}};function memberAllocator(){return new KeyAllocator(Y)}const Q=/^(.+)_id$/i,te=/^(.*[a-z0-9])I[dD]$/;function relationNameFromColumn(e){return(Q.exec(e)??te.exec(e))?.[1]}const ne={postgresql:translatePostgresColumn,sqlite:translateSqliteColumn,mysql:translateMysqlColumn,snowflake:translateSnowflakeColumn},re={postgresql:void 0,sqlite:`BLOB`,mysql:`BINARY(16)`,snowflake:void 0},$="its name is not an identifier (ASCII letters, digits and _, at most 63 bytes), which is all `.map()` accepts";function junctionAction(e){let t=e??`noAction`;return t===`cascade`||t===`restrict`||t===`noAction`?t:void 0}function generatedJunction(e,t,n){let r=junctionAction(t.onDelete),i=junctionAction(n.onDelete),a=junctionAction(t.onUpdate),o=junctionAction(n.onUpdate);if(r===void 0||i===void 0||a===void 0||o===void 0)return;let s=r===i?{onDelete:r}:{onDeleteSides:{source:r,target:i}},c=a===o?{onUpdate:a}:{onUpdateSides:{source:a,target:o}};return{table:e,source:t.columns[0],target:n.columns[0],...s,...c}}function sameSet(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function sorted(e){return[...e].sort()}function translateSnapshot(e){let{snapshot:t,dialect:n,migrationDriver:r}=e,a=[],o=[],c=r.capabilities.introspectionReadsConstraintNames,l=new Map((t.enums??[]).map(e=>[e.name,e])),u=ne[n],d=new Set,f=re[n];if(f!==void 0){let isBlob=(e,t)=>e.columns.find(e=>e.name===t)?.type.toUpperCase()===f;for(let e of t.tables)for(let t of e.primaryKey?.columns??[])isBlob(e,t)&&d.add(`${e.name}\0${t}`);for(let e=!0;e;){e=!1;for(let n of t.tables)for(let t of n.foreignKeys)t.columns.forEach((r,i)=>{let a=`${n.name}\0${r}`,o=`${t.referencedTable}\0${t.referencedColumns[i]}`;!d.has(a)&&d.has(o)&&isBlob(n,r)&&(d.add(a),e=!0)})}}let keyedColumns=e=>new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.raw?[]:e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),p=new KeyAllocator,m=new Map,h=new Map;for(let n of t.tables){let t=n.primaryKey;if(!t||t.columns.length===0){a.push({kind:`table`,name:n.name,reason:`it has no primary key, and a VibORM model is addressed by one`});continue}if(!i(n.name)){a.push({kind:`table`,name:n.name,reason:$});continue}let s=new Map,c=keyedColumns(n);for(let t of n.columns){if(!i(t.name)){s.set(t.name,{skip:$});continue}s.set(t.name,u({column:t,enums:l,identity:e.identityColumns.has(`${n.name}\0${t.name}`),enumColumnType:e=>r.getEnumColumnType(n.name,t.name,e),binaryKey:d.has(`${n.name}\0${t.name}`),keyed:c.has(t.name)}))}let f=t.columns.find(e=>{let t=s.get(e);return t===void 0||`skip`in t});if(f!==void 0){let e=s.get(f);a.push({kind:`table`,name:n.name,reason:`its primary key column "${f}" cannot be translated: ${e&&`skip`in e?e.skip:`it is not a column of the table`}`});continue}let _=p.claimName(n.name),v={},y={fields:v};_!==n.name&&(y.table=n.name);let b={key:_,table:n,members:memberAllocator(),fields:v,fieldOf:new Map,document:y,keys:[]};for(let e of n.columns){let t=s.get(e.name);if(`skip`in t){a.push({kind:`column`,table:n.name,name:e.name,reason:t.skip});continue}let r=b.members.claimName(e.name),i={...t.field};if(r!==e.name&&(i.column=e.name),v[r]=i,b.fieldOf.set(e.name,r),t.enumType!==void 0){let n=h.get(t.enumType)??[];n.push({build:b,field:r,column:e.name}),h.set(t.enumType,n)}t.skippedDefault!==void 0&&a.push({kind:`default`,table:n.name,name:e.name,reason:t.skippedDefault}),t.approximated!==void 0&&o.push({kind:`approximated`,table:n.name,name:e.name,message:t.approximated})}let x=t.columns.map(e=>b.fieldOf.get(e));if(x.forEach((e,r)=>{let i=v[e];g(i)||!i.nullable||(i.nullable=!1,o.push({kind:`approximated`,table:n.name,name:t.columns[r],message:"the database lets this primary key column hold NULL (SQLite does unless it is NOT NULL, outside a rowid table's INTEGER key), and the document declares it NOT NULL, as every model key is: a push of the document rebuilds the table to make it NOT NULL, which fails while a row's key is NULL and cannot keep what the table carries beyond the document (its `unstated` warnings)"}))}),x.length===1){let e=v[x[0]];e.type!==`toOne`&&e.type!==`toMany`&&(Object.assign(e,{id:!0}),e.type===`string`&&e.generate===void 0&&Object.assign(e,{generate:{kind:`ulid`,generate:!1,implicit:!0}}))}else y.ids=[{fields:x}];t.withoutRowid&&(y.withoutRowid=!0),b.keys.push(sorted(t.columns)),m.set(n.name,b)}for(let e of m.values()){let{table:t,fields:n,document:r,fieldOf:l}=e,u=[],d=[],missing=e=>e.find(e=>!l.has(e)),derivedUnique=(e,n)=>e.startsWith(`${t.name}_`)&&e.endsWith(`_key`)&&n.every(e=>l.has(e)),f=t.indexes.filter(e=>e.unique&&!e.raw&&e.where===void 0&&(e.type===void 0||e.type===`btree`)&&derivedUnique(e.name,e.columns)),p=[...t.uniqueConstraints,...f.map(e=>({name:e.name,columns:e.columns}))];for(let r of p){let f=missing(r.columns);if(f!==void 0){a.push({kind:`uniqueConstraint`,table:t.name,name:r.name,reason:`its column "${f}" is not translated`});continue}let p=r.columns.map(e=>l.get(e)),derived=e=>s(`${t.name}_${e}_key`);if(p.length===1&&(!c||r.name===derived(r.columns[0]))){Object.assign(n[p[0]],{unique:!0}),e.keys.push(sorted(r.columns));continue}if(!c||r.name===derived(p.join(`_`))){d.push({fields:p}),e.keys.push(sorted(r.columns));continue}let m=`${t.name}_`,h=r.name.startsWith(m)&&r.name.endsWith(`_key`)?r.name.slice(m.length,-4):void 0;if(h!==void 0&&i(h)){d.push({fields:p,name:h}),e.keys.push(sorted(r.columns));continue}u.push({fields:p,name:r.name,unique:!0}),o.push({kind:`approximated`,table:t.name,name:r.name,message:`the unique constraint "${r.name}" is declared as a unique index under the same name, because a document names compound keys "<table>_<name>_key"; it is not a key \`findUnique\` accepts`})}for(let e of t.indexes){if(f.includes(e))continue;let n=missing(e.columns),r=e.raw?"it is a raw index (`.rawIndex()`), which a document cannot declare: keep it in a TypeScript schema":e.where===void 0?n===void 0?void 0:`its column "${n}" is not translated`:`it is a partial index (WHERE ${e.where}), and a document has no \`where\`: keep it in a TypeScript schema`;if(r!==void 0){a.push({kind:`index`,table:t.name,name:e.name,reason:r});continue}let i={fields:e.columns.map(e=>l.get(e)),name:e.name};e.unique&&(i.unique=!0),e.type!==void 0&&e.type!==`btree`&&(i.type=e.type),u.push(i)}d.length>0&&(r.uniques=d),u.length>0&&(r.indexes=u)}let _=new Map;for(let e of m.values()){let t=[],n=[...e.table.foreignKeys].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0);for(let r of n){let n=m.get(r.referencedTable),skip=t=>a.push({kind:`foreignKey`,table:e.table.name,name:r.name,reason:t});if(n===void 0){skip(`it references "${r.referencedTable}", which the document does not declare`);continue}let i=r.columns.find(t=>!e.fieldOf.has(t)),o=r.referencedColumns.find(e=>!n.fieldOf.has(e));if(i!==void 0||o!==void 0){skip(`its column "${i??`${r.referencedTable}.${o}`}" is not translated`);continue}if(r.onDelete===`setDefault`||r.onUpdate===`setDefault`){skip(`its referential action is SET DEFAULT, which a VibORM relation does not declare`);continue}if(!n.keys.some(e=>sameSet(e,r.referencedColumns))){skip(`it references (${r.referencedColumns.join(`, `)}) of "${r.referencedTable}", which the document does not declare as a key`);continue}t.push({owner:e,target:n,fk:r})}_.set(e,t)}let v=new Map;for(let[e,n]of _){let[r,i]=n;if(n.length!==2||r===void 0||i===void 0)continue;let a=e.table;if(t.tables.some(e=>e!==a&&e.foreignKeys.some(e=>e.referencedTable===a.name)))continue;let o=a.columns.map(e=>e.name),s=[...r.fk.columns,...i.fk.columns];a.foreignKeys.length!==2||r.fk.columns.some(e=>i.fk.columns.includes(e))||!sameSet(s,o)||!sameSet(a.primaryKey?.columns??[],o)||!n.every(e=>sameSet(e.fk.referencedColumns,e.target.table.primaryKey?.columns??[]))||v.set(e,[r,i])}let y=new Map,addPair=(e,t,n,r)=>{let i=e.key<t.key?[e.key,t.key]:[t.key,e.key],a=i.join(`\0`),o=y.get(a)??[];o.push({models:i,label:n,slots:r}),y.set(a,o)},b=new Set,action=e=>e===void 0||e===`setDefault`?`noAction`:e,relationNames=(e,t)=>{let{owner:n,target:r,fk:i}=e,a=i.columns.length===1?relationNameFromColumn(n.fieldOf.get(i.columns[0])):void 0,o=n.members.claim(a??r.key),s=n===r||t.filter(e=>e.target===r).length>1;return{toOne:o,inverse:r.members.claim(s?`${n.key}_by_${o}`:n.key)}};for(let t of m.values()){let n=_.get(t)??[],r=v.get(t);if(r){let[n,i]=r,a=n.fk.columns.length===1&&i.fk.columns.length===1?generatedJunction(t.table.name,n.fk,i.fk):void 0;if(!e.junctionModels.has(t.table.name)&&a!==void 0){m.delete(t.table.name),b.add(t.table.name);let e=n.target,r=i.target,o=e.members.claim(relationNameFromColumn(i.fk.columns[0])??r.key),s=r.members.claim(relationNameFromColumn(n.fk.columns[0])??e.key);e.fields[o]={type:`toMany`,target:r.key,junction:a},r.fields[s]={type:`toMany`,target:e.key},addPair(e,r,t.table.name,[{model:e,key:o},{model:r,key:s}]);continue}}let i=new Map;for(let e of n){let{target:r,fk:a}=e,{toOne:o,inverse:s}=relationNames(e,n);i.set(e,{toOne:o,inverse:s});let c={type:`toOne`,target:r.key,fields:a.columns.map(e=>t.fieldOf.get(e)),references:a.referencedColumns.map(e=>r.fieldOf.get(e)),onDelete:action(a.onDelete),onUpdate:action(a.onUpdate)};t.fields[o]=c;let l=t.keys.some(e=>sameSet(e,a.columns));r.fields[s]=l?{type:`toOne`,target:t.key}:{type:`toMany`,target:t.key},addPair(t,r,a.name,[{model:t,key:o},{model:r,key:s}])}if(r){let[e,n]=r,a=e.target,o=n.target,s=i.get(e).toOne,c=i.get(n).toOne,l=a.members.claim(c),u=o.members.claim(s);a.fields[l]={type:`toMany`,target:o.key,junction:{model:t.key,source:s,target:c}},o.fields[u]={type:`toMany`,target:a.key},addPair(a,o,t.table.name,[{model:a,key:l},{model:o,key:u}])}}for(let e of y.values())if(e.length>1||e[0].models[0]===e[0].models[1])for(let t of e)for(let e of t.slots)Object.assign(e.model.fields[e.key],{name:t.label});let x={},S=new KeyAllocator;for(let[e,t]of n===`postgresql`?l:[]){let n=(h.get(e)??[]).filter(e=>m.has(e.build.table.name));if(n.length===0){a.push({kind:`enum`,name:e,reason:`no translated column uses it, and a document declares an enum through its fields`});continue}let i=n.length===1?n[0]:void 0;if(i&&r.getEnumColumnType(i.build.table.name,i.column,t.values)===e)continue;let o=S.claimName(e);x[o]={values:[...t.values],name:e};for(let e of n)Object.assign(e.build.fields[e.field],{enum:o})}let C={};for(let e of m.values())C[e.key]=e.document;return{document:{version:1,...Object.keys(x).length>0?{enums:x}:{},models:C},skipped:a,warnings:o,tables:new Set([...[...m.values()].map(e=>e.table.name),...b]),generatedJunctions:b}}function describeColumn(e){return`${e.type}${e.nullable?` NULL`:` NOT NULL`}${e.default===void 0?``:` DEFAULT ${e.default}`}`}function operationType(e){return e.type}function describe(e){let push=(e,t,n)=>({kind:`drift`,table:e,name:t,message:`push would ${n}`});switch(e.type){case`createTable`:return push(e.table.name,void 0,`create table "${e.table.name}"`);case`dropTable`:return push(e.tableName,void 0,`drop table "${e.tableName}"`);case`addColumn`:return push(e.tableName,e.column.name,`add column "${e.column.name}" (${describeColumn(e.column)})`);case`dropColumn`:return push(e.tableName,e.columnName,`drop column "${e.columnName}"`);case`alterColumn`:return push(e.tableName,e.columnName,`alter column "${e.columnName}" from ${describeColumn(e.from)} to ${describeColumn(e.to)}`);case`createIndex`:return push(e.tableName,e.index.name,`create index "${e.index.name}" on (${e.index.columns.join(`, `)})`);case`dropIndex`:return push(e.tableName,e.indexName,`drop index "${e.indexName}"`);case`addForeignKey`:return push(e.tableName,e.fk.name,`add foreign key "${e.fk.name}" on (${e.fk.columns.join(`, `)})`);case`dropForeignKey`:return push(e.tableName,e.fkName,`drop foreign key "${e.fkName}"`);case`addUniqueConstraint`:return push(e.tableName,e.constraint.name,`add unique constraint "${e.constraint.name}" on (${e.constraint.columns.join(`, `)})`);case`dropUniqueConstraint`:return push(e.tableName,e.constraintName,`drop unique constraint "${e.constraintName}"`);case`addPrimaryKey`:return push(e.tableName,e.primaryKey.name,`add a primary key on (${e.primaryKey.columns.join(`, `)})`);case`dropPrimaryKey`:return push(e.tableName,e.constraintName,`drop primary key "${e.constraintName}"`);case`createEnum`:return push(void 0,e.enumDef.name,`create enum "${e.enumDef.name}"`);case`dropEnum`:return push(void 0,e.enumName,`drop enum "${e.enumName}"`);case`alterEnum`:return push(void 0,e.enumName,`alter enum "${e.enumName}"`);case`renameTable`:return push(e.from,void 0,`rename table "${e.from}" to "${e.to}"`);case`renameColumn`:return push(e.tableName,e.from,`rename column "${e.from}" to "${e.to}"`);default:return push(void 0,void 0,operationType(e))}}function tableOf(e){return e.table}async function verifyDocument(e,t,n){let r=_(e,{validate:!0});a(r);let i=f(r,{migrationDriver:n}),o=n.capabilities.introspectionReadsConstraintNames,s=await p(t,i,{matchConstraintsByShape:!o,refuseConstraintNameChurn:!1}),c=new Set,l=[];for(let e of s.operations){if(e.type!==`addForeignKey`&&e.type!==`addUniqueConstraint`)continue;let n=(e.type===`addForeignKey`?e.fk:e.constraint).columns.join(`\0`),r=t.tables.find(t=>t.name===e.tableName),i=s.operations.find(t=>c.has(t)?!1:e.type===`addForeignKey`&&t.type===`dropForeignKey`&&t.tableName===e.tableName?r?.foreignKeys.some(r=>r.name===t.fkName&&r.columns.join(`\0`)===n&&r.referencedTable===e.fk.referencedTable):e.type===`addUniqueConstraint`&&t.type===`dropUniqueConstraint`&&t.tableName===e.tableName?r?.uniqueConstraints.some(e=>e.name===t.constraintName&&e.columns.join(`\0`)===n):!1);if(i===void 0)continue;c.add(e),c.add(i);let a=i.type===`dropForeignKey`?i.fkName:i.type===`dropUniqueConstraint`?i.constraintName:``,o=e.type===`addForeignKey`?e.fk.name:e.constraint.name;l.push({kind:`drift`,table:e.tableName,name:a,message:`push refuses this table: the constraint "${a}" is the one VibORM names "${o}", and a document cannot name it`})}for(let e of s.operations)c.has(e)||l.push(describe(e));for(let e of s.ambiguousChanges)l.push(e.type===`ambiguousColumn`?{kind:`drift`,table:e.tableName,name:e.droppedColumn.name,message:`push would replace column "${e.droppedColumn.name}" by "${e.addedColumn.name}"`}:{kind:`drift`,table:e.droppedTable,message:`push would replace table "${e.droppedTable}" by "${e.addedTable}"`});if(o){let e=new Map(i.tables.map(e=>[e.name,e]));for(let n of t.tables){let t=n.primaryKey?.name,r=e.get(n.name)?.primaryKey?.name;t!==void 0&&r!==void 0&&t!==r&&l.push({kind:`drift`,table:n.name,name:t,message:`push refuses this table: its primary key is named "${t}" and VibORM names it "${r}"`})}}let u=new Set;for(let e of l){let t=tableOf(e);t!==void 0&&u.add(t)}return{warnings:l,drifted:u}}h();const ie=[`postgresql`,`sqlite`,`mysql`,`snowflake`],ae={kind:`approximated`,message:`Snowflake enforces no primary, unique or foreign key: the document's keys, uniques and relations are the ones the catalog declares, and a row may break them`};function isIntrospectionDialect(e){return ie.some(t=>t===e)}function declaredSnapshot(e,t){let n=e.tables.filter(e=>t.has(e.name)),r=new Set(n.flatMap(e=>e.columns.map(e=>e.type.endsWith(`[]`)?e.type.slice(0,-2):e.type))),i=e.enums?.filter(e=>r.has(e.name));return{tables:n,...i&&i.length>0?{enums:i}:{}}}function lighten(e){let t=new Set,n={};for(let[r,{indexes:i,...a}]of Object.entries(e.document.models)){for(let e of i??[])t.add(`${a.table??r}\0${e.name}`);n[r]=a}return{...e,document:v(_({...e.document,light:!0,models:n})),skipped:e.skipped.filter(e=>e.kind!==`index`&&e.kind!==`check`),warnings:e.warnings.filter(e=>e.kind===`approximated`&&!t.has(`${e.table}\0${e.name}`))}}async function introspectDriver(e,t){let i=e.dialect;if(!isIntrospectionDialect(i))throw new r(`introspectSchema does not translate ${i} yet; PostgreSQL, SQLite, MySQL and Snowflake are supported.`,n.FEATURE_NOT_SUPPORTED,{meta:{dialect:i,feature:`introspect-schema`}});let a=await readCatalog(e,i,t),o=new Set;for(let e=0;;e++){let t=translateSnapshot({snapshot:a.snapshot,dialect:i,migrationDriver:a.migrationDriver,identityColumns:a.identityColumns,junctionModels:o}),n=i===`snowflake`?{warnings:[ae],drifted:new Set}:await verifyDocument(t.document,declaredSnapshot(a.snapshot,t.tables),a.migrationDriver),r=[...t.generatedJunctions].filter(e=>n.drifted.has(e));if(r.length>0&&e===0){for(let e of r)o.add(e);continue}return{document:v(_(t.document)),skipped:[...a.skipped,...t.skipped],warnings:[...t.warnings,...a.hazards.filter(({table:e,feature:n})=>t.tables.has(e)&&!n.startsWith(`CHECK`)).map(({table:e,feature:t})=>({kind:`unstated`,table:e,message:`the document cannot carry ${t}: the database keeps it and a push of the document plans nothing for it, but a push that recreates the table or the column cannot keep it`})),...n.warnings],dialect:i}}}async function introspectSchema(e){let read=async t=>{let n=await introspectDriver(t,e.tables);return e.light?lighten(n):n};if(e.driver!==void 0)return await read(e.driver);let{driver:t}=await openDriver(e.url);try{return await read(t)}finally{await t.disconnect()}}export{introspectSchema as t};
2
- //# sourceMappingURL=introspect-DD_5FEl0.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,n}from"./base-z-cH5ZBI.mjs";import{t as r}from"./migrations-BMiRjR-N.mjs";import{s as i}from"./native-types-DgjMUikz.mjs";import{t as a}from"./hydration-A3zffFWP.mjs";import{$ as o,Ln as s,Q as c,Wn as l,_ as u,k as d,n as f,nn as p}from"./serializer-rBq3v1xr.mjs";import{n as m}from"./array-literal-DHinAnVs.mjs";import{t as h}from"./every-tOgQmaIE.mjs";import{a as g,n as _,r as v}from"./json-DgMc8-GU.mjs";const y=/^([a-z][a-z0-9+.-]*):/i,b=/\.(?:db|sqlite3?|db3)$/i;function sqlitePath(e){for(let t of[`sqlite://`,`sqlite:`,`file://`,`file:`])if(e.startsWith(t))return e.slice(t.length);return y.test(e)?void 0:e}async function openDriver(e){let t=y.exec(e)?.[1]?.toLowerCase();if(t===`postgres`||t===`postgresql`){let{PgDriver:t}=await import(`./pg.mjs`);return{driver:new t({databaseUrl:e,options:{}}),dialect:`postgresql`}}if(t===`libsql`||t===`http`||t===`https`||t===`ws`||t===`wss`){let{LibSQLDriver:t}=await import(`./libsql.mjs`),n=new URL(e),r=n.searchParams.get(`authToken`)??void 0;return n.searchParams.delete(`authToken`),{driver:new t({databaseUrl:n.href,...r===void 0?{}:{authToken:r}}),dialect:`sqlite`}}if(t===`mysql`){let{MySQL2Driver:t}=await import(`./mysql2.mjs`);return{driver:new t({databaseUrl:e}),dialect:`mysql`}}if(t===`snowflake`)throw new r(`A snowflake:// URL carries no key or token. Pass the driver instead: introspectSchema({ driver: new SnowflakeDriver({ databaseUrl, privateKey }) }) with SnowflakeDriver from "viborm/snowflake".`,n.INVALID_INPUT,{meta:{feature:`introspect-url`}});if(t===`surrealdb`||t===`surreal`)throw new r(`introspectSchema does not translate SurrealDB yet; PostgreSQL, SQLite and MySQL are supported.`,n.FEATURE_NOT_SUPPORTED,{meta:{feature:`introspect-schema`}});let i=sqlitePath(e);if(i!==void 0&&(t!==void 0||b.test(i)||i===`:memory:`)){let{SQLite3Driver:e}=await import(`./sqlite3.mjs`);return{driver:new e({dataDir:i,options:{readonly:!0,fileMustExist:!0}}),dialect:`sqlite`}}throw new r(`introspectSchema cannot tell which database "${t??e}" names. Use postgres:// or postgresql:// for PostgreSQL, mysql:// for MySQL, file: or sqlite: (or a .db / .sqlite file) for SQLite, and libsql:// for libSQL; or pass a driver.`,n.INVALID_INPUT,{meta:{feature:`introspect-url`}})}const x=new Set([d.state,d.log]);function refusedTable(e){if(!t(e))return;let n=e.meta?.table;return typeof n==`string`?n:void 0}async function introspectScope(e,t){let n=u(e,t);return await Object.getPrototypeOf(n).introspect.call(n,(t,n)=>e._executeRaw(t,n))}async function rows(e,t,n){return(await e._executeRaw(t,n)).rows}async function readCatalog(e,t,n){let r=u(e),i=[],a=new Map,o,s;for(;;){let t=a.size===0?n:(n??o??[]).filter(e=>!a.has(e));try{s=await introspectScope(e,t);break}catch(t){let i=refusedTable(t);if(i===void 0||a.has(i))throw t;if(a.set(i,t instanceof Error?t.message:`introspection refused it`),n===void 0&&o===void 0){let t=r.generateInventoryTables();o=(await rows(e,t.sql,t.params)).map(e=>e.name)}}}for(let[e,t]of a)i.push({kind:`table`,name:e,reason:t});let selected=e=>!(a.has(e)||x.has(e))&&(n===void 0||n.includes(e));for(let e of s.tables)x.has(e.name)&&i.push({kind:`table`,name:e.name,reason:`it is VibORM's migration control table`});let c=new Set;if(t===`postgresql`){let t=r.namespace;for(let n of await rows(e,`SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = $1 AND is_identity = 'YES'`,[t]))c.add(`${n.table_name}\0${n.column_name}`);for(let n of await rows(e,`SELECT table_name AS name, 'view' AS kind FROM information_schema.views WHERE table_schema = $1 UNION ALL SELECT matviewname AS name, 'materialized view' AS kind FROM pg_catalog.pg_matviews WHERE schemaname = $1 ORDER BY 1`,[t]))i.push({kind:`view`,name:n.name,reason:`it is a ${n.kind}, and a document declares tables only`});for(let n of await rows(e,`SELECT rel.relname AS table_name, con.conname AS name, pg_catalog.pg_get_constraintdef(con.oid) AS definition FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid JOIN pg_catalog.pg_namespace ns ON ns.oid = rel.relnamespace WHERE ns.nspname = $1 AND con.contype = 'c' ORDER BY 1, 2`,[t]))selected(n.table_name)&&i.push({kind:`check`,table:n.table_name,name:n.name,reason:`a document has no CHECK constraint (${n.definition}); the database keeps enforcing it`})}else if(t===`mysql`){let t=r.namespace;for(let n of await rows(e,`SELECT TABLE_NAME AS name FROM information_schema.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME`,[t]))i.push({kind:`view`,name:n.name,reason:`it is a view, and a document declares tables only`});for(let n of await rows(e,`SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS name, cc.CHECK_CLAUSE AS definition FROM information_schema.TABLE_CONSTRAINTS tc JOIN information_schema.CHECK_CONSTRAINTS cc ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME WHERE tc.CONSTRAINT_SCHEMA = ? AND tc.CONSTRAINT_TYPE = 'CHECK' ORDER BY 1, 2`,[t]))selected(n.table_name)&&i.push({kind:`check`,table:n.table_name,name:n.name,reason:`a document has no CHECK constraint (${n.definition}); the database keeps enforcing it`})}else if(t===`snowflake`){let t=r.namespace;for(let n of await rows(e,t===void 0?`SELECT TABLE_NAME AS "name" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = CURRENT_SCHEMA() ORDER BY TABLE_NAME`:`SELECT TABLE_NAME AS "name" FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME`,t===void 0?[]:[t]))i.push({kind:`view`,name:n.name,reason:`it is a view, and a document declares tables only`})}else for(let t of await rows(e,`SELECT name FROM sqlite_master WHERE type = 'view' ORDER BY name`,[]))i.push({kind:`view`,name:t.name,reason:`it is a view, and a document declares tables only`});let l=s.tables.filter(e=>selected(e.name));return{snapshot:{...s,tables:l},skipped:i,identityColumns:c,hazards:await r.adoptionHazards(l.map(e=>e.name),async(t,n)=>({rows:await rows(e,t,n??[])})),migrationDriver:r}}const S=new Set([`string`,`int`,`number`,`decimal`,`boolean`,`datetime`,`date`,`time`,`bigint`,`blob`,`enum`]),C=/^'([\s\S]*)'$/,w=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,T=/^[+-]?\d+$/,E=new Set([`now()`,`now() at time zone 'utc'`,`date_trunc('milliseconds',now())`,`date_trunc('milliseconds',now() at time zone 'utc')`,`current_date`,`current_time`,`localtimestamp`,`localtime`,`timezone('utc',current_time)`,`timezone('utc',current_time(3))`,`strftime('%Y-%m-%dT%H:%M:%fZ','now')`,`current_timestamp(3)`,`current_timestamp(6)`,`(current_timestamp(3))`]),D=/^\d{4}-\d{2}-\d{2}$/,ee=/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-]\d{2}(?::?\d{2})?|Z)?$/;function jsonDefault(e){return typeof e==`object`&&e&&!Array.isArray(e)&&Object.keys(e).length===1&&Object.keys(e)[0]?.startsWith(`$`)?{$raw:e}:e}const O=/^\(('[\s\S]*')\)$/,k=/\\(.)/g;function unquote(e,t){let n=e.replaceAll(`''`,`'`);if(t!==`mysql`)return n;let r=!0,i=n.replace(k,(e,t)=>{let n=l.get(t);return n===void 0&&(r=!1),n??t});return r?i:void 0}function coefficientText(e,t){if(t===0)return BigInt(e).toString();let n=e.startsWith(`-`),r=BigInt(n?e.slice(1):e).toString().padStart(t+1,`0`);return`${n?`-`:``}${r.slice(0,-t)}.${r.slice(-t)}`}function isCalendarDate(e,t){let[n,r,i]=e.split(`-`).map(Number),[a,o,s]=t.split(`:`).map(Number),c=new Date(0);return c.setUTCFullYear(n,r-1,i),c.setUTCHours(a,o,Math.trunc(s)),c.getUTCFullYear()===n&&c.getUTCMonth()===r-1&&c.getUTCDate()===i&&c.getUTCHours()===a&&c.getUTCMinutes()===o&&c.getUTCSeconds()===Math.trunc(s)}function literalValue(e,t,n){switch(e.type){case`string`:return n?t:void 0;case`enum`:return Array.isArray(e.enum)&&e.enum.includes(t)?t:void 0;case`int`:case`number`:return w.test(t)&&(e.type===`number`||T.test(t))?Number(t):void 0;case`bigint`:return T.test(t)?{$bigint:BigInt(t).toString()}:void 0;case`decimal`:return w.test(t)?t:void 0;case`boolean`:{let e=t.toLowerCase();return e===`true`||e===`t`||e===`1`?!0:e===`false`||e===`f`||e===`0`?!1:void 0}case`json`:try{return jsonDefault(JSON.parse(t))}catch{return}case`datetime`:{let e=ee.exec(t);if(!e||!isCalendarDate(e[1],e[2]))return;let n=e[3]??`Z`,r=n.length===3?`${n}:00`:n,i=new Date(`${e[1]}T${e[2]}${r}`);return Number.isNaN(i.getTime())?void 0:i.toISOString()}case`date`:return D.test(t)&&isCalendarDate(t,`00:00:00`)?t:void 0;default:return}}function readDefault(e,t,n,r){let i=c(n,t.type);if(i===void 0)return;let a=`the default \`${n}\` has no document spelling`;if(E.has(i)||E.has(i.toLowerCase())){if(e.type===`datetime`||e.type===`date`||e.type===`time`){if(e.array)return a;e.generate={kind:`now`};return}return a}if(i===`gen_random_uuid()`||i===`uuidv7()`){if(e.type!==`string`||e.array)return a;e.generate={kind:i===`gen_random_uuid()`?`uuid`:`uuidv7`};return}let o=n.trim(),s=r===`mysql`?O.exec(o)?.[1]:void 0,l=C.exec(s??o),u=l?unquote(l[1],r):n.trim();if(u===void 0)return a;if(e.array){if(!(l&&r===`postgresql`)){if(!l)return a;try{let t=JSON.parse(u);if(!Array.isArray(t))return a;let n=[];for(let r of t){let t=r===null?null:literalValue(e,typeof r==`string`?r:JSON.stringify(r),typeof r==`string`);if(t===void 0)return a;n.push(t)}e.default=n;return}catch{return a}}let t=m(u);if(t===void 0)return a;let n=[];for(let r of t){let t=r===null?null:literalValue(e,r,!0);if(t===void 0)return a;n.push(t)}e.default=n;return}let d=literalValue(e,e.type===`decimal`&&r===`sqlite`&&T.test(u)?coefficientText(u,e.scale):u,l!==null);if(d===void 0)return a;e.default=d}const A=/^varchar\((\d+)\)$/,j=/^char\((\d+)\)$/,M=/^(bit|varbit)(\((\d+)\))?$/,N=/^numeric\((\d+),(\d+)\)$/,P=/^timestamp(?:\((\d)\))?( with time zone)?$/,F=/^time(?:\((\d)\))?( with time zone)?$/,I=new Set([`citext`,`xml`,`inet`,`cidr`,`macaddr`,`macaddr8`,`tsvector`,`tsquery`]);function pgNative(e){return{db:`pg`,type:e}}function postgresBase(e,t,n){if(e===`text`)return{type:`string`};if(A.test(e)||j.test(e)||I.has(e)||M.exec(e))return{type:`string`,native:pgNative(e)};if(e===`uuid`)return n?{type:`string`,native:pgNative(`uuid`)}:{type:`string`,generate:{kind:`uuid`,generate:!1}};if(e===`integer`)return{type:`int`};if(e===`smallint`||e===`oid`)return{type:`int`,native:pgNative(e)};if(e===`bigint`)return{type:`bigint`};if(e===`real`)return{type:`number`,native:pgNative(`real`)};if(e===`double precision`)return{type:`number`};if(e===`boolean`)return{type:`boolean`};if(e===`date`)return{type:`date`};if(e===`bytea`)return{type:`blob`};if(e===`jsonb`)return{type:`json`};if(e===`json`)return{type:`json`,native:pgNative(`json`)};let r=N.exec(e);if(r){let e=t.decimal;return e===void 0?`numeric(${r[1]},${r[2]}) is outside VibORM's fixed-decimal domain`:{type:`decimal`,precision:e.precision,scale:e.scale}}if(e===`numeric`)return"an unconstrained `numeric` has no precision and scale, and a VibORM decimal declares both";if(e===`varchar`)return"`varchar` without a length has no document spelling (use `text`, or a length)";let i=P.exec(e);if(i){let e=i[1],t=i[2]!==void 0,n={type:`datetime`};if(t||(n.withoutTimezone=!0),e!==`3`){let r=t?`timestamptz`:`timestamp`;n.native=pgNative(e===void 0?r:`${r}(${e})`)}return n}let a=F.exec(e);if(a){let e=a[1],t=a[2]!==void 0,n={type:`time`};if(t||e!==`3`){let r=t?`timetz`:`time`;n.native=pgNative(e===void 0?r:`${r}(${e})`)}return n}return`the type \`${t.type}\` has no VibORM scalar`}function translatePostgresColumn(e){let{column:t}=e,n=t.type.endsWith(`[]`),r=n?t.type.slice(0,-2):t.type,i=e.enums.get(r),a;if(i)a={type:`enum`,enum:[...i.values]};else{let e=postgresBase(o(r),t,n);if(typeof e==`string`)return{skip:e};a=e}return finish(a,e,n,`postgresql`,i?.name)}function finish(e,t,n,r,i,a){let{column:o}=t;if(n){if(!S.has(e.type))return{skip:`a list of ${e.type} has no VibORM scalar`};e.array=!0}o.nullable&&(e.nullable=!0);let s;return t.identity||o.autoIncrement?e.type===`int`||e.type===`bigint`?e.generate={kind:`increment`}:s=`an auto-increment ${e.type} has no document spelling`:o.default!==void 0&&(s=readDefault(e,o,o.default,r)),{field:e,enumType:i,skippedDefault:s,approximated:a}}const L=/^TEXT CHECK\(/,R=/'((?:[^']|'')*)'/g;function sqliteEnumValues(e){let{type:t}=e.column,n=t.indexOf(` IN (`);if(n===-1)return;let r=[...t.slice(n).matchAll(R)].map(e=>e[1].replaceAll(`''`,`'`));return e.enumColumnType(r)===t?r:void 0}function sqliteAffinity(e){return e.includes(`INT`)?{type:`int`}:e.includes(`CHAR`)||e.includes(`CLOB`)||e.includes(`TEXT`)?{type:`string`}:e===``||e.includes(`BLOB`)?{type:`blob`}:e.includes(`REAL`)||e.includes(`FLOA`)||e.includes(`DOUB`)?{type:`number`}:e.includes(`BOOL`)?{type:`boolean`}:e.includes(`DATETIME`)||e.includes(`TIMESTAMP`)?{type:`datetime`}:e===`DATE`?{type:`date`}:{type:`number`}}function translateSqliteColumn(e){let{column:t}=e,n=t.type.trim().toUpperCase();if(t.decimal)return finish({type:`decimal`,precision:t.decimal.precision,scale:t.decimal.scale},e,n===`TEXT`,`sqlite`);if(L.test(t.type)){let n=sqliteEnumValues(e);return n===void 0?{skip:`the CHECK in \`${t.type}\` is not a VibORM enum`}:finish({type:`enum`,enum:n},e,!1,`sqlite`)}let r,i;switch(n){case`TEXT`:r=t.default?.trim()===`(strftime('%Y-%m-%dT%H:%M:%fZ','now'))`?{type:`datetime`}:{type:`string`};break;case`INTEGER`:r={type:`int`};break;case`REAL`:r={type:`number`};break;case`BLOB`:e.binaryKey?(r={type:`string`,generate:{kind:`uuid`,generate:!1}},i=`a BLOB key is read as a UUID, the key VibORM stores as sixteen bytes on SQLite; a key holding other bytes does not decode`):r={type:`blob`};break;case`JSON`:r={type:`json`};break;default:r=sqliteAffinity(n),i=`the declared type \`${t.type}\` is read by SQLite's affinity rules as ${r.type}, which VibORM spells \`${r.type===`string`?`TEXT`:r.type===`number`?`REAL`:r.type===`blob`?`BLOB`:r.type===`datetime`||r.type===`date`?`TEXT`:`INTEGER`}\``}return finish(r,e,!1,`sqlite`,void 0,i)}const z=/^(varchar|char|binary|varbinary|bit)\((\d+)\)$/,B=/^(datetime|timestamp|time)(?:\((\d)\))?$/,V=new Set([`tinyint`,`tinyint unsigned`,`smallint`,`smallint unsigned`,`mediumint`,`mediumint unsigned`,`int unsigned`,`year`]),H=new Set([`tinytext`,`mediumtext`,`longtext`]),U=new Set([`tinyblob`,`mediumblob`,`longblob`]),W=/^(tinyint|smallint|mediumint|int|bigint)\(\d+\)/;function mysqlNative(e){return{db:`mysql`,type:e}}function mysqlBase(e,t){let{column:n}=t;if(e===`text`)return{type:`string`};if(e===`tinyint(1)`)return{type:`boolean`};let r=e.replace(W,`$1`);if(r===`int`)return{type:`int`};if(r===`bigint`)return{type:`bigint`};if(r===`bigint unsigned`)return{type:`bigint`,native:mysqlNative(`BIGINT UNSIGNED`)};if(V.has(r))return{type:`int`,native:mysqlNative(r.toUpperCase())};if(r===`double`)return{type:`number`};if(r===`float`)return{type:`number`,native:mysqlNative(`FLOAT`)};if(r===`json`)return{type:`json`};if(r===`blob`)return{type:`blob`};if(U.has(r))return{type:`blob`,native:mysqlNative(r.toUpperCase())};if(H.has(r))return{type:`string`,native:mysqlNative(r.toUpperCase())};if(r===`date`)return{type:`date`};if(r.startsWith(`decimal(`)){let e=n.decimal;return e===void 0?`${n.type} is outside VibORM's fixed-decimal domain`:{type:`decimal`,precision:e.precision,scale:e.scale}}let i=z.exec(r);if(i){let[,e,n]=i;if(e===`binary`&&n===`16`&&t.binaryKey)return{type:`string`,generate:{kind:`uuid`,generate:!1}};if(e===`varchar`&&n===`191`&&t.keyed)return{type:`string`};let r=mysqlNative(`${e.toUpperCase()}(${n})`);return e===`binary`||e===`varbinary`?{type:`blob`,native:r}:{type:`string`,native:r}}let a=B.exec(r);if(a){let[,e,t]=a,n={type:e===`time`?`time`:`datetime`};return(e===`timestamp`||t!==`3`)&&(n.native=mysqlNative(t===void 0?e.toUpperCase():`${e.toUpperCase()}(${t})`)),n}return`the type \`${n.type}\` has no VibORM scalar`}function translateMysqlColumn(e){let{column:t}=e;if(t.type.toUpperCase().startsWith(`ENUM(`)){let n=e.enums.get(t.type);return n===void 0||e.enumColumnType(n.values)!==t.type?{skip:`the enum \`${t.type}\` is not one VibORM spells`}:finish({type:`enum`,enum:[...n.values]},e,!1,`mysql`)}let n=mysqlBase(t.type.trim().toLowerCase(),e);return typeof n==`string`?{skip:n}:finish(n,e,!1,`mysql`,void 0,n.type===`string`&&n.generate?.kind===`uuid`?`a BINARY(16) key is read as a UUID, the key VibORM stores as sixteen bytes on MySQL; a key holding other bytes does not decode`:void 0)}const G=/^number\((\d+),(\d+)\)$/,K=/\(.*\)$/,q=/^vector\((float|int), (\d+)\)$/,J=/^(?:current_timestamp|sysdate|systimestamp|localtimestamp|current_date|current_time|getdate)(?:\(\d*\))?$/i;function snowflakeBase(e){let t=e.type.toLowerCase(),n=G.exec(t);if(n){let e=Number(n[1]),t=Number(n[2]);return t===0?{type:e<=9?`int`:`bigint`}:{type:`decimal`,precision:e,scale:t}}switch(t.replace(K,``)){case`float`:return{type:`number`};case`varchar`:return{type:`string`};case`boolean`:return{type:`boolean`};case`date`:return{type:`date`};case`time`:return{type:`time`};case`timestamp_ntz`:case`timestamp_ltz`:case`timestamp_tz`:return{type:`datetime`};case`binary`:return{type:`blob`};case`variant`:case`object`:case`array`:return{type:`json`};case`geography`:return{type:`point`};case`geometry`:return`a GEOMETRY is planar, in any SRID: VibORM's point is a geographic EPSG:4326 point (a GEOGRAPHY)`;default:break}let r=q.exec(t);return r?.[1]===`float`?{type:`vector`,dimension:Number(r[2])}:r?"a VECTOR(INT) has no VibORM scalar: `s.vector()` holds floats":`the type \`${e.type.toUpperCase()}\` has no VibORM scalar`}function translateSnowflakeColumn(e){let{column:t}=e,n=snowflakeBase(t);if(typeof n==`string`)return{skip:n};let r=t.type.toLowerCase().replace(K,``),i=r===`timestamp_ntz`?`a TIMESTAMP_NTZ holds a wall clock with no zone; VibORM reads it as UTC`:r===`geography`?`a GEOGRAPHY may hold any shape; VibORM reads it as a point, and a row holding another shape does not decode`:void 0;if(t.default!==void 0&&J.test(t.default.trim())&&(n.type===`datetime`||n.type===`date`||n.type===`time`)){n.generate={kind:`now`};let{default:r,...a}=t;return finish(n,{...e,column:a},!1,`snowflake`,void 0,i)}return finish(n,e,!1,`snowflake`,void 0,i)}const Y=new Set([`_count`,`_distance`]),X=/[^a-zA-Z0-9_]/g,Z=/^[0-9]/;function keyCandidate(e){let t=e.replace(X,`_`);return(t===``||Z.test(t))&&(t=`_${t}`),t.slice(0,60)}var KeyAllocator=class{#e=new Set;#t;constructor(e=new Set){this.#t=e}#n(e){return!(this.#e.has(e)||this.#t.has(e))&&i(e)}claimName(e){return this.#n(e)?(this.#e.add(e),e):this.claim(keyCandidate(e))}claim(e){let t=keyCandidate(e),n=t;for(let e=2;!this.#n(n);e++)n=`${t}_${e}`;return this.#e.add(n),n}};function memberAllocator(){return new KeyAllocator(Y)}const Q=/^(.+)_id$/i,te=/^(.*[a-z0-9])I[dD]$/;function relationNameFromColumn(e){return(Q.exec(e)??te.exec(e))?.[1]}const ne={postgresql:translatePostgresColumn,sqlite:translateSqliteColumn,mysql:translateMysqlColumn,snowflake:translateSnowflakeColumn},re={postgresql:void 0,sqlite:`BLOB`,mysql:`BINARY(16)`,snowflake:void 0},$="its name is not an identifier (ASCII letters, digits and _, at most 63 bytes), which is all `.map()` accepts";function junctionAction(e){let t=e??`noAction`;return t===`cascade`||t===`restrict`||t===`noAction`?t:void 0}function generatedJunction(e,t,n){let r=junctionAction(t.onDelete),i=junctionAction(n.onDelete),a=junctionAction(t.onUpdate),o=junctionAction(n.onUpdate);if(r===void 0||i===void 0||a===void 0||o===void 0)return;let s=r===i?{onDelete:r}:{onDeleteSides:{source:r,target:i}},c=a===o?{onUpdate:a}:{onUpdateSides:{source:a,target:o}};return{table:e,source:t.columns[0],target:n.columns[0],...s,...c}}function sameSet(e,t){return e.length===t.length&&e.every(e=>t.includes(e))}function sorted(e){return[...e].sort()}function translateSnapshot(e){let{snapshot:t,dialect:n,migrationDriver:r}=e,a=[],o=[],c=r.capabilities.introspectionReadsConstraintNames,l=new Map((t.enums??[]).map(e=>[e.name,e])),u=ne[n],d=new Set,f=re[n];if(f!==void 0){let isBlob=(e,t)=>e.columns.find(e=>e.name===t)?.type.toUpperCase()===f;for(let e of t.tables)for(let t of e.primaryKey?.columns??[])isBlob(e,t)&&d.add(`${e.name}\0${t}`);for(let e=!0;e;){e=!1;for(let n of t.tables)for(let t of n.foreignKeys)t.columns.forEach((r,i)=>{let a=`${n.name}\0${r}`,o=`${t.referencedTable}\0${t.referencedColumns[i]}`;!d.has(a)&&d.has(o)&&isBlob(n,r)&&(d.add(a),e=!0)})}}let keyedColumns=e=>new Set([...e.primaryKey?.columns??[],...e.uniqueConstraints.flatMap(e=>e.columns),...e.indexes.flatMap(e=>e.raw?[]:e.columns),...e.foreignKeys.flatMap(e=>e.columns)]),p=new KeyAllocator,m=new Map,h=new Map;for(let n of t.tables){let t=n.primaryKey;if(!t||t.columns.length===0){a.push({kind:`table`,name:n.name,reason:`it has no primary key, and a VibORM model is addressed by one`});continue}if(!i(n.name)){a.push({kind:`table`,name:n.name,reason:$});continue}let s=new Map,c=keyedColumns(n);for(let t of n.columns){if(!i(t.name)){s.set(t.name,{skip:$});continue}s.set(t.name,u({column:t,enums:l,identity:e.identityColumns.has(`${n.name}\0${t.name}`),enumColumnType:e=>r.getEnumColumnType(n.name,t.name,e),binaryKey:d.has(`${n.name}\0${t.name}`),keyed:c.has(t.name)}))}let f=t.columns.find(e=>{let t=s.get(e);return t===void 0||`skip`in t});if(f!==void 0){let e=s.get(f);a.push({kind:`table`,name:n.name,reason:`its primary key column "${f}" cannot be translated: ${e&&`skip`in e?e.skip:`it is not a column of the table`}`});continue}let _=p.claimName(n.name),v={},y={fields:v};_!==n.name&&(y.table=n.name);let b={key:_,table:n,members:memberAllocator(),fields:v,fieldOf:new Map,document:y,keys:[]};for(let e of n.columns){let t=s.get(e.name);if(`skip`in t){a.push({kind:`column`,table:n.name,name:e.name,reason:t.skip});continue}let r=b.members.claimName(e.name),i={...t.field};if(r!==e.name&&(i.column=e.name),v[r]=i,b.fieldOf.set(e.name,r),t.enumType!==void 0){let n=h.get(t.enumType)??[];n.push({build:b,field:r,column:e.name}),h.set(t.enumType,n)}t.skippedDefault!==void 0&&a.push({kind:`default`,table:n.name,name:e.name,reason:t.skippedDefault}),t.approximated!==void 0&&o.push({kind:`approximated`,table:n.name,name:e.name,message:t.approximated})}let x=t.columns.map(e=>b.fieldOf.get(e));if(x.forEach((e,r)=>{let i=v[e];g(i)||!i.nullable||(i.nullable=!1,o.push({kind:`approximated`,table:n.name,name:t.columns[r],message:"the database lets this primary key column hold NULL (SQLite does unless it is NOT NULL, outside a rowid table's INTEGER key), and the document declares it NOT NULL, as every model key is: a push of the document rebuilds the table to make it NOT NULL, which fails while a row's key is NULL and cannot keep what the table carries beyond the document (its `unstated` warnings)"}))}),x.length===1){let e=v[x[0]];e.type!==`toOne`&&e.type!==`toMany`&&(Object.assign(e,{id:!0}),e.type===`string`&&e.generate===void 0&&Object.assign(e,{generate:{kind:`ulid`,generate:!1,implicit:!0}}))}else y.ids=[{fields:x}];t.withoutRowid&&(y.withoutRowid=!0),b.keys.push(sorted(t.columns)),m.set(n.name,b)}for(let e of m.values()){let{table:t,fields:n,document:r,fieldOf:l}=e,u=[],d=[],missing=e=>e.find(e=>!l.has(e)),derivedUnique=(e,n)=>e.startsWith(`${t.name}_`)&&e.endsWith(`_key`)&&n.every(e=>l.has(e)),f=t.indexes.filter(e=>e.unique&&!e.raw&&e.where===void 0&&(e.type===void 0||e.type===`btree`)&&derivedUnique(e.name,e.columns)),p=[...t.uniqueConstraints,...f.map(e=>({name:e.name,columns:e.columns}))];for(let r of p){let f=missing(r.columns);if(f!==void 0){a.push({kind:`uniqueConstraint`,table:t.name,name:r.name,reason:`its column "${f}" is not translated`});continue}let p=r.columns.map(e=>l.get(e)),derived=e=>s(`${t.name}_${e}_key`);if(p.length===1&&(!c||r.name===derived(r.columns[0]))){Object.assign(n[p[0]],{unique:!0}),e.keys.push(sorted(r.columns));continue}if(!c||r.name===derived(p.join(`_`))){d.push({fields:p}),e.keys.push(sorted(r.columns));continue}let m=`${t.name}_`,h=r.name.startsWith(m)&&r.name.endsWith(`_key`)?r.name.slice(m.length,-4):void 0;if(h!==void 0&&i(h)){d.push({fields:p,name:h}),e.keys.push(sorted(r.columns));continue}u.push({fields:p,name:r.name,unique:!0}),o.push({kind:`approximated`,table:t.name,name:r.name,message:`the unique constraint "${r.name}" is declared as a unique index under the same name, because a document names compound keys "<table>_<name>_key"; it is not a key \`findUnique\` accepts`})}for(let e of t.indexes){if(f.includes(e))continue;let n=missing(e.columns),r=e.raw?"it is a raw index (`.rawIndex()`), which a document cannot declare: keep it in a TypeScript schema":e.where===void 0?n===void 0?void 0:`its column "${n}" is not translated`:`it is a partial index (WHERE ${e.where}), and a document has no \`where\`: keep it in a TypeScript schema`;if(r!==void 0){a.push({kind:`index`,table:t.name,name:e.name,reason:r});continue}let i={fields:e.columns.map(e=>l.get(e)),name:e.name};e.unique&&(i.unique=!0),e.type!==void 0&&e.type!==`btree`&&(i.type=e.type),u.push(i)}d.length>0&&(r.uniques=d),u.length>0&&(r.indexes=u)}let _=new Map;for(let e of m.values()){let t=[],n=[...e.table.foreignKeys].sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0);for(let r of n){let n=m.get(r.referencedTable),skip=t=>a.push({kind:`foreignKey`,table:e.table.name,name:r.name,reason:t});if(n===void 0){skip(`it references "${r.referencedTable}", which the document does not declare`);continue}let i=r.columns.find(t=>!e.fieldOf.has(t)),o=r.referencedColumns.find(e=>!n.fieldOf.has(e));if(i!==void 0||o!==void 0){skip(`its column "${i??`${r.referencedTable}.${o}`}" is not translated`);continue}if(r.onDelete===`setDefault`||r.onUpdate===`setDefault`){skip(`its referential action is SET DEFAULT, which a VibORM relation does not declare`);continue}if(!n.keys.some(e=>sameSet(e,r.referencedColumns))){skip(`it references (${r.referencedColumns.join(`, `)}) of "${r.referencedTable}", which the document does not declare as a key`);continue}t.push({owner:e,target:n,fk:r})}_.set(e,t)}let v=new Map;for(let[e,n]of _){let[r,i]=n;if(n.length!==2||r===void 0||i===void 0)continue;let a=e.table;if(t.tables.some(e=>e!==a&&e.foreignKeys.some(e=>e.referencedTable===a.name)))continue;let o=a.columns.map(e=>e.name),s=[...r.fk.columns,...i.fk.columns];a.foreignKeys.length!==2||r.fk.columns.some(e=>i.fk.columns.includes(e))||!sameSet(s,o)||!sameSet(a.primaryKey?.columns??[],o)||!n.every(e=>sameSet(e.fk.referencedColumns,e.target.table.primaryKey?.columns??[]))||v.set(e,[r,i])}let y=new Map,addPair=(e,t,n,r)=>{let i=e.key<t.key?[e.key,t.key]:[t.key,e.key],a=i.join(`\0`),o=y.get(a)??[];o.push({models:i,label:n,slots:r}),y.set(a,o)},b=new Set,action=e=>e===void 0||e===`setDefault`?`noAction`:e,relationNames=(e,t)=>{let{owner:n,target:r,fk:i}=e,a=i.columns.length===1?relationNameFromColumn(n.fieldOf.get(i.columns[0])):void 0,o=n.members.claim(a??r.key),s=n===r||t.filter(e=>e.target===r).length>1;return{toOne:o,inverse:r.members.claim(s?`${n.key}_by_${o}`:n.key)}};for(let t of m.values()){let n=_.get(t)??[],r=v.get(t);if(r){let[n,i]=r,a=n.fk.columns.length===1&&i.fk.columns.length===1?generatedJunction(t.table.name,n.fk,i.fk):void 0;if(!e.junctionModels.has(t.table.name)&&a!==void 0){m.delete(t.table.name),b.add(t.table.name);let e=n.target,r=i.target,o=e.members.claim(relationNameFromColumn(i.fk.columns[0])??r.key),s=r.members.claim(relationNameFromColumn(n.fk.columns[0])??e.key);e.fields[o]={type:`toMany`,target:r.key,junction:a},r.fields[s]={type:`toMany`,target:e.key},addPair(e,r,t.table.name,[{model:e,key:o},{model:r,key:s}]);continue}}let i=new Map;for(let e of n){let{target:r,fk:a}=e,{toOne:o,inverse:s}=relationNames(e,n);i.set(e,{toOne:o,inverse:s});let c={type:`toOne`,target:r.key,fields:a.columns.map(e=>t.fieldOf.get(e)),references:a.referencedColumns.map(e=>r.fieldOf.get(e)),onDelete:action(a.onDelete),onUpdate:action(a.onUpdate)};t.fields[o]=c;let l=t.keys.some(e=>sameSet(e,a.columns));r.fields[s]=l?{type:`toOne`,target:t.key}:{type:`toMany`,target:t.key},addPair(t,r,a.name,[{model:t,key:o},{model:r,key:s}])}if(r){let[e,n]=r,a=e.target,o=n.target,s=i.get(e).toOne,c=i.get(n).toOne,l=a.members.claim(c),u=o.members.claim(s);a.fields[l]={type:`toMany`,target:o.key,junction:{model:t.key,source:s,target:c}},o.fields[u]={type:`toMany`,target:a.key},addPair(a,o,t.table.name,[{model:a,key:l},{model:o,key:u}])}}for(let e of y.values())if(e.length>1||e[0].models[0]===e[0].models[1])for(let t of e)for(let e of t.slots)Object.assign(e.model.fields[e.key],{name:t.label});let x={},S=new KeyAllocator;for(let[e,t]of n===`postgresql`?l:[]){let n=(h.get(e)??[]).filter(e=>m.has(e.build.table.name));if(n.length===0){a.push({kind:`enum`,name:e,reason:`no translated column uses it, and a document declares an enum through its fields`});continue}let i=n.length===1?n[0]:void 0;if(i&&r.getEnumColumnType(i.build.table.name,i.column,t.values)===e)continue;let o=S.claimName(e);x[o]={values:[...t.values],name:e};for(let e of n)Object.assign(e.build.fields[e.field],{enum:o})}let C={};for(let e of m.values())C[e.key]=e.document;return{document:{version:1,...Object.keys(x).length>0?{enums:x}:{},models:C},skipped:a,warnings:o,tables:new Set([...[...m.values()].map(e=>e.table.name),...b]),generatedJunctions:b}}function describeColumn(e){return`${e.type}${e.nullable?` NULL`:` NOT NULL`}${e.default===void 0?``:` DEFAULT ${e.default}`}`}function operationType(e){return e.type}function describe(e){let push=(e,t,n)=>({kind:`drift`,table:e,name:t,message:`push would ${n}`});switch(e.type){case`createTable`:return push(e.table.name,void 0,`create table "${e.table.name}"`);case`dropTable`:return push(e.tableName,void 0,`drop table "${e.tableName}"`);case`addColumn`:return push(e.tableName,e.column.name,`add column "${e.column.name}" (${describeColumn(e.column)})`);case`dropColumn`:return push(e.tableName,e.columnName,`drop column "${e.columnName}"`);case`alterColumn`:return push(e.tableName,e.columnName,`alter column "${e.columnName}" from ${describeColumn(e.from)} to ${describeColumn(e.to)}`);case`createIndex`:return push(e.tableName,e.index.name,`create index "${e.index.name}" on (${e.index.columns.join(`, `)})`);case`dropIndex`:return push(e.tableName,e.indexName,`drop index "${e.indexName}"`);case`addForeignKey`:return push(e.tableName,e.fk.name,`add foreign key "${e.fk.name}" on (${e.fk.columns.join(`, `)})`);case`dropForeignKey`:return push(e.tableName,e.fkName,`drop foreign key "${e.fkName}"`);case`addUniqueConstraint`:return push(e.tableName,e.constraint.name,`add unique constraint "${e.constraint.name}" on (${e.constraint.columns.join(`, `)})`);case`dropUniqueConstraint`:return push(e.tableName,e.constraintName,`drop unique constraint "${e.constraintName}"`);case`addPrimaryKey`:return push(e.tableName,e.primaryKey.name,`add a primary key on (${e.primaryKey.columns.join(`, `)})`);case`dropPrimaryKey`:return push(e.tableName,e.constraintName,`drop primary key "${e.constraintName}"`);case`createEnum`:return push(void 0,e.enumDef.name,`create enum "${e.enumDef.name}"`);case`dropEnum`:return push(void 0,e.enumName,`drop enum "${e.enumName}"`);case`alterEnum`:return push(void 0,e.enumName,`alter enum "${e.enumName}"`);case`renameTable`:return push(e.from,void 0,`rename table "${e.from}" to "${e.to}"`);case`renameColumn`:return push(e.tableName,e.from,`rename column "${e.from}" to "${e.to}"`);default:return push(void 0,void 0,operationType(e))}}function tableOf(e){return e.table}async function verifyDocument(e,t,n){let r=_(e,{validate:!0});a(r);let i=f(r,{migrationDriver:n}),o=n.capabilities.introspectionReadsConstraintNames,s=await p(t,i,{matchConstraintsByShape:!o,refuseConstraintNameChurn:!1}),c=new Set,l=[];for(let e of s.operations){if(e.type!==`addForeignKey`&&e.type!==`addUniqueConstraint`)continue;let n=(e.type===`addForeignKey`?e.fk:e.constraint).columns.join(`\0`),r=t.tables.find(t=>t.name===e.tableName),i=s.operations.find(t=>c.has(t)?!1:e.type===`addForeignKey`&&t.type===`dropForeignKey`&&t.tableName===e.tableName?r?.foreignKeys.some(r=>r.name===t.fkName&&r.columns.join(`\0`)===n&&r.referencedTable===e.fk.referencedTable):e.type===`addUniqueConstraint`&&t.type===`dropUniqueConstraint`&&t.tableName===e.tableName?r?.uniqueConstraints.some(e=>e.name===t.constraintName&&e.columns.join(`\0`)===n):!1);if(i===void 0)continue;c.add(e),c.add(i);let a=i.type===`dropForeignKey`?i.fkName:i.type===`dropUniqueConstraint`?i.constraintName:``,o=e.type===`addForeignKey`?e.fk.name:e.constraint.name;l.push({kind:`drift`,table:e.tableName,name:a,message:`push refuses this table: the constraint "${a}" is the one VibORM names "${o}", and a document cannot name it`})}for(let e of s.operations)c.has(e)||l.push(describe(e));for(let e of s.ambiguousChanges)l.push(e.type===`ambiguousColumn`?{kind:`drift`,table:e.tableName,name:e.droppedColumn.name,message:`push would replace column "${e.droppedColumn.name}" by "${e.addedColumn.name}"`}:{kind:`drift`,table:e.droppedTable,message:`push would replace table "${e.droppedTable}" by "${e.addedTable}"`});if(o){let e=new Map(i.tables.map(e=>[e.name,e]));for(let n of t.tables){let t=n.primaryKey?.name,r=e.get(n.name)?.primaryKey?.name;t!==void 0&&r!==void 0&&t!==r&&l.push({kind:`drift`,table:n.name,name:t,message:`push refuses this table: its primary key is named "${t}" and VibORM names it "${r}"`})}}let u=new Set;for(let e of l){let t=tableOf(e);t!==void 0&&u.add(t)}return{warnings:l,drifted:u}}h();const ie=[`postgresql`,`sqlite`,`mysql`,`snowflake`],ae={kind:`approximated`,message:`Snowflake enforces no primary, unique or foreign key: the document's keys, uniques and relations are the ones the catalog declares, and a row may break them`};function isIntrospectionDialect(e){return ie.some(t=>t===e)}function declaredSnapshot(e,t){let n=e.tables.filter(e=>t.has(e.name)),r=new Set(n.flatMap(e=>e.columns.map(e=>e.type.endsWith(`[]`)?e.type.slice(0,-2):e.type))),i=e.enums?.filter(e=>r.has(e.name));return{tables:n,...i&&i.length>0?{enums:i}:{}}}function lighten(e){let t=new Set,n={};for(let[r,{indexes:i,...a}]of Object.entries(e.document.models)){for(let e of i??[])t.add(`${a.table??r}\0${e.name}`);n[r]=a}return{...e,document:v(_({...e.document,light:!0,models:n})),skipped:e.skipped.filter(e=>e.kind!==`index`&&e.kind!==`check`),warnings:e.warnings.filter(e=>e.kind===`approximated`&&!t.has(`${e.table}\0${e.name}`))}}async function introspectDriver(e,t){let i=e.dialect;if(!isIntrospectionDialect(i))throw new r(`introspectSchema does not translate ${i} yet; PostgreSQL, SQLite, MySQL and Snowflake are supported.`,n.FEATURE_NOT_SUPPORTED,{meta:{dialect:i,feature:`introspect-schema`}});let a=await readCatalog(e,i,t),o=new Set;for(let e=0;;e++){let t=translateSnapshot({snapshot:a.snapshot,dialect:i,migrationDriver:a.migrationDriver,identityColumns:a.identityColumns,junctionModels:o}),n=i===`snowflake`?{warnings:[ae],drifted:new Set}:await verifyDocument(t.document,declaredSnapshot(a.snapshot,t.tables),a.migrationDriver),r=[...t.generatedJunctions].filter(e=>n.drifted.has(e));if(r.length>0&&e===0){for(let e of r)o.add(e);continue}return{document:v(_(t.document)),skipped:[...a.skipped,...t.skipped],warnings:[...t.warnings,...a.hazards.filter(({table:e,feature:n})=>t.tables.has(e)&&!n.startsWith(`CHECK`)).map(({table:e,feature:t})=>({kind:`unstated`,table:e,message:`the document cannot carry ${t}: the database keeps it and a push of the document plans nothing for it, but a push that recreates the table or the column cannot keep it`})),...n.warnings],dialect:i}}}async function introspectSchema(e){let read=async t=>{let n=await introspectDriver(t,e.tables);return e.light?lighten(n):n};if(e.driver!==void 0)return await read(e.driver);let{driver:t}=await openDriver(e.url);try{return await read(t)}finally{await t.disconnect()}}export{introspectSchema as t};
2
+ //# sourceMappingURL=introspect-Bm6xnXcG.mjs.map