pqb 0.11.31 → 0.11.33
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 +50 -12
- package/dist/index.js +90 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +90 -19
- 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 { Sql, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase, EmptyObject, RawExpression, ColumnTypeBase, MaybeArray, QueryResultRow, AdapterBase, QueryInput, ColumnsParsers, getValueKey, StringKey, ColumnOutput, QueryThen, QueryCatch, NullableColumn, EmptyTuple, ColumnTypesBase, ColumnShapeOutput, DefaultSelectColumns, DbBase, SetOptional,
|
|
2
|
+
import { Sql, QueryBaseCommon, ColumnsShapeBase, QueryInternal, QueryMetaBase, EmptyObject, RawExpression, ColumnTypeBase, MaybeArray, QueryResultRow, AdapterBase, QueryInput, ColumnsParsers, getValueKey, StringKey, ColumnOutput, QueryThen, QueryCatch, NullableColumn, EmptyTuple, ColumnTypesBase, ColumnShapeOutput, DefaultSelectColumns, DbBase, SetOptional, MergeObjects, CoalesceString, QueryCommon, Spread, BaseNumberData, Code, ColumnWithDefault, numberTypeMethods, BaseStringData, PrimaryKeyColumn, DateTypeMethods, DateColumnData, EncodeColumn, ParseColumn, JSONTypeAny, record, ArrayMethodsData, arrayMethods, ForeignKeyTable, name, ColumnNameOfTable, ColumnDataBase, BaseOperators, ValidationContext, MessageParam } from 'orchid-core';
|
|
3
3
|
import { PoolConfig, Pool, PoolClient } from 'pg';
|
|
4
4
|
import { inspect } from 'util';
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
@@ -200,7 +200,7 @@ type SimpleJoinItem = {
|
|
|
200
200
|
];
|
|
201
201
|
isSubQuery: boolean;
|
|
202
202
|
};
|
|
203
|
-
type JoinLateralItem = [type: string, joined: Query, as
|
|
203
|
+
type JoinLateralItem = [type: string, joined: Query, as: string];
|
|
204
204
|
type WhereItem = (Omit<Record<string, unknown | Record<string, unknown | Query | RawExpression> | RawExpression>, 'NOT' | 'AND' | 'OR' | 'IN' | 'EXISTS' | 'ON' | 'ON_JSON_PATH_EQUALS'> & {
|
|
205
205
|
NOT?: MaybeArray<WhereItem>;
|
|
206
206
|
AND?: MaybeArray<WhereItem>;
|
|
@@ -310,6 +310,7 @@ declare class TransactionAdapter implements Adapter {
|
|
|
310
310
|
|
|
311
311
|
type JoinedShapes = Record<string, ColumnsShapeBase>;
|
|
312
312
|
type JoinedParsers = Record<string, ColumnsParsers>;
|
|
313
|
+
type JoinOverrides = Record<string, string>;
|
|
313
314
|
type CommonQueryData = {
|
|
314
315
|
adapter: Adapter;
|
|
315
316
|
shape: ColumnsShapeBase;
|
|
@@ -326,6 +327,7 @@ type CommonQueryData = {
|
|
|
326
327
|
joinedParsers?: JoinedParsers;
|
|
327
328
|
joinedForSelect?: string;
|
|
328
329
|
innerJoinLateral?: true;
|
|
330
|
+
joinOverrides?: JoinOverrides;
|
|
329
331
|
schema?: string;
|
|
330
332
|
select?: SelectItem[];
|
|
331
333
|
as?: string;
|
|
@@ -1436,15 +1438,10 @@ declare class QueryGet {
|
|
|
1436
1438
|
_getOptional<T extends Query, Arg extends GetArg<T>>(this: T, arg: Arg): GetOptionalResult<T, Arg>;
|
|
1437
1439
|
}
|
|
1438
1440
|
|
|
1439
|
-
type MergeQuery<T extends Query, Q extends Query, ReturnType extends QueryReturnType = QueryReturnType extends Q['returnType'] ? T['returnType'] : Q['returnType'],
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
returnType:
|
|
1443
|
-
then: QueryThen<Data>;
|
|
1444
|
-
catch: QueryCatch<Data>;
|
|
1445
|
-
selectable: T['selectable'] & Q['selectable'];
|
|
1446
|
-
windows: T['windows'] & Q['windows'];
|
|
1447
|
-
withData: T['withData'] & Q['withData'];
|
|
1441
|
+
type MergeQuery<T extends Query, Q extends Query, ReturnType extends QueryReturnType = QueryReturnType extends Q['returnType'] ? T['returnType'] : Q['returnType'], Result extends ColumnsShapeBase = T['meta']['hasSelect'] extends true ? Q['meta']['hasSelect'] extends true ? {
|
|
1442
|
+
[K in keyof T['result'] | keyof Q['result']]: K extends keyof Q['result'] ? Q['result'][K] : T['result'][K];
|
|
1443
|
+
} : T['result'] : Q['result'], Data = GetQueryResult<ReturnType, Result>> = {
|
|
1444
|
+
[K in keyof T]: K extends 'meta' ? MergeObjects<T['meta'], Q['meta']> : K extends 'result' ? Result : K extends 'returnType' ? ReturnType : K extends 'then' ? QueryThen<Data> : K extends 'catch' ? QueryCatch<Data> : K extends 'selectable' ? T['selectable'] & Q['selectable'] : K extends 'windows' ? MergeObjects<T['windows'], Q['windows']> : K extends 'withData' ? MergeObjects<T['withData'], Q['withData']> : T[K];
|
|
1448
1445
|
};
|
|
1449
1446
|
declare class MergeQueryMethods {
|
|
1450
1447
|
merge<T extends Query, Q extends Query>(this: T, q: Q): MergeQuery<T, Q>;
|
|
@@ -1510,6 +1507,9 @@ type OrderArg<T extends Query, Key extends PropertyKey = keyof T['selectable'] |
|
|
|
1510
1507
|
} | RawExpression;
|
|
1511
1508
|
type OrderArgs<T extends Query> = OrderArg<T>[] | [TemplateStringsArray, ...unknown[]];
|
|
1512
1509
|
type FindArgs<T extends Query> = [T['shape'][T['singlePrimaryKey']]['type'] | RawExpression] | [TemplateStringsArray, ...unknown[]];
|
|
1510
|
+
type QueryHelper<T extends Query, Args extends unknown[], Result> = <Q extends {
|
|
1511
|
+
[K in keyof T]: K extends 'then' ? QueryThen<unknown> : K extends 'result' ? ColumnsShapeBase : T[K];
|
|
1512
|
+
}>(q: Q, ...args: Args) => Result extends Query ? MergeQuery<Q, Result> : Result;
|
|
1513
1513
|
interface QueryMethods extends Omit<AsMethods, 'result'>, Aggregate, Select, From, Join, With, Union, Json, Create, Update, Delete, Transaction, For, ColumnInfoMethods, Omit<Where, 'result'>, Clear, Having, Window, Then, QueryLog, QueryHooks, QueryUpsertOrCreate, QueryGet, MergeQueryMethods, RawSqlMethods, CopyMethods {
|
|
1514
1514
|
}
|
|
1515
1515
|
declare class QueryMethods {
|
|
@@ -1562,6 +1562,44 @@ declare class QueryMethods {
|
|
|
1562
1562
|
restartIdentity?: boolean;
|
|
1563
1563
|
cascade?: boolean;
|
|
1564
1564
|
}): SetQueryReturnsVoid<T>;
|
|
1565
|
+
/**
|
|
1566
|
+
* Use `makeHelper` to make a query helper - a function where you can modify the query, and reuse this function across different places.
|
|
1567
|
+
*
|
|
1568
|
+
* ```ts
|
|
1569
|
+
* const defaultAuthorSelect = db.author.makeHelper((q) => {
|
|
1570
|
+
* return q.select('firstName', 'lastName');
|
|
1571
|
+
* });
|
|
1572
|
+
*
|
|
1573
|
+
* // this will select id, firstName, lastName with a correct TS type
|
|
1574
|
+
* // and return a single record
|
|
1575
|
+
* const result = await defaultAuthorSelect(db.author.select('id').find(1));
|
|
1576
|
+
* ```
|
|
1577
|
+
*
|
|
1578
|
+
* Such helper is available for relation queries inside `select`:
|
|
1579
|
+
*
|
|
1580
|
+
* ```ts
|
|
1581
|
+
* await db.book.select({
|
|
1582
|
+
* author: (book) => defaultAuthorSelect(book.author),
|
|
1583
|
+
* });
|
|
1584
|
+
* ```
|
|
1585
|
+
*
|
|
1586
|
+
* Helper can accept additional arguments:
|
|
1587
|
+
*
|
|
1588
|
+
* ```ts
|
|
1589
|
+
* const selectFollowing = db.user.makeHelper((q, currentUser: { id: number }) => {
|
|
1590
|
+
* return q.select({
|
|
1591
|
+
* following: (q) =>
|
|
1592
|
+
* q.followers.where({ followerId: currentUser.id }).exists(),
|
|
1593
|
+
* });
|
|
1594
|
+
* });
|
|
1595
|
+
*
|
|
1596
|
+
* // select some columns and the `following` boolean field from users
|
|
1597
|
+
* await selectFollowing(db.user.select('id', 'name'), currentUser);
|
|
1598
|
+
* ```
|
|
1599
|
+
*
|
|
1600
|
+
* @param fn - helper function
|
|
1601
|
+
*/
|
|
1602
|
+
makeHelper<T extends Query, Args extends unknown[], Result>(this: T, fn: (q: T, ...args: Args) => Result): QueryHelper<T, Args, Result>;
|
|
1565
1603
|
}
|
|
1566
1604
|
|
|
1567
1605
|
type AggregateArg<T extends Query> = Expression<T> | Record<string, Expression<T>> | [Expression<T>, string];
|
|
@@ -3831,4 +3869,4 @@ declare const testTransaction: {
|
|
|
3831
3869
|
close(arg: Arg): Promise<void>;
|
|
3832
3870
|
};
|
|
3833
3871
|
|
|
3834
|
-
export { Adapter, AdapterConfig, AdapterOptions, AddQuerySelect, AddQueryWith, AfterHook, AfterHookKey, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, BaseRelation, BeforeHook, BeforeHookKey, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnType, ColumnTypes, ColumnsObject, ColumnsShape, CommonQueryData, CopyOptions, CopyQueryData, Create, CreateCtx, CreateData, CreateMethodsNames, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, EnumColumn, Expression, ExpressionOfType, ExpressionOutput, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, HasAndBelongsToManyRelation, HasManyRelation, HasOneRelation, Having, HavingArg, HavingArgs, HavingItem, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, JSONTypes, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinResult, JoinedParsers, JoinedShapes, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operators, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryArraysResult, QueryBase, QueryData, QueryError, QueryErrorName, QueryGet, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryUpsertOrCreate, QueryWithTable, RawSqlMethods, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SelectableFromShape, SerialColumn, SerialColumnData, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumnInfo, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, StringExpression, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TransactionOptions, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertCreateArg, UpsertData, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryHook, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, utils as columnUtils, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, createDb, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getRaw, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isRequiredRelationKey, jsonTypes, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, referencesArgsToCode, relationQueryKey, resetTableData, setQueryObjectValue, simplifyColumnDefault, testTransaction, toSql, toSqlCacheKey };
|
|
3872
|
+
export { Adapter, AdapterConfig, AdapterOptions, AddQuerySelect, AddQueryWith, AfterHook, AfterHookKey, Aggregate, Aggregate1ArgumentTypes, AggregateArg, AggregateItem, AggregateItemArg, AggregateItemOptions, AggregateOptions, AliasOrTable, ArrayColumn, ArrayData, ArrayOfColumnsObjects, BaseRelation, BeforeHook, BeforeHookKey, BelongsToRelation, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BooleanExpression, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, CitextColumn, Clear, ClearStatement, ColumnData, ColumnFromDbParams, ColumnInfo, ColumnInfoMethods, ColumnInfoQueryData, ColumnOperators, ColumnType, ColumnTypes, ColumnsObject, ColumnsShape, CommonQueryData, CopyOptions, CopyQueryData, Create, CreateCtx, CreateData, CreateMethodsNames, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DbOptions, DbResult, DbTableOptions, DecimalBaseColumn, DecimalColumn, DefaultColumnTypes, Delete, DeleteMethodsNames, DeleteQueryData, DomainColumn, DoublePrecisionColumn, DropMode, EnumColumn, Expression, ExpressionOfType, ExpressionOutput, For, ForeignKey, ForeignKeyAction, ForeignKeyMatch, ForeignKeyOptions, From, FromArgs, FromResult, GetArg, GetQueryResult, HasAndBelongsToManyRelation, HasManyRelation, HasOneRelation, Having, HavingArg, HavingArgs, HavingItem, IdentityColumn, IndexColumnOptions, IndexOptions, InetColumn, InsertQueryData, IntegerBaseColumn, IntegerColumn, IntervalColumn, IsolationLevel, JSONColumn, JSONTextColumn, JSONTypes, Join, JoinArgs, JoinCallback, JoinFirstArg, JoinItem, JoinLateralCallback, JoinLateralItem, JoinLateralResult, JoinOverrides, JoinResult, JoinedParsers, JoinedShapes, Json, JsonItem, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQuery, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NoPrimaryKeyOption, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, NumberColumn, NumberColumnData, NumberExpression, OnConflictItem, OnConflictMergeUpdate, OnConflictQueryBuilder, OnQueryBuilder, Operators, OrchidOrmError, OrchidOrmInternalError, OrderArg, OrderArgs, OrderItem, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, Query, QueryArraysResult, QueryBase, QueryData, QueryError, QueryErrorName, QueryGet, QueryHooks, QueryLog, QueryLogObject, QueryLogOptions, QueryLogger, QueryMethods, QueryResult, QueryReturnType, QueryReturnsAll, QueryUpsertOrCreate, QueryWithTable, RawSqlMethods, RealColumn, Relation, RelationQuery, RelationQueryBase, RelationQueryData, RelationsBase, Select, SelectAgg, SelectArg, SelectFunctionItem, SelectItem, SelectQueryData, Selectable, SelectableBase, SelectableFromShape, SerialColumn, SerialColumnData, SetQueryReturns, SetQueryReturnsAll, SetQueryReturnsColumnInfo, SetQueryReturnsOne, SetQueryReturnsOneOptional, SetQueryReturnsPluck, SetQueryReturnsRowCount, SetQueryReturnsRows, SetQueryReturnsValue, SetQueryReturnsValueOptional, SetQueryReturnsVoid, SetQueryTableAlias, SetQueryWith, SimpleJoinItem, SingleColumnIndexOptions, SmallIntColumn, SmallSerialColumn, SortDir, StringColumn, StringExpression, TableData, TextBaseColumn, TextColumn, TextColumnData, Then, TimeColumn, TimeInterval, TimestampColumn, TimestampTZColumn, ToSqlCtx, ToSqlOptions, Transaction, TransactionAdapter, TransactionOptions, TruncateQueryData, TsQueryColumn, TsVectorColumn, TypeParsers, UUIDColumn, UnhandledTypeError, Union, UnionArg, UnionItem, UnionKind, UnknownColumn, Update, UpdateCtx, UpdateData, UpdateQueryData, UpdateQueryDataItem, UpdateQueryDataObject, UpdatedAtDataInjector, UpsertCreateArg, UpsertData, UpsertResult, UpsertThis, VarCharColumn, VirtualColumn, Where, WhereArg, WhereArgs, WhereInArg, WhereInColumn, WhereInItem, WhereInValues, WhereItem, WhereJsonPathEqualsItem, WhereOnItem, WhereOnJoinItem, WhereQueryBuilder, WhereResult, WindowArg, WindowArgDeclaration, WindowDeclaration, WindowFunctionOptions, WindowItem, With, WithDataBase, WithDataItem, WithItem, WithOptions, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addQueryHook, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, anyShape, checkIfASimpleQuery, cloneQueryArrays, columnCheckToCode, columnCode, columnForeignKeysToCode, columnIndexesToCode, columnTypes, utils as columnUtils, columnsByType, columnsShapeToCode, constraintPropsToCode, constraintToCode, createDb, foreignKeyArgumentToCode, getClonedQueryData, getColumnTypes, getConstraintKind, getQueryAs, getRaw, getShapeFromSelect, getTableData, handleResult, identityToCode, indexToCode, instantiateColumn, isQueryReturnsAll, isRequiredRelationKey, jsonTypes, logColors, logParamToLogObject, makeRegexToFindInSql, makeSql, newTableData, parseRecord, parseResult, primaryKeyToCode, processSelectArg, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, quoteString, referencesArgsToCode, relationQueryKey, resetTableData, setQueryObjectValue, simplifyColumnDefault, testTransaction, toSql, toSqlCacheKey };
|
package/dist/index.js
CHANGED
|
@@ -174,42 +174,46 @@ const getJoinedColumnName = (data, shape, table, key, isOwnColumn) => {
|
|
|
174
174
|
return (_c = (isOwnColumn ? shape[key] : void 0) || ((_b = (_a = data.joinedShapes) == null ? void 0 : _a[table]) == null ? void 0 : _b[key])) == null ? void 0 : _c.data.name;
|
|
175
175
|
};
|
|
176
176
|
const revealColumnToSql = (data, shape, column, quotedAs, select) => {
|
|
177
|
-
var _a, _b;
|
|
177
|
+
var _a, _b, _c;
|
|
178
178
|
const index = column.indexOf(".");
|
|
179
179
|
if (index !== -1) {
|
|
180
180
|
const table = column.slice(0, index);
|
|
181
181
|
const key = column.slice(index + 1);
|
|
182
|
-
const
|
|
183
|
-
return
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
182
|
+
const tableName = ((_a = data.joinOverrides) == null ? void 0 : _a[table]) || table;
|
|
183
|
+
return `"${tableName}"."${getJoinedColumnName(
|
|
184
|
+
data,
|
|
185
|
+
shape,
|
|
186
|
+
tableName,
|
|
187
|
+
key,
|
|
188
|
+
`"${table}"` === quotedAs
|
|
189
|
+
) || key}"`;
|
|
190
|
+
} else if ((_b = data.joinedShapes) == null ? void 0 : _b[column]) {
|
|
187
191
|
return select ? `row_to_json("${column}".*)` : `"${column}".r`;
|
|
188
192
|
} else if (quotedAs && shape[column]) {
|
|
189
193
|
return `${quotedAs}.${q(shape[column].data.name || column)}`;
|
|
190
194
|
} else {
|
|
191
|
-
return q(((
|
|
195
|
+
return q(((_c = shape[column]) == null ? void 0 : _c.data.name) || column);
|
|
192
196
|
}
|
|
193
197
|
};
|
|
194
198
|
const revealColumnToSqlWithAs = (data, column, quotedAs, select) => {
|
|
195
|
-
var _a, _b;
|
|
199
|
+
var _a, _b, _c;
|
|
196
200
|
const index = column.indexOf(".");
|
|
197
201
|
if (index !== -1) {
|
|
198
202
|
const table = column.slice(0, index);
|
|
199
203
|
const key = column.slice(index + 1);
|
|
200
|
-
const
|
|
204
|
+
const tableName = ((_a = data.joinOverrides) == null ? void 0 : _a[table]) || table;
|
|
201
205
|
const name = getJoinedColumnName(
|
|
202
206
|
data,
|
|
203
207
|
data.shape,
|
|
204
208
|
table,
|
|
205
209
|
key,
|
|
206
|
-
|
|
210
|
+
`"${table}"` === quotedAs
|
|
207
211
|
);
|
|
208
|
-
return
|
|
209
|
-
} else if ((
|
|
212
|
+
return `"${tableName}"."${name || key}"${name && name !== key ? ` AS "${key}"` : ""}`;
|
|
213
|
+
} else if ((_b = data.joinedShapes) == null ? void 0 : _b[column]) {
|
|
210
214
|
return select ? `row_to_json("${column}".*) "${column}"` : `"${column}".r "${column}"`;
|
|
211
215
|
} else {
|
|
212
|
-
const name = (
|
|
216
|
+
const name = (_c = data.shape[column]) == null ? void 0 : _c.data.name;
|
|
213
217
|
return `${quotedAs ? `${quotedAs}.` : ""}${q(name || column)}${name && name !== column ? ` AS ${q(column)}` : ""}`;
|
|
214
218
|
}
|
|
215
219
|
};
|
|
@@ -1899,12 +1903,14 @@ const getObjectOrRawConditions = (query, data, values, quotedAs, joinAs, joinSha
|
|
|
1899
1903
|
};
|
|
1900
1904
|
const pushJoinSql = (ctx, table, query, quotedAs) => {
|
|
1901
1905
|
query.join.forEach((item) => {
|
|
1906
|
+
var _a;
|
|
1902
1907
|
if (Array.isArray(item)) {
|
|
1903
1908
|
const q2 = item[1];
|
|
1904
1909
|
const { aliasValue } = ctx;
|
|
1905
1910
|
ctx.aliasValue = true;
|
|
1911
|
+
const as = item[2];
|
|
1906
1912
|
ctx.sql.push(
|
|
1907
|
-
`${item[0]} LATERAL (${q2.toSql(ctx).text}) "${
|
|
1913
|
+
`${item[0]} LATERAL (${q2.toSql(ctx).text}) "${((_a = query.joinOverrides) == null ? void 0 : _a[as]) || as}" ON true`
|
|
1908
1914
|
);
|
|
1909
1915
|
ctx.aliasValue = aliasValue;
|
|
1910
1916
|
} else {
|
|
@@ -3658,11 +3664,22 @@ class Adapter {
|
|
|
3658
3664
|
}
|
|
3659
3665
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3660
3666
|
query(query, types2) {
|
|
3661
|
-
return performQuery(
|
|
3667
|
+
return performQuery(
|
|
3668
|
+
this.pool,
|
|
3669
|
+
query,
|
|
3670
|
+
types2,
|
|
3671
|
+
this.schema
|
|
3672
|
+
);
|
|
3662
3673
|
}
|
|
3663
3674
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3664
3675
|
arrays(query, types2) {
|
|
3665
|
-
return performQuery(
|
|
3676
|
+
return performQuery(
|
|
3677
|
+
this.pool,
|
|
3678
|
+
query,
|
|
3679
|
+
types2,
|
|
3680
|
+
this.schema,
|
|
3681
|
+
"array"
|
|
3682
|
+
);
|
|
3666
3683
|
}
|
|
3667
3684
|
async transaction(begin, cb) {
|
|
3668
3685
|
const client = await this.pool.connect();
|
|
@@ -4400,7 +4417,11 @@ const _joinLateral = (q, type, arg, cb, as) => {
|
|
|
4400
4417
|
setQueryObjectValue(q, "joinedShapes", joinKey, shape);
|
|
4401
4418
|
setQueryObjectValue(q, "joinedParsers", joinKey, result.query.parsers);
|
|
4402
4419
|
}
|
|
4403
|
-
return pushQueryValue(q, "join", [
|
|
4420
|
+
return pushQueryValue(q, "join", [
|
|
4421
|
+
type,
|
|
4422
|
+
result,
|
|
4423
|
+
as || getQueryAs(result)
|
|
4424
|
+
]);
|
|
4404
4425
|
};
|
|
4405
4426
|
|
|
4406
4427
|
const addParserForRawExpression = (q, key, raw2) => {
|
|
@@ -4470,7 +4491,7 @@ const addParserForSelectItem = (q, as, key, arg) => {
|
|
|
4470
4491
|
}
|
|
4471
4492
|
};
|
|
4472
4493
|
const processSelectArg = (q, as, arg, columnAs) => {
|
|
4473
|
-
var _a;
|
|
4494
|
+
var _a, _b, _c, _d;
|
|
4474
4495
|
if (typeof arg === "string") {
|
|
4475
4496
|
if ((_a = q.query.joinedShapes) == null ? void 0 : _a[arg]) {
|
|
4476
4497
|
addParsersForSelectJoined(q, arg);
|
|
@@ -4489,7 +4510,6 @@ const processSelectArg = (q, as, arg, columnAs) => {
|
|
|
4489
4510
|
q.isSubQuery = isSubQuery;
|
|
4490
4511
|
if (!orchidCore.isRaw(value) && value.joinQuery) {
|
|
4491
4512
|
value = value.joinQuery(q, value);
|
|
4492
|
-
value.query.joinedForSelect = key;
|
|
4493
4513
|
let query;
|
|
4494
4514
|
const returnType = value.query.returnType;
|
|
4495
4515
|
if (!returnType || returnType === "all") {
|
|
@@ -4508,6 +4528,17 @@ const processSelectArg = (q, as, arg, columnAs) => {
|
|
|
4508
4528
|
}
|
|
4509
4529
|
query = value;
|
|
4510
4530
|
}
|
|
4531
|
+
let asOverride = key;
|
|
4532
|
+
let suffix = "";
|
|
4533
|
+
if ((_b = value.query.joinedShapes) == null ? void 0 : _b[key]) {
|
|
4534
|
+
suffix = 2;
|
|
4535
|
+
const joinOverrides = (_d = (_c = q.query).joinOverrides) != null ? _d : _c.joinOverrides = {};
|
|
4536
|
+
while (joinOverrides[asOverride = `${key}${suffix}`]) {
|
|
4537
|
+
suffix++;
|
|
4538
|
+
}
|
|
4539
|
+
joinOverrides[key] = asOverride;
|
|
4540
|
+
}
|
|
4541
|
+
value.query.joinedForSelect = asOverride;
|
|
4511
4542
|
_joinLateral(
|
|
4512
4543
|
q,
|
|
4513
4544
|
value.query.innerJoinLateral ? "JOIN" : "LEFT JOIN",
|
|
@@ -6582,6 +6613,46 @@ class QueryMethods {
|
|
|
6582
6613
|
}
|
|
6583
6614
|
return this._exec();
|
|
6584
6615
|
}
|
|
6616
|
+
/**
|
|
6617
|
+
* Use `makeHelper` to make a query helper - a function where you can modify the query, and reuse this function across different places.
|
|
6618
|
+
*
|
|
6619
|
+
* ```ts
|
|
6620
|
+
* const defaultAuthorSelect = db.author.makeHelper((q) => {
|
|
6621
|
+
* return q.select('firstName', 'lastName');
|
|
6622
|
+
* });
|
|
6623
|
+
*
|
|
6624
|
+
* // this will select id, firstName, lastName with a correct TS type
|
|
6625
|
+
* // and return a single record
|
|
6626
|
+
* const result = await defaultAuthorSelect(db.author.select('id').find(1));
|
|
6627
|
+
* ```
|
|
6628
|
+
*
|
|
6629
|
+
* Such helper is available for relation queries inside `select`:
|
|
6630
|
+
*
|
|
6631
|
+
* ```ts
|
|
6632
|
+
* await db.book.select({
|
|
6633
|
+
* author: (book) => defaultAuthorSelect(book.author),
|
|
6634
|
+
* });
|
|
6635
|
+
* ```
|
|
6636
|
+
*
|
|
6637
|
+
* Helper can accept additional arguments:
|
|
6638
|
+
*
|
|
6639
|
+
* ```ts
|
|
6640
|
+
* const selectFollowing = db.user.makeHelper((q, currentUser: { id: number }) => {
|
|
6641
|
+
* return q.select({
|
|
6642
|
+
* following: (q) =>
|
|
6643
|
+
* q.followers.where({ followerId: currentUser.id }).exists(),
|
|
6644
|
+
* });
|
|
6645
|
+
* });
|
|
6646
|
+
*
|
|
6647
|
+
* // select some columns and the `following` boolean field from users
|
|
6648
|
+
* await selectFollowing(db.user.select('id', 'name'), currentUser);
|
|
6649
|
+
* ```
|
|
6650
|
+
*
|
|
6651
|
+
* @param fn - helper function
|
|
6652
|
+
*/
|
|
6653
|
+
makeHelper(fn) {
|
|
6654
|
+
return fn;
|
|
6655
|
+
}
|
|
6585
6656
|
}
|
|
6586
6657
|
orchidCore.applyMixins(QueryMethods, [
|
|
6587
6658
|
QueryBase,
|