sedentary 0.0.10 → 0.0.14

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,341 @@
1
+ import { Pool, PoolClient, PoolConfig } from "pg";
2
+ import format from "pg-format";
3
+ import { Attribute, DB, Index, Natural, Table } from "sedentary/lib/db";
4
+
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", varchar: "VARCHAR" };
18
+
19
+ export class PGDB extends DB {
20
+ private client: PoolClient;
21
+ private indexes: string[];
22
+ private pool: Pool;
23
+ private version: number;
24
+
25
+ constructor(connection: PoolConfig, log: (message: string) => void) {
26
+ super(log);
27
+
28
+ this.pool = new Pool(connection);
29
+ }
30
+
31
+ async connect(): Promise<void> {
32
+ this.client = await this.pool.connect();
33
+
34
+ const res = await this.client.query("SELECT version()");
35
+
36
+ this.version = parseInt(res.rows[0].version.split(" ")[1].split(".")[0], 10);
37
+ }
38
+
39
+ async dropConstraints(table: Table): Promise<number[]> {
40
+ const indexes: number[] = [];
41
+ const res = await this.client.query("SELECT * FROM pg_constraint WHERE conrelid = $1 ORDER BY conname", [table.oid]);
42
+
43
+ for(const row of res.rows) {
44
+ const constraint = table.constraints.filter(_ => _.constraintName === row.conname);
45
+
46
+ if(constraint.length === 0) {
47
+ const statement = `ALTER TABLE ${table.tableName} DROP CONSTRAINT ${row.conname} CASCADE`;
48
+
49
+ this.log(statement);
50
+ await this.client.query(statement);
51
+ } else indexes.push(row.conindid);
52
+ }
53
+
54
+ return indexes;
55
+ }
56
+
57
+ async dropField(tableName: string, fieldName: string): Promise<void> {
58
+ const statement = `ALTER TABLE ${tableName} DROP COLUMN ${fieldName}`;
59
+
60
+ this.log(statement);
61
+ await this.client.query(statement);
62
+ }
63
+
64
+ async dropFields(table: Table): Promise<void> {
65
+ 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]);
66
+
67
+ for(const i in res.rows) if(table.attributes.filter(f => f.fieldName === res.rows[i].attname).length === 0) await this.dropField(table.tableName, res.rows[i].attname);
68
+ }
69
+
70
+ async dropIndexes(table: Table, constraintIndexes: number[]): Promise<void> {
71
+ const { indexes, oid } = table;
72
+ const iobject: { [key: string]: Index } = {};
73
+ const res = await this.client.query(
74
+ "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",
75
+ [oid]
76
+ );
77
+
78
+ for(const row of res.rows) {
79
+ const { amname, attname, indexrelid, indisunique, relname } = row;
80
+
81
+ if(! constraintIndexes.includes(indexrelid)) {
82
+ if(iobject[relname]) iobject[relname].fields.push(attname);
83
+ else iobject[relname] = { fields: [attname], indexName: relname, type: amname, unique: indisunique };
84
+ }
85
+ }
86
+
87
+ this.indexes = [];
88
+ for(const index of indexes) {
89
+ const { indexName } = index;
90
+
91
+ if(iobject[indexName] && this.indexesEq(index, iobject[indexName])) {
92
+ this.indexes.push(indexName);
93
+ delete iobject[indexName];
94
+ }
95
+ }
96
+
97
+ for(const index of Object.keys(iobject).sort()) {
98
+ const statement = `DROP INDEX ${index}`;
99
+
100
+ this.log(statement);
101
+ await this.client.query(statement);
102
+ }
103
+ }
104
+
105
+ async end(): Promise<void> {
106
+ await this.pool.end();
107
+ }
108
+
109
+ fieldType(attribute: Attribute<Natural, unknown>): string[] {
110
+ const { size, type } = attribute;
111
+ let ret;
112
+
113
+ switch(type) {
114
+ case "DATETIME":
115
+ return ["DATETIME", "TIMESTAMP (3) WITH TIME ZONE"];
116
+ case "INT":
117
+ ret = size === 2 ? "SMALLINT" : "INTEGER";
118
+
119
+ return [ret, ret];
120
+ case "INT8":
121
+ return ["BIGINT", "BIGINT"];
122
+ case "VARCHAR":
123
+ return ["VARCHAR", "VARCHAR" + (size ? `(${size})` : "")];
124
+ }
125
+
126
+ throw new Error(`Unknown type: '${type}', '${size}'`);
127
+ }
128
+
129
+ async sync(): Promise<void> {
130
+ let err: Error;
131
+
132
+ try {
133
+ await super.sync();
134
+ } catch(e) {
135
+ err = e;
136
+ }
137
+
138
+ this.client.release();
139
+
140
+ if(err) throw err;
141
+ }
142
+
143
+ async syncConstraints(table: Table): Promise<void> {
144
+ for(const constraint of table.constraints) {
145
+ const { attribute, constraintName, type } = constraint;
146
+ 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", [
147
+ table.oid,
148
+ attribute.fieldName
149
+ ]);
150
+
151
+ if(! res.rowCount) {
152
+ let query: string;
153
+
154
+ switch(type) {
155
+ case "f":
156
+ query = `FOREIGN KEY (${attribute.fieldName}) REFERENCES ${attribute.foreignKey.tableName}(${attribute.foreignKey.fieldName})`;
157
+ break;
158
+ case "u":
159
+ query = `UNIQUE(${attribute.fieldName})`;
160
+ break;
161
+ }
162
+
163
+ const statement = `ALTER TABLE ${table.tableName} ADD CONSTRAINT ${constraintName} ${query}`;
164
+
165
+ this.log(statement);
166
+ await this.client.query(statement);
167
+ }
168
+ }
169
+ }
170
+
171
+ async syncFields(table: Table): Promise<void> {
172
+ const { attributes, oid, tableName } = table;
173
+
174
+ for(const attribute of attributes) {
175
+ const { fieldName, notNull, size } = attribute;
176
+ const defaultValue = attribute.defaultValue === undefined ? undefined : format("%L", attribute.defaultValue);
177
+ const [base, type] = this.fieldType(attribute);
178
+
179
+ const res = await this.client.query(
180
+ `SELECT attnotnull, atttypmod, typname, ${
181
+ this.version >= 12 ? "pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) AS adsrc" : "adsrc"
182
+ } FROM pg_type, pg_attribute LEFT JOIN pg_attrdef ON adrelid = attrelid AND adnum = attnum WHERE attrelid = $1 AND attnum > 0 AND atttypid = pg_type.oid AND attislocal = 't' AND attname = $2`,
183
+ [oid, fieldName]
184
+ );
185
+
186
+ const addField = async () => {
187
+ const statement = `ALTER TABLE ${tableName} ADD COLUMN ${fieldName} ${type}`;
188
+
189
+ this.log(statement);
190
+ await this.client.query(statement);
191
+ };
192
+
193
+ const dropDefault = async () => {
194
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} DROP DEFAULT`;
195
+
196
+ this.log(statement);
197
+ await this.client.query(statement);
198
+ };
199
+
200
+ const setNotNull = async (isNull: boolean) => {
201
+ if(isNull === notNull) return;
202
+
203
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} ${notNull ? "SET" : "DROP"} NOT NULL`;
204
+
205
+ this.log(statement);
206
+ await this.client.query(statement);
207
+ };
208
+
209
+ const setDefault = async (isNull: boolean) => {
210
+ if(defaultValue !== undefined) {
211
+ let statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} SET DEFAULT ${defaultValue}`;
212
+
213
+ this.log(statement);
214
+ await this.client.query(statement);
215
+
216
+ if(isNull) {
217
+ statement = `UPDATE ${tableName} SET ${fieldName} = ${defaultValue} WHERE ${fieldName} IS NULL`;
218
+
219
+ this.log(statement);
220
+ this.client.query(statement);
221
+ }
222
+ }
223
+
224
+ await setNotNull(isNull);
225
+ };
226
+
227
+ if(! res.rowCount) {
228
+ await addField();
229
+ await setDefault(false);
230
+ } else {
231
+ const { adsrc, attnotnull, atttypmod, typname } = res.rows[0];
232
+
233
+ if(types[typname] !== base || (base === "VARCHAR" && (size ? size + 4 !== atttypmod : atttypmod !== -1))) {
234
+ if(needDrop.filter(([type, name]) => attribute.type === type && typname === name).length) {
235
+ await this.dropField(tableName, fieldName);
236
+ await addField();
237
+ await setDefault(false);
238
+ } else {
239
+ if(adsrc) dropDefault();
240
+
241
+ const using = needUsing.filter(([type, name]) => attribute.type === type && typname === name).length ? " USING " + fieldName + "::" + type : "";
242
+ const statement = `ALTER TABLE ${tableName} ALTER COLUMN ${fieldName} TYPE ${type}${using}`;
243
+
244
+ this.log(statement);
245
+ await this.client.query(statement);
246
+ await setDefault(attnotnull);
247
+ }
248
+ } else if(defaultValue === undefined) {
249
+ if(adsrc) dropDefault();
250
+ await setNotNull(attnotnull);
251
+ } else if(! adsrc || adsrc.split("::")[0] !== defaultValue) await setDefault(attnotnull);
252
+ }
253
+ }
254
+ }
255
+
256
+ async syncIndexes(table: Table): Promise<void> {
257
+ const { indexes, tableName } = table;
258
+
259
+ for(const index of indexes) {
260
+ const { fields, indexName, type, unique } = index;
261
+
262
+ if(! this.indexes.includes(indexName)) {
263
+ const statement = `CREATE${unique ? " UNIQUE" : ""} INDEX ${indexName} ON ${tableName} USING ${type} (${fields.join(", ")})`;
264
+
265
+ this.log(statement);
266
+ await this.client.query(statement);
267
+ }
268
+ }
269
+ }
270
+
271
+ async syncSequence(table: Table): Promise<void> {
272
+ if(! table.autoIncrementOwn) return;
273
+
274
+ const statement = `ALTER SEQUENCE ${table.tableName}_id_seq OWNED BY ${table.tableName}.id`;
275
+
276
+ this.log(statement);
277
+ await this.client.query(statement);
278
+ }
279
+
280
+ async syncTable(table: Table): Promise<void> {
281
+ if(table.autoIncrement) {
282
+ await (async () => {
283
+ try {
284
+ await this.client.query(`SELECT currval('${table.tableName}_id_seq')`);
285
+ } catch(e) {
286
+ if(e.code === "55000") return;
287
+ if(e.code === "42P01") {
288
+ const statement = `CREATE SEQUENCE ${table.tableName}_id_seq`;
289
+
290
+ this.log(statement);
291
+ await this.client.query(statement);
292
+ table.autoIncrementOwn = true;
293
+
294
+ return;
295
+ }
296
+
297
+ throw e;
298
+ }
299
+ })();
300
+ }
301
+
302
+ let create: boolean;
303
+ const resTable = await this.client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
304
+
305
+ if(resTable.rowCount) {
306
+ table.oid = resTable.rows[0].oid;
307
+
308
+ let drop: boolean;
309
+ const resParent = await this.client.query("SELECT inhparent FROM pg_inherits WHERE inhrelid = $1", [table.oid]);
310
+
311
+ if(resParent.rowCount) {
312
+ if(! table.parent) drop = true;
313
+ else if(this.tables[table.parent.tableName].oid === resParent.rows[0].inhparent) return;
314
+
315
+ drop = true;
316
+ } else if(table.parent) drop = true;
317
+
318
+ if(drop) {
319
+ const statement = `DROP TABLE ${table.tableName} CASCADE`;
320
+
321
+ create = true;
322
+ this.log(statement);
323
+ await this.client.query(statement);
324
+ }
325
+ } else create = true;
326
+
327
+ if(create) {
328
+ const parent = table.parent ? ` INHERITS (${table.parent.tableName})` : "";
329
+ const statement = `CREATE TABLE ${table.tableName} ()${parent}`;
330
+
331
+ this.log(statement);
332
+ await this.client.query(statement);
333
+
334
+ const resTable = await this.client.query("SELECT oid FROM pg_class WHERE relname = $1", [table.tableName]);
335
+
336
+ table.oid = resTable.rows[0].oid;
337
+ }
338
+ }
339
+ }
340
+
341
+ // farray[0].defaultValue = "nextval('" + tname + "_id_seq'::regclass)";