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/esm/manager.js ADDED
@@ -0,0 +1,138 @@
1
+ import { Logger } from '@pgpmjs/logger';
2
+ import { Pool } from 'pg';
3
+ import { getPgEnvOptions } from 'pg-env';
4
+ import { DbAdmin } from './admin';
5
+ import { PgTestClient } from './test-client';
6
+ const log = new Logger('test-connector');
7
+ const SYS_EVENTS = ['SIGTERM'];
8
+ const end = (pool) => {
9
+ try {
10
+ if (pool.ended || pool.ending) {
11
+ log.warn('⚠️ pg pool already ended or ending');
12
+ return;
13
+ }
14
+ pool.end();
15
+ }
16
+ catch (err) {
17
+ log.error('❌ pg pool termination error:', err);
18
+ }
19
+ };
20
+ export class PgTestConnector {
21
+ static instance;
22
+ clients = new Set();
23
+ pgPools = new Map();
24
+ seenDbConfigs = new Map();
25
+ pendingConnects = new Set();
26
+ config;
27
+ verbose = false;
28
+ shuttingDown = false;
29
+ constructor(config, verbose = false) {
30
+ this.verbose = verbose;
31
+ this.config = config;
32
+ SYS_EVENTS.forEach((event) => {
33
+ process.on(event, () => {
34
+ log.info(`⏹ Received ${event}, closing all connections...`);
35
+ this.closeAll();
36
+ });
37
+ });
38
+ }
39
+ static getInstance(config, verbose = false) {
40
+ if (!PgTestConnector.instance) {
41
+ PgTestConnector.instance = new PgTestConnector(config, verbose);
42
+ }
43
+ return PgTestConnector.instance;
44
+ }
45
+ poolKey(config) {
46
+ return `${config.user}@${config.host}:${config.port}/${config.database}`;
47
+ }
48
+ dbKey(config) {
49
+ return `${config.host}:${config.port}/${config.database}`;
50
+ }
51
+ beginTeardown() {
52
+ this.shuttingDown = true;
53
+ }
54
+ registerConnect(p) {
55
+ this.pendingConnects.add(p);
56
+ p.finally(() => this.pendingConnects.delete(p));
57
+ }
58
+ async awaitPendingConnects() {
59
+ const arr = Array.from(this.pendingConnects);
60
+ if (arr.length) {
61
+ await Promise.allSettled(arr);
62
+ }
63
+ }
64
+ getPool(config) {
65
+ const key = this.poolKey(config);
66
+ if (!this.pgPools.has(key)) {
67
+ const pool = new Pool(config);
68
+ this.pgPools.set(key, pool);
69
+ log.info(`📘 Created new pg pool: ${key}`);
70
+ }
71
+ return this.pgPools.get(key);
72
+ }
73
+ getClient(config, opts = {}) {
74
+ if (this.shuttingDown) {
75
+ throw new Error('PgTestConnector is shutting down; no new clients allowed');
76
+ }
77
+ const client = new PgTestClient(config, {
78
+ trackConnect: (p) => this.registerConnect(p),
79
+ ...opts
80
+ });
81
+ this.clients.add(client);
82
+ const key = this.dbKey(config);
83
+ this.seenDbConfigs.set(key, config);
84
+ log.info(`🔌 New PgTestClient connected to ${config.database}`);
85
+ return client;
86
+ }
87
+ async closeAll() {
88
+ this.beginTeardown();
89
+ await this.awaitPendingConnects();
90
+ log.info('🧹 Closing all PgTestClients...');
91
+ await Promise.all(Array.from(this.clients).map(async (client) => {
92
+ try {
93
+ await client.close();
94
+ log.success(`✅ Closed client for ${client.config.database}`);
95
+ }
96
+ catch (err) {
97
+ log.error(`❌ Error closing PgTestClient for ${client.config.database}:`, err);
98
+ }
99
+ }));
100
+ this.clients.clear();
101
+ log.info('🧯 Disposing pg pools...');
102
+ for (const [key, pool] of this.pgPools.entries()) {
103
+ log.debug(`🧯 Disposing pg pool [${key}]`);
104
+ end(pool);
105
+ }
106
+ this.pgPools.clear();
107
+ log.info('🗑️ Dropping seen databases...');
108
+ await Promise.all(Array.from(this.seenDbConfigs.values()).map(async (config) => {
109
+ try {
110
+ const rootPg = getPgEnvOptions(this.config);
111
+ const admin = new DbAdmin({ ...config, user: rootPg.user, password: rootPg.password }, this.verbose);
112
+ admin.drop();
113
+ log.warn(`🧨 Dropped database: ${config.database}`);
114
+ }
115
+ catch (err) {
116
+ log.error(`❌ Failed to drop database ${config.database}:`, err);
117
+ }
118
+ }));
119
+ this.seenDbConfigs.clear();
120
+ log.success('✅ All PgTestClients closed, pools disposed, databases dropped.');
121
+ this.pendingConnects.clear();
122
+ this.shuttingDown = false;
123
+ }
124
+ close() {
125
+ this.closeAll();
126
+ }
127
+ drop(config) {
128
+ const key = this.dbKey(config);
129
+ const admin = new DbAdmin(config, this.verbose);
130
+ admin.drop();
131
+ log.warn(`🧨 Dropped database: ${config.database}`);
132
+ this.seenDbConfigs.delete(key);
133
+ }
134
+ async kill(client) {
135
+ await client.close();
136
+ this.drop(client.config);
137
+ }
138
+ }
package/esm/roles.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Default role mapping configuration
3
+ */
4
+ export const DEFAULT_ROLE_MAPPING = {
5
+ anonymous: 'anonymous',
6
+ authenticated: 'authenticated',
7
+ administrator: 'administrator',
8
+ default: 'anonymous'
9
+ };
10
+ /**
11
+ * Get resolved role mapping with defaults
12
+ */
13
+ export const getRoleMapping = (options) => {
14
+ return {
15
+ ...DEFAULT_ROLE_MAPPING,
16
+ ...(options?.roles || {})
17
+ };
18
+ };
19
+ /**
20
+ * Get role name by key with fallback to default mapping
21
+ */
22
+ export const getRoleName = (roleKey, options) => {
23
+ const mapping = getRoleMapping(options);
24
+ return mapping[roleKey];
25
+ };
26
+ /**
27
+ * Get default role name
28
+ */
29
+ export const getDefaultRole = (options) => {
30
+ const mapping = getRoleMapping(options);
31
+ return mapping.default;
32
+ };
@@ -0,0 +1,23 @@
1
+ export function sqlfile(files) {
2
+ return {
3
+ seed(ctx) {
4
+ for (const file of files) {
5
+ ctx.admin.loadSql(file, ctx.config.database);
6
+ }
7
+ }
8
+ };
9
+ }
10
+ export function fn(fn) {
11
+ return {
12
+ seed: fn
13
+ };
14
+ }
15
+ export function compose(adapters) {
16
+ return {
17
+ async seed(ctx) {
18
+ for (const adapter of adapters) {
19
+ await adapter.seed(ctx);
20
+ }
21
+ }
22
+ };
23
+ }
@@ -0,0 +1,108 @@
1
+ import { pipeline } from 'node:stream/promises';
2
+ import { Logger } from '@pgpmjs/logger';
3
+ import { parse } from 'csv-parse';
4
+ import { createReadStream, createWriteStream, existsSync } from 'fs';
5
+ import { from as copyFrom, to as copyTo } from 'pg-copy-streams';
6
+ const log = new Logger('csv');
7
+ /**
8
+ * Standalone helper function to load CSV files into PostgreSQL tables
9
+ * @param client - PostgreSQL client instance
10
+ * @param tables - Map of table names to CSV file paths
11
+ */
12
+ export async function loadCsvMap(client, tables) {
13
+ for (const [table, filePath] of Object.entries(tables)) {
14
+ if (!existsSync(filePath)) {
15
+ throw new Error(`CSV file not found: ${filePath}`);
16
+ }
17
+ log.info(`📥 Seeding "${table}" from ${filePath}`);
18
+ const columns = await parseCsvHeader(filePath);
19
+ const quotedColumns = columns.map(col => `"${col.replace(/"/g, '""')}"`);
20
+ const columnList = quotedColumns.join(', ');
21
+ const copyCommand = `COPY ${table} (${columnList}) FROM STDIN WITH CSV HEADER`;
22
+ log.info(`Using columns: ${columnList}`);
23
+ const stream = client.query(copyFrom(copyCommand));
24
+ const source = createReadStream(filePath);
25
+ try {
26
+ await pipeline(source, stream);
27
+ log.success(`✅ Successfully seeded "${table}"`);
28
+ }
29
+ catch (err) {
30
+ log.error(`❌ COPY failed for "${table}": ${err.message}`);
31
+ throw err;
32
+ }
33
+ }
34
+ }
35
+ export function csv(tables) {
36
+ return {
37
+ async seed(ctx) {
38
+ for (const [table, filePath] of Object.entries(tables)) {
39
+ if (!existsSync(filePath)) {
40
+ throw new Error(`CSV file not found: ${filePath}`);
41
+ }
42
+ log.info(`📥 Seeding "${table}" from ${filePath}`);
43
+ await copyCsvIntoTable(ctx.pg, table, filePath);
44
+ }
45
+ }
46
+ };
47
+ }
48
+ async function parseCsvHeader(filePath) {
49
+ const file = createReadStream(filePath);
50
+ const parser = parse({
51
+ bom: true,
52
+ to_line: 1,
53
+ skip_empty_lines: true,
54
+ });
55
+ return new Promise((resolve, reject) => {
56
+ const cleanup = (err) => {
57
+ parser.destroy();
58
+ file.destroy();
59
+ if (err)
60
+ reject(err);
61
+ };
62
+ parser.on('readable', () => {
63
+ const row = parser.read();
64
+ if (!row)
65
+ return;
66
+ if (row.length === 0) {
67
+ cleanup(new Error('CSV header has no columns'));
68
+ return;
69
+ }
70
+ cleanup();
71
+ resolve(row);
72
+ });
73
+ parser.on('error', cleanup);
74
+ file.on('error', cleanup);
75
+ file.pipe(parser);
76
+ });
77
+ }
78
+ export async function copyCsvIntoTable(pg, table, filePath) {
79
+ const client = pg.client;
80
+ const columns = await parseCsvHeader(filePath);
81
+ const quotedColumns = columns.map(col => `"${col.replace(/"/g, '""')}"`);
82
+ const columnList = quotedColumns.join(', ');
83
+ const copyCommand = `COPY ${table} (${columnList}) FROM STDIN WITH CSV HEADER`;
84
+ log.info(`Using columns: ${columnList}`);
85
+ const stream = client.query(copyFrom(copyCommand));
86
+ const source = createReadStream(filePath);
87
+ try {
88
+ await pipeline(source, stream);
89
+ log.success(`✅ Successfully seeded "${table}"`);
90
+ }
91
+ catch (err) {
92
+ log.error(`❌ COPY failed for "${table}": ${err.message}`);
93
+ throw err;
94
+ }
95
+ }
96
+ export async function exportTableToCsv(pg, table, filePath) {
97
+ const client = pg.client;
98
+ const stream = client.query(copyTo(`COPY ${table} TO STDOUT WITH CSV HEADER`));
99
+ const target = createWriteStream(filePath);
100
+ try {
101
+ await pipeline(stream, target);
102
+ log.success(`✅ Exported "${table}" to ${filePath}`);
103
+ }
104
+ catch (err) {
105
+ log.error(`❌ Failed to export "${table}": ${err.message}`);
106
+ throw err;
107
+ }
108
+ }
@@ -0,0 +1,14 @@
1
+ import { compose, fn, sqlfile } from './adapters';
2
+ import { csv } from './csv';
3
+ import { json } from './json';
4
+ import { pgpm } from './pgpm';
5
+ export * from './csv';
6
+ export * from './types';
7
+ export const seed = {
8
+ pgpm,
9
+ json,
10
+ csv,
11
+ compose,
12
+ fn,
13
+ sqlfile
14
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Standalone helper function to insert JSON data into PostgreSQL tables
3
+ * @param client - PostgreSQL client instance
4
+ * @param data - Map of table names to arrays of row objects
5
+ */
6
+ export async function insertJson(client, data) {
7
+ for (const [table, rows] of Object.entries(data)) {
8
+ if (!Array.isArray(rows) || rows.length === 0)
9
+ continue;
10
+ const columns = Object.keys(rows[0]);
11
+ const placeholders = columns.map((_, i) => `$${i + 1}`).join(', ');
12
+ const sql = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders})`;
13
+ for (const row of rows) {
14
+ const values = columns.map((c) => row[c]);
15
+ await client.query(sql, values);
16
+ }
17
+ }
18
+ }
19
+ export function json(data) {
20
+ return {
21
+ async seed(ctx) {
22
+ const { pg } = ctx;
23
+ for (const [table, rows] of Object.entries(data)) {
24
+ if (!Array.isArray(rows) || rows.length === 0)
25
+ continue;
26
+ const columns = Object.keys(rows[0]);
27
+ const placeholders = columns.map((_, i) => `$${i + 1}`).join(', ');
28
+ const sql = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders})`;
29
+ for (const row of rows) {
30
+ const values = columns.map((c) => row[c]);
31
+ await pg.query(sql, values);
32
+ }
33
+ }
34
+ }
35
+ };
36
+ }
@@ -0,0 +1,28 @@
1
+ import { PgpmPackage } from '@pgpmjs/core';
2
+ import { getEnvOptions } from '@pgpmjs/env';
3
+ /**
4
+ * Standalone helper function to deploy pgpm package
5
+ * @param config - PostgreSQL configuration
6
+ * @param cwd - Current working directory (defaults to process.cwd())
7
+ * @param cache - Whether to enable caching (defaults to false)
8
+ */
9
+ export async function deployPgpm(config, cwd, cache = false) {
10
+ const proj = new PgpmPackage(cwd ?? process.cwd());
11
+ if (!proj.isInModule())
12
+ return;
13
+ await proj.deploy(getEnvOptions({
14
+ pg: config,
15
+ deployment: {
16
+ fast: true,
17
+ usePlan: true,
18
+ cache
19
+ }
20
+ }), proj.getModuleName());
21
+ }
22
+ export function pgpm(cwd, cache = false) {
23
+ return {
24
+ async seed(ctx) {
25
+ await deployPgpm(ctx.config, cwd ?? ctx.connect.cwd, cache);
26
+ }
27
+ };
28
+ }
@@ -0,0 +1,15 @@
1
+ import { existsSync, readFileSync } from 'fs';
2
+ /**
3
+ * Standalone helper function to load SQL files into PostgreSQL
4
+ * @param client - PostgreSQL client instance
5
+ * @param files - Array of SQL file paths to execute
6
+ */
7
+ export async function loadSqlFiles(client, files) {
8
+ for (const file of files) {
9
+ if (!existsSync(file)) {
10
+ throw new Error(`SQL file not found: ${file}`);
11
+ }
12
+ const sql = readFileSync(file, 'utf-8');
13
+ await client.query(sql);
14
+ }
15
+ }
@@ -0,0 +1 @@
1
+ export {};
package/esm/stream.js ADDED
@@ -0,0 +1,96 @@
1
+ import { spawn } from 'child_process';
2
+ import { getSpawnEnvWithPg } from 'pg-env';
3
+ import { Readable } from 'stream';
4
+ function setArgs(config) {
5
+ const args = [
6
+ '-U', config.user,
7
+ '-h', config.host,
8
+ '-d', config.database
9
+ ];
10
+ if (config.port) {
11
+ args.push('-p', String(config.port));
12
+ }
13
+ return args;
14
+ }
15
+ // Converts a string to a readable stream (replaces streamify-string)
16
+ function stringToStream(text) {
17
+ const stream = new Readable({
18
+ read() {
19
+ this.push(text);
20
+ this.push(null);
21
+ }
22
+ });
23
+ return stream;
24
+ }
25
+ /**
26
+ * Executes SQL statements by streaming them to psql.
27
+ *
28
+ * IMPORTANT: PostgreSQL stderr handling
29
+ * -------------------------------------
30
+ * PostgreSQL sends different message types to stderr, not just errors:
31
+ * - ERROR: Actual SQL errors (should fail)
32
+ * - WARNING: Potential issues (informational)
33
+ * - NOTICE: Informational messages (should NOT fail)
34
+ * - INFO: Informational messages (should NOT fail)
35
+ * - DEBUG: Debug messages (should NOT fail)
36
+ *
37
+ * Example scenario that previously caused false failures:
38
+ * When running SQL like:
39
+ * GRANT administrator TO app_user;
40
+ *
41
+ * If app_user is already a member of administrator, PostgreSQL outputs:
42
+ * NOTICE: role "app_user" is already a member of role "administrator"
43
+ *
44
+ * This is NOT an error - the GRANT succeeded (it's idempotent). But because
45
+ * this message goes to stderr, the old implementation would reject the promise
46
+ * and fail the test, even though nothing was wrong.
47
+ *
48
+ * Solution:
49
+ * 1. Buffer stderr instead of rejecting immediately on any output
50
+ * 2. Use ON_ERROR_STOP=1 so psql exits with non-zero code on actual SQL errors
51
+ * 3. Only reject if the exit code is non-zero, using buffered stderr as the error message
52
+ *
53
+ * This way, NOTICE/WARNING messages are collected but don't cause failures,
54
+ * while actual SQL errors still properly fail with meaningful error messages.
55
+ */
56
+ export async function streamSql(config, sql) {
57
+ const args = [
58
+ ...setArgs(config),
59
+ // ON_ERROR_STOP=1 makes psql exit with a non-zero code when it encounters
60
+ // an actual SQL error. Without this, psql might continue executing subsequent
61
+ // statements and exit with code 0 even if some statements failed.
62
+ '-v', 'ON_ERROR_STOP=1'
63
+ ];
64
+ return new Promise((resolve, reject) => {
65
+ const sqlStream = stringToStream(sql);
66
+ // Buffer stderr instead of rejecting immediately. This allows us to collect
67
+ // all output (including harmless NOTICE messages) and only use it for error
68
+ // reporting if the process actually fails.
69
+ let stderrBuffer = '';
70
+ const proc = spawn('psql', args, {
71
+ env: getSpawnEnvWithPg(config)
72
+ });
73
+ sqlStream.pipe(proc.stdin);
74
+ // Collect stderr output. We don't reject here because stderr may contain
75
+ // harmless NOTICE/WARNING messages that shouldn't cause test failures.
76
+ proc.stderr.on('data', (data) => {
77
+ stderrBuffer += data.toString();
78
+ });
79
+ // Determine success/failure based on exit code, not stderr content.
80
+ // Exit code 0 = success (even if there were NOTICE messages on stderr)
81
+ // Exit code non-zero = actual error occurred
82
+ proc.on('close', (code) => {
83
+ if (code !== 0) {
84
+ // Include the buffered stderr in the error message for debugging
85
+ reject(new Error(stderrBuffer || `psql exited with code ${code}`));
86
+ }
87
+ else {
88
+ resolve();
89
+ }
90
+ });
91
+ // Handle spawn errors (e.g., psql not found)
92
+ proc.on('error', (error) => {
93
+ reject(error);
94
+ });
95
+ });
96
+ }
@@ -0,0 +1,168 @@
1
+ import { Client } from 'pg';
2
+ import { getRoleName } from './roles';
3
+ import { generateContextStatements } from './context-utils';
4
+ import { insertJson } from './seed/json';
5
+ import { loadCsvMap } from './seed/csv';
6
+ import { loadSqlFiles } from './seed/sql';
7
+ import { deployPgpm } from './seed/pgpm';
8
+ export class PgTestClient {
9
+ config;
10
+ client;
11
+ opts;
12
+ ctxStmts = '';
13
+ contextSettings = {};
14
+ _ended = false;
15
+ connectPromise = null;
16
+ constructor(config, opts = {}) {
17
+ this.opts = opts;
18
+ this.config = config;
19
+ this.client = new Client({
20
+ host: this.config.host,
21
+ port: this.config.port,
22
+ database: this.config.database,
23
+ user: this.config.user,
24
+ password: this.config.password
25
+ });
26
+ if (!opts.deferConnect) {
27
+ this.connectPromise = this.client.connect();
28
+ if (opts.trackConnect)
29
+ opts.trackConnect(this.connectPromise);
30
+ }
31
+ }
32
+ async ensureConnected() {
33
+ if (this.connectPromise) {
34
+ try {
35
+ await this.connectPromise;
36
+ }
37
+ catch { }
38
+ }
39
+ }
40
+ async close() {
41
+ if (!this._ended) {
42
+ this._ended = true;
43
+ await this.ensureConnected();
44
+ this.client.end();
45
+ }
46
+ }
47
+ async begin() {
48
+ await this.client.query('BEGIN;');
49
+ }
50
+ async savepoint(name = 'lqlsavepoint') {
51
+ await this.client.query(`SAVEPOINT "${name}";`);
52
+ }
53
+ async rollback(name = 'lqlsavepoint') {
54
+ await this.client.query(`ROLLBACK TO SAVEPOINT "${name}";`);
55
+ }
56
+ async commit() {
57
+ await this.client.query('COMMIT;');
58
+ }
59
+ async beforeEach() {
60
+ await this.begin();
61
+ await this.savepoint();
62
+ }
63
+ async afterEach() {
64
+ await this.rollback();
65
+ await this.commit();
66
+ }
67
+ setContext(ctx) {
68
+ Object.assign(this.contextSettings, ctx);
69
+ this.ctxStmts = generateContextStatements(this.contextSettings);
70
+ }
71
+ /**
72
+ * Set authentication context for the current session.
73
+ * Configures role and user ID using cascading defaults from options → opts.auth → RoleMapping.
74
+ */
75
+ auth(options = {}) {
76
+ const role = options.role ?? this.opts.auth?.role ?? getRoleName('authenticated', this.opts);
77
+ const userIdKey = options.userIdKey ?? this.opts.auth?.userIdKey ?? 'jwt.claims.user_id';
78
+ const userId = options.userId ?? this.opts.auth?.userId ?? null;
79
+ this.setContext({
80
+ role,
81
+ [userIdKey]: userId !== null ? String(userId) : null
82
+ });
83
+ }
84
+ /**
85
+ * Commit current transaction to make data visible to other connections, then start fresh transaction.
86
+ * Maintains test isolation by creating a savepoint and reapplying session context.
87
+ */
88
+ async publish() {
89
+ await this.commit(); // make data visible to other sessions
90
+ await this.begin(); // fresh tx
91
+ await this.savepoint(); // keep rollback harness
92
+ await this.ctxQuery(); // reapply all setContext()
93
+ }
94
+ /**
95
+ * Clear all session context variables and reset to default anonymous role.
96
+ */
97
+ clearContext() {
98
+ const defaultRole = getRoleName('anonymous', this.opts);
99
+ const nulledSettings = {};
100
+ Object.keys(this.contextSettings).forEach(key => {
101
+ nulledSettings[key] = null;
102
+ });
103
+ nulledSettings.role = defaultRole;
104
+ this.ctxStmts = generateContextStatements(nulledSettings);
105
+ this.contextSettings = { role: defaultRole };
106
+ }
107
+ async any(query, values) {
108
+ const result = await this.query(query, values);
109
+ return result.rows;
110
+ }
111
+ async one(query, values) {
112
+ const rows = await this.any(query, values);
113
+ if (rows.length !== 1) {
114
+ throw new Error('Expected exactly one result');
115
+ }
116
+ return rows[0];
117
+ }
118
+ async oneOrNone(query, values) {
119
+ const rows = await this.any(query, values);
120
+ return rows[0] || null;
121
+ }
122
+ async many(query, values) {
123
+ const rows = await this.any(query, values);
124
+ if (rows.length === 0)
125
+ throw new Error('Expected many rows, got none');
126
+ return rows;
127
+ }
128
+ async manyOrNone(query, values) {
129
+ return this.any(query, values);
130
+ }
131
+ async none(query, values) {
132
+ await this.query(query, values);
133
+ }
134
+ async result(query, values) {
135
+ return this.query(query, values);
136
+ }
137
+ async ctxQuery() {
138
+ if (this.ctxStmts) {
139
+ await this.client.query(this.ctxStmts);
140
+ }
141
+ }
142
+ // NOTE: all queries should call ctxQuery() before executing the query
143
+ async query(query, values) {
144
+ await this.ctxQuery();
145
+ const result = await this.client.query(query, values);
146
+ return result;
147
+ }
148
+ async loadJson(data) {
149
+ await this.ctxQuery();
150
+ await insertJson(this.client, data);
151
+ }
152
+ async loadSql(files) {
153
+ await this.ctxQuery();
154
+ await loadSqlFiles(this.client, files);
155
+ }
156
+ // NON-RLS load/seed methods:
157
+ async loadCsv(tables) {
158
+ // await this.ctxQuery(); // no point to call ctxQuery() here
159
+ // because POSTGRES doesn't support row-level security on COPY FROM...
160
+ await loadCsvMap(this.client, tables);
161
+ }
162
+ async loadPgpm(cwd, cache = false) {
163
+ // await this.ctxQuery(); // no point to call ctxQuery() here
164
+ // because deployPgpm() has it's own way of getting the client...
165
+ // so for now, we'll expose this but it's limited
166
+ await deployPgpm(this.config, cwd, cache);
167
+ }
168
+ }