ConnManager.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const fs = require('fs-extra');
  2. const SqliteConnectionPool = require('./SqliteConnectionPool');
  3. const log = new (require('../core/AppLogger'))().log;//singleton
  4. const migrations = {
  5. };
  6. let instance = null;
  7. //singleton
  8. class ConnManager {
  9. constructor() {
  10. if (!instance) {
  11. this.inited = false;
  12. instance = this;
  13. }
  14. return instance;
  15. }
  16. async init(config) {
  17. this.config = config;
  18. this._pool = {};
  19. const force = null;//(config.branch == 'development' ? 'last' : null);
  20. for (const poolConfig of this.config.db) {
  21. const dbFileName = this.config.dataDir + '/' + poolConfig.fileName;
  22. //бэкап
  23. if (!poolConfig.noBak && await fs.pathExists(dbFileName))
  24. await fs.copy(dbFileName, `${dbFileName}.bak`);
  25. const connPool = new SqliteConnectionPool();
  26. await connPool.open(poolConfig, dbFileName);
  27. log(`Opened database "${poolConfig.poolName}"`);
  28. //миграции
  29. const migs = migrations[poolConfig.poolName];
  30. if (migs && migs.data.length) {
  31. const applied = await connPool.migrate(migs.data, migs.table, force);
  32. if (applied.length)
  33. log(`${applied.length} migrations applied to "${poolConfig.poolName}"`);
  34. }
  35. this._pool[poolConfig.poolName] = connPool;
  36. }
  37. this.inited = true;
  38. }
  39. get pool() {
  40. return this._pool;
  41. }
  42. }
  43. module.exports = ConnManager;