| 34 | } |
| 35 | |
| 36 | async doUpgrade() { |
| 37 | this.called = true; |
| 38 | for (const channel in this.channels) { |
| 39 | const name = `db.ver${channel === 'hydrooj' ? '' : `-${channel}`}`; |
| 40 | let dbVer = system.get(name) ?? 0; |
| 41 | const scripts = this.channels[channel]; |
| 42 | const isFresh = !dbVer; |
| 43 | const expected = scripts.length; |
| 44 | if (isFresh) { |
| 45 | await scripts[0]?.(this.ctx); |
| 46 | await system.set(name, expected); |
| 47 | continue; |
| 48 | } |
| 49 | let upgraded = false; |
| 50 | if (dbVer > expected) { |
| 51 | logger.warn('Current database version for [%s] is %d, expected %d.', channel, dbVer, expected); |
| 52 | logger.warn('You are likely trying to apply a downgrade.'); |
| 53 | logger.warn('This version of Hydro is not compatible with newer data version.'); |
| 54 | if (!argv.options.ignoreVersion) { |
| 55 | logger.warn('To prevent data corruption, the startup has been aborted.'); |
| 56 | logger.warn('If you want to continue, use --ignore-version on startup.'); |
| 57 | logger.warn('Do it at your own risk.'); |
| 58 | await new Promise(() => { }); |
| 59 | } |
| 60 | } |
| 61 | while (dbVer < expected) { |
| 62 | const func = scripts[dbVer]; |
| 63 | if (typeof func !== 'function') { |
| 64 | dbVer++; |
| 65 | continue; |
| 66 | } |
| 67 | logger.info('Upgrading database [%s]: from %d to %d', channel, dbVer, expected); |
| 68 | if ('dontWait' in func) { |
| 69 | logger.info('[Background Task]'); |
| 70 | // For those scripts we don't really care if they fail |
| 71 | func(this.ctx).then(() => { |
| 72 | logger.info('Background Task Completed [%s]: from %d to %d', channel, func.dontWait, expected); |
| 73 | }).catch(logger.error); |
| 74 | } else { |
| 75 | const result = await func(this.ctx); |
| 76 | if (!result) break; |
| 77 | } |
| 78 | dbVer++; |
| 79 | await system.set(name, dbVer); |
| 80 | upgraded = true; |
| 81 | } |
| 82 | if (upgraded) logger.success('Database upgraded [%s]: current version %d', channel, dbVer); |
| 83 | } |
| 84 | } |
| 85 | } |