@zero-server/sdk 0.9.0 → 0.9.2
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/LICENSE +21 -21
- package/README.md +460 -437
- package/index.js +414 -412
- package/lib/app.js +1172 -1172
- package/lib/auth/authorize.js +399 -399
- package/lib/auth/enrollment.js +367 -367
- package/lib/auth/index.js +57 -57
- package/lib/auth/jwt.js +731 -731
- package/lib/auth/oauth.js +362 -362
- package/lib/auth/session.js +588 -588
- package/lib/auth/trustedDevice.js +409 -409
- package/lib/auth/twoFactor.js +1150 -1150
- package/lib/auth/webauthn.js +946 -946
- package/lib/body/index.js +14 -14
- package/lib/body/json.js +109 -109
- package/lib/body/multipart.js +440 -440
- package/lib/body/raw.js +71 -71
- package/lib/body/rawBuffer.js +160 -160
- package/lib/body/sendError.js +25 -25
- package/lib/body/text.js +75 -75
- package/lib/body/typeMatch.js +41 -41
- package/lib/body/urlencoded.js +235 -235
- package/lib/cli.js +845 -845
- package/lib/cluster.js +666 -666
- package/lib/debug.js +372 -372
- package/lib/env/index.js +460 -460
- package/lib/errors.js +683 -683
- package/lib/fetch/index.js +256 -256
- package/lib/grpc/balancer.js +378 -378
- package/lib/grpc/call.js +708 -708
- package/lib/grpc/client.js +764 -764
- package/lib/grpc/codec.js +1221 -1221
- package/lib/grpc/credentials.js +398 -398
- package/lib/grpc/frame.js +262 -262
- package/lib/grpc/health.js +287 -287
- package/lib/grpc/index.js +121 -121
- package/lib/grpc/metadata.js +461 -461
- package/lib/grpc/proto.js +821 -821
- package/lib/grpc/reflection.js +590 -590
- package/lib/grpc/server.js +445 -445
- package/lib/grpc/status.js +118 -118
- package/lib/grpc/watch.js +173 -173
- package/lib/http/index.js +10 -10
- package/lib/http/request.js +727 -727
- package/lib/http/response.js +799 -799
- package/lib/lifecycle.js +557 -557
- package/lib/middleware/compress.js +230 -230
- package/lib/middleware/cookieParser.js +237 -237
- package/lib/middleware/cors.js +93 -93
- package/lib/middleware/csrf.js +136 -136
- package/lib/middleware/errorHandler.js +101 -101
- package/lib/middleware/helmet.js +175 -175
- package/lib/middleware/index.js +19 -17
- package/lib/middleware/logger.js +74 -74
- package/lib/middleware/rateLimit.js +88 -88
- package/lib/middleware/requestId.js +53 -53
- package/lib/middleware/static.js +326 -326
- package/lib/middleware/timeout.js +71 -71
- package/lib/middleware/validator.js +254 -254
- package/lib/observe/health.js +326 -326
- package/lib/observe/index.js +50 -50
- package/lib/observe/logger.js +359 -359
- package/lib/observe/metrics.js +805 -805
- package/lib/observe/tracing.js +592 -592
- package/lib/orm/adapters/json.js +290 -290
- package/lib/orm/adapters/memory.js +764 -764
- package/lib/orm/adapters/mongo.js +764 -764
- package/lib/orm/adapters/mysql.js +933 -933
- package/lib/orm/adapters/postgres.js +1144 -1144
- package/lib/orm/adapters/redis.js +1534 -1534
- package/lib/orm/adapters/sql-base.js +212 -212
- package/lib/orm/adapters/sqlite.js +858 -858
- package/lib/orm/audit.js +649 -649
- package/lib/orm/cache.js +394 -394
- package/lib/orm/geo.js +387 -387
- package/lib/orm/index.js +784 -784
- package/lib/orm/migrate.js +432 -432
- package/lib/orm/model.js +1706 -1706
- package/lib/orm/plugin.js +375 -375
- package/lib/orm/procedures.js +836 -836
- package/lib/orm/profiler.js +233 -233
- package/lib/orm/query.js +1772 -1772
- package/lib/orm/replicas.js +241 -241
- package/lib/orm/schema.js +307 -307
- package/lib/orm/search.js +380 -380
- package/lib/orm/seed/data/commerce.js +136 -136
- package/lib/orm/seed/data/internet.js +111 -111
- package/lib/orm/seed/data/locations.js +204 -204
- package/lib/orm/seed/data/names.js +338 -338
- package/lib/orm/seed/data/person.js +128 -128
- package/lib/orm/seed/data/phone.js +211 -211
- package/lib/orm/seed/data/words.js +134 -134
- package/lib/orm/seed/factory.js +178 -178
- package/lib/orm/seed/fake.js +1186 -1186
- package/lib/orm/seed/index.js +18 -18
- package/lib/orm/seed/rng.js +70 -70
- package/lib/orm/seed/seeder.js +124 -124
- package/lib/orm/seed/unique.js +68 -68
- package/lib/orm/snapshot.js +366 -366
- package/lib/orm/tenancy.js +605 -605
- package/lib/orm/views.js +350 -350
- package/lib/router/index.js +436 -436
- package/lib/sse/index.js +8 -8
- package/lib/sse/stream.js +349 -349
- package/lib/ws/connection.js +451 -451
- package/lib/ws/handshake.js +125 -125
- package/lib/ws/index.js +14 -14
- package/lib/ws/room.js +223 -223
- package/package.json +73 -73
- package/types/app.d.ts +223 -223
- package/types/auth.d.ts +520 -520
- package/types/cluster.d.ts +75 -75
- package/types/env.d.ts +80 -80
- package/types/errors.d.ts +316 -316
- package/types/fetch.d.ts +43 -43
- package/types/grpc.d.ts +432 -432
- package/types/index.d.ts +384 -384
- package/types/lifecycle.d.ts +60 -60
- package/types/middleware.d.ts +320 -320
- package/types/observe.d.ts +304 -304
- package/types/orm.d.ts +1887 -1887
- package/types/request.d.ts +109 -109
- package/types/response.d.ts +157 -157
- package/types/router.d.ts +78 -78
- package/types/sse.d.ts +78 -78
- package/types/websocket.d.ts +126 -126
|
@@ -1,1144 +1,1144 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module orm/adapters/postgres
|
|
3
|
-
* @description PostgreSQL adapter using the optional `pg` driver.
|
|
4
|
-
* Requires: `npm install pg`
|
|
5
|
-
*
|
|
6
|
-
* @example
|
|
7
|
-
* const { Database, Model, TYPES } = require('@zero-server/sdk');
|
|
8
|
-
*
|
|
9
|
-
* const db = Database.connect('postgres', {
|
|
10
|
-
* host: '127.0.0.1',
|
|
11
|
-
* user: 'postgres',
|
|
12
|
-
* password: '',
|
|
13
|
-
* database: 'myapp',
|
|
14
|
-
* });
|
|
15
|
-
*
|
|
16
|
-
* class Article extends Model {
|
|
17
|
-
* static table = 'articles';
|
|
18
|
-
* static schema = {
|
|
19
|
-
* id: { type: TYPES.SERIAL, primaryKey: true },
|
|
20
|
-
* title: { type: TYPES.STRING, required: true },
|
|
21
|
-
* content: { type: TYPES.TEXT },
|
|
22
|
-
* tags: { type: TYPES.JSONB, default: [] },
|
|
23
|
-
* };
|
|
24
|
-
* static timestamps = true;
|
|
25
|
-
* }
|
|
26
|
-
*
|
|
27
|
-
* db.register(Article);
|
|
28
|
-
* await db.sync();
|
|
29
|
-
*
|
|
30
|
-
* await Article.create({ title: 'Hello', content: 'World', tags: ['intro'] });
|
|
31
|
-
* const recent = await Article.query().orderBy('createdAt', 'desc').limit(10).exec();
|
|
32
|
-
*/
|
|
33
|
-
const BaseSqlAdapter = require('./sql-base');
|
|
34
|
-
const { validateFKAction, validateCheck } = require('../schema');
|
|
35
|
-
|
|
36
|
-
class PostgresAdapter extends BaseSqlAdapter
|
|
37
|
-
{
|
|
38
|
-
/**
|
|
39
|
-
* @constructor
|
|
40
|
-
* @param {object} options - Configuration options.
|
|
41
|
-
* @param {string} [options.user] - Database user.
|
|
42
|
-
* @param {string} [options.password] - Database password.
|
|
43
|
-
* @param {string} options.database - Database name.
|
|
44
|
-
* @param {number} [options.max=10] - Max pool size.
|
|
45
|
-
* @param {number} [options.idleTimeoutMillis=10000] - Idle client timeout.
|
|
46
|
-
* @param {number} [options.connectionTimeoutMillis=0] - Connection timeout (0 = no limit).
|
|
47
|
-
* @param {boolean|object} [options.ssl] - SSL mode or TLS options.
|
|
48
|
-
* @param {string} [options.connectionString] - Full connection URI (overrides individual settings).
|
|
49
|
-
* @param {string} [options.application_name] - Identify the app in pg_stat_activity.
|
|
50
|
-
* @param {number} [options.statement_timeout] - Statement timeout in ms.
|
|
51
|
-
*/
|
|
52
|
-
constructor(options = {})
|
|
53
|
-
{
|
|
54
|
-
super();
|
|
55
|
-
let pg;
|
|
56
|
-
try { pg = require('pg'); }
|
|
57
|
-
catch (e)
|
|
58
|
-
{
|
|
59
|
-
throw new Error(
|
|
60
|
-
'PostgreSQL adapter requires "pg" package.\n' +
|
|
61
|
-
'Install it with: npm install pg'
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
this._pool = new pg.Pool({ max: 10, ...options });
|
|
65
|
-
this._options = options;
|
|
66
|
-
|
|
67
|
-
/** @private Prepared statement name cache for pg named queries */
|
|
68
|
-
this._stmtCache = new Map();
|
|
69
|
-
this._stmtCacheHits = 0;
|
|
70
|
-
this._stmtCacheMisses = 0;
|
|
71
|
-
this._stmtCacheMax = options.stmtCacheSize || 256;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** @private */
|
|
75
|
-
_typeMap(colDef)
|
|
76
|
-
{
|
|
77
|
-
const map = {
|
|
78
|
-
string: `VARCHAR(${colDef.maxLength || 255})`, text: 'TEXT',
|
|
79
|
-
integer: 'INTEGER', float: 'DOUBLE PRECISION', boolean: 'BOOLEAN',
|
|
80
|
-
date: 'DATE', datetime: 'TIMESTAMPTZ', json: 'JSONB', blob: 'BYTEA',
|
|
81
|
-
uuid: 'UUID',
|
|
82
|
-
bigint: 'BIGINT', smallint: 'SMALLINT', tinyint: 'SMALLINT',
|
|
83
|
-
decimal: `NUMERIC(${colDef.precision || 10},${colDef.scale || 2})`,
|
|
84
|
-
serial: 'SERIAL', bigserial: 'BIGSERIAL',
|
|
85
|
-
timestamp: 'TIMESTAMP', time: 'TIME', interval: 'INTERVAL',
|
|
86
|
-
inet: 'INET', cidr: 'CIDR', macaddr: 'MACADDR',
|
|
87
|
-
money: 'MONEY', real: 'REAL', double: 'DOUBLE PRECISION',
|
|
88
|
-
jsonb: 'JSONB', xml: 'XML', citext: 'CITEXT',
|
|
89
|
-
array: colDef.arrayOf ? `${colDef.arrayOf}[]` : 'TEXT[]',
|
|
90
|
-
binary: 'BYTEA', varbinary: 'BYTEA',
|
|
91
|
-
char: `CHAR(${colDef.length || 1})`,
|
|
92
|
-
enum: colDef.enum
|
|
93
|
-
? `VARCHAR(255) CHECK ("${(colDef._name || 'col').replace(/"/g, '""')}" IN (${colDef.enum.map(v => `'${String(v).replace(/'/g, "''")}'`).join(',')}))`
|
|
94
|
-
: 'VARCHAR(255)',
|
|
95
|
-
};
|
|
96
|
-
return map[colDef.type] || 'TEXT';
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* @private
|
|
101
|
-
* PostgreSQL uses $1, $2, ... style parameters.
|
|
102
|
-
* Override the base class WHERE builders.
|
|
103
|
-
*/
|
|
104
|
-
|
|
105
|
-
_buildWherePg(conditions, startIdx = 1)
|
|
106
|
-
{
|
|
107
|
-
if (!conditions || Object.keys(conditions).length === 0)
|
|
108
|
-
return { clause: '', values: [], nextIdx: startIdx };
|
|
109
|
-
const parts = [];
|
|
110
|
-
const values = [];
|
|
111
|
-
let idx = startIdx;
|
|
112
|
-
for (const [k, v] of Object.entries(conditions))
|
|
113
|
-
{
|
|
114
|
-
if (v === null) { parts.push(`"${k}" IS NULL`); }
|
|
115
|
-
else { parts.push(`"${k}" = $${idx++}`); values.push(this._toSqlValue(v)); }
|
|
116
|
-
}
|
|
117
|
-
return { clause: ' WHERE ' + parts.join(' AND '), values, nextIdx: idx };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** @private */
|
|
121
|
-
_buildWhereFromChainPg(where, startIdx = 1)
|
|
122
|
-
{
|
|
123
|
-
if (!where || where.length === 0) return { clause: '', values: [], nextIdx: startIdx };
|
|
124
|
-
const parts = [];
|
|
125
|
-
const values = [];
|
|
126
|
-
let idx = startIdx;
|
|
127
|
-
|
|
128
|
-
for (let i = 0; i < where.length; i++)
|
|
129
|
-
{
|
|
130
|
-
const w = where[i];
|
|
131
|
-
|
|
132
|
-
// Handle raw WHERE clauses (from whereRaw) — convert ? to $N
|
|
133
|
-
if (w.raw)
|
|
134
|
-
{
|
|
135
|
-
let rawExpr = w.raw;
|
|
136
|
-
if (w.params)
|
|
137
|
-
{
|
|
138
|
-
for (const p of w.params)
|
|
139
|
-
{
|
|
140
|
-
rawExpr = rawExpr.replace('?', `$${idx++}`);
|
|
141
|
-
values.push(p);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (i === 0) parts.push(rawExpr);
|
|
145
|
-
else parts.push(`${w.logic} ${rawExpr}`);
|
|
146
|
-
continue;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const { field, op, value, logic } = w;
|
|
150
|
-
let expr;
|
|
151
|
-
|
|
152
|
-
if (op === 'IS NULL') expr = `"${field}" IS NULL`;
|
|
153
|
-
else if (op === 'IS NOT NULL') expr = `"${field}" IS NOT NULL`;
|
|
154
|
-
else if (op === 'IN' || op === 'NOT IN')
|
|
155
|
-
{
|
|
156
|
-
if (!Array.isArray(value) || value.length === 0)
|
|
157
|
-
expr = op === 'IN' ? '0=1' : '1=1';
|
|
158
|
-
else
|
|
159
|
-
{
|
|
160
|
-
const placeholders = value.map(() => `$${idx++}`).join(', ');
|
|
161
|
-
expr = `"${field}" ${op} (${placeholders})`;
|
|
162
|
-
values.push(...value.map(v => this._toSqlValue(v)));
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
else if (op === 'BETWEEN')
|
|
166
|
-
{
|
|
167
|
-
expr = `"${field}" BETWEEN $${idx++} AND $${idx++}`;
|
|
168
|
-
values.push(this._toSqlValue(value[0]), this._toSqlValue(value[1]));
|
|
169
|
-
}
|
|
170
|
-
else
|
|
171
|
-
{
|
|
172
|
-
expr = `"${field}" ${op} $${idx++}`;
|
|
173
|
-
values.push(this._toSqlValue(value));
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
if (i === 0) parts.push(expr);
|
|
177
|
-
else parts.push(`${logic} ${expr}`);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
return { clause: ' WHERE ' + parts.join(' '), values, nextIdx: idx };
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Create a table with the given schema.
|
|
185
|
-
* @param {string} table - Table name.
|
|
186
|
-
* @param {object} schema - Column definitions keyed by column name.
|
|
187
|
-
* @returns {Promise<void>}
|
|
188
|
-
*/
|
|
189
|
-
async createTable(table, schema, tableOptions = {})
|
|
190
|
-
{
|
|
191
|
-
const cols = [];
|
|
192
|
-
const tableConstraints = [];
|
|
193
|
-
const compositePKs = [];
|
|
194
|
-
|
|
195
|
-
for (const [name, def] of Object.entries(schema))
|
|
196
|
-
{
|
|
197
|
-
// Pass column name for enum CHECK constraints
|
|
198
|
-
const defWithName = { ...def, _name: name };
|
|
199
|
-
|
|
200
|
-
// Collect composite PK candidates
|
|
201
|
-
if (def.primaryKey && def.compositeKey)
|
|
202
|
-
{
|
|
203
|
-
compositePKs.push(name);
|
|
204
|
-
let line = `"${name}" ${this._typeMap(defWithName)}`;
|
|
205
|
-
if (def.required) line += ' NOT NULL';
|
|
206
|
-
cols.push(line);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
let line = `"${name}" ${this._typeMap(defWithName)}`;
|
|
211
|
-
if (def.primaryKey && def.autoIncrement)
|
|
212
|
-
{
|
|
213
|
-
line = `"${name}" SERIAL PRIMARY KEY`;
|
|
214
|
-
}
|
|
215
|
-
else
|
|
216
|
-
{
|
|
217
|
-
if (def.primaryKey) line += ' PRIMARY KEY';
|
|
218
|
-
if (def.required && !def.primaryKey) line += ' NOT NULL';
|
|
219
|
-
if (def.unique && !def.compositeUnique) line += ' UNIQUE';
|
|
220
|
-
if (def.default !== undefined && typeof def.default !== 'function')
|
|
221
|
-
line += ` DEFAULT ${this._sqlDefault(def.default)}`;
|
|
222
|
-
|
|
223
|
-
// CHECK constraint
|
|
224
|
-
if (def.check) line += ` CHECK(${validateCheck(def.check)})`;
|
|
225
|
-
|
|
226
|
-
if (def.references)
|
|
227
|
-
{
|
|
228
|
-
line += ` REFERENCES "${def.references.table}"("${def.references.column || 'id'}")`;
|
|
229
|
-
if (def.references.onDelete) line += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
|
|
230
|
-
if (def.references.onUpdate) line += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
cols.push(line);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// Composite primary key
|
|
237
|
-
if (compositePKs.length > 0)
|
|
238
|
-
{
|
|
239
|
-
tableConstraints.push(`PRIMARY KEY (${compositePKs.map(k => `"${k}"`).join(', ')})`);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// Composite unique constraints
|
|
243
|
-
const compositeUniques = {};
|
|
244
|
-
for (const [name, def] of Object.entries(schema))
|
|
245
|
-
{
|
|
246
|
-
if (def.compositeUnique)
|
|
247
|
-
{
|
|
248
|
-
const group = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
|
|
249
|
-
if (!compositeUniques[group]) compositeUniques[group] = [];
|
|
250
|
-
compositeUniques[group].push(name);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
for (const [group, columns] of Object.entries(compositeUniques))
|
|
254
|
-
{
|
|
255
|
-
tableConstraints.push(`CONSTRAINT "uq_${table}_${group}" UNIQUE (${columns.map(c => `"${c}"`).join(', ')})`);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const allParts = [...cols, ...tableConstraints];
|
|
259
|
-
let sql = `CREATE TABLE IF NOT EXISTS "${table}" (${allParts.join(', ')})`;
|
|
260
|
-
if (tableOptions.tablespace)
|
|
261
|
-
{
|
|
262
|
-
const ts = String(tableOptions.tablespace);
|
|
263
|
-
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(ts)) throw new Error(`Invalid tablespace name: ${ts}`);
|
|
264
|
-
sql += ` TABLESPACE ${ts}`;
|
|
265
|
-
}
|
|
266
|
-
if (tableOptions.unlogged) sql = sql.replace('CREATE TABLE', 'CREATE UNLOGGED TABLE');
|
|
267
|
-
await this._pool.query(sql);
|
|
268
|
-
if (tableOptions.comment)
|
|
269
|
-
{
|
|
270
|
-
await this._pool.query(`COMMENT ON TABLE "${table}" IS $1`, [tableOptions.comment]);
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
// Create indexes defined in schema
|
|
274
|
-
for (const [name, def] of Object.entries(schema))
|
|
275
|
-
{
|
|
276
|
-
if (def.index)
|
|
277
|
-
{
|
|
278
|
-
const idxName = typeof def.index === 'string' ? def.index : `idx_${table}_${name}`;
|
|
279
|
-
await this._pool.query(`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${table}" ("${name}")`);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
// Composite indexes
|
|
284
|
-
const compositeIndexes = {};
|
|
285
|
-
for (const [name, def] of Object.entries(schema))
|
|
286
|
-
{
|
|
287
|
-
if (def.compositeIndex)
|
|
288
|
-
{
|
|
289
|
-
const group = typeof def.compositeIndex === 'string' ? def.compositeIndex : 'default';
|
|
290
|
-
if (!compositeIndexes[group]) compositeIndexes[group] = [];
|
|
291
|
-
compositeIndexes[group].push(name);
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
for (const [group, columns] of Object.entries(compositeIndexes))
|
|
295
|
-
{
|
|
296
|
-
const idxName = `idx_${table}_${group}`;
|
|
297
|
-
await this._pool.query(`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${table}" (${columns.map(c => `"${c}"`).join(', ')})`);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Drop a table if it exists.
|
|
303
|
-
* @param {string} table - Table name.
|
|
304
|
-
* @returns {Promise<void>}
|
|
305
|
-
*/
|
|
306
|
-
async dropTable(table)
|
|
307
|
-
{
|
|
308
|
-
await this._pool.query(`DROP TABLE IF EXISTS "${table}"`);
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Insert a single row.
|
|
313
|
-
* @param {string} table - Table name.
|
|
314
|
-
* @param {object} data - Row data as key-value pairs.
|
|
315
|
-
* @returns {Promise<object>} The inserted row.
|
|
316
|
-
*/
|
|
317
|
-
async insert(table, data)
|
|
318
|
-
{
|
|
319
|
-
const keys = Object.keys(data);
|
|
320
|
-
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
321
|
-
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
|
|
322
|
-
const sql = `INSERT INTO "${table}" (${keys.map(k => `"${k}"`).join(', ')}) VALUES (${placeholders}) RETURNING *`;
|
|
323
|
-
const { rows } = await this._pool.query(sql, values);
|
|
324
|
-
return rows[0] || { ...data };
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* Insert multiple rows in a batch.
|
|
329
|
-
* @param {string} table - Table name.
|
|
330
|
-
* @param {Array<object>} dataArray - Array of row objects.
|
|
331
|
-
* @returns {Promise<Array<object>>} The inserted rows.
|
|
332
|
-
*/
|
|
333
|
-
async insertMany(table, dataArray)
|
|
334
|
-
{
|
|
335
|
-
if (!dataArray.length) return [];
|
|
336
|
-
const keys = Object.keys(dataArray[0]);
|
|
337
|
-
const values = [];
|
|
338
|
-
let idx = 1;
|
|
339
|
-
const rowPlaceholders = dataArray.map(data => {
|
|
340
|
-
const ph = keys.map(() => `$${idx++}`).join(', ');
|
|
341
|
-
for (const k of keys) values.push(this._toSqlValue(data[k]));
|
|
342
|
-
return `(${ph})`;
|
|
343
|
-
}).join(', ');
|
|
344
|
-
const sql = `INSERT INTO "${table}" (${keys.map(k => `"${k}"`).join(', ')}) VALUES ${rowPlaceholders} RETURNING *`;
|
|
345
|
-
const { rows } = await this._pool.query(sql, values);
|
|
346
|
-
return rows;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Update a single row by primary key.
|
|
351
|
-
* @param {string} table - Table name.
|
|
352
|
-
* @param {string} pk - Primary key column.
|
|
353
|
-
* @param {*} pkVal - Primary key value.
|
|
354
|
-
* @param {object} data - Fields to update.
|
|
355
|
-
* @returns {Promise<void>}
|
|
356
|
-
*/
|
|
357
|
-
async update(table, pk, pkVal, data)
|
|
358
|
-
{
|
|
359
|
-
const keys = Object.keys(data);
|
|
360
|
-
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
361
|
-
const sets = keys.map((k, i) => `"${k}" = $${i + 1}`).join(', ');
|
|
362
|
-
values.push(pkVal);
|
|
363
|
-
await this._pool.query(`UPDATE "${table}" SET ${sets} WHERE "${pk}" = $${values.length}`, values);
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/**
|
|
367
|
-
* Update rows matching the given conditions.
|
|
368
|
-
* @param {string} table - Table name.
|
|
369
|
-
* @param {object} conditions - Filter conditions.
|
|
370
|
-
* @param {object} data - Fields to update.
|
|
371
|
-
* @returns {Promise<number>} Number of affected rows.
|
|
372
|
-
*/
|
|
373
|
-
async updateWhere(table, conditions, data)
|
|
374
|
-
{
|
|
375
|
-
const keys = Object.keys(data);
|
|
376
|
-
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
377
|
-
const sets = keys.map((k, i) => `"${k}" = $${i + 1}`).join(', ');
|
|
378
|
-
const { clause, values: whereVals } = this._buildWherePg(conditions, keys.length + 1);
|
|
379
|
-
values.push(...whereVals);
|
|
380
|
-
const { rowCount } = await this._pool.query(`UPDATE "${table}" SET ${sets}${clause}`, values);
|
|
381
|
-
return rowCount;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
/**
|
|
385
|
-
* Delete a single row by primary key.
|
|
386
|
-
* @param {string} table - Table name.
|
|
387
|
-
* @param {string} pk - Primary key column.
|
|
388
|
-
* @param {*} pkVal - Primary key value.
|
|
389
|
-
* @returns {Promise<void>}
|
|
390
|
-
*/
|
|
391
|
-
async remove(table, pk, pkVal)
|
|
392
|
-
{
|
|
393
|
-
await this._pool.query(`DELETE FROM "${table}" WHERE "${pk}" = $1`, [pkVal]);
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* Delete rows matching the given conditions.
|
|
398
|
-
* @param {string} table - Table name.
|
|
399
|
-
* @param {object} conditions - Filter conditions.
|
|
400
|
-
* @returns {Promise<number>} Number of deleted rows.
|
|
401
|
-
*/
|
|
402
|
-
async deleteWhere(table, conditions)
|
|
403
|
-
{
|
|
404
|
-
const { clause, values } = this._buildWherePg(conditions);
|
|
405
|
-
const { rowCount } = await this._pool.query(`DELETE FROM "${table}"${clause}`, values);
|
|
406
|
-
return rowCount;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* Execute a query descriptor built by the Query builder.
|
|
411
|
-
* @param {object} descriptor - Query descriptor with table, fields, where, orderBy, limit, offset.
|
|
412
|
-
* @returns {Promise<Array<object>>} Result rows.
|
|
413
|
-
*/
|
|
414
|
-
async execute(descriptor)
|
|
415
|
-
{
|
|
416
|
-
const { action, table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
|
|
417
|
-
|
|
418
|
-
if (action === 'count')
|
|
419
|
-
{
|
|
420
|
-
const joinStr = this._buildJoins(joins, table);
|
|
421
|
-
const { clause, values } = this._buildWhereFromChainPg(where);
|
|
422
|
-
const { rows } = await this._pool.query(`SELECT COUNT(*) as count FROM "${table}"${joinStr}${clause}`, values);
|
|
423
|
-
return parseInt(rows[0].count, 10);
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
const selectFields = fields && fields.length ? fields.map(f => `"${f}"`).join(', ') : '*';
|
|
427
|
-
const distinctStr = distinct ? 'DISTINCT ' : '';
|
|
428
|
-
const joinStr = this._buildJoins(joins, table);
|
|
429
|
-
let sql = `SELECT ${distinctStr}${selectFields} FROM "${table}"${joinStr}`;
|
|
430
|
-
const values = [];
|
|
431
|
-
let paramIdx = 1;
|
|
432
|
-
|
|
433
|
-
if (where && where.length)
|
|
434
|
-
{
|
|
435
|
-
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
436
|
-
sql += clause;
|
|
437
|
-
values.push(...wv);
|
|
438
|
-
paramIdx = nextIdx;
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
sql += this._buildGroupBy(groupBy);
|
|
442
|
-
|
|
443
|
-
if (having && having.length)
|
|
444
|
-
{
|
|
445
|
-
const { clause: hClause, nextIdx: hIdx } = this._buildHavingPg(having, values, paramIdx);
|
|
446
|
-
sql += hClause;
|
|
447
|
-
paramIdx = hIdx;
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
if (orderBy && orderBy.length)
|
|
451
|
-
sql += ' ORDER BY ' + orderBy.map(o => `"${o.field}" ${o.dir}`).join(', ');
|
|
452
|
-
if (limit !== null && limit !== undefined)
|
|
453
|
-
{
|
|
454
|
-
sql += ` LIMIT $${paramIdx++}`;
|
|
455
|
-
values.push(limit);
|
|
456
|
-
}
|
|
457
|
-
if (offset !== null && offset !== undefined)
|
|
458
|
-
{
|
|
459
|
-
sql += ` OFFSET $${paramIdx++}`;
|
|
460
|
-
values.push(offset);
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
const { rows } = await this._pool.query(sql, values);
|
|
464
|
-
return rows;
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
/**
|
|
468
|
-
* Execute an aggregate function (count, sum, avg, min, max).
|
|
469
|
-
* @param {object} descriptor - Aggregate descriptor with table, function, field, where.
|
|
470
|
-
* @returns {Promise<number|null>} Aggregate result.
|
|
471
|
-
*/
|
|
472
|
-
async aggregate(descriptor)
|
|
473
|
-
{
|
|
474
|
-
const { table, where, aggregateFn, aggregateField, joins, groupBy, having } = descriptor;
|
|
475
|
-
const fn = aggregateFn.toUpperCase();
|
|
476
|
-
const joinStr = this._buildJoins(joins, table);
|
|
477
|
-
const values = [];
|
|
478
|
-
let paramIdx = 1;
|
|
479
|
-
|
|
480
|
-
let sql = `SELECT ${fn}("${aggregateField}") as result FROM "${table}"${joinStr}`;
|
|
481
|
-
|
|
482
|
-
if (where && where.length)
|
|
483
|
-
{
|
|
484
|
-
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
485
|
-
sql += clause;
|
|
486
|
-
values.push(...wv);
|
|
487
|
-
paramIdx = nextIdx;
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
sql += this._buildGroupBy(groupBy);
|
|
491
|
-
|
|
492
|
-
if (having && having.length)
|
|
493
|
-
{
|
|
494
|
-
const { clause: hClause } = this._buildHavingPg(having, values, paramIdx);
|
|
495
|
-
sql += hClause;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
const { rows } = await this._pool.query(sql, values);
|
|
499
|
-
return rows[0] ? rows[0].result : null;
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
/**
|
|
503
|
-
* Get the query execution plan (EXPLAIN).
|
|
504
|
-
* @param {object} descriptor - Query descriptor.
|
|
505
|
-
* @param {object} [options] - Configuration options.
|
|
506
|
-
* @param {boolean} [options.analyze] - Include ANALYZE.
|
|
507
|
-
* @param {boolean} [options.buffers] - Include BUFFERS.
|
|
508
|
-
* @param {string} [options.format] - Output format (TEXT, JSON, XML, YAML).
|
|
509
|
-
* @returns {Promise<Array>} Array of execution plan rows.
|
|
510
|
-
*/
|
|
511
|
-
async explain(descriptor, options = {})
|
|
512
|
-
{
|
|
513
|
-
const { table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
|
|
514
|
-
|
|
515
|
-
const selectFields = fields && fields.length ? fields.map(f => `"${f}"`).join(', ') : '*';
|
|
516
|
-
const distinctStr = distinct ? 'DISTINCT ' : '';
|
|
517
|
-
const joinStr = this._buildJoins(joins, table);
|
|
518
|
-
let sql = `SELECT ${distinctStr}${selectFields} FROM "${table}"${joinStr}`;
|
|
519
|
-
const values = [];
|
|
520
|
-
let paramIdx = 1;
|
|
521
|
-
|
|
522
|
-
if (where && where.length)
|
|
523
|
-
{
|
|
524
|
-
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
525
|
-
sql += clause;
|
|
526
|
-
values.push(...wv);
|
|
527
|
-
paramIdx = nextIdx;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
sql += this._buildGroupBy(groupBy);
|
|
531
|
-
|
|
532
|
-
if (having && having.length)
|
|
533
|
-
{
|
|
534
|
-
const { clause: hClause, nextIdx: hIdx } = this._buildHavingPg(having, values, paramIdx);
|
|
535
|
-
sql += hClause;
|
|
536
|
-
paramIdx = hIdx;
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
if (orderBy && orderBy.length)
|
|
540
|
-
sql += ' ORDER BY ' + orderBy.map(o => `"${o.field}" ${o.dir}`).join(', ');
|
|
541
|
-
if (limit !== null && limit !== undefined)
|
|
542
|
-
{
|
|
543
|
-
sql += ` LIMIT $${paramIdx++}`;
|
|
544
|
-
values.push(limit);
|
|
545
|
-
}
|
|
546
|
-
if (offset !== null && offset !== undefined)
|
|
547
|
-
{
|
|
548
|
-
sql += ` OFFSET $${paramIdx++}`;
|
|
549
|
-
values.push(offset);
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
const parts = ['EXPLAIN'];
|
|
553
|
-
if (options.analyze) parts.push('ANALYZE');
|
|
554
|
-
if (options.buffers) parts.push('BUFFERS');
|
|
555
|
-
if (options.format)
|
|
556
|
-
{
|
|
557
|
-
const fmt = String(options.format).toUpperCase();
|
|
558
|
-
const allowed = ['TEXT', 'JSON', 'XML', 'YAML'];
|
|
559
|
-
if (allowed.includes(fmt)) parts.push(`FORMAT ${fmt}`);
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
const { rows } = await this._pool.query(`${parts.join(' ')} ${sql}`, values);
|
|
563
|
-
return rows;
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
/**
|
|
567
|
-
* Get prepared statement cache statistics.
|
|
568
|
-
* @returns {{ size: number, maxSize: number, hits: number, misses: number, hitRate: number }}
|
|
569
|
-
*/
|
|
570
|
-
stmtCacheStats()
|
|
571
|
-
{
|
|
572
|
-
const total = this._stmtCacheHits + this._stmtCacheMisses;
|
|
573
|
-
return {
|
|
574
|
-
size: this._stmtCache.size,
|
|
575
|
-
maxSize: this._stmtCacheMax,
|
|
576
|
-
hits: this._stmtCacheHits,
|
|
577
|
-
misses: this._stmtCacheMisses,
|
|
578
|
-
hitRate: total > 0 ? this._stmtCacheHits / total : 0,
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
/**
|
|
583
|
-
* Pre-warm the connection pool by creating idle connections.
|
|
584
|
-
* @param {number} [count=5] - Number of connections to warm up.
|
|
585
|
-
* @returns {Promise<number>} Number of connections successfully warmed.
|
|
586
|
-
*/
|
|
587
|
-
async warmup(count)
|
|
588
|
-
{
|
|
589
|
-
const n = Math.min(Math.max(1, Math.floor(Number(count) || 5)), this._pool.options.max || 10);
|
|
590
|
-
const clients = [];
|
|
591
|
-
for (let i = 0; i < n; i++)
|
|
592
|
-
{
|
|
593
|
-
try
|
|
594
|
-
{
|
|
595
|
-
const client = await this._pool.connect();
|
|
596
|
-
clients.push(client);
|
|
597
|
-
}
|
|
598
|
-
catch (e) { break; }
|
|
599
|
-
}
|
|
600
|
-
for (const client of clients) client.release();
|
|
601
|
-
return clients.length;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
/**
|
|
605
|
-
* Close the database connection.
|
|
606
|
-
* @returns {Promise<void>}
|
|
607
|
-
*/
|
|
608
|
-
async close() { await this._pool.end(); }
|
|
609
|
-
/** @override */
|
|
610
|
-
async raw(sql, ...params) { const { rows } = await this._pool.query(sql, params); return rows; }
|
|
611
|
-
|
|
612
|
-
/** @override */
|
|
613
|
-
async transaction(fn)
|
|
614
|
-
{
|
|
615
|
-
const client = await this._pool.connect();
|
|
616
|
-
try
|
|
617
|
-
{
|
|
618
|
-
await client.query('BEGIN');
|
|
619
|
-
const result = await fn(client);
|
|
620
|
-
await client.query('COMMIT');
|
|
621
|
-
return result;
|
|
622
|
-
}
|
|
623
|
-
catch (e) { await client.query('ROLLBACK'); throw e; }
|
|
624
|
-
finally { client.release(); }
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// -- PostgreSQL Utilities ----------------------------
|
|
628
|
-
|
|
629
|
-
/**
|
|
630
|
-
* List all user-created tables in the current schema.
|
|
631
|
-
* @param {string} [schema='public'] - Schema name.
|
|
632
|
-
* @returns {Promise<string[]>} Array of table names.
|
|
633
|
-
*/
|
|
634
|
-
async tables(schema = 'public')
|
|
635
|
-
{
|
|
636
|
-
const { rows } = await this._pool.query(
|
|
637
|
-
`SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = $1 ORDER BY tablename`,
|
|
638
|
-
[schema]
|
|
639
|
-
);
|
|
640
|
-
return rows.map(r => r.tablename);
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
/**
|
|
644
|
-
* Get column information for a table.
|
|
645
|
-
* @param {string} table - Table name.
|
|
646
|
-
* @param {string} [schema='public'] - Schema definition.
|
|
647
|
-
* @returns {Promise<Array<{ column_name: string, data_type: string, is_nullable: string, column_default: string }>>}
|
|
648
|
-
*/
|
|
649
|
-
async columns(table, schema = 'public')
|
|
650
|
-
{
|
|
651
|
-
const { rows } = await this._pool.query(
|
|
652
|
-
`SELECT column_name, data_type, is_nullable, column_default
|
|
653
|
-
FROM information_schema.columns
|
|
654
|
-
WHERE table_schema = $1 AND table_name = $2
|
|
655
|
-
ORDER BY ordinal_position`,
|
|
656
|
-
[schema, table]
|
|
657
|
-
);
|
|
658
|
-
return rows;
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
/**
|
|
662
|
-
* Get the current database size in bytes.
|
|
663
|
-
* @returns {Promise<number>} Database size in bytes.
|
|
664
|
-
*/
|
|
665
|
-
async databaseSize()
|
|
666
|
-
{
|
|
667
|
-
const { rows } = await this._pool.query('SELECT pg_database_size(current_database()) AS size');
|
|
668
|
-
return Number(rows[0].size) || 0;
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
/**
|
|
672
|
-
* Get the row count for a table (estimated for large tables, exact for small ones).
|
|
673
|
-
* @param {string} table - Table name.
|
|
674
|
-
* @returns {Promise<number>} Total relation size in bytes.
|
|
675
|
-
*/
|
|
676
|
-
async tableSize(table)
|
|
677
|
-
{
|
|
678
|
-
const { rows } = await this._pool.query(
|
|
679
|
-
`SELECT pg_total_relation_size($1) AS size`, [table]
|
|
680
|
-
);
|
|
681
|
-
return Number(rows[0].size) || 0;
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
/**
|
|
685
|
-
* Get connection pool status.
|
|
686
|
-
* @returns {{ total: number, idle: number, waiting: number }}
|
|
687
|
-
*/
|
|
688
|
-
poolStatus()
|
|
689
|
-
{
|
|
690
|
-
return {
|
|
691
|
-
total: this._pool.totalCount,
|
|
692
|
-
idle: this._pool.idleCount,
|
|
693
|
-
waiting: this._pool.waitingCount,
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
/**
|
|
698
|
-
* Get the PostgreSQL server version string.
|
|
699
|
-
* @returns {Promise<string>} Full server version string.
|
|
700
|
-
*/
|
|
701
|
-
async version()
|
|
702
|
-
{
|
|
703
|
-
const { rows } = await this._pool.query('SELECT version() AS ver');
|
|
704
|
-
return rows[0].ver;
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
/**
|
|
708
|
-
* Ping the database to check connectivity.
|
|
709
|
-
* @returns {Promise<boolean>} `true` if the server is reachable.
|
|
710
|
-
*/
|
|
711
|
-
async ping()
|
|
712
|
-
{
|
|
713
|
-
try
|
|
714
|
-
{
|
|
715
|
-
await this._pool.query('SELECT 1');
|
|
716
|
-
return true;
|
|
717
|
-
}
|
|
718
|
-
catch { return false; }
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
/**
|
|
722
|
-
* Execute a raw statement that doesn't return rows (INSERT, UPDATE, DDL).
|
|
723
|
-
* @param {string} sql - SQL query string.
|
|
724
|
-
* @param {...*} params - Bound parameter values.
|
|
725
|
-
* @returns {Promise<{ rowCount: number }>}
|
|
726
|
-
*/
|
|
727
|
-
async exec(sql, ...params)
|
|
728
|
-
{
|
|
729
|
-
const { rowCount } = await this._pool.query(sql, params);
|
|
730
|
-
return { rowCount: rowCount || 0 };
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
// -- Table Info & Debug (Schema Introspection) -----------
|
|
734
|
-
|
|
735
|
-
/**
|
|
736
|
-
* Get detailed table status (rows, sizes, etc.) from pg_stat_user_tables.
|
|
737
|
-
* @param {string} [table] - Table name. If omitted, returns all tables.
|
|
738
|
-
* @returns {Promise<Array<{ name: string, rows: number, totalSize: number, dataSize: number, indexSize: number, sequentialScans: number, indexScans: number, liveTuples: number, deadTuples: number, lastVacuum: string, lastAutoVacuum: string, lastAnalyze: string }>>}
|
|
739
|
-
*/
|
|
740
|
-
async tableStatus(table)
|
|
741
|
-
{
|
|
742
|
-
let sql = `SELECT
|
|
743
|
-
s.relname AS name,
|
|
744
|
-
pg_total_relation_size(s.relid) AS total_size,
|
|
745
|
-
pg_relation_size(s.relid) AS data_size,
|
|
746
|
-
pg_indexes_size(s.relid) AS index_size,
|
|
747
|
-
s.n_live_tup AS live_tuples,
|
|
748
|
-
s.n_dead_tup AS dead_tuples,
|
|
749
|
-
s.seq_scan AS seq_scans,
|
|
750
|
-
s.idx_scan AS idx_scans,
|
|
751
|
-
s.last_vacuum, s.last_autovacuum,
|
|
752
|
-
s.last_analyze, s.last_autoanalyze
|
|
753
|
-
FROM pg_stat_user_tables s`;
|
|
754
|
-
const params = [];
|
|
755
|
-
if (table)
|
|
756
|
-
{
|
|
757
|
-
sql += ` WHERE s.relname = $1`;
|
|
758
|
-
params.push(table);
|
|
759
|
-
}
|
|
760
|
-
sql += ' ORDER BY s.relname';
|
|
761
|
-
const { rows } = await this._pool.query(sql, params);
|
|
762
|
-
return rows.map(r => ({
|
|
763
|
-
name: r.name,
|
|
764
|
-
rows: Number(r.live_tuples) || 0,
|
|
765
|
-
totalSize: Number(r.total_size) || 0,
|
|
766
|
-
dataSize: Number(r.data_size) || 0,
|
|
767
|
-
indexSize: Number(r.index_size) || 0,
|
|
768
|
-
sequentialScans: Number(r.seq_scans) || 0,
|
|
769
|
-
indexScans: Number(r.idx_scans) || 0,
|
|
770
|
-
liveTuples: Number(r.live_tuples) || 0,
|
|
771
|
-
deadTuples: Number(r.dead_tuples) || 0,
|
|
772
|
-
lastVacuum: r.last_vacuum, lastAutoVacuum: r.last_autovacuum,
|
|
773
|
-
lastAnalyze: r.last_analyze,
|
|
774
|
-
}));
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
/**
|
|
778
|
-
* Get table size in human-readable format.
|
|
779
|
-
* @param {string} table - Table name.
|
|
780
|
-
* @returns {Promise<{ rows: number, dataSize: string, indexSize: string, totalSize: string }>}
|
|
781
|
-
*/
|
|
782
|
-
async tableSizeFormatted(table)
|
|
783
|
-
{
|
|
784
|
-
const status = await this.tableStatus(table);
|
|
785
|
-
if (!status.length) return { rows: 0, dataSize: '0 B', indexSize: '0 B', totalSize: '0 B' };
|
|
786
|
-
const s = status[0];
|
|
787
|
-
const fmt = (b) => {
|
|
788
|
-
if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
|
|
789
|
-
if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
|
|
790
|
-
if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
|
|
791
|
-
return b + ' B';
|
|
792
|
-
};
|
|
793
|
-
return { rows: s.rows, dataSize: fmt(s.dataSize), indexSize: fmt(s.indexSize), totalSize: fmt(s.totalSize) };
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
/**
|
|
797
|
-
* Get indexes for a table.
|
|
798
|
-
* @param {string} table - Table name.
|
|
799
|
-
* @returns {Promise<Array<{ name: string, columns: string, unique: boolean, type: string, size: number }>>}
|
|
800
|
-
*/
|
|
801
|
-
async indexes(table)
|
|
802
|
-
{
|
|
803
|
-
const { rows } = await this._pool.query(
|
|
804
|
-
`SELECT i.relname AS name, ix.indisunique AS unique, am.amname AS type,
|
|
805
|
-
pg_relation_size(i.oid) AS size,
|
|
806
|
-
array_to_string(array_agg(a.attname ORDER BY k.n), ', ') AS columns
|
|
807
|
-
FROM pg_index ix
|
|
808
|
-
JOIN pg_class t ON t.oid = ix.indrelid
|
|
809
|
-
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
810
|
-
JOIN pg_am am ON am.oid = i.relam
|
|
811
|
-
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n)
|
|
812
|
-
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
813
|
-
WHERE t.relname = $1
|
|
814
|
-
GROUP BY i.relname, ix.indisunique, am.amname, i.oid`,
|
|
815
|
-
[table]
|
|
816
|
-
);
|
|
817
|
-
return rows.map(r => ({
|
|
818
|
-
name: r.name, columns: r.columns, unique: r.unique,
|
|
819
|
-
type: r.type, size: Number(r.size) || 0,
|
|
820
|
-
}));
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
/**
|
|
824
|
-
* Get foreign keys for a table.
|
|
825
|
-
* @param {string} table - Table name.
|
|
826
|
-
* @returns {Promise<Array<{ constraintName: string, column: string, referencedTable: string, referencedColumn: string, onDelete: string, onUpdate: string }>>}
|
|
827
|
-
*/
|
|
828
|
-
async foreignKeys(table)
|
|
829
|
-
{
|
|
830
|
-
const { rows } = await this._pool.query(
|
|
831
|
-
`SELECT tc.constraint_name, kcu.column_name,
|
|
832
|
-
ccu.table_name AS referenced_table,
|
|
833
|
-
ccu.column_name AS referenced_column,
|
|
834
|
-
rc.delete_rule, rc.update_rule
|
|
835
|
-
FROM information_schema.table_constraints tc
|
|
836
|
-
JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name
|
|
837
|
-
JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
|
|
838
|
-
JOIN information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name
|
|
839
|
-
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1`,
|
|
840
|
-
[table]
|
|
841
|
-
);
|
|
842
|
-
return rows.map(r => ({
|
|
843
|
-
constraintName: r.constraint_name, column: r.column_name,
|
|
844
|
-
referencedTable: r.referenced_table, referencedColumn: r.referenced_column,
|
|
845
|
-
onDelete: r.delete_rule, onUpdate: r.update_rule,
|
|
846
|
-
}));
|
|
847
|
-
}
|
|
848
|
-
|
|
849
|
-
/**
|
|
850
|
-
* Get full database overview — all tables with size and row counts.
|
|
851
|
-
* @returns {Promise<{ tables: Array, totalSize: string, totalRows: number }>}
|
|
852
|
-
*/
|
|
853
|
-
async overview()
|
|
854
|
-
{
|
|
855
|
-
const status = await this.tableStatus();
|
|
856
|
-
let totalBytes = 0;
|
|
857
|
-
let totalRows = 0;
|
|
858
|
-
const fmt = (b) => {
|
|
859
|
-
if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
|
|
860
|
-
if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
|
|
861
|
-
if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
|
|
862
|
-
return b + ' B';
|
|
863
|
-
};
|
|
864
|
-
const tables = status.map(s => {
|
|
865
|
-
totalBytes += s.totalSize;
|
|
866
|
-
totalRows += s.rows;
|
|
867
|
-
return { ...s, formattedSize: fmt(s.totalSize) };
|
|
868
|
-
});
|
|
869
|
-
return { tables, totalSize: fmt(totalBytes), totalRows };
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
/**
|
|
873
|
-
* Get server settings/variables.
|
|
874
|
-
* @param {string} [filter] - LIKE pattern to filter settings.
|
|
875
|
-
* @returns {Promise<Object<string, string>>} Key-value map of server settings.
|
|
876
|
-
*/
|
|
877
|
-
async variables(filter)
|
|
878
|
-
{
|
|
879
|
-
const sql = filter
|
|
880
|
-
? `SELECT name, setting FROM pg_settings WHERE name LIKE $1`
|
|
881
|
-
: 'SELECT name, setting FROM pg_settings';
|
|
882
|
-
const params = filter ? [filter] : [];
|
|
883
|
-
const { rows } = await this._pool.query(sql, params);
|
|
884
|
-
const out = {};
|
|
885
|
-
for (const r of rows) out[r.name] = r.setting;
|
|
886
|
-
return out;
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
/**
|
|
890
|
-
* Get active backends (like MySQL SHOW PROCESSLIST).
|
|
891
|
-
* @returns {Promise<Array<{ pid: number, user: string, database: string, state: string, query: string, duration: string }>>}
|
|
892
|
-
*/
|
|
893
|
-
async processlist()
|
|
894
|
-
{
|
|
895
|
-
const { rows } = await this._pool.query(
|
|
896
|
-
`SELECT pid, usename AS user, datname AS database, state, query,
|
|
897
|
-
now() - query_start AS duration
|
|
898
|
-
FROM pg_stat_activity WHERE datname = current_database()`
|
|
899
|
-
);
|
|
900
|
-
return rows.map(r => ({
|
|
901
|
-
pid: r.pid, user: r.user, database: r.database,
|
|
902
|
-
state: r.state, query: r.query, duration: String(r.duration || ''),
|
|
903
|
-
}));
|
|
904
|
-
}
|
|
905
|
-
|
|
906
|
-
/**
|
|
907
|
-
* Get table constraints (PRIMARY KEY, UNIQUE, CHECK, FK).
|
|
908
|
-
* @param {string} table - Table name.
|
|
909
|
-
* @returns {Promise<Array<{ name: string, type: string, definition: string }>>}
|
|
910
|
-
*/
|
|
911
|
-
async constraints(table)
|
|
912
|
-
{
|
|
913
|
-
const { rows } = await this._pool.query(
|
|
914
|
-
`SELECT conname AS name, contype AS type,
|
|
915
|
-
pg_get_constraintdef(c.oid) AS definition
|
|
916
|
-
FROM pg_constraint c
|
|
917
|
-
JOIN pg_class t ON t.oid = c.conrelid
|
|
918
|
-
WHERE t.relname = $1`,
|
|
919
|
-
[table]
|
|
920
|
-
);
|
|
921
|
-
const typeMap = { p: 'PRIMARY KEY', u: 'UNIQUE', c: 'CHECK', f: 'FOREIGN KEY', x: 'EXCLUSION' };
|
|
922
|
-
return rows.map(r => ({
|
|
923
|
-
name: r.name, type: typeMap[r.type] || r.type, definition: r.definition,
|
|
924
|
-
}));
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
/**
|
|
928
|
-
* Get table and column comments for schema documentation.
|
|
929
|
-
* @param {string} table - Table name.
|
|
930
|
-
* @returns {Promise<{ tableComment: string, columns: Array<{ name: string, comment: string }> }>}
|
|
931
|
-
*/
|
|
932
|
-
async comments(table)
|
|
933
|
-
{
|
|
934
|
-
const { rows: tcRows } = await this._pool.query(
|
|
935
|
-
`SELECT obj_description(c.oid) AS comment FROM pg_class c WHERE c.relname = $1`, [table]
|
|
936
|
-
);
|
|
937
|
-
const { rows: colRows } = await this._pool.query(
|
|
938
|
-
`SELECT a.attname AS name, col_description(c.oid, a.attnum) AS comment
|
|
939
|
-
FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid
|
|
940
|
-
WHERE c.relname = $1 AND a.attnum > 0 AND NOT a.attisdropped
|
|
941
|
-
ORDER BY a.attnum`, [table]
|
|
942
|
-
);
|
|
943
|
-
return {
|
|
944
|
-
tableComment: (tcRows[0] && tcRows[0].comment) || '',
|
|
945
|
-
columns: colRows.map(r => ({ name: r.name, comment: r.comment || '' })),
|
|
946
|
-
};
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
/**
|
|
950
|
-
* Run a LISTEN/NOTIFY style query. Useful for subscribing to PG notifications.
|
|
951
|
-
* @param {string} channel - Channel name.
|
|
952
|
-
* @param {Function} callback - Receives { channel, payload }.
|
|
953
|
-
* @returns {Promise<Function>} Unlisten function.
|
|
954
|
-
*/
|
|
955
|
-
async listen(channel, callback)
|
|
956
|
-
{
|
|
957
|
-
const ch = String(channel);
|
|
958
|
-
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(ch)) throw new Error(`Invalid channel name: ${ch}`);
|
|
959
|
-
const client = await this._pool.connect();
|
|
960
|
-
await client.query(`LISTEN ${ch}`);
|
|
961
|
-
client.on('notification', callback);
|
|
962
|
-
return async () =>
|
|
963
|
-
{
|
|
964
|
-
await client.query(`UNLISTEN ${ch}`);
|
|
965
|
-
client.removeListener('notification', callback);
|
|
966
|
-
client.release();
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
// -- Migration / DDL Methods ----------------------------
|
|
971
|
-
|
|
972
|
-
/**
|
|
973
|
-
* Add a column to an existing table.
|
|
974
|
-
* @param {string} table - Table name.
|
|
975
|
-
* @param {string} column - Column name.
|
|
976
|
-
* @param {object} def - Column definition (type, required, default, etc.)
|
|
977
|
-
* @returns {Promise<void>}
|
|
978
|
-
*/
|
|
979
|
-
async addColumn(table, column, def)
|
|
980
|
-
{
|
|
981
|
-
const defWithName = { ...def, _name: column };
|
|
982
|
-
let colDef = this._typeMap(defWithName);
|
|
983
|
-
if (def.required) colDef += ' NOT NULL';
|
|
984
|
-
if (def.unique) colDef += ' UNIQUE';
|
|
985
|
-
if (def.default !== undefined && typeof def.default !== 'function')
|
|
986
|
-
colDef += ` DEFAULT ${this._sqlDefault(def.default)}`;
|
|
987
|
-
if (def.check) colDef += ` CHECK(${validateCheck(def.check)})`;
|
|
988
|
-
if (def.references)
|
|
989
|
-
{
|
|
990
|
-
colDef += ` REFERENCES "${def.references.table}"("${def.references.column || 'id'}")`;
|
|
991
|
-
if (def.references.onDelete) colDef += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
|
|
992
|
-
if (def.references.onUpdate) colDef += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
|
|
993
|
-
}
|
|
994
|
-
await this._pool.query(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${colDef}`);
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
/**
|
|
998
|
-
* Drop a column from a table.
|
|
999
|
-
* @param {string} table - Table name.
|
|
1000
|
-
* @param {string} column - Column name.
|
|
1001
|
-
* @returns {Promise<void>}
|
|
1002
|
-
*/
|
|
1003
|
-
async dropColumn(table, column)
|
|
1004
|
-
{
|
|
1005
|
-
await this._pool.query(`ALTER TABLE "${table}" DROP COLUMN "${column}"`);
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
/**
|
|
1009
|
-
* Rename a column.
|
|
1010
|
-
* @param {string} table - Table name.
|
|
1011
|
-
* @param {string} oldName - Current name.
|
|
1012
|
-
* @param {string} newName - New name.
|
|
1013
|
-
* @returns {Promise<void>}
|
|
1014
|
-
*/
|
|
1015
|
-
async renameColumn(table, oldName, newName)
|
|
1016
|
-
{
|
|
1017
|
-
await this._pool.query(`ALTER TABLE "${table}" RENAME COLUMN "${oldName}" TO "${newName}"`);
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
/**
|
|
1021
|
-
* Rename a table.
|
|
1022
|
-
* @param {string} oldName - Current name.
|
|
1023
|
-
* @param {string} newName - New name.
|
|
1024
|
-
* @returns {Promise<void>}
|
|
1025
|
-
*/
|
|
1026
|
-
async renameTable(oldName, newName)
|
|
1027
|
-
{
|
|
1028
|
-
await this._pool.query(`ALTER TABLE "${oldName}" RENAME TO "${newName}"`);
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
/**
|
|
1032
|
-
* Create an index on a table.
|
|
1033
|
-
* @param {string} table - Table name.
|
|
1034
|
-
* @param {string|string[]} columns - Column name(s).
|
|
1035
|
-
* @param {{ name?: string, unique?: boolean }} [options={}]
|
|
1036
|
-
* @returns {Promise<void>}
|
|
1037
|
-
*/
|
|
1038
|
-
async createIndex(table, columns, options = {})
|
|
1039
|
-
{
|
|
1040
|
-
const cols = Array.isArray(columns) ? columns : [columns];
|
|
1041
|
-
const name = options.name || `idx_${table}_${cols.join('_')}`;
|
|
1042
|
-
const unique = options.unique ? 'UNIQUE ' : '';
|
|
1043
|
-
await this._pool.query(`CREATE ${unique}INDEX IF NOT EXISTS "${name}" ON "${table}" (${cols.map(c => `"${c}"`).join(', ')})`);
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
/**
|
|
1047
|
-
* Drop an index.
|
|
1048
|
-
* @param {string} name - Index name.
|
|
1049
|
-
* @returns {Promise<void>}
|
|
1050
|
-
*/
|
|
1051
|
-
async dropIndex(_table, name)
|
|
1052
|
-
{
|
|
1053
|
-
await this._pool.query(`DROP INDEX IF EXISTS "${name}"`);
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
/**
|
|
1057
|
-
* Add a foreign key constraint.
|
|
1058
|
-
* @param {string} table - Table name.
|
|
1059
|
-
* @param {string} column - Column name.
|
|
1060
|
-
* @param {string} refTable - Referenced table name.
|
|
1061
|
-
* @param {string} refColumn - Referenced column name.
|
|
1062
|
-
* @param {{ onDelete?: string, onUpdate?: string, name?: string }} [options={}]
|
|
1063
|
-
* @returns {Promise<void>}
|
|
1064
|
-
*/
|
|
1065
|
-
async addForeignKey(table, column, refTable, refColumn, options = {})
|
|
1066
|
-
{
|
|
1067
|
-
const name = options.name || `fk_${table}_${column}`;
|
|
1068
|
-
let sql = `ALTER TABLE "${table}" ADD CONSTRAINT "${name}" FOREIGN KEY ("${column}") REFERENCES "${refTable}"("${refColumn}")`;
|
|
1069
|
-
if (options.onDelete) sql += ` ON DELETE ${validateFKAction(options.onDelete)}`;
|
|
1070
|
-
if (options.onUpdate) sql += ` ON UPDATE ${validateFKAction(options.onUpdate)}`;
|
|
1071
|
-
await this._pool.query(sql);
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
/**
|
|
1075
|
-
* Drop a foreign key constraint.
|
|
1076
|
-
* @param {string} table - Table name.
|
|
1077
|
-
* @param {string} constraintName - Constraint name.
|
|
1078
|
-
* @returns {Promise<void>}
|
|
1079
|
-
*/
|
|
1080
|
-
async dropForeignKey(table, constraintName)
|
|
1081
|
-
{
|
|
1082
|
-
await this._pool.query(`ALTER TABLE "${table}" DROP CONSTRAINT "${constraintName}"`);
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
/**
|
|
1086
|
-
* Check if a table exists.
|
|
1087
|
-
* @param {string} table - Table name.
|
|
1088
|
-
* @returns {Promise<boolean>} `true` if the table exists.
|
|
1089
|
-
*/
|
|
1090
|
-
async hasTable(table)
|
|
1091
|
-
{
|
|
1092
|
-
const { rows } = await this._pool.query(
|
|
1093
|
-
`SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1`,
|
|
1094
|
-
[table]
|
|
1095
|
-
);
|
|
1096
|
-
return rows.length > 0;
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
/**
|
|
1100
|
-
* Check if a column exists on a table.
|
|
1101
|
-
* @param {string} table - Table name.
|
|
1102
|
-
* @param {string} column - Column name.
|
|
1103
|
-
* @returns {Promise<boolean>} `true` if the column exists.
|
|
1104
|
-
*/
|
|
1105
|
-
async hasColumn(table, column)
|
|
1106
|
-
{
|
|
1107
|
-
const { rows } = await this._pool.query(
|
|
1108
|
-
`SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
|
|
1109
|
-
[table, column]
|
|
1110
|
-
);
|
|
1111
|
-
return rows.length > 0;
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
/**
|
|
1115
|
-
* Get detailed column info for a table (migration-friendly format).
|
|
1116
|
-
* @param {string} table - Table name.
|
|
1117
|
-
* @returns {Promise<Array<{ name: string, type: string, nullable: boolean, defaultValue: string|null, primaryKey: boolean }>>}
|
|
1118
|
-
*/
|
|
1119
|
-
async describeTable(table)
|
|
1120
|
-
{
|
|
1121
|
-
const { rows } = await this._pool.query(
|
|
1122
|
-
`SELECT c.column_name AS name, c.data_type AS type,
|
|
1123
|
-
c.is_nullable = 'YES' AS nullable, c.column_default AS default_value,
|
|
1124
|
-
COALESCE(tc.constraint_type = 'PRIMARY KEY', false) AS pk
|
|
1125
|
-
FROM information_schema.columns c
|
|
1126
|
-
LEFT JOIN information_schema.key_column_usage kcu
|
|
1127
|
-
ON c.column_name = kcu.column_name AND c.table_name = kcu.table_name AND c.table_schema = kcu.table_schema
|
|
1128
|
-
LEFT JOIN information_schema.table_constraints tc
|
|
1129
|
-
ON kcu.constraint_name = tc.constraint_name AND tc.constraint_type = 'PRIMARY KEY'
|
|
1130
|
-
WHERE c.table_schema = 'public' AND c.table_name = $1
|
|
1131
|
-
ORDER BY c.ordinal_position`,
|
|
1132
|
-
[table]
|
|
1133
|
-
);
|
|
1134
|
-
return rows.map(r => ({
|
|
1135
|
-
name: r.name,
|
|
1136
|
-
type: r.type,
|
|
1137
|
-
nullable: r.nullable,
|
|
1138
|
-
defaultValue: r.default_value,
|
|
1139
|
-
primaryKey: r.pk,
|
|
1140
|
-
}));
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
module.exports = PostgresAdapter;
|
|
1
|
+
/**
|
|
2
|
+
* @module orm/adapters/postgres
|
|
3
|
+
* @description PostgreSQL adapter using the optional `pg` driver.
|
|
4
|
+
* Requires: `npm install pg`
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const { Database, Model, TYPES } = require('@zero-server/sdk');
|
|
8
|
+
*
|
|
9
|
+
* const db = Database.connect('postgres', {
|
|
10
|
+
* host: '127.0.0.1',
|
|
11
|
+
* user: 'postgres',
|
|
12
|
+
* password: '',
|
|
13
|
+
* database: 'myapp',
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* class Article extends Model {
|
|
17
|
+
* static table = 'articles';
|
|
18
|
+
* static schema = {
|
|
19
|
+
* id: { type: TYPES.SERIAL, primaryKey: true },
|
|
20
|
+
* title: { type: TYPES.STRING, required: true },
|
|
21
|
+
* content: { type: TYPES.TEXT },
|
|
22
|
+
* tags: { type: TYPES.JSONB, default: [] },
|
|
23
|
+
* };
|
|
24
|
+
* static timestamps = true;
|
|
25
|
+
* }
|
|
26
|
+
*
|
|
27
|
+
* db.register(Article);
|
|
28
|
+
* await db.sync();
|
|
29
|
+
*
|
|
30
|
+
* await Article.create({ title: 'Hello', content: 'World', tags: ['intro'] });
|
|
31
|
+
* const recent = await Article.query().orderBy('createdAt', 'desc').limit(10).exec();
|
|
32
|
+
*/
|
|
33
|
+
const BaseSqlAdapter = require('./sql-base');
|
|
34
|
+
const { validateFKAction, validateCheck } = require('../schema');
|
|
35
|
+
|
|
36
|
+
class PostgresAdapter extends BaseSqlAdapter
|
|
37
|
+
{
|
|
38
|
+
/**
|
|
39
|
+
* @constructor
|
|
40
|
+
* @param {object} options - Configuration options.
|
|
41
|
+
* @param {string} [options.user] - Database user.
|
|
42
|
+
* @param {string} [options.password] - Database password.
|
|
43
|
+
* @param {string} options.database - Database name.
|
|
44
|
+
* @param {number} [options.max=10] - Max pool size.
|
|
45
|
+
* @param {number} [options.idleTimeoutMillis=10000] - Idle client timeout.
|
|
46
|
+
* @param {number} [options.connectionTimeoutMillis=0] - Connection timeout (0 = no limit).
|
|
47
|
+
* @param {boolean|object} [options.ssl] - SSL mode or TLS options.
|
|
48
|
+
* @param {string} [options.connectionString] - Full connection URI (overrides individual settings).
|
|
49
|
+
* @param {string} [options.application_name] - Identify the app in pg_stat_activity.
|
|
50
|
+
* @param {number} [options.statement_timeout] - Statement timeout in ms.
|
|
51
|
+
*/
|
|
52
|
+
constructor(options = {})
|
|
53
|
+
{
|
|
54
|
+
super();
|
|
55
|
+
let pg;
|
|
56
|
+
try { pg = require('pg'); }
|
|
57
|
+
catch (e)
|
|
58
|
+
{
|
|
59
|
+
throw new Error(
|
|
60
|
+
'PostgreSQL adapter requires "pg" package.\n' +
|
|
61
|
+
'Install it with: npm install pg'
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
this._pool = new pg.Pool({ max: 10, ...options });
|
|
65
|
+
this._options = options;
|
|
66
|
+
|
|
67
|
+
/** @private Prepared statement name cache for pg named queries */
|
|
68
|
+
this._stmtCache = new Map();
|
|
69
|
+
this._stmtCacheHits = 0;
|
|
70
|
+
this._stmtCacheMisses = 0;
|
|
71
|
+
this._stmtCacheMax = options.stmtCacheSize || 256;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @private */
|
|
75
|
+
_typeMap(colDef)
|
|
76
|
+
{
|
|
77
|
+
const map = {
|
|
78
|
+
string: `VARCHAR(${colDef.maxLength || 255})`, text: 'TEXT',
|
|
79
|
+
integer: 'INTEGER', float: 'DOUBLE PRECISION', boolean: 'BOOLEAN',
|
|
80
|
+
date: 'DATE', datetime: 'TIMESTAMPTZ', json: 'JSONB', blob: 'BYTEA',
|
|
81
|
+
uuid: 'UUID',
|
|
82
|
+
bigint: 'BIGINT', smallint: 'SMALLINT', tinyint: 'SMALLINT',
|
|
83
|
+
decimal: `NUMERIC(${colDef.precision || 10},${colDef.scale || 2})`,
|
|
84
|
+
serial: 'SERIAL', bigserial: 'BIGSERIAL',
|
|
85
|
+
timestamp: 'TIMESTAMP', time: 'TIME', interval: 'INTERVAL',
|
|
86
|
+
inet: 'INET', cidr: 'CIDR', macaddr: 'MACADDR',
|
|
87
|
+
money: 'MONEY', real: 'REAL', double: 'DOUBLE PRECISION',
|
|
88
|
+
jsonb: 'JSONB', xml: 'XML', citext: 'CITEXT',
|
|
89
|
+
array: colDef.arrayOf ? `${colDef.arrayOf}[]` : 'TEXT[]',
|
|
90
|
+
binary: 'BYTEA', varbinary: 'BYTEA',
|
|
91
|
+
char: `CHAR(${colDef.length || 1})`,
|
|
92
|
+
enum: colDef.enum
|
|
93
|
+
? `VARCHAR(255) CHECK ("${(colDef._name || 'col').replace(/"/g, '""')}" IN (${colDef.enum.map(v => `'${String(v).replace(/'/g, "''")}'`).join(',')}))`
|
|
94
|
+
: 'VARCHAR(255)',
|
|
95
|
+
};
|
|
96
|
+
return map[colDef.type] || 'TEXT';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @private
|
|
101
|
+
* PostgreSQL uses $1, $2, ... style parameters.
|
|
102
|
+
* Override the base class WHERE builders.
|
|
103
|
+
*/
|
|
104
|
+
|
|
105
|
+
_buildWherePg(conditions, startIdx = 1)
|
|
106
|
+
{
|
|
107
|
+
if (!conditions || Object.keys(conditions).length === 0)
|
|
108
|
+
return { clause: '', values: [], nextIdx: startIdx };
|
|
109
|
+
const parts = [];
|
|
110
|
+
const values = [];
|
|
111
|
+
let idx = startIdx;
|
|
112
|
+
for (const [k, v] of Object.entries(conditions))
|
|
113
|
+
{
|
|
114
|
+
if (v === null) { parts.push(`"${k}" IS NULL`); }
|
|
115
|
+
else { parts.push(`"${k}" = $${idx++}`); values.push(this._toSqlValue(v)); }
|
|
116
|
+
}
|
|
117
|
+
return { clause: ' WHERE ' + parts.join(' AND '), values, nextIdx: idx };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @private */
|
|
121
|
+
_buildWhereFromChainPg(where, startIdx = 1)
|
|
122
|
+
{
|
|
123
|
+
if (!where || where.length === 0) return { clause: '', values: [], nextIdx: startIdx };
|
|
124
|
+
const parts = [];
|
|
125
|
+
const values = [];
|
|
126
|
+
let idx = startIdx;
|
|
127
|
+
|
|
128
|
+
for (let i = 0; i < where.length; i++)
|
|
129
|
+
{
|
|
130
|
+
const w = where[i];
|
|
131
|
+
|
|
132
|
+
// Handle raw WHERE clauses (from whereRaw) — convert ? to $N
|
|
133
|
+
if (w.raw)
|
|
134
|
+
{
|
|
135
|
+
let rawExpr = w.raw;
|
|
136
|
+
if (w.params)
|
|
137
|
+
{
|
|
138
|
+
for (const p of w.params)
|
|
139
|
+
{
|
|
140
|
+
rawExpr = rawExpr.replace('?', `$${idx++}`);
|
|
141
|
+
values.push(p);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (i === 0) parts.push(rawExpr);
|
|
145
|
+
else parts.push(`${w.logic} ${rawExpr}`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const { field, op, value, logic } = w;
|
|
150
|
+
let expr;
|
|
151
|
+
|
|
152
|
+
if (op === 'IS NULL') expr = `"${field}" IS NULL`;
|
|
153
|
+
else if (op === 'IS NOT NULL') expr = `"${field}" IS NOT NULL`;
|
|
154
|
+
else if (op === 'IN' || op === 'NOT IN')
|
|
155
|
+
{
|
|
156
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
157
|
+
expr = op === 'IN' ? '0=1' : '1=1';
|
|
158
|
+
else
|
|
159
|
+
{
|
|
160
|
+
const placeholders = value.map(() => `$${idx++}`).join(', ');
|
|
161
|
+
expr = `"${field}" ${op} (${placeholders})`;
|
|
162
|
+
values.push(...value.map(v => this._toSqlValue(v)));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
else if (op === 'BETWEEN')
|
|
166
|
+
{
|
|
167
|
+
expr = `"${field}" BETWEEN $${idx++} AND $${idx++}`;
|
|
168
|
+
values.push(this._toSqlValue(value[0]), this._toSqlValue(value[1]));
|
|
169
|
+
}
|
|
170
|
+
else
|
|
171
|
+
{
|
|
172
|
+
expr = `"${field}" ${op} $${idx++}`;
|
|
173
|
+
values.push(this._toSqlValue(value));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (i === 0) parts.push(expr);
|
|
177
|
+
else parts.push(`${logic} ${expr}`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return { clause: ' WHERE ' + parts.join(' '), values, nextIdx: idx };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Create a table with the given schema.
|
|
185
|
+
* @param {string} table - Table name.
|
|
186
|
+
* @param {object} schema - Column definitions keyed by column name.
|
|
187
|
+
* @returns {Promise<void>}
|
|
188
|
+
*/
|
|
189
|
+
async createTable(table, schema, tableOptions = {})
|
|
190
|
+
{
|
|
191
|
+
const cols = [];
|
|
192
|
+
const tableConstraints = [];
|
|
193
|
+
const compositePKs = [];
|
|
194
|
+
|
|
195
|
+
for (const [name, def] of Object.entries(schema))
|
|
196
|
+
{
|
|
197
|
+
// Pass column name for enum CHECK constraints
|
|
198
|
+
const defWithName = { ...def, _name: name };
|
|
199
|
+
|
|
200
|
+
// Collect composite PK candidates
|
|
201
|
+
if (def.primaryKey && def.compositeKey)
|
|
202
|
+
{
|
|
203
|
+
compositePKs.push(name);
|
|
204
|
+
let line = `"${name}" ${this._typeMap(defWithName)}`;
|
|
205
|
+
if (def.required) line += ' NOT NULL';
|
|
206
|
+
cols.push(line);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
let line = `"${name}" ${this._typeMap(defWithName)}`;
|
|
211
|
+
if (def.primaryKey && def.autoIncrement)
|
|
212
|
+
{
|
|
213
|
+
line = `"${name}" SERIAL PRIMARY KEY`;
|
|
214
|
+
}
|
|
215
|
+
else
|
|
216
|
+
{
|
|
217
|
+
if (def.primaryKey) line += ' PRIMARY KEY';
|
|
218
|
+
if (def.required && !def.primaryKey) line += ' NOT NULL';
|
|
219
|
+
if (def.unique && !def.compositeUnique) line += ' UNIQUE';
|
|
220
|
+
if (def.default !== undefined && typeof def.default !== 'function')
|
|
221
|
+
line += ` DEFAULT ${this._sqlDefault(def.default)}`;
|
|
222
|
+
|
|
223
|
+
// CHECK constraint
|
|
224
|
+
if (def.check) line += ` CHECK(${validateCheck(def.check)})`;
|
|
225
|
+
|
|
226
|
+
if (def.references)
|
|
227
|
+
{
|
|
228
|
+
line += ` REFERENCES "${def.references.table}"("${def.references.column || 'id'}")`;
|
|
229
|
+
if (def.references.onDelete) line += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
|
|
230
|
+
if (def.references.onUpdate) line += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
cols.push(line);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Composite primary key
|
|
237
|
+
if (compositePKs.length > 0)
|
|
238
|
+
{
|
|
239
|
+
tableConstraints.push(`PRIMARY KEY (${compositePKs.map(k => `"${k}"`).join(', ')})`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Composite unique constraints
|
|
243
|
+
const compositeUniques = {};
|
|
244
|
+
for (const [name, def] of Object.entries(schema))
|
|
245
|
+
{
|
|
246
|
+
if (def.compositeUnique)
|
|
247
|
+
{
|
|
248
|
+
const group = typeof def.compositeUnique === 'string' ? def.compositeUnique : 'default';
|
|
249
|
+
if (!compositeUniques[group]) compositeUniques[group] = [];
|
|
250
|
+
compositeUniques[group].push(name);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
for (const [group, columns] of Object.entries(compositeUniques))
|
|
254
|
+
{
|
|
255
|
+
tableConstraints.push(`CONSTRAINT "uq_${table}_${group}" UNIQUE (${columns.map(c => `"${c}"`).join(', ')})`);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const allParts = [...cols, ...tableConstraints];
|
|
259
|
+
let sql = `CREATE TABLE IF NOT EXISTS "${table}" (${allParts.join(', ')})`;
|
|
260
|
+
if (tableOptions.tablespace)
|
|
261
|
+
{
|
|
262
|
+
const ts = String(tableOptions.tablespace);
|
|
263
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(ts)) throw new Error(`Invalid tablespace name: ${ts}`);
|
|
264
|
+
sql += ` TABLESPACE ${ts}`;
|
|
265
|
+
}
|
|
266
|
+
if (tableOptions.unlogged) sql = sql.replace('CREATE TABLE', 'CREATE UNLOGGED TABLE');
|
|
267
|
+
await this._pool.query(sql);
|
|
268
|
+
if (tableOptions.comment)
|
|
269
|
+
{
|
|
270
|
+
await this._pool.query(`COMMENT ON TABLE "${table}" IS $1`, [tableOptions.comment]);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Create indexes defined in schema
|
|
274
|
+
for (const [name, def] of Object.entries(schema))
|
|
275
|
+
{
|
|
276
|
+
if (def.index)
|
|
277
|
+
{
|
|
278
|
+
const idxName = typeof def.index === 'string' ? def.index : `idx_${table}_${name}`;
|
|
279
|
+
await this._pool.query(`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${table}" ("${name}")`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Composite indexes
|
|
284
|
+
const compositeIndexes = {};
|
|
285
|
+
for (const [name, def] of Object.entries(schema))
|
|
286
|
+
{
|
|
287
|
+
if (def.compositeIndex)
|
|
288
|
+
{
|
|
289
|
+
const group = typeof def.compositeIndex === 'string' ? def.compositeIndex : 'default';
|
|
290
|
+
if (!compositeIndexes[group]) compositeIndexes[group] = [];
|
|
291
|
+
compositeIndexes[group].push(name);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
for (const [group, columns] of Object.entries(compositeIndexes))
|
|
295
|
+
{
|
|
296
|
+
const idxName = `idx_${table}_${group}`;
|
|
297
|
+
await this._pool.query(`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${table}" (${columns.map(c => `"${c}"`).join(', ')})`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Drop a table if it exists.
|
|
303
|
+
* @param {string} table - Table name.
|
|
304
|
+
* @returns {Promise<void>}
|
|
305
|
+
*/
|
|
306
|
+
async dropTable(table)
|
|
307
|
+
{
|
|
308
|
+
await this._pool.query(`DROP TABLE IF EXISTS "${table}"`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Insert a single row.
|
|
313
|
+
* @param {string} table - Table name.
|
|
314
|
+
* @param {object} data - Row data as key-value pairs.
|
|
315
|
+
* @returns {Promise<object>} The inserted row.
|
|
316
|
+
*/
|
|
317
|
+
async insert(table, data)
|
|
318
|
+
{
|
|
319
|
+
const keys = Object.keys(data);
|
|
320
|
+
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
321
|
+
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
|
|
322
|
+
const sql = `INSERT INTO "${table}" (${keys.map(k => `"${k}"`).join(', ')}) VALUES (${placeholders}) RETURNING *`;
|
|
323
|
+
const { rows } = await this._pool.query(sql, values);
|
|
324
|
+
return rows[0] || { ...data };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Insert multiple rows in a batch.
|
|
329
|
+
* @param {string} table - Table name.
|
|
330
|
+
* @param {Array<object>} dataArray - Array of row objects.
|
|
331
|
+
* @returns {Promise<Array<object>>} The inserted rows.
|
|
332
|
+
*/
|
|
333
|
+
async insertMany(table, dataArray)
|
|
334
|
+
{
|
|
335
|
+
if (!dataArray.length) return [];
|
|
336
|
+
const keys = Object.keys(dataArray[0]);
|
|
337
|
+
const values = [];
|
|
338
|
+
let idx = 1;
|
|
339
|
+
const rowPlaceholders = dataArray.map(data => {
|
|
340
|
+
const ph = keys.map(() => `$${idx++}`).join(', ');
|
|
341
|
+
for (const k of keys) values.push(this._toSqlValue(data[k]));
|
|
342
|
+
return `(${ph})`;
|
|
343
|
+
}).join(', ');
|
|
344
|
+
const sql = `INSERT INTO "${table}" (${keys.map(k => `"${k}"`).join(', ')}) VALUES ${rowPlaceholders} RETURNING *`;
|
|
345
|
+
const { rows } = await this._pool.query(sql, values);
|
|
346
|
+
return rows;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Update a single row by primary key.
|
|
351
|
+
* @param {string} table - Table name.
|
|
352
|
+
* @param {string} pk - Primary key column.
|
|
353
|
+
* @param {*} pkVal - Primary key value.
|
|
354
|
+
* @param {object} data - Fields to update.
|
|
355
|
+
* @returns {Promise<void>}
|
|
356
|
+
*/
|
|
357
|
+
async update(table, pk, pkVal, data)
|
|
358
|
+
{
|
|
359
|
+
const keys = Object.keys(data);
|
|
360
|
+
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
361
|
+
const sets = keys.map((k, i) => `"${k}" = $${i + 1}`).join(', ');
|
|
362
|
+
values.push(pkVal);
|
|
363
|
+
await this._pool.query(`UPDATE "${table}" SET ${sets} WHERE "${pk}" = $${values.length}`, values);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Update rows matching the given conditions.
|
|
368
|
+
* @param {string} table - Table name.
|
|
369
|
+
* @param {object} conditions - Filter conditions.
|
|
370
|
+
* @param {object} data - Fields to update.
|
|
371
|
+
* @returns {Promise<number>} Number of affected rows.
|
|
372
|
+
*/
|
|
373
|
+
async updateWhere(table, conditions, data)
|
|
374
|
+
{
|
|
375
|
+
const keys = Object.keys(data);
|
|
376
|
+
const values = keys.map(k => this._toSqlValue(data[k]));
|
|
377
|
+
const sets = keys.map((k, i) => `"${k}" = $${i + 1}`).join(', ');
|
|
378
|
+
const { clause, values: whereVals } = this._buildWherePg(conditions, keys.length + 1);
|
|
379
|
+
values.push(...whereVals);
|
|
380
|
+
const { rowCount } = await this._pool.query(`UPDATE "${table}" SET ${sets}${clause}`, values);
|
|
381
|
+
return rowCount;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Delete a single row by primary key.
|
|
386
|
+
* @param {string} table - Table name.
|
|
387
|
+
* @param {string} pk - Primary key column.
|
|
388
|
+
* @param {*} pkVal - Primary key value.
|
|
389
|
+
* @returns {Promise<void>}
|
|
390
|
+
*/
|
|
391
|
+
async remove(table, pk, pkVal)
|
|
392
|
+
{
|
|
393
|
+
await this._pool.query(`DELETE FROM "${table}" WHERE "${pk}" = $1`, [pkVal]);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Delete rows matching the given conditions.
|
|
398
|
+
* @param {string} table - Table name.
|
|
399
|
+
* @param {object} conditions - Filter conditions.
|
|
400
|
+
* @returns {Promise<number>} Number of deleted rows.
|
|
401
|
+
*/
|
|
402
|
+
async deleteWhere(table, conditions)
|
|
403
|
+
{
|
|
404
|
+
const { clause, values } = this._buildWherePg(conditions);
|
|
405
|
+
const { rowCount } = await this._pool.query(`DELETE FROM "${table}"${clause}`, values);
|
|
406
|
+
return rowCount;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Execute a query descriptor built by the Query builder.
|
|
411
|
+
* @param {object} descriptor - Query descriptor with table, fields, where, orderBy, limit, offset.
|
|
412
|
+
* @returns {Promise<Array<object>>} Result rows.
|
|
413
|
+
*/
|
|
414
|
+
async execute(descriptor)
|
|
415
|
+
{
|
|
416
|
+
const { action, table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
|
|
417
|
+
|
|
418
|
+
if (action === 'count')
|
|
419
|
+
{
|
|
420
|
+
const joinStr = this._buildJoins(joins, table);
|
|
421
|
+
const { clause, values } = this._buildWhereFromChainPg(where);
|
|
422
|
+
const { rows } = await this._pool.query(`SELECT COUNT(*) as count FROM "${table}"${joinStr}${clause}`, values);
|
|
423
|
+
return parseInt(rows[0].count, 10);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const selectFields = fields && fields.length ? fields.map(f => `"${f}"`).join(', ') : '*';
|
|
427
|
+
const distinctStr = distinct ? 'DISTINCT ' : '';
|
|
428
|
+
const joinStr = this._buildJoins(joins, table);
|
|
429
|
+
let sql = `SELECT ${distinctStr}${selectFields} FROM "${table}"${joinStr}`;
|
|
430
|
+
const values = [];
|
|
431
|
+
let paramIdx = 1;
|
|
432
|
+
|
|
433
|
+
if (where && where.length)
|
|
434
|
+
{
|
|
435
|
+
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
436
|
+
sql += clause;
|
|
437
|
+
values.push(...wv);
|
|
438
|
+
paramIdx = nextIdx;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
sql += this._buildGroupBy(groupBy);
|
|
442
|
+
|
|
443
|
+
if (having && having.length)
|
|
444
|
+
{
|
|
445
|
+
const { clause: hClause, nextIdx: hIdx } = this._buildHavingPg(having, values, paramIdx);
|
|
446
|
+
sql += hClause;
|
|
447
|
+
paramIdx = hIdx;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (orderBy && orderBy.length)
|
|
451
|
+
sql += ' ORDER BY ' + orderBy.map(o => `"${o.field}" ${o.dir}`).join(', ');
|
|
452
|
+
if (limit !== null && limit !== undefined)
|
|
453
|
+
{
|
|
454
|
+
sql += ` LIMIT $${paramIdx++}`;
|
|
455
|
+
values.push(limit);
|
|
456
|
+
}
|
|
457
|
+
if (offset !== null && offset !== undefined)
|
|
458
|
+
{
|
|
459
|
+
sql += ` OFFSET $${paramIdx++}`;
|
|
460
|
+
values.push(offset);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const { rows } = await this._pool.query(sql, values);
|
|
464
|
+
return rows;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Execute an aggregate function (count, sum, avg, min, max).
|
|
469
|
+
* @param {object} descriptor - Aggregate descriptor with table, function, field, where.
|
|
470
|
+
* @returns {Promise<number|null>} Aggregate result.
|
|
471
|
+
*/
|
|
472
|
+
async aggregate(descriptor)
|
|
473
|
+
{
|
|
474
|
+
const { table, where, aggregateFn, aggregateField, joins, groupBy, having } = descriptor;
|
|
475
|
+
const fn = aggregateFn.toUpperCase();
|
|
476
|
+
const joinStr = this._buildJoins(joins, table);
|
|
477
|
+
const values = [];
|
|
478
|
+
let paramIdx = 1;
|
|
479
|
+
|
|
480
|
+
let sql = `SELECT ${fn}("${aggregateField}") as result FROM "${table}"${joinStr}`;
|
|
481
|
+
|
|
482
|
+
if (where && where.length)
|
|
483
|
+
{
|
|
484
|
+
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
485
|
+
sql += clause;
|
|
486
|
+
values.push(...wv);
|
|
487
|
+
paramIdx = nextIdx;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
sql += this._buildGroupBy(groupBy);
|
|
491
|
+
|
|
492
|
+
if (having && having.length)
|
|
493
|
+
{
|
|
494
|
+
const { clause: hClause } = this._buildHavingPg(having, values, paramIdx);
|
|
495
|
+
sql += hClause;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const { rows } = await this._pool.query(sql, values);
|
|
499
|
+
return rows[0] ? rows[0].result : null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Get the query execution plan (EXPLAIN).
|
|
504
|
+
* @param {object} descriptor - Query descriptor.
|
|
505
|
+
* @param {object} [options] - Configuration options.
|
|
506
|
+
* @param {boolean} [options.analyze] - Include ANALYZE.
|
|
507
|
+
* @param {boolean} [options.buffers] - Include BUFFERS.
|
|
508
|
+
* @param {string} [options.format] - Output format (TEXT, JSON, XML, YAML).
|
|
509
|
+
* @returns {Promise<Array>} Array of execution plan rows.
|
|
510
|
+
*/
|
|
511
|
+
async explain(descriptor, options = {})
|
|
512
|
+
{
|
|
513
|
+
const { table, fields, where, orderBy, limit, offset, distinct, joins, groupBy, having } = descriptor;
|
|
514
|
+
|
|
515
|
+
const selectFields = fields && fields.length ? fields.map(f => `"${f}"`).join(', ') : '*';
|
|
516
|
+
const distinctStr = distinct ? 'DISTINCT ' : '';
|
|
517
|
+
const joinStr = this._buildJoins(joins, table);
|
|
518
|
+
let sql = `SELECT ${distinctStr}${selectFields} FROM "${table}"${joinStr}`;
|
|
519
|
+
const values = [];
|
|
520
|
+
let paramIdx = 1;
|
|
521
|
+
|
|
522
|
+
if (where && where.length)
|
|
523
|
+
{
|
|
524
|
+
const { clause, values: wv, nextIdx } = this._buildWhereFromChainPg(where, paramIdx);
|
|
525
|
+
sql += clause;
|
|
526
|
+
values.push(...wv);
|
|
527
|
+
paramIdx = nextIdx;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
sql += this._buildGroupBy(groupBy);
|
|
531
|
+
|
|
532
|
+
if (having && having.length)
|
|
533
|
+
{
|
|
534
|
+
const { clause: hClause, nextIdx: hIdx } = this._buildHavingPg(having, values, paramIdx);
|
|
535
|
+
sql += hClause;
|
|
536
|
+
paramIdx = hIdx;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
if (orderBy && orderBy.length)
|
|
540
|
+
sql += ' ORDER BY ' + orderBy.map(o => `"${o.field}" ${o.dir}`).join(', ');
|
|
541
|
+
if (limit !== null && limit !== undefined)
|
|
542
|
+
{
|
|
543
|
+
sql += ` LIMIT $${paramIdx++}`;
|
|
544
|
+
values.push(limit);
|
|
545
|
+
}
|
|
546
|
+
if (offset !== null && offset !== undefined)
|
|
547
|
+
{
|
|
548
|
+
sql += ` OFFSET $${paramIdx++}`;
|
|
549
|
+
values.push(offset);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const parts = ['EXPLAIN'];
|
|
553
|
+
if (options.analyze) parts.push('ANALYZE');
|
|
554
|
+
if (options.buffers) parts.push('BUFFERS');
|
|
555
|
+
if (options.format)
|
|
556
|
+
{
|
|
557
|
+
const fmt = String(options.format).toUpperCase();
|
|
558
|
+
const allowed = ['TEXT', 'JSON', 'XML', 'YAML'];
|
|
559
|
+
if (allowed.includes(fmt)) parts.push(`FORMAT ${fmt}`);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const { rows } = await this._pool.query(`${parts.join(' ')} ${sql}`, values);
|
|
563
|
+
return rows;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Get prepared statement cache statistics.
|
|
568
|
+
* @returns {{ size: number, maxSize: number, hits: number, misses: number, hitRate: number }}
|
|
569
|
+
*/
|
|
570
|
+
stmtCacheStats()
|
|
571
|
+
{
|
|
572
|
+
const total = this._stmtCacheHits + this._stmtCacheMisses;
|
|
573
|
+
return {
|
|
574
|
+
size: this._stmtCache.size,
|
|
575
|
+
maxSize: this._stmtCacheMax,
|
|
576
|
+
hits: this._stmtCacheHits,
|
|
577
|
+
misses: this._stmtCacheMisses,
|
|
578
|
+
hitRate: total > 0 ? this._stmtCacheHits / total : 0,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Pre-warm the connection pool by creating idle connections.
|
|
584
|
+
* @param {number} [count=5] - Number of connections to warm up.
|
|
585
|
+
* @returns {Promise<number>} Number of connections successfully warmed.
|
|
586
|
+
*/
|
|
587
|
+
async warmup(count)
|
|
588
|
+
{
|
|
589
|
+
const n = Math.min(Math.max(1, Math.floor(Number(count) || 5)), this._pool.options.max || 10);
|
|
590
|
+
const clients = [];
|
|
591
|
+
for (let i = 0; i < n; i++)
|
|
592
|
+
{
|
|
593
|
+
try
|
|
594
|
+
{
|
|
595
|
+
const client = await this._pool.connect();
|
|
596
|
+
clients.push(client);
|
|
597
|
+
}
|
|
598
|
+
catch (e) { break; }
|
|
599
|
+
}
|
|
600
|
+
for (const client of clients) client.release();
|
|
601
|
+
return clients.length;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Close the database connection.
|
|
606
|
+
* @returns {Promise<void>}
|
|
607
|
+
*/
|
|
608
|
+
async close() { await this._pool.end(); }
|
|
609
|
+
/** @override */
|
|
610
|
+
async raw(sql, ...params) { const { rows } = await this._pool.query(sql, params); return rows; }
|
|
611
|
+
|
|
612
|
+
/** @override */
|
|
613
|
+
async transaction(fn)
|
|
614
|
+
{
|
|
615
|
+
const client = await this._pool.connect();
|
|
616
|
+
try
|
|
617
|
+
{
|
|
618
|
+
await client.query('BEGIN');
|
|
619
|
+
const result = await fn(client);
|
|
620
|
+
await client.query('COMMIT');
|
|
621
|
+
return result;
|
|
622
|
+
}
|
|
623
|
+
catch (e) { await client.query('ROLLBACK'); throw e; }
|
|
624
|
+
finally { client.release(); }
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// -- PostgreSQL Utilities ----------------------------
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* List all user-created tables in the current schema.
|
|
631
|
+
* @param {string} [schema='public'] - Schema name.
|
|
632
|
+
* @returns {Promise<string[]>} Array of table names.
|
|
633
|
+
*/
|
|
634
|
+
async tables(schema = 'public')
|
|
635
|
+
{
|
|
636
|
+
const { rows } = await this._pool.query(
|
|
637
|
+
`SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = $1 ORDER BY tablename`,
|
|
638
|
+
[schema]
|
|
639
|
+
);
|
|
640
|
+
return rows.map(r => r.tablename);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Get column information for a table.
|
|
645
|
+
* @param {string} table - Table name.
|
|
646
|
+
* @param {string} [schema='public'] - Schema definition.
|
|
647
|
+
* @returns {Promise<Array<{ column_name: string, data_type: string, is_nullable: string, column_default: string }>>}
|
|
648
|
+
*/
|
|
649
|
+
async columns(table, schema = 'public')
|
|
650
|
+
{
|
|
651
|
+
const { rows } = await this._pool.query(
|
|
652
|
+
`SELECT column_name, data_type, is_nullable, column_default
|
|
653
|
+
FROM information_schema.columns
|
|
654
|
+
WHERE table_schema = $1 AND table_name = $2
|
|
655
|
+
ORDER BY ordinal_position`,
|
|
656
|
+
[schema, table]
|
|
657
|
+
);
|
|
658
|
+
return rows;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Get the current database size in bytes.
|
|
663
|
+
* @returns {Promise<number>} Database size in bytes.
|
|
664
|
+
*/
|
|
665
|
+
async databaseSize()
|
|
666
|
+
{
|
|
667
|
+
const { rows } = await this._pool.query('SELECT pg_database_size(current_database()) AS size');
|
|
668
|
+
return Number(rows[0].size) || 0;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Get the row count for a table (estimated for large tables, exact for small ones).
|
|
673
|
+
* @param {string} table - Table name.
|
|
674
|
+
* @returns {Promise<number>} Total relation size in bytes.
|
|
675
|
+
*/
|
|
676
|
+
async tableSize(table)
|
|
677
|
+
{
|
|
678
|
+
const { rows } = await this._pool.query(
|
|
679
|
+
`SELECT pg_total_relation_size($1) AS size`, [table]
|
|
680
|
+
);
|
|
681
|
+
return Number(rows[0].size) || 0;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Get connection pool status.
|
|
686
|
+
* @returns {{ total: number, idle: number, waiting: number }}
|
|
687
|
+
*/
|
|
688
|
+
poolStatus()
|
|
689
|
+
{
|
|
690
|
+
return {
|
|
691
|
+
total: this._pool.totalCount,
|
|
692
|
+
idle: this._pool.idleCount,
|
|
693
|
+
waiting: this._pool.waitingCount,
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Get the PostgreSQL server version string.
|
|
699
|
+
* @returns {Promise<string>} Full server version string.
|
|
700
|
+
*/
|
|
701
|
+
async version()
|
|
702
|
+
{
|
|
703
|
+
const { rows } = await this._pool.query('SELECT version() AS ver');
|
|
704
|
+
return rows[0].ver;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Ping the database to check connectivity.
|
|
709
|
+
* @returns {Promise<boolean>} `true` if the server is reachable.
|
|
710
|
+
*/
|
|
711
|
+
async ping()
|
|
712
|
+
{
|
|
713
|
+
try
|
|
714
|
+
{
|
|
715
|
+
await this._pool.query('SELECT 1');
|
|
716
|
+
return true;
|
|
717
|
+
}
|
|
718
|
+
catch { return false; }
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Execute a raw statement that doesn't return rows (INSERT, UPDATE, DDL).
|
|
723
|
+
* @param {string} sql - SQL query string.
|
|
724
|
+
* @param {...*} params - Bound parameter values.
|
|
725
|
+
* @returns {Promise<{ rowCount: number }>}
|
|
726
|
+
*/
|
|
727
|
+
async exec(sql, ...params)
|
|
728
|
+
{
|
|
729
|
+
const { rowCount } = await this._pool.query(sql, params);
|
|
730
|
+
return { rowCount: rowCount || 0 };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// -- Table Info & Debug (Schema Introspection) -----------
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Get detailed table status (rows, sizes, etc.) from pg_stat_user_tables.
|
|
737
|
+
* @param {string} [table] - Table name. If omitted, returns all tables.
|
|
738
|
+
* @returns {Promise<Array<{ name: string, rows: number, totalSize: number, dataSize: number, indexSize: number, sequentialScans: number, indexScans: number, liveTuples: number, deadTuples: number, lastVacuum: string, lastAutoVacuum: string, lastAnalyze: string }>>}
|
|
739
|
+
*/
|
|
740
|
+
async tableStatus(table)
|
|
741
|
+
{
|
|
742
|
+
let sql = `SELECT
|
|
743
|
+
s.relname AS name,
|
|
744
|
+
pg_total_relation_size(s.relid) AS total_size,
|
|
745
|
+
pg_relation_size(s.relid) AS data_size,
|
|
746
|
+
pg_indexes_size(s.relid) AS index_size,
|
|
747
|
+
s.n_live_tup AS live_tuples,
|
|
748
|
+
s.n_dead_tup AS dead_tuples,
|
|
749
|
+
s.seq_scan AS seq_scans,
|
|
750
|
+
s.idx_scan AS idx_scans,
|
|
751
|
+
s.last_vacuum, s.last_autovacuum,
|
|
752
|
+
s.last_analyze, s.last_autoanalyze
|
|
753
|
+
FROM pg_stat_user_tables s`;
|
|
754
|
+
const params = [];
|
|
755
|
+
if (table)
|
|
756
|
+
{
|
|
757
|
+
sql += ` WHERE s.relname = $1`;
|
|
758
|
+
params.push(table);
|
|
759
|
+
}
|
|
760
|
+
sql += ' ORDER BY s.relname';
|
|
761
|
+
const { rows } = await this._pool.query(sql, params);
|
|
762
|
+
return rows.map(r => ({
|
|
763
|
+
name: r.name,
|
|
764
|
+
rows: Number(r.live_tuples) || 0,
|
|
765
|
+
totalSize: Number(r.total_size) || 0,
|
|
766
|
+
dataSize: Number(r.data_size) || 0,
|
|
767
|
+
indexSize: Number(r.index_size) || 0,
|
|
768
|
+
sequentialScans: Number(r.seq_scans) || 0,
|
|
769
|
+
indexScans: Number(r.idx_scans) || 0,
|
|
770
|
+
liveTuples: Number(r.live_tuples) || 0,
|
|
771
|
+
deadTuples: Number(r.dead_tuples) || 0,
|
|
772
|
+
lastVacuum: r.last_vacuum, lastAutoVacuum: r.last_autovacuum,
|
|
773
|
+
lastAnalyze: r.last_analyze,
|
|
774
|
+
}));
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* Get table size in human-readable format.
|
|
779
|
+
* @param {string} table - Table name.
|
|
780
|
+
* @returns {Promise<{ rows: number, dataSize: string, indexSize: string, totalSize: string }>}
|
|
781
|
+
*/
|
|
782
|
+
async tableSizeFormatted(table)
|
|
783
|
+
{
|
|
784
|
+
const status = await this.tableStatus(table);
|
|
785
|
+
if (!status.length) return { rows: 0, dataSize: '0 B', indexSize: '0 B', totalSize: '0 B' };
|
|
786
|
+
const s = status[0];
|
|
787
|
+
const fmt = (b) => {
|
|
788
|
+
if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
|
|
789
|
+
if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
|
|
790
|
+
if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
|
|
791
|
+
return b + ' B';
|
|
792
|
+
};
|
|
793
|
+
return { rows: s.rows, dataSize: fmt(s.dataSize), indexSize: fmt(s.indexSize), totalSize: fmt(s.totalSize) };
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Get indexes for a table.
|
|
798
|
+
* @param {string} table - Table name.
|
|
799
|
+
* @returns {Promise<Array<{ name: string, columns: string, unique: boolean, type: string, size: number }>>}
|
|
800
|
+
*/
|
|
801
|
+
async indexes(table)
|
|
802
|
+
{
|
|
803
|
+
const { rows } = await this._pool.query(
|
|
804
|
+
`SELECT i.relname AS name, ix.indisunique AS unique, am.amname AS type,
|
|
805
|
+
pg_relation_size(i.oid) AS size,
|
|
806
|
+
array_to_string(array_agg(a.attname ORDER BY k.n), ', ') AS columns
|
|
807
|
+
FROM pg_index ix
|
|
808
|
+
JOIN pg_class t ON t.oid = ix.indrelid
|
|
809
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
810
|
+
JOIN pg_am am ON am.oid = i.relam
|
|
811
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n)
|
|
812
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
813
|
+
WHERE t.relname = $1
|
|
814
|
+
GROUP BY i.relname, ix.indisunique, am.amname, i.oid`,
|
|
815
|
+
[table]
|
|
816
|
+
);
|
|
817
|
+
return rows.map(r => ({
|
|
818
|
+
name: r.name, columns: r.columns, unique: r.unique,
|
|
819
|
+
type: r.type, size: Number(r.size) || 0,
|
|
820
|
+
}));
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Get foreign keys for a table.
|
|
825
|
+
* @param {string} table - Table name.
|
|
826
|
+
* @returns {Promise<Array<{ constraintName: string, column: string, referencedTable: string, referencedColumn: string, onDelete: string, onUpdate: string }>>}
|
|
827
|
+
*/
|
|
828
|
+
async foreignKeys(table)
|
|
829
|
+
{
|
|
830
|
+
const { rows } = await this._pool.query(
|
|
831
|
+
`SELECT tc.constraint_name, kcu.column_name,
|
|
832
|
+
ccu.table_name AS referenced_table,
|
|
833
|
+
ccu.column_name AS referenced_column,
|
|
834
|
+
rc.delete_rule, rc.update_rule
|
|
835
|
+
FROM information_schema.table_constraints tc
|
|
836
|
+
JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name
|
|
837
|
+
JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
|
|
838
|
+
JOIN information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name
|
|
839
|
+
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = $1`,
|
|
840
|
+
[table]
|
|
841
|
+
);
|
|
842
|
+
return rows.map(r => ({
|
|
843
|
+
constraintName: r.constraint_name, column: r.column_name,
|
|
844
|
+
referencedTable: r.referenced_table, referencedColumn: r.referenced_column,
|
|
845
|
+
onDelete: r.delete_rule, onUpdate: r.update_rule,
|
|
846
|
+
}));
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Get full database overview — all tables with size and row counts.
|
|
851
|
+
* @returns {Promise<{ tables: Array, totalSize: string, totalRows: number }>}
|
|
852
|
+
*/
|
|
853
|
+
async overview()
|
|
854
|
+
{
|
|
855
|
+
const status = await this.tableStatus();
|
|
856
|
+
let totalBytes = 0;
|
|
857
|
+
let totalRows = 0;
|
|
858
|
+
const fmt = (b) => {
|
|
859
|
+
if (b >= 1073741824) return (b / 1073741824).toFixed(2) + ' GB';
|
|
860
|
+
if (b >= 1048576) return (b / 1048576).toFixed(2) + ' MB';
|
|
861
|
+
if (b >= 1024) return (b / 1024).toFixed(2) + ' KB';
|
|
862
|
+
return b + ' B';
|
|
863
|
+
};
|
|
864
|
+
const tables = status.map(s => {
|
|
865
|
+
totalBytes += s.totalSize;
|
|
866
|
+
totalRows += s.rows;
|
|
867
|
+
return { ...s, formattedSize: fmt(s.totalSize) };
|
|
868
|
+
});
|
|
869
|
+
return { tables, totalSize: fmt(totalBytes), totalRows };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Get server settings/variables.
|
|
874
|
+
* @param {string} [filter] - LIKE pattern to filter settings.
|
|
875
|
+
* @returns {Promise<Object<string, string>>} Key-value map of server settings.
|
|
876
|
+
*/
|
|
877
|
+
async variables(filter)
|
|
878
|
+
{
|
|
879
|
+
const sql = filter
|
|
880
|
+
? `SELECT name, setting FROM pg_settings WHERE name LIKE $1`
|
|
881
|
+
: 'SELECT name, setting FROM pg_settings';
|
|
882
|
+
const params = filter ? [filter] : [];
|
|
883
|
+
const { rows } = await this._pool.query(sql, params);
|
|
884
|
+
const out = {};
|
|
885
|
+
for (const r of rows) out[r.name] = r.setting;
|
|
886
|
+
return out;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Get active backends (like MySQL SHOW PROCESSLIST).
|
|
891
|
+
* @returns {Promise<Array<{ pid: number, user: string, database: string, state: string, query: string, duration: string }>>}
|
|
892
|
+
*/
|
|
893
|
+
async processlist()
|
|
894
|
+
{
|
|
895
|
+
const { rows } = await this._pool.query(
|
|
896
|
+
`SELECT pid, usename AS user, datname AS database, state, query,
|
|
897
|
+
now() - query_start AS duration
|
|
898
|
+
FROM pg_stat_activity WHERE datname = current_database()`
|
|
899
|
+
);
|
|
900
|
+
return rows.map(r => ({
|
|
901
|
+
pid: r.pid, user: r.user, database: r.database,
|
|
902
|
+
state: r.state, query: r.query, duration: String(r.duration || ''),
|
|
903
|
+
}));
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* Get table constraints (PRIMARY KEY, UNIQUE, CHECK, FK).
|
|
908
|
+
* @param {string} table - Table name.
|
|
909
|
+
* @returns {Promise<Array<{ name: string, type: string, definition: string }>>}
|
|
910
|
+
*/
|
|
911
|
+
async constraints(table)
|
|
912
|
+
{
|
|
913
|
+
const { rows } = await this._pool.query(
|
|
914
|
+
`SELECT conname AS name, contype AS type,
|
|
915
|
+
pg_get_constraintdef(c.oid) AS definition
|
|
916
|
+
FROM pg_constraint c
|
|
917
|
+
JOIN pg_class t ON t.oid = c.conrelid
|
|
918
|
+
WHERE t.relname = $1`,
|
|
919
|
+
[table]
|
|
920
|
+
);
|
|
921
|
+
const typeMap = { p: 'PRIMARY KEY', u: 'UNIQUE', c: 'CHECK', f: 'FOREIGN KEY', x: 'EXCLUSION' };
|
|
922
|
+
return rows.map(r => ({
|
|
923
|
+
name: r.name, type: typeMap[r.type] || r.type, definition: r.definition,
|
|
924
|
+
}));
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/**
|
|
928
|
+
* Get table and column comments for schema documentation.
|
|
929
|
+
* @param {string} table - Table name.
|
|
930
|
+
* @returns {Promise<{ tableComment: string, columns: Array<{ name: string, comment: string }> }>}
|
|
931
|
+
*/
|
|
932
|
+
async comments(table)
|
|
933
|
+
{
|
|
934
|
+
const { rows: tcRows } = await this._pool.query(
|
|
935
|
+
`SELECT obj_description(c.oid) AS comment FROM pg_class c WHERE c.relname = $1`, [table]
|
|
936
|
+
);
|
|
937
|
+
const { rows: colRows } = await this._pool.query(
|
|
938
|
+
`SELECT a.attname AS name, col_description(c.oid, a.attnum) AS comment
|
|
939
|
+
FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid
|
|
940
|
+
WHERE c.relname = $1 AND a.attnum > 0 AND NOT a.attisdropped
|
|
941
|
+
ORDER BY a.attnum`, [table]
|
|
942
|
+
);
|
|
943
|
+
return {
|
|
944
|
+
tableComment: (tcRows[0] && tcRows[0].comment) || '',
|
|
945
|
+
columns: colRows.map(r => ({ name: r.name, comment: r.comment || '' })),
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* Run a LISTEN/NOTIFY style query. Useful for subscribing to PG notifications.
|
|
951
|
+
* @param {string} channel - Channel name.
|
|
952
|
+
* @param {Function} callback - Receives { channel, payload }.
|
|
953
|
+
* @returns {Promise<Function>} Unlisten function.
|
|
954
|
+
*/
|
|
955
|
+
async listen(channel, callback)
|
|
956
|
+
{
|
|
957
|
+
const ch = String(channel);
|
|
958
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(ch)) throw new Error(`Invalid channel name: ${ch}`);
|
|
959
|
+
const client = await this._pool.connect();
|
|
960
|
+
await client.query(`LISTEN ${ch}`);
|
|
961
|
+
client.on('notification', callback);
|
|
962
|
+
return async () =>
|
|
963
|
+
{
|
|
964
|
+
await client.query(`UNLISTEN ${ch}`);
|
|
965
|
+
client.removeListener('notification', callback);
|
|
966
|
+
client.release();
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// -- Migration / DDL Methods ----------------------------
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* Add a column to an existing table.
|
|
974
|
+
* @param {string} table - Table name.
|
|
975
|
+
* @param {string} column - Column name.
|
|
976
|
+
* @param {object} def - Column definition (type, required, default, etc.)
|
|
977
|
+
* @returns {Promise<void>}
|
|
978
|
+
*/
|
|
979
|
+
async addColumn(table, column, def)
|
|
980
|
+
{
|
|
981
|
+
const defWithName = { ...def, _name: column };
|
|
982
|
+
let colDef = this._typeMap(defWithName);
|
|
983
|
+
if (def.required) colDef += ' NOT NULL';
|
|
984
|
+
if (def.unique) colDef += ' UNIQUE';
|
|
985
|
+
if (def.default !== undefined && typeof def.default !== 'function')
|
|
986
|
+
colDef += ` DEFAULT ${this._sqlDefault(def.default)}`;
|
|
987
|
+
if (def.check) colDef += ` CHECK(${validateCheck(def.check)})`;
|
|
988
|
+
if (def.references)
|
|
989
|
+
{
|
|
990
|
+
colDef += ` REFERENCES "${def.references.table}"("${def.references.column || 'id'}")`;
|
|
991
|
+
if (def.references.onDelete) colDef += ` ON DELETE ${validateFKAction(def.references.onDelete)}`;
|
|
992
|
+
if (def.references.onUpdate) colDef += ` ON UPDATE ${validateFKAction(def.references.onUpdate)}`;
|
|
993
|
+
}
|
|
994
|
+
await this._pool.query(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${colDef}`);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/**
|
|
998
|
+
* Drop a column from a table.
|
|
999
|
+
* @param {string} table - Table name.
|
|
1000
|
+
* @param {string} column - Column name.
|
|
1001
|
+
* @returns {Promise<void>}
|
|
1002
|
+
*/
|
|
1003
|
+
async dropColumn(table, column)
|
|
1004
|
+
{
|
|
1005
|
+
await this._pool.query(`ALTER TABLE "${table}" DROP COLUMN "${column}"`);
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* Rename a column.
|
|
1010
|
+
* @param {string} table - Table name.
|
|
1011
|
+
* @param {string} oldName - Current name.
|
|
1012
|
+
* @param {string} newName - New name.
|
|
1013
|
+
* @returns {Promise<void>}
|
|
1014
|
+
*/
|
|
1015
|
+
async renameColumn(table, oldName, newName)
|
|
1016
|
+
{
|
|
1017
|
+
await this._pool.query(`ALTER TABLE "${table}" RENAME COLUMN "${oldName}" TO "${newName}"`);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* Rename a table.
|
|
1022
|
+
* @param {string} oldName - Current name.
|
|
1023
|
+
* @param {string} newName - New name.
|
|
1024
|
+
* @returns {Promise<void>}
|
|
1025
|
+
*/
|
|
1026
|
+
async renameTable(oldName, newName)
|
|
1027
|
+
{
|
|
1028
|
+
await this._pool.query(`ALTER TABLE "${oldName}" RENAME TO "${newName}"`);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* Create an index on a table.
|
|
1033
|
+
* @param {string} table - Table name.
|
|
1034
|
+
* @param {string|string[]} columns - Column name(s).
|
|
1035
|
+
* @param {{ name?: string, unique?: boolean }} [options={}]
|
|
1036
|
+
* @returns {Promise<void>}
|
|
1037
|
+
*/
|
|
1038
|
+
async createIndex(table, columns, options = {})
|
|
1039
|
+
{
|
|
1040
|
+
const cols = Array.isArray(columns) ? columns : [columns];
|
|
1041
|
+
const name = options.name || `idx_${table}_${cols.join('_')}`;
|
|
1042
|
+
const unique = options.unique ? 'UNIQUE ' : '';
|
|
1043
|
+
await this._pool.query(`CREATE ${unique}INDEX IF NOT EXISTS "${name}" ON "${table}" (${cols.map(c => `"${c}"`).join(', ')})`);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* Drop an index.
|
|
1048
|
+
* @param {string} name - Index name.
|
|
1049
|
+
* @returns {Promise<void>}
|
|
1050
|
+
*/
|
|
1051
|
+
async dropIndex(_table, name)
|
|
1052
|
+
{
|
|
1053
|
+
await this._pool.query(`DROP INDEX IF EXISTS "${name}"`);
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
/**
|
|
1057
|
+
* Add a foreign key constraint.
|
|
1058
|
+
* @param {string} table - Table name.
|
|
1059
|
+
* @param {string} column - Column name.
|
|
1060
|
+
* @param {string} refTable - Referenced table name.
|
|
1061
|
+
* @param {string} refColumn - Referenced column name.
|
|
1062
|
+
* @param {{ onDelete?: string, onUpdate?: string, name?: string }} [options={}]
|
|
1063
|
+
* @returns {Promise<void>}
|
|
1064
|
+
*/
|
|
1065
|
+
async addForeignKey(table, column, refTable, refColumn, options = {})
|
|
1066
|
+
{
|
|
1067
|
+
const name = options.name || `fk_${table}_${column}`;
|
|
1068
|
+
let sql = `ALTER TABLE "${table}" ADD CONSTRAINT "${name}" FOREIGN KEY ("${column}") REFERENCES "${refTable}"("${refColumn}")`;
|
|
1069
|
+
if (options.onDelete) sql += ` ON DELETE ${validateFKAction(options.onDelete)}`;
|
|
1070
|
+
if (options.onUpdate) sql += ` ON UPDATE ${validateFKAction(options.onUpdate)}`;
|
|
1071
|
+
await this._pool.query(sql);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* Drop a foreign key constraint.
|
|
1076
|
+
* @param {string} table - Table name.
|
|
1077
|
+
* @param {string} constraintName - Constraint name.
|
|
1078
|
+
* @returns {Promise<void>}
|
|
1079
|
+
*/
|
|
1080
|
+
async dropForeignKey(table, constraintName)
|
|
1081
|
+
{
|
|
1082
|
+
await this._pool.query(`ALTER TABLE "${table}" DROP CONSTRAINT "${constraintName}"`);
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Check if a table exists.
|
|
1087
|
+
* @param {string} table - Table name.
|
|
1088
|
+
* @returns {Promise<boolean>} `true` if the table exists.
|
|
1089
|
+
*/
|
|
1090
|
+
async hasTable(table)
|
|
1091
|
+
{
|
|
1092
|
+
const { rows } = await this._pool.query(
|
|
1093
|
+
`SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1`,
|
|
1094
|
+
[table]
|
|
1095
|
+
);
|
|
1096
|
+
return rows.length > 0;
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* Check if a column exists on a table.
|
|
1101
|
+
* @param {string} table - Table name.
|
|
1102
|
+
* @param {string} column - Column name.
|
|
1103
|
+
* @returns {Promise<boolean>} `true` if the column exists.
|
|
1104
|
+
*/
|
|
1105
|
+
async hasColumn(table, column)
|
|
1106
|
+
{
|
|
1107
|
+
const { rows } = await this._pool.query(
|
|
1108
|
+
`SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
|
|
1109
|
+
[table, column]
|
|
1110
|
+
);
|
|
1111
|
+
return rows.length > 0;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* Get detailed column info for a table (migration-friendly format).
|
|
1116
|
+
* @param {string} table - Table name.
|
|
1117
|
+
* @returns {Promise<Array<{ name: string, type: string, nullable: boolean, defaultValue: string|null, primaryKey: boolean }>>}
|
|
1118
|
+
*/
|
|
1119
|
+
async describeTable(table)
|
|
1120
|
+
{
|
|
1121
|
+
const { rows } = await this._pool.query(
|
|
1122
|
+
`SELECT c.column_name AS name, c.data_type AS type,
|
|
1123
|
+
c.is_nullable = 'YES' AS nullable, c.column_default AS default_value,
|
|
1124
|
+
COALESCE(tc.constraint_type = 'PRIMARY KEY', false) AS pk
|
|
1125
|
+
FROM information_schema.columns c
|
|
1126
|
+
LEFT JOIN information_schema.key_column_usage kcu
|
|
1127
|
+
ON c.column_name = kcu.column_name AND c.table_name = kcu.table_name AND c.table_schema = kcu.table_schema
|
|
1128
|
+
LEFT JOIN information_schema.table_constraints tc
|
|
1129
|
+
ON kcu.constraint_name = tc.constraint_name AND tc.constraint_type = 'PRIMARY KEY'
|
|
1130
|
+
WHERE c.table_schema = 'public' AND c.table_name = $1
|
|
1131
|
+
ORDER BY c.ordinal_position`,
|
|
1132
|
+
[table]
|
|
1133
|
+
);
|
|
1134
|
+
return rows.map(r => ({
|
|
1135
|
+
name: r.name,
|
|
1136
|
+
type: r.type,
|
|
1137
|
+
nullable: r.nullable,
|
|
1138
|
+
defaultValue: r.default_value,
|
|
1139
|
+
primaryKey: r.pk,
|
|
1140
|
+
}));
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
module.exports = PostgresAdapter;
|