@devbro/sql-generator
Version:
generic sql generator
74 lines • 2.13 kB
JavaScript
import { Connection as ConnectionAbs } from "../../Connection";
import { Pool } from "pg";
import { Query } from "../../Query";
import { PostgresqlQueryGrammar } from "./PostgresqlQueryGrammar";
import { Schema } from "../../Schema";
import { PostgresqlSchemaGrammar } from "./PostgresqlSchemaGrammar";
import Cursor from "pg-cursor";
class PostgresqlConnection extends ConnectionAbs {
connection;
static pool;
static defaults = {
port: 5432,
ssl: false,
max: 20,
idleTimeoutMillis: 1,
// wait X milli seconds before closing an idle/released connection
connectionTimeoutMillis: 3e4,
// wait up to 30 seconds to obtain a new connection
maxUses: 7500
};
constructor(params) {
super();
if (!PostgresqlConnection.pool) {
PostgresqlConnection.pool = new Pool({ ...PostgresqlConnection.defaults, ...params });
}
}
async connect() {
this.connection = await PostgresqlConnection.pool.connect();
return true;
}
async runQuery(sql) {
const result = await this.connection?.query(sql.sql, sql.bindings);
return result?.rows;
}
async runCursor(sql) {
return this.connection?.query(new Cursor(sql.sql, sql.bindings));
}
async disconnect() {
await this.connection?.release();
return true;
}
getQuery() {
return new Query(this, new PostgresqlQueryGrammar());
}
getSchema() {
return new Schema(this, new PostgresqlSchemaGrammar());
}
async beginTransaction() {
if (!this.connection) {
throw new Error("No active connection to begin a transaction.");
}
await this.connection.query("BEGIN");
}
async commit() {
if (!this.connection) {
throw new Error("No active connection to commit a transaction.");
}
await this.connection.query("COMMIT");
}
async rollback() {
if (!this.connection) {
throw new Error("No active connection to rollback a transaction.");
}
await this.connection.query("ROLLBACK");
}
static async destroy() {
PostgresqlConnection.pool.end();
return;
}
}
export {
PostgresqlConnection
};
//# sourceMappingURL=PostgresqlConnection.mjs.map