@squiz/db-lib 1.71.2 → 1.72.0
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +19 -0
- package/lib/AbstractRepository.d.ts +2 -0
- package/lib/AbstractRepository.d.ts.map +1 -0
- package/lib/AbstractRepository.integration.spec.d.ts +1 -0
- package/lib/AbstractRepository.integration.spec.d.ts.map +1 -0
- package/lib/AbstractRepository.integration.spec.js +118 -0
- package/lib/AbstractRepository.integration.spec.js.map +1 -0
- package/lib/AbstractRepository.js +187 -0
- package/lib/AbstractRepository.js.map +1 -0
- package/lib/ConnectionManager.d.ts +1 -0
- package/lib/ConnectionManager.d.ts.map +1 -0
- package/lib/ConnectionManager.js +58 -0
- package/lib/ConnectionManager.js.map +1 -0
- package/lib/Migrator.d.ts +1 -0
- package/lib/Migrator.d.ts.map +1 -0
- package/lib/Migrator.js +160 -0
- package/lib/Migrator.js.map +1 -0
- package/lib/PostgresErrorCodes.d.ts +1 -0
- package/lib/PostgresErrorCodes.d.ts.map +1 -0
- package/lib/PostgresErrorCodes.js +274 -0
- package/lib/PostgresErrorCodes.js.map +1 -0
- package/lib/Repositories.d.ts +1 -0
- package/lib/Repositories.d.ts.map +1 -0
- package/lib/Repositories.js +3 -0
- package/lib/Repositories.js.map +1 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.d.ts +50 -9
- package/lib/dynamodb/AbstractDynamoDbRepository.d.ts.map +1 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.js +456 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.js.map +1 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.spec.d.ts +1 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.spec.d.ts.map +1 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.spec.js +924 -0
- package/lib/dynamodb/AbstractDynamoDbRepository.spec.js.map +1 -0
- package/lib/dynamodb/DynamoDbManager.d.ts +1 -0
- package/lib/dynamodb/DynamoDbManager.d.ts.map +1 -0
- package/lib/dynamodb/DynamoDbManager.js +66 -0
- package/lib/dynamodb/DynamoDbManager.js.map +1 -0
- package/lib/dynamodb/getDynamoDbOptions.d.ts +1 -0
- package/lib/dynamodb/getDynamoDbOptions.d.ts.map +1 -0
- package/lib/dynamodb/getDynamoDbOptions.js +15 -0
- package/lib/dynamodb/getDynamoDbOptions.js.map +1 -0
- package/lib/error/DuplicateItemError.d.ts +1 -0
- package/lib/error/DuplicateItemError.d.ts.map +1 -0
- package/lib/error/DuplicateItemError.js +12 -0
- package/lib/error/DuplicateItemError.js.map +1 -0
- package/lib/error/InvalidDataFormatError.d.ts +1 -0
- package/lib/error/InvalidDataFormatError.d.ts.map +1 -0
- package/lib/error/InvalidDataFormatError.js +12 -0
- package/lib/error/InvalidDataFormatError.js.map +1 -0
- package/lib/error/InvalidDbSchemaError.d.ts +1 -0
- package/lib/error/InvalidDbSchemaError.d.ts.map +1 -0
- package/lib/error/InvalidDbSchemaError.js +12 -0
- package/lib/error/InvalidDbSchemaError.js.map +1 -0
- package/lib/error/MissingKeyValuesError.d.ts +1 -0
- package/lib/error/MissingKeyValuesError.d.ts.map +1 -0
- package/lib/error/MissingKeyValuesError.js +12 -0
- package/lib/error/MissingKeyValuesError.js.map +1 -0
- package/lib/error/TransactionError.d.ts +1 -0
- package/lib/error/TransactionError.d.ts.map +1 -0
- package/lib/error/TransactionError.js +12 -0
- package/lib/error/TransactionError.js.map +1 -0
- package/lib/getConnectionInfo.d.ts +1 -0
- package/lib/getConnectionInfo.d.ts.map +1 -0
- package/lib/getConnectionInfo.js +30 -0
- package/lib/getConnectionInfo.js.map +1 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +33 -70416
- package/lib/index.js.map +1 -7
- package/package.json +5 -5
- package/src/AbstractRepository.ts +26 -20
- package/src/dynamodb/AbstractDynamoDbRepository.spec.ts +289 -37
- package/src/dynamodb/AbstractDynamoDbRepository.ts +140 -31
- package/src/dynamodb/getDynamoDbOptions.ts +1 -1
- package/tsconfig.json +5 -2
- package/tsconfig.tsbuildinfo +1 -1
- package/build.js +0 -31
package/CHANGELOG.md
CHANGED
@@ -1,5 +1,24 @@
|
|
1
1
|
# Change Log
|
2
2
|
|
3
|
+
## 1.72.0
|
4
|
+
|
5
|
+
### Minor Changes
|
6
|
+
|
7
|
+
- 464fd13: add dynamodb support management api
|
8
|
+
|
9
|
+
### Patch Changes
|
10
|
+
|
11
|
+
- Updated dependencies [464fd13]
|
12
|
+
- @squiz/dx-common-lib@1.69.0
|
13
|
+
|
14
|
+
## 1.71.3
|
15
|
+
|
16
|
+
### Patch Changes
|
17
|
+
|
18
|
+
- 1187eec: manual bump of dx-common-lib version
|
19
|
+
- Updated dependencies [1187eec]
|
20
|
+
- @squiz/dx-common-lib@1.68.3
|
21
|
+
|
3
22
|
## 1.71.2
|
4
23
|
|
5
24
|
### Patch Changes
|
@@ -38,6 +38,7 @@ export declare abstract class AbstractRepository<SHAPE extends object, DATA_CLAS
|
|
38
38
|
new (data?: Record<string, unknown>): DATA_CLASS;
|
39
39
|
});
|
40
40
|
protected getConnection(): Promise<PoolClient>;
|
41
|
+
private sanitiseValue;
|
41
42
|
create(value: SHAPE, transactionClient?: PoolClient | null): Promise<SHAPE>;
|
42
43
|
update(where: Partial<SHAPE>, newValue: Exclude<Partial<SHAPE>, Record<string, never>>, transactionClient?: PoolClient | null): Promise<SHAPE[]>;
|
43
44
|
delete(where: Partial<SHAPE>, transactionClient?: PoolClient | null): Promise<number>;
|
@@ -53,3 +54,4 @@ export declare abstract class AbstractRepository<SHAPE extends object, DATA_CLAS
|
|
53
54
|
getCountRaw(whereClause?: string, values?: any[], tableRef?: string): Promise<number>;
|
54
55
|
getPageRaw(pageNumber: number, sortBy?: (keyof SHAPE)[], direction?: SortDirection, whereClause?: string, tableRef?: string, values?: any[], pageSize?: number | null, searchFields?: Partial<SHAPE> | null): Promise<PageResult<SHAPE>>;
|
55
56
|
}
|
57
|
+
//# sourceMappingURL=AbstractRepository.d.ts.map
|
@@ -0,0 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AW,GAAG,OAAO,CAAC,MAAM,CAAC;IASjG,UAAU,CACd,UAAU,EAAE,MAAM,EAClB,MAAM,GAAE,CAAC,MAAM,KAAK,CAAC,EAAO,EAC5B,SAAS,GAAE,aAAqB,EAChC,WAAW,GAAE,MAAW,EACxB,QAAQ,GAAE,MAAW,EACrB,MAAM,GAAE,GAAG,EAAO,EAClB,QAAQ,GAAE,MAAM,GAAG,IAAW,EAC9B,YAAY,GAAE,OAAO,CAAC,KAAK,CAAC,GAAG,IAAW,GACzC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;CAkD9B"}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"AbstractRepository.integration.spec.d.ts","sourceRoot":"","sources":["../src/AbstractRepository.integration.spec.ts"],"names":[],"mappings":""}
|
@@ -0,0 +1,118 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
const AbstractRepository_1 = require("./AbstractRepository");
|
4
|
+
const ConnectionManager_1 = require("./ConnectionManager");
|
5
|
+
class RepoTest {
|
6
|
+
constructor(data = {}) {
|
7
|
+
var _a, _b, _c, _d, _e, _f;
|
8
|
+
this.lowercase = (_a = data.lowercase) !== null && _a !== void 0 ? _a : 'some lowercase';
|
9
|
+
this.camelCase = (_b = data.camelCase) !== null && _b !== void 0 ? _b : 'some camelCase';
|
10
|
+
this.PascalCase = (_c = data.PascalCase) !== null && _c !== void 0 ? _c : 'some PascalCase';
|
11
|
+
this.snake_case = (_d = data.snake_case) !== null && _d !== void 0 ? _d : 'some snake_case';
|
12
|
+
this['kebab-case'] = (_e = data['kebab-case']) !== null && _e !== void 0 ? _e : 'some kebab-case';
|
13
|
+
this.UPPERCASE = (_f = data.UPPERCASE) !== null && _f !== void 0 ? _f : 'some UPPERCASE';
|
14
|
+
}
|
15
|
+
}
|
16
|
+
function defaultMapping() {
|
17
|
+
return {
|
18
|
+
lowercase: 'lowercase',
|
19
|
+
camelCase: 'camel_case',
|
20
|
+
PascalCase: 'pascal_case',
|
21
|
+
snake_case: 'snake_case',
|
22
|
+
'kebab-case': 'kebab_case',
|
23
|
+
UPPERCASE: 'uppercase',
|
24
|
+
};
|
25
|
+
}
|
26
|
+
const allProperties = Object.keys(defaultMapping());
|
27
|
+
class AbstractRepositoryIntegrationTest extends AbstractRepository_1.AbstractRepository {
|
28
|
+
}
|
29
|
+
describe('AbstractRepository', () => {
|
30
|
+
let db;
|
31
|
+
beforeAll(async () => {
|
32
|
+
db = new ConnectionManager_1.ConnectionManager('AbstractRepositoryIntegrationTest', process.env.COMPONENT_DB_CONNECTION_STRING, '', [], (db) => ({
|
33
|
+
test: new AbstractRepositoryIntegrationTest(db.repositories, db.pool, 'abstract_repository_db_test', defaultMapping(), RepoTest),
|
34
|
+
}));
|
35
|
+
await db.pool.query(`
|
36
|
+
CREATE TABLE IF NOT EXISTS abstract_repository_db_test (
|
37
|
+
lowercase text,
|
38
|
+
camel_case text,
|
39
|
+
pascal_case text,
|
40
|
+
snake_case text,
|
41
|
+
kebab_case text,
|
42
|
+
uppercase text
|
43
|
+
);
|
44
|
+
`);
|
45
|
+
});
|
46
|
+
afterAll(async () => {
|
47
|
+
await db.pool.query('DROP TABLE IF EXISTS abstract_repository_db_test;');
|
48
|
+
await db.close();
|
49
|
+
});
|
50
|
+
describe('properties are always mapped to columns', () => {
|
51
|
+
beforeEach(async () => {
|
52
|
+
await db.pool.query('DELETE FROM abstract_repository_db_test;');
|
53
|
+
});
|
54
|
+
it('create', async () => {
|
55
|
+
const repo = db.repositories.test;
|
56
|
+
const data = new RepoTest();
|
57
|
+
const result = await repo.create(data);
|
58
|
+
expect(result).toEqual(data);
|
59
|
+
});
|
60
|
+
it.each(allProperties)('update %s', async (property) => {
|
61
|
+
const repo = db.repositories.test;
|
62
|
+
const data = await repo.create(new RepoTest());
|
63
|
+
const result = await repo.update({ [property]: data[property] }, { [property]: `new ${data[property]}` });
|
64
|
+
expect(result).toEqual([{ ...data, [property]: `new ${data[property]}` }]);
|
65
|
+
});
|
66
|
+
it.each(allProperties)('delete %s', async (property) => {
|
67
|
+
const repo = db.repositories.test;
|
68
|
+
const data = await repo.create(new RepoTest());
|
69
|
+
const result = await repo.delete({ [property]: data[property] });
|
70
|
+
expect(result).toEqual(1);
|
71
|
+
});
|
72
|
+
it.each(allProperties)('findOne %s', async (property) => {
|
73
|
+
const repo = db.repositories.test;
|
74
|
+
const findData = await repo.create(new RepoTest({ [property]: 'some value' }));
|
75
|
+
const _differentData = await repo.create(new RepoTest({ [property]: 'some other value' }));
|
76
|
+
const result = await repo.findOne({ [property]: findData[property] });
|
77
|
+
expect(result).toEqual(findData);
|
78
|
+
});
|
79
|
+
it.each(allProperties)('find %s', async (property) => {
|
80
|
+
const repo = db.repositories.test;
|
81
|
+
const findData = await repo.create(new RepoTest({ [property]: 'some value' }));
|
82
|
+
const _differentData = await repo.create(new RepoTest({ [property]: 'some other value' }));
|
83
|
+
const result = await repo.find({ [property]: findData[property] });
|
84
|
+
expect(result).toEqual([findData]);
|
85
|
+
});
|
86
|
+
it.each(allProperties)('findAll %s', async (property) => {
|
87
|
+
const repo = db.repositories.test;
|
88
|
+
const findData = await repo.create(new RepoTest({ [property]: 'some value' }));
|
89
|
+
const differentData = await repo.create(new RepoTest({ [property]: 'some other value' }));
|
90
|
+
const result = await repo.findAll();
|
91
|
+
expect(result).toEqual([findData, differentData]);
|
92
|
+
});
|
93
|
+
it.each(allProperties)('getPage %s', async (property) => {
|
94
|
+
const repo = db.repositories.test;
|
95
|
+
const firstData = await repo.create(new RepoTest({ [property]: 'aaaaa' }));
|
96
|
+
const secondData = await repo.create(new RepoTest({ [property]: 'bbbb' }));
|
97
|
+
const ascResult = await repo.getPage(1, [property], 'asc');
|
98
|
+
expect(ascResult).toMatchObject({ items: [firstData, secondData], totalCount: 2 });
|
99
|
+
const descResult = await repo.getPage(1, [property], 'desc');
|
100
|
+
expect(descResult).toMatchObject({ items: [secondData, firstData], totalCount: 2 });
|
101
|
+
});
|
102
|
+
it.each(allProperties)('getPageRaw %s', async (property) => {
|
103
|
+
const repo = db.repositories.test;
|
104
|
+
const firstData = await repo.create(new RepoTest({ [property]: 'aaaaa' }));
|
105
|
+
const secondData = await repo.create(new RepoTest({ [property]: 'bbbb' }));
|
106
|
+
const ascResult = await repo.getPageRaw(1, [property], 'asc');
|
107
|
+
expect(ascResult).toMatchObject({ items: [firstData, secondData], totalCount: 2 });
|
108
|
+
const descResult = await repo.getPageRaw(1, [property], 'desc');
|
109
|
+
expect(descResult).toMatchObject({ items: [secondData, firstData], totalCount: 2 });
|
110
|
+
});
|
111
|
+
it.each(allProperties)('update Fails when new value is empty object - %s', async (property) => {
|
112
|
+
const repo = db.repositories.test;
|
113
|
+
const data = await repo.create(new RepoTest());
|
114
|
+
await expect(repo.update({ [property]: data[property] }, {})).rejects.toThrowErrorMatchingInlineSnapshot('"Failed updating the repository, update values cannot be empty"');
|
115
|
+
});
|
116
|
+
});
|
117
|
+
});
|
118
|
+
//# sourceMappingURL=AbstractRepository.integration.spec.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"AbstractRepository.integration.spec.js","sourceRoot":"","sources":["../src/AbstractRepository.integration.spec.ts"],"names":[],"mappings":";;AAAA,6DAA0D;AAC1D,2DAAwD;AAWxD,MAAM,QAAQ;IAQZ,YAAY,OAA2B,EAAE;;QACvC,IAAI,CAAC,SAAS,GAAG,MAAA,IAAI,CAAC,SAAS,mCAAI,gBAAgB,CAAC;QACpD,IAAI,CAAC,SAAS,GAAG,MAAA,IAAI,CAAC,SAAS,mCAAI,gBAAgB,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,MAAA,IAAI,CAAC,UAAU,mCAAI,iBAAiB,CAAC;QACvD,IAAI,CAAC,UAAU,GAAG,MAAA,IAAI,CAAC,UAAU,mCAAI,iBAAiB,CAAC;QACvD,IAAI,CAAC,YAAY,CAAC,GAAG,MAAA,IAAI,CAAC,YAAY,CAAC,mCAAI,iBAAi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AE,UAAU,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC;YACnF,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,CAAC;YAChE,MAAM,CAAC,UAAU,CAAC,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,CAAC,UAAU,EAAE,SAAS,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC,CAAC;QACtF,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,mDAAmD,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;YAC7F,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC;YAClC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,QAAQ,EAAE,CAAC,CAAC;YAC/C,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,kCAAkC,CACtG,iEAAiE,CAClE,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
@@ -0,0 +1,187 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.AbstractRepository = exports.DEFAULT_PAGE_SIZE = void 0;
|
4
|
+
const pg_1 = require("pg");
|
5
|
+
const dx_common_lib_1 = require("@squiz/dx-common-lib");
|
6
|
+
exports.DEFAULT_PAGE_SIZE = 20;
|
7
|
+
class AbstractRepository {
|
8
|
+
constructor(repositories, pool, tableName, mapping, classRef) {
|
9
|
+
this.repositories = repositories;
|
10
|
+
this.pool = pool;
|
11
|
+
this.classRef = classRef;
|
12
|
+
this.tableName = `"${tableName}"`;
|
13
|
+
this.modelPropertyToSqlColumn = mapping;
|
14
|
+
this.sqlColumnToModelProperty = Object.entries(mapping).reduce((prev, curr) => {
|
15
|
+
const [modelProp, columnName] = curr;
|
16
|
+
prev[columnName] = modelProp;
|
17
|
+
return prev;
|
18
|
+
}, {});
|
19
|
+
}
|
20
|
+
async getConnection() {
|
21
|
+
return await this.pool.connect();
|
22
|
+
}
|
23
|
+
sanitiseValue(value) {
|
24
|
+
const sanitisedValue = Object.entries(value)
|
25
|
+
.map(([key, value]) => [this.modelPropertyToSqlColumn[key], value])
|
26
|
+
.filter(([column, _v]) => !!column);
|
27
|
+
const columns = sanitisedValue.map(([column]) => (0, pg_1.escapeIdentifier)(column));
|
28
|
+
const bindingParams = sanitisedValue.map((_, index) => `$${index + 1}`);
|
29
|
+
const values = sanitisedValue.map(([_column, value]) => value);
|
30
|
+
return {
|
31
|
+
columns,
|
32
|
+
bindingParams,
|
33
|
+
values,
|
34
|
+
};
|
35
|
+
}
|
36
|
+
async create(value, transactionClient = null) {
|
37
|
+
const valueAsClass = new this.classRef(value);
|
38
|
+
const { columns, bindingParams, values } = this.sanitiseValue(valueAsClass);
|
39
|
+
const result = await this.executeQuery(`INSERT INTO ${this.tableName} (${columns.join(', ')}) VALUES (${bindingParams.join(', ')}) RETURNING *`, values, transactionClient);
|
40
|
+
return result[0];
|
41
|
+
}
|
42
|
+
async update(where, newValue, transactionClient = null) {
|
43
|
+
if (Object.keys(newValue).length === 0) {
|
44
|
+
throw new dx_common_lib_1.InvalidUpdateValueError('Failed updating the repository, update values cannot be empty');
|
45
|
+
}
|
46
|
+
const whereValues = Object.values(where);
|
47
|
+
const newValues = this.sanitiseValue(newValue);
|
48
|
+
const setValues = newValues.columns.map((c, i) => `${c} = ${newValues.bindingParams[i]}`);
|
49
|
+
const whereString = this.createWhereStringFromPartialModel(where, setValues.length);
|
50
|
+
const result = await this.executeQuery(`UPDATE ${this.tableName}
|
51
|
+
SET ${setValues.join(', ')}
|
52
|
+
WHERE ${whereString}
|
53
|
+
RETURNING *`, [...newValues.values, ...whereValues], transactionClient);
|
54
|
+
return result;
|
55
|
+
}
|
56
|
+
async delete(where, transactionClient = null) {
|
57
|
+
var _a;
|
58
|
+
const client = transactionClient !== null && transactionClient !== void 0 ? transactionClient : (await this.getConnection());
|
59
|
+
try {
|
60
|
+
const whereString = this.createWhereStringFromPartialModel(where);
|
61
|
+
const result = await client.query(`DELETE FROM ${this.tableName} WHERE ${whereString}`, Object.values(where));
|
62
|
+
return (_a = result.rowCount) !== null && _a !== void 0 ? _a : 0;
|
63
|
+
}
|
64
|
+
finally {
|
65
|
+
if (client && !transactionClient) {
|
66
|
+
client.release();
|
67
|
+
}
|
68
|
+
}
|
69
|
+
}
|
70
|
+
createWhereStringFromPartialModel(values, initialIndex = 0) {
|
71
|
+
const keys = Object.keys(values);
|
72
|
+
if (keys.length == 0) {
|
73
|
+
throw new Error(`Values cannot be an empty object. It must have at least one property`);
|
74
|
+
}
|
75
|
+
const sql = keys.reduce((acc, key, index) => {
|
76
|
+
const condition = `"${this.modelPropertyToSqlColumn[key]}" = $${1 + index + initialIndex}`;
|
77
|
+
return acc === '' ? `${acc} ${condition}` : `${acc} AND ${condition}`;
|
78
|
+
}, '');
|
79
|
+
return sql;
|
80
|
+
}
|
81
|
+
async executeQueryRaw(query, values, transactionClient = null) {
|
82
|
+
const client = transactionClient !== null && transactionClient !== void 0 ? transactionClient : (await this.getConnection());
|
83
|
+
try {
|
84
|
+
const result = await client.query(query, values);
|
85
|
+
return result.rows;
|
86
|
+
}
|
87
|
+
finally {
|
88
|
+
if (client && !transactionClient) {
|
89
|
+
client.release();
|
90
|
+
}
|
91
|
+
}
|
92
|
+
}
|
93
|
+
async executeQuery(query, values, transactionClient = null) {
|
94
|
+
const rows = await this.executeQueryRaw(query, values, transactionClient);
|
95
|
+
return rows.map((a) => this.createAndHydrateModel(a));
|
96
|
+
}
|
97
|
+
createAndHydrateModel(row) {
|
98
|
+
const inputData = {};
|
99
|
+
for (const key of Object.keys(row)) {
|
100
|
+
const translatedKey = this.sqlColumnToModelProperty[key];
|
101
|
+
inputData[translatedKey] = row[key];
|
102
|
+
}
|
103
|
+
return new this.classRef(inputData);
|
104
|
+
}
|
105
|
+
async findOne(item, transactionClient) {
|
106
|
+
const result = await this.executeQuery(`SELECT *
|
107
|
+
FROM ${this.tableName}
|
108
|
+
WHERE ${this.createWhereStringFromPartialModel(item)}
|
109
|
+
LIMIT 1`, Object.values(item), transactionClient);
|
110
|
+
return result[0];
|
111
|
+
}
|
112
|
+
async find(item) {
|
113
|
+
const result = await this.executeQuery(`SELECT *
|
114
|
+
FROM ${this.tableName}
|
115
|
+
WHERE ${this.createWhereStringFromPartialModel(item)}`, Object.values(item));
|
116
|
+
return result;
|
117
|
+
}
|
118
|
+
async findAll() {
|
119
|
+
const result = await this.executeQuery(`SELECT *
|
120
|
+
FROM ${this.tableName}`, []);
|
121
|
+
return result;
|
122
|
+
}
|
123
|
+
async getCount(item = null) {
|
124
|
+
let whereClause = '';
|
125
|
+
if (item) {
|
126
|
+
whereClause = `WHERE ${this.createWhereStringFromPartialModel(item)}`;
|
127
|
+
}
|
128
|
+
return this.getCountRaw(whereClause, item ? Object.values(item) : []);
|
129
|
+
}
|
130
|
+
async getPage(pageNumber, sortBy = [], direction = 'asc', pageSize = null, item = null) {
|
131
|
+
let whereClause = '';
|
132
|
+
if (item) {
|
133
|
+
whereClause = `WHERE ${this.createWhereStringFromPartialModel(item)}`;
|
134
|
+
}
|
135
|
+
return this.getPageRaw(pageNumber, sortBy, direction, whereClause, this.tableName, Object.values(item !== null && item !== void 0 ? item : {}), pageSize);
|
136
|
+
}
|
137
|
+
async getCountRaw(whereClause = '', values = [], tableRef = '') {
|
138
|
+
const result = await this.executeQueryRaw(`SELECT COUNT(*) FROM ${this.tableName} ${tableRef} ${whereClause}`, values);
|
139
|
+
return parseInt(result[0].count);
|
140
|
+
}
|
141
|
+
async getPageRaw(pageNumber, sortBy = [], direction = 'asc', whereClause = '', tableRef = '', values = [], pageSize = null, searchFields = null) {
|
142
|
+
if (pageSize === null) {
|
143
|
+
pageSize = exports.DEFAULT_PAGE_SIZE;
|
144
|
+
}
|
145
|
+
if (pageNumber <= 0) {
|
146
|
+
throw new Error(`Page number value cannot be less than 1`);
|
147
|
+
}
|
148
|
+
if (pageSize <= 0) {
|
149
|
+
throw new Error(`Page size value cannot be less than 1`);
|
150
|
+
}
|
151
|
+
let orderByClause = '';
|
152
|
+
if (sortBy.length) {
|
153
|
+
orderByClause = `ORDER BY ${sortBy
|
154
|
+
.map((a) => this.modelPropertyToSqlColumn[a])
|
155
|
+
.join(',')} ${direction}`;
|
156
|
+
}
|
157
|
+
const offset = (pageNumber - 1) * pageSize;
|
158
|
+
if (searchFields !== null) {
|
159
|
+
const searchFieldsWhere = [];
|
160
|
+
for (const [key, value] of Object.entries(searchFields)) {
|
161
|
+
if (typeof value !== 'string') {
|
162
|
+
throw new Error(`Search field ${key} needs to be of type string`);
|
163
|
+
}
|
164
|
+
searchFieldsWhere.push(`${this.modelPropertyToSqlColumn[key]} LIKE $${values.length + 1}`);
|
165
|
+
values.push(`%${value}%`);
|
166
|
+
}
|
167
|
+
if (whereClause.length) {
|
168
|
+
whereClause = `${whereClause} AND`;
|
169
|
+
}
|
170
|
+
whereClause = `${whereClause} (${searchFieldsWhere.join(' OR ')})`;
|
171
|
+
}
|
172
|
+
const query = `
|
173
|
+
SELECT *
|
174
|
+
FROM ${this.tableName} ${tableRef} ${whereClause} ${orderByClause}
|
175
|
+
OFFSET ${offset}
|
176
|
+
LIMIT ${pageSize}
|
177
|
+
`;
|
178
|
+
const items = await this.executeQuery(query, values);
|
179
|
+
return {
|
180
|
+
items,
|
181
|
+
totalCount: await this.getCountRaw(whereClause, values, tableRef),
|
182
|
+
pageSize,
|
183
|
+
};
|
184
|
+
}
|
185
|
+
}
|
186
|
+
exports.AbstractRepository = AbstractRepository;
|
187
|
+
//# sourceMappingURL=AbstractRepository.js.map
|
@@ -0,0 +1 @@
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jC,iBAAiB,EAAE,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC;IAyB9C,eAAe;IAOf,KAAK;IAKL,oBAAoB,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,MAAM,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAiBlG"}
|
@@ -0,0 +1,58 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.ConnectionManager = void 0;
|
4
|
+
const pg_1 = require("pg");
|
5
|
+
// import os from 'os';
|
6
|
+
const Migrator_1 = require("./Migrator");
|
7
|
+
class ConnectionManager {
|
8
|
+
constructor(applicationName, connection, migrationDirectory, migrationList, repositoryCreator) {
|
9
|
+
this.applicationName = applicationName;
|
10
|
+
this.migrationDirectory = migrationDirectory;
|
11
|
+
this.migrationList = migrationList;
|
12
|
+
let connectionInfo;
|
13
|
+
if (typeof connection === 'string') {
|
14
|
+
connectionInfo = { connectionString: connection };
|
15
|
+
}
|
16
|
+
else {
|
17
|
+
connectionInfo = connection;
|
18
|
+
}
|
19
|
+
this.pool = new pg_1.Pool({
|
20
|
+
...connectionInfo,
|
21
|
+
application_name: applicationName,
|
22
|
+
query_timeout: 5000, // TODO consider
|
23
|
+
// idleTimeoutMillis: 0, // TODO consider
|
24
|
+
// connectionTimeoutMillis: 2000,
|
25
|
+
// max: os.cpus().length * 2,
|
26
|
+
});
|
27
|
+
this.repositories = repositoryCreator(this);
|
28
|
+
}
|
29
|
+
async applyMigrations() {
|
30
|
+
const connection = await this.pool.connect();
|
31
|
+
const migrator = new Migrator_1.Migrator(this.migrationDirectory, this.migrationList, connection);
|
32
|
+
await migrator.migrate();
|
33
|
+
}
|
34
|
+
async close() {
|
35
|
+
await this.pool.end();
|
36
|
+
this.pool.removeAllListeners();
|
37
|
+
}
|
38
|
+
async executeInTransaction(func) {
|
39
|
+
const client = await this.pool.connect();
|
40
|
+
try {
|
41
|
+
await client.query('BEGIN');
|
42
|
+
const value = await func(client);
|
43
|
+
await client.query('COMMIT');
|
44
|
+
return value;
|
45
|
+
}
|
46
|
+
catch (e) {
|
47
|
+
await client.query('ROLLBACK');
|
48
|
+
throw e;
|
49
|
+
}
|
50
|
+
finally {
|
51
|
+
if (client) {
|
52
|
+
client.release();
|
53
|
+
}
|
54
|
+
}
|
55
|
+
}
|
56
|
+
}
|
57
|
+
exports.ConnectionManager = ConnectionManager;
|
58
|
+
//# sourceMappingURL=ConnectionManager.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"ConnectionManager.js","sourceRoot":"","sources":["../src/ConnectionManager.ts"],"names":[],"mappings":";;;AAAA,2BAA0B;AAE1B,uBAAuB;AACvB,yCAAsC;AAmBtC,MAAa,iBAAiB;IAI5B,YACY,eAAuB,EACjC,UAAiC,EACvB,kBAA0B,EAC1B,aAAuB,EACjC,iBAAyD;QAJ/C,oBAAe,GAAf,eAAe,CAAQ;QAEvB,uBAAkB,GAAlB,kBAAkB,CAAQ;QAC1B,kBAAa,GAAb,aAAa,CAAU;QAGjC,IAAI,cAAkD,CAAC;QAEvD,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE;YAClC,cAAc,GAAG,EAAE,gBAAgB,EAAE,UAAU,EAAE,CAAC;SACnD;aAAM;YACL,cAAc,GAAG,UAAU,CAAC;SAC7B;QAED,IAAI,CAAC,IAAI,GAAG,IAAI,SAAI,CAAC;YACnB,GAAG,cAAc;YAEjB,gBAAgB,EAAE,eAAe;YAEjC,aAAa,EAAE,IAAI,EAAE,gBAAgB;YACrC,yCAAyC;YACzC,iCAAiC;YAEjC,6BAA6B;SAC9B,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC9C,CAAC;IAEM,KAAK,CAAC,eAAe;QAC1B,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,O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F,qBAAa,QAAQ;IACP,SAAS,CAAC,YAAY,EAAE,MAAM;IAAE,SAAS,CAAC,aAAa,EAAE,MAAM,EAAE;IAAE,SAAS,CAAC,IAAI,EAAE,UAAU;gBAAnF,YAAY,EAAE,MAAM,EAAY,aAAa,EAAE,MAAM,EAAE,EAAY,IAAI,EAAE,UAAU;cAEzF,0BAA0B;cAI1B,oBAAoB;cASpB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM;cAc7C,UAAU,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE;cAiChE,MAAM,CAAC,SAAS,EAAE,MAAM;cAMxB,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC;cAMnC,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC;cAsBpB,aAAa;cAgBb,iBAAiB,CAAC,SAAS,EAAE,MAAM;cAkBnC,YAAY,CAAC,SAAS,EAAE,MAAM;cAe9B,eAAe,CAAC,SAAS,EAAE,MAAM;IAWjD,SAAS,CAAC,OAAO;CAGlB"}
|
package/lib/Migrator.js
ADDED
@@ -0,0 +1,160 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
exports.Migrator = void 0;
|
7
|
+
const promises_1 = __importDefault(require("fs/promises"));
|
8
|
+
const path_1 = __importDefault(require("path"));
|
9
|
+
const os_1 = __importDefault(require("os"));
|
10
|
+
const dx_logger_lib_1 = require("@squiz/dx-logger-lib");
|
11
|
+
// Be carful about changing this value. This needs to be consistent across deployments
|
12
|
+
// this ID is used to signal other running instances that a migration is executing.
|
13
|
+
const MIGRATION_ADVISORY_LOCK = 4569465;
|
14
|
+
const logger = (0, dx_logger_lib_1.getLogger)({ name: 'db-migrator', meta: { pid: process.pid, hostname: os_1.default.hostname() } });
|
15
|
+
class Migrator {
|
16
|
+
constructor(migrationDir, migrationList, pool) {
|
17
|
+
this.migrationDir = migrationDir;
|
18
|
+
this.migrationList = migrationList;
|
19
|
+
this.pool = pool;
|
20
|
+
}
|
21
|
+
async ensureMigrationTableExists() {
|
22
|
+
return this.pool.query('create table if not exists "__migrations__" (id varchar(128) NOT NULL)');
|
23
|
+
}
|
24
|
+
async getAppliedMigrations() {
|
25
|
+
await this.ensureMigrationTableExists();
|
26
|
+
const result = await this.pool.query('select * from __migrations__');
|
27
|
+
return result.rows.map(function (row) {
|
28
|
+
return row.id;
|
29
|
+
});
|
30
|
+
}
|
31
|
+
async doSqlMigration(migration, sql) {
|
32
|
+
try {
|
33
|
+
const result = await this.pool.query(sql);
|
34
|
+
logger.info('Applying ' + migration);
|
35
|
+
if (result.rowCount !== undefined) {
|
36
|
+
logger.info('affected rows', result.rowCount);
|
37
|
+
}
|
38
|
+
}
|
39
|
+
catch (e) {
|
40
|
+
logger.info('error occurred running migration', migration, e);
|
41
|
+
throw e;
|
42
|
+
}
|
43
|
+
}
|
44
|
+
async getPending(migrationsList, appliedMigrations) {
|
45
|
+
const pending = [];
|
46
|
+
// get all migrations
|
47
|
+
for (let i = 0; i < migrationsList.length; i++) {
|
48
|
+
if (migrationsList[i] !== appliedMigrations[i]) {
|
49
|
+
pending.push(migrationsList[i]);
|
50
|
+
}
|
51
|
+
}
|
52
|
+
// validate order
|
53
|
+
for (let i = 0; i < pending.length; i++) {
|
54
|
+
if (appliedMigrations.includes(pending[i])) {
|
55
|
+
throw new Error(`${pending[i]} has already run. Are you sure your migrations are in the correct order.`);
|
56
|
+
}
|
57
|
+
}
|
58
|
+
// check the migration list is the right one (based on applied migrations on the db)
|
59
|
+
for (let i = 0; i < migrationsList.length; i++) {
|
60
|
+
if (migrationsList[i] !== appliedMigrations[i] && appliedMigrations[i] !== undefined) {
|
61
|
+
throw new Error(`Migration #${i + 1} ${migrationsList[i]} on the migration list does not match with the applied migration ${appliedMigrations[i]}. Are you sure your migrations are running in the correct DB? Migration list: [${migrationsList.join(', ')}], Applied migrations: [${appliedMigrations.join(', ')}]`);
|
62
|
+
}
|
63
|
+
}
|
64
|
+
return pending;
|
65
|
+
}
|
66
|
+
async getSql(migration) {
|
67
|
+
const sql = await promises_1.default.readFile(path_1.default.join(this.migrationDir, migration), { encoding: 'utf-8' });
|
68
|
+
return sql;
|
69
|
+
}
|
70
|
+
async tryToObtainLock() {
|
71
|
+
const result = await this.pool.query(`SELECT pg_try_advisory_lock(${MIGRATION_ADVISORY_LOCK}) as lockobtained`);
|
72
|
+
return result.rows[0].lockobtained;
|
73
|
+
}
|
74
|
+
async releaseLock() {
|
75
|
+
await this.pool.query(`SELECT pg_advisory_unlock(${MIGRATION_ADVISORY_LOCK}) lockreleased`);
|
76
|
+
}
|
77
|
+
async migrate() {
|
78
|
+
try {
|
79
|
+
const lockObtained = await this.tryToObtainLock();
|
80
|
+
if (lockObtained === false) {
|
81
|
+
logger.info('migration already running');
|
82
|
+
await sleep(500);
|
83
|
+
return await this.migrate();
|
84
|
+
}
|
85
|
+
await this.runMigrations();
|
86
|
+
logger.info('completed migration');
|
87
|
+
await this.releaseLock();
|
88
|
+
this.dispose();
|
89
|
+
}
|
90
|
+
catch (e) {
|
91
|
+
logger.info('migration failed releasing lock');
|
92
|
+
await this.releaseLock();
|
93
|
+
throw e;
|
94
|
+
}
|
95
|
+
}
|
96
|
+
async runMigrations() {
|
97
|
+
const appliedMigrations = await this.getAppliedMigrations();
|
98
|
+
const pending = await this.getPending(this.migrationList, appliedMigrations);
|
99
|
+
if (pending.length === 0) {
|
100
|
+
logger.info('No pending migrations');
|
101
|
+
return;
|
102
|
+
}
|
103
|
+
logger.info('Pending migrations:\n\t' + pending.join('\n\t'));
|
104
|
+
for (const migration of pending) {
|
105
|
+
await this.runMigration(migration);
|
106
|
+
}
|
107
|
+
}
|
108
|
+
async doScriptMigration(migration) {
|
109
|
+
const migrationScript = path_1.default.join(this.migrationDir, migration);
|
110
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
111
|
+
const migrationFunc = require(migrationScript);
|
112
|
+
// eslint-disable-next-line @typescript-eslint/ban-types
|
113
|
+
let callable;
|
114
|
+
if (migrationFunc instanceof Function) {
|
115
|
+
callable = migrationFunc;
|
116
|
+
}
|
117
|
+
else if (migrationFunc.default instanceof Function) {
|
118
|
+
callable = migrationFunc.default;
|
119
|
+
}
|
120
|
+
else {
|
121
|
+
throw new Error(`${migrationScript} isn't callable`);
|
122
|
+
}
|
123
|
+
await callable(this.pool, logger);
|
124
|
+
}
|
125
|
+
async runMigration(migration) {
|
126
|
+
try {
|
127
|
+
await this.pool.query('BEGIN');
|
128
|
+
await this.doMigrationWork(migration);
|
129
|
+
await this.pool.query('insert into __migrations__ (id) values ($1)', [migration]);
|
130
|
+
await this.pool.query('COMMIT');
|
131
|
+
}
|
132
|
+
catch (e) {
|
133
|
+
logger.error('migration failed', migration, e);
|
134
|
+
await this.pool.query('ROLLBACK');
|
135
|
+
throw e;
|
136
|
+
}
|
137
|
+
}
|
138
|
+
async doMigrationWork(migration) {
|
139
|
+
if (migration.endsWith('.sql')) {
|
140
|
+
const sql = await this.getSql(migration);
|
141
|
+
await this.doSqlMigration(migration, sql);
|
142
|
+
}
|
143
|
+
else if (migration.endsWith('.js')) {
|
144
|
+
await this.doScriptMigration(migration);
|
145
|
+
}
|
146
|
+
else {
|
147
|
+
throw new Error(`${migration} as an invalid migration extension`);
|
148
|
+
}
|
149
|
+
}
|
150
|
+
dispose() {
|
151
|
+
return this.pool.release();
|
152
|
+
}
|
153
|
+
}
|
154
|
+
exports.Migrator = Migrator;
|
155
|
+
async function sleep(timeMs) {
|
156
|
+
return new Promise((resolve) => {
|
157
|
+
setTimeout(resolve, timeMs);
|
158
|
+
});
|
159
|
+
}
|
160
|
+
//# sourceMappingURL=Migrator.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3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