pqb 0.4.0 → 0.4.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/index.esm.js CHANGED
@@ -1117,15 +1117,49 @@ const getFrom = (model, query, values) => {
1117
1117
  return quoteSchemaAndTable(query.schema, model.table);
1118
1118
  };
1119
1119
 
1120
+ const pushQueryArray = (q, key, value) => {
1121
+ if (!q.query[key])
1122
+ q.query[key] = value;
1123
+ else
1124
+ q.query[key].push(
1125
+ ...value
1126
+ );
1127
+ return q;
1128
+ };
1129
+ const pushQueryValue = (q, key, value) => {
1130
+ pushOrNewArrayToObject(
1131
+ q.query,
1132
+ key,
1133
+ value
1134
+ );
1135
+ return q;
1136
+ };
1137
+ const setQueryObjectValue = (q, object, key, value) => {
1138
+ if (!q.query[object])
1139
+ q.query[object] = {
1140
+ [key]: value
1141
+ };
1142
+ else
1143
+ q.query[object][key] = value;
1144
+ return q;
1145
+ };
1146
+
1120
1147
  const pushInsertSql = (ctx, model, query, quotedAs) => {
1121
1148
  const quotedColumns = query.columns.map(q);
1122
- ctx.sql.push(
1123
- `INSERT INTO ${quotedAs}(${quotedColumns.join(", ")}) VALUES ${isRaw(query.values) ? getRaw(query.values, ctx.values) : query.values.map(
1124
- (row) => `(${row.map(
1125
- (value) => value === void 0 ? "DEFAULT" : addValue(ctx.values, value)
1126
- ).join(", ")})`
1127
- ).join(", ")}`
1128
- );
1149
+ ctx.sql.push(`INSERT INTO ${quotedAs}(${quotedColumns.join(", ")})`);
1150
+ if (query.fromQuery) {
1151
+ const q2 = query.fromQuery.clone();
1152
+ pushQueryValue(
1153
+ q2,
1154
+ "select",
1155
+ isRaw(query.values) ? query.values : raw(encodeRow(ctx, query.values[0]))
1156
+ );
1157
+ ctx.sql.push(q2.toSql({ values: ctx.values }).text);
1158
+ } else {
1159
+ ctx.sql.push(
1160
+ `VALUES ${isRaw(query.values) ? getRaw(query.values, ctx.values) : query.values.map((row) => `(${encodeRow(ctx, row)})`).join(", ")}`
1161
+ );
1162
+ }
1129
1163
  if (query.onConflict) {
1130
1164
  ctx.sql.push("ON CONFLICT");
1131
1165
  const { expr, type } = query.onConflict;
@@ -1168,6 +1202,11 @@ const pushInsertSql = (ctx, model, query, quotedAs) => {
1168
1202
  pushWhereStatementSql(ctx, model, query, quotedAs);
1169
1203
  pushReturningSql(ctx, model, query, quotedAs);
1170
1204
  };
1205
+ const encodeRow = (ctx, row) => {
1206
+ return row.map(
1207
+ (value) => value === void 0 ? "DEFAULT" : addValue(ctx.values, value)
1208
+ ).join(", ");
1209
+ };
1171
1210
  const pushReturningSql = (ctx, model, query, quotedAs) => {
1172
1211
  if (query.select) {
1173
1212
  ctx.sql.push(`RETURNING ${selectToSql(ctx, model, query, quotedAs)}`);
@@ -3141,33 +3180,6 @@ class TransactionAdapter {
3141
3180
  }
3142
3181
  }
3143
3182
 
3144
- const pushQueryArray = (q, key, value) => {
3145
- if (!q.query[key])
3146
- q.query[key] = value;
3147
- else
3148
- q.query[key].push(
3149
- ...value
3150
- );
3151
- return q;
3152
- };
3153
- const pushQueryValue = (q, key, value) => {
3154
- pushOrNewArrayToObject(
3155
- q.query,
3156
- key,
3157
- value
3158
- );
3159
- return q;
3160
- };
3161
- const setQueryObjectValue = (q, object, key, value) => {
3162
- if (!q.query[object])
3163
- q.query[object] = {
3164
- [key]: value
3165
- };
3166
- else
3167
- q.query[object][key] = value;
3168
- return q;
3169
- };
3170
-
3171
3183
  const getValueKey = Symbol("get");
3172
3184
  const _get = (q, returnType, arg) => {
3173
3185
  q.query.returnType = returnType;
@@ -3239,8 +3251,8 @@ const then = async (q, resolve, reject) => {
3239
3251
  let beforeCallbacks;
3240
3252
  let afterCallbacks;
3241
3253
  if (q.query.type === "insert") {
3242
- beforeCallbacks = q.query.beforeInsert;
3243
- afterCallbacks = q.query.afterInsert;
3254
+ beforeCallbacks = q.query.beforeCreate;
3255
+ afterCallbacks = q.query.afterCreate;
3244
3256
  } else if (q.query.type === "update") {
3245
3257
  beforeCallbacks = q.query.beforeUpdate;
3246
3258
  afterCallbacks = q.query.afterUpdate;
@@ -3601,7 +3613,9 @@ class Aggregate {
3601
3613
  return this.clone()._count(arg, options);
3602
3614
  }
3603
3615
  _count(arg = "*", options) {
3604
- return get(this._selectCount(arg, options));
3616
+ return get(
3617
+ this._selectCount(arg, options)
3618
+ );
3605
3619
  }
3606
3620
  selectCount(arg, options) {
3607
3621
  return this.clone()._selectCount(arg, options);
@@ -3847,17 +3861,17 @@ class QueryCallbacks {
3847
3861
  _afterQuery(cb) {
3848
3862
  return pushQueryValue(this, "afterQuery", cb);
3849
3863
  }
3850
- beforeInsert(cb) {
3851
- return this.clone()._beforeInsert(cb);
3864
+ beforeCreate(cb) {
3865
+ return this.clone()._beforeCreate(cb);
3852
3866
  }
3853
- _beforeInsert(cb) {
3854
- return pushQueryValue(this, "beforeInsert", cb);
3867
+ _beforeCreate(cb) {
3868
+ return pushQueryValue(this, "beforeCreate", cb);
3855
3869
  }
3856
- afterInsert(cb) {
3857
- return this.clone()._afterInsert(cb);
3870
+ afterCreate(cb) {
3871
+ return this.clone()._afterCreate(cb);
3858
3872
  }
3859
- _afterInsert(cb) {
3860
- return pushQueryValue(this, "afterInsert", cb);
3873
+ _afterCreate(cb) {
3874
+ return pushQueryValue(this, "afterCreate", cb);
3861
3875
  }
3862
3876
  beforeUpdate(cb) {
3863
3877
  return this.clone()._beforeUpdate(cb);
@@ -3940,22 +3954,16 @@ class ColumnInfoMethods {
3940
3954
  if (column) {
3941
3955
  this.query.column = column;
3942
3956
  }
3943
- this.then = function(resolve, reject) {
3944
- new Then().then.call(
3945
- this,
3946
- (rows) => {
3947
- if (column) {
3948
- resolve == null ? void 0 : resolve(rowToColumnInfo(rows[0]));
3949
- } else {
3950
- const info = {};
3951
- rows.forEach((row) => {
3952
- info[row.column_name] = rowToColumnInfo(row);
3953
- });
3954
- resolve == null ? void 0 : resolve(info);
3955
- }
3956
- },
3957
- reject
3958
- );
3957
+ this.query.handleResult = async (_, result) => {
3958
+ if (column) {
3959
+ return rowToColumnInfo(result.rows[0]);
3960
+ } else {
3961
+ const info = {};
3962
+ result.rows.forEach((row) => {
3963
+ info[row.column_name] = rowToColumnInfo(row);
3964
+ });
3965
+ return info;
3966
+ }
3959
3967
  };
3960
3968
  return this;
3961
3969
  }
@@ -4153,7 +4161,17 @@ var __spreadValues$4 = (a, b) => {
4153
4161
  }
4154
4162
  return a;
4155
4163
  };
4156
- const processInsertItem = (item, rowIndex, ctx, columns, columnsMap) => {
4164
+ const handleSelect = (q) => {
4165
+ var _a;
4166
+ const select = (_a = q.query.select) == null ? void 0 : _a[0];
4167
+ const isCount = typeof select === "object" && "function" in select && select.function === "count";
4168
+ if (isCount) {
4169
+ q.query.select = void 0;
4170
+ } else if (isCount || !q.query.select) {
4171
+ q.query.select = ["*"];
4172
+ }
4173
+ };
4174
+ const processCreateItem = (item, rowIndex, ctx, columns, columnsMap) => {
4157
4175
  Object.keys(item).forEach((key) => {
4158
4176
  if (ctx.relations[key]) {
4159
4177
  if (ctx.relations[key].type === "belongsTo") {
@@ -4185,13 +4203,13 @@ const processInsertItem = (item, rowIndex, ctx, columns, columnsMap) => {
4185
4203
  }
4186
4204
  });
4187
4205
  };
4188
- const createInsertCtx = (q) => ({
4206
+ const createCtx = (q) => ({
4189
4207
  prependRelations: {},
4190
4208
  appendRelations: {},
4191
4209
  requiredReturning: {},
4192
4210
  relations: q.relations
4193
4211
  });
4194
- const getInsertSingleReturnType = (q) => {
4212
+ const getSingleReturnType = (q) => {
4195
4213
  const { select, returnType = "all" } = q.query;
4196
4214
  if (select) {
4197
4215
  return returnType === "all" ? "one" : returnType;
@@ -4199,7 +4217,7 @@ const getInsertSingleReturnType = (q) => {
4199
4217
  return "rowCount";
4200
4218
  }
4201
4219
  };
4202
- const getInsertManyReturnType = (q) => {
4220
+ const getManyReturnType = (q) => {
4203
4221
  const { select, returnType } = q.query;
4204
4222
  if (select) {
4205
4223
  return returnType === "one" || returnType === "oneOrThrow" ? "all" : returnType;
@@ -4207,18 +4225,18 @@ const getInsertManyReturnType = (q) => {
4207
4225
  return "rowCount";
4208
4226
  }
4209
4227
  };
4210
- const handleInsertOneData = (q, data, ctx) => {
4228
+ const handleOneData = (q, data, ctx) => {
4211
4229
  const columns = [];
4212
4230
  const columnsMap = {};
4213
4231
  const defaults = q.query.defaults;
4214
4232
  if (defaults) {
4215
4233
  data = __spreadValues$4(__spreadValues$4({}, defaults), data);
4216
4234
  }
4217
- processInsertItem(data, 0, ctx, columns, columnsMap);
4235
+ processCreateItem(data, 0, ctx, columns, columnsMap);
4218
4236
  const values = [columns.map((key) => data[key])];
4219
4237
  return { columns, values };
4220
4238
  };
4221
- const handleInsertManyData = (q, data, ctx) => {
4239
+ const handleManyData = (q, data, ctx) => {
4222
4240
  const columns = [];
4223
4241
  const columnsMap = {};
4224
4242
  const defaults = q.query.defaults;
@@ -4226,7 +4244,7 @@ const handleInsertManyData = (q, data, ctx) => {
4226
4244
  data = data.map((item) => __spreadValues$4(__spreadValues$4({}, defaults), item));
4227
4245
  }
4228
4246
  data.forEach((item, i) => {
4229
- processInsertItem(item, i, ctx, columns, columnsMap);
4247
+ processCreateItem(item, i, ctx, columns, columnsMap);
4230
4248
  });
4231
4249
  const values = Array(data.length);
4232
4250
  data.forEach((item, i) => {
@@ -4320,67 +4338,68 @@ const insert = (self, {
4320
4338
  q.query.returnType = appendRelationsKeys.length ? "all" : returnType;
4321
4339
  return q;
4322
4340
  };
4323
- class Insert {
4324
- insert(data) {
4325
- return this.clone()._insert(data);
4341
+ class Create {
4342
+ create(data) {
4343
+ return this.clone()._create(data);
4326
4344
  }
4327
- _insert(data) {
4328
- const ctx = createInsertCtx(this);
4345
+ _create(data) {
4346
+ var _a;
4347
+ handleSelect(this);
4348
+ const ctx = createCtx(this);
4349
+ const obj = handleOneData(this, data, ctx);
4350
+ let { columns } = obj;
4351
+ const { fromQuery } = this.query;
4352
+ if (fromQuery) {
4353
+ if (!queryTypeWithLimitOne[fromQuery.query.returnType]) {
4354
+ throw new Error(
4355
+ "Cannot create based on a query which returns multiple records"
4356
+ );
4357
+ }
4358
+ const queryColumns = [];
4359
+ (_a = fromQuery.query.select) == null ? void 0 : _a.forEach((item) => {
4360
+ if (typeof item === "string") {
4361
+ const index = item.indexOf(".");
4362
+ queryColumns.push(index === -1 ? item : item.slice(index + 1));
4363
+ } else if ("selectAs" in item) {
4364
+ queryColumns.push(...Object.keys(item.selectAs));
4365
+ }
4366
+ });
4367
+ queryColumns.push(...columns);
4368
+ columns = queryColumns;
4369
+ }
4329
4370
  return insert(
4330
4371
  this,
4331
- handleInsertOneData(this, data, ctx),
4332
- getInsertSingleReturnType(this),
4372
+ { columns, values: obj.values },
4373
+ getSingleReturnType(this),
4333
4374
  ctx
4334
4375
  );
4335
4376
  }
4336
- insertMany(data) {
4337
- return this.clone()._insertMany(data);
4377
+ createMany(data) {
4378
+ return this.clone()._createMany(data);
4338
4379
  }
4339
- _insertMany(data) {
4340
- const ctx = createInsertCtx(this);
4380
+ _createMany(data) {
4381
+ handleSelect(this);
4382
+ const ctx = createCtx(this);
4341
4383
  return insert(
4342
4384
  this,
4343
- handleInsertManyData(this, data, ctx),
4344
- getInsertManyReturnType(this),
4385
+ handleManyData(this, data, ctx),
4386
+ getManyReturnType(this),
4345
4387
  ctx
4346
4388
  );
4347
4389
  }
4348
- insertRaw(data) {
4349
- return this.clone()._insertRaw(data);
4350
- }
4351
- _insertRaw(data) {
4352
- return insert(
4353
- this,
4354
- data,
4355
- getInsertManyReturnType(this)
4356
- );
4357
- }
4358
- create(data) {
4359
- return this.clone()._create(data);
4360
- }
4361
- _create(data) {
4362
- if (!this.query.select) {
4363
- this.query.select = ["*"];
4364
- }
4365
- return this.clone()._insert(data);
4366
- }
4367
- createMany(data) {
4368
- return this.clone()._createMany(data);
4369
- }
4370
- _createMany(data) {
4371
- if (!this.query.select) {
4372
- this.query.select = ["*"];
4373
- }
4374
- return this.clone()._insertMany(data);
4375
- }
4376
4390
  createRaw(data) {
4377
4391
  return this.clone()._createRaw(data);
4378
4392
  }
4379
4393
  _createRaw(data) {
4380
- if (!this.query.select) {
4381
- this.query.select = ["*"];
4382
- }
4383
- return this.clone()._insertRaw(data);
4394
+ handleSelect(this);
4395
+ return insert(this, data, getManyReturnType(this));
4396
+ }
4397
+ createFrom(query, data) {
4398
+ return this.clone()._createFrom(query, data);
4399
+ }
4400
+ _createFrom(query, data) {
4401
+ this.query.fromQuery = query;
4402
+ return this._create(data);
4384
4403
  }
4385
4404
  defaults(data) {
4386
4405
  return this.clone()._defaults(data);
@@ -5323,7 +5342,7 @@ class QueryUpsert {
5323
5342
  const { handleResult } = this.query;
5324
5343
  this.query.handleResult = async (q, queryResult) => {
5325
5344
  if (queryResult.rowCount === 0) {
5326
- return q.insert(data.create);
5345
+ return q.create(data.create);
5327
5346
  } else if (queryResult.rowCount > 1) {
5328
5347
  throw new MoreThanOneRowError(
5329
5348
  `Only one row was expected to find for upsert, found ${queryResult.rowCount} rows.`
@@ -5509,7 +5528,7 @@ applyMixins(QueryMethods, [
5509
5528
  With,
5510
5529
  Union,
5511
5530
  Json,
5512
- Insert,
5531
+ Create,
5513
5532
  Update,
5514
5533
  Delete,
5515
5534
  Transaction,
@@ -5660,5 +5679,5 @@ const createDb = (_a) => {
5660
5679
  const relationQueryKey = Symbol("relationQuery");
5661
5680
  const isRequiredRelationKey = Symbol("isRequiredRelation");
5662
5681
 
5663
- export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, Insert, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, applyMixins, array, arrayToEnum, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
5682
+ export { Adapter, Aggregate, ArrayColumn, ArrayOfColumnsObjects, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CharColumn, CidrColumn, CircleColumn, Clear, ColumnInfoMethods, ColumnType, ColumnsObject, Create, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeWithTimeZoneBaseClass, Db, DecimalBaseColumn, DecimalColumn, Delete, DoublePrecisionColumn, EMPTY_OBJECT, EnumColumn, For, From, Having, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, Join, Json, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MergeQueryMethods, MoneyColumn, MoreThanOneRowError, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, OnConflictQueryBuilder, OnQueryBuilder, Operators, PathColumn, PluckResultColumnType, PointColumn, PolygonColumn, PormError, PormInternalError, QueryCallbacks, QueryError, QueryGet, QueryLog, QueryMethods, QueryUpsert, RealColumn, Select, SerialColumn, SmallIntColumn, SmallSerialColumn, TextBaseColumn, TextColumn, Then, TimeColumn, TimeWithTimeZoneColumn, TimestampColumn, TimestampWithTimeZoneColumn, Transaction, TransactionAdapter, TsQueryColumn, TsVectorColumn, UUIDColumn, UnhandledTypeError, Union, Update, VarCharColumn, Where, WhereQueryBuilder, With, XMLColumn, addOr, addOrNot, addParserForRawExpression, addParserForSelectItem, addParserToQuery, addQueryOn, addQueryOrOn, addWhere, addWhereIn, addWhereNot, aggregate1FunctionNames, applyMixins, array, arrayToEnum, checkIfASimpleQuery, columnTypes, utils as columnUtils, constructType, createDb, createOperator, defaultsKey, discriminatedUnion, emptyObject, enumType, getClonedQueryData, getColumnTypes, getQueryAs, getQueryParsers, getRaw, getRawSql, getTableData, getValidEnumValues, getValueKey, handleResult, instanceOf, intersection, isRaw, isRequiredRelationKey, joinTruthy, jsonTypes, lazy, literal, logColors, logParamToLogObject, makeRegexToFindInSql, map, nativeEnum, newTableData, noop, notNullable, notNullish, nullable, nullish, object, optional, parseRecord, parseResult, processSelectArg, pushOrNewArray, pushOrNewArrayToObject, pushQueryArray, pushQueryOn, pushQueryOrOn, pushQueryValue, queryMethodByReturnType, queryTypeWithLimitOne, quote, raw, record, relationQueryKey, required, resetTableData, scalarTypes, set, setQueryObjectValue, toArray, toSql, toSqlCacheKey, tuple, union };
5664
5683
  //# sourceMappingURL=index.esm.js.map