db.js 836 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. const { Pool } = require('pg');
  2. class Database {
  3. constructor(config) {
  4. this.pool = new Pool(config);
  5. }
  6. async connect() {
  7. this.client = await this.pool.connect();
  8. return this.client;
  9. }
  10. async setSchema(schema) {
  11. if (this.client) {
  12. await this.client.query(`SET search_path TO ${schema}`);
  13. } else {
  14. throw new Error('Client is not connected.');
  15. }
  16. }
  17. async query(text, params) {
  18. if (this.client) {
  19. return this.client.query(text, params);
  20. } else {
  21. throw new Error('Client is not connected.');
  22. }
  23. }
  24. async disconnect() {
  25. if (this.client) {
  26. this.client.release();
  27. this.client = null;
  28. }
  29. }
  30. }
  31. // 导出数据库实例
  32. module.exports = Database;