pqb 0.62.1 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { inspect } from 'node:util';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { MaybeArray as MaybeArray$1 } from 'rollup';
4
- import { RecordOptionalString as RecordOptionalString$1, DefaultPrivileges as DefaultPrivileges$1, Query as Query$1 } from 'pqb/internal';
4
+ import { RecordOptionalString as RecordOptionalString$1, DefaultPrivileges as DefaultPrivileges$1 } from 'pqb/internal';
5
+ import { Query as Query$1 } from 'pqb';
5
6
 
6
7
  type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
7
8
  type MaybeArray<T> = T | T[];
@@ -252,6 +253,11 @@ declare abstract class QueryError<T extends PickQueryShape = PickQueryShape> ext
252
253
  get columns(): { [K in keyof T["shape"]]?: true | undefined; };
253
254
  }
254
255
 
256
+ interface SqlSessionState {
257
+ role?: string;
258
+ setConfig?: Record<string, string | number | boolean>;
259
+ }
260
+
255
261
  /**
256
262
  * Generic result returning from query methods.
257
263
  */
@@ -342,6 +348,7 @@ interface AdapterTransactionOptions {
342
348
  locals?: {
343
349
  [ConfigName: string]: string | number;
344
350
  };
351
+ sqlSessionState?: SqlSessionState;
345
352
  }
346
353
  type TransactionArgs<Result> = [
347
354
  cbOrOptions: undefined | AdapterTransactionOptions | ((adapter: TransactionAdapterBase) => Promise<Result>),
@@ -366,8 +373,8 @@ interface AdapterBase {
366
373
  getHost(): string;
367
374
  getSchema(): QuerySchema | undefined;
368
375
  connect?(): Promise<unknown>;
369
- query<T extends QueryResultRow = QueryResultRow>(text: string, values?: unknown[], startingSavepoint?: string, releasingSavepoint?: string): Promise<QueryResult<T>>;
370
- arrays<R extends any[] = any[]>(text: string, values?: unknown[], startingSavepoint?: string, releasingSavepoint?: string): Promise<QueryArraysResult<R>>;
376
+ query<T extends QueryResultRow = QueryResultRow>(text: string, values?: unknown[], startingSavepoint?: string, releasingSavepoint?: string, sqlSessionState?: SqlSessionState): Promise<QueryResult<T>>;
377
+ arrays<R extends any[] = any[]>(text: string, values?: unknown[], startingSavepoint?: string, releasingSavepoint?: string, sqlSessionState?: SqlSessionState): Promise<QueryArraysResult<R>>;
371
378
  /**
372
379
  * Run a transaction
373
380
  *
@@ -2499,18 +2506,21 @@ interface QueryDataSources {
2499
2506
  [K: string]: QuerySourceItem;
2500
2507
  }
2501
2508
 
2502
- interface OrderArgSelf extends PickQuerySelectable, PickQueryResult, PickQueryTsQuery {
2509
+ declare namespace Order {
2510
+ export interface ArgThis extends PickQuerySelectable, PickQueryResult, PickQueryTsQuery {
2511
+ }
2512
+ export type Arg<T extends ArgThis> = ArgKey<T> | ArgTsQuery<T> | {
2513
+ [K in ArgKey<T> | ArgTsQuery<T>]?: K extends ArgTsQuery<T> ? OrderTsQueryConfig : SortDir;
2514
+ } | Expression;
2515
+ export type Args<T extends ArgThis> = Arg<T>[];
2516
+ type ArgTsQuery<T extends ArgThis> = string | undefined extends T['__tsQuery'] ? never : Exclude<T['__tsQuery'], undefined>;
2517
+ type ArgKey<T extends ArgThis> = {
2518
+ [K in keyof T['__selectable']]: T['__selectable'][K]['column']['queryType'] extends undefined ? never : K;
2519
+ }[keyof T['__selectable']] | {
2520
+ [K in keyof T['result']]: T['result'][K]['dataType'] extends 'array' | 'object' | 'runtimeComputed' ? never : K;
2521
+ }[keyof T['result']];
2522
+ export {};
2503
2523
  }
2504
- type OrderArg<T extends OrderArgSelf> = OrderArgKey<T> | OrderArgTsQuery<T> | {
2505
- [K in OrderArgKey<T> | OrderArgTsQuery<T>]?: K extends OrderArgTsQuery<T> ? OrderTsQueryConfig : SortDir;
2506
- } | Expression;
2507
- type OrderArgs<T extends OrderArgSelf> = OrderArg<T>[];
2508
- type OrderArgTsQuery<T extends OrderArgSelf> = string | undefined extends T['__tsQuery'] ? never : Exclude<T['__tsQuery'], undefined>;
2509
- type OrderArgKey<T extends OrderArgSelf> = {
2510
- [K in keyof T['__selectable']]: T['__selectable'][K]['column']['queryType'] extends undefined ? never : K;
2511
- }[keyof T['__selectable']] | {
2512
- [K in keyof T['result']]: T['result'][K]['dataType'] extends 'array' | 'object' | 'runtimeComputed' ? never : K;
2513
- }[keyof T['result']];
2514
2524
  declare class QueryOrder {
2515
2525
  /**
2516
2526
  * Adds an order by clause to the query.
@@ -2547,7 +2557,7 @@ declare class QueryOrder {
2547
2557
  *
2548
2558
  * @param args - column name(s) or an object with column names and sort directions.
2549
2559
  */
2550
- order<T extends OrderArgSelf>(this: T, ...args: OrderArgs<T>): T;
2560
+ order<T extends Order.ArgThis>(this: T, ...args: Order.Args<T>): T;
2551
2561
  /**
2552
2562
  * Order by SQL expression
2553
2563
  *
@@ -2562,12 +2572,12 @@ declare class QueryOrder {
2562
2572
  orderSql<T>(this: T, ...args: SQLQueryArgs): T;
2563
2573
  }
2564
2574
 
2565
- interface WindowArg<T extends OrderArgSelf> {
2575
+ interface WindowArg<T extends Order.ArgThis> {
2566
2576
  [K: string]: WindowArgDeclaration<T> | Expression;
2567
2577
  }
2568
- interface WindowArgDeclaration<T extends OrderArgSelf = OrderArgSelf> {
2578
+ interface WindowArgDeclaration<T extends Order.ArgThis = Order.ArgThis> {
2569
2579
  partitionBy?: SelectableOrExpression<T> | SelectableOrExpressions<T>;
2570
- order?: OrderArg<T>;
2580
+ order?: Order.Arg<T>;
2571
2581
  }
2572
2582
  type WindowResult<T, W extends RecordUnknown> = T & {
2573
2583
  windows: {
@@ -2601,12 +2611,12 @@ declare class QueryWindow {
2601
2611
  *
2602
2612
  * @param arg - window config
2603
2613
  */
2604
- window<T extends OrderArgSelf, W extends WindowArg<T>>(this: T, arg: W): WindowResult<T, W>;
2614
+ window<T extends Order.ArgThis, W extends WindowArg<T>>(this: T, arg: W): WindowResult<T, W>;
2605
2615
  }
2606
2616
 
2607
2617
  interface AggregateOptions<T extends PickQuerySelectableResultRelationsWindows> {
2608
2618
  distinct?: boolean;
2609
- order?: OrderArg<T> | OrderArgs<T>;
2619
+ order?: Order.Arg<T> | Order.Args<T>;
2610
2620
  filter?: WhereArg<T>;
2611
2621
  filterOr?: WhereArgs<T>;
2612
2622
  withinGroup?: boolean;
@@ -4149,7 +4159,7 @@ declare class QueryWithSchema {
4149
4159
  withSchema<T>(this: T, schema: QuerySchema | undefined): T;
4150
4160
  }
4151
4161
 
4152
- interface AsyncState {
4162
+ interface AsyncState extends SqlSessionState {
4153
4163
  transactionAdapter?: TransactionAdapterBase;
4154
4164
  transactionId?: number;
4155
4165
  afterCommit?: TransactionAfterCommitHook[];
@@ -4158,7 +4168,7 @@ interface AsyncState {
4158
4168
  catchI?: number;
4159
4169
  schema?: QuerySchema;
4160
4170
  }
4161
- interface StorageOptions {
4171
+ interface StorageOptions extends SqlSessionState {
4162
4172
  log?: boolean;
4163
4173
  schema?: QuerySchema;
4164
4174
  }
@@ -5161,7 +5171,9 @@ declare abstract class ExpressionTypeMethod {
5161
5171
  }
5162
5172
 
5163
5173
  type IsolationLevel = 'SERIALIZABLE' | 'REPEATABLE READ' | 'READ COMMITTED' | 'READ UNCOMMITTED';
5164
- interface TransactionOptions extends StorageOptions {
5174
+ interface TransactionOptions {
5175
+ log?: boolean;
5176
+ schema?: QuerySchema;
5165
5177
  level?: IsolationLevel;
5166
5178
  readOnly?: boolean;
5167
5179
  deferrable?: boolean;
@@ -7110,22 +7122,27 @@ type CreateRelationsDataOmittingFKeys<T extends CreateSelf, Union> = (Union exte
7110
7122
  } & Partial<Union['nested']> : {
7111
7123
  [P in Union['columns'] & keyof T['inputType']]: CreateColumn<T, P>;
7112
7124
  } | Union['nested']) => void : never) extends (u: infer Obj) => void ? Obj : never;
7113
- type CreateResult<T extends CreateSelf> = T extends {
7125
+ type CreateResult<T extends CreateSelf, Data> = T extends {
7114
7126
  isCount: true;
7115
- } ? T : T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T>> : SetQueryResult<T, NarrowCreateResult<T>>;
7116
- type InsertResult<T extends CreateSelf> = T['__hasSelect'] extends true ? T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T>> : SetQueryResult<T, NarrowCreateResult<T>> : SetQueryReturnsRowCount<T>;
7127
+ } ? T : T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T, Data>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T, Data>> : SetQueryResult<T, NarrowCreateResult<T, Data>>;
7128
+ type InsertResult<T extends CreateSelf, Data> = T['__hasSelect'] extends true ? T['returnType'] extends undefined | 'all' ? SetQueryReturnsOneResult<T, NarrowCreateResult<T, Data>> : T['returnType'] extends 'pluck' ? SetQueryReturnsColumnResult<T, NarrowCreateResult<T, Data>> : SetQueryResult<T, NarrowCreateResult<T, Data>> : SetQueryReturnsRowCount<T>;
7117
7129
  type CreateManyResult<T extends CreateSelf> = T extends {
7118
7130
  isCount: true;
7119
- } ? SetQueryResult<T, NarrowCreateResult<T>> : T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAllResult<T, NarrowCreateResult<T>> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetQueryReturnsPluckColumnResult<T, NarrowCreateResult<T>> : SetQueryResult<T, NarrowCreateResult<T>>;
7120
- type InsertManyResult<T extends CreateSelf> = T['__hasSelect'] extends true ? T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAllResult<T, NarrowCreateResult<T>> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetQueryReturnsPluckColumnResult<T, NarrowCreateResult<T>> : SetQueryResult<T, NarrowCreateResult<T>> : SetQueryReturnsRowCountMany<T>;
7131
+ } ? T : T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAll<T> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetValueQueryReturnsPluckColumn<T> : T;
7132
+ type InsertManyResult<T extends CreateSelf> = T['__hasSelect'] extends true ? T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAll<T> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetValueQueryReturnsPluckColumn<T> : T : SetQueryReturnsRowCountMany<T>;
7121
7133
  /**
7122
7134
  * When creating a record with a *belongs to* nested record,
7123
7135
  * un-nullify foreign key columns of the result.
7124
7136
  *
7125
7137
  * The same should work as well with any non-null columns passed to `create`, but it's to be implemented later.
7126
7138
  */
7127
- type NarrowCreateResult<T extends CreateSelf> = EmptyObject extends T['relations'] ? T['result'] : {
7128
- [K in keyof T['result']]: K extends T['relations'][keyof T['relations']]['omitForeignKeyInCreate'] ? Column.Pick.QueryColumnOfTypeAndOps<string, Exclude<T['result'][K]['type'], null>, T['result'][K]['operators']> : T['result'][K];
7139
+ type NarrowCreateResult<T extends CreateSelf, Data> = EmptyObject extends T['relations'] ? T['result'] : {
7140
+ [K in keyof T['result']]: true extends {
7141
+ [R in keyof T['relations']]: K extends T['relations'][R]['omitForeignKeyInCreate'] ? T['relations'][R]['dataForCreate'] extends {
7142
+ columns: unknown;
7143
+ nested: unknown;
7144
+ } ? keyof T['relations'][R]['dataForCreate']['nested'] extends keyof Data ? true : T['relations'][R]['dataForCreate']['columns'] extends keyof Data ? null | undefined extends Data[T['relations'][R]['dataForCreate']['columns']] ? never : true : never : never : never;
7145
+ }[keyof T['relations']] ? Column.Pick.QueryColumnOfTypeAndOps<string, Exclude<T['result'][K]['outputType'], null>, T['result'][K]['operators']> : T['result'][K];
7129
7146
  };
7130
7147
  type IgnoreResult<T extends CreateSelf> = T['returnType'] extends 'oneOrThrow' ? QueryTakeOptional<T> : T['returnType'] extends 'valueOrThrow' ? SetQueryReturnsColumnOptional<T, T['result']['value']> : T;
7131
7148
  type OnConflictArg<T extends PickQueryUniqueProperties> = T['internal']['uniqueColumnNames'] | T['internal']['uniqueColumnTuples'] | Expression | {
@@ -7145,8 +7162,8 @@ interface CreateCtx {
7145
7162
  returnTypeAll?: true;
7146
7163
  resultAll: RecordUnknown[];
7147
7164
  }
7148
- declare const _queryCreate: <T extends CreateSelf>(q: T, data: CreateData<T>) => CreateResult<T>;
7149
- declare const _queryInsert: <T extends CreateSelf>(query: T, data: CreateData<T>) => InsertResult<T>;
7165
+ declare const _queryCreate: <T extends CreateSelf, Data extends CreateData<T>>(q: T, data: Data) => CreateResult<T, Data>;
7166
+ declare const _queryInsert: <T extends CreateSelf, Data extends CreateData<T>>(query: T, data: Data) => InsertResult<T, Data>;
7150
7167
  declare const _queryCreateMany: <T extends CreateSelf>(q: T, data: CreateData<T>[]) => CreateManyResult<T>;
7151
7168
  declare const _queryInsertMany: <T extends CreateSelf>(q: T, data: CreateData<T>[]) => InsertManyResult<T>;
7152
7169
  declare const _queryDefaults: <T extends CreateSelf, Data extends Partial<CreateData<T>>>(q: T, data: Data) => AddQueryDefaults<T, keyof Data>;
@@ -7157,6 +7174,7 @@ declare const _queryDefaults: <T extends CreateSelf, Data extends Partial<Create
7157
7174
  */
7158
7175
  type CreateMethodsNames = 'create' | 'insert' | 'createMany' | 'insertMany' | CreateFromMethodNames;
7159
7176
  type CreateManyMethodsNames = 'createMany' | 'insertMany' | CreateManyFromMethodNames;
7177
+ type ExtraPropertiesAreNotAllowed<T extends CreateSelf, Data> = keyof Data extends keyof T['inputType'] | keyof T['relations'] ? Data : `Extra properties are not allowed: ${Exclude<keyof Data, keyof T['inputType'] | keyof T['relations']> & string}`;
7160
7178
  declare class QueryCreate {
7161
7179
  /**
7162
7180
  * `create` and `insert` create a single record.
@@ -7207,16 +7225,12 @@ declare class QueryCreate {
7207
7225
  * )
7208
7226
  * .from('b');
7209
7227
  * ```
7210
- *
7211
- * @param data - data for the record, may have values, raw SQL, queries, relation operations.
7212
7228
  */
7213
- create<T extends CreateSelf>(this: T, data: CreateData<T>): CreateResult<T>;
7229
+ create<T extends CreateSelf, Data extends CreateData<T>>(this: T, data: ExtraPropertiesAreNotAllowed<T, Data>): CreateResult<T, Data>;
7214
7230
  /**
7215
7231
  * Works exactly as {@link create}, except that it returns inserted row count by default.
7216
- *
7217
- * @param data - data for the record, may have values, raw SQL, queries, relation operations.
7218
7232
  */
7219
- insert<T extends CreateSelf>(this: T, data: CreateData<T>): InsertResult<T>;
7233
+ insert<T extends CreateSelf, Data extends CreateData<T>>(this: T, data: ExtraPropertiesAreNotAllowed<T, Data>): InsertResult<T, Data>;
7220
7234
  /**
7221
7235
  * `createMany` and `insertMany` will create a batch of records.
7222
7236
  *
@@ -9028,7 +9042,7 @@ declare module "./index" {
9028
9042
  * @param search - name of the search to use the query from
9029
9043
  * @param options - `text` for a text source, `options` for `ts_headline` options
9030
9044
  */
9031
- headline<T extends OrderArgSelf>(this: T, search: HeadlineSearchArg<T>, options?: HeadlineParams<T>): SetQueryReturnsColumnOrThrow<T, Column.Pick.QueryColumnOfType<string>>;
9045
+ headline<T extends Order.ArgThis>(this: T, search: HeadlineSearchArg<T>, options?: HeadlineParams<T>): SetQueryReturnsColumnOrThrow<T, Column.Pick.QueryColumnOfType<string>>;
9032
9046
  }
9033
9047
  }
9034
9048
  type SearchArg<T extends PickQuerySelectable, As extends string> = {
@@ -9768,6 +9782,7 @@ interface QueryHelper<T extends PickQueryTableMetaShapeTableAs, Args extends any
9768
9782
  args: Args;
9769
9783
  result: Result;
9770
9784
  }
9785
+ type QueryHelperResult<T extends QueryHelper<PickQueryTableMetaShapeTableAs, any[], MergeQueryArg>> = T['result'];
9771
9786
  interface NarrowTypeSelf extends PickQueryResultReturnType {
9772
9787
  returnType: undefined | 'all' | 'one' | 'oneOrThrow' | 'value' | 'valueOrThrow' | 'pluck';
9773
9788
  }
@@ -10344,6 +10359,12 @@ interface Query extends IsQuery, PickQueryTable, PickQueryShape, PickQuerySelect
10344
10359
  relationQueries: IsQueries;
10345
10360
  error: new (message: string, length: number, name: QueryErrorName) => QueryError;
10346
10361
  }
10362
+ declare namespace Query {
10363
+ namespace Order {
10364
+ type Arg<T extends Order.ArgThis> = Order.Arg<T>;
10365
+ type Args<T extends Order.ArgThis> = Order.Args<T>;
10366
+ }
10367
+ }
10347
10368
  type SelectableOfType<T extends PickQuerySelectable, Type> = {
10348
10369
  [K in keyof T['__selectable']]: T['__selectable'][K]['column']['type'] extends Type | null ? K : never;
10349
10370
  }[keyof T['__selectable']];
@@ -10899,5 +10920,5 @@ declare const testTransaction: {
10899
10920
  close(arg: Arg): Promise<void>;
10900
10921
  };
10901
10922
 
10902
- export { ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, ColumnsShape, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DefaultPrivileges, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn$1 as StringColumn, TableData, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, XMLColumn, _appendQuery, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setConnectRetryConfig, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, snakeCaseKey, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
10903
- export type { AdapterBase, AdapterConfigBase, AfterCommitStandaloneHook, AfterHook, ArrayColumnValue, ArrayData, AsyncState, BaseNumberData, Code, Codes, ColumnFromDbParams, ColumnSchemaConfig, ColumnSchemaGetterColumns, ColumnSchemaGetterTableClass, ColumnToCodeCtx, ColumnTypeSchemaArg, ColumnsByType, ComputedColumnsFromOptions, ComputedOptionsConfig, ComputedOptionsFactory, CreateCtx, CreateData, CreateManyMethodsNames, CreateMethodsNames, CreateSelf, DateColumnData, DbDomainArg, DbExtension, DbOptions, DbResult, DbSharedOptions, DbSqlMethod, DbStructureDomainsMap, DbTableOptionScopes, DbTableOptions, DecimalColumnData, DefaultColumnTypes, DefaultSchemaConfig, DeleteMethodsNames, EmptyObject, EmptyTuple, FromArg, FromResult, GeneratorIgnore, HookSelectValue, IsQuery, IsolationLevel, JoinQueryMethod, JoinedShapes, MapTableScopesOption, MaybeArray, MaybePromise, MergeQuery, NoPrimaryKeyOption, NonUniqDataItem, NumberColumnData, OperatorsArray, OperatorsJson, OperatorsOrdinalText, Ord, PickQueryInputType, PickQueryInternal, PickQueryQ, PickQueryRelations, PickQuerySelectableRelations, PickQueryShape, Query, QueryAfterHook, QueryArraysResult, QueryBeforeActionHook, QueryBeforeHook, QueryData, QueryHasWhere, QueryInternal, QueryLogObject, QueryLogOptions, QueryLogger, QueryManyTake, QueryManyTakeOptional, QueryOrExpression, QueryResult, QueryResultRow, QueryReturnType, QuerySchema, QueryScopes, RawSqlBase, RecordKeyTrue, RecordOptionalString, RecordString, RecordStringOrNumber, RecordUnknown, RelationConfigBase, RelationJoinQuery, RelationsBase, SearchWeight, SelectableFromShape, SerialColumnData, ShallowSimplify, ShapeColumnPrimaryKeys, ShapeUniqueColumns, SingleSql, SingleSqlItem, Sql, SqlFn, StorageOptions, StringData, TableDataFn, TableDataInput, TableDataItem, TableDataItemsUniqueColumnTuples, TableDataItemsUniqueColumns, TableDataItemsUniqueConstraints, TableDataMethods, TemplateLiteralArgs, Timestamps, TransactionAdapterBase, TransactionArgs, TransactionOptions, UniqueConstraints, UniqueTableDataItem, UpdateData, UpsertData, UpsertThis, WhereArg };
10923
+ export { ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, ColumnsShape, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DefaultPrivileges, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, Query, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn$1 as StringColumn, TableData, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, XMLColumn, _appendQuery, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setConnectRetryConfig, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, snakeCaseKey, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
10924
+ export type { AdapterBase, AdapterConfigBase, AfterCommitStandaloneHook, AfterHook, ArrayColumnValue, ArrayData, AsyncState, BaseNumberData, Code, Codes, ColumnFromDbParams, ColumnSchemaConfig, ColumnSchemaGetterColumns, ColumnSchemaGetterTableClass, ColumnToCodeCtx, ColumnTypeSchemaArg, ColumnsByType, ComputedColumnsFromOptions, ComputedOptionsConfig, ComputedOptionsFactory, CreateCtx, CreateData, CreateManyMethodsNames, CreateMethodsNames, CreateSelf, DateColumnData, DbDomainArg, DbExtension, DbOptions, DbResult, DbSharedOptions, DbSqlMethod, DbStructureDomainsMap, DbTableOptionScopes, DbTableOptions, DecimalColumnData, DefaultColumnTypes, DefaultSchemaConfig, DeleteMethodsNames, EmptyObject, EmptyTuple, FromArg, FromResult, GeneratorIgnore, HookSelectValue, IsQuery, IsolationLevel, JoinQueryMethod, JoinedShapes, MapTableScopesOption, MaybeArray, MaybePromise, MergeQuery, NoPrimaryKeyOption, NonUniqDataItem, NumberColumnData, OperatorsArray, OperatorsJson, OperatorsOrdinalText, Ord, PickQueryInputType, PickQueryInternal, PickQueryQ, PickQueryRelations, PickQuerySelectableRelations, PickQueryShape, QueryAfterHook, QueryArraysResult, QueryBeforeActionHook, QueryBeforeHook, QueryData, QueryHasWhere, QueryHelperResult, QueryInternal, QueryLogObject, QueryLogOptions, QueryLogger, QueryManyTake, QueryManyTakeOptional, QueryOrExpression, QueryResult, QueryResultRow, QueryReturnType, QuerySchema, QueryScopes, RawSqlBase, RecordKeyTrue, RecordOptionalString, RecordString, RecordStringOrNumber, RecordUnknown, RelationConfigBase, RelationJoinQuery, RelationsBase, SearchWeight, SelectableFromShape, SerialColumnData, ShallowSimplify, ShapeColumnPrimaryKeys, ShapeUniqueColumns, SingleSql, SingleSqlItem, Sql, SqlFn, SqlSessionState, StorageOptions, StringData, TableDataFn, TableDataInput, TableDataItem, TableDataItemsUniqueColumnTuples, TableDataItemsUniqueColumns, TableDataItemsUniqueConstraints, TableDataMethods, TemplateLiteralArgs, Timestamps, TransactionAdapterBase, TransactionArgs, TransactionOptions, UniqueConstraints, UniqueTableDataItem, UpdateData, UpsertData, UpsertThis, WhereArg };
package/dist/index.js CHANGED
@@ -3975,6 +3975,14 @@ class UnhandledTypeError extends OrchidOrmInternalError {
3975
3975
  super(query, `Unhandled type: ${JSON.stringify(value)} received`);
3976
3976
  }
3977
3977
  }
3978
+ class NestedSqlSessionError extends OrchidOrmInternalError {
3979
+ constructor(query) {
3980
+ super(
3981
+ query,
3982
+ "Cannot nest SQL session scopes. Outer scope already has role or setConfig defined."
3983
+ );
3984
+ }
3985
+ }
3978
3986
 
3979
3987
  const escape = (value, migration, nested) => {
3980
3988
  const type = typeof value;
@@ -4071,15 +4079,53 @@ class QueryLog {
4071
4079
  }
4072
4080
  }
4073
4081
 
4074
- const processStorageOptions = (query, options) => {
4082
+ const hasSqlSessionContextOptions = (options) => {
4083
+ return options.role !== void 0 || options.setConfig !== void 0;
4084
+ };
4085
+ const hasActiveSqlSessionContext = (state) => {
4086
+ if (!state) return false;
4087
+ return state.role !== void 0 || state.setConfig !== void 0;
4088
+ };
4089
+ const sqlSessionContextNormalizeSetConfig = (setConfig) => {
4090
+ return Object.fromEntries(
4091
+ Object.entries(setConfig).map(([key, value]) => [key, String(value)])
4092
+ );
4093
+ };
4094
+ const sqlSessionContextSetStorageOptions = (query, state, options, result) => {
4095
+ if (hasSqlSessionContextOptions(options) && hasActiveSqlSessionContext(state)) {
4096
+ throw new NestedSqlSessionError(query);
4097
+ }
4098
+ if (options.role !== void 0) {
4099
+ result.role = options.role;
4100
+ }
4101
+ if (options.setConfig) {
4102
+ result.setConfig = sqlSessionContextNormalizeSetConfig(options.setConfig);
4103
+ }
4104
+ };
4105
+ const sqlSessionContextMergeStorageState = (state, options) => {
4106
+ if (!options) return state;
4107
+ return {
4108
+ role: options.role ?? state?.role,
4109
+ setConfig: options.setConfig ?? state?.setConfig
4110
+ };
4111
+ };
4112
+ const sqlSessionContextGetStateFromAsyncState = (state) => {
4113
+ return state?.role || state?.setConfig ? state : void 0;
4114
+ };
4115
+
4116
+ const processStorageOptions = (query, state, options) => {
4075
4117
  let log;
4076
4118
  if (options.log !== void 0 && !query.q.log) {
4077
4119
  log = logParamToLogObject(query.q.logger, options.log);
4078
4120
  }
4079
- return log || "schema" in options ? {
4080
- log,
4081
- schema: options.schema
4082
- } : void 0;
4121
+ const result = {};
4122
+ if (log) result.log = log;
4123
+ if ("schema" in options) result.schema = options.schema;
4124
+ sqlSessionContextSetStorageOptions(query, state, options, result);
4125
+ if (result.log === void 0 && result.schema === void 0 && result.role === void 0 && result.setConfig === void 0) {
4126
+ return void 0;
4127
+ }
4128
+ return result;
4083
4129
  };
4084
4130
  let currentDefaultSchema;
4085
4131
  const setCurrentDefaultSchema = (schema) => {
@@ -4089,14 +4135,15 @@ const getQuerySchema$1 = (query) => query.q.schema || currentDefaultSchema;
4089
4135
  class QueryStorage {
4090
4136
  async withOptions(options, cb) {
4091
4137
  const state = this.internal.asyncStorage.getStore();
4092
- const opts = processStorageOptions(this, options);
4093
- return this.internal.asyncStorage.run(
4094
- {
4095
- ...state,
4096
- ...opts
4097
- },
4098
- cb
4099
- );
4138
+ const opts = processStorageOptions(this, state, options);
4139
+ const sqlSessionState = sqlSessionContextMergeStorageState(state, opts);
4140
+ const newState = opts ? {
4141
+ ...state,
4142
+ log: opts.log ?? state?.log,
4143
+ schema: opts.schema ?? state?.schema,
4144
+ ...sqlSessionState
4145
+ } : void 0;
4146
+ return !opts ? state ? this.internal.asyncStorage.run(state, cb) : cb() : this.internal.asyncStorage.run(newState, cb);
4100
4147
  }
4101
4148
  }
4102
4149
 
@@ -4146,7 +4193,7 @@ class QueryTransaction {
4146
4193
  const sql = {
4147
4194
  values: emptyArray
4148
4195
  };
4149
- const opts = processStorageOptions(this, options);
4196
+ const opts = processStorageOptions(this, void 0, options);
4150
4197
  const log = opts?.log || this.q.log;
4151
4198
  let logData;
4152
4199
  let state = this.internal.asyncStorage.getStore();
@@ -4948,7 +4995,8 @@ const then = async (q, adapter, state, beforeHooks, afterHooks, afterSaveHooks,
4948
4995
  method,
4949
4996
  sql,
4950
4997
  startingSavepoint,
4951
- releasingSavepoint
4998
+ releasingSavepoint,
4999
+ sqlSessionContextGetStateFromAsyncState(state)
4952
5000
  );
4953
5001
  const { runAfterQuery } = sql;
4954
5002
  if (log) {
@@ -4994,7 +5042,8 @@ const then = async (q, adapter, state, beforeHooks, afterHooks, afterSaveHooks,
4994
5042
  queryMethod,
4995
5043
  sql,
4996
5044
  i === 0 ? startingSavepoint : void 0,
4997
- i === last ? releasingSavepoint : void 0
5045
+ i === last ? releasingSavepoint : void 0,
5046
+ sqlSessionContextGetStateFromAsyncState(state)
4998
5047
  );
4999
5048
  if (queryResult) {
5000
5049
  queryResult.rowCount += result2.rowCount;
@@ -5286,12 +5335,13 @@ const then = async (q, adapter, state, beforeHooks, afterHooks, afterSaveHooks,
5286
5335
  const setCatchingSavepoint = (catchTrx) => {
5287
5336
  return catchTrx ? `s${catchTrx.catchI = (catchTrx.catchI || 0) + 1}` : void 0;
5288
5337
  };
5289
- const execQuery = (adapter, method, sql, startingSavepoint, releasingSavepoint) => {
5338
+ const execQuery = (adapter, method, sql, startingSavepoint, releasingSavepoint, sqlSessionState) => {
5290
5339
  return adapter[method](
5291
5340
  sql.text,
5292
5341
  sql.values,
5293
5342
  startingSavepoint,
5294
- releasingSavepoint
5343
+ releasingSavepoint,
5344
+ sqlSessionState
5295
5345
  ).then((result) => {
5296
5346
  if (result.rowCount && !result.rows.length) {
5297
5347
  result.rows.length = result.rowCount;
@@ -12890,16 +12940,12 @@ class QueryCreate {
12890
12940
  * )
12891
12941
  * .from('b');
12892
12942
  * ```
12893
- *
12894
- * @param data - data for the record, may have values, raw SQL, queries, relation operations.
12895
12943
  */
12896
12944
  create(data) {
12897
12945
  return _queryCreate(_clone(this), data);
12898
12946
  }
12899
12947
  /**
12900
12948
  * Works exactly as {@link create}, except that it returns inserted row count by default.
12901
- *
12902
- * @param data - data for the record, may have values, raw SQL, queries, relation operations.
12903
12949
  */
12904
12950
  insert(data) {
12905
12951
  return _queryInsert(_clone(this), data);
@@ -15801,7 +15847,14 @@ const performQuery = async (q, args, method) => {
15801
15847
  let logData;
15802
15848
  if (log) logData = log.beforeQuery(sql);
15803
15849
  try {
15804
- const result = await (trx?.transactionAdapter || q.adapterNotInTransaction)[method](sql.text, sql.values);
15850
+ const adapter = trx?.transactionAdapter || q.adapterNotInTransaction;
15851
+ const result = await adapter[method](
15852
+ sql.text,
15853
+ sql.values,
15854
+ void 0,
15855
+ void 0,
15856
+ sqlSessionContextGetStateFromAsyncState(trx)
15857
+ );
15805
15858
  if (log) log.afterQuery(sql, logData);
15806
15859
  return result;
15807
15860
  } catch (err) {