pqb 0.72.0 → 0.72.2

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/internal.mjs CHANGED
@@ -69,13 +69,6 @@ const singleQuote$1 = (s) => {
69
69
  return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
70
70
  };
71
71
  /**
72
- * For code generation: stringify array of strings using a single quote.
73
- * @param arr
74
- */
75
- const singleQuoteArray = (arr) => {
76
- return `[${arr.map(singleQuote$1).join(", ")}]`;
77
- };
78
- /**
79
72
  * For code generation: some strings must be quoted when used as an object key.
80
73
  * This function quotes the strings when needed.
81
74
  * @param key - object key to quote
@@ -476,6 +469,9 @@ var Column$1 = class {
476
469
  as(column) {
477
470
  return setColumnData$1(this, "as", column);
478
471
  }
472
+ brand(_token) {
473
+ return this;
474
+ }
479
475
  input(fn) {
480
476
  const cloned = Object.create(this);
481
477
  cloned.inputSchema = fn(this.inputSchema);
@@ -1083,131 +1079,6 @@ const columnErrorMessagesToCode = (errors) => {
1083
1079
  addCode$1(code, "})");
1084
1080
  return code;
1085
1081
  };
1086
- const indexOrExcludeToCode = (innerToCode) => (item, t, prefix) => {
1087
- const code = innerToCode(item, t);
1088
- if (prefix) code[0] = prefix + code[0];
1089
- const last = code[code.length - 1];
1090
- if (typeof last === "string" && !last.endsWith(",")) addCode$1(code, ",");
1091
- return code;
1092
- };
1093
- const indexInnerToCode$1 = (index, t) => {
1094
- const code = [`${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`];
1095
- const columnOptions = [
1096
- "collate",
1097
- "opclass",
1098
- "order",
1099
- "weight"
1100
- ];
1101
- const indexOptionsKeys = [
1102
- index.options.tsVector ? "unique" : void 0,
1103
- "name",
1104
- "using",
1105
- "nullsNotDistinct",
1106
- "deferrable",
1107
- "include",
1108
- "with",
1109
- "tablespace",
1110
- "where",
1111
- "language",
1112
- "languageColumn",
1113
- "dropMode"
1114
- ];
1115
- const hasOptions = indexOptionsKeys.some((key) => key && index.options[key]);
1116
- const columnsMultiline = index.columns.some((column) => {
1117
- for (const key in column) if (key !== "column" && column[key] !== void 0) return true;
1118
- return false;
1119
- });
1120
- if (columnsMultiline) {
1121
- const objects = [];
1122
- for (const column of index.columns) {
1123
- const expr = "expression" in column ? column.expression : column.column;
1124
- let hasOptions = false;
1125
- for (const key in column) if (key !== "column") hasOptions = true;
1126
- if (!hasOptions) objects.push(`${singleQuote$1(expr)},`);
1127
- else {
1128
- const props = [`${"expression" in column ? "expression" : "column"}: ${singleQuote$1(expr)},`];
1129
- for (const key of columnOptions) {
1130
- const value = column[key];
1131
- if (value !== void 0) props.push(`${key}: ${singleQuote$1(value)},`);
1132
- }
1133
- objects.push("{", props, "},");
1134
- }
1135
- }
1136
- code.push([
1137
- "[",
1138
- objects,
1139
- hasOptions ? "]," : "]"
1140
- ]);
1141
- } else addCode$1(code, `[${index.columns.map((it) => singleQuote$1(it.column)).join(", ")}]`);
1142
- if (hasOptions) {
1143
- if (columnsMultiline) code.push(["{"]);
1144
- else addCode$1(code, ", {");
1145
- const options = [];
1146
- for (const key of indexOptionsKeys) {
1147
- if (!key) continue;
1148
- const value = index.options[key];
1149
- if (value === null || value === void 0) continue;
1150
- options.push(`${key}: ${Array.isArray(value) ? singleQuoteArray(value) : typeof value === "string" ? singleQuote$1(value) : value},`);
1151
- }
1152
- if (columnsMultiline) code.push([options, "},"]);
1153
- else {
1154
- code.push(options);
1155
- addCode$1(code, "}");
1156
- }
1157
- }
1158
- if (columnsMultiline) code.push("),");
1159
- else addCode$1(code, ")");
1160
- return code;
1161
- };
1162
- indexOrExcludeToCode(indexInnerToCode$1);
1163
- const excludeInnerToCode$1 = (item, t) => {
1164
- const code = [`${t}.exclude(`];
1165
- const columnOptions = [
1166
- "collate",
1167
- "opclass",
1168
- "order",
1169
- "with"
1170
- ];
1171
- const optionsKeys = [
1172
- "name",
1173
- "using",
1174
- "include",
1175
- "with",
1176
- "tablespace",
1177
- "where",
1178
- "dropMode"
1179
- ];
1180
- const hasOptions = optionsKeys.some((key) => key && item.options[key]);
1181
- const objects = [];
1182
- for (const column of item.columns) {
1183
- const expr = "expression" in column ? column.expression : column.column;
1184
- const props = [`${"expression" in column ? "expression" : "column"}: ${singleQuote$1(expr)},`];
1185
- for (const key of columnOptions) {
1186
- const value = column[key];
1187
- if (value !== void 0) props.push(`${key}: ${singleQuote$1(value)},`);
1188
- }
1189
- objects.push("{", props, "},");
1190
- }
1191
- code.push([
1192
- "[",
1193
- objects,
1194
- hasOptions ? "]," : "]"
1195
- ]);
1196
- if (hasOptions) {
1197
- code.push(["{"]);
1198
- const options = [];
1199
- for (const key of optionsKeys) {
1200
- if (!key) continue;
1201
- const value = item.options[key];
1202
- if (value === null || value === void 0) continue;
1203
- options.push(`${key}: ${Array.isArray(value) ? singleQuoteArray(value) : typeof value === "string" ? singleQuote$1(value) : value},`);
1204
- }
1205
- code.push([options, "},"]);
1206
- }
1207
- code.push("),");
1208
- return code;
1209
- };
1210
- indexOrExcludeToCode(excludeInnerToCode$1);
1211
1082
  const columnForeignKeysToCode = (foreignKeys, migration) => {
1212
1083
  const code = [];
1213
1084
  for (const foreignKey of foreignKeys) {
@@ -1911,6 +1782,17 @@ const make = (_op) => {
1911
1782
  (q.chain ??= []).push(_op, val || value);
1912
1783
  if (getValueParser(q.parsers)) setValueParser(q, void 0);
1913
1784
  q.getColumn = BooleanColumn$1.instance;
1785
+ if (this instanceof Expression$1 && this.result) {
1786
+ let column;
1787
+ if (this.result.value?.data.name) {
1788
+ column = Object.create(BooleanColumn$1.instance);
1789
+ column.data = {
1790
+ ...column.data,
1791
+ name: this.result.value.data.name
1792
+ };
1793
+ } else column = BooleanColumn$1.instance;
1794
+ this.result.value = column;
1795
+ }
1914
1796
  return setQueryOperators(this, boolean);
1915
1797
  }, { _op });
1916
1798
  };
@@ -2417,7 +2299,8 @@ var SimpleRawSQL = class extends RawSql$1 {
2417
2299
  };
2418
2300
  const raw$1 = (sql) => new SimpleRawSQL(sql);
2419
2301
  const makeTimestamps = (timestamp) => {
2420
- const nowRaw = raw$1(getDefaultNowFn());
2302
+ const now = getDefaultNowFn();
2303
+ const nowRaw = raw$1(now);
2421
2304
  const updatedAt = timestamp().default(nowRaw);
2422
2305
  let updater;
2423
2306
  updatedAt.data.modifyQuery = (q, column) => {
@@ -2450,7 +2333,7 @@ const timestampHelpers = {
2450
2333
  };
2451
2334
  const defaultSrid = 4326;
2452
2335
  const encode = ({ srid = defaultSrid, lon, lat }) => {
2453
- const arr = new Uint8Array(25);
2336
+ const arr = /* @__PURE__ */ new Uint8Array(25);
2454
2337
  const view = new DataView(arr.buffer);
2455
2338
  view.setInt8(0, 1);
2456
2339
  view.setInt8(1, 1);
@@ -2479,7 +2362,7 @@ var PostgisGeographyPointColumn$1 = class extends Column$1 {
2479
2362
  }
2480
2363
  };
2481
2364
  const parse = (input) => {
2482
- const bytes = new Uint8Array(20);
2365
+ const bytes = /* @__PURE__ */ new Uint8Array(20);
2483
2366
  for (let i = 0; i < 40; i += 2) bytes[i / 2] = parseInt(input.slice(10 + i, 12 + i), 16);
2484
2367
  const view = new DataView(bytes.buffer);
2485
2368
  const srid = view.getUint32(0, true);
@@ -3775,7 +3658,8 @@ const resolveCallbacksInArgs = (q, args) => {
3775
3658
  qb.q.and = qb.q.or = qb.q.scopes = void 0;
3776
3659
  qb.q.subQuery = 1;
3777
3660
  _setSubQueryAliases(qb);
3778
- args[i] = prepareSubQueryForSql$1(q, resolveSubQueryCallback(qb, arg));
3661
+ const resolved = resolveSubQueryCallback(qb, arg);
3662
+ args[i] = prepareSubQueryForSql$1(q, resolved);
3779
3663
  } else if (arg.constructor === Object) {
3780
3664
  const copy = args[i] = { ...arg };
3781
3665
  for (const key in arg) {
@@ -3982,12 +3866,15 @@ const _addToHookSelectWithTable = (query, selects, table) => {
3982
3866
  const setSelectRelation = (q) => {
3983
3867
  q.selectRelation = true;
3984
3868
  };
3985
- const addParsersForSelectJoined = (q, arg, as = arg) => {
3869
+ const addParsersForSelectJoinedWildcard = (q, arg, as = arg) => {
3986
3870
  const parsers = q.q.joinedParsers?.[arg];
3987
3871
  if (parsers) setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
3988
3872
  const batchParsers = q.q.joinedBatchParsers?.[arg];
3989
3873
  if (batchParsers) pushQueryArrayImmutable(q, "batchParsers", batchParsers.map((x) => ({
3990
- path: [{ key: as }, ...x.path],
3874
+ path: [{
3875
+ key: as,
3876
+ returnType: "one"
3877
+ }, ...x.path],
3991
3878
  fn: x.fn
3992
3879
  })));
3993
3880
  };
@@ -4157,7 +4044,8 @@ const processSelectAsArg = (q, selectAs, as, key, arg, columnAlias, outerReturnT
4157
4044
  subQuery = value;
4158
4045
  } else subQuery = value.json(false);
4159
4046
  else subQuery = value;
4160
- const as = _joinLateral(q, innerJoinLateral || query.q.returnType === "valueOrThrow" ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4047
+ const joinLateral = innerJoinLateral || query.q.returnType === "valueOrThrow";
4048
+ const as = _joinLateral(q, joinLateral ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4161
4049
  if (as) value.q.joinedForSelect = _copyQueryAliasToQuery(value, q, as);
4162
4050
  }
4163
4051
  if (value.q.getColumn?.data.skipValueToArray) value.q.notFoundDefault ??= null;
@@ -4189,7 +4077,7 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
4189
4077
  const table = getFullColumnTable(query, arg, index, as);
4190
4078
  const column = arg.slice(index + 1);
4191
4079
  if (column === "*") {
4192
- addParsersForSelectJoined(query, table, columnAs);
4080
+ addParsersForSelectJoinedWildcard(query, table, columnAs);
4193
4081
  return table === as ? column : arg;
4194
4082
  }
4195
4083
  if (table === as) return selectColumn(query, q, column, columnAs, columnAlias);
@@ -4361,11 +4249,20 @@ function queryJson(self, coalesce) {
4361
4249
  }
4362
4250
  const moveQueryToCte = (ctx, query, type, dontAddTableHook) => {
4363
4251
  const { returnType } = query.q;
4252
+ const throwOnNotFound = returnType === "valueOrThrow";
4364
4253
  let valueAs;
4365
4254
  if (returnType === "value" || returnType === "valueOrThrow" || returnType === "pluck") {
4366
4255
  const first = query.q.select[0];
4367
- if (first instanceof SelectItemExpression && typeof first.item === "string") valueAs = first.item;
4368
- else {
4256
+ if (first instanceof SelectItemExpression && typeof first.item === "string") {
4257
+ const columnName = first.result.value?.data.name;
4258
+ if (columnName && columnName !== first.item) {
4259
+ query = _clone$1(query);
4260
+ query.q.returnType = "one";
4261
+ query.q.select = [{ selectAs: { [first.item]: first } }];
4262
+ if (throwOnNotFound && query.q.type !== "upsert") query.q.cteThrowOnNotFound = true;
4263
+ }
4264
+ valueAs = first.item;
4265
+ } else {
4369
4266
  query = _clone$1(query);
4370
4267
  query.q.returnType = "one";
4371
4268
  query.q.select = [{ selectAs: { value: query.q.select[0] } }];
@@ -4422,7 +4319,7 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4422
4319
  const afterUpdateCommit = data.afterUpdateCommit;
4423
4320
  const afterSaveCommit = data.afterSaveCommit;
4424
4321
  const afterDeleteCommit = data.afterDeleteCommit;
4425
- const throwOnNotFound = hookPurpose !== "Create" && (data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4322
+ const throwOnNotFound = hookPurpose !== "Create" && (data.cteThrowOnNotFound || data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4426
4323
  const hasAfterHook = afterCreate || afterUpdate || afterSave || afterDelete || afterCreateCommit || afterUpdateCommit || afterSaveCommit || afterDeleteCommit;
4427
4324
  if (!select && !hasAfterHook && !throwOnNotFound) return;
4428
4325
  const tableHook = {
@@ -4447,7 +4344,8 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4447
4344
  tableHook,
4448
4345
  throwOnNotFound
4449
4346
  };
4450
- const cteHooks = setCteHooks(ctx, throwOnNotFound || !!tableHook.select);
4347
+ const hasSelect = throwOnNotFound || !!tableHook.select;
4348
+ const cteHooks = setCteHooks(ctx, hasSelect);
4451
4349
  (cteHooks.tableHooks ??= {})[ctx.cteName] ??= item;
4452
4350
  }
4453
4351
  } else ctx.topCtx.tableHook = tableHook;
@@ -4840,7 +4738,8 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
4840
4738
  const value = data[key];
4841
4739
  if (value === void 0) continue;
4842
4740
  if (key === "AND") {
4843
- const sql = processAnds(toArray$1(value), ctx, table, query, quotedAs);
4741
+ const arr = toArray$1(value);
4742
+ const sql = processAnds(arr, ctx, table, query, quotedAs);
4844
4743
  if (sql) ands.push(sql);
4845
4744
  } else if (key === "OR") {
4846
4745
  const sqls = value.map(toArray$1).reduce((acc, and) => {
@@ -5692,7 +5591,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
5692
5591
  upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
5693
5592
  upsertOrCreate.q.and = [new RawSql$1(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
5694
5593
  if (query.upsertInsert) {
5695
- _queryInsert$1(upsertOrCreate, query.upsertInsert());
5594
+ const insertData = query.upsertInsert();
5595
+ _queryInsert$1(upsertOrCreate, insertData);
5696
5596
  upsertOrCreate.q.type = "upsert";
5697
5597
  }
5698
5598
  upsertOrCreate.q.with = query.upsertCreateWith;
@@ -5805,7 +5705,8 @@ const cteToSqlGiveAs = (ctx, item, type, dontAddTableHook) => {
5805
5705
  let as;
5806
5706
  if (typeof item.n === "string") as = item.n;
5807
5707
  else if (ctx === ctx.topCtx) {
5808
- as = setFreeAlias$1((ctx.topCtx.topCTE ??= newTopCte(ctx)).names, "q", true);
5708
+ const topCTE = ctx.topCtx.topCTE ??= newTopCte(ctx);
5709
+ as = setFreeAlias$1(topCTE.names, "q", true);
5809
5710
  item.n(as);
5810
5711
  } else throw new Error("not implemented yet");
5811
5712
  if (item.q) inner = getSqlText$1(toSql(item.q, type, ctx.topCtx, true, as, void 0, dontAddTableHook));
@@ -5999,7 +5900,11 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
5999
5900
  const columnToSqlNotSelect = (ctx, data, shape, column, quotedAs, useSelectList) => columnToSql(ctx, data, shape, column, quotedAs, void 0, void 0, void 0, useSelectList, true);
6000
5901
  const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList, skipValueToArray) => {
6001
5902
  let index = column.indexOf(".");
6002
- if (index !== -1) return tableColumnToSql(ctx, data, shape, column.slice(0, index), column.slice(index + 1), quotedAs, select, as, jsonList, skipValueToArray);
5903
+ if (index !== -1) {
5904
+ const table = column.slice(0, index);
5905
+ const key = column.slice(index + 1);
5906
+ return tableColumnToSql(ctx, data, shape, table, key, quotedAs, select, as, jsonList, skipValueToArray);
5907
+ }
6003
5908
  return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList, void 0, skipValueToArray);
6004
5909
  };
6005
5910
  const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select, skipValueToArray) => {
@@ -6175,7 +6080,9 @@ const insert = (self, { columns, insertFrom, values }, many, queryMany) => {
6175
6080
  };
6176
6081
  const _queryInsert$1 = (query, data) => {
6177
6082
  throwIfReadOnly(query);
6178
- return insert(query, handleOneData(query, data, createCtx()));
6083
+ const ctx = createCtx();
6084
+ const obj = handleOneData(query, data, ctx);
6085
+ return insert(query, obj);
6179
6086
  };
6180
6087
  /**
6181
6088
  * Is used by all create from queries methods.