Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | 8x 8x 8x 8x 9x 9x 8x 272x 272x 272x 5x 5x 5x 34x 1x 33x 1x 32x 5x 27x 5x 5x 267x 1x 1x 1x 266x 1x 1x 1x 265x 2x 2x 2x 2x 2x 263x 15x 1x 1x 1x 14x 2x 2x 2x 12x 12x 12x 248x 248x 8x 13x 1x 1x 1x 1x 8x 8x 13x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 1x 3x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 3x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x | /**
* PostgreSQL Database Adapter for Coherent.js
*
* @fileoverview PostgreSQL adapter implementation with connection pooling and advanced features.
*/
import { normalizeIsolationLevel } from './isolation-level.js';
/**
* Convert `?` placeholders to PostgreSQL's numbered `$1, $2, ...` parameters.
*
* Left untouched: `?` inside single-quoted strings (including `E'...'` escape strings),
* double-quoted identifiers, dollar-quoted strings and comments, and the JSONB operators
* `?|` and `?&`. The JSONB key-exists operator `?` cannot be told apart from a
* placeholder: write it as `??` (sent as a single `?`) or use `jsonb_exists()`.
*
* @param {string} sql - SQL with `?` placeholders
* @returns {string} SQL with numbered parameters
*/
function convertPlaceholders(sql) {
let output = '';
let index = 1;
let i = 0;
const copyUntil = (end) => {
output += sql.slice(i, end);
i = end;
};
while (i < sql.length) {
const char = sql[i];
const next = sql[i + 1];
if (char === '\'' || char === '"') {
// E'...' strings treat backslash as an escape character
const escapes = char === '\'' && /[Ee]/.test(sql[i - 1] || '') && !/[A-Za-z0-9_]/.test(sql[i - 2] || '');
let j = i + 1;
while (j < sql.length) {
if (escapes && sql[j] === '\\') {
j += 2;
} else if (sql[j] === char && sql[j + 1] === char) {
j += 2;
} else if (sql[j] === char) {
break;
} else {
j++;
}
}
copyUntil(Math.min(j + 1, sql.length));
continue;
}
if (char === '-' && next === '-') {
const end = sql.indexOf('\n', i);
copyUntil(end === -1 ? sql.length : end);
continue;
}
if (char === '/' && next === '*') {
const end = sql.indexOf('*/', i + 2);
copyUntil(end === -1 ? sql.length : end + 2);
continue;
}
if (char === '$') {
const tag = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
Eif (tag) {
const end = sql.indexOf(tag[0], i + tag[0].length);
copyUntil(end === -1 ? sql.length : end + tag[0].length);
continue;
}
}
if (char === '?') {
if (next === '?') {
output += '?';
i += 2;
continue;
}
if ((next === '|' && sql[i + 2] !== '|') || next === '&') {
output += `?${next}`;
i += 2;
continue;
}
output += `$${index++}`;
i++;
continue;
}
output += char;
i++;
}
return output;
}
/**
* Create PostgreSQL adapter instance
*
* @returns {Object} PostgreSQL adapter instance
*/
export function createPostgreSQLAdapter() {
let pg = null;
async function initializePostgreSQL() {
Eif (!pg) {
try {
const pgModule = await import('pg');
pg = pgModule.default || pgModule;
} catch {
throw new Error('pg package is required for PostgreSQL adapter. Install with: npm install pg');
}
}
}
function extractInsertId(result) {
Iif (result.rows && result.rows.length > 0) {
const row = result.rows[0];
return row.id || row.insertId || row.lastval || null;
}
return null;
}
return {
/**
* Create connection pool
*/
async createPool(config) {
await initializePostgreSQL();
const poolConfig = {
host: config.host,
port: config.port,
database: config.database,
user: config.username,
password: config.password,
min: config.pool.min,
max: config.pool.max,
acquireTimeoutMillis: config.pool.acquireTimeoutMillis,
createTimeoutMillis: config.pool.createTimeoutMillis,
destroyTimeoutMillis: config.pool.destroyTimeoutMillis,
idleTimeoutMillis: config.pool.idleTimeoutMillis,
reapIntervalMillis: config.pool.reapIntervalMillis,
createRetryIntervalMillis: config.pool.createRetryIntervalMillis,
ssl: config.ssl || false
};
const pool = new pg.Pool(poolConfig);
pool.on('error', (err) => {
console.error('PostgreSQL pool error:', err);
});
return pool;
},
/**
* Test database connection
*/
async testConnection(pool) {
const client = await pool.connect();
try {
await client.query('SELECT 1');
} finally {
client.release();
}
},
/**
* Execute database query
*/
async query(pool, sql, params = [], options = {}) {
const client = await pool.connect();
try {
const pgSql = convertPlaceholders(sql);
const result = await client.query(pgSql, params);
Iif (options.single) {
return result.rows[0] || null;
}
return {
rows: result.rows,
rowCount: result.rowCount,
affectedRows: result.rowCount,
insertId: extractInsertId(result)
};
} finally {
client.release();
}
},
/**
* Start database transaction
*
* @param {Object} pool - pg Pool
* @param {Object} [options={}]
* @param {string} [options.isolationLevel] - READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ or SERIALIZABLE
* @param {boolean} [options.readOnly] - Start a READ ONLY transaction
*/
async transaction(pool, options = {}) {
// Validate before taking a client, so a bad option cannot leak one
const isolationLevel = normalizeIsolationLevel(options.isolationLevel);
let beginSql = 'BEGIN';
if (isolationLevel) {
beginSql += ` ISOLATION LEVEL ${isolationLevel}`;
}
if (options.readOnly) {
beginSql += ' READ ONLY';
}
const client = await pool.connect();
let released = false;
const release = (error) => {
Eif (!released) {
released = true;
// A truthy argument makes pg discard the client instead of reusing it
client.release(error);
}
};
try {
await client.query(beginSql);
} catch (_error) {
release(_error);
throw _error;
}
const assertActive = () => {
if (transaction.isCommitted || transaction.isRolledBack) {
throw new Error('Transaction already completed');
}
};
const transaction = {
client,
pool,
isCommitted: false,
isRolledBack: false,
query: async (sql, params, queryOptions) => {
if (transaction.isCommitted || transaction.isRolledBack) {
throw new Error('Cannot execute query on completed transaction');
}
const pgSql = convertPlaceholders(sql);
const result = await client.query(pgSql, params);
if (queryOptions && queryOptions.single) {
return result.rows[0] || null;
}
return {
rows: result.rows,
rowCount: result.rowCount,
affectedRows: result.rowCount,
insertId: extractInsertId(result)
};
},
commit: async () => {
assertActive();
try {
await client.query('COMMIT');
transaction.isCommitted = true;
release();
} catch (_error) {
// PostgreSQL ends the transaction when COMMIT fails
transaction.isRolledBack = true;
release(_error);
throw _error;
}
},
rollback: async () => {
assertActive();
transaction.isRolledBack = true;
try {
await client.query('ROLLBACK');
release();
} catch (_error) {
release(_error);
throw _error;
}
}
};
return transaction;
},
/**
* Get pool statistics
*/
getPoolStats(pool) {
return {
total: pool.totalCount,
available: pool.idleCount,
acquired: pool.totalCount - pool.idleCount,
waiting: pool.waitingCount
};
},
/**
* Close connection pool
*/
async closePool(pool) {
await pool.end();
}
};
}
|