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.js CHANGED
@@ -67,13 +67,6 @@ const singleQuote$1 = (s) => {
67
67
  return `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
68
68
  };
69
69
  /**
70
- * For code generation: stringify array of strings using a single quote.
71
- * @param arr
72
- */
73
- const singleQuoteArray = (arr) => {
74
- return `[${arr.map(singleQuote$1).join(", ")}]`;
75
- };
76
- /**
77
70
  * For code generation: some strings must be quoted when used as an object key.
78
71
  * This function quotes the strings when needed.
79
72
  * @param key - object key to quote
@@ -1081,131 +1074,6 @@ const columnErrorMessagesToCode = (errors) => {
1081
1074
  addCode$1(code, "})");
1082
1075
  return code;
1083
1076
  };
1084
- const indexOrExcludeToCode = (innerToCode) => (item, t, prefix) => {
1085
- const code = innerToCode(item, t);
1086
- if (prefix) code[0] = prefix + code[0];
1087
- const last = code[code.length - 1];
1088
- if (typeof last === "string" && !last.endsWith(",")) addCode$1(code, ",");
1089
- return code;
1090
- };
1091
- const indexInnerToCode$1 = (index, t) => {
1092
- const code = [`${t}.${index.options.tsVector ? "searchIndex" : index.options.unique ? "unique" : "index"}(`];
1093
- const columnOptions = [
1094
- "collate",
1095
- "opclass",
1096
- "order",
1097
- "weight"
1098
- ];
1099
- const indexOptionsKeys = [
1100
- index.options.tsVector ? "unique" : void 0,
1101
- "name",
1102
- "using",
1103
- "nullsNotDistinct",
1104
- "deferrable",
1105
- "include",
1106
- "with",
1107
- "tablespace",
1108
- "where",
1109
- "language",
1110
- "languageColumn",
1111
- "dropMode"
1112
- ];
1113
- const hasOptions = indexOptionsKeys.some((key) => key && index.options[key]);
1114
- const columnsMultiline = index.columns.some((column) => {
1115
- for (const key in column) if (key !== "column" && column[key] !== void 0) return true;
1116
- return false;
1117
- });
1118
- if (columnsMultiline) {
1119
- const objects = [];
1120
- for (const column of index.columns) {
1121
- const expr = "expression" in column ? column.expression : column.column;
1122
- let hasOptions = false;
1123
- for (const key in column) if (key !== "column") hasOptions = true;
1124
- if (!hasOptions) objects.push(`${singleQuote$1(expr)},`);
1125
- else {
1126
- const props = [`${"expression" in column ? "expression" : "column"}: ${singleQuote$1(expr)},`];
1127
- for (const key of columnOptions) {
1128
- const value = column[key];
1129
- if (value !== void 0) props.push(`${key}: ${singleQuote$1(value)},`);
1130
- }
1131
- objects.push("{", props, "},");
1132
- }
1133
- }
1134
- code.push([
1135
- "[",
1136
- objects,
1137
- hasOptions ? "]," : "]"
1138
- ]);
1139
- } else addCode$1(code, `[${index.columns.map((it) => singleQuote$1(it.column)).join(", ")}]`);
1140
- if (hasOptions) {
1141
- if (columnsMultiline) code.push(["{"]);
1142
- else addCode$1(code, ", {");
1143
- const options = [];
1144
- for (const key of indexOptionsKeys) {
1145
- if (!key) continue;
1146
- const value = index.options[key];
1147
- if (value === null || value === void 0) continue;
1148
- options.push(`${key}: ${Array.isArray(value) ? singleQuoteArray(value) : typeof value === "string" ? singleQuote$1(value) : value},`);
1149
- }
1150
- if (columnsMultiline) code.push([options, "},"]);
1151
- else {
1152
- code.push(options);
1153
- addCode$1(code, "}");
1154
- }
1155
- }
1156
- if (columnsMultiline) code.push("),");
1157
- else addCode$1(code, ")");
1158
- return code;
1159
- };
1160
- indexOrExcludeToCode(indexInnerToCode$1);
1161
- const excludeInnerToCode$1 = (item, t) => {
1162
- const code = [`${t}.exclude(`];
1163
- const columnOptions = [
1164
- "collate",
1165
- "opclass",
1166
- "order",
1167
- "with"
1168
- ];
1169
- const optionsKeys = [
1170
- "name",
1171
- "using",
1172
- "include",
1173
- "with",
1174
- "tablespace",
1175
- "where",
1176
- "dropMode"
1177
- ];
1178
- const hasOptions = optionsKeys.some((key) => key && item.options[key]);
1179
- const objects = [];
1180
- for (const column of item.columns) {
1181
- const expr = "expression" in column ? column.expression : column.column;
1182
- const props = [`${"expression" in column ? "expression" : "column"}: ${singleQuote$1(expr)},`];
1183
- for (const key of columnOptions) {
1184
- const value = column[key];
1185
- if (value !== void 0) props.push(`${key}: ${singleQuote$1(value)},`);
1186
- }
1187
- objects.push("{", props, "},");
1188
- }
1189
- code.push([
1190
- "[",
1191
- objects,
1192
- hasOptions ? "]," : "]"
1193
- ]);
1194
- if (hasOptions) {
1195
- code.push(["{"]);
1196
- const options = [];
1197
- for (const key of optionsKeys) {
1198
- if (!key) continue;
1199
- const value = item.options[key];
1200
- if (value === null || value === void 0) continue;
1201
- options.push(`${key}: ${Array.isArray(value) ? singleQuoteArray(value) : typeof value === "string" ? singleQuote$1(value) : value},`);
1202
- }
1203
- code.push([options, "},"]);
1204
- }
1205
- code.push("),");
1206
- return code;
1207
- };
1208
- indexOrExcludeToCode(excludeInnerToCode$1);
1209
1077
  const columnForeignKeysToCode = (foreignKeys, migration) => {
1210
1078
  const code = [];
1211
1079
  for (const foreignKey of foreignKeys) {
@@ -1909,6 +1777,17 @@ const make = (_op) => {
1909
1777
  (q.chain ??= []).push(_op, val || value);
1910
1778
  if (getValueParser(q.parsers)) setValueParser(q, void 0);
1911
1779
  q.getColumn = BooleanColumn$1.instance;
1780
+ if (this instanceof Expression$1 && this.result) {
1781
+ let column;
1782
+ if (this.result.value?.data.name) {
1783
+ column = Object.create(BooleanColumn$1.instance);
1784
+ column.data = {
1785
+ ...column.data,
1786
+ name: this.result.value.data.name
1787
+ };
1788
+ } else column = BooleanColumn$1.instance;
1789
+ this.result.value = column;
1790
+ }
1912
1791
  return setQueryOperators(this, boolean);
1913
1792
  }, { _op });
1914
1793
  };
@@ -2415,7 +2294,8 @@ var SimpleRawSQL = class extends RawSql$1 {
2415
2294
  };
2416
2295
  const raw$1 = (sql) => new SimpleRawSQL(sql);
2417
2296
  const makeTimestamps = (timestamp) => {
2418
- const nowRaw = raw$1(getDefaultNowFn());
2297
+ const now = getDefaultNowFn();
2298
+ const nowRaw = raw$1(now);
2419
2299
  const updatedAt = timestamp().default(nowRaw);
2420
2300
  let updater;
2421
2301
  updatedAt.data.modifyQuery = (q, column) => {
@@ -2448,7 +2328,7 @@ const timestampHelpers = {
2448
2328
  };
2449
2329
  const defaultSrid = 4326;
2450
2330
  const encode = ({ srid = defaultSrid, lon, lat }) => {
2451
- const arr = new Uint8Array(25);
2331
+ const arr = /* @__PURE__ */ new Uint8Array(25);
2452
2332
  const view = new DataView(arr.buffer);
2453
2333
  view.setInt8(0, 1);
2454
2334
  view.setInt8(1, 1);
@@ -2477,7 +2357,7 @@ var PostgisGeographyPointColumn$1 = class extends Column$1 {
2477
2357
  }
2478
2358
  };
2479
2359
  const parse = (input) => {
2480
- const bytes = new Uint8Array(20);
2360
+ const bytes = /* @__PURE__ */ new Uint8Array(20);
2481
2361
  for (let i = 0; i < 40; i += 2) bytes[i / 2] = parseInt(input.slice(10 + i, 12 + i), 16);
2482
2362
  const view = new DataView(bytes.buffer);
2483
2363
  const srid = view.getUint32(0, true);
@@ -3773,7 +3653,8 @@ const resolveCallbacksInArgs = (q, args) => {
3773
3653
  qb.q.and = qb.q.or = qb.q.scopes = void 0;
3774
3654
  qb.q.subQuery = 1;
3775
3655
  _setSubQueryAliases(qb);
3776
- args[i] = prepareSubQueryForSql$1(q, resolveSubQueryCallback(qb, arg));
3656
+ const resolved = resolveSubQueryCallback(qb, arg);
3657
+ args[i] = prepareSubQueryForSql$1(q, resolved);
3777
3658
  } else if (arg.constructor === Object) {
3778
3659
  const copy = args[i] = { ...arg };
3779
3660
  for (const key in arg) {
@@ -3980,12 +3861,15 @@ const _addToHookSelectWithTable = (query, selects, table) => {
3980
3861
  const setSelectRelation = (q) => {
3981
3862
  q.selectRelation = true;
3982
3863
  };
3983
- const addParsersForSelectJoined = (q, arg, as = arg) => {
3864
+ const addParsersForSelectJoinedWildcard = (q, arg, as = arg) => {
3984
3865
  const parsers = q.q.joinedParsers?.[arg];
3985
3866
  if (parsers) setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
3986
3867
  const batchParsers = q.q.joinedBatchParsers?.[arg];
3987
3868
  if (batchParsers) pushQueryArrayImmutable(q, "batchParsers", batchParsers.map((x) => ({
3988
- path: [{ key: as }, ...x.path],
3869
+ path: [{
3870
+ key: as,
3871
+ returnType: "one"
3872
+ }, ...x.path],
3989
3873
  fn: x.fn
3990
3874
  })));
3991
3875
  };
@@ -4155,7 +4039,8 @@ const processSelectAsArg = (q, selectAs, as, key, arg, columnAlias, outerReturnT
4155
4039
  subQuery = value;
4156
4040
  } else subQuery = value.json(false);
4157
4041
  else subQuery = value;
4158
- const as = _joinLateral(q, innerJoinLateral || query.q.returnType === "valueOrThrow" ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4042
+ const joinLateral = innerJoinLateral || query.q.returnType === "valueOrThrow";
4043
+ const as = _joinLateral(q, joinLateral ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
4159
4044
  if (as) value.q.joinedForSelect = _copyQueryAliasToQuery(value, q, as);
4160
4045
  }
4161
4046
  if (value.q.getColumn?.data.skipValueToArray) value.q.notFoundDefault ??= null;
@@ -4187,7 +4072,7 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
4187
4072
  const table = getFullColumnTable(query, arg, index, as);
4188
4073
  const column = arg.slice(index + 1);
4189
4074
  if (column === "*") {
4190
- addParsersForSelectJoined(query, table, columnAs);
4075
+ addParsersForSelectJoinedWildcard(query, table, columnAs);
4191
4076
  return table === as ? column : arg;
4192
4077
  }
4193
4078
  if (table === as) return selectColumn(query, q, column, columnAs, columnAlias);
@@ -4359,11 +4244,20 @@ function queryJson(self, coalesce) {
4359
4244
  }
4360
4245
  const moveQueryToCte = (ctx, query, type, dontAddTableHook) => {
4361
4246
  const { returnType } = query.q;
4247
+ const throwOnNotFound = returnType === "valueOrThrow";
4362
4248
  let valueAs;
4363
4249
  if (returnType === "value" || returnType === "valueOrThrow" || returnType === "pluck") {
4364
4250
  const first = query.q.select[0];
4365
- if (first instanceof SelectItemExpression && typeof first.item === "string") valueAs = first.item;
4366
- else {
4251
+ if (first instanceof SelectItemExpression && typeof first.item === "string") {
4252
+ const columnName = first.result.value?.data.name;
4253
+ if (columnName && columnName !== first.item) {
4254
+ query = _clone$1(query);
4255
+ query.q.returnType = "one";
4256
+ query.q.select = [{ selectAs: { [first.item]: first } }];
4257
+ if (throwOnNotFound && query.q.type !== "upsert") query.q.cteThrowOnNotFound = true;
4258
+ }
4259
+ valueAs = first.item;
4260
+ } else {
4367
4261
  query = _clone$1(query);
4368
4262
  query.q.returnType = "one";
4369
4263
  query.q.select = [{ selectAs: { value: query.q.select[0] } }];
@@ -4420,7 +4314,7 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4420
4314
  const afterUpdateCommit = data.afterUpdateCommit;
4421
4315
  const afterSaveCommit = data.afterSaveCommit;
4422
4316
  const afterDeleteCommit = data.afterDeleteCommit;
4423
- const throwOnNotFound = hookPurpose !== "Create" && (data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4317
+ const throwOnNotFound = hookPurpose !== "Create" && (data.cteThrowOnNotFound || data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
4424
4318
  const hasAfterHook = afterCreate || afterUpdate || afterSave || afterDelete || afterCreateCommit || afterUpdateCommit || afterSaveCommit || afterDeleteCommit;
4425
4319
  if (!select && !hasAfterHook && !throwOnNotFound) return;
4426
4320
  const tableHook = {
@@ -4445,7 +4339,8 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
4445
4339
  tableHook,
4446
4340
  throwOnNotFound
4447
4341
  };
4448
- const cteHooks = setCteHooks(ctx, throwOnNotFound || !!tableHook.select);
4342
+ const hasSelect = throwOnNotFound || !!tableHook.select;
4343
+ const cteHooks = setCteHooks(ctx, hasSelect);
4449
4344
  (cteHooks.tableHooks ??= {})[ctx.cteName] ??= item;
4450
4345
  }
4451
4346
  } else ctx.topCtx.tableHook = tableHook;
@@ -4838,7 +4733,8 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
4838
4733
  const value = data[key];
4839
4734
  if (value === void 0) continue;
4840
4735
  if (key === "AND") {
4841
- const sql = processAnds(toArray$1(value), ctx, table, query, quotedAs);
4736
+ const arr = toArray$1(value);
4737
+ const sql = processAnds(arr, ctx, table, query, quotedAs);
4842
4738
  if (sql) ands.push(sql);
4843
4739
  } else if (key === "OR") {
4844
4740
  const sqls = value.map(toArray$1).reduce((acc, and) => {
@@ -5690,7 +5586,8 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
5690
5586
  upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
5691
5587
  upsertOrCreate.q.and = [new RawSql$1(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
5692
5588
  if (query.upsertInsert) {
5693
- _queryInsert$1(upsertOrCreate, query.upsertInsert());
5589
+ const insertData = query.upsertInsert();
5590
+ _queryInsert$1(upsertOrCreate, insertData);
5694
5591
  upsertOrCreate.q.type = "upsert";
5695
5592
  }
5696
5593
  upsertOrCreate.q.with = query.upsertCreateWith;
@@ -5803,7 +5700,8 @@ const cteToSqlGiveAs = (ctx, item, type, dontAddTableHook) => {
5803
5700
  let as;
5804
5701
  if (typeof item.n === "string") as = item.n;
5805
5702
  else if (ctx === ctx.topCtx) {
5806
- as = setFreeAlias$1((ctx.topCtx.topCTE ??= newTopCte(ctx)).names, "q", true);
5703
+ const topCTE = ctx.topCtx.topCTE ??= newTopCte(ctx);
5704
+ as = setFreeAlias$1(topCTE.names, "q", true);
5807
5705
  item.n(as);
5808
5706
  } else throw new Error("not implemented yet");
5809
5707
  if (item.q) inner = getSqlText$1(toSql(item.q, type, ctx.topCtx, true, as, void 0, dontAddTableHook));
@@ -5997,7 +5895,11 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
5997
5895
  const columnToSqlNotSelect = (ctx, data, shape, column, quotedAs, useSelectList) => columnToSql(ctx, data, shape, column, quotedAs, void 0, void 0, void 0, useSelectList, true);
5998
5896
  const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList, skipValueToArray) => {
5999
5897
  let index = column.indexOf(".");
6000
- if (index !== -1) return tableColumnToSql(ctx, data, shape, column.slice(0, index), column.slice(index + 1), quotedAs, select, as, jsonList, skipValueToArray);
5898
+ if (index !== -1) {
5899
+ const table = column.slice(0, index);
5900
+ const key = column.slice(index + 1);
5901
+ return tableColumnToSql(ctx, data, shape, table, key, quotedAs, select, as, jsonList, skipValueToArray);
5902
+ }
6001
5903
  return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList, void 0, skipValueToArray);
6002
5904
  };
6003
5905
  const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select, skipValueToArray) => {
@@ -6173,7 +6075,9 @@ const insert = (self, { columns, insertFrom, values }, many, queryMany) => {
6173
6075
  };
6174
6076
  const _queryInsert$1 = (query, data) => {
6175
6077
  throwIfReadOnly(query);
6176
- return insert(query, handleOneData(query, data, createCtx()));
6078
+ const ctx = createCtx();
6079
+ const obj = handleOneData(query, data, ctx);
6080
+ return insert(query, obj);
6177
6081
  };
6178
6082
  /**
6179
6083
  * Is used by all create from queries methods.