1234567891011121314151617181920212223242526272829303132333435363738 |
- const { Pool } = require('pg');
- class Database {
- constructor(config) {
- this.pool = new Pool(config);
- }
- async connect() {
- this.client = await this.pool.connect();
- return this.client;
- }
- async setSchema(schema) {
- if (this.client) {
- await this.client.query(`SET search_path TO ${schema}`);
- } else {
- throw new Error('Client is not connected.');
- }
- }
- async query(text, params) {
- if (this.client) {
- return this.client.query(text, params);
- } else {
- throw new Error('Client is not connected.');
- }
- }
- async disconnect() {
- if (this.client) {
- this.client.release();
- this.client = null;
- }
- }
- }
- // 导出数据库实例
- module.exports = Database;
|