You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB

11 months ago
  1. const pgSql = require("pg");
  2. class PostgresSQLConnector {
  3. #connected = false;
  4. constructor(
  5. config = {
  6. connectionString: null,
  7. }
  8. ) {
  9. this.connectionString = config.connectionString;
  10. this._client = new pgSql.Client({
  11. connectionString: this.connectionString,
  12. });
  13. }
  14. async connect() {
  15. await this._client.connect();
  16. this.#connected = true;
  17. return this._client;
  18. }
  19. /**
  20. *
  21. * @param {string} queryString the SQL query to be run
  22. * @returns {import(".").QueryResult}
  23. */
  24. async runQuery(queryString = "") {
  25. const result = { rows: [], count: 0, error: null };
  26. try {
  27. if (!this.#connected) await this.connect();
  28. const query = await this._client.query(queryString);
  29. result.rows = query.rows;
  30. result.count = query.rowCount;
  31. } catch (err) {
  32. console.log(this.constructor.name, err);
  33. result.error = err.message;
  34. } finally {
  35. await this._client.end();
  36. this.#connected = false;
  37. }
  38. return result;
  39. }
  40. getTablesSql() {
  41. return `SELECT * FROM pg_catalog.pg_tables WHERE schemaname = 'public'`;
  42. }
  43. getTableSchemaSql(table_name) {
  44. return ` select column_name, data_type, character_maximum_length, column_default, is_nullable from INFORMATION_SCHEMA.COLUMNS where table_name = '${table_name}'`;
  45. }
  46. }
  47. module.exports.PostgresSQLConnector = PostgresSQLConnector;