sedentary-pg 0.0.25 → 0.0.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{adsrc.js → dist/cjs/adsrc.js} +0 -0
- package/{index.js → dist/cjs/index.js} +0 -0
- package/{pgdb.js → dist/cjs/pgdb.js} +3 -3
- package/dist/es/adsrc.js +3 -0
- package/dist/es/index.js +22 -0
- package/dist/es/pgdb.js +448 -0
- package/{adsrc.d.ts → dist/types/adsrc.d.ts} +0 -0
- package/{index.d.ts → dist/types/index.d.ts} +1 -2
- package/{pgdb.d.ts → dist/types/pgdb.d.ts} +1 -1
- package/package.json +9 -9
|
File without changes
|
|
File without changes
|
|
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.TransactionPG = exports.PGDB = void 0;
|
|
7
7
|
const pg_1 = require("pg");
|
|
8
8
|
const pg_format_1 = __importDefault(require("pg-format"));
|
|
9
|
-
const
|
|
9
|
+
const sedentary_1 = require("sedentary");
|
|
10
10
|
const adsrc_1 = require("./adsrc");
|
|
11
11
|
const needDrop = [
|
|
12
12
|
["DATETIME", "int2"],
|
|
@@ -22,7 +22,7 @@ const needUsing = [
|
|
|
22
22
|
];
|
|
23
23
|
const types = { int2: "SMALLINT", int4: "INTEGER", int8: "BIGINT", timestamptz: "DATETIME", varchar: "VARCHAR" };
|
|
24
24
|
const actions = { cascade: "c", "no action": "a", restrict: "r", "set default": "d", "set null": "n" };
|
|
25
|
-
class PGDB extends
|
|
25
|
+
class PGDB extends sedentary_1.DB {
|
|
26
26
|
constructor(connection, log) {
|
|
27
27
|
super(log);
|
|
28
28
|
this.oidLoad = {};
|
|
@@ -419,7 +419,7 @@ class PGDB extends db_1.DB {
|
|
|
419
419
|
}
|
|
420
420
|
}
|
|
421
421
|
exports.PGDB = PGDB;
|
|
422
|
-
class TransactionPG extends
|
|
422
|
+
class TransactionPG extends sedentary_1.Transaction {
|
|
423
423
|
constructor(client) {
|
|
424
424
|
super();
|
|
425
425
|
this.released = false;
|
package/dist/es/adsrc.js
ADDED
package/dist/es/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
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(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: is not unique: can't be used as FKEY target`);
|
|
16
|
+
return super.FKEY(attribute, options);
|
|
17
|
+
}
|
|
18
|
+
async begin() {
|
|
19
|
+
return this.db.begin();
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export const Package = SedentaryPG;
|
package/dist/es/pgdb.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { DatabaseError, Pool } 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
|
+
["INT", "timestamptz"],
|
|
10
|
+
["INT8", "timestamptz"]
|
|
11
|
+
];
|
|
12
|
+
const needUsing = [
|
|
13
|
+
["DATETIME", "varchar"],
|
|
14
|
+
["INT", "varchar"],
|
|
15
|
+
["INT8", "varchar"]
|
|
16
|
+
];
|
|
17
|
+
const types = { int2: "SMALLINT", int4: "INTEGER", int8: "BIGINT", timestamptz: "DATETIME", varchar: "VARCHAR" };
|
|
18
|
+
const actions = { cascade: "c", "no action": "a", restrict: "r", "set default": "d", "set null": "n" };
|
|
19
|
+
export class PGDB extends DB {
|
|
20
|
+
client;
|
|
21
|
+
indexes;
|
|
22
|
+
oidLoad = {};
|
|
23
|
+
pool;
|
|
24
|
+
version;
|
|
25
|
+
constructor(connection, log) {
|
|
26
|
+
super(log);
|
|
27
|
+
this.client = {};
|
|
28
|
+
this.indexes = [];
|
|
29
|
+
this.pool = new Pool(connection);
|
|
30
|
+
this.version = 0;
|
|
31
|
+
}
|
|
32
|
+
async connect() {
|
|
33
|
+
this.client = await this.pool.connect();
|
|
34
|
+
const res = await this.client.query("SELECT version()");
|
|
35
|
+
this.version = parseInt(res.rows[0].version.split(" ")[1].split(".")[0], 10);
|
|
36
|
+
}
|
|
37
|
+
async end() {
|
|
38
|
+
if (this.client.release)
|
|
39
|
+
this.client.release();
|
|
40
|
+
await this.pool.end();
|
|
41
|
+
}
|
|
42
|
+
defaultNeq(src, value) {
|
|
43
|
+
if (src === value)
|
|
44
|
+
return false;
|
|
45
|
+
return src.split("::")[0] !== value;
|
|
46
|
+
}
|
|
47
|
+
async begin() {
|
|
48
|
+
const ret = new TransactionPG(await this.pool.connect());
|
|
49
|
+
await ret.client.query("BEGIN");
|
|
50
|
+
return ret;
|
|
51
|
+
}
|
|
52
|
+
escape(value) {
|
|
53
|
+
if (value === null || value === undefined)
|
|
54
|
+
throw new Error("SedentaryPG: Can't escape null nor undefined values; use the 'IS NULL' operator instead");
|
|
55
|
+
const type = typeof value;
|
|
56
|
+
if (type === "number" || type === "boolean")
|
|
57
|
+
return value.toString();
|
|
58
|
+
if (type === "string")
|
|
59
|
+
return format("%L", value);
|
|
60
|
+
if (value instanceof Date)
|
|
61
|
+
return format("%L", value).replace(/\.\d\d\d\+/, "+");
|
|
62
|
+
return format("%L", JSON.stringify(value));
|
|
63
|
+
}
|
|
64
|
+
fill(attributes, row, entry) {
|
|
65
|
+
const loaded = {};
|
|
66
|
+
for (const attribute in attributes)
|
|
67
|
+
entry[attribute] = loaded[attribute] = row[attributes[attribute]];
|
|
68
|
+
Object.defineProperty(entry, "loaded", { configurable: true, value: loaded });
|
|
69
|
+
}
|
|
70
|
+
load(tableName, attributes, pk, model, table) {
|
|
71
|
+
const pkFldName = pk.fieldName;
|
|
72
|
+
return async (where, order, tx) => {
|
|
73
|
+
const { oid } = table;
|
|
74
|
+
const ret = [];
|
|
75
|
+
const client = tx ? tx.client : await this.pool.connect();
|
|
76
|
+
const oidPK = {};
|
|
77
|
+
try {
|
|
78
|
+
const query = `SELECT *, tableoid FROM ${tableName}${where ? ` WHERE ${where}` : ""}${order && order.length ? ` ORDER BY ${order.map(_ => (_.startsWith("-") ? `${_.substring(1)} DESC` : _)).join(",")}` : ""}`;
|
|
79
|
+
this.log(query);
|
|
80
|
+
const res = await client.query(query);
|
|
81
|
+
for (const row of res.rows) {
|
|
82
|
+
if (row.tableoid === oid) {
|
|
83
|
+
const entry = new model("load");
|
|
84
|
+
this.fill(attributes, row, entry);
|
|
85
|
+
ret.push(entry);
|
|
86
|
+
entry.postLoad();
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
if (!oidPK[row.tableoid])
|
|
90
|
+
oidPK[row.tableoid] = [];
|
|
91
|
+
oidPK[row.tableoid].push([ret.length, row[pkFldName]]);
|
|
92
|
+
ret.push(null);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
for (const oid in oidPK) {
|
|
96
|
+
const res = await this.oidLoad[oid](oidPK[oid].map(_ => _[1]));
|
|
97
|
+
for (const entry of res)
|
|
98
|
+
for (const [id] of oidPK[oid])
|
|
99
|
+
ret[id] = entry;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
if (!tx)
|
|
104
|
+
client.release();
|
|
105
|
+
}
|
|
106
|
+
return ret;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
save(tableName, attributes, pk) {
|
|
110
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
111
|
+
const self = this;
|
|
112
|
+
const pkAttrnName = pk.attributeName;
|
|
113
|
+
const pkFldName = pk.fieldName;
|
|
114
|
+
return async function () {
|
|
115
|
+
let changed = false;
|
|
116
|
+
const client = this.tx ? this.tx.client : await self.pool.connect();
|
|
117
|
+
try {
|
|
118
|
+
const { loaded } = this;
|
|
119
|
+
if (loaded) {
|
|
120
|
+
const actions = [];
|
|
121
|
+
for (const attribute in attributes) {
|
|
122
|
+
const value = this[attribute];
|
|
123
|
+
if (value !== loaded[attribute])
|
|
124
|
+
actions.push(`${attributes[attribute]} = ${self.escape(value)}`);
|
|
125
|
+
}
|
|
126
|
+
if (actions.length) {
|
|
127
|
+
const query = `UPDATE ${tableName} SET ${actions.join(", ")} WHERE ${pkFldName} = ${self.escape(this[pkAttrnName])}`;
|
|
128
|
+
self.log(query);
|
|
129
|
+
self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
|
|
130
|
+
changed = true;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
const fields = [];
|
|
135
|
+
const values = [];
|
|
136
|
+
for (const attribute in attributes) {
|
|
137
|
+
const value = this[attribute];
|
|
138
|
+
if (value !== null && value !== undefined) {
|
|
139
|
+
fields.push(attributes[attribute]);
|
|
140
|
+
values.push(self.escape(value));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const query = fields.length ? `INSERT INTO ${tableName} (${fields.join(", ")}) VALUES (${values.join(", ")})` : `INSERT INTO ${tableName} DEFAULT VALUES`;
|
|
144
|
+
self.log(query);
|
|
145
|
+
self.fill(attributes, (await client.query(query + " RETURNING *")).rows[0], this);
|
|
146
|
+
changed = true;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
if (!this.tx)
|
|
151
|
+
client.release();
|
|
152
|
+
}
|
|
153
|
+
return changed;
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
async dropConstraints(table) {
|
|
157
|
+
const indexes = [];
|
|
158
|
+
const res = await this.client.query("SELECT confdeltype, confupdtype, conindid, conname, contype FROM pg_constraint WHERE conrelid = $1 ORDER BY conname", [table.oid]);
|
|
159
|
+
for (const row of res.rows) {
|
|
160
|
+
const arr = table.constraints.filter(_ => _.constraintName === row.conname && _.type === row.contype);
|
|
161
|
+
let drop = false;
|
|
162
|
+
if (arr.length === 0)
|
|
163
|
+
drop = true;
|
|
164
|
+
else if (row.contype === "u")
|
|
165
|
+
indexes.push(row.conindid);
|
|
166
|
+
else {
|
|
167
|
+
const { options } = arr[0].attribute.foreignKey;
|
|
168
|
+
if (actions[options.onDelete] !== row.confdeltype || actions[options.onUpdate] !== row.confupdtype)
|
|
169
|
+
drop = true;
|
|
170
|
+
}
|
|
171
|
+
if (drop) {
|
|
172
|
+
const statement = `ALTER TABLE ${table.tableName} DROP CONSTRAINT ${row.conname} CASCADE`;
|
|
173
|
+
this.syncLog(statement);
|
|
174
|
+
if (this.sync)
|
|
175
|
+
await this.client.query(statement);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return indexes;
|
|
179
|
+
}
|
|
180
|
+
async dropField(tableName, fieldName) {
|
|
181
|
+
const statement = `ALTER TABLE ${tableName} DROP COLUMN ${fieldName}`;
|
|
182
|
+
this.syncLog(statement);
|
|
183
|
+
if (this.sync)
|
|
184
|
+
await this.client.query(statement);
|
|
185
|
+
}
|
|
186
|
+
async dropFields(table) {
|
|
187
|
+
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]);
|
|
188
|
+
for (const i in res.rows)
|
|
189
|
+
if (!table.findField(res.rows[i].attname))
|
|
190
|
+
await this.dropField(table.tableName, res.rows[i].attname);
|
|
191
|
+
}
|
|
192
|
+
async dropIndexes(table, constraintIndexes) {
|
|
193
|
+
const { indexes, oid } = table;
|
|
194
|
+
const iobject = {};
|
|
195
|
+
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]);
|
|
196
|
+
for (const row of res.rows) {
|
|
197
|
+
const { amname, attname, indexrelid, indisunique, relname } = row;
|
|
198
|
+
if (!constraintIndexes.includes(indexrelid)) {
|
|
199
|
+
if (iobject[relname])
|
|
200
|
+
iobject[relname].fields.push(attname);
|
|
201
|
+
else
|
|
202
|
+
iobject[relname] = { fields: [attname], indexName: relname, type: amname, unique: indisunique };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
this.indexes = [];
|
|
206
|
+
for (const index of indexes) {
|
|
207
|
+
const { indexName } = index;
|
|
208
|
+
if (iobject[indexName] && this.indexesEq(index, iobject[indexName])) {
|
|
209
|
+
this.indexes.push(indexName);
|
|
210
|
+
delete iobject[indexName];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const index of Object.keys(iobject).sort()) {
|
|
214
|
+
const statement = `DROP INDEX ${index}`;
|
|
215
|
+
this.syncLog(statement);
|
|
216
|
+
if (this.sync)
|
|
217
|
+
await this.client.query(statement);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async syncConstraints(table) {
|
|
221
|
+
for (const constraint of table.constraints) {
|
|
222
|
+
const { attribute, constraintName, type } = constraint;
|
|
223
|
+
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", [
|
|
224
|
+
table.oid,
|
|
225
|
+
attribute.fieldName
|
|
226
|
+
]);
|
|
227
|
+
if (!res.rowCount) {
|
|
228
|
+
let query;
|
|
229
|
+
if (type === "f") {
|
|
230
|
+
const { fieldName, options, tableName } = attribute.foreignKey;
|
|
231
|
+
const onDelete = options.onDelete !== "no action" ? ` ON DELETE ${options.onDelete.toUpperCase()}` : "";
|
|
232
|
+
const onUpdate = options.onUpdate !== "no action" ? ` ON UPDATE ${options.onUpdate.toUpperCase()}` : "";
|
|
233
|
+
query = `FOREIGN KEY (${attribute.fieldName}) REFERENCES ${tableName}(${fieldName})${onDelete}${onUpdate}`;
|
|
234
|
+
}
|
|
235
|
+
else
|
|
236
|
+
query = `UNIQUE(${attribute.fieldName})`;
|
|
237
|
+
const statement = `ALTER TABLE ${table.tableName} ADD CONSTRAINT ${constraintName} ${query}`;
|
|
238
|
+
this.syncLog(statement);
|
|
239
|
+
if (this.sync)
|
|
240
|
+
await this.client.query(statement);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async syncDataBase() {
|
|
245
|
+
await super.syncDataBase();
|
|
246
|
+
for (const table of this.tables)
|
|
247
|
+
this.oidLoad[table.oid || 0] = (ids) => table.model.load({ [table.pk.attributeName]: ["IN", ids] });
|
|
248
|
+
}
|
|
249
|
+
fieldType(attribute) {
|
|
250
|
+
const { size, type } = attribute;
|
|
251
|
+
let ret;
|
|
252
|
+
switch (type) {
|
|
253
|
+
case "DATETIME":
|
|
254
|
+
return ["DATETIME", "TIMESTAMP (3) WITH TIME ZONE"];
|
|
255
|
+
case "INT":
|
|
256
|
+
ret = size === 2 ? "SMALLINT" : "INTEGER";
|
|
257
|
+
return [ret, ret];
|
|
258
|
+
case "INT8":
|
|
259
|
+
return ["BIGINT", "BIGINT"];
|
|
260
|
+
case "VARCHAR":
|
|
261
|
+
return ["VARCHAR", "VARCHAR" + (size ? `(${size})` : "")];
|
|
262
|
+
}
|
|
263
|
+
throw new Error(`Unknown type: '${type}', '${size}'`);
|
|
264
|
+
}
|
|
265
|
+
async syncFields(table) {
|
|
266
|
+
const { attributes, autoIncrement, oid, tableName } = table;
|
|
267
|
+
for (const attribute of attributes) {
|
|
268
|
+
const { fieldName, notNull, size } = attribute;
|
|
269
|
+
const defaultValue = attribute.defaultValue === undefined ? (autoIncrement && fieldName === "id" ? `nextval('${tableName}_id_seq'::regclass)` : undefined) : this.escape(attribute.defaultValue);
|
|
270
|
+
const [base, type] = this.fieldType(attribute);
|
|
271
|
+
const where = "attrelid = $1 AND attnum > 0 AND atttypid = pg_type.oid AND attislocal = 't' AND attname = $2";
|
|
272
|
+
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]);
|
|
273
|
+
const addField = async () => {
|
|
274
|
+
const statement = `ALTER TABLE ${tableName} ADD COLUMN ${fieldName} ${type}`;
|
|
275
|
+
this.syncLog(statement);
|
|
276
|
+
if (this.sync)
|
|
277
|
+
await this.client.query(statement);
|
|
278
|
+
};
|
|
279
|
+
const dropDefault = async () => {
|
|
280
|
+
const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} DROP DEFAULT`;
|
|
281
|
+
this.syncLog(statement);
|
|
282
|
+
if (this.sync)
|
|
283
|
+
await this.client.query(statement);
|
|
284
|
+
};
|
|
285
|
+
const setNotNull = async (isNotNull) => {
|
|
286
|
+
if (isNotNull === notNull)
|
|
287
|
+
return;
|
|
288
|
+
const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} ${notNull ? "SET" : "DROP"} NOT NULL`;
|
|
289
|
+
this.syncLog(statement);
|
|
290
|
+
if (this.sync)
|
|
291
|
+
await this.client.query(statement);
|
|
292
|
+
};
|
|
293
|
+
const setDefault = async (isNotNull, create) => {
|
|
294
|
+
if (defaultValue !== undefined) {
|
|
295
|
+
let statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} SET DEFAULT ${defaultValue}`;
|
|
296
|
+
this.syncLog(statement);
|
|
297
|
+
if (this.sync)
|
|
298
|
+
await this.client.query(statement);
|
|
299
|
+
if (!isNotNull && !create) {
|
|
300
|
+
statement = `UPDATE ${tableName} SET ${fieldName} = ${defaultValue} WHERE ${fieldName} IS NULL`;
|
|
301
|
+
this.syncLog(statement);
|
|
302
|
+
if (this.sync)
|
|
303
|
+
this.client.query(statement);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
await setNotNull(isNotNull);
|
|
307
|
+
};
|
|
308
|
+
if (!res.rowCount) {
|
|
309
|
+
await addField();
|
|
310
|
+
await setDefault(false, true);
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
const { adsrc, attnotnull, atttypmod, typname } = res.rows[0];
|
|
314
|
+
if (types[typname] !== base || (base === "VARCHAR" && (size ? size + 4 !== atttypmod : atttypmod !== -1))) {
|
|
315
|
+
if (needDrop.filter(([type, name]) => attribute.type === type && typname === name).length) {
|
|
316
|
+
await this.dropField(tableName, fieldName);
|
|
317
|
+
await addField();
|
|
318
|
+
await setDefault(false, true);
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
if (adsrc)
|
|
322
|
+
dropDefault();
|
|
323
|
+
const using = needUsing.filter(([type, name]) => attribute.type === type && typname === name).length ? " USING " + fieldName + "::" + type : "";
|
|
324
|
+
const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} TYPE ${type}${using}`;
|
|
325
|
+
this.syncLog(statement);
|
|
326
|
+
if (this.sync)
|
|
327
|
+
await this.client.query(statement);
|
|
328
|
+
await setDefault(attnotnull, false);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else if (defaultValue === undefined) {
|
|
332
|
+
if (adsrc)
|
|
333
|
+
dropDefault();
|
|
334
|
+
await setNotNull(attnotnull);
|
|
335
|
+
}
|
|
336
|
+
else if (!adsrc || this.defaultNeq(adsrc, defaultValue))
|
|
337
|
+
await setDefault(attnotnull, false);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async syncIndexes(table) {
|
|
342
|
+
const { indexes, tableName } = table;
|
|
343
|
+
for (const index of indexes) {
|
|
344
|
+
const { fields, indexName, type, unique } = index;
|
|
345
|
+
if (!this.indexes.includes(indexName)) {
|
|
346
|
+
const statement = `CREATE${unique ? " UNIQUE" : ""} INDEX ${indexName} ON ${tableName} USING ${type} (${fields.join(", ")})`;
|
|
347
|
+
this.syncLog(statement);
|
|
348
|
+
if (this.sync)
|
|
349
|
+
await this.client.query(statement);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async syncSequence(table) {
|
|
354
|
+
if (!table.autoIncrementOwn)
|
|
355
|
+
return;
|
|
356
|
+
const statement = `ALTER SEQUENCE ${table.tableName}_id_seq OWNED BY ${table.tableName}.id`;
|
|
357
|
+
this.syncLog(statement);
|
|
358
|
+
if (this.sync)
|
|
359
|
+
await this.client.query(statement);
|
|
360
|
+
}
|
|
361
|
+
async syncTable(table) {
|
|
362
|
+
if (table.autoIncrement) {
|
|
363
|
+
await (async () => {
|
|
364
|
+
try {
|
|
365
|
+
await this.client.query(`SELECT currval('${table.tableName}_id_seq')`);
|
|
366
|
+
}
|
|
367
|
+
catch (e) {
|
|
368
|
+
if (e instanceof DatabaseError && e.code === "55000")
|
|
369
|
+
return;
|
|
370
|
+
if (e instanceof DatabaseError && e.code === "42P01") {
|
|
371
|
+
const statement = `CREATE SEQUENCE ${table.tableName}_id_seq`;
|
|
372
|
+
this.syncLog(statement);
|
|
373
|
+
if (this.sync)
|
|
374
|
+
await this.client.query(statement);
|
|
375
|
+
table.autoIncrementOwn = true;
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
throw e;
|
|
379
|
+
}
|
|
380
|
+
})();
|
|
381
|
+
}
|
|
382
|
+
let create = false;
|
|
383
|
+
const resTable = await this.client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
|
|
384
|
+
if (resTable.rowCount) {
|
|
385
|
+
table.oid = resTable.rows[0].oid;
|
|
386
|
+
let drop = false;
|
|
387
|
+
const resParent = await this.client.query("SELECT inhparent FROM pg_inherits WHERE inhrelid = $1", [table.oid]);
|
|
388
|
+
if (resParent.rowCount) {
|
|
389
|
+
if (!table.parent)
|
|
390
|
+
drop = true;
|
|
391
|
+
else if (this.findTable(table.parent.tableName).oid === resParent.rows[0].inhparent)
|
|
392
|
+
return;
|
|
393
|
+
drop = true;
|
|
394
|
+
}
|
|
395
|
+
else if (table.parent)
|
|
396
|
+
drop = true;
|
|
397
|
+
if (drop) {
|
|
398
|
+
const statement = `DROP TABLE ${table.tableName} CASCADE`;
|
|
399
|
+
create = true;
|
|
400
|
+
this.syncLog(statement);
|
|
401
|
+
if (this.sync)
|
|
402
|
+
await this.client.query(statement);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
else
|
|
406
|
+
create = true;
|
|
407
|
+
if (create) {
|
|
408
|
+
const parent = table.parent ? ` INHERITS (${table.parent.tableName})` : "";
|
|
409
|
+
const statement = `CREATE TABLE ${table.tableName} ()${parent}`;
|
|
410
|
+
this.syncLog(statement);
|
|
411
|
+
if (this.sync)
|
|
412
|
+
await this.client.query(statement);
|
|
413
|
+
const resTable = await this.client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
|
|
414
|
+
table.oid = resTable.rows[0]?.oid;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
export class TransactionPG extends Transaction {
|
|
419
|
+
client;
|
|
420
|
+
released = false;
|
|
421
|
+
constructor(client) {
|
|
422
|
+
super();
|
|
423
|
+
this.client = client;
|
|
424
|
+
}
|
|
425
|
+
release() {
|
|
426
|
+
this.released = true;
|
|
427
|
+
this.client.release();
|
|
428
|
+
}
|
|
429
|
+
async commit() {
|
|
430
|
+
if (!this.released) {
|
|
431
|
+
await this.client.query("COMMIT");
|
|
432
|
+
this.release();
|
|
433
|
+
super.commit();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
async rollback() {
|
|
437
|
+
try {
|
|
438
|
+
if (!this.released) {
|
|
439
|
+
super.rollback();
|
|
440
|
+
await this.client.query("ROLLBACK");
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
finally {
|
|
444
|
+
if (!this.released)
|
|
445
|
+
this.release();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
File without changes
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { EntryBase, ForeignKeyOptions, Natural, Sedentary, SedentaryOptions, Type } from "sedentary";
|
|
2
|
-
import { Attribute } from "sedentary/db";
|
|
1
|
+
import { Attribute, EntryBase, ForeignKeyOptions, Natural, Sedentary, SedentaryOptions, Type } from "sedentary";
|
|
3
2
|
import { PoolConfig } from "pg";
|
|
4
3
|
import { PGDB, TransactionPG } from "./pgdb";
|
|
5
4
|
export { EntryBase, SedentaryOptions, Type } from "sedentary";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { PoolClient, PoolConfig } from "pg";
|
|
2
|
-
import { Attribute, DB, EntryBase, Natural, Table, Transaction } from "sedentary
|
|
2
|
+
import { Attribute, DB, EntryBase, Natural, Table, Transaction } from "sedentary";
|
|
3
3
|
export declare class PGDB extends DB<TransactionPG> {
|
|
4
4
|
private client;
|
|
5
5
|
private indexes;
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"@types/pg": "8.6.4",
|
|
10
10
|
"pg": "8.7.3",
|
|
11
11
|
"pg-format": "1.0.4",
|
|
12
|
-
"sedentary": "0.0.
|
|
12
|
+
"sedentary": "0.0.28"
|
|
13
13
|
},
|
|
14
14
|
"description": "The ORM which never needs to migrate - PostgreSQL",
|
|
15
15
|
"devDependencies": {
|
|
@@ -44,6 +44,8 @@
|
|
|
44
44
|
"sqlite"
|
|
45
45
|
],
|
|
46
46
|
"license": "MIT",
|
|
47
|
+
"main": "./dist/cjs/index.js",
|
|
48
|
+
"module": "./dist/es/index.js",
|
|
47
49
|
"name": "sedentary-pg",
|
|
48
50
|
"prettier": {
|
|
49
51
|
"arrowParens": "avoid",
|
|
@@ -62,15 +64,14 @@
|
|
|
62
64
|
"packagejson": "node -r ts-node/register utils.ts packagejson",
|
|
63
65
|
"test": "mocha -r ts-node/register test/*ts",
|
|
64
66
|
"travis": "node -r ts-node/register utils.ts travis",
|
|
65
|
-
"tsc": "tsc
|
|
67
|
+
"tsc": "tsc -p tsconfig.cjs.json && tsc -p tsconfig.es.json && tsc -p tsconfig.types.json",
|
|
66
68
|
"version": "node -r ts-node/register utils.ts version"
|
|
67
69
|
},
|
|
68
70
|
"tsd": {
|
|
69
71
|
"compilerOptions": {
|
|
70
72
|
"alwaysStrict": true,
|
|
71
|
-
"declaration": true,
|
|
72
73
|
"esModuleInterop": true,
|
|
73
|
-
"
|
|
74
|
+
"moduleResolution": "node",
|
|
74
75
|
"noImplicitAny": true,
|
|
75
76
|
"noImplicitReturns": true,
|
|
76
77
|
"noImplicitThis": true,
|
|
@@ -78,10 +79,9 @@
|
|
|
78
79
|
"strictBindCallApply": true,
|
|
79
80
|
"strictFunctionTypes": true,
|
|
80
81
|
"strictNullChecks": true,
|
|
81
|
-
"strictPropertyInitialization": true
|
|
82
|
-
"target": "es2017"
|
|
82
|
+
"strictPropertyInitialization": true
|
|
83
83
|
}
|
|
84
84
|
},
|
|
85
|
-
"types": "index.d.ts",
|
|
86
|
-
"version": "0.0.
|
|
87
|
-
}
|
|
85
|
+
"types": "./dist/types/index.d.ts",
|
|
86
|
+
"version": "0.0.28"
|
|
87
|
+
}
|