const fs = require("node:fs"); const path = require("node:path"); const { Sequelize } = require("sequelize"); const { dataDir } = require("./paths"); const logger = require("./logger"); const storage = adoptLegacyDatabase(path.join(dataDir(), "frislit.db")); /* * A data directory that was served by tunlit still holds tunlit.db. Rename it * instead of starting from an empty database; if the rename fails (read-only * mount, different filesystem), use the old file in place. */ function adoptLegacyDatabase(target) { const legacy = path.join(path.dirname(target), "tunlit.db"); if (fs.existsSync(target) || !fs.existsSync(legacy)) return target; try { fs.renameSync(legacy, target); for (const suffix of ["-wal", "-shm"]) { if (fs.existsSync(legacy + suffix)) fs.renameSync(legacy + suffix, target + suffix); } logger.info(`Adopted the tunlit database as ${path.basename(target)}`); return target; } catch (error) { logger.warn(`Could not rename tunlit.db (${error.message}), using it in place`); return legacy; } } Sequelize.DATE.prototype._stringify = function (date) { return (date instanceof Date ? date : new Date(date)).toISOString(); }; module.exports = new Sequelize({ dialect: "sqlite", storage, logging: message => logger.debug(message), query: { raw: true }, }); module.exports.storagePath = storage;