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.

59 lines
1.6 KiB

11 months ago
  1. const mysql = require("mysql2/promise");
  2. const UrlPattern = require("url-pattern");
  3. class MySQLConnector {
  4. #connected = false;
  5. database_id = "";
  6. constructor(
  7. config = {
  8. connectionString: null,
  9. }
  10. ) {
  11. this.connectionString = config.connectionString;
  12. this._client = null;
  13. this.database_id = this.#parseDatabase();
  14. }
  15. #parseDatabase() {
  16. const connectionPattern = new UrlPattern("mysql\\://*@*/:database*");
  17. const match = connectionPattern.match(this.connectionString);
  18. return match?.database;
  19. }
  20. async connect() {
  21. this._client = await mysql.createConnection({ uri: this.connectionString });
  22. this.#connected = true;
  23. return this._client;
  24. }
  25. /**
  26. *
  27. * @param {string} queryString the SQL query to be run
  28. * @returns {import(".").QueryResult}
  29. */
  30. async runQuery(queryString = "") {
  31. const result = { rows: [], count: 0, error: null };
  32. try {
  33. if (!this.#connected) await this.connect();
  34. const [query] = await this._client.query(queryString);
  35. result.rows = query;
  36. result.count = query?.length;
  37. } catch (err) {
  38. console.log(this.constructor.name, err);
  39. result.error = err.message;
  40. } finally {
  41. await this._client.end();
  42. this.#connected = false;
  43. }
  44. return result;
  45. }
  46. getTablesSql() {
  47. return `SELECT table_name FROM information_schema.tables WHERE table_schema = '${this.database_id}'`;
  48. }
  49. getTableSchemaSql(table_name) {
  50. return `SHOW COLUMNS FROM ${this.database_id}.${table_name};`;
  51. }
  52. }
  53. module.exports.MySQLConnector = MySQLConnector;