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