ConnManager.js 1.6 KB

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