@squiz/db-lib 1.2.10 → 1.2.12

Sign up to get free protection for your applications and to get access to all the features.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,22 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [1.2.12](https://gitlab.squiz.net/developer-experience/cmp/compare/v1.2.2...v1.2.12) (2022-11-24)
7
+
8
+ **Note:** Version bump only for package @squiz/db-lib
9
+
10
+
11
+
12
+
13
+
14
+ ## [1.2.11](https://gitlab.squiz.net/developer-experience/cmp/compare/v1.2.2...v1.2.11) (2022-11-11)
15
+
16
+ **Note:** Version bump only for package @squiz/db-lib
17
+
18
+
19
+
20
+
21
+
6
22
  ## [1.2.10](https://gitlab.squiz.net/developer-experience/cmp/compare/v1.2.2...v1.2.10) (2022-11-09)
7
23
 
8
24
  **Note:** Version bump only for package @squiz/db-lib
@@ -9,15 +9,15 @@ export interface Writer<T> {
9
9
  update(where: Partial<T>, newValue: Partial<T>): Promise<T[]>;
10
10
  delete(where: Partial<T>): Promise<number>;
11
11
  }
12
- export declare type Repository<T> = Reader<T> & Writer<T>;
13
- export declare type PageResult<T> = {
12
+ export type Repository<T> = Reader<T> & Writer<T>;
13
+ export type PageResult<T> = {
14
14
  items: T[];
15
15
  totalCount: number;
16
16
  pageSize: number;
17
17
  };
18
- export declare type SortDirection = 'desc' | 'asc';
18
+ export type SortDirection = 'desc' | 'asc';
19
19
  export declare const DEFAULT_PAGE_SIZE = 20;
20
- export declare abstract class AbstractRepository<T, ObjT extends T> implements Reader<T>, Writer<T> {
20
+ export declare abstract class AbstractRepository<T extends object, ObjT extends T> implements Reader<T>, Writer<T> {
21
21
  protected repositories: Repositories;
22
22
  protected pool: Pool;
23
23
  protected classRef: {
@@ -11,7 +11,7 @@ export interface DbConnection {
11
11
  export interface ConnectionStringObj {
12
12
  connectionString: string;
13
13
  }
14
- export declare type TransactionClient = PoolClient;
14
+ export type TransactionClient = PoolClient;
15
15
  export declare class ConnectionManager<T extends Repositories> {
16
16
  protected applicationName: string;
17
17
  protected migrationDirectory: string;
package/lib/Migrator.d.ts CHANGED
@@ -6,13 +6,15 @@ export declare class Migrator {
6
6
  constructor(migrationDir: string, migrationList: string[], pool: PoolClient);
7
7
  protected ensureMigrationTableExists(): Promise<import("pg").QueryResult<any>>;
8
8
  protected getAppliedMigrations(): Promise<any[]>;
9
- protected applyMigration(migration: string, sql: string): Promise<void>;
9
+ protected doSqlMigration(migration: string, sql: string): Promise<void>;
10
10
  protected getPending(migrationsList: string[], appliedMigrations: string[]): Promise<string[]>;
11
11
  protected getSql(migration: string): Promise<string>;
12
12
  protected tryToObtainLock(): Promise<boolean>;
13
13
  protected releaseLock(): Promise<void>;
14
14
  migrate(): Promise<any>;
15
15
  protected runMigrations(): Promise<void>;
16
+ protected doScriptMigration(migration: string): Promise<void>;
16
17
  protected runMigration(migration: string): Promise<void>;
18
+ protected doMigrationWork(migration: string): Promise<void>;
17
19
  protected dispose(): void;
18
20
  }
@@ -1,2 +1,2 @@
1
1
  import { Repository } from './AbstractRepository';
2
- export declare type Repositories = Record<string, Repository<any>>;
2
+ export type Repositories = Record<string, Repository<any>>;
package/lib/index.js CHANGED
@@ -3778,7 +3778,7 @@ var require_pg_pool = __commonJS({
3778
3778
  } else {
3779
3779
  this.log("new client connected");
3780
3780
  if (this.options.maxLifetimeSeconds !== 0) {
3781
- setTimeout(() => {
3781
+ const maxLifetimeTimeout = setTimeout(() => {
3782
3782
  this.log("ending client due to expired lifetime");
3783
3783
  this._expired.add(client);
3784
3784
  const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
@@ -3791,6 +3791,8 @@ var require_pg_pool = __commonJS({
3791
3791
  );
3792
3792
  }
3793
3793
  }, this.options.maxLifetimeSeconds * 1e3);
3794
+ maxLifetimeTimeout.unref();
3795
+ client.once("end", () => clearTimeout(maxLifetimeTimeout));
3794
3796
  }
3795
3797
  return this._acquireClient(client, pendingItem, idleListener, true);
3796
3798
  }
@@ -3897,20 +3899,24 @@ var require_pg_pool = __commonJS({
3897
3899
  };
3898
3900
  client.once("error", onError);
3899
3901
  this.log("dispatching query");
3900
- client.query(text, values, (err2, res) => {
3901
- this.log("query dispatched");
3902
- client.removeListener("error", onError);
3903
- if (clientReleased) {
3904
- return;
3905
- }
3906
- clientReleased = true;
3907
- client.release(err2);
3908
- if (err2) {
3909
- return cb(err2);
3910
- } else {
3902
+ try {
3903
+ client.query(text, values, (err2, res) => {
3904
+ this.log("query dispatched");
3905
+ client.removeListener("error", onError);
3906
+ if (clientReleased) {
3907
+ return;
3908
+ }
3909
+ clientReleased = true;
3910
+ client.release(err2);
3911
+ if (err2) {
3912
+ return cb(err2);
3913
+ }
3911
3914
  return cb(void 0, res);
3912
- }
3913
- });
3915
+ });
3916
+ } catch (err2) {
3917
+ client.release(err2);
3918
+ return cb(err2);
3919
+ }
3914
3920
  });
3915
3921
  return response.result;
3916
3922
  }
@@ -5473,6 +5479,7 @@ var require_combine = __commonJS({
5473
5479
  var require_safe_stable_stringify = __commonJS({
5474
5480
  "../dx-logger-lib/node_modules/safe-stable-stringify/index.js"(exports, module2) {
5475
5481
  "use strict";
5482
+ var { hasOwnProperty } = Object.prototype;
5476
5483
  var stringify = configure();
5477
5484
  stringify.configure = configure;
5478
5485
  stringify.stringify = stringify;
@@ -5481,7 +5488,7 @@ var require_safe_stable_stringify = __commonJS({
5481
5488
  exports.configure = configure;
5482
5489
  module2.exports = stringify;
5483
5490
  var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/;
5484
- var strEscapeSequencesReplacer = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/g;
5491
+ var strEscapeSequencesReplacer = new RegExp(strEscapeSequencesRegExp, "g");
5485
5492
  var meta = [
5486
5493
  "\\u0000",
5487
5494
  "\\u0001",
@@ -5601,13 +5608,13 @@ var require_safe_stable_stringify = __commonJS({
5601
5608
  last = i + 1;
5602
5609
  } else if (point >= 55296 && point <= 57343) {
5603
5610
  if (point <= 56319 && i + 1 < str.length) {
5604
- const point2 = str.charCodeAt(i + 1);
5605
- if (point2 >= 56320 && point2 <= 57343) {
5611
+ const nextPoint = str.charCodeAt(i + 1);
5612
+ if (nextPoint >= 56320 && nextPoint <= 57343) {
5606
5613
  i++;
5607
5614
  continue;
5608
5615
  }
5609
5616
  }
5610
- result += `${str.slice(last, i)}${`\\u${point.toString(16)}`}`;
5617
+ result += `${str.slice(last, i)}\\u${point.toString(16)}`;
5611
5618
  last = i + 1;
5612
5619
  }
5613
5620
  }
@@ -5632,7 +5639,7 @@ var require_safe_stable_stringify = __commonJS({
5632
5639
  var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(
5633
5640
  Object.getPrototypeOf(
5634
5641
  Object.getPrototypeOf(
5635
- new Uint8Array()
5642
+ new Int8Array()
5636
5643
  )
5637
5644
  ),
5638
5645
  Symbol.toStringTag
@@ -5652,8 +5659,8 @@ var require_safe_stable_stringify = __commonJS({
5652
5659
  return res;
5653
5660
  }
5654
5661
  function getCircularValueOption(options) {
5655
- if (options && Object.prototype.hasOwnProperty.call(options, "circularValue")) {
5656
- var circularValue = options.circularValue;
5662
+ if (hasOwnProperty.call(options, "circularValue")) {
5663
+ const circularValue = options.circularValue;
5657
5664
  if (typeof circularValue === "string") {
5658
5665
  return `"${circularValue}"`;
5659
5666
  }
@@ -5672,8 +5679,9 @@ var require_safe_stable_stringify = __commonJS({
5672
5679
  return '"[Circular]"';
5673
5680
  }
5674
5681
  function getBooleanOption(options, key) {
5675
- if (options && Object.prototype.hasOwnProperty.call(options, key)) {
5676
- var value = options[key];
5682
+ let value;
5683
+ if (hasOwnProperty.call(options, key)) {
5684
+ value = options[key];
5677
5685
  if (typeof value !== "boolean") {
5678
5686
  throw new TypeError(`The "${key}" argument must be of type boolean`);
5679
5687
  }
@@ -5681,8 +5689,9 @@ var require_safe_stable_stringify = __commonJS({
5681
5689
  return value === void 0 ? true : value;
5682
5690
  }
5683
5691
  function getPositiveIntegerOption(options, key) {
5684
- if (options && Object.prototype.hasOwnProperty.call(options, key)) {
5685
- var value = options[key];
5692
+ let value;
5693
+ if (hasOwnProperty.call(options, key)) {
5694
+ value = options[key];
5686
5695
  if (typeof value !== "number") {
5687
5696
  throw new TypeError(`The "${key}" argument must be of type number`);
5688
5697
  }
@@ -5704,15 +5713,39 @@ var require_safe_stable_stringify = __commonJS({
5704
5713
  function getUniqueReplacerSet(replacerArray) {
5705
5714
  const replacerSet = /* @__PURE__ */ new Set();
5706
5715
  for (const value of replacerArray) {
5707
- if (typeof value === "string") {
5708
- replacerSet.add(value);
5709
- } else if (typeof value === "number") {
5716
+ if (typeof value === "string" || typeof value === "number") {
5710
5717
  replacerSet.add(String(value));
5711
5718
  }
5712
5719
  }
5713
5720
  return replacerSet;
5714
5721
  }
5722
+ function getStrictOption(options) {
5723
+ if (hasOwnProperty.call(options, "strict")) {
5724
+ const value = options.strict;
5725
+ if (typeof value !== "boolean") {
5726
+ throw new TypeError('The "strict" argument must be of type boolean');
5727
+ }
5728
+ if (value) {
5729
+ return (value2) => {
5730
+ let message = `Object can not safely be stringified. Received type ${typeof value2}`;
5731
+ if (typeof value2 !== "function")
5732
+ message += ` (${value2.toString()})`;
5733
+ throw new Error(message);
5734
+ };
5735
+ }
5736
+ }
5737
+ }
5715
5738
  function configure(options) {
5739
+ options = { ...options };
5740
+ const fail = getStrictOption(options);
5741
+ if (fail) {
5742
+ if (options.bigint === void 0) {
5743
+ options.bigint = false;
5744
+ }
5745
+ if (!("circularValue" in options)) {
5746
+ options.circularValue = Error;
5747
+ }
5748
+ }
5716
5749
  const circularValue = getCircularValueOption(options);
5717
5750
  const bigint = getBooleanOption(options, "bigint");
5718
5751
  const deterministic = getBooleanOption(options, "deterministic");
@@ -5821,11 +5854,17 @@ ${originalIndentation}`;
5821
5854
  return `{${res}}`;
5822
5855
  }
5823
5856
  case "number":
5824
- return isFinite(value) ? String(value) : "null";
5857
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
5825
5858
  case "boolean":
5826
5859
  return value === true ? "true" : "false";
5860
+ case "undefined":
5861
+ return void 0;
5827
5862
  case "bigint":
5828
- return bigint ? String(value) : void 0;
5863
+ if (bigint) {
5864
+ return String(value);
5865
+ }
5866
+ default:
5867
+ return fail ? fail(value) : void 0;
5829
5868
  }
5830
5869
  }
5831
5870
  function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
@@ -5908,11 +5947,17 @@ ${originalIndentation}`;
5908
5947
  return `{${res}}`;
5909
5948
  }
5910
5949
  case "number":
5911
- return isFinite(value) ? String(value) : "null";
5950
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
5912
5951
  case "boolean":
5913
5952
  return value === true ? "true" : "false";
5953
+ case "undefined":
5954
+ return void 0;
5914
5955
  case "bigint":
5915
- return bigint ? String(value) : void 0;
5956
+ if (bigint) {
5957
+ return String(value);
5958
+ }
5959
+ default:
5960
+ return fail ? fail(value) : void 0;
5916
5961
  }
5917
5962
  }
5918
5963
  function stringifyIndent(key, value, stack, spacer, indentation) {
@@ -6013,11 +6058,17 @@ ${originalIndentation}`;
6013
6058
  return `{${res}}`;
6014
6059
  }
6015
6060
  case "number":
6016
- return isFinite(value) ? String(value) : "null";
6061
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
6017
6062
  case "boolean":
6018
6063
  return value === true ? "true" : "false";
6064
+ case "undefined":
6065
+ return void 0;
6019
6066
  case "bigint":
6020
- return bigint ? String(value) : void 0;
6067
+ if (bigint) {
6068
+ return String(value);
6069
+ }
6070
+ default:
6071
+ return fail ? fail(value) : void 0;
6021
6072
  }
6022
6073
  }
6023
6074
  function stringifySimple(key, value, stack) {
@@ -6101,11 +6152,17 @@ ${originalIndentation}`;
6101
6152
  return `{${res}}`;
6102
6153
  }
6103
6154
  case "number":
6104
- return isFinite(value) ? String(value) : "null";
6155
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
6105
6156
  case "boolean":
6106
6157
  return value === true ? "true" : "false";
6158
+ case "undefined":
6159
+ return void 0;
6107
6160
  case "bigint":
6108
- return bigint ? String(value) : void 0;
6161
+ if (bigint) {
6162
+ return String(value);
6163
+ }
6164
+ default:
6165
+ return fail ? fail(value) : void 0;
6109
6166
  }
6110
6167
  }
6111
6168
  function stringify2(value, replacer, space) {
@@ -7679,9 +7736,9 @@ var require_buffer_list = __commonJS({
7679
7736
  }
7680
7737
  });
7681
7738
 
7682
- // ../dx-logger-lib/node_modules/string_decoder/node_modules/safe-buffer/index.js
7739
+ // ../dx-logger-lib/node_modules/safe-buffer/index.js
7683
7740
  var require_safe_buffer = __commonJS({
7684
- "../dx-logger-lib/node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports, module2) {
7741
+ "../dx-logger-lib/node_modules/safe-buffer/index.js"(exports, module2) {
7685
7742
  var buffer = require("buffer");
7686
7743
  var Buffer2 = buffer.Buffer;
7687
7744
  function copyProps(src, dst) {
@@ -15052,7 +15109,7 @@ var require_tslib = __commonJS({
15052
15109
  function step(op) {
15053
15110
  if (f)
15054
15111
  throw new TypeError("Generator is already executing.");
15055
- while (_)
15112
+ while (g && (g = 0, op[0] && (_ = 0)), _)
15056
15113
  try {
15057
15114
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
15058
15115
  return t;
@@ -31175,14 +31232,13 @@ var Migrator = class {
31175
31232
  return row.id;
31176
31233
  });
31177
31234
  }
31178
- async applyMigration(migration, sql) {
31235
+ async doSqlMigration(migration, sql) {
31179
31236
  try {
31180
31237
  const result = await this.pool.query(sql);
31181
31238
  logger.info("Applying " + migration);
31182
31239
  if (result.rowCount !== void 0) {
31183
31240
  logger.info("affected rows", result.rowCount);
31184
31241
  }
31185
- await this.pool.query("insert into __migrations__ (id) values ($1)", [migration]);
31186
31242
  } catch (e) {
31187
31243
  logger.info("error occurred running migration", migration, e);
31188
31244
  throw e;
@@ -31252,11 +31308,24 @@ var Migrator = class {
31252
31308
  await this.runMigration(migration);
31253
31309
  }
31254
31310
  }
31311
+ async doScriptMigration(migration) {
31312
+ const migrationScript = import_path.default.join(this.migrationDir, migration);
31313
+ const migrationFunc = require(migrationScript);
31314
+ let callable;
31315
+ if (migrationFunc instanceof Function) {
31316
+ callable = migrationFunc;
31317
+ } else if (migrationFunc.default instanceof Function) {
31318
+ callable = migrationFunc.default;
31319
+ } else {
31320
+ throw new Error(`${migrationScript} isn't callable`);
31321
+ }
31322
+ await callable(this.pool, logger);
31323
+ }
31255
31324
  async runMigration(migration) {
31256
31325
  try {
31257
31326
  await this.pool.query("BEGIN");
31258
- const sql = await this.getSql(migration);
31259
- await this.applyMigration(migration, sql);
31327
+ await this.doMigrationWork(migration);
31328
+ await this.pool.query("insert into __migrations__ (id) values ($1)", [migration]);
31260
31329
  await this.pool.query("COMMIT");
31261
31330
  } catch (e) {
31262
31331
  logger.error("migration failed", migration, e);
@@ -31264,6 +31333,16 @@ var Migrator = class {
31264
31333
  throw e;
31265
31334
  }
31266
31335
  }
31336
+ async doMigrationWork(migration) {
31337
+ if (migration.endsWith(".sql")) {
31338
+ const sql = await this.getSql(migration);
31339
+ await this.doSqlMigration(migration, sql);
31340
+ } else if (migration.endsWith(".js")) {
31341
+ await this.doScriptMigration(migration);
31342
+ } else {
31343
+ throw new Error(`${migration} as an invalid migration extension`);
31344
+ }
31345
+ }
31267
31346
  dispose() {
31268
31347
  return this.pool.release();
31269
31348
  }