pqb 0.72.0 → 0.72.1

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
@@ -1083,131 +1076,6 @@ const columnErrorMessagesToCode = (errors) => {
1083
1076
  addCode$1(code, "})");
1084
1077
  return code;
1085
1078
  };
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
1079
  const columnForeignKeysToCode = (foreignKeys, migration) => {
1212
1080
  const code = [];
1213
1081
  for (const foreignKey of foreignKeys) {
@@ -1911,6 +1779,17 @@ const make = (_op) => {
1911
1779
  (q.chain ??= []).push(_op, val || value);
1912
1780
  if (getValueParser(q.parsers)) setValueParser(q, void 0);
1913
1781
  q.getColumn = BooleanColumn$1.instance;
1782
+ if (this instanceof Expression$1 && this.result) {
1783
+ let column;
1784
+ if (this.result.value?.data.name) {
1785
+ column = Object.create(BooleanColumn$1.instance);
1786
+ column.data = {
1787
+ ...column.data,
1788
+ name: this.result.value.data.name
1789
+ };
1790
+ } else column = BooleanColumn$1.instance;
1791
+ this.result.value = column;
1792
+ }
1914
1793
  return setQueryOperators(this, boolean);
1915
1794
  }, { _op });
1916
1795
  };
@@ -2417,7 +2296,8 @@ var SimpleRawSQL = class extends RawSql$1 {
2417
2296
  };
2418
2297
  const raw$1 = (sql) => new SimpleRawSQL(sql);
2419
2298
  const makeTimestamps = (timestamp) => {
2420
- const nowRaw = raw$1(getDefaultNowFn());
2299
+ const now = getDefaultNowFn();
2300
+ const nowRaw = raw$1(now);
2421
2301
  const updatedAt = timestamp().default(nowRaw);
2422
2302
  let updater;
2423
2303
  updatedAt.data.modifyQuery = (q, column) => {
@@ -2450,7 +2330,7 @@ const timestampHelpers = {
2450
2330
  };
2451
2331
  const defaultSrid = 4326;
2452
2332
  const encode = ({ srid = defaultSrid, lon, lat }) => {
2453
- const arr = new Uint8Array(25);
2333
+ const arr = /* @__PURE__ */ new Uint8Array(25);
2454
2334
  const view = new DataView(arr.buffer);
2455
2335
  view.setInt8(0, 1);
2456
2336
  view.setInt8(1, 1);
@@ -2479,7 +2359,7 @@ var PostgisGeographyPointColumn$1 = class extends Column$1 {
2479
2359
  }
2480
2360
  };
2481
2361
  const parse = (input) => {
2482
- const bytes = new Uint8Array(20);
2362
+ const bytes = /* @__PURE__ */ new Uint8Array(20);
2483
2363
  for (let i = 0; i < 40; i += 2) bytes[i / 2] = parseInt(input.slice(10 + i, 12 + i), 16);
2484
2364
  const view = new DataView(bytes.buffer);
2485
2365
  const srid = view.getUint32(0, true);
@@ -3775,7 +3655,8 @@ const resolveCallbacksInArgs = (q, args) => {
3775
3655
  qb.q.and = qb.q.or = qb.q.scopes = void 0;
3776
3656
  qb.q.subQuery = 1;
3777
3657
  _setSubQueryAliases(qb);
3778
- args[i] = prepareSubQueryForSql$1(q, resolveSubQueryCallback(qb, arg));
3658
+ const resolved = resolveSubQueryCallback(qb, arg);
3659
+ args[i] = prepareSubQueryForSql$1(q, resolved);
3779
3660
  } else if (arg.constructor === Object) {
3780
3661
  const copy = args[i] = { ...arg };
3781
3662
  for (const key in arg) {
@@ -3982,12 +3863,15 @@ const _addToHookSelectWithTable = (query, selects, table) => {
3982
3863
  const setSelectRelation = (q) => {
3983
3864
  q.selectRelation = true;
3984
3865
  };
3985
- const addParsersForSelectJoined = (q, arg, as = arg) => {
3866
+ const addParsersForSelectJoinedWildcard = (q, arg, as = arg) => {
3986
3867
  const parsers = q.q.joinedParsers?.[arg];
3987
3868
  if (parsers) setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
3988
3869
  const batchParsers = q.q.joinedBatchParsers?.[arg];
3989
3870
  if (batchParsers) pushQueryArrayImmutable(q, "batchParsers", batchParsers.map((x) => ({
3990
- path: [{ key: as }, ...x.path],
3871
+ path: [{
3872
+ key: as,
3873
+ returnType: "one"
3874
+ }, ...x.path],
3991
3875
  fn: x.fn
3992
3876
  })));
3993
3877
  };
@@ -4157,7 +4041,8 @@ const processSelectAsArg = (q, selectAs, as, key, arg, columnAlias, outerReturnT
4157
4041
  subQuery = value;
4158
4042
  } else subQuery = value.json(false);
4159
4043
  else subQuery = value;
4160
- const as = _joinLateral(q, innerJoinLateral || query.q.returnType === "valueOrThrow" ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4044
+ const joinLateral = innerJoinLateral || query.q.returnType === "valueOrThrow";
4045
+ const as = _joinLateral(q, joinLateral ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4161
4046
  if (as) value.q.joinedForSelect = _copyQueryAliasToQuery(value, q, as);
4162
4047
  }
4163
4048
  if (value.q.getColumn?.data.skipValueToArray) value.q.notFoundDefault ??= null;
@@ -4189,7 +4074,7 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
4189
4074
  const table = getFullColumnTable(query, arg, index, as);
4190
4075
  const column = arg.slice(index + 1);
4191
4076
  if (column === "*") {
4192
- addParsersForSelectJoined(query, table, columnAs);
4077
+ addParsersForSelectJoinedWildcard(query, table, columnAs);
4193
4078
  return table === as ? column : arg;
4194
4079
  }
4195
4080
  if (table === as) return selectColumn(query, q, column, columnAs, columnAlias);
@@ -4361,11 +4246,20 @@ function queryJson(self, coalesce) {
4361
4246
  }
4362
4247
  const moveQueryToCte = (ctx, query, type, dontAddTableHook) => {
4363
4248
  const { returnType } = query.q;
4249
+ const throwOnNotFound = returnType === "valueOrThrow";
4364
4250
  let valueAs;
4365
4251
  if (returnType === "value" || returnType === "valueOrThrow" || returnType === "pluck") {
4366
4252
  const first = query.q.select[0];
4367
- if (first instanceof SelectItemExpression && typeof first.item === "string") valueAs = first.item;
4368
- else {
4253
+ if (first instanceof SelectItemExpression && typeof first.item === "string") {
4254
+ const columnName = first.result.value?.data.name;
4255
+ if (columnName && columnName !== first.item) {
4256
+ query = _clone$1(query);
4257
+ query.q.returnType = "one";
4258
+ query.q.select = [{ selectAs: { [first.item]: first } }];
4259
+ if (throwOnNotFound && query.q.type !== "upsert") query.q.cteThrowOnNotFound = true;
4260
+ }
4261
+ valueAs = first.item;
4262
+ } else {
4369
4263
  query = _clone$1(query);
4370
4264
  query.q.returnType = "one";
4371
4265
  query.q.select = [{ selectAs: { value: query.q.select[0] } }];
@@ -4422,7 +4316,7 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4422
4316
  const afterUpdateCommit = data.afterUpdateCommit;
4423
4317
  const afterSaveCommit = data.afterSaveCommit;
4424
4318
  const afterDeleteCommit = data.afterDeleteCommit;
4425
- const throwOnNotFound = hookPurpose !== "Create" && (data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4319
+ const throwOnNotFound = hookPurpose !== "Create" && (data.cteThrowOnNotFound || data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4426
4320
  const hasAfterHook = afterCreate || afterUpdate || afterSave || afterDelete || afterCreateCommit || afterUpdateCommit || afterSaveCommit || afterDeleteCommit;
4427
4321
  if (!select && !hasAfterHook && !throwOnNotFound) return;
4428
4322
  const tableHook = {
@@ -4447,7 +4341,8 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4447
4341
  tableHook,
4448
4342
  throwOnNotFound
4449
4343
  };
4450
- const cteHooks = setCteHooks(ctx, throwOnNotFound || !!tableHook.select);
4344
+ const hasSelect = throwOnNotFound || !!tableHook.select;
4345
+ const cteHooks = setCteHooks(ctx, hasSelect);
4451
4346
  (cteHooks.tableHooks ??= {})[ctx.cteName] ??= item;
4452
4347
  }
4453
4348
  } else ctx.topCtx.tableHook = tableHook;
@@ -4840,7 +4735,8 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
4840
4735
  const value = data[key];
4841
4736
  if (value === void 0) continue;
4842
4737
  if (key === "AND") {
4843
- const sql = processAnds(toArray$1(value), ctx, table, query, quotedAs);
4738
+ const arr = toArray$1(value);
4739
+ const sql = processAnds(arr, ctx, table, query, quotedAs);
4844
4740
  if (sql) ands.push(sql);
4845
4741
  } else if (key === "OR") {
4846
4742
  const sqls = value.map(toArray$1).reduce((acc, and) => {
@@ -5692,7 +5588,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
5692
5588
  upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
5693
5589
  upsertOrCreate.q.and = [new RawSql$1(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
5694
5590
  if (query.upsertInsert) {
5695
- _queryInsert$1(upsertOrCreate, query.upsertInsert());
5591
+ const insertData = query.upsertInsert();
5592
+ _queryInsert$1(upsertOrCreate, insertData);
5696
5593
  upsertOrCreate.q.type = "upsert";
5697
5594
  }
5698
5595
  upsertOrCreate.q.with = query.upsertCreateWith;
@@ -5805,7 +5702,8 @@ const cteToSqlGiveAs = (ctx, item, type, dontAddTableHook) => {
5805
5702
  let as;
5806
5703
  if (typeof item.n === "string") as = item.n;
5807
5704
  else if (ctx === ctx.topCtx) {
5808
- as = setFreeAlias$1((ctx.topCtx.topCTE ??= newTopCte(ctx)).names, "q", true);
5705
+ const topCTE = ctx.topCtx.topCTE ??= newTopCte(ctx);
5706
+ as = setFreeAlias$1(topCTE.names, "q", true);
5809
5707
  item.n(as);
5810
5708
  } else throw new Error("not implemented yet");
5811
5709
  if (item.q) inner = getSqlText$1(toSql(item.q, type, ctx.topCtx, true, as, void 0, dontAddTableHook));
@@ -5999,7 +5897,11 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
5999
5897
  const columnToSqlNotSelect = (ctx, data, shape, column, quotedAs, useSelectList) => columnToSql(ctx, data, shape, column, quotedAs, void 0, void 0, void 0, useSelectList, true);
6000
5898
  const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList, skipValueToArray) => {
6001
5899
  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);
5900
+ if (index !== -1) {
5901
+ const table = column.slice(0, index);
5902
+ const key = column.slice(index + 1);
5903
+ return tableColumnToSql(ctx, data, shape, table, key, quotedAs, select, as, jsonList, skipValueToArray);
5904
+ }
6003
5905
  return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList, void 0, skipValueToArray);
6004
5906
  };
6005
5907
  const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select, skipValueToArray) => {
@@ -6175,7 +6077,9 @@ const insert = (self, { columns, insertFrom, values }, many, queryMany) => {
6175
6077
  };
6176
6078
  const _queryInsert$1 = (query, data) => {
6177
6079
  throwIfReadOnly(query);
6178
- return insert(query, handleOneData(query, data, createCtx()));
6080
+ const ctx = createCtx();
6081
+ const obj = handleOneData(query, data, ctx);
6082
+ return insert(query, obj);
6179
6083
  };
6180
6084
  /**
6181
6085
  * Is used by all create from queries methods.