pqb 0.18.33 → 0.19.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 +111 -27
- package/dist/index.js +29 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +29 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as orchid_core from 'orchid-core';
|
|
2
|
-
import { QueryResultRow, AdapterBase, QueryInput, Sql, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase,
|
|
2
|
+
import { QueryResultRow, AdapterBase, QueryInput, Sql, StringKey, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase, Expression, ColumnTypeBase, MaybeArray, TemplateLiteralArgs, ColumnsParsers, getValueKey, ColumnTypesBase, ColumnShapeOutput, DefaultSelectColumns, EmptyObject, DbBase, QueryThen, QueryCatch, TransactionState, SQLQueryArgs, NullableColumn, SetOptional, EmptyTuple, MergeObjects, RawSQLBase, RawSQLValues, ExpressionTypeMethod, DynamicSQLArg, StaticSQLArgs, Spread, Code, OperatorToSQL, BaseNumberData, NumberTypeMethods, ColumnWithDefault, StringTypeData, PrimaryKeyColumn, stringTypeMethods, DateTypeMethods, DateColumnData, EncodeColumn, ParseColumn, JSONType, JSONUnknown, JSONTypes, ArrayMethodsData, arrayTypeMethods, ForeignKeyTable, TimestampHelpers, ColumnNameOfTable, ColumnDataBase, ValidationContext, ErrorMessage } from 'orchid-core';
|
|
3
3
|
import { PoolConfig, Pool, PoolClient } from 'pg';
|
|
4
4
|
import { inspect } from 'node:util';
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
@@ -50,30 +50,12 @@ declare class TransactionAdapter implements Adapter {
|
|
|
50
50
|
close(): Promise<void>;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
* Clones the current query chain, useful for re-using partial query snippets in other queries without mutating the original.
|
|
56
|
-
*
|
|
57
|
-
* Used under the hood, and not really needed on the app side.
|
|
58
|
-
*/
|
|
59
|
-
clone<T extends QueryBase>(this: T): T;
|
|
60
|
-
abstract result: ColumnsShapeBase;
|
|
61
|
-
q: QueryData;
|
|
62
|
-
table?: string;
|
|
63
|
-
selectable: SelectableBase;
|
|
64
|
-
shape: ColumnsShapeBase;
|
|
65
|
-
relations: RelationsBase;
|
|
66
|
-
withData: WithDataBase;
|
|
67
|
-
baseQuery: Query;
|
|
68
|
-
internal: QueryInternal;
|
|
69
|
-
meta: QueryMetaBase;
|
|
70
|
-
returnType: QueryReturnType;
|
|
71
|
-
}
|
|
72
|
-
|
|
53
|
+
type RelationsChain = (Query | RelationQuery)[];
|
|
54
|
+
type RelationJoinQuery = (joiningQuery: Query, baseQuery: Query) => Query;
|
|
73
55
|
type RelationConfigBase = {
|
|
74
56
|
table: QueryWithTable;
|
|
75
57
|
query: QueryWithTable;
|
|
76
|
-
joinQuery
|
|
58
|
+
joinQuery: RelationJoinQuery;
|
|
77
59
|
one: boolean;
|
|
78
60
|
required: boolean;
|
|
79
61
|
omitForeignKeyInCreate: PropertyKey;
|
|
@@ -102,6 +84,26 @@ type RelationQuery<Name extends PropertyKey = PropertyKey, Config extends Relati
|
|
|
102
84
|
} : K extends 'join' ? <T extends Query>(this: T) => T : K extends CreateMethodsNames ? Config['chainedCreate'] extends true ? T[K] : never : K extends DeleteMethodsNames ? Config['chainedDelete'] extends true ? T[K] : never : K extends keyof T ? T[K] : K extends 'relationConfig' ? Config : never;
|
|
103
85
|
}> = ((params: Config['params']) => Config['one'] extends true ? Config['required'] extends true ? SetQueryReturnsOne<Q> : SetQueryReturnsOneOptional<Q> : Q) & Q;
|
|
104
86
|
|
|
87
|
+
declare abstract class QueryBase implements QueryBaseCommon {
|
|
88
|
+
/**
|
|
89
|
+
* Clones the current query chain, useful for re-using partial query snippets in other queries without mutating the original.
|
|
90
|
+
*
|
|
91
|
+
* Used under the hood, and not really needed on the app side.
|
|
92
|
+
*/
|
|
93
|
+
clone<T extends QueryBase>(this: T): T;
|
|
94
|
+
abstract result: ColumnsShapeBase;
|
|
95
|
+
q: QueryData;
|
|
96
|
+
table?: string;
|
|
97
|
+
selectable: SelectableBase;
|
|
98
|
+
shape: ColumnsShapeBase;
|
|
99
|
+
relations: RelationsBase;
|
|
100
|
+
withData: WithDataBase;
|
|
101
|
+
baseQuery: Query;
|
|
102
|
+
internal: QueryInternal;
|
|
103
|
+
meta: QueryMetaBase;
|
|
104
|
+
returnType: QueryReturnType;
|
|
105
|
+
}
|
|
106
|
+
|
|
105
107
|
declare const checkIfASimpleQuery: (q: Query) => boolean;
|
|
106
108
|
type WithItem = [
|
|
107
109
|
as: string,
|
|
@@ -314,6 +316,7 @@ type CommonQueryData = {
|
|
|
314
316
|
transform?: ((input: unknown) => unknown)[];
|
|
315
317
|
language?: string;
|
|
316
318
|
isSubQuery?: true;
|
|
319
|
+
relChain?: RelationsChain;
|
|
317
320
|
/**
|
|
318
321
|
* Stores current operator functions available for the query.
|
|
319
322
|
* Is needed to remove these operators from query object when changing the query type, see {@link setQueryOperators}.
|
|
@@ -591,6 +594,73 @@ type DbResult<ColumnTypes> = Db<string, Record<string, never>, EmptyObject, Colu
|
|
|
591
594
|
adapter: Adapter;
|
|
592
595
|
close: Adapter['close'];
|
|
593
596
|
};
|
|
597
|
+
/**
|
|
598
|
+
* For the case of using the query builder as a standalone tool, use `createDb` from `pqb` package.
|
|
599
|
+
*
|
|
600
|
+
* As `Orchid ORM` focuses on ORM usage, docs examples mostly demonstrates how to work with ORM-defined tables,
|
|
601
|
+
* but everything that's not related to table relations should also work with `pqb` query builder on its own.
|
|
602
|
+
*
|
|
603
|
+
* It is accepting the same options as `orchidORM` + options of `createBaseTable`:
|
|
604
|
+
*
|
|
605
|
+
* ```ts
|
|
606
|
+
* import { createDb } from 'orchid-orm';
|
|
607
|
+
*
|
|
608
|
+
* const db = createDb({
|
|
609
|
+
* // db connection options
|
|
610
|
+
* databaseURL: process.env.DATABASE_URL,
|
|
611
|
+
* log: true,
|
|
612
|
+
*
|
|
613
|
+
* // columns in db are in snake case:
|
|
614
|
+
* snakeCase: true,
|
|
615
|
+
*
|
|
616
|
+
* // override default SQL for timestamp, see `nowSQL` above
|
|
617
|
+
* nowSQL: `now() AT TIME ZONE 'UTC'`,
|
|
618
|
+
*
|
|
619
|
+
* // override column types:
|
|
620
|
+
* columnTypes: (t) => ({
|
|
621
|
+
* // by default timestamp is returned as a string, override to a number
|
|
622
|
+
* timestamp: () => t.timestamp().asNumber(),
|
|
623
|
+
* }),
|
|
624
|
+
* });
|
|
625
|
+
* ```
|
|
626
|
+
*
|
|
627
|
+
* After `db` is defined, construct queryable tables in such way:
|
|
628
|
+
*
|
|
629
|
+
* ```ts
|
|
630
|
+
* export const User = db('user', (t) => ({
|
|
631
|
+
* id: t.identity().primaryKey(),
|
|
632
|
+
* name: t.text(3, 100),
|
|
633
|
+
* password: t.text(8, 200),
|
|
634
|
+
* age: t.integer().nullable(),
|
|
635
|
+
* ...t.timestamps(),
|
|
636
|
+
* }));
|
|
637
|
+
* ```
|
|
638
|
+
*
|
|
639
|
+
* Now the `User` can be used for making type-safe queries:
|
|
640
|
+
*
|
|
641
|
+
* ```ts
|
|
642
|
+
* const users = await User.select('id', 'name') // only known columns are allowed
|
|
643
|
+
* .where({ age: { gte: 20 } }) // gte is available only on the numeric field, and the only number is allowed
|
|
644
|
+
* .order({ createdAt: 'DESC' }) // type safe as well
|
|
645
|
+
* .limit(10);
|
|
646
|
+
*
|
|
647
|
+
* // users array has a proper type of Array<{ id: number, name: string }>
|
|
648
|
+
* ```
|
|
649
|
+
*
|
|
650
|
+
* The optional third argument is for table options:
|
|
651
|
+
*
|
|
652
|
+
* ```ts
|
|
653
|
+
* const Table = db('table', (t) => ({ ...columns }), {
|
|
654
|
+
* // provide this value if the table belongs to a specific database schema:
|
|
655
|
+
* schema: 'customTableSchema',
|
|
656
|
+
* // override `log` option of `createDb`:
|
|
657
|
+
* log: true, // boolean or object described `createdDb` section
|
|
658
|
+
* logger: { ... }, // override logger
|
|
659
|
+
* noPrimaryKey: 'ignore', // override noPrimaryKey
|
|
660
|
+
* snakeCase: true, // override snakeCase
|
|
661
|
+
* })
|
|
662
|
+
* ```
|
|
663
|
+
*/
|
|
594
664
|
declare const createDb: <ColumnTypes extends Record<string, orchid_core.AnyColumnTypeCreator> = DefaultColumnTypes>({ log, logger, columnTypes: ctOrFn, snakeCase, nowSQL, ...options }: DbOptions<ColumnTypes>) => DbResult<ColumnTypes>;
|
|
595
665
|
|
|
596
666
|
type ToSQLCtx = {
|
|
@@ -1891,7 +1961,7 @@ declare class QueryGet {
|
|
|
1891
1961
|
* It will throw `NotFoundError` when not found.
|
|
1892
1962
|
*
|
|
1893
1963
|
* ```ts
|
|
1894
|
-
* import { NumberColumn } from '
|
|
1964
|
+
* import { NumberColumn } from 'orchid-orm';
|
|
1895
1965
|
*
|
|
1896
1966
|
* const firstName: string = await db.table.get('name');
|
|
1897
1967
|
*
|
|
@@ -3754,7 +3824,7 @@ declare abstract class JsonModifiers extends QueryBase {
|
|
|
3754
3824
|
* Selects a value from JSON data using a JSON path.
|
|
3755
3825
|
*
|
|
3756
3826
|
* ```ts
|
|
3757
|
-
* import { columnTypes } from '
|
|
3827
|
+
* import { columnTypes } from 'orchid-orm';
|
|
3758
3828
|
*
|
|
3759
3829
|
* db.table.jsonPathQuery(
|
|
3760
3830
|
* columnTypes.text(3, 100), // type of the value
|
|
@@ -4001,7 +4071,7 @@ declare class With {
|
|
|
4001
4071
|
* Add Common Table Expression (CTE) to the query.
|
|
4002
4072
|
*
|
|
4003
4073
|
* ```ts
|
|
4004
|
-
* import { columnTypes } from '
|
|
4074
|
+
* import { columnTypes } from 'orchid-orm';
|
|
4005
4075
|
* import { NumberColumn } from './number';
|
|
4006
4076
|
*
|
|
4007
4077
|
* // .with optionally accepts such options:
|
|
@@ -4345,7 +4415,7 @@ declare class Update {
|
|
|
4345
4415
|
* To make sure that at least one row was updated use `updateOrThrow`:
|
|
4346
4416
|
*
|
|
4347
4417
|
* ```ts
|
|
4348
|
-
* import { NotFoundError } from '
|
|
4418
|
+
* import { NotFoundError } from 'orchid-orm';
|
|
4349
4419
|
*
|
|
4350
4420
|
* try {
|
|
4351
4421
|
* // updatedCount is guaranteed to be greater than 0
|
|
@@ -5635,6 +5705,20 @@ declare class QueryMethods<ColumnTypes> {
|
|
|
5635
5705
|
* await selectFollowing(db.user.select('id', 'name'), currentUser);
|
|
5636
5706
|
* ```
|
|
5637
5707
|
*
|
|
5708
|
+
* To get the result type of query helper, use `QueryHelperResult` type:
|
|
5709
|
+
*
|
|
5710
|
+
* ```ts
|
|
5711
|
+
* import { QueryHelperResult } from 'orchid-orm';
|
|
5712
|
+
*
|
|
5713
|
+
* const selectHelper = db.table.makeHelper((q) => q.select('id', 'name'));
|
|
5714
|
+
*
|
|
5715
|
+
* // This type is identical to `db.table.select('id', 'name')`
|
|
5716
|
+
* type SelectQuery = QueryHelperResult<typeof selectHelper>;
|
|
5717
|
+
*
|
|
5718
|
+
* // Await to get result, the type is `{ id: number, name: string }[]`
|
|
5719
|
+
* type Result = Awaited<QueryHelperResult<typeof selectHelper>>;
|
|
5720
|
+
* ```
|
|
5721
|
+
*
|
|
5638
5722
|
* @param fn - helper function
|
|
5639
5723
|
*/
|
|
5640
5724
|
makeHelper<T extends Query, Args extends unknown[], Result>(this: T, fn: (q: T, ...args: Args) => Result): QueryHelper<T, Args, Result>;
|
|
@@ -7155,4 +7239,4 @@ declare module 'orchid-core' {
|
|
|
7155
7239
|
}
|
|
7156
7240
|
declare function addComputedColumns<T extends Query, Computed extends ComputedColumnsBase<T>>(q: T, computed: Computed): QueryWithComputed<T, Computed>;
|
|
7157
7241
|
|
|
7158
|
-
export { Adapter, AdapterConfig, AdapterOptions, AddQueryDefaults, AddQuerySelect, AddQueryWith, AfterHook, AggregateMethods, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AsMethods, BaseOperators, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanNullable, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnExpression, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnRefExpression, ColumnType, ColumnsObject, ColumnsShape, CommonQueryData, ComputedColumnsBase, CopyMethods, CopyOptions, CopyQueryData, Create, CreateColumn, CreateCtx, CreateData, CreateKind, CreateMethodsNames, CreateRelationDataOmittingFKeys, CreateRelationsData, CreateRelationsDataOmittingFKeys, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, DynamicRawSQL, EnumColumn, ExpressionOutput, FnExpression, FnExpressionArgs, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, GetStringArg, GroupArg, Having, HavingItem, HookAction, HookSelect, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, JsonItem, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrCreateArg, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, OrderTsQueryConfig, Over, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryAfterHook, QueryArraysResult, QueryBase, QueryBeforeHook, QueryData, QueryDefaultReturnData, QueryError, QueryErrorName, QueryGet, QueryHelperResult, QueryHookSelect, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QuerySourceItem, QueryTransform, QueryTransformFn, QueryUpsertOrCreate, QueryWithComputed, QueryWithTable, RawSQL, RawSqlMethods, RealColumn, RelationConfigBase, RelationConfigDataForCreate, RelationQuery, RelationQueryBase, RelationsBase, SearchArg, SearchMethods, SearchWeight, Select, SelectArg, SelectAs, SelectItem, SelectQueryData, SelectSubQueryResult, SelectableBase, SelectableFromShape, SelectableOfType, SelectableOrExpression, SelectableOrExpressionOfType, SerialColumn, SerialColumnData, SetQueryKind, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumn, SetQueryReturnsColumnInfo, SetQueryReturnsColumnOptional, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsPluckColumn, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSQLCtx, ToSQLOptions, Transaction, TransactionAdapter, TransactionOptions, TransformMethods, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertArg, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBase, WhereQueryBuilder, WhereResult, WhereSearchItem, WhereSearchResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addComputedColumns, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryOn, addWhere, addWhereIn, addWhereNot, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, countSelect, createDb, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
|
|
7242
|
+
export { Adapter, AdapterConfig, AdapterOptions, AddQueryDefaults, AddQuerySelect, AddQueryWith, AfterHook, AggregateMethods, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, AsMethods, BaseOperators, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanNullable, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnExpression, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnRefExpression, ColumnType, ColumnsObject, ColumnsShape, CommonQueryData, ComputedColumnsBase, CopyMethods, CopyOptions, CopyQueryData, Create, CreateColumn, CreateCtx, CreateData, CreateKind, CreateMethodsNames, CreateRelationDataOmittingFKeys, CreateRelationsData, CreateRelationsDataOmittingFKeys, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, DynamicRawSQL, EnumColumn, ExpressionOutput, FnExpression, FnExpressionArgs, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, GetStringArg, GroupArg, Having, HavingItem, HookAction, HookSelect, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, JsonItem, JsonMethods, JsonModifiers, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operator, Operators, OrCreateArg, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, OrderTsQueryConfig, Over, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryAfterHook, QueryArraysResult, QueryBase, QueryBeforeHook, QueryData, QueryDefaultReturnData, QueryError, QueryErrorName, QueryGet, QueryHelperResult, QueryHookSelect, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QuerySourceItem, QueryTransform, QueryTransformFn, QueryUpsertOrCreate, QueryWithComputed, QueryWithTable, RawSQL, RawSqlMethods, RealColumn, RelationConfigBase, RelationConfigDataForCreate, RelationJoinQuery, RelationQuery, RelationQueryBase, RelationsBase, RelationsChain, SearchArg, SearchMethods, SearchWeight, Select, SelectArg, SelectAs, SelectItem, SelectQueryData, SelectSubQueryResult, SelectableBase, SelectableFromShape, SelectableOfType, SelectableOrExpression, SelectableOrExpressionOfType, SerialColumn, SerialColumnData, SetQueryKind, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumn, SetQueryReturnsColumnInfo, SetQueryReturnsColumnOptional, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsPluckColumn, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSQLCtx, ToSQLOptions, Transaction, TransactionAdapter, TransactionOptions, TransformMethods, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertArg, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBase, WhereQueryBuilder, WhereResult, WhereSearchItem, WhereSearchResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addComputedColumns, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryOn, addWhere, addWhereIn, addWhereNot, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, countSelect, createDb, extendQuery, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isSelectingCount, joinSubQuery, logColors, logParamToLogObject, makeExpression, makeFnExpression, makeRegexToFindInSql, makeSQL, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushLimitSQL, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, raw, referencesArgsToCode, resetTableData, resolveSubQueryCallback, saveSearchAlias, setParserForSelectedString, setQueryObjectValue, setQueryOperators, simplifyColumnDefault, templateLiteralToSQL, testTransaction, throwIfNoWhere, toSQL, toSQLCacheKey };
|
package/dist/index.js
CHANGED
|
@@ -1074,7 +1074,7 @@ const processWhere = (ands, ctx, table, query, data, quotedAs, not) => {
|
|
|
1074
1074
|
const res = data(qb);
|
|
1075
1075
|
const expr = res instanceof orchidCore.Expression ? res : res.q.expr;
|
|
1076
1076
|
if (!(res instanceof orchidCore.Expression) && res.q.expr) {
|
|
1077
|
-
const q = "relationConfig" in res ? res.relationConfig.joinQuery(
|
|
1077
|
+
const q = "relationConfig" in res ? res.relationConfig.joinQuery(res, table) : res.clone();
|
|
1078
1078
|
q.q.select = [expr];
|
|
1079
1079
|
ands.push(`${prefix}(${makeSQL(q, ctx).text})`);
|
|
1080
1080
|
} else {
|
|
@@ -1308,7 +1308,7 @@ const processJoinItem = (ctx, table, query, item, quotedAs) => {
|
|
|
1308
1308
|
if (typeof first === "string") {
|
|
1309
1309
|
if (first in table.relations) {
|
|
1310
1310
|
const { query: toQuery, joinQuery } = table.relations[first].relationConfig;
|
|
1311
|
-
const jq = joinQuery(
|
|
1311
|
+
const jq = joinQuery(toQuery, table);
|
|
1312
1312
|
const { q: j } = jq;
|
|
1313
1313
|
const tableName = typeof j.from === "string" ? j.from : jq.table;
|
|
1314
1314
|
target = quoteSchemaAndTable(j.schema, tableName);
|
|
@@ -1436,8 +1436,8 @@ const processArgs = (args, ctx, table, query, first, joinAs, joinShape, quotedAs
|
|
|
1436
1436
|
base = base.as(q.q.as);
|
|
1437
1437
|
}
|
|
1438
1438
|
const { q: query2 } = first.joinQueryAfterCallback(
|
|
1439
|
-
|
|
1440
|
-
|
|
1439
|
+
base,
|
|
1440
|
+
table
|
|
1441
1441
|
);
|
|
1442
1442
|
if (query2.and) {
|
|
1443
1443
|
pushQueryArray(q, "and", query2.and);
|
|
@@ -2431,16 +2431,18 @@ const makeRegexToFindInSql = (value) => {
|
|
|
2431
2431
|
return new RegExp(`${value}(?=(?:[^']*'[^']*')*[^']*$)`, "g");
|
|
2432
2432
|
};
|
|
2433
2433
|
const resolveSubQueryCallback = (q, cb) => {
|
|
2434
|
-
const { isSubQuery } = q.q;
|
|
2434
|
+
const { isSubQuery, relChain } = q.q;
|
|
2435
2435
|
q.q.isSubQuery = true;
|
|
2436
|
+
q.q.relChain = void 0;
|
|
2436
2437
|
const result = cb(q);
|
|
2437
2438
|
q.q.isSubQuery = isSubQuery;
|
|
2439
|
+
q.q.relChain = relChain;
|
|
2438
2440
|
return result;
|
|
2439
2441
|
};
|
|
2440
2442
|
const joinSubQuery = (q, sub) => {
|
|
2441
2443
|
if (!("relationConfig" in sub))
|
|
2442
2444
|
return sub;
|
|
2443
|
-
return sub.relationConfig.joinQuery(
|
|
2445
|
+
return sub.relationConfig.joinQuery(sub, q);
|
|
2444
2446
|
};
|
|
2445
2447
|
|
|
2446
2448
|
const pushQueryArray = (q, key, value) => {
|
|
@@ -5816,8 +5818,8 @@ const _joinLateral = (q, type, arg, cb, as) => {
|
|
|
5816
5818
|
let result = cb(query);
|
|
5817
5819
|
if (relation) {
|
|
5818
5820
|
result = relation.relationConfig.joinQuery(
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
+
result,
|
|
5822
|
+
q
|
|
5821
5823
|
);
|
|
5822
5824
|
}
|
|
5823
5825
|
const joinKey = as || result.q.as || result.table;
|
|
@@ -5888,7 +5890,7 @@ const processSelectArg = (q, as, arg, columnAs) => {
|
|
|
5888
5890
|
if (typeof value === "function") {
|
|
5889
5891
|
value = resolveSubQueryCallback(q, value);
|
|
5890
5892
|
if (!orchidCore.isExpression(value) && value.joinQuery) {
|
|
5891
|
-
value = value.joinQuery(
|
|
5893
|
+
value = value.joinQuery(value, q);
|
|
5892
5894
|
let query;
|
|
5893
5895
|
const returnType = value.q.returnType;
|
|
5894
5896
|
if (!returnType || returnType === "all") {
|
|
@@ -6185,7 +6187,7 @@ class QueryGet {
|
|
|
6185
6187
|
* It will throw `NotFoundError` when not found.
|
|
6186
6188
|
*
|
|
6187
6189
|
* ```ts
|
|
6188
|
-
* import { NumberColumn } from '
|
|
6190
|
+
* import { NumberColumn } from 'orchid-orm';
|
|
6189
6191
|
*
|
|
6190
6192
|
* const firstName: string = await db.table.get('name');
|
|
6191
6193
|
*
|
|
@@ -7469,7 +7471,7 @@ class JsonModifiers extends QueryBase {
|
|
|
7469
7471
|
* Selects a value from JSON data using a JSON path.
|
|
7470
7472
|
*
|
|
7471
7473
|
* ```ts
|
|
7472
|
-
* import { columnTypes } from '
|
|
7474
|
+
* import { columnTypes } from 'orchid-orm';
|
|
7473
7475
|
*
|
|
7474
7476
|
* db.table.jsonPathQuery(
|
|
7475
7477
|
* columnTypes.text(3, 100), // type of the value
|
|
@@ -8056,7 +8058,7 @@ class With {
|
|
|
8056
8058
|
* Add Common Table Expression (CTE) to the query.
|
|
8057
8059
|
*
|
|
8058
8060
|
* ```ts
|
|
8059
|
-
* import { columnTypes } from '
|
|
8061
|
+
* import { columnTypes } from 'orchid-orm';
|
|
8060
8062
|
* import { NumberColumn } from './number';
|
|
8061
8063
|
*
|
|
8062
8064
|
* // .with optionally accepts such options:
|
|
@@ -8561,7 +8563,7 @@ class Update {
|
|
|
8561
8563
|
* To make sure that at least one row was updated use `updateOrThrow`:
|
|
8562
8564
|
*
|
|
8563
8565
|
* ```ts
|
|
8564
|
-
* import { NotFoundError } from '
|
|
8566
|
+
* import { NotFoundError } from 'orchid-orm';
|
|
8565
8567
|
*
|
|
8566
8568
|
* try {
|
|
8567
8569
|
* // updatedCount is guaranteed to be greater than 0
|
|
@@ -9897,6 +9899,20 @@ class QueryMethods {
|
|
|
9897
9899
|
* await selectFollowing(db.user.select('id', 'name'), currentUser);
|
|
9898
9900
|
* ```
|
|
9899
9901
|
*
|
|
9902
|
+
* To get the result type of query helper, use `QueryHelperResult` type:
|
|
9903
|
+
*
|
|
9904
|
+
* ```ts
|
|
9905
|
+
* import { QueryHelperResult } from 'orchid-orm';
|
|
9906
|
+
*
|
|
9907
|
+
* const selectHelper = db.table.makeHelper((q) => q.select('id', 'name'));
|
|
9908
|
+
*
|
|
9909
|
+
* // This type is identical to `db.table.select('id', 'name')`
|
|
9910
|
+
* type SelectQuery = QueryHelperResult<typeof selectHelper>;
|
|
9911
|
+
*
|
|
9912
|
+
* // Await to get result, the type is `{ id: number, name: string }[]`
|
|
9913
|
+
* type Result = Awaited<QueryHelperResult<typeof selectHelper>>;
|
|
9914
|
+
* ```
|
|
9915
|
+
*
|
|
9900
9916
|
* @param fn - helper function
|
|
9901
9917
|
*/
|
|
9902
9918
|
makeHelper(fn) {
|