pgsql-seed 0.0.1
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/README.md +734 -0
- package/admin.d.ts +26 -0
- package/admin.js +144 -0
- package/connect.d.ts +19 -0
- package/connect.js +95 -0
- package/context-utils.d.ts +8 -0
- package/context-utils.js +28 -0
- package/esm/admin.js +140 -0
- package/esm/connect.js +90 -0
- package/esm/context-utils.js +25 -0
- package/esm/index.js +7 -0
- package/esm/manager.js +138 -0
- package/esm/roles.js +32 -0
- package/esm/seed/adapters.js +23 -0
- package/esm/seed/csv.js +108 -0
- package/esm/seed/index.js +14 -0
- package/esm/seed/json.js +36 -0
- package/esm/seed/pgpm.js +28 -0
- package/esm/seed/sql.js +15 -0
- package/esm/seed/types.js +1 -0
- package/esm/stream.js +96 -0
- package/esm/test-client.js +168 -0
- package/esm/utils.js +91 -0
- package/index.d.ts +7 -0
- package/index.js +25 -0
- package/manager.d.ts +26 -0
- package/manager.js +142 -0
- package/package.json +61 -0
- package/roles.d.ts +17 -0
- package/roles.js +38 -0
- package/seed/adapters.d.ts +4 -0
- package/seed/adapters.js +28 -0
- package/seed/csv.d.ts +15 -0
- package/seed/csv.js +114 -0
- package/seed/index.d.ts +14 -0
- package/seed/index.js +31 -0
- package/seed/json.d.ts +12 -0
- package/seed/json.js +40 -0
- package/seed/pgpm.d.ts +10 -0
- package/seed/pgpm.js +32 -0
- package/seed/sql.d.ts +7 -0
- package/seed/sql.js +18 -0
- package/seed/types.d.ts +13 -0
- package/seed/types.js +2 -0
- package/stream.d.ts +33 -0
- package/stream.js +99 -0
- package/test-client.d.ts +55 -0
- package/test-client.js +172 -0
- package/utils.d.ts +17 -0
- package/utils.js +105 -0
package/admin.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { PgTestConnectionOptions } from '@pgpmjs/types';
|
|
2
|
+
import { PgConfig } from 'pg-env';
|
|
3
|
+
import { SeedAdapter } from './seed/types';
|
|
4
|
+
export declare class DbAdmin {
|
|
5
|
+
private config;
|
|
6
|
+
private verbose;
|
|
7
|
+
private roleConfig?;
|
|
8
|
+
constructor(config: PgConfig, verbose?: boolean, roleConfig?: PgTestConnectionOptions);
|
|
9
|
+
private getEnv;
|
|
10
|
+
private run;
|
|
11
|
+
private safeDropDb;
|
|
12
|
+
drop(dbName?: string): void;
|
|
13
|
+
dropTemplate(dbName: string): void;
|
|
14
|
+
create(dbName?: string): void;
|
|
15
|
+
createFromTemplate(template: string, dbName?: string): void;
|
|
16
|
+
installExtensions(extensions: string[] | string, dbName?: string): void;
|
|
17
|
+
connectionString(dbName?: string): string;
|
|
18
|
+
createTemplateFromBase(base: string, template: string): void;
|
|
19
|
+
cleanupTemplate(template: string): void;
|
|
20
|
+
grantRole(role: string, user: string, dbName?: string): Promise<void>;
|
|
21
|
+
grantConnect(role: string, dbName?: string): Promise<void>;
|
|
22
|
+
createUserRole(user: string, password: string, dbName: string, useLocksForRoles?: boolean): Promise<void>;
|
|
23
|
+
loadSql(file: string, dbName: string): void;
|
|
24
|
+
streamSql(sql: string, dbName: string): Promise<void>;
|
|
25
|
+
createSeededTemplate(templateName: string, adapter: SeedAdapter): Promise<void>;
|
|
26
|
+
}
|
package/admin.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DbAdmin = void 0;
|
|
4
|
+
const core_1 = require("@pgpmjs/core");
|
|
5
|
+
const logger_1 = require("@pgpmjs/logger");
|
|
6
|
+
const child_process_1 = require("child_process");
|
|
7
|
+
const fs_1 = require("fs");
|
|
8
|
+
const pg_env_1 = require("pg-env");
|
|
9
|
+
const roles_1 = require("./roles");
|
|
10
|
+
const stream_1 = require("./stream");
|
|
11
|
+
const log = new logger_1.Logger('db-admin');
|
|
12
|
+
class DbAdmin {
|
|
13
|
+
config;
|
|
14
|
+
verbose;
|
|
15
|
+
roleConfig;
|
|
16
|
+
constructor(config, verbose = false, roleConfig) {
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.verbose = verbose;
|
|
19
|
+
this.roleConfig = roleConfig;
|
|
20
|
+
this.config = (0, pg_env_1.getPgEnvOptions)(config);
|
|
21
|
+
}
|
|
22
|
+
getEnv() {
|
|
23
|
+
return {
|
|
24
|
+
PGHOST: this.config.host,
|
|
25
|
+
PGPORT: String(this.config.port),
|
|
26
|
+
PGUSER: this.config.user,
|
|
27
|
+
PGPASSWORD: this.config.password
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
run(command) {
|
|
31
|
+
try {
|
|
32
|
+
(0, child_process_1.execSync)(command, {
|
|
33
|
+
stdio: this.verbose ? 'inherit' : 'pipe',
|
|
34
|
+
env: {
|
|
35
|
+
...process.env,
|
|
36
|
+
...this.getEnv()
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
if (this.verbose)
|
|
40
|
+
log.success(`Executed: ${command}`);
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
log.error(`Command failed: ${command}`);
|
|
44
|
+
if (this.verbose)
|
|
45
|
+
log.error(err.message);
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
safeDropDb(name) {
|
|
50
|
+
try {
|
|
51
|
+
this.run(`dropdb "${name}"`);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (!err.message.includes('does not exist')) {
|
|
55
|
+
log.warn(`Could not drop database ${name}: ${err.message}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
drop(dbName) {
|
|
60
|
+
this.safeDropDb(dbName ?? this.config.database);
|
|
61
|
+
}
|
|
62
|
+
dropTemplate(dbName) {
|
|
63
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate='false' WHERE datname='${dbName}';"`);
|
|
64
|
+
this.drop(dbName);
|
|
65
|
+
}
|
|
66
|
+
create(dbName) {
|
|
67
|
+
const db = dbName ?? this.config.database;
|
|
68
|
+
this.run(`createdb -U ${this.config.user} -h ${this.config.host} -p ${this.config.port} "${db}"`);
|
|
69
|
+
}
|
|
70
|
+
createFromTemplate(template, dbName) {
|
|
71
|
+
const db = dbName ?? this.config.database;
|
|
72
|
+
this.run(`createdb -U ${this.config.user} -h ${this.config.host} -p ${this.config.port} -e "${db}" -T "${template}"`);
|
|
73
|
+
}
|
|
74
|
+
installExtensions(extensions, dbName) {
|
|
75
|
+
const db = dbName ?? this.config.database;
|
|
76
|
+
const extList = typeof extensions === 'string' ? extensions.split(',') : extensions;
|
|
77
|
+
for (const extension of extList) {
|
|
78
|
+
this.run(`psql --dbname "${db}" -c 'CREATE EXTENSION IF NOT EXISTS "${extension}" CASCADE;'`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
connectionString(dbName) {
|
|
82
|
+
const { user, password, host, port } = this.config;
|
|
83
|
+
const db = dbName ?? this.config.database;
|
|
84
|
+
return `postgres://${user}:${password}@${host}:${port}/${db}`;
|
|
85
|
+
}
|
|
86
|
+
createTemplateFromBase(base, template) {
|
|
87
|
+
this.run(`createdb -T "${base}" "${template}"`);
|
|
88
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate = true WHERE datname = '${template}';"`);
|
|
89
|
+
}
|
|
90
|
+
cleanupTemplate(template) {
|
|
91
|
+
try {
|
|
92
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate = false WHERE datname = '${template}'"`);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
log.warn(`Skipping failed UPDATE of datistemplate for ${template}`);
|
|
96
|
+
}
|
|
97
|
+
this.safeDropDb(template);
|
|
98
|
+
}
|
|
99
|
+
async grantRole(role, user, dbName) {
|
|
100
|
+
const db = dbName ?? this.config.database;
|
|
101
|
+
const sql = (0, core_1.generateGrantRoleSQL)(role, user);
|
|
102
|
+
await this.streamSql(sql, db);
|
|
103
|
+
}
|
|
104
|
+
async grantConnect(role, dbName) {
|
|
105
|
+
const db = dbName ?? this.config.database;
|
|
106
|
+
const sql = `GRANT CONNECT ON DATABASE "${db}" TO ${role};`;
|
|
107
|
+
await this.streamSql(sql, db);
|
|
108
|
+
}
|
|
109
|
+
// ONLY granting admin role for testing purposes, normally the db connection for apps won't have admin role
|
|
110
|
+
// DO NOT USE THIS FOR PRODUCTION
|
|
111
|
+
async createUserRole(user, password, dbName, useLocksForRoles = false) {
|
|
112
|
+
const anonRole = (0, roles_1.getRoleName)('anonymous', this.roleConfig);
|
|
113
|
+
const authRole = (0, roles_1.getRoleName)('authenticated', this.roleConfig);
|
|
114
|
+
const adminRole = (0, roles_1.getRoleName)('administrator', this.roleConfig);
|
|
115
|
+
const sql = (0, core_1.generateCreateUserWithGrantsSQL)(user, password, [anonRole, authRole, adminRole], useLocksForRoles);
|
|
116
|
+
await this.streamSql(sql, dbName);
|
|
117
|
+
}
|
|
118
|
+
loadSql(file, dbName) {
|
|
119
|
+
if (!(0, fs_1.existsSync)(file)) {
|
|
120
|
+
throw new Error(`Missing SQL file: ${file}`);
|
|
121
|
+
}
|
|
122
|
+
this.run(`psql -f ${file} ${dbName}`);
|
|
123
|
+
}
|
|
124
|
+
async streamSql(sql, dbName) {
|
|
125
|
+
await (0, stream_1.streamSql)({
|
|
126
|
+
...this.config,
|
|
127
|
+
database: dbName
|
|
128
|
+
}, sql);
|
|
129
|
+
}
|
|
130
|
+
async createSeededTemplate(templateName, adapter) {
|
|
131
|
+
const seedDb = this.config.database;
|
|
132
|
+
this.create(seedDb);
|
|
133
|
+
await adapter.seed({
|
|
134
|
+
admin: this,
|
|
135
|
+
config: this.config,
|
|
136
|
+
pg: null, // placeholder for PgTestClient
|
|
137
|
+
connect: null // placeholder for connection factory
|
|
138
|
+
});
|
|
139
|
+
this.cleanupTemplate(templateName);
|
|
140
|
+
this.createTemplateFromBase(seedDb, templateName);
|
|
141
|
+
this.drop(seedDb);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
exports.DbAdmin = DbAdmin;
|
package/connect.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { PgTestConnectionOptions } from '@pgpmjs/types';
|
|
2
|
+
import { PgConfig } from 'pg-env';
|
|
3
|
+
import { DbAdmin } from './admin';
|
|
4
|
+
import { PgTestConnector } from './manager';
|
|
5
|
+
import { SeedAdapter } from './seed/types';
|
|
6
|
+
import { PgTestClient } from './test-client';
|
|
7
|
+
export declare const getPgRootAdmin: (config: PgConfig, connOpts?: PgTestConnectionOptions) => DbAdmin;
|
|
8
|
+
export interface GetConnectionOpts {
|
|
9
|
+
pg?: Partial<PgConfig>;
|
|
10
|
+
db?: Partial<PgTestConnectionOptions>;
|
|
11
|
+
}
|
|
12
|
+
export interface GetConnectionResult {
|
|
13
|
+
pg: PgTestClient;
|
|
14
|
+
db: PgTestClient;
|
|
15
|
+
admin: DbAdmin;
|
|
16
|
+
teardown: () => Promise<void>;
|
|
17
|
+
manager: PgTestConnector;
|
|
18
|
+
}
|
|
19
|
+
export declare const getConnections: (cn?: GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<GetConnectionResult>;
|
package/connect.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getConnections = exports.getPgRootAdmin = void 0;
|
|
4
|
+
const env_1 = require("@pgpmjs/env");
|
|
5
|
+
const crypto_1 = require("crypto");
|
|
6
|
+
const pg_cache_1 = require("pg-cache");
|
|
7
|
+
const pg_env_1 = require("pg-env");
|
|
8
|
+
const admin_1 = require("./admin");
|
|
9
|
+
const manager_1 = require("./manager");
|
|
10
|
+
const roles_1 = require("./roles");
|
|
11
|
+
const seed_1 = require("./seed");
|
|
12
|
+
let manager;
|
|
13
|
+
const getPgRootAdmin = (config, connOpts = {}) => {
|
|
14
|
+
const opts = (0, pg_env_1.getPgEnvOptions)({
|
|
15
|
+
user: config.user,
|
|
16
|
+
password: config.password,
|
|
17
|
+
host: config.host,
|
|
18
|
+
port: config.port,
|
|
19
|
+
database: connOpts.rootDb
|
|
20
|
+
});
|
|
21
|
+
const admin = new admin_1.DbAdmin(opts, false, connOpts);
|
|
22
|
+
return admin;
|
|
23
|
+
};
|
|
24
|
+
exports.getPgRootAdmin = getPgRootAdmin;
|
|
25
|
+
const getConnOopts = (cn = {}) => {
|
|
26
|
+
const connect = (0, env_1.getConnEnvOptions)(cn.db);
|
|
27
|
+
const config = (0, pg_env_1.getPgEnvOptions)({
|
|
28
|
+
database: `${connect.prefix}${(0, crypto_1.randomUUID)()}`,
|
|
29
|
+
...cn.pg
|
|
30
|
+
});
|
|
31
|
+
return {
|
|
32
|
+
pg: config,
|
|
33
|
+
db: connect
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const getConnections = async (cn = {}, seedAdapters = [seed_1.seed.pgpm()]) => {
|
|
37
|
+
cn = getConnOopts(cn);
|
|
38
|
+
const config = cn.pg;
|
|
39
|
+
const connOpts = cn.db;
|
|
40
|
+
const root = (0, exports.getPgRootAdmin)(config, connOpts);
|
|
41
|
+
await root.createUserRole(connOpts.connections.app.user, connOpts.connections.app.password, connOpts.rootDb);
|
|
42
|
+
const admin = new admin_1.DbAdmin(config, false, connOpts);
|
|
43
|
+
if (process.env.TEST_DB) {
|
|
44
|
+
config.database = process.env.TEST_DB;
|
|
45
|
+
}
|
|
46
|
+
else if (connOpts.template) {
|
|
47
|
+
admin.createFromTemplate(connOpts.template, config.database);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
admin.create(config.database);
|
|
51
|
+
admin.installExtensions(connOpts.extensions);
|
|
52
|
+
}
|
|
53
|
+
await admin.grantConnect(connOpts.connections.app.user, config.database);
|
|
54
|
+
manager = manager_1.PgTestConnector.getInstance(config);
|
|
55
|
+
const pg = manager.getClient(config);
|
|
56
|
+
let teardownPromise = null;
|
|
57
|
+
const teardown = async () => {
|
|
58
|
+
if (teardownPromise)
|
|
59
|
+
return teardownPromise;
|
|
60
|
+
teardownPromise = (async () => {
|
|
61
|
+
manager.beginTeardown();
|
|
62
|
+
await (0, pg_cache_1.teardownPgPools)();
|
|
63
|
+
await manager.closeAll();
|
|
64
|
+
})();
|
|
65
|
+
return teardownPromise;
|
|
66
|
+
};
|
|
67
|
+
if (seedAdapters.length) {
|
|
68
|
+
try {
|
|
69
|
+
await seed_1.seed.compose(seedAdapters).seed({
|
|
70
|
+
connect: connOpts,
|
|
71
|
+
admin,
|
|
72
|
+
config: config,
|
|
73
|
+
pg: manager.getClient(config)
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
const err = error;
|
|
78
|
+
const msg = err && (err.stack || err.message) ? (err.stack || err.message) : String(err);
|
|
79
|
+
process.stderr.write(`[pgsql-test] Seed error (continuing): ${msg}\n`);
|
|
80
|
+
// continue without teardown to allow caller-managed lifecycle
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const dbConfig = {
|
|
84
|
+
...config,
|
|
85
|
+
user: connOpts.connections.app.user,
|
|
86
|
+
password: connOpts.connections.app.password
|
|
87
|
+
};
|
|
88
|
+
const db = manager.getClient(dbConfig, {
|
|
89
|
+
auth: connOpts.auth,
|
|
90
|
+
roles: connOpts.roles
|
|
91
|
+
});
|
|
92
|
+
db.setContext({ role: (0, roles_1.getDefaultRole)(connOpts) });
|
|
93
|
+
return { pg, db, teardown, manager, admin };
|
|
94
|
+
};
|
|
95
|
+
exports.getConnections = getConnections;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PgTestClientContext } from '@pgpmjs/types';
|
|
2
|
+
/**
|
|
3
|
+
* Generate SQL statements to set PostgreSQL session context variables
|
|
4
|
+
* Uses SET LOCAL ROLE for the 'role' key and set_config() for other variables
|
|
5
|
+
* @param context - Context settings to apply
|
|
6
|
+
* @returns SQL string with SET LOCAL ROLE and set_config() statements
|
|
7
|
+
*/
|
|
8
|
+
export declare function generateContextStatements(context: PgTestClientContext): string;
|
package/context-utils.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateContextStatements = generateContextStatements;
|
|
4
|
+
/**
|
|
5
|
+
* Generate SQL statements to set PostgreSQL session context variables
|
|
6
|
+
* Uses SET LOCAL ROLE for the 'role' key and set_config() for other variables
|
|
7
|
+
* @param context - Context settings to apply
|
|
8
|
+
* @returns SQL string with SET LOCAL ROLE and set_config() statements
|
|
9
|
+
*/
|
|
10
|
+
function generateContextStatements(context) {
|
|
11
|
+
return Object.entries(context)
|
|
12
|
+
.map(([key, val]) => {
|
|
13
|
+
if (key === 'role') {
|
|
14
|
+
if (val === null || val === undefined) {
|
|
15
|
+
return 'SET LOCAL ROLE NONE;';
|
|
16
|
+
}
|
|
17
|
+
const escapedRole = val.replace(/"/g, '""');
|
|
18
|
+
return `SET LOCAL ROLE "${escapedRole}";`;
|
|
19
|
+
}
|
|
20
|
+
// Use set_config for other context variables
|
|
21
|
+
if (val === null || val === undefined) {
|
|
22
|
+
return `SELECT set_config('${key}', NULL, true);`;
|
|
23
|
+
}
|
|
24
|
+
const escapedVal = val.replace(/'/g, "''");
|
|
25
|
+
return `SELECT set_config('${key}', '${escapedVal}', true);`;
|
|
26
|
+
})
|
|
27
|
+
.join('\n');
|
|
28
|
+
}
|
package/esm/admin.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { generateCreateUserWithGrantsSQL, generateGrantRoleSQL } from '@pgpmjs/core';
|
|
2
|
+
import { Logger } from '@pgpmjs/logger';
|
|
3
|
+
import { execSync } from 'child_process';
|
|
4
|
+
import { existsSync } from 'fs';
|
|
5
|
+
import { getPgEnvOptions } from 'pg-env';
|
|
6
|
+
import { getRoleName } from './roles';
|
|
7
|
+
import { streamSql as stream } from './stream';
|
|
8
|
+
const log = new Logger('db-admin');
|
|
9
|
+
export class DbAdmin {
|
|
10
|
+
config;
|
|
11
|
+
verbose;
|
|
12
|
+
roleConfig;
|
|
13
|
+
constructor(config, verbose = false, roleConfig) {
|
|
14
|
+
this.config = config;
|
|
15
|
+
this.verbose = verbose;
|
|
16
|
+
this.roleConfig = roleConfig;
|
|
17
|
+
this.config = getPgEnvOptions(config);
|
|
18
|
+
}
|
|
19
|
+
getEnv() {
|
|
20
|
+
return {
|
|
21
|
+
PGHOST: this.config.host,
|
|
22
|
+
PGPORT: String(this.config.port),
|
|
23
|
+
PGUSER: this.config.user,
|
|
24
|
+
PGPASSWORD: this.config.password
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
run(command) {
|
|
28
|
+
try {
|
|
29
|
+
execSync(command, {
|
|
30
|
+
stdio: this.verbose ? 'inherit' : 'pipe',
|
|
31
|
+
env: {
|
|
32
|
+
...process.env,
|
|
33
|
+
...this.getEnv()
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
if (this.verbose)
|
|
37
|
+
log.success(`Executed: ${command}`);
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
log.error(`Command failed: ${command}`);
|
|
41
|
+
if (this.verbose)
|
|
42
|
+
log.error(err.message);
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
safeDropDb(name) {
|
|
47
|
+
try {
|
|
48
|
+
this.run(`dropdb "${name}"`);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
if (!err.message.includes('does not exist')) {
|
|
52
|
+
log.warn(`Could not drop database ${name}: ${err.message}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
drop(dbName) {
|
|
57
|
+
this.safeDropDb(dbName ?? this.config.database);
|
|
58
|
+
}
|
|
59
|
+
dropTemplate(dbName) {
|
|
60
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate='false' WHERE datname='${dbName}';"`);
|
|
61
|
+
this.drop(dbName);
|
|
62
|
+
}
|
|
63
|
+
create(dbName) {
|
|
64
|
+
const db = dbName ?? this.config.database;
|
|
65
|
+
this.run(`createdb -U ${this.config.user} -h ${this.config.host} -p ${this.config.port} "${db}"`);
|
|
66
|
+
}
|
|
67
|
+
createFromTemplate(template, dbName) {
|
|
68
|
+
const db = dbName ?? this.config.database;
|
|
69
|
+
this.run(`createdb -U ${this.config.user} -h ${this.config.host} -p ${this.config.port} -e "${db}" -T "${template}"`);
|
|
70
|
+
}
|
|
71
|
+
installExtensions(extensions, dbName) {
|
|
72
|
+
const db = dbName ?? this.config.database;
|
|
73
|
+
const extList = typeof extensions === 'string' ? extensions.split(',') : extensions;
|
|
74
|
+
for (const extension of extList) {
|
|
75
|
+
this.run(`psql --dbname "${db}" -c 'CREATE EXTENSION IF NOT EXISTS "${extension}" CASCADE;'`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
connectionString(dbName) {
|
|
79
|
+
const { user, password, host, port } = this.config;
|
|
80
|
+
const db = dbName ?? this.config.database;
|
|
81
|
+
return `postgres://${user}:${password}@${host}:${port}/${db}`;
|
|
82
|
+
}
|
|
83
|
+
createTemplateFromBase(base, template) {
|
|
84
|
+
this.run(`createdb -T "${base}" "${template}"`);
|
|
85
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate = true WHERE datname = '${template}';"`);
|
|
86
|
+
}
|
|
87
|
+
cleanupTemplate(template) {
|
|
88
|
+
try {
|
|
89
|
+
this.run(`psql -c "UPDATE pg_database SET datistemplate = false WHERE datname = '${template}'"`);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
log.warn(`Skipping failed UPDATE of datistemplate for ${template}`);
|
|
93
|
+
}
|
|
94
|
+
this.safeDropDb(template);
|
|
95
|
+
}
|
|
96
|
+
async grantRole(role, user, dbName) {
|
|
97
|
+
const db = dbName ?? this.config.database;
|
|
98
|
+
const sql = generateGrantRoleSQL(role, user);
|
|
99
|
+
await this.streamSql(sql, db);
|
|
100
|
+
}
|
|
101
|
+
async grantConnect(role, dbName) {
|
|
102
|
+
const db = dbName ?? this.config.database;
|
|
103
|
+
const sql = `GRANT CONNECT ON DATABASE "${db}" TO ${role};`;
|
|
104
|
+
await this.streamSql(sql, db);
|
|
105
|
+
}
|
|
106
|
+
// ONLY granting admin role for testing purposes, normally the db connection for apps won't have admin role
|
|
107
|
+
// DO NOT USE THIS FOR PRODUCTION
|
|
108
|
+
async createUserRole(user, password, dbName, useLocksForRoles = false) {
|
|
109
|
+
const anonRole = getRoleName('anonymous', this.roleConfig);
|
|
110
|
+
const authRole = getRoleName('authenticated', this.roleConfig);
|
|
111
|
+
const adminRole = getRoleName('administrator', this.roleConfig);
|
|
112
|
+
const sql = generateCreateUserWithGrantsSQL(user, password, [anonRole, authRole, adminRole], useLocksForRoles);
|
|
113
|
+
await this.streamSql(sql, dbName);
|
|
114
|
+
}
|
|
115
|
+
loadSql(file, dbName) {
|
|
116
|
+
if (!existsSync(file)) {
|
|
117
|
+
throw new Error(`Missing SQL file: ${file}`);
|
|
118
|
+
}
|
|
119
|
+
this.run(`psql -f ${file} ${dbName}`);
|
|
120
|
+
}
|
|
121
|
+
async streamSql(sql, dbName) {
|
|
122
|
+
await stream({
|
|
123
|
+
...this.config,
|
|
124
|
+
database: dbName
|
|
125
|
+
}, sql);
|
|
126
|
+
}
|
|
127
|
+
async createSeededTemplate(templateName, adapter) {
|
|
128
|
+
const seedDb = this.config.database;
|
|
129
|
+
this.create(seedDb);
|
|
130
|
+
await adapter.seed({
|
|
131
|
+
admin: this,
|
|
132
|
+
config: this.config,
|
|
133
|
+
pg: null, // placeholder for PgTestClient
|
|
134
|
+
connect: null // placeholder for connection factory
|
|
135
|
+
});
|
|
136
|
+
this.cleanupTemplate(templateName);
|
|
137
|
+
this.createTemplateFromBase(seedDb, templateName);
|
|
138
|
+
this.drop(seedDb);
|
|
139
|
+
}
|
|
140
|
+
}
|
package/esm/connect.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getConnEnvOptions } from '@pgpmjs/env';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { teardownPgPools } from 'pg-cache';
|
|
4
|
+
import { getPgEnvOptions, } from 'pg-env';
|
|
5
|
+
import { DbAdmin } from './admin';
|
|
6
|
+
import { PgTestConnector } from './manager';
|
|
7
|
+
import { getDefaultRole } from './roles';
|
|
8
|
+
import { seed } from './seed';
|
|
9
|
+
let manager;
|
|
10
|
+
export const getPgRootAdmin = (config, connOpts = {}) => {
|
|
11
|
+
const opts = getPgEnvOptions({
|
|
12
|
+
user: config.user,
|
|
13
|
+
password: config.password,
|
|
14
|
+
host: config.host,
|
|
15
|
+
port: config.port,
|
|
16
|
+
database: connOpts.rootDb
|
|
17
|
+
});
|
|
18
|
+
const admin = new DbAdmin(opts, false, connOpts);
|
|
19
|
+
return admin;
|
|
20
|
+
};
|
|
21
|
+
const getConnOopts = (cn = {}) => {
|
|
22
|
+
const connect = getConnEnvOptions(cn.db);
|
|
23
|
+
const config = getPgEnvOptions({
|
|
24
|
+
database: `${connect.prefix}${randomUUID()}`,
|
|
25
|
+
...cn.pg
|
|
26
|
+
});
|
|
27
|
+
return {
|
|
28
|
+
pg: config,
|
|
29
|
+
db: connect
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
export const getConnections = async (cn = {}, seedAdapters = [seed.pgpm()]) => {
|
|
33
|
+
cn = getConnOopts(cn);
|
|
34
|
+
const config = cn.pg;
|
|
35
|
+
const connOpts = cn.db;
|
|
36
|
+
const root = getPgRootAdmin(config, connOpts);
|
|
37
|
+
await root.createUserRole(connOpts.connections.app.user, connOpts.connections.app.password, connOpts.rootDb);
|
|
38
|
+
const admin = new DbAdmin(config, false, connOpts);
|
|
39
|
+
if (process.env.TEST_DB) {
|
|
40
|
+
config.database = process.env.TEST_DB;
|
|
41
|
+
}
|
|
42
|
+
else if (connOpts.template) {
|
|
43
|
+
admin.createFromTemplate(connOpts.template, config.database);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
admin.create(config.database);
|
|
47
|
+
admin.installExtensions(connOpts.extensions);
|
|
48
|
+
}
|
|
49
|
+
await admin.grantConnect(connOpts.connections.app.user, config.database);
|
|
50
|
+
manager = PgTestConnector.getInstance(config);
|
|
51
|
+
const pg = manager.getClient(config);
|
|
52
|
+
let teardownPromise = null;
|
|
53
|
+
const teardown = async () => {
|
|
54
|
+
if (teardownPromise)
|
|
55
|
+
return teardownPromise;
|
|
56
|
+
teardownPromise = (async () => {
|
|
57
|
+
manager.beginTeardown();
|
|
58
|
+
await teardownPgPools();
|
|
59
|
+
await manager.closeAll();
|
|
60
|
+
})();
|
|
61
|
+
return teardownPromise;
|
|
62
|
+
};
|
|
63
|
+
if (seedAdapters.length) {
|
|
64
|
+
try {
|
|
65
|
+
await seed.compose(seedAdapters).seed({
|
|
66
|
+
connect: connOpts,
|
|
67
|
+
admin,
|
|
68
|
+
config: config,
|
|
69
|
+
pg: manager.getClient(config)
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
const err = error;
|
|
74
|
+
const msg = err && (err.stack || err.message) ? (err.stack || err.message) : String(err);
|
|
75
|
+
process.stderr.write(`[pgsql-test] Seed error (continuing): ${msg}\n`);
|
|
76
|
+
// continue without teardown to allow caller-managed lifecycle
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const dbConfig = {
|
|
80
|
+
...config,
|
|
81
|
+
user: connOpts.connections.app.user,
|
|
82
|
+
password: connOpts.connections.app.password
|
|
83
|
+
};
|
|
84
|
+
const db = manager.getClient(dbConfig, {
|
|
85
|
+
auth: connOpts.auth,
|
|
86
|
+
roles: connOpts.roles
|
|
87
|
+
});
|
|
88
|
+
db.setContext({ role: getDefaultRole(connOpts) });
|
|
89
|
+
return { pg, db, teardown, manager, admin };
|
|
90
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate SQL statements to set PostgreSQL session context variables
|
|
3
|
+
* Uses SET LOCAL ROLE for the 'role' key and set_config() for other variables
|
|
4
|
+
* @param context - Context settings to apply
|
|
5
|
+
* @returns SQL string with SET LOCAL ROLE and set_config() statements
|
|
6
|
+
*/
|
|
7
|
+
export function generateContextStatements(context) {
|
|
8
|
+
return Object.entries(context)
|
|
9
|
+
.map(([key, val]) => {
|
|
10
|
+
if (key === 'role') {
|
|
11
|
+
if (val === null || val === undefined) {
|
|
12
|
+
return 'SET LOCAL ROLE NONE;';
|
|
13
|
+
}
|
|
14
|
+
const escapedRole = val.replace(/"/g, '""');
|
|
15
|
+
return `SET LOCAL ROLE "${escapedRole}";`;
|
|
16
|
+
}
|
|
17
|
+
// Use set_config for other context variables
|
|
18
|
+
if (val === null || val === undefined) {
|
|
19
|
+
return `SELECT set_config('${key}', NULL, true);`;
|
|
20
|
+
}
|
|
21
|
+
const escapedVal = val.replace(/'/g, "''");
|
|
22
|
+
return `SELECT set_config('${key}', '${escapedVal}', true);`;
|
|
23
|
+
})
|
|
24
|
+
.join('\n');
|
|
25
|
+
}
|