pqb 0.67.2 → 0.67.3

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
@@ -8713,6 +8713,8 @@ interface QueryData extends QueryDataAliases, PickQueryDataParsers, HasHookSelec
8713
8713
  /** upsert **/
8714
8714
  upsertUpdate?: boolean;
8715
8715
  upsertSecond?: boolean;
8716
+ upsertCreateAppendQueries?: SubQueryForSql[];
8717
+ upsertCreateAsFns?: AsFn[];
8716
8718
  upsertInsert?(): unknown;
8717
8719
  /** insert **/
8718
8720
  columns: string[];
@@ -10539,6 +10541,7 @@ declare abstract class QueryAsMethods {
10539
10541
  as<T extends AsQueryArg, As extends string>(this: T, as: As): SetQueryTableAlias<T, As>;
10540
10542
  }
10541
10543
  declare const _appendQuery: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10544
+ declare const _appendQueryOnUpsertCreate: (main: Query, append: Query, asFn: (as: string) => void) => Query;
10542
10545
  declare const getPrimaryKeys: (q: Query) => string[];
10543
10546
  /**
10544
10547
  * Set value into the object in query data, create the object if it doesn't yet exist.
@@ -10694,4 +10697,4 @@ declare const testTransaction: {
10694
10697
  */
10695
10698
  close(arg: Arg$1): Promise<void>;
10696
10699
  };
10697
- 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, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, 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, 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 FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinQueryMethod, 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 OperatorsJson, type OperatorsOrdinalText, 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 RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeColumnPrimaryKeys, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, 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 TransactionAdapter, TransactionAdapterClass, type TransactionOptions, TsQueryColumn, TsVectorColumn, UUIDColumn, type UniqueConstraints, type UniqueTableDataItem, UnknownColumn, type UpdateData, type UpsertData, type UpsertThis, VarCharColumn, VirtualColumn, type WhereArg, 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, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
10700
+ 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, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, type Code, type Codes, Column, type ColumnFromDbParams, 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, 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 FromArg, type FromResult, type GeneratorIgnore, type Grant, type HookSelectValue, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, type IsQuery, type IsolationLevel, JSONColumn, JSONTextColumn, type JoinQueryMethod, 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 OperatorsJson, type OperatorsOrdinalText, 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 RelationConfigBase, type RelationJoinQuery, type RelationsBase, type Rls, type RlsPolicy, type SchemaConfigFnWithOptions, type SearchWeight, type SelectableFromShape, SerialColumn, type SerialColumnData, type ShallowSimplify, type ShapeColumnPrimaryKeys, type ShapeUniqueColumns, type SingleSql, type SingleSqlItem, SmallIntColumn, SmallSerialColumn, type Sql, type SqlFn, type SqlSessionState, 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 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, _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, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, referencesArgsToCode, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
package/dist/index.js CHANGED
@@ -4563,7 +4563,11 @@ const loadRelations = async (state, result, savepointState, renames) => {
4563
4563
  const q = state.query;
4564
4564
  const primaryKeys = requirePrimaryKeys(q, "Cannot select a relation of a table that has no primary keys");
4565
4565
  const selectQuery = _unscope(q, "nonDeleted");
4566
- selectQuery.q.type = selectQuery.q.returnType = void 0;
4566
+ selectQuery.q.type = void 0;
4567
+ selectQuery.q.returnType = void 0;
4568
+ selectQuery.q.with = void 0;
4569
+ selectQuery.q.appendQueries = void 0;
4570
+ selectQuery.q.valuesJoinedAs = void 0;
4567
4571
  const matchSourceTableIds = {};
4568
4572
  for (const pkey of primaryKeys) matchSourceTableIds[pkey] = { in: result.map((row) => row[pkey]) };
4569
4573
  (selectQuery.q.and ??= []).push(matchSourceTableIds);
@@ -6961,22 +6965,33 @@ const setMutativeQueriesSelectRelationsSqlState = (d, as, rel) => {
6961
6965
  const handleInsertAndUpdateSelectRelationsSqlState = (ctx, state) => {
6962
6966
  if (state) ctx.topCtx.mutativeQueriesSelectRelationsSqlState = state;
6963
6967
  };
6968
+ const unsetValuesJoinedAsForMutativeSelectRelations = (query) => {
6969
+ if (!query.q.selectRelation || !query.q.valuesJoinedAs) return;
6970
+ const { valuesJoinedAs } = query.q;
6971
+ query.q.valuesJoinedAs = void 0;
6972
+ return valuesJoinedAs;
6973
+ };
6974
+ const restoreValuesJoinedAsForMutativeSelectRelations = (query, valuesJoinedAs) => {
6975
+ if (valuesJoinedAs) query.q.valuesJoinedAs = valuesJoinedAs;
6976
+ };
6964
6977
  const handleDeleteSelectRelationsSqlState = (ctx, query, relationSelectState) => {
6965
6978
  const selectRelations = relationSelectState?.value;
6966
6979
  if (!selectRelations) return;
6967
6980
  const selectPrimaryKeysQuery = prepareSubQueryForSql(query, _clone(query));
6981
+ selectPrimaryKeysQuery.q.valuesJoinedAs = void 0;
6968
6982
  const primaryKeys = requirePrimaryKeys(query, "primary keys are required for selecting relation in delete");
6969
6983
  _addToHookSelect(selectPrimaryKeysQuery, primaryKeys, true);
6970
6984
  const { as: cteAs } = moveQueryToCte(ctx, selectPrimaryKeysQuery, void 0, true);
6971
6985
  const relKeys = Object.keys(selectRelations);
6972
6986
  const hookSelect = selectPrimaryKeysQuery.q.hookSelect;
6987
+ const queryAs = getQueryAs(query);
6973
6988
  const join = {
6974
6989
  type: "JOIN",
6975
6990
  args: {
6976
6991
  w: cteAs,
6977
6992
  a: [Object.fromEntries(primaryKeys.map((key) => {
6978
6993
  const selected = hookSelect.get(key);
6979
- return [cteAs + "." + (selected.as || selected.select), key];
6994
+ return [cteAs + "." + (selected.as || selected.select), `${queryAs}.${key}`];
6980
6995
  }))]
6981
6996
  }
6982
6997
  };
@@ -7711,6 +7726,14 @@ function pushLimitSQL(sql, values, q) {
7711
7726
  }
7712
7727
  }
7713
7728
  const pushUpdateSql = (ctx, query, q, quotedAs, isSubSql) => {
7729
+ const valuesJoinedAs = unsetValuesJoinedAsForMutativeSelectRelations(query);
7730
+ try {
7731
+ return pushUpdateSqlWithoutValuesJoinedAs(ctx, query, q, quotedAs, isSubSql);
7732
+ } finally {
7733
+ restoreValuesJoinedAsForMutativeSelectRelations(query, valuesJoinedAs);
7734
+ }
7735
+ };
7736
+ const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) => {
7714
7737
  const quotedTable = `"${query.table || q.from}"`;
7715
7738
  const from = quoteTableWithSchema(query);
7716
7739
  const set = [];
@@ -9569,6 +9592,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9569
9592
  _queryInsert(upsertOrCreate, query.upsertInsert());
9570
9593
  upsertOrCreate.q.type = "upsert";
9571
9594
  }
9595
+ upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
9596
+ upsertOrCreate.q.asFns = query.upsertCreateAsFns;
9572
9597
  const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
9573
9598
  sql.push(makeFirstSql(isSubSql), "UNION ALL", makeSecondSql(isSubSql));
9574
9599
  } else {
@@ -9724,9 +9749,9 @@ const addTopCteInternal = (place, ctx, item, type, dontAddTableHook) => {
9724
9749
  topCTE.stack.pop();
9725
9750
  };
9726
9751
  const addWithToSql = (ctx, sql, isSubSql) => {
9727
- if (!isSubSql && ctx.topCtx.topCTE) {
9752
+ if (!isSubSql && ctx.topCtx.topCTE?.append.length) {
9728
9753
  const sqls = [];
9729
- if (!isSubSql && ctx.topCtx.topCTE) for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9754
+ for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9730
9755
  sql.text = "WITH " + sqls.join(", ") + " " + sql.text;
9731
9756
  }
9732
9757
  };
@@ -12370,6 +12395,9 @@ var QueryExpressions = class {
12370
12395
  const _appendQuery = (main, append, asFn) => {
12371
12396
  return pushQueryValueImmutable(pushQueryValueImmutable(main, "appendQueries", prepareSubQueryForSql(main, append)), "asFns", asFn);
12372
12397
  };
12398
+ const _appendQueryOnUpsertCreate = (main, append, asFn) => {
12399
+ return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
12400
+ };
12373
12401
  const mergableObjects = new Set([
12374
12402
  "shape",
12375
12403
  "withShapes",
@@ -14401,6 +14429,7 @@ exports.VarCharColumn = VarCharColumn;
14401
14429
  exports.VirtualColumn = VirtualColumn;
14402
14430
  exports.XMLColumn = XMLColumn;
14403
14431
  exports._appendQuery = _appendQuery;
14432
+ exports._appendQueryOnUpsertCreate = _appendQueryOnUpsertCreate;
14404
14433
  exports._clone = _clone;
14405
14434
  exports._createDbSqlMethod = _createDbSqlMethod;
14406
14435
  exports._hookSelectColumns = _hookSelectColumns;