pqb 0.67.1 → 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.mjs CHANGED
@@ -3478,6 +3478,11 @@ var NestedSqlSessionError = class extends OrchidOrmInternalError {
3478
3478
  super(query, "Cannot nest SQL session scopes. Outer scope already has role or setConfig defined.");
3479
3479
  }
3480
3480
  };
3481
+ var CannotMutateReadOnlyTableError = class extends OrchidOrmInternalError {
3482
+ constructor(query) {
3483
+ super(query, "Cannot mutate a readonly table.");
3484
+ }
3485
+ };
3481
3486
  const escape = (value, migration, nested) => {
3482
3487
  const type = typeof value;
3483
3488
  if (type === "number" || type === "bigint") return String(value);
@@ -4535,7 +4540,11 @@ const loadRelations = async (state, result, savepointState, renames) => {
4535
4540
  const q = state.query;
4536
4541
  const primaryKeys = requirePrimaryKeys(q, "Cannot select a relation of a table that has no primary keys");
4537
4542
  const selectQuery = _unscope(q, "nonDeleted");
4538
- selectQuery.q.type = selectQuery.q.returnType = void 0;
4543
+ selectQuery.q.type = void 0;
4544
+ selectQuery.q.returnType = void 0;
4545
+ selectQuery.q.with = void 0;
4546
+ selectQuery.q.appendQueries = void 0;
4547
+ selectQuery.q.valuesJoinedAs = void 0;
4539
4548
  const matchSourceTableIds = {};
4540
4549
  for (const pkey of primaryKeys) matchSourceTableIds[pkey] = { in: result.map((row) => row[pkey]) };
4541
4550
  (selectQuery.q.and ??= []).push(matchSourceTableIds);
@@ -5160,6 +5169,9 @@ const throwIfNoWhere = (q, method) => {
5160
5169
  const throwIfJoinLateral = (q, method) => {
5161
5170
  if (q.q.join?.some((x) => Array.isArray(x) || "s" in x.args && x.args.s)) throw new OrchidOrmInternalError(q, `Cannot join a complex query in ${method}`);
5162
5171
  };
5172
+ const throwIfReadOnly = (query) => {
5173
+ if (query.internal.readOnly) throw new CannotMutateReadOnlyTableError(query);
5174
+ };
5163
5175
  const throwOnReadOnlyUpdate = (query, column, key) => {
5164
5176
  if (column.data.appReadOnly || column.data.readOnly) throw new OrchidOrmInternalError(query, "Trying to update a readonly column", { column: key });
5165
5177
  };
@@ -6930,22 +6942,33 @@ const setMutativeQueriesSelectRelationsSqlState = (d, as, rel) => {
6930
6942
  const handleInsertAndUpdateSelectRelationsSqlState = (ctx, state) => {
6931
6943
  if (state) ctx.topCtx.mutativeQueriesSelectRelationsSqlState = state;
6932
6944
  };
6945
+ const unsetValuesJoinedAsForMutativeSelectRelations = (query) => {
6946
+ if (!query.q.selectRelation || !query.q.valuesJoinedAs) return;
6947
+ const { valuesJoinedAs } = query.q;
6948
+ query.q.valuesJoinedAs = void 0;
6949
+ return valuesJoinedAs;
6950
+ };
6951
+ const restoreValuesJoinedAsForMutativeSelectRelations = (query, valuesJoinedAs) => {
6952
+ if (valuesJoinedAs) query.q.valuesJoinedAs = valuesJoinedAs;
6953
+ };
6933
6954
  const handleDeleteSelectRelationsSqlState = (ctx, query, relationSelectState) => {
6934
6955
  const selectRelations = relationSelectState?.value;
6935
6956
  if (!selectRelations) return;
6936
6957
  const selectPrimaryKeysQuery = prepareSubQueryForSql(query, _clone(query));
6958
+ selectPrimaryKeysQuery.q.valuesJoinedAs = void 0;
6937
6959
  const primaryKeys = requirePrimaryKeys(query, "primary keys are required for selecting relation in delete");
6938
6960
  _addToHookSelect(selectPrimaryKeysQuery, primaryKeys, true);
6939
6961
  const { as: cteAs } = moveQueryToCte(ctx, selectPrimaryKeysQuery, void 0, true);
6940
6962
  const relKeys = Object.keys(selectRelations);
6941
6963
  const hookSelect = selectPrimaryKeysQuery.q.hookSelect;
6964
+ const queryAs = getQueryAs(query);
6942
6965
  const join = {
6943
6966
  type: "JOIN",
6944
6967
  args: {
6945
6968
  w: cteAs,
6946
6969
  a: [Object.fromEntries(primaryKeys.map((key) => {
6947
6970
  const selected = hookSelect.get(key);
6948
- return [cteAs + "." + (selected.as || selected.select), key];
6971
+ return [cteAs + "." + (selected.as || selected.select), `${queryAs}.${key}`];
6949
6972
  }))]
6950
6973
  }
6951
6974
  };
@@ -7680,6 +7703,14 @@ function pushLimitSQL(sql, values, q) {
7680
7703
  }
7681
7704
  }
7682
7705
  const pushUpdateSql = (ctx, query, q, quotedAs, isSubSql) => {
7706
+ const valuesJoinedAs = unsetValuesJoinedAsForMutativeSelectRelations(query);
7707
+ try {
7708
+ return pushUpdateSqlWithoutValuesJoinedAs(ctx, query, q, quotedAs, isSubSql);
7709
+ } finally {
7710
+ restoreValuesJoinedAsForMutativeSelectRelations(query, valuesJoinedAs);
7711
+ }
7712
+ };
7713
+ const pushUpdateSqlWithoutValuesJoinedAs = (ctx, query, q, quotedAs, isSubSql) => {
7683
7714
  const quotedTable = `"${query.table || q.from}"`;
7684
7715
  const from = quoteTableWithSchema(query);
7685
7716
  const set = [];
@@ -8457,6 +8488,7 @@ var AggregateMethods = class {
8457
8488
  * @param data - optionally passed custom data when creating a single record.
8458
8489
  */
8459
8490
  const insertFrom = (query, from, many, queryMany, data) => {
8491
+ throwIfReadOnly(query);
8460
8492
  const ctx = createCtx();
8461
8493
  const obj = data && (Array.isArray(data) ? handleManyData(query, data, ctx) : handleOneData(query, data, ctx));
8462
8494
  return insert(query, {
@@ -8912,17 +8944,21 @@ const insert = (self, { columns, insertFrom, values }, many, queryMany) => {
8912
8944
  return self;
8913
8945
  };
8914
8946
  const _queryCreate = (q, data) => {
8947
+ throwIfReadOnly(q);
8915
8948
  createSelect(q);
8916
8949
  return _queryInsert(q, data);
8917
8950
  };
8918
8951
  const _queryInsert = (query, data) => {
8952
+ throwIfReadOnly(query);
8919
8953
  return insert(query, handleOneData(query, data, createCtx()));
8920
8954
  };
8921
8955
  const _queryCreateMany = (q, data) => {
8956
+ throwIfReadOnly(q);
8922
8957
  createSelect(q);
8923
8958
  return _queryInsertMany(q, data);
8924
8959
  };
8925
8960
  const _queryInsertMany = (q, data) => {
8961
+ throwIfReadOnly(q);
8926
8962
  let result = insert(q, handleManyData(q, data, createCtx()), true);
8927
8963
  if (!data.length) result = result.none();
8928
8964
  return result;
@@ -9533,6 +9569,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
9533
9569
  _queryInsert(upsertOrCreate, query.upsertInsert());
9534
9570
  upsertOrCreate.q.type = "upsert";
9535
9571
  }
9572
+ upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
9573
+ upsertOrCreate.q.asFns = query.upsertCreateAsFns;
9536
9574
  const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
9537
9575
  sql.push(makeFirstSql(isSubSql), "UNION ALL", makeSecondSql(isSubSql));
9538
9576
  } else {
@@ -9688,9 +9726,9 @@ const addTopCteInternal = (place, ctx, item, type, dontAddTableHook) => {
9688
9726
  topCTE.stack.pop();
9689
9727
  };
9690
9728
  const addWithToSql = (ctx, sql, isSubSql) => {
9691
- if (!isSubSql && ctx.topCtx.topCTE) {
9729
+ if (!isSubSql && ctx.topCtx.topCTE?.append.length) {
9692
9730
  const sqls = [];
9693
- if (!isSubSql && ctx.topCtx.topCTE) for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9731
+ for (const append of ctx.topCtx.topCTE.append) sqls.push(...append);
9694
9732
  sql.text = "WITH " + sqls.join(", ") + " " + sql.text;
9695
9733
  }
9696
9734
  };
@@ -11271,6 +11309,7 @@ var QueryGet = class {
11271
11309
  }
11272
11310
  };
11273
11311
  const _queryDelete = (query) => {
11312
+ throwIfReadOnly(query);
11274
11313
  const q = query.q;
11275
11314
  if (!q.select) {
11276
11315
  if (q.returnType === "oneOrThrow" || q.returnType === "valueOrThrow") q.throwOnNotFound = true;
@@ -11454,6 +11493,7 @@ var RefExpression = class extends Expression {
11454
11493
  };
11455
11494
  const _queryUpdateMany = (self, primaryKeys, data, strict) => {
11456
11495
  const query = self;
11496
+ throwIfReadOnly(query);
11457
11497
  const { q } = query;
11458
11498
  const { shape } = q;
11459
11499
  q.type = "update";
@@ -11473,6 +11513,7 @@ const _queryUpdateMany = (self, primaryKeys, data, strict) => {
11473
11513
  return query;
11474
11514
  };
11475
11515
  const _queryChangeCounter = (self, op, data) => {
11516
+ throwIfReadOnly(self);
11476
11517
  const q = self.q;
11477
11518
  q.type = "update";
11478
11519
  if (!q.select) {
@@ -11505,6 +11546,7 @@ const _queryChangeCounter = (self, op, data) => {
11505
11546
  };
11506
11547
  const _queryUpdate = (updateSelf, arg) => {
11507
11548
  const query = updateSelf;
11549
+ throwIfReadOnly(query);
11508
11550
  const { q } = query;
11509
11551
  q.type = "update";
11510
11552
  const set = { ...arg };
@@ -11832,6 +11874,7 @@ var QueryUpdate = class {
11832
11874
  */
11833
11875
  updateFrom(arg, ...args) {
11834
11876
  const q = _clone(this);
11877
+ throwIfReadOnly(q);
11835
11878
  const joinArgs = _joinReturningArgs(q, true, arg, args, true);
11836
11879
  if (!joinArgs) return _queryNone(q);
11837
11880
  joinArgs.u = true;
@@ -12329,6 +12372,9 @@ var QueryExpressions = class {
12329
12372
  const _appendQuery = (main, append, asFn) => {
12330
12373
  return pushQueryValueImmutable(pushQueryValueImmutable(main, "appendQueries", prepareSubQueryForSql(main, append)), "asFns", asFn);
12331
12374
  };
12375
+ const _appendQueryOnUpsertCreate = (main, append, asFn) => {
12376
+ return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
12377
+ };
12332
12378
  const mergableObjects = new Set([
12333
12379
  "shape",
12334
12380
  "withShapes",
@@ -13100,6 +13146,7 @@ var QueryTruncate = class {
13100
13146
  * @param options - truncate options, may have `cascade: true` and `restartIdentity: true`
13101
13147
  */
13102
13148
  truncate(options) {
13149
+ throwIfReadOnly(this);
13103
13150
  const query = Object.create(_clone(this));
13104
13151
  query.toSQL = () => makeTruncateSql(query, options);
13105
13152
  return _queryExec(query);
@@ -13763,6 +13810,7 @@ var Db = class extends QueryMethods {
13763
13810
  snakeCase: options.snakeCase,
13764
13811
  noPrimaryKey: options.noPrimaryKey === "ignore",
13765
13812
  comment: options.comment,
13813
+ readOnly: options.readOnly,
13766
13814
  nowSQL: options.nowSQL,
13767
13815
  tableData,
13768
13816
  selectAllCount
@@ -14289,6 +14337,6 @@ const testTransaction = {
14289
14337
  if (db.internal[trxForTest]?.length === 0) return db.q.adapter.close();
14290
14338
  }
14291
14339
  };
14292
- export { AdapterClass, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TransactionAdapterClass, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, XMLColumn, _appendQuery, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, 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 };
14340
+ export { AdapterClass, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TransactionAdapterClass, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, 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 };
14293
14341
 
14294
14342
  //# sourceMappingURL=index.mjs.map