connManager.js 1.5 KB

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