kern-orm 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2455,7 +2455,11 @@ interface DbMutationState<T extends AnyTable, U extends UsedRelation> extends Mu
2455
2455
  }
2456
2456
  interface DbMethods<T extends Tables, R extends SchemaRelations> {
2457
2457
  readonly $schema: Schema<T, R>;
2458
- /** Database that the `Db` is bound to. */
2458
+ /**
2459
+ * Database that the `Db` is bound to.
2460
+ *
2461
+ * Reading it calls the function given to `bindSchema` instead of a database, as a statement does, such as to resolve the database of the current context.
2462
+ */
2459
2463
  readonly $database: Database;
2460
2464
  /**
2461
2465
  * PostgreSQL schema of the tables, or `undefined` for a `Db` bound without `schemaName`.
@@ -2562,8 +2566,10 @@ type AnyDb = Db<any, any>;
2562
2566
  * Binds a schema to a database, placing its tables in a PostgreSQL schema.
2563
2567
  *
2564
2568
  * Schemas bound to the same database, such as tenant and SaaS schemas, share its connections and transactions.
2569
+ * Given a function instead of a database, such as one that reads it from dependency injection, the `Db` calls it for each statement and at the start of each transaction, session, and lock, in the async context of the caller.
2570
+ * The function must return the same database within a transaction or session; in the callback of a transaction or session of the `Db`, a statement for which it returns another database rejects.
2565
2571
  */
2566
- declare function bindSchema<T extends Tables, R extends SchemaRelations>(schema: Schema<T, R>, database: Database, options?: BindOptions): Db<T, R>;
2572
+ declare function bindSchema<T extends Tables, R extends SchemaRelations>(schema: Schema<T, R>, database: Database | (() => Database), options?: BindOptions): Db<T, R>;
2567
2573
  /** Occurrence of a table in `FROM`. */
2568
2574
  interface TableSourceNode {
2569
2575
  readonly kind: "table";
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as NotAColumn, $i as BaseType, $n as avg, $r as WhereValues, $t as SchemaTables, A as SqlQueryResult, Ai as QueryState, An as ExpressionInput, Ar as UpdateSet, At as DeclaredRelations, B as createDatabase, Bi as ColumnShape, Bn as SelectionFieldTypes, Br as FoundState, Bt as RequiredMember, C as ResultByRows, Ci as ScalarQuery, Cn as TypedOperandInput, Cr as ResultOf, Ct as DbQueryState, D as SessionOptions, Di as FoundKey, Dn as greatest, Dr as ColumnValue, Dt as SynchronousResult, E as ResultRows, Ei as EmptyRecord, En as coalesce, Er as from, Et as NotSynchronous, F as TransactionConnectionError, Fi as TableQueryState, Fn as GroupedRecord, Fr as Helper, Ft as RelationDeclaration, G as toSnakeCase, Gi as TableFactoryOptions, Gn as AggregateExpression, Gr as KeyCheck, Gt as UsableRelation, H as isOutcomeUnknown, Hi as KeyColumns, Hn as SelectionUses, Hr as SelectedOperandType, Ht as SchemaRelations, I as TransactionOptions, Ii as AnyTable, In as MergeSelection, Ir as HelperEffect, It as RelationDeclarations, J as param, Ji as ToColumns, Jn as GroupAggregateExpression, Jr as PrimaryKeyValues, Jt as one, K as SqlTemplate, Ki as TableKeys, Kn as AggregateOptions, Kr as NotAKey, Kt as UsedRelation, L as TypeOptions, Li as AnyTableKeys, Ln as NestedQuery, Lr as defineHelper, Lt as RelationKey, M as SqlStatement, Mi as QueryValueType, Mn as GroupOperandValue, Mr as UpsertValues, Mt as NoRelations, N as SqlValue, Ni as SelectQueryState, Nn as GroupSelectionResult, Nr as RowLockOptions, Nt as OneRelationKeys, O as SqlFragment, Oi as Grouped, On as least, Or as ConflictUpdateSet, Ot as TransformedQuery, P as TextValue, Pi as SingletonQueryState, Pn as GroupedField, Pr as AnyHelper, Pt as Relation, Q as MatchResult, Qi as AnyType, Qn as UnfilteredStringAggOptions, Qr as WhereFilter, Qt as SchemaPartRelations, R as TypeTransform, Ri as ColumnDefinitions, Rn as SelectedFieldTypes, Rr as FilteredStateRows, Rt as RelationKeys, S as QueryErrorCondition, Si as OperandUses, Sn as TypedOperand, Sr as BoundSelectQuery, St as DbOf, T as ResultMode, Ti as ValuesQuery, Tn as caseWhen, Tr as SingletonInsertMany, Tt as AnyTransformedQuery, U as isQueryError, Ui as Selectable, Un as Literal, Ur as GroupTerm, Ut as TableContext, V as createStatement, Vi as ColumnValues, Vn as SelectionResult, Vr as GroupedState, Vt as SchemaContext, W as toDriverError, Wi as Table, Wn as literal, Wr as GroupTerms, Wt as TableRelations, X as ColumnRefKey, Xi as defineTable, Xn as StringAggOptions, Xr as WhereCallback, Xt as Schema, Y as sql, Yi as createTableFactory, Yn as GroupValue, Yr as EqValue, Yt as AnySchema, Z as MatchCheck, Zi as RequiredRelationError, Zn as UnfilteredAggregateOptions, Zr as WhereCondition, Zt as SchemaPart, _ as OneRow, _a as defineGenericOperator, _i as BooleanResult, _n as CaseBranch, _r as orderBy, _t as UntypedExpression, a as Database, aa as AnyColumn, ai as not, an as SelectionState, ar as some, at as TextConversionSignature, b as QueryError, bi as OperandValue, bn as FollowingOperand, br as RelationRefs, bt as Db, c as DerivableType, ca as KeyKind, ci as FilteredRows, cn as AnyMutationQuery, cr as OrderColumns, ct as TextTypeOperators, d as DriverErrorFields, da as MergeOperators, di as CompileOptions, dn as ConflictTarget, dr as OrderTerm, dt as orderingOperators, ea as Type, ei as CombinedCondition, en as Tables, er as count, et as matches, f as DriverResult, fa as NoOperators, fi as EqualityOperator, fn as InitialInsertState, fr as OrderTerms, ft as AnyExpression, g as NotFoundError, ga as OperatorSignature, gi as equalityOperators, gn as MutationQueryState, gr as desc, gt as TypedExpression, h as IsolationLevel, ha as GenericOperatorImplementation, hi as InSignature, hn as MutationQuery, hr as asc, ht as ExpressionOperators, i as ConnectionError, ia as defineType, ii as and, in as RecordQueryState, ir as min, it as PatternSignature, j as SqlQueryState, ji as QueryStateOf, jn as ExpressionValue, jr as UpdateValues, jt as MergeRelations, k as SqlQuery, ki as InitialQueryState, kn as ColumnFieldTypes, kr as InsertValues, kt as TransformedQueryState, l as DerivableTypeWithParameters, la as ToColumn, li as QueryResult, ln as ConflictActionRequired, lr as OrderDirection, lt as textOperators, m as InitialSqlQueryState, ma as GenericOperator, mi as HasEquality, mn as InsertMutationState, mr as SelectedRefs, mt as Expression, n as BaseDerivableType, na as TypeOperators, ni as ConditionOperand, nn as AnyRecordQuery, nr as every, nt as FALSE, o as DatabaseOptions, oa as Column, oi as or, on as AnyQuery, or as stringAgg, ot as TextLengthSignature, p as FieldTypes, pa as OperatorDefinitions, pi as EqualityOperators, pn as InitialMutationState, pr as Ordering, pt as BaseOperators, q as identifier, qi as TableOptions, qn as CountExpression, qr as PrimaryKeyColumn, qt as many, r as Connection, ra as TypeOutput, ri as Predicate, rn as RecordQuery, rr as max, rt as TRUE, s as DecodedFields, sa as ColumnAttributes, si as ExistsValueType, sn as SelectQueryKind, sr as sum, st as TextOperators, t as AnySqlQuery, ta as TypeInput, ti as Condition, tn as defineSchema, tr as countDistinct, tt as defineExpression, u as Driver, ua as BoundOperators, ui as CountValueType, un as ConflictKeyRequired, ur as OrderKey, ut as NumberTypeOperators, v as OneValueRows, vi as ComparisonSignature, vn as CaseCondition, vr as ColumnRefs, vt as AnyDb, w as ResultDecodeError, wi as TypedScalarQuery, wn as TypedOperandOperators, wr as SelectQuery, wt as bindSchema, x as QueryErrorCode, xi as compare, xn as NullSkippingResult, xr as AnySelectQuery, xt as DbMutationState, y as PollLockOptions, yi as Operand, yn as CaseValue, yr as QueryContext, yt as BindOptions, z as ValueRows, zi as ColumnOperators, zn as Selection, zr as FoundQueryState, zt as RelationKind } from "./index-CFkH9TlC.mjs";
1
+ import { $ as NotAColumn, $i as BaseType, $n as avg, $r as WhereValues, $t as SchemaTables, A as SqlQueryResult, Ai as QueryState, An as ExpressionInput, Ar as UpdateSet, At as DeclaredRelations, B as createDatabase, Bi as ColumnShape, Bn as SelectionFieldTypes, Br as FoundState, Bt as RequiredMember, C as ResultByRows, Ci as ScalarQuery, Cn as TypedOperandInput, Cr as ResultOf, Ct as DbQueryState, D as SessionOptions, Di as FoundKey, Dn as greatest, Dr as ColumnValue, Dt as SynchronousResult, E as ResultRows, Ei as EmptyRecord, En as coalesce, Er as from, Et as NotSynchronous, F as TransactionConnectionError, Fi as TableQueryState, Fn as GroupedRecord, Fr as Helper, Ft as RelationDeclaration, G as toSnakeCase, Gi as TableFactoryOptions, Gn as AggregateExpression, Gr as KeyCheck, Gt as UsableRelation, H as isOutcomeUnknown, Hi as KeyColumns, Hn as SelectionUses, Hr as SelectedOperandType, Ht as SchemaRelations, I as TransactionOptions, Ii as AnyTable, In as MergeSelection, Ir as HelperEffect, It as RelationDeclarations, J as param, Ji as ToColumns, Jn as GroupAggregateExpression, Jr as PrimaryKeyValues, Jt as one, K as SqlTemplate, Ki as TableKeys, Kn as AggregateOptions, Kr as NotAKey, Kt as UsedRelation, L as TypeOptions, Li as AnyTableKeys, Ln as NestedQuery, Lr as defineHelper, Lt as RelationKey, M as SqlStatement, Mi as QueryValueType, Mn as GroupOperandValue, Mr as UpsertValues, Mt as NoRelations, N as SqlValue, Ni as SelectQueryState, Nn as GroupSelectionResult, Nr as RowLockOptions, Nt as OneRelationKeys, O as SqlFragment, Oi as Grouped, On as least, Or as ConflictUpdateSet, Ot as TransformedQuery, P as TextValue, Pi as SingletonQueryState, Pn as GroupedField, Pr as AnyHelper, Pt as Relation, Q as MatchResult, Qi as AnyType, Qn as UnfilteredStringAggOptions, Qr as WhereFilter, Qt as SchemaPartRelations, R as TypeTransform, Ri as ColumnDefinitions, Rn as SelectedFieldTypes, Rr as FilteredStateRows, Rt as RelationKeys, S as QueryErrorCondition, Si as OperandUses, Sn as TypedOperand, Sr as BoundSelectQuery, St as DbOf, T as ResultMode, Ti as ValuesQuery, Tn as caseWhen, Tr as SingletonInsertMany, Tt as AnyTransformedQuery, U as isQueryError, Ui as Selectable, Un as Literal, Ur as GroupTerm, Ut as TableContext, V as createStatement, Vi as ColumnValues, Vn as SelectionResult, Vr as GroupedState, Vt as SchemaContext, W as toDriverError, Wi as Table, Wn as literal, Wr as GroupTerms, Wt as TableRelations, X as ColumnRefKey, Xi as defineTable, Xn as StringAggOptions, Xr as WhereCallback, Xt as Schema, Y as sql, Yi as createTableFactory, Yn as GroupValue, Yr as EqValue, Yt as AnySchema, Z as MatchCheck, Zi as RequiredRelationError, Zn as UnfilteredAggregateOptions, Zr as WhereCondition, Zt as SchemaPart, _ as OneRow, _a as defineGenericOperator, _i as BooleanResult, _n as CaseBranch, _r as orderBy, _t as UntypedExpression, a as Database, aa as AnyColumn, ai as not, an as SelectionState, ar as some, at as TextConversionSignature, b as QueryError, bi as OperandValue, bn as FollowingOperand, br as RelationRefs, bt as Db, c as DerivableType, ca as KeyKind, ci as FilteredRows, cn as AnyMutationQuery, cr as OrderColumns, ct as TextTypeOperators, d as DriverErrorFields, da as MergeOperators, di as CompileOptions, dn as ConflictTarget, dr as OrderTerm, dt as orderingOperators, ea as Type, ei as CombinedCondition, en as Tables, er as count, et as matches, f as DriverResult, fa as NoOperators, fi as EqualityOperator, fn as InitialInsertState, fr as OrderTerms, ft as AnyExpression, g as NotFoundError, ga as OperatorSignature, gi as equalityOperators, gn as MutationQueryState, gr as desc, gt as TypedExpression, h as IsolationLevel, ha as GenericOperatorImplementation, hi as InSignature, hn as MutationQuery, hr as asc, ht as ExpressionOperators, i as ConnectionError, ia as defineType, ii as and, in as RecordQueryState, ir as min, it as PatternSignature, j as SqlQueryState, ji as QueryStateOf, jn as ExpressionValue, jr as UpdateValues, jt as MergeRelations, k as SqlQuery, ki as InitialQueryState, kn as ColumnFieldTypes, kr as InsertValues, kt as TransformedQueryState, l as DerivableTypeWithParameters, la as ToColumn, li as QueryResult, ln as ConflictActionRequired, lr as OrderDirection, lt as textOperators, m as InitialSqlQueryState, ma as GenericOperator, mi as HasEquality, mn as InsertMutationState, mr as SelectedRefs, mt as Expression, n as BaseDerivableType, na as TypeOperators, ni as ConditionOperand, nn as AnyRecordQuery, nr as every, nt as FALSE, o as DatabaseOptions, oa as Column, oi as or, on as AnyQuery, or as stringAgg, ot as TextLengthSignature, p as FieldTypes, pa as OperatorDefinitions, pi as EqualityOperators, pn as InitialMutationState, pr as Ordering, pt as BaseOperators, q as identifier, qi as TableOptions, qn as CountExpression, qr as PrimaryKeyColumn, qt as many, r as Connection, ra as TypeOutput, ri as Predicate, rn as RecordQuery, rr as max, rt as TRUE, s as DecodedFields, sa as ColumnAttributes, si as ExistsValueType, sn as SelectQueryKind, sr as sum, st as TextOperators, t as AnySqlQuery, ta as TypeInput, ti as Condition, tn as defineSchema, tr as countDistinct, tt as defineExpression, u as Driver, ua as BoundOperators, ui as CountValueType, un as ConflictKeyRequired, ur as OrderKey, ut as NumberTypeOperators, v as OneValueRows, vi as ComparisonSignature, vn as CaseCondition, vr as ColumnRefs, vt as AnyDb, w as ResultDecodeError, wi as TypedScalarQuery, wn as TypedOperandOperators, wr as SelectQuery, wt as bindSchema, x as QueryErrorCode, xi as compare, xn as NullSkippingResult, xr as AnySelectQuery, xt as DbMutationState, y as PollLockOptions, yi as Operand, yn as CaseValue, yr as QueryContext, yt as BindOptions, z as ValueRows, zi as ColumnOperators, zn as Selection, zr as FoundQueryState, zt as RelationKind } from "./index-DFcelQx0.mjs";
2
2
  export { type AggregateExpression, type AggregateOptions, type AnyColumn, type AnyDb, type AnyExpression, type AnyHelper, type AnyMutationQuery, type AnyQuery, type AnyRecordQuery, type AnySchema, type AnySelectQuery, type AnySqlQuery, type AnyTable, type AnyTableKeys, type AnyTransformedQuery, type AnyType, type BaseDerivableType, type BaseOperators, type BaseType, type BindOptions, type BooleanResult, type BoundOperators, type BoundSelectQuery, type CaseBranch, type CaseCondition, type CaseValue, type Column, type ColumnAttributes, type ColumnDefinitions, type ColumnFieldTypes, type ColumnOperators, type ColumnRefKey, type ColumnRefs, type ColumnShape, type ColumnValue, type ColumnValues, type CombinedCondition, type ComparisonSignature, type CompileOptions, type Condition, type ConditionOperand, type ConflictActionRequired, type ConflictKeyRequired, type ConflictTarget, type ConflictUpdateSet, type Connection, ConnectionError, type CountExpression, type CountValueType, type Database, type DatabaseOptions, type Db, type DbMutationState, type DbOf, type DbQueryState, type DeclaredRelations, type DecodedFields, type DerivableType, type DerivableTypeWithParameters, type Driver, type DriverErrorFields, type DriverResult, type EmptyRecord, type EqValue, type EqualityOperator, type EqualityOperators, type ExistsValueType, type Expression, type ExpressionInput, type ExpressionOperators, type ExpressionValue, FALSE, type FieldTypes, type FilteredRows, type FilteredStateRows, type FollowingOperand, type FoundKey, type FoundQueryState, type FoundState, type GenericOperator, type GenericOperatorImplementation, type GroupAggregateExpression, type GroupOperandValue, type GroupSelectionResult, type GroupTerm, type GroupTerms, type GroupValue, type Grouped, type GroupedField, type GroupedRecord, type GroupedState, type HasEquality, type Helper, type HelperEffect, type InSignature, type InitialInsertState, type InitialMutationState, type InitialQueryState, type InitialSqlQueryState, type InsertMutationState, type InsertValues, type IsolationLevel, type KeyCheck, type KeyColumns, type KeyKind, type Literal, type MatchCheck, type MatchResult, type MergeOperators, type MergeRelations, type MergeSelection, type MutationQuery, type MutationQueryState, type NestedQuery, type NoOperators, type NoRelations, type NotAColumn, type NotAKey, NotFoundError, type NotSynchronous, type NullSkippingResult, type NumberTypeOperators, type OneRelationKeys, type OneRow, type OneValueRows, type Operand, type OperandUses, type OperandValue, type OperatorDefinitions, type OperatorSignature, type OrderColumns, type OrderDirection, type OrderKey, type OrderTerm, type OrderTerms, type Ordering, type PatternSignature, type PollLockOptions, type Predicate, type PrimaryKeyColumn, type PrimaryKeyValues, type QueryContext, QueryError, type QueryErrorCode, type QueryErrorCondition, type QueryResult, type QueryState, type QueryStateOf, type QueryValueType, type RecordQuery, type RecordQueryState, type Relation, type RelationDeclaration, type RelationDeclarations, type RelationKey, type RelationKeys, type RelationKind, type RelationRefs, type RequiredMember, RequiredRelationError, type ResultByRows, ResultDecodeError, type ResultMode, type ResultOf, type ResultRows, type RowLockOptions, type ScalarQuery, type Schema, type SchemaContext, type SchemaPart, type SchemaPartRelations, type SchemaRelations, type SchemaTables, type SelectQuery, type SelectQueryKind, type SelectQueryState, type Selectable, type SelectedFieldTypes, type SelectedOperandType, type SelectedRefs, type Selection, type SelectionFieldTypes, type SelectionResult, type SelectionState, type SelectionUses, type SessionOptions, type SingletonInsertMany, type SingletonQueryState, type SqlFragment, type SqlQuery, type SqlQueryResult, type SqlQueryState, type SqlStatement, type SqlTemplate, type SqlValue, type StringAggOptions, type SynchronousResult, TRUE, type Table, type TableContext, type TableFactoryOptions, type TableKeys, type TableOptions, type TableQueryState, type TableRelations, type Tables, type TextConversionSignature, type TextLengthSignature, type TextOperators, type TextTypeOperators, type TextValue, type ToColumn, type ToColumns, TransactionConnectionError, type TransactionOptions, type TransformedQuery, type TransformedQueryState, type Type, type TypeInput, type TypeOperators, type TypeOptions, type TypeOutput, type TypeTransform, type TypedExpression, type TypedOperand, type TypedOperandInput, type TypedOperandOperators, type TypedScalarQuery, type UnfilteredAggregateOptions, type UnfilteredStringAggOptions, type UntypedExpression, type UpdateSet, type UpdateValues, type UpsertValues, type UsableRelation, type UsedRelation, type ValueRows, type ValuesQuery, type WhereCallback, type WhereCondition, type WhereFilter, type WhereValues, and, asc, avg, bindSchema, caseWhen, coalesce, compare, count, countDistinct, createDatabase, createStatement, createTableFactory, defineExpression, defineGenericOperator, defineHelper, defineSchema, defineTable, defineType, desc, equalityOperators, every, from, greatest, identifier, isOutcomeUnknown, isQueryError, least, literal, many, matches, max, min, not, one, or, orderBy, orderingOperators, param, some, sql, stringAgg, sum, textOperators, toDriverError, toSnakeCase };
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { A as valuesQueryNode, B as oneNode, C as defineType, D as equalityOperators, E as Column, F as falseNode, I as noFilters, L as noJoins, M as createList, N as createNode, P as createSelectNode, R as noOrder, S as getBooleanType, T as isType$1, V as trueNode, _ as toCastValueNode, b as toNode, c as compare, d as getType, f as isExpression, g as toBooleanExpression, h as rejectSqlQueryOperand, i as textOperators, j as defineGenericOperator, k as isEqualityCompatible, l as compareNodes, m as operandNode, n as text, p as isOperandSource, s as orderingOperators, u as createIsNullNode, v as toExpression, w as describeRejectedDbType, x as toValueNode, y as toFunctionOperandNode, z as noProjections } from "./text-ucmJCsCN.mjs";
2
2
  import { SqlFragment, SqlQuery, assertUntypedValue, bindParameter, createFieldDecodeError, createResultDecodeError, encodeParameter, isRecordKey, quoteIdentifier, renderFragment, startSqlQuery, takeOnlyRow, toMissingResult, toValueRows } from "kern-db/builder";
3
- import { ConnectionError, NotFoundError, NotFoundError as NotFoundError$1, QueryError, ResultDecodeError, ResultDecodeError as ResultDecodeError$1, TransactionConnectionError, createDatabase, createStatement, createStatement as createStatement$1, identifier as identifier$1, isOutcomeUnknown, isQueryError, toDriverError } from "kern-db";
3
+ import { ConnectionError, NotFoundError, NotFoundError as NotFoundError$1, QueryError, ResultDecodeError, ResultDecodeError as ResultDecodeError$1, TransactionConnectionError, createDatabase, createStatement, createStatement as createStatement$1, identifier as identifier$1, isDatabase, isOutcomeUnknown, isQueryError, toDriverError } from "kern-db";
4
4
  import { types } from "node:util";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
5
6
  // src/ast/boolean.ts
6
7
  /** Combines predicate nodes with `AND` or `OR`, flattening nested groups of the same kind. */
7
8
  function combineNodes(kind, operands) {
@@ -4128,6 +4129,8 @@ function defineEntries(methods, tables, start) {
4128
4129
  * Binds a schema to a database, placing its tables in a PostgreSQL schema.
4129
4130
  *
4130
4131
  * Schemas bound to the same database, such as tenant and SaaS schemas, share its connections and transactions.
4132
+ * Given a function instead of a database, such as one that reads it from dependency injection, the `Db` calls it for each statement and at the start of each transaction, session, and lock, in the async context of the caller.
4133
+ * The function must return the same database within a transaction or session; in the callback of a transaction or session of the `Db`, a statement for which it returns another database rejects.
4131
4134
  */
4132
4135
  function bindSchema(schema, database, options = {}) {
4133
4136
  const tables = new Set(Object.values(schema.$tables));
@@ -4135,6 +4138,7 @@ function bindSchema(schema, database, options = {}) {
4135
4138
  const definitions = collectDefinitions(relations);
4136
4139
  const { schemaName } = options;
4137
4140
  const resolveSchemaName = () => typeof schemaName === "function" ? schemaName() : schemaName;
4141
+ const { resolveDatabase, executor, track } = createDatabaseResolver(database);
4138
4142
  function compile(query) {
4139
4143
  if (query instanceof SqlQuery) throw new TypeError("A query of SQL text executes when it is awaited and compiles with its toSQL, not with $execute or $compile");
4140
4144
  if (query.db !== void 0 && query.db !== db) throw new Error("Cannot run a query bound to another Db");
@@ -4146,7 +4150,9 @@ function bindSchema(schema, database, options = {}) {
4146
4150
  }
4147
4151
  const methods = {
4148
4152
  $schema: schema,
4149
- $database: database,
4153
+ get $database() {
4154
+ return resolveDatabase();
4155
+ },
4150
4156
  get $schemaName() {
4151
4157
  return resolveSchemaName();
4152
4158
  },
@@ -4156,33 +4162,69 @@ function bindSchema(schema, database, options = {}) {
4156
4162
  },
4157
4163
  async $execute(query) {
4158
4164
  const compiled = compile(query);
4165
+ const database = resolveDatabase();
4159
4166
  if (compiled.locksRows && !database.isInTransaction()) throw new Error("Cannot lock the rows of a query outside a transaction, where the locks would end with its statement; a test transaction alone does not count");
4160
4167
  return decodeStatement(compiled, await database.execute(compiled));
4161
4168
  },
4162
4169
  $select: (selection) => startRecordQuery(selection, db),
4163
4170
  $query(strings, ...values) {
4164
4171
  const node = toRawSqlNode(strings, values);
4165
- return startSqlQuery(() => compileText(node), database);
4172
+ return startSqlQuery(() => compileText(node), executor);
4166
4173
  },
4167
4174
  async $script(script, ...values) {
4168
- if (typeof script === "string") return database.script(script);
4175
+ if (typeof script === "string") return resolveDatabase().script(script);
4169
4176
  const { text, parameters } = compileText(toRawSqlNode(script, values));
4170
4177
  if (parameters.length > 0) throw new Error("A script has no parameters, so it takes no values, also in the queries and sql fragments that it interpolates");
4171
- return database.script(text);
4178
+ return resolveDatabase().script(text);
4179
+ },
4180
+ async $transaction(callback, options) {
4181
+ const database = resolveDatabase();
4182
+ return database.transaction(track(database, callback), options);
4183
+ },
4184
+ async $ensureTransaction(callback) {
4185
+ const database = resolveDatabase();
4186
+ return database.ensureTransaction(track(database, callback));
4172
4187
  },
4173
- $transaction: (callback, options) => database.transaction(callback, options),
4174
- $ensureTransaction: (callback) => database.ensureTransaction(callback),
4175
- $isInTransaction: () => database.isInTransaction(),
4176
- $isInTransactionBlock: () => database.isInTransactionBlock(),
4177
- $session: (callback, options) => database.session(callback, options),
4178
- $lock: (key) => database.lock(key),
4179
- $tryLock: (key) => database.tryLock(key),
4180
- $pollLock: (key, options) => database.pollLock(key, options)
4188
+ $isInTransaction: () => resolveDatabase().isInTransaction(),
4189
+ $isInTransactionBlock: () => resolveDatabase().isInTransactionBlock(),
4190
+ async $session(callback, options) {
4191
+ const database = resolveDatabase();
4192
+ return database.session(track(database, callback), options);
4193
+ },
4194
+ $lock: async (key) => resolveDatabase().lock(key),
4195
+ $tryLock: async (key) => resolveDatabase().tryLock(key),
4196
+ $pollLock: async (key, options) => resolveDatabase().pollLock(key, options)
4181
4197
  };
4182
4198
  const contexts = createQueryContexts(Object.keys(schema.$tables), relations);
4183
4199
  const db = defineEntries(methods, schema.$tables, (key) => bindQuery(startQuery(schema.$tables[key], contexts[key]), db));
4184
4200
  return db;
4185
4201
  }
4202
+ /**
4203
+ * Creates the resolver of `database`, the database given to `bindSchema` or a function that returns it.
4204
+ *
4205
+ * Only the callbacks of the transactions and sessions of the `Db` are checked: a transaction of its database or of another `Db` is not known here, and checking it would require kern-db to expose the transactions of every database in the async context.
4206
+ */
4207
+ function createDatabaseResolver(database) {
4208
+ if (typeof database !== "function") return {
4209
+ resolveDatabase: () => database,
4210
+ executor: database,
4211
+ track: (_, callback) => callback
4212
+ };
4213
+ const getDatabase = database;
4214
+ const started = new AsyncLocalStorage();
4215
+ function resolveDatabase() {
4216
+ const resolved = getDatabase();
4217
+ if (!isDatabase(resolved)) throw new TypeError("The function passed to bindSchema must return a database");
4218
+ const current = started.getStore();
4219
+ if (current !== void 0 && current !== resolved) throw new Error("The function passed to bindSchema returned another database inside the callback of a transaction or session of the Db; it must return the same database there");
4220
+ return resolved;
4221
+ }
4222
+ return {
4223
+ resolveDatabase,
4224
+ executor: { execute: (statement) => resolveDatabase().execute(statement) },
4225
+ track: (resolved, callback) => started.getStore() === resolved ? callback : () => started.run(resolved, callback)
4226
+ };
4227
+ }
4186
4228
  // src/table/snake-case.ts
4187
4229
  const wordStart = /(?<=[\p{Ll}\p{N}])(?=\p{Lu})|(?<=\p{Lu})(?=\p{Lu}(?!s$)\p{Ll})/gu;
4188
4230
  /**
package/dist/types.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { $i as BaseType, ct as TextTypeOperators, da as MergeOperators, ea as Type, fa as NoOperators, fi as EqualityOperator, ft as AnyExpression, hi as InSignature, ma as GenericOperator, mi as HasEquality, oa as Column, pa as OperatorDefinitions, pi as EqualityOperators, st as TextOperators, ut as NumberTypeOperators, vi as ComparisonSignature } from "./index-CFkH9TlC.mjs";
1
+ import { $i as BaseType, ct as TextTypeOperators, da as MergeOperators, ea as Type, fa as NoOperators, fi as EqualityOperator, ft as AnyExpression, hi as InSignature, ma as GenericOperator, mi as HasEquality, oa as Column, pa as OperatorDefinitions, pi as EqualityOperators, st as TextOperators, ut as NumberTypeOperators, vi as ComparisonSignature } from "./index-DFcelQx0.mjs";
2
2
  /**
3
3
  * Creates a one-dimensional array type of `element` values.
4
4
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kern-orm",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Fully typed relational query builder for PostgreSQL with ambient transactions and single-query relation loading",
5
5
  "keywords": [
6
6
  "orm",