pqb 0.72.2 → 0.73.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 +14 -6
- package/dist/index.js +25 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +25 -9
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.ts +13 -6
- package/dist/internal.js +28 -7
- package/dist/internal.js.map +1 -1
- package/dist/internal.mjs +24 -9
- package/dist/internal.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -158,8 +158,10 @@ interface EnsureCount {
|
|
|
158
158
|
}
|
|
159
159
|
type EnsureCountItem = {
|
|
160
160
|
count: number;
|
|
161
|
+
message?: string;
|
|
161
162
|
} | {
|
|
162
163
|
jsonNotNull: string;
|
|
164
|
+
message?: string;
|
|
163
165
|
};
|
|
164
166
|
interface CteTableHooks {
|
|
165
167
|
[K: string]: CteTableHook;
|
|
@@ -1769,9 +1771,8 @@ declare class UUIDColumn<Schema extends ColumnSchemaConfig> extends Column {
|
|
|
1769
1771
|
T & {
|
|
1770
1772
|
data: {
|
|
1771
1773
|
primaryKey: Name;
|
|
1772
|
-
default: true;
|
|
1773
1774
|
};
|
|
1774
|
-
};
|
|
1775
|
+
} & Column.Data.Default;
|
|
1775
1776
|
toCode(ctx: ColumnToCodeCtx, key: string): Code;
|
|
1776
1777
|
}
|
|
1777
1778
|
declare class XMLColumn<Schema extends ColumnSchemaConfig> extends Column {
|
|
@@ -1948,6 +1949,9 @@ type SimpleJoinItemNonSubQueryArgs = [{
|
|
|
1948
1949
|
[K: string]: string | Expression;
|
|
1949
1950
|
} | Expression | true] | [leftColumn: string | Expression, rightColumn: string | Expression] | [leftColumn: string | Expression, op: string, rightColumn: string | Expression];
|
|
1950
1951
|
type JoinItemArgs = {
|
|
1952
|
+
u?: true;
|
|
1953
|
+
x: RawSql;
|
|
1954
|
+
} | {
|
|
1951
1955
|
u?: true;
|
|
1952
1956
|
c?: Column.QueryColumns;
|
|
1953
1957
|
l: SubQueryForSql;
|
|
@@ -3861,7 +3865,7 @@ type WhereArg<T extends PickQuerySelectableRelations> = { [K in keyof T['__selec
|
|
|
3861
3865
|
* db.table.where((q) => q.relation.count().equals(10))
|
|
3862
3866
|
* ```
|
|
3863
3867
|
*/
|
|
3864
|
-
type WhereQueryBuilder<T extends PickQueryRelations> = EmptyObject extends T['relations'] ? { [K in keyof T]: K extends keyof Where | keyof QueryExpressions | 'table' | 'get' | 'columnTypes' | '__selectable' | 'relations' | 'useHelper' | 'modify' | 'result' | 'returnType' | 'withData' | 'windows' | 'then' ? T[K] : never; } : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? T['relations'][K]['query'] : K extends keyof T & (keyof Where | keyof QueryExpressions | 'table' | 'get' | 'columnTypes' | '__selectable' | 'relations' | 'useHelper' | 'modify' | 'result' | 'returnType' | 'withData' | 'windows' | 'then') ? T[K] : never; };
|
|
3868
|
+
type WhereQueryBuilder<T extends PickQueryRelations> = EmptyObject extends T['relations'] ? { [K in keyof T]: K extends keyof Where | keyof QueryExpressions | 'table' | 'get' | 'columnTypes' | '__selectable' | 'relations' | 'useHelper' | 'modify' | 'result' | 'returnType' | 'withData' | 'windows' | 'then' | 'none' ? T[K] : never; } : { [K in keyof T['relations'] | keyof T]: K extends keyof T['relations'] ? T['relations'][K]['query'] : K extends keyof T & (keyof Where | keyof QueryExpressions | 'table' | 'get' | 'columnTypes' | '__selectable' | 'relations' | 'useHelper' | 'modify' | 'result' | 'returnType' | 'withData' | 'windows' | 'then' | 'none') ? T[K] : never; };
|
|
3865
3869
|
type WhereArgs<T extends PickQuerySelectableRelations> = WhereArg<T>[];
|
|
3866
3870
|
type WhereNotArgs<T extends PickQuerySelectableRelations> = [WhereArg<T>];
|
|
3867
3871
|
type WhereInColumn<T extends PickQuerySelectableRelations> = keyof T['__selectable'] | [keyof T['__selectable'], ...(keyof T['__selectable'])[]];
|
|
@@ -7794,6 +7798,7 @@ type CreateManyFromResult<T extends CreateSelf> = T extends {
|
|
|
7794
7798
|
} ? T : T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAll<T> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetValueQueryReturnsPluckColumn<T> : T;
|
|
7795
7799
|
type InsertManyFromResult<T extends CreateSelf> = T['__hasSelect'] extends true ? T['returnType'] extends 'one' | 'oneOrThrow' ? SetQueryReturnsAll<T> : T['returnType'] extends 'value' | 'valueOrThrow' ? SetValueQueryReturnsPluckColumn<T> : T : SetQueryReturnsRowCountMany<T>;
|
|
7796
7800
|
declare const _queryCreateManyFrom: <T extends CreateSelf, Q extends QueryReturningOne>(q: T, query: Q, data: Omit<CreateData<T>, keyof Q['result']>[]) => CreateManyFromResult<T>;
|
|
7801
|
+
declare const _queryInsertForEachFrom: <T extends CreateSelf>(q: T, query: IsQuery) => InsertManyFromResult<T>;
|
|
7797
7802
|
declare class QueryCreateFrom {
|
|
7798
7803
|
/**
|
|
7799
7804
|
* Inserts a single record based on a query that selects a single record.
|
|
@@ -9004,7 +9009,10 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
|
|
|
9004
9009
|
wrapInTransaction?: boolean;
|
|
9005
9010
|
throwOnNotFound?: boolean;
|
|
9006
9011
|
cteThrowOnNotFound?: boolean;
|
|
9007
|
-
ensureCount?:
|
|
9012
|
+
ensureCount?: {
|
|
9013
|
+
expected: number;
|
|
9014
|
+
message?: string;
|
|
9015
|
+
};
|
|
9008
9016
|
with?: WithItems;
|
|
9009
9017
|
withShapes?: WithConfigs;
|
|
9010
9018
|
joinTo?: QueryDataJoinTo;
|
|
@@ -11004,7 +11012,7 @@ declare abstract class QueryAsMethods {
|
|
|
11004
11012
|
*/
|
|
11005
11013
|
as<T extends AsQueryArg, As extends string>(this: T, as: As): SetQueryTableAlias<T, As>;
|
|
11006
11014
|
}
|
|
11007
|
-
declare const _appendQuery: (main: Query, append: Query, asFn: (as: string) => void) => Query;
|
|
11015
|
+
declare const _appendQuery: (main: Query, append: Query, asFn: (as: string) => void, appendAsFn?: (as: string) => void) => Query;
|
|
11008
11016
|
declare const _appendQueryOnUpsertCreate: (main: Query, append: Query, asFn: (as: string) => void) => Query;
|
|
11009
11017
|
declare const _onUpsertUpdate: (q: Query, asFn: (as: string) => void) => Query;
|
|
11010
11018
|
declare const _prependWithOnUpsertCreate: (q: Query, name: string | ((as: string) => void), query: Query) => void;
|
|
@@ -11177,4 +11185,4 @@ declare const testTransaction: {
|
|
|
11177
11185
|
*/
|
|
11178
11186
|
close(arg: Arg$1): Promise<void>;
|
|
11179
11187
|
};
|
|
11180
|
-
export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, type BrandColumn, type BrandColumnsShape, type Branded, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnRefExpression, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, type DateColumnInput, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type ExpressionData, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsDate, type OperatorsJson, type OperatorsNumber, type OperatorsOrdinalText, type OperatorsText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RefreshMaterializedViewOptions, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectSqlColumn, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StaticSQLArgs, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type ToSQLCtx, type ToSqlValues, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _onUpsertUpdate, _orCreate, _prependWith, _prependWithOnUpsertCreate, _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, constraintToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, indexToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
|
|
11188
|
+
export { type Adapter, AdapterClass, type AdapterConfigBase, type AdapterParams, type AdapterSchemaConfigOptions, type AfterCommitStandaloneHook, type AfterHook, ArrayColumn, type ArrayColumnValue, type ArrayData, type AsyncState, type BaseNumberData, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, type BrandColumn, type BrandColumnsShape, type Branded, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, type ColumnRefExpression, type ColumnSchemaConfig, type ColumnSchemaGetterColumns, type ColumnSchemaGetterTableClass, type ColumnToCodeCtx, type ColumnTypeSchemaArg, type ColumnsByType, type ColumnsShape, type ComputedColumnsFromOptions, type ComputedOptionsConfig, type ComputedOptionsFactory, type CreateCtx, type CreateData, type CreateManyMethodsNames, type CreateMethodsNames, type CreateSelf, CustomTypeColumn, DateBaseColumn, DateColumn, type DateColumnData, type DateColumnInput, DateTimeBaseClass, DateTimeTzBaseClass, Db, type DbDomainArg, type DbExtension, type DbOptions, type DbResult, type DbSharedOptions, type DbSqlMethod, type DbStructureDomainsMap, type DbTableOptionScopes, type DbTableOptions, DecimalColumn, type DecimalColumnData, type DefaultColumnTypes, type DefaultPrivileges, type DefaultSchemaConfig, type DeleteMethodsNames, DomainColumn, DoublePrecisionColumn, type DriverAdapter, DynamicRawSQL, type EmptyObject, type EmptyTuple, EnumColumn, Expression, type ExpressionData, type FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinedShapes, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, type MapTableScopesOption, type MaybeArray, type MaybePromise, type MergeQuery, MoneyColumn, type NoPrimaryKeyOption, type NonUniqDataItem, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, type NumberColumnData, Operators, type OperatorsArray, type OperatorsDate, type OperatorsJson, type OperatorsNumber, type OperatorsOrdinalText, type OperatorsText, OrchidOrmInternalError, type Ord, PathColumn, type PickQueryInputType, type PickQueryInternal, type PickQueryQ, type PickQueryRelations, type PickQuerySelectableRelations, type PickQueryShape, PointColumn, PolygonColumn, PostgisGeographyPointColumn, type Query, type QueryAfterHook, type QueryBeforeActionHook, type QueryBeforeHook, type QueryData, QueryError, type QueryHasWhere, type QueryHelperResult, QueryHookUtils, QueryHooks, type QueryInternal, type QueryLogObject, type QueryLogOptions, type QueryLogger, type QueryManyTake, type QueryManyTakeOptional, type QueryOrExpression, type QueryResult, type QueryResultRow, type QueryReturnType, type QuerySchema, type QueryScopes, RawSql, type RawSqlBase, RealColumn, type RecordKeyTrue, type RecordOptionalString, type RecordString, type RecordStringOrNumber, type RecordUnknown, type RefreshMaterializedViewOptions, type RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectSqlColumn, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, type StaticSQLArgs, type StorageOptions, StringColumn, type StringData, type TableData, type TableDataFn, type TableDataInput, type TableDataItem, type TableDataItemsUniqueColumnTuples, type TableDataItemsUniqueColumns, type TableDataItemsUniqueConstraints, type TableDataMethods, type TemplateLiteralArgs, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, type Timestamps, type ToSQLCtx, type ToSqlValues, type TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _onUpsertUpdate, _orCreate, _prependWith, _prependWithOnUpsertCreate, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertForEachFrom, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, constraintToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, indexToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
|
package/dist/index.js
CHANGED
|
@@ -4949,8 +4949,12 @@ const then = async (q, adapter, state, beforeHooks, afterHooks, afterSaveHooks,
|
|
|
4949
4949
|
} catch (err) {
|
|
4950
4950
|
let error;
|
|
4951
4951
|
if (err instanceof adapter.errorClass) {
|
|
4952
|
-
|
|
4953
|
-
|
|
4952
|
+
const code = getDriverErrorCode(err);
|
|
4953
|
+
const notFound = err.message.match(/"(.*):not-found:(\d+):(\d+)"$/);
|
|
4954
|
+
if (code === "22P02" && notFound) {
|
|
4955
|
+
const [, message, expected, actual] = notFound;
|
|
4956
|
+
error = Number(expected) === 1 && !message ? new NotFoundError(q) : new NotFoundError(q, `Expected to find at least ${expected} record(s)${message ? ` ${message}` : ""}, but found ${actual}`);
|
|
4957
|
+
} else {
|
|
4954
4958
|
error = new q.error();
|
|
4955
4959
|
adapter.assignError(error, err);
|
|
4956
4960
|
}
|
|
@@ -6654,7 +6658,8 @@ const processJoinItem = (ctx, table, query, args, quotedAs) => {
|
|
|
6654
6658
|
if (alias) target += ` ${alias}`;
|
|
6655
6659
|
if (r && s) target = subJoinToSql(ctx, j, `"${joinTable}"`, !forbidLateral, joinAs, true);
|
|
6656
6660
|
else on = whereToSql(ctx, j, j.q, joinAs);
|
|
6657
|
-
} else if ("
|
|
6661
|
+
} else if ("x" in args) target = args.x.makeSQL(ctx, quotedAs);
|
|
6662
|
+
else if ("w" in args) {
|
|
6658
6663
|
const { w } = args;
|
|
6659
6664
|
target = `"${w}"`;
|
|
6660
6665
|
if ("r" in args) {
|
|
@@ -6931,7 +6936,10 @@ const moveMutativeQueryToCteBase = (toSql, ctx, query, type = query.q.type) => {
|
|
|
6931
6936
|
const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
|
|
6932
6937
|
if (data.ensureCount !== void 0 && ctx.cteName) {
|
|
6933
6938
|
const cteHooks = setCteHooks(ctx, true);
|
|
6934
|
-
(cteHooks.ensureCount ??= {})[ctx.cteName] = {
|
|
6939
|
+
(cteHooks.ensureCount ??= {})[ctx.cteName] = {
|
|
6940
|
+
count: data.ensureCount.expected,
|
|
6941
|
+
message: data.ensureCount.message
|
|
6942
|
+
};
|
|
6935
6943
|
}
|
|
6936
6944
|
const afterCreate = data.afterCreate;
|
|
6937
6945
|
const afterUpdate = data.afterUpdate;
|
|
@@ -7096,8 +7104,10 @@ const selectToSqlList = (ctx, table, query, quotedAs, hookSelect = query.hookSel
|
|
|
7096
7104
|
list.push(`${sql} "${as}"`);
|
|
7097
7105
|
if (jsonList) jsonList[as] = value.result.value;
|
|
7098
7106
|
aliases?.push(as);
|
|
7099
|
-
} else if (delayedRelationSelect && isRelationQuery(value))
|
|
7100
|
-
|
|
7107
|
+
} else if (delayedRelationSelect && isRelationQuery(value)) {
|
|
7108
|
+
if (delayedRelationSelect.query.q.type !== "delete") ctx.selectedCount--;
|
|
7109
|
+
setMutativeQueriesSelectRelationsSqlState(delayedRelationSelect, as, value);
|
|
7110
|
+
} else {
|
|
7101
7111
|
pushSubQuerySql(ctx, query, value, as, list, quotedAs, aliases);
|
|
7102
7112
|
if (jsonList) jsonList[as] = value.q.returnType === "value" || value.q.returnType === "valueOrThrow" ? value.q.expr?.result.value || value.result?.value : void 0;
|
|
7103
7113
|
}
|
|
@@ -9700,7 +9710,12 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
|
|
|
9700
9710
|
if (ctx.topCtx.cteHooks.hasSelect) {
|
|
9701
9711
|
if (prependedSelectParenthesis) result.text += ")";
|
|
9702
9712
|
const { tableHooks, ensureCount } = ctx.topCtx.cteHooks;
|
|
9703
|
-
const keyValues = [...tableHooks ? Object.entries(tableHooks).map(([cteName, data]) => `'${cteName}', (SELECT json_agg(${makeRowToJson(ctx, cteName, data.shape, false, true)}) FROM "${cteName}")`) : emptyArray, ...ensureCount ? Object.entries(ensureCount).map(([cteName, item]) =>
|
|
9713
|
+
const keyValues = [...tableHooks ? Object.entries(tableHooks).map(([cteName, data]) => `'${cteName}', (SELECT json_agg(${makeRowToJson(ctx, cteName, data.shape, false, true)}) FROM "${cteName}")`) : emptyArray, ...ensureCount ? Object.entries(ensureCount).map(([cteName, item]) => {
|
|
9714
|
+
const expected = "count" in item ? item.count : 1;
|
|
9715
|
+
const message = (item.message || "").replace(/'/g, "''");
|
|
9716
|
+
const notFound = "count" in item && item.count > 1 ? `(SELECT '${message}:not-found:${expected}:' || (SELECT count(*) FROM "${cteName}"))::int` : `(SELECT '${message}:not-found:${expected}:0')::int`;
|
|
9717
|
+
return `'#${cteName}', CASE WHEN ${"count" in item ? `(SELECT count(*) FROM "${cteName}") < ${item.count}` : `(SELECT "${cteName}"."${item.jsonNotNull}" FROM "${cteName}") IS NULL`} THEN ${notFound} END`;
|
|
9718
|
+
}) : emptyArray];
|
|
9704
9719
|
result.text += ` UNION ALL SELECT ${"NULL, ".repeat(ctx.selectedCount || 0)}json_build_object(${keyValues.join(", ")})`;
|
|
9705
9720
|
}
|
|
9706
9721
|
}
|
|
@@ -12492,7 +12507,8 @@ var QueryExpressions = class {
|
|
|
12492
12507
|
return new OrExpression(args);
|
|
12493
12508
|
}
|
|
12494
12509
|
};
|
|
12495
|
-
const _appendQuery = (main, append, asFn) => {
|
|
12510
|
+
const _appendQuery = (main, append, asFn, appendAsFn) => {
|
|
12511
|
+
if (appendAsFn) append = pushQueryValueImmutable(append, "asFns", appendAsFn);
|
|
12496
12512
|
return pushQueryValueImmutable(pushQueryValueImmutable(main, "appendQueries", prepareSubQueryForSql(main, append)), "asFns", asFn);
|
|
12497
12513
|
};
|
|
12498
12514
|
const _appendQueryOnUpsertCreate = (main, append, asFn) => {
|
|
@@ -14676,6 +14692,7 @@ exports._queryFindByOptional = _queryFindByOptional;
|
|
|
14676
14692
|
exports._queryHookAfterCreate = _queryHookAfterCreate;
|
|
14677
14693
|
exports._queryHookAfterUpdate = _queryHookAfterUpdate;
|
|
14678
14694
|
exports._queryInsert = _queryInsert;
|
|
14695
|
+
exports._queryInsertForEachFrom = _queryInsertForEachFrom;
|
|
14679
14696
|
exports._queryInsertMany = _queryInsertMany;
|
|
14680
14697
|
exports._queryJoinOn = _queryJoinOn;
|
|
14681
14698
|
exports._queryRows = _queryRows;
|