sedentary-pg 0.0.43 → 0.0.44

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.
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.adsrc = void 0;
4
+ // cspell: disable-next-line
5
+ function adsrc(version) {
6
+ // cspell: disable-next-line
7
+ return version >= 12 ? "pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS adsrc" : "adsrc";
8
+ }
9
+ exports.adsrc = adsrc;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SedentaryPG = exports.TransactionPG = exports.Type = exports.EntryBase = void 0;
4
+ const sedentary_1 = require("sedentary");
5
+ const pgdb_1 = require("./pgdb");
6
+ var sedentary_2 = require("sedentary");
7
+ Object.defineProperty(exports, "EntryBase", { enumerable: true, get: function () { return sedentary_2.EntryBase; } });
8
+ Object.defineProperty(exports, "Type", { enumerable: true, get: function () { return sedentary_2.Type; } });
9
+ var pgdb_2 = require("./pgdb");
10
+ Object.defineProperty(exports, "TransactionPG", { enumerable: true, get: function () { return pgdb_2.TransactionPG; } });
11
+ class SedentaryPG extends sedentary_1.Sedentary {
12
+ constructor(connection, options) {
13
+ super(options);
14
+ if (!(connection instanceof Object))
15
+ throw new Error("SedentaryPG.constructor: 'connection' argument: Wrong type, expected 'Object'");
16
+ this.db = new pgdb_1.PGDB(connection, this.log);
17
+ }
18
+ FKey(attribute, options) {
19
+ const { attributeName, modelName, unique } = attribute;
20
+ if (!unique)
21
+ throw new Error(`SedentaryPG.FKey: '${modelName}' model: '${attributeName}' attribute: is not unique: can't be used as FKey target`);
22
+ return super.FKey(attribute, options);
23
+ }
24
+ begin() {
25
+ return this.db.begin();
26
+ }
27
+ client() {
28
+ return this.db.client();
29
+ }
30
+ }
31
+ exports.SedentaryPG = SedentaryPG;
@@ -0,0 +1,521 @@
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.TransactionPG = exports.PGDB = void 0;
7
+ const pg_1 = require("pg");
8
+ const pg_format_1 = __importDefault(require("pg-format"));
9
+ const sedentary_1 = require("sedentary");
10
+ const adsrc_1 = require("./adsrc");
11
+ const needDrop = [
12
+ ["DATETIME", "int2"],
13
+ ["DATETIME", "int4"],
14
+ ["DATETIME", "int8"],
15
+ ["DATETIME", "numeric"],
16
+ ["INT", "json"],
17
+ ["INT", "timestamptz"],
18
+ ["INT8", "json"],
19
+ ["INT8", "timestamptz"],
20
+ ["JSON", "int2"],
21
+ ["JSON", "int4"],
22
+ ["JSON", "int8"],
23
+ ["JSON", "numeric"],
24
+ ["NUMBER", "json"],
25
+ ["NUMBER", "timestamptz"]
26
+ ];
27
+ const needUsing = [
28
+ ["BOOLEAN", "varchar"],
29
+ ["DATETIME", "varchar"],
30
+ ["INT", "varchar"],
31
+ ["INT8", "varchar"],
32
+ ["JSON", "varchar"],
33
+ ["NUMBER", "varchar"]
34
+ ];
35
+ const types = { bool: "BOOL", int2: "SMALLINT", int4: "INTEGER", int8: "BIGINT", json: "JSON", numeric: "NUMERIC", timestamptz: "DATETIME", varchar: "VARCHAR" };
36
+ const actions = { cascade: "c", "no action": "a", restrict: "r", "set default": "d", "set null": "n" };
37
+ function parseInt8(value) {
38
+ return BigInt(value);
39
+ }
40
+ function parseNumber(value) {
41
+ return parseFloat(value);
42
+ }
43
+ pg_1.types.setTypeParser(20, parseInt8);
44
+ pg_1.types.setTypeParser(1700, parseNumber);
45
+ class PGDB extends sedentary_1.DB {
46
+ constructor(connection, log) {
47
+ super(log);
48
+ this._client = {};
49
+ this.indexes = [];
50
+ this.oidLoad = {};
51
+ this.released = false;
52
+ this.version = 0;
53
+ this.pool = new pg_1.Pool(connection);
54
+ }
55
+ async connect() {
56
+ this._client = await this.pool.connect();
57
+ const res = await this._client.query("SELECT version()");
58
+ this.version = parseInt(res.rows[0].version.split(" ")[1].split(".")[0], 10);
59
+ }
60
+ async end() {
61
+ if (!this.released)
62
+ this._client.release();
63
+ await this.pool.end();
64
+ }
65
+ defaultNeq(src, value) {
66
+ if (src === value)
67
+ return false;
68
+ return src.split("::")[0] !== value;
69
+ }
70
+ async begin() {
71
+ const ret = new TransactionPG(this.log, await this.pool.connect());
72
+ this.log("BEGIN");
73
+ await ret._client.query("BEGIN");
74
+ return ret;
75
+ }
76
+ async client() {
77
+ return await this.pool.connect();
78
+ }
79
+ escape(value) {
80
+ if (value === null || value === undefined)
81
+ throw new Error("SedentaryPG: Can't escape null nor undefined values; use the 'IS NULL' operator instead");
82
+ if (typeof value === "boolean" || typeof value === "number")
83
+ return value.toString();
84
+ if (typeof value === "string")
85
+ return (0, pg_format_1.default)("%L", value);
86
+ //if(value instanceof Date)
87
+ return (0, pg_format_1.default)("%L", value).replace(/\.\d\d\d\+/, "+");
88
+ //return format("%L", JSON.stringify(value));
89
+ }
90
+ fill(attributes, row, entry) {
91
+ const loaded = {};
92
+ for (const attribute in attributes)
93
+ entry[attribute] = loaded[attribute] = row[attributes[attribute]];
94
+ Object.defineProperty(entry, "loaded", { configurable: true, value: loaded });
95
+ }
96
+ load(tableName, attributes, pk, model, table) {
97
+ const pkFldName = pk.fieldName;
98
+ return async (where, order, limit, tx, lock) => {
99
+ const { oid } = table;
100
+ const ret = [];
101
+ const client = tx ? tx._client : await this.pool.connect();
102
+ const oidPK = {};
103
+ try {
104
+ const forUpdate = lock ? " FOR UPDATE" : "";
105
+ const orderBy = order && order.length ? ` ORDER BY ${(typeof order === "string" ? [order] : order).map(_ => (_.startsWith("-") ? `${_.substring(1)} DESC` : _)).join(",")}` : "";
106
+ const limitTo = typeof limit === "number" ? ` LIMIT ${limit}` : "";
107
+ const query = `SELECT *, tableoid FROM ${tableName}${where ? ` WHERE ${where}` : ""}${orderBy}${limitTo}${forUpdate}`;
108
+ this.log(query);
109
+ const res = await client.query(query);
110
+ for (const row of res.rows) {
111
+ if (row.tableoid === oid) {
112
+ const entry = new model("load");
113
+ this.fill(attributes, row, entry);
114
+ if (tx)
115
+ tx.addEntry(entry);
116
+ ret.push(entry);
117
+ entry.postLoad();
118
+ }
119
+ else {
120
+ if (!oidPK[row.tableoid])
121
+ oidPK[row.tableoid] = [];
122
+ oidPK[row.tableoid].push([ret.length, row[pkFldName]]);
123
+ ret.push(null);
124
+ }
125
+ }
126
+ for (const oid in oidPK) {
127
+ const res = await this.oidLoad[oid](oidPK[oid].map(_ => _[1]));
128
+ for (const entry of res)
129
+ for (const [id, pk] of oidPK[oid])
130
+ if (pk === entry[pkFldName])
131
+ ret[id] = entry;
132
+ }
133
+ }
134
+ finally {
135
+ if (!tx)
136
+ client.release();
137
+ }
138
+ return ret;
139
+ };
140
+ }
141
+ remove(tableName, pk) {
142
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
143
+ const self = this;
144
+ const pkAttrName = pk.attributeName;
145
+ const pkFldName = pk.fieldName;
146
+ return async function () {
147
+ const client = this.tx ? this.tx._client : await self.pool.connect();
148
+ let removed = false;
149
+ try {
150
+ const query = `DELETE FROM ${tableName} WHERE ${pkFldName} = ${self.escape(this[pkAttrName])}`;
151
+ self.log(query);
152
+ removed = (await client.query(query)).rowCount === 1;
153
+ }
154
+ finally {
155
+ if (!this.tx)
156
+ client.release();
157
+ }
158
+ return removed;
159
+ };
160
+ }
161
+ save(tableName, attributes, pk) {
162
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
163
+ const self = this;
164
+ const pkAttrName = pk.attributeName;
165
+ const pkFldName = pk.fieldName;
166
+ return async function () {
167
+ const client = this.tx ? this.tx._client : await self.pool.connect();
168
+ let changed = false;
169
+ try {
170
+ const { loaded } = this;
171
+ if (loaded) {
172
+ const actions = [];
173
+ for (const attribute in attributes) {
174
+ const value = this[attribute];
175
+ if (value !== loaded[attribute])
176
+ actions.push(`${attributes[attribute]} = ${self.escape(value)}`);
177
+ }
178
+ if (actions.length) {
179
+ const query = `UPDATE ${tableName} SET ${actions.join(", ")} WHERE ${pkFldName} = ${self.escape(this[pkAttrName])}`;
180
+ self.log(query);
181
+ self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
182
+ changed = true;
183
+ }
184
+ }
185
+ else {
186
+ const fields = [];
187
+ const values = [];
188
+ for (const attribute in attributes) {
189
+ const value = this[attribute];
190
+ if (value !== null && value !== undefined) {
191
+ fields.push(attributes[attribute]);
192
+ values.push(self.escape(value));
193
+ }
194
+ }
195
+ const query = fields.length ? `INSERT INTO ${tableName} (${fields.join(", ")}) VALUES (${values.join(", ")})` : `INSERT INTO ${tableName} DEFAULT VALUES`;
196
+ self.log(query);
197
+ self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
198
+ changed = true;
199
+ }
200
+ }
201
+ finally {
202
+ if (!this.tx)
203
+ client.release();
204
+ }
205
+ return changed;
206
+ };
207
+ }
208
+ async dropConstraints(table) {
209
+ const indexes = [];
210
+ const res = await this._client.query("SELECT confdeltype, confupdtype, conindid, conname, contype FROM pg_constraint WHERE conrelid = $1 ORDER BY conname", [table.oid]);
211
+ for (const row of res.rows) {
212
+ const arr = table.constraints.filter(_ => _.constraintName === row.conname && _.type === row.contype);
213
+ let drop = false;
214
+ if (arr.length === 0)
215
+ drop = true;
216
+ else if (row.contype === "u")
217
+ indexes.push(row.conindid);
218
+ else {
219
+ const { options } = arr[0].attribute.foreignKey;
220
+ if (actions[options.onDelete] !== row.confdeltype || actions[options.onUpdate] !== row.confupdtype)
221
+ drop = true;
222
+ }
223
+ if (drop) {
224
+ const statement = `ALTER TABLE ${table.tableName} DROP CONSTRAINT ${row.conname} CASCADE`;
225
+ this.syncLog(statement);
226
+ if (this.sync)
227
+ await this._client.query(statement);
228
+ }
229
+ }
230
+ return indexes;
231
+ }
232
+ async dropField(tableName, fieldName) {
233
+ const statement = `ALTER TABLE ${tableName} DROP COLUMN ${fieldName}`;
234
+ this.syncLog(statement);
235
+ if (this.sync)
236
+ await this._client.query(statement);
237
+ }
238
+ async dropFields(table) {
239
+ const res = await this._client.query("SELECT attname FROM pg_attribute WHERE attrelid = $1 AND attnum > 0 AND attisdropped = false AND attinhcount = 0", [table.oid]);
240
+ for (const i in res.rows)
241
+ if (!table.findField(res.rows[i].attname))
242
+ await this.dropField(table.tableName, res.rows[i].attname);
243
+ }
244
+ async dropIndexes(table, constraintIndexes) {
245
+ const { indexes, oid } = table;
246
+ const iObject = {};
247
+ const res = await this._client.query("SELECT amname, attname, indexrelid, indisunique, relname FROM pg_class, pg_index, pg_attribute, pg_am WHERE indrelid = $1 AND indexrelid = pg_class.oid AND attrelid = pg_class.oid AND relam = pg_am.oid ORDER BY attnum", [oid]);
248
+ for (const row of res.rows) {
249
+ const { amname, attname, indexrelid, indisunique, relname } = row;
250
+ if (!constraintIndexes.includes(indexrelid)) {
251
+ if (iObject[relname])
252
+ iObject[relname].fields.push(attname);
253
+ else
254
+ iObject[relname] = { fields: [attname], indexName: relname, type: amname, unique: indisunique };
255
+ }
256
+ }
257
+ this.indexes = [];
258
+ for (const index of indexes) {
259
+ const { indexName } = index;
260
+ if (iObject[indexName] && this.indexesEq(index, iObject[indexName])) {
261
+ this.indexes.push(indexName);
262
+ delete iObject[indexName];
263
+ }
264
+ }
265
+ for (const index of Object.keys(iObject).sort()) {
266
+ const statement = `DROP INDEX ${index}`;
267
+ this.syncLog(statement);
268
+ if (this.sync)
269
+ await this._client.query(statement);
270
+ }
271
+ }
272
+ async syncConstraints(table) {
273
+ for (const constraint of table.constraints) {
274
+ const { attribute, constraintName, type } = constraint;
275
+ const res = await this._client.query("SELECT attname FROM pg_attribute, pg_constraint WHERE attrelid = $1 AND conrelid = $1 AND attnum = conkey[1] AND attname = $2", [
276
+ table.oid,
277
+ attribute.fieldName
278
+ ]);
279
+ if (!res.rowCount) {
280
+ let query;
281
+ if (type === "f") {
282
+ const { fieldName, options, tableName } = attribute.foreignKey;
283
+ const onDelete = options.onDelete !== "no action" ? ` ON DELETE ${options.onDelete.toUpperCase()}` : "";
284
+ const onUpdate = options.onUpdate !== "no action" ? ` ON UPDATE ${options.onUpdate.toUpperCase()}` : "";
285
+ query = `FOREIGN KEY (${attribute.fieldName}) REFERENCES ${tableName}(${fieldName})${onDelete}${onUpdate}`;
286
+ }
287
+ else
288
+ query = `UNIQUE(${attribute.fieldName})`;
289
+ const statement = `ALTER TABLE ${table.tableName} ADD CONSTRAINT ${constraintName} ${query}`;
290
+ this.syncLog(statement);
291
+ if (this.sync)
292
+ await this._client.query(statement);
293
+ }
294
+ }
295
+ }
296
+ async syncDataBase() {
297
+ try {
298
+ await super.syncDataBase();
299
+ for (const table of this.tables)
300
+ this.oidLoad[table.oid || 0] = (ids) => table.model.load({ [table.pk.attributeName]: ["IN", ids] });
301
+ }
302
+ catch (e) {
303
+ throw e;
304
+ }
305
+ finally {
306
+ this.released = true;
307
+ this._client.release();
308
+ }
309
+ }
310
+ fieldType(attribute) {
311
+ const { size, type } = attribute;
312
+ let ret;
313
+ switch (type) {
314
+ case "BOOLEAN":
315
+ return ["BOOL", "BOOL"];
316
+ case "DATETIME":
317
+ return ["DATETIME", "TIMESTAMP (3) WITH TIME ZONE"];
318
+ case "INT":
319
+ ret = size === 2 ? "SMALLINT" : "INTEGER";
320
+ return [ret, ret];
321
+ case "INT8":
322
+ return ["BIGINT", "BIGINT"];
323
+ case "JSON":
324
+ return ["JSON", "JSON"];
325
+ case "NUMBER":
326
+ return ["NUMERIC", "NUMERIC"];
327
+ case "VARCHAR":
328
+ return ["VARCHAR", "VARCHAR" + (size ? `(${size})` : "")];
329
+ }
330
+ throw new Error(`Unknown type: '${type}', '${size}'`);
331
+ }
332
+ async syncFields(table) {
333
+ const { attributes, autoIncrement, oid, tableName } = table;
334
+ for (const attribute of attributes) {
335
+ const { fieldName, notNull, size } = attribute;
336
+ const defaultValue = attribute.defaultValue === undefined ? (autoIncrement && fieldName === "id" ? `nextval('${tableName}_id_seq'::regclass)` : undefined) : this.escape(attribute.defaultValue);
337
+ const [base, type] = this.fieldType(attribute);
338
+ const where = "attrelid = $1 AND attnum > 0 AND atttypid = pg_type.oid AND attislocal = 't' AND attname = $2";
339
+ const res = await this._client.query(`SELECT attnotnull, atttypmod, typname, ${(0, adsrc_1.adsrc)(this.version)} FROM pg_type, pg_attribute LEFT JOIN pg_attrdef ON adrelid = attrelid AND adnum = attnum WHERE ${where}`, [oid, fieldName]);
340
+ const addField = async () => {
341
+ const statement = `ALTER TABLE ${tableName} ADD COLUMN ${fieldName} ${type}`;
342
+ this.syncLog(statement);
343
+ if (this.sync)
344
+ await this._client.query(statement);
345
+ };
346
+ const dropDefault = async () => {
347
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} DROP DEFAULT`;
348
+ this.syncLog(statement);
349
+ if (this.sync)
350
+ await this._client.query(statement);
351
+ };
352
+ const setNotNull = async (isNotNull) => {
353
+ if (isNotNull === notNull)
354
+ return;
355
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} ${notNull ? "SET" : "DROP"} NOT NULL`;
356
+ this.syncLog(statement);
357
+ if (this.sync)
358
+ await this._client.query(statement);
359
+ };
360
+ const setDefault = async (isNotNull) => {
361
+ if (defaultValue !== undefined) {
362
+ let statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} SET DEFAULT ${defaultValue}`;
363
+ this.syncLog(statement);
364
+ if (this.sync)
365
+ await this._client.query(statement);
366
+ if (notNull && !isNotNull) {
367
+ statement = `UPDATE ${tableName} SET ${fieldName} = ${defaultValue} WHERE ${fieldName} IS NULL`;
368
+ this.syncLog(statement);
369
+ if (this.sync)
370
+ this._client.query(statement);
371
+ }
372
+ }
373
+ await setNotNull(isNotNull);
374
+ };
375
+ if (!res.rowCount) {
376
+ await addField();
377
+ await setDefault(false);
378
+ }
379
+ else {
380
+ const { adsrc, attnotnull, atttypmod, typname } = res.rows[0];
381
+ if (types[typname] !== base || (base === "VARCHAR" && (size ? size + 4 !== atttypmod : atttypmod !== -1))) {
382
+ if (needDrop.some(([type, name]) => attribute.type === type && typname === name)) {
383
+ await this.dropField(tableName, fieldName);
384
+ await addField();
385
+ await setDefault(false);
386
+ }
387
+ else {
388
+ if (adsrc)
389
+ dropDefault();
390
+ const using = needUsing.some(([type, name]) => attribute.type === type && typname === name) ? " USING " + fieldName + "::" + type : "";
391
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} TYPE ${type}${using}`;
392
+ this.syncLog(statement);
393
+ if (this.sync)
394
+ await this._client.query(statement);
395
+ await setDefault(attnotnull);
396
+ }
397
+ }
398
+ else if (defaultValue === undefined) {
399
+ if (adsrc)
400
+ dropDefault();
401
+ await setNotNull(attnotnull);
402
+ }
403
+ else if (!adsrc || this.defaultNeq(adsrc, defaultValue))
404
+ await setDefault(attnotnull);
405
+ }
406
+ }
407
+ }
408
+ async syncIndexes(table) {
409
+ const { indexes, tableName } = table;
410
+ for (const index of indexes) {
411
+ const { fields, indexName, type, unique } = index;
412
+ if (!this.indexes.includes(indexName)) {
413
+ const statement = `CREATE${unique ? " UNIQUE" : ""} INDEX ${indexName} ON ${tableName} USING ${type} (${fields.join(", ")})`;
414
+ this.syncLog(statement);
415
+ if (this.sync)
416
+ await this._client.query(statement);
417
+ }
418
+ }
419
+ }
420
+ async syncSequence(table) {
421
+ if (!table.autoIncrementOwn)
422
+ return;
423
+ const statement = `ALTER SEQUENCE ${table.tableName}_id_seq OWNED BY ${table.tableName}.id`;
424
+ this.syncLog(statement);
425
+ if (this.sync)
426
+ await this._client.query(statement);
427
+ }
428
+ async syncTable(table) {
429
+ if (table.autoIncrement) {
430
+ await (async () => {
431
+ try {
432
+ await this._client.query(`SELECT currval('${table.tableName}_id_seq')`);
433
+ }
434
+ catch (e) {
435
+ if (e instanceof pg_1.DatabaseError && e.code === "55000")
436
+ return;
437
+ if (e instanceof pg_1.DatabaseError && e.code === "42P01") {
438
+ const statement = `CREATE SEQUENCE ${table.tableName}_id_seq`;
439
+ this.syncLog(statement);
440
+ if (this.sync)
441
+ await this._client.query(statement);
442
+ table.autoIncrementOwn = true;
443
+ return;
444
+ }
445
+ throw e;
446
+ }
447
+ })();
448
+ }
449
+ let create = false;
450
+ const resTable = await this._client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
451
+ if (resTable.rowCount) {
452
+ table.oid = resTable.rows[0].oid;
453
+ let drop = false;
454
+ const resParent = await this._client.query("SELECT inhparent FROM pg_inherits WHERE inhrelid = $1", [table.oid]);
455
+ if (resParent.rowCount) {
456
+ if (!table.parent)
457
+ drop = true;
458
+ else if (this.findTable(table.parent.tableName).oid === resParent.rows[0].inhparent)
459
+ return;
460
+ drop = true;
461
+ }
462
+ else if (table.parent)
463
+ drop = true;
464
+ if (drop) {
465
+ const statement = `DROP TABLE ${table.tableName} CASCADE`;
466
+ create = true;
467
+ this.syncLog(statement);
468
+ if (this.sync)
469
+ await this._client.query(statement);
470
+ }
471
+ }
472
+ else
473
+ create = true;
474
+ if (create) {
475
+ const parent = table.parent ? ` INHERITS (${table.parent.tableName})` : "";
476
+ const statement = `CREATE TABLE ${table.tableName} ()${parent}`;
477
+ this.syncLog(statement);
478
+ if (this.sync)
479
+ await this._client.query(statement);
480
+ const resTable = await this._client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
481
+ table.oid = resTable.rows[0]?.oid;
482
+ }
483
+ }
484
+ }
485
+ exports.PGDB = PGDB;
486
+ class TransactionPG extends sedentary_1.Transaction {
487
+ constructor(log, client) {
488
+ super(log);
489
+ this.released = false;
490
+ this._client = client;
491
+ }
492
+ async client() {
493
+ return this._client;
494
+ }
495
+ release() {
496
+ this.released = true;
497
+ this._client.release();
498
+ }
499
+ async commit() {
500
+ if (!this.released) {
501
+ this.log("COMMIT");
502
+ await this._client.query("COMMIT");
503
+ this.release();
504
+ super.commit();
505
+ }
506
+ }
507
+ async rollback() {
508
+ try {
509
+ if (!this.released) {
510
+ super.rollback();
511
+ this.log("ROLLBACK");
512
+ await this._client.query("ROLLBACK");
513
+ }
514
+ }
515
+ finally {
516
+ if (!this.released)
517
+ this.release();
518
+ }
519
+ }
520
+ }
521
+ exports.TransactionPG = TransactionPG;
@@ -0,0 +1,5 @@
1
+ // cspell: disable-next-line
2
+ export function adsrc(version) {
3
+ // cspell: disable-next-line
4
+ return version >= 12 ? "pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS adsrc" : "adsrc";
5
+ }
@@ -0,0 +1,24 @@
1
+ import { Sedentary } from "sedentary";
2
+ import { PGDB } from "./pgdb";
3
+ export { EntryBase, Type } from "sedentary";
4
+ export { TransactionPG } from "./pgdb";
5
+ export class SedentaryPG extends Sedentary {
6
+ constructor(connection, options) {
7
+ super(options);
8
+ if (!(connection instanceof Object))
9
+ throw new Error("SedentaryPG.constructor: 'connection' argument: Wrong type, expected 'Object'");
10
+ this.db = new PGDB(connection, this.log);
11
+ }
12
+ FKey(attribute, options) {
13
+ const { attributeName, modelName, unique } = attribute;
14
+ if (!unique)
15
+ throw new Error(`SedentaryPG.FKey: '${modelName}' model: '${attributeName}' attribute: is not unique: can't be used as FKey target`);
16
+ return super.FKey(attribute, options);
17
+ }
18
+ begin() {
19
+ return this.db.begin();
20
+ }
21
+ client() {
22
+ return this.db.client();
23
+ }
24
+ }
@@ -0,0 +1,515 @@
1
+ import { DatabaseError, Pool, types as PGtypes } from "pg";
2
+ import format from "pg-format";
3
+ import { DB, Transaction } from "sedentary";
4
+ import { adsrc } from "./adsrc";
5
+ const needDrop = [
6
+ ["DATETIME", "int2"],
7
+ ["DATETIME", "int4"],
8
+ ["DATETIME", "int8"],
9
+ ["DATETIME", "numeric"],
10
+ ["INT", "json"],
11
+ ["INT", "timestamptz"],
12
+ ["INT8", "json"],
13
+ ["INT8", "timestamptz"],
14
+ ["JSON", "int2"],
15
+ ["JSON", "int4"],
16
+ ["JSON", "int8"],
17
+ ["JSON", "numeric"],
18
+ ["NUMBER", "json"],
19
+ ["NUMBER", "timestamptz"]
20
+ ];
21
+ const needUsing = [
22
+ ["BOOLEAN", "varchar"],
23
+ ["DATETIME", "varchar"],
24
+ ["INT", "varchar"],
25
+ ["INT8", "varchar"],
26
+ ["JSON", "varchar"],
27
+ ["NUMBER", "varchar"]
28
+ ];
29
+ const types = { bool: "BOOL", int2: "SMALLINT", int4: "INTEGER", int8: "BIGINT", json: "JSON", numeric: "NUMERIC", timestamptz: "DATETIME", varchar: "VARCHAR" };
30
+ const actions = { cascade: "c", "no action": "a", restrict: "r", "set default": "d", "set null": "n" };
31
+ function parseInt8(value) {
32
+ return BigInt(value);
33
+ }
34
+ function parseNumber(value) {
35
+ return parseFloat(value);
36
+ }
37
+ PGtypes.setTypeParser(20, parseInt8);
38
+ PGtypes.setTypeParser(1700, parseNumber);
39
+ export class PGDB extends DB {
40
+ _client = {};
41
+ indexes = [];
42
+ oidLoad = {};
43
+ pool;
44
+ released = false;
45
+ version = 0;
46
+ constructor(connection, log) {
47
+ super(log);
48
+ this.pool = new Pool(connection);
49
+ }
50
+ async connect() {
51
+ this._client = await this.pool.connect();
52
+ const res = await this._client.query("SELECT version()");
53
+ this.version = parseInt(res.rows[0].version.split(" ")[1].split(".")[0], 10);
54
+ }
55
+ async end() {
56
+ if (!this.released)
57
+ this._client.release();
58
+ await this.pool.end();
59
+ }
60
+ defaultNeq(src, value) {
61
+ if (src === value)
62
+ return false;
63
+ return src.split("::")[0] !== value;
64
+ }
65
+ async begin() {
66
+ const ret = new TransactionPG(this.log, await this.pool.connect());
67
+ this.log("BEGIN");
68
+ await ret._client.query("BEGIN");
69
+ return ret;
70
+ }
71
+ async client() {
72
+ return await this.pool.connect();
73
+ }
74
+ escape(value) {
75
+ if (value === null || value === undefined)
76
+ throw new Error("SedentaryPG: Can't escape null nor undefined values; use the 'IS NULL' operator instead");
77
+ if (typeof value === "boolean" || typeof value === "number")
78
+ return value.toString();
79
+ if (typeof value === "string")
80
+ return format("%L", value);
81
+ //if(value instanceof Date)
82
+ return format("%L", value).replace(/\.\d\d\d\+/, "+");
83
+ //return format("%L", JSON.stringify(value));
84
+ }
85
+ fill(attributes, row, entry) {
86
+ const loaded = {};
87
+ for (const attribute in attributes)
88
+ entry[attribute] = loaded[attribute] = row[attributes[attribute]];
89
+ Object.defineProperty(entry, "loaded", { configurable: true, value: loaded });
90
+ }
91
+ load(tableName, attributes, pk, model, table) {
92
+ const pkFldName = pk.fieldName;
93
+ return async (where, order, limit, tx, lock) => {
94
+ const { oid } = table;
95
+ const ret = [];
96
+ const client = tx ? tx._client : await this.pool.connect();
97
+ const oidPK = {};
98
+ try {
99
+ const forUpdate = lock ? " FOR UPDATE" : "";
100
+ const orderBy = order && order.length ? ` ORDER BY ${(typeof order === "string" ? [order] : order).map(_ => (_.startsWith("-") ? `${_.substring(1)} DESC` : _)).join(",")}` : "";
101
+ const limitTo = typeof limit === "number" ? ` LIMIT ${limit}` : "";
102
+ const query = `SELECT *, tableoid FROM ${tableName}${where ? ` WHERE ${where}` : ""}${orderBy}${limitTo}${forUpdate}`;
103
+ this.log(query);
104
+ const res = await client.query(query);
105
+ for (const row of res.rows) {
106
+ if (row.tableoid === oid) {
107
+ const entry = new model("load");
108
+ this.fill(attributes, row, entry);
109
+ if (tx)
110
+ tx.addEntry(entry);
111
+ ret.push(entry);
112
+ entry.postLoad();
113
+ }
114
+ else {
115
+ if (!oidPK[row.tableoid])
116
+ oidPK[row.tableoid] = [];
117
+ oidPK[row.tableoid].push([ret.length, row[pkFldName]]);
118
+ ret.push(null);
119
+ }
120
+ }
121
+ for (const oid in oidPK) {
122
+ const res = await this.oidLoad[oid](oidPK[oid].map(_ => _[1]));
123
+ for (const entry of res)
124
+ for (const [id, pk] of oidPK[oid])
125
+ if (pk === entry[pkFldName])
126
+ ret[id] = entry;
127
+ }
128
+ }
129
+ finally {
130
+ if (!tx)
131
+ client.release();
132
+ }
133
+ return ret;
134
+ };
135
+ }
136
+ remove(tableName, pk) {
137
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
138
+ const self = this;
139
+ const pkAttrName = pk.attributeName;
140
+ const pkFldName = pk.fieldName;
141
+ return async function () {
142
+ const client = this.tx ? this.tx._client : await self.pool.connect();
143
+ let removed = false;
144
+ try {
145
+ const query = `DELETE FROM ${tableName} WHERE ${pkFldName} = ${self.escape(this[pkAttrName])}`;
146
+ self.log(query);
147
+ removed = (await client.query(query)).rowCount === 1;
148
+ }
149
+ finally {
150
+ if (!this.tx)
151
+ client.release();
152
+ }
153
+ return removed;
154
+ };
155
+ }
156
+ save(tableName, attributes, pk) {
157
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
158
+ const self = this;
159
+ const pkAttrName = pk.attributeName;
160
+ const pkFldName = pk.fieldName;
161
+ return async function () {
162
+ const client = this.tx ? this.tx._client : await self.pool.connect();
163
+ let changed = false;
164
+ try {
165
+ const { loaded } = this;
166
+ if (loaded) {
167
+ const actions = [];
168
+ for (const attribute in attributes) {
169
+ const value = this[attribute];
170
+ if (value !== loaded[attribute])
171
+ actions.push(`${attributes[attribute]} = ${self.escape(value)}`);
172
+ }
173
+ if (actions.length) {
174
+ const query = `UPDATE ${tableName} SET ${actions.join(", ")} WHERE ${pkFldName} = ${self.escape(this[pkAttrName])}`;
175
+ self.log(query);
176
+ self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
177
+ changed = true;
178
+ }
179
+ }
180
+ else {
181
+ const fields = [];
182
+ const values = [];
183
+ for (const attribute in attributes) {
184
+ const value = this[attribute];
185
+ if (value !== null && value !== undefined) {
186
+ fields.push(attributes[attribute]);
187
+ values.push(self.escape(value));
188
+ }
189
+ }
190
+ const query = fields.length ? `INSERT INTO ${tableName} (${fields.join(", ")}) VALUES (${values.join(", ")})` : `INSERT INTO ${tableName} DEFAULT VALUES`;
191
+ self.log(query);
192
+ self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
193
+ changed = true;
194
+ }
195
+ }
196
+ finally {
197
+ if (!this.tx)
198
+ client.release();
199
+ }
200
+ return changed;
201
+ };
202
+ }
203
+ async dropConstraints(table) {
204
+ const indexes = [];
205
+ const res = await this._client.query("SELECT confdeltype, confupdtype, conindid, conname, contype FROM pg_constraint WHERE conrelid = $1 ORDER BY conname", [table.oid]);
206
+ for (const row of res.rows) {
207
+ const arr = table.constraints.filter(_ => _.constraintName === row.conname && _.type === row.contype);
208
+ let drop = false;
209
+ if (arr.length === 0)
210
+ drop = true;
211
+ else if (row.contype === "u")
212
+ indexes.push(row.conindid);
213
+ else {
214
+ const { options } = arr[0].attribute.foreignKey;
215
+ if (actions[options.onDelete] !== row.confdeltype || actions[options.onUpdate] !== row.confupdtype)
216
+ drop = true;
217
+ }
218
+ if (drop) {
219
+ const statement = `ALTER TABLE ${table.tableName} DROP CONSTRAINT ${row.conname} CASCADE`;
220
+ this.syncLog(statement);
221
+ if (this.sync)
222
+ await this._client.query(statement);
223
+ }
224
+ }
225
+ return indexes;
226
+ }
227
+ async dropField(tableName, fieldName) {
228
+ const statement = `ALTER TABLE ${tableName} DROP COLUMN ${fieldName}`;
229
+ this.syncLog(statement);
230
+ if (this.sync)
231
+ await this._client.query(statement);
232
+ }
233
+ async dropFields(table) {
234
+ const res = await this._client.query("SELECT attname FROM pg_attribute WHERE attrelid = $1 AND attnum > 0 AND attisdropped = false AND attinhcount = 0", [table.oid]);
235
+ for (const i in res.rows)
236
+ if (!table.findField(res.rows[i].attname))
237
+ await this.dropField(table.tableName, res.rows[i].attname);
238
+ }
239
+ async dropIndexes(table, constraintIndexes) {
240
+ const { indexes, oid } = table;
241
+ const iObject = {};
242
+ const res = await this._client.query("SELECT amname, attname, indexrelid, indisunique, relname FROM pg_class, pg_index, pg_attribute, pg_am WHERE indrelid = $1 AND indexrelid = pg_class.oid AND attrelid = pg_class.oid AND relam = pg_am.oid ORDER BY attnum", [oid]);
243
+ for (const row of res.rows) {
244
+ const { amname, attname, indexrelid, indisunique, relname } = row;
245
+ if (!constraintIndexes.includes(indexrelid)) {
246
+ if (iObject[relname])
247
+ iObject[relname].fields.push(attname);
248
+ else
249
+ iObject[relname] = { fields: [attname], indexName: relname, type: amname, unique: indisunique };
250
+ }
251
+ }
252
+ this.indexes = [];
253
+ for (const index of indexes) {
254
+ const { indexName } = index;
255
+ if (iObject[indexName] && this.indexesEq(index, iObject[indexName])) {
256
+ this.indexes.push(indexName);
257
+ delete iObject[indexName];
258
+ }
259
+ }
260
+ for (const index of Object.keys(iObject).sort()) {
261
+ const statement = `DROP INDEX ${index}`;
262
+ this.syncLog(statement);
263
+ if (this.sync)
264
+ await this._client.query(statement);
265
+ }
266
+ }
267
+ async syncConstraints(table) {
268
+ for (const constraint of table.constraints) {
269
+ const { attribute, constraintName, type } = constraint;
270
+ const res = await this._client.query("SELECT attname FROM pg_attribute, pg_constraint WHERE attrelid = $1 AND conrelid = $1 AND attnum = conkey[1] AND attname = $2", [
271
+ table.oid,
272
+ attribute.fieldName
273
+ ]);
274
+ if (!res.rowCount) {
275
+ let query;
276
+ if (type === "f") {
277
+ const { fieldName, options, tableName } = attribute.foreignKey;
278
+ const onDelete = options.onDelete !== "no action" ? ` ON DELETE ${options.onDelete.toUpperCase()}` : "";
279
+ const onUpdate = options.onUpdate !== "no action" ? ` ON UPDATE ${options.onUpdate.toUpperCase()}` : "";
280
+ query = `FOREIGN KEY (${attribute.fieldName}) REFERENCES ${tableName}(${fieldName})${onDelete}${onUpdate}`;
281
+ }
282
+ else
283
+ query = `UNIQUE(${attribute.fieldName})`;
284
+ const statement = `ALTER TABLE ${table.tableName} ADD CONSTRAINT ${constraintName} ${query}`;
285
+ this.syncLog(statement);
286
+ if (this.sync)
287
+ await this._client.query(statement);
288
+ }
289
+ }
290
+ }
291
+ async syncDataBase() {
292
+ try {
293
+ await super.syncDataBase();
294
+ for (const table of this.tables)
295
+ this.oidLoad[table.oid || 0] = (ids) => table.model.load({ [table.pk.attributeName]: ["IN", ids] });
296
+ }
297
+ catch (e) {
298
+ throw e;
299
+ }
300
+ finally {
301
+ this.released = true;
302
+ this._client.release();
303
+ }
304
+ }
305
+ fieldType(attribute) {
306
+ const { size, type } = attribute;
307
+ let ret;
308
+ switch (type) {
309
+ case "BOOLEAN":
310
+ return ["BOOL", "BOOL"];
311
+ case "DATETIME":
312
+ return ["DATETIME", "TIMESTAMP (3) WITH TIME ZONE"];
313
+ case "INT":
314
+ ret = size === 2 ? "SMALLINT" : "INTEGER";
315
+ return [ret, ret];
316
+ case "INT8":
317
+ return ["BIGINT", "BIGINT"];
318
+ case "JSON":
319
+ return ["JSON", "JSON"];
320
+ case "NUMBER":
321
+ return ["NUMERIC", "NUMERIC"];
322
+ case "VARCHAR":
323
+ return ["VARCHAR", "VARCHAR" + (size ? `(${size})` : "")];
324
+ }
325
+ throw new Error(`Unknown type: '${type}', '${size}'`);
326
+ }
327
+ async syncFields(table) {
328
+ const { attributes, autoIncrement, oid, tableName } = table;
329
+ for (const attribute of attributes) {
330
+ const { fieldName, notNull, size } = attribute;
331
+ const defaultValue = attribute.defaultValue === undefined ? (autoIncrement && fieldName === "id" ? `nextval('${tableName}_id_seq'::regclass)` : undefined) : this.escape(attribute.defaultValue);
332
+ const [base, type] = this.fieldType(attribute);
333
+ const where = "attrelid = $1 AND attnum > 0 AND atttypid = pg_type.oid AND attislocal = 't' AND attname = $2";
334
+ const res = await this._client.query(`SELECT attnotnull, atttypmod, typname, ${adsrc(this.version)} FROM pg_type, pg_attribute LEFT JOIN pg_attrdef ON adrelid = attrelid AND adnum = attnum WHERE ${where}`, [oid, fieldName]);
335
+ const addField = async () => {
336
+ const statement = `ALTER TABLE ${tableName} ADD COLUMN ${fieldName} ${type}`;
337
+ this.syncLog(statement);
338
+ if (this.sync)
339
+ await this._client.query(statement);
340
+ };
341
+ const dropDefault = async () => {
342
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} DROP DEFAULT`;
343
+ this.syncLog(statement);
344
+ if (this.sync)
345
+ await this._client.query(statement);
346
+ };
347
+ const setNotNull = async (isNotNull) => {
348
+ if (isNotNull === notNull)
349
+ return;
350
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} ${notNull ? "SET" : "DROP"} NOT NULL`;
351
+ this.syncLog(statement);
352
+ if (this.sync)
353
+ await this._client.query(statement);
354
+ };
355
+ const setDefault = async (isNotNull) => {
356
+ if (defaultValue !== undefined) {
357
+ let statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} SET DEFAULT ${defaultValue}`;
358
+ this.syncLog(statement);
359
+ if (this.sync)
360
+ await this._client.query(statement);
361
+ if (notNull && !isNotNull) {
362
+ statement = `UPDATE ${tableName} SET ${fieldName} = ${defaultValue} WHERE ${fieldName} IS NULL`;
363
+ this.syncLog(statement);
364
+ if (this.sync)
365
+ this._client.query(statement);
366
+ }
367
+ }
368
+ await setNotNull(isNotNull);
369
+ };
370
+ if (!res.rowCount) {
371
+ await addField();
372
+ await setDefault(false);
373
+ }
374
+ else {
375
+ const { adsrc, attnotnull, atttypmod, typname } = res.rows[0];
376
+ if (types[typname] !== base || (base === "VARCHAR" && (size ? size + 4 !== atttypmod : atttypmod !== -1))) {
377
+ if (needDrop.some(([type, name]) => attribute.type === type && typname === name)) {
378
+ await this.dropField(tableName, fieldName);
379
+ await addField();
380
+ await setDefault(false);
381
+ }
382
+ else {
383
+ if (adsrc)
384
+ dropDefault();
385
+ const using = needUsing.some(([type, name]) => attribute.type === type && typname === name) ? " USING " + fieldName + "::" + type : "";
386
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} TYPE ${type}${using}`;
387
+ this.syncLog(statement);
388
+ if (this.sync)
389
+ await this._client.query(statement);
390
+ await setDefault(attnotnull);
391
+ }
392
+ }
393
+ else if (defaultValue === undefined) {
394
+ if (adsrc)
395
+ dropDefault();
396
+ await setNotNull(attnotnull);
397
+ }
398
+ else if (!adsrc || this.defaultNeq(adsrc, defaultValue))
399
+ await setDefault(attnotnull);
400
+ }
401
+ }
402
+ }
403
+ async syncIndexes(table) {
404
+ const { indexes, tableName } = table;
405
+ for (const index of indexes) {
406
+ const { fields, indexName, type, unique } = index;
407
+ if (!this.indexes.includes(indexName)) {
408
+ const statement = `CREATE${unique ? " UNIQUE" : ""} INDEX ${indexName} ON ${tableName} USING ${type} (${fields.join(", ")})`;
409
+ this.syncLog(statement);
410
+ if (this.sync)
411
+ await this._client.query(statement);
412
+ }
413
+ }
414
+ }
415
+ async syncSequence(table) {
416
+ if (!table.autoIncrementOwn)
417
+ return;
418
+ const statement = `ALTER SEQUENCE ${table.tableName}_id_seq OWNED BY ${table.tableName}.id`;
419
+ this.syncLog(statement);
420
+ if (this.sync)
421
+ await this._client.query(statement);
422
+ }
423
+ async syncTable(table) {
424
+ if (table.autoIncrement) {
425
+ await (async () => {
426
+ try {
427
+ await this._client.query(`SELECT currval('${table.tableName}_id_seq')`);
428
+ }
429
+ catch (e) {
430
+ if (e instanceof DatabaseError && e.code === "55000")
431
+ return;
432
+ if (e instanceof DatabaseError && e.code === "42P01") {
433
+ const statement = `CREATE SEQUENCE ${table.tableName}_id_seq`;
434
+ this.syncLog(statement);
435
+ if (this.sync)
436
+ await this._client.query(statement);
437
+ table.autoIncrementOwn = true;
438
+ return;
439
+ }
440
+ throw e;
441
+ }
442
+ })();
443
+ }
444
+ let create = false;
445
+ const resTable = await this._client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
446
+ if (resTable.rowCount) {
447
+ table.oid = resTable.rows[0].oid;
448
+ let drop = false;
449
+ const resParent = await this._client.query("SELECT inhparent FROM pg_inherits WHERE inhrelid = $1", [table.oid]);
450
+ if (resParent.rowCount) {
451
+ if (!table.parent)
452
+ drop = true;
453
+ else if (this.findTable(table.parent.tableName).oid === resParent.rows[0].inhparent)
454
+ return;
455
+ drop = true;
456
+ }
457
+ else if (table.parent)
458
+ drop = true;
459
+ if (drop) {
460
+ const statement = `DROP TABLE ${table.tableName} CASCADE`;
461
+ create = true;
462
+ this.syncLog(statement);
463
+ if (this.sync)
464
+ await this._client.query(statement);
465
+ }
466
+ }
467
+ else
468
+ create = true;
469
+ if (create) {
470
+ const parent = table.parent ? ` INHERITS (${table.parent.tableName})` : "";
471
+ const statement = `CREATE TABLE ${table.tableName} ()${parent}`;
472
+ this.syncLog(statement);
473
+ if (this.sync)
474
+ await this._client.query(statement);
475
+ const resTable = await this._client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
476
+ table.oid = resTable.rows[0]?.oid;
477
+ }
478
+ }
479
+ }
480
+ export class TransactionPG extends Transaction {
481
+ _client;
482
+ released = false;
483
+ constructor(log, client) {
484
+ super(log);
485
+ this._client = client;
486
+ }
487
+ async client() {
488
+ return this._client;
489
+ }
490
+ release() {
491
+ this.released = true;
492
+ this._client.release();
493
+ }
494
+ async commit() {
495
+ if (!this.released) {
496
+ this.log("COMMIT");
497
+ await this._client.query("COMMIT");
498
+ this.release();
499
+ super.commit();
500
+ }
501
+ }
502
+ async rollback() {
503
+ try {
504
+ if (!this.released) {
505
+ super.rollback();
506
+ this.log("ROLLBACK");
507
+ await this._client.query("ROLLBACK");
508
+ }
509
+ }
510
+ finally {
511
+ if (!this.released)
512
+ this.release();
513
+ }
514
+ }
515
+ }
@@ -0,0 +1 @@
1
+ export declare function adsrc(version: number): "pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS adsrc" | "adsrc";
@@ -0,0 +1,11 @@
1
+ import { Attribute, EntryBase, ForeignKeyOptions, Sedentary, SedentaryOptions, Type } from "sedentary";
2
+ import { PoolConfig } from "pg";
3
+ import { PGDB, TransactionPG } from "./pgdb";
4
+ export { Entry, EntryBase, SedentaryOptions, Type } from "sedentary";
5
+ export { TransactionPG } from "./pgdb";
6
+ export declare class SedentaryPG extends Sedentary<PGDB, TransactionPG> {
7
+ constructor(connection: PoolConfig, options?: SedentaryOptions);
8
+ FKey<T, E extends EntryBase>(attribute: Attribute<T, E>, options?: ForeignKeyOptions): Type<T, E>;
9
+ begin(): Promise<TransactionPG>;
10
+ client(): Promise<import("pg").PoolClient>;
11
+ }
@@ -0,0 +1,46 @@
1
+ import { PoolClient, PoolConfig } from "pg";
2
+ import { Attribute, DB, EntryBase, Table, Transaction } from "sedentary";
3
+ export declare class PGDB extends DB<TransactionPG> {
4
+ private _client;
5
+ private indexes;
6
+ private oidLoad;
7
+ private pool;
8
+ private released;
9
+ private version;
10
+ constructor(connection: PoolConfig, log: (message: string) => void);
11
+ connect(): Promise<void>;
12
+ end(): Promise<void>;
13
+ defaultNeq(src: string, value: unknown): boolean;
14
+ begin(): Promise<TransactionPG>;
15
+ client(): Promise<PoolClient>;
16
+ escape(value: unknown): string;
17
+ fill(attributes: Record<string, string>, row: Record<string, unknown>, entry: Record<string, unknown>): void;
18
+ load(tableName: string, attributes: Record<string, string>, pk: Attribute<unknown, unknown>, model: new (from: "load") => EntryBase, table: Table): (where: string, order?: string | string[], limit?: number, tx?: Transaction) => Promise<EntryBase[]>;
19
+ remove(tableName: string, pk: Attribute<unknown, unknown>): (this: Record<string, unknown> & {
20
+ tx?: TransactionPG;
21
+ }) => Promise<boolean>;
22
+ save(tableName: string, attributes: Record<string, string>, pk: Attribute<unknown, unknown>): (this: Record<string, unknown> & {
23
+ loaded?: Record<string, unknown>;
24
+ tx?: TransactionPG;
25
+ }) => Promise<boolean>;
26
+ dropConstraints(table: Table): Promise<number[]>;
27
+ dropField(tableName: string, fieldName: string): Promise<void>;
28
+ dropFields(table: Table): Promise<void>;
29
+ dropIndexes(table: Table, constraintIndexes: number[]): Promise<void>;
30
+ syncConstraints(table: Table): Promise<void>;
31
+ syncDataBase(): Promise<void>;
32
+ fieldType(attribute: Attribute<unknown, unknown>): string[];
33
+ syncFields(table: Table): Promise<void>;
34
+ syncIndexes(table: Table): Promise<void>;
35
+ syncSequence(table: Table): Promise<void>;
36
+ syncTable(table: Table): Promise<void>;
37
+ }
38
+ export declare class TransactionPG extends Transaction {
39
+ private _client;
40
+ private released;
41
+ constructor(log: (message: string) => void, client: PoolClient);
42
+ client(): Promise<PoolClient>;
43
+ private release;
44
+ commit(): Promise<void>;
45
+ rollback(): Promise<void>;
46
+ }
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "@types/pg": "8.6.5",
10
10
  "pg": "8.7.3",
11
11
  "pg-format": "1.0.4",
12
- "sedentary": "0.0.43"
12
+ "sedentary": "0.0.44"
13
13
  },
14
14
  "description": "The ORM which never needs to migrate - PostgreSQL",
15
15
  "engines": {
@@ -40,12 +40,12 @@
40
40
  "scripts": {
41
41
  "build": "make build",
42
42
  "coverage": "jest --coverage --no-cache --runInBand",
43
- "deploy": "npm_config_registry=\"registry.npmjs.org\" npm publish",
43
+ "deploy": "make deploy",
44
44
  "precoverage": "make pretest",
45
45
  "preinstall": "if [ -f Makefile ] ; then make ; fi",
46
46
  "pretest": "make pretest",
47
47
  "test": "jest --no-cache --runInBand"
48
48
  },
49
49
  "types": "./dist/types/index.d.ts",
50
- "version": "0.0.43"
50
+ "version": "0.0.44"
51
51
  }