import Migration from "swaf/db/Migration"; import FileModel from "../models/FileModel.js"; export default class ReplaceTtlWithExpiresAtFilesTable extends Migration { public async install(): Promise { await this.query(`ALTER TABLE files ADD COLUMN expires_at DATETIME NULL`); const files = await FileModel.select().get(); for (const file of files) { if (file.created_at && typeof file.ttl === 'number' && file.ttl > 0) { file.expires_at = new Date(file.created_at.getTime() + file.ttl * 1000); } const callbacks: (() => Promise)[] = []; await file.save(this.getCurrentConnection(), callback => { callbacks.push(callback); }); for (const c of callbacks) await c(); } await this.query(`ALTER TABLE files DROP COLUMN ttl`); } public async rollback(): Promise { await this.query(`ALTER TABLE files ADD COLUMN ttl INT UNSIGNED NOT NULL DEFAULT 0`); const files = await FileModel.select().get(); for (const file of files) { if (file.created_at && file.expires_at) { file.ttl = Math.ceil((file.expires_at.getTime() - file.created_at.getTime()) / 1000); } const callbacks: (() => Promise)[] = []; await file.save(this.getCurrentConnection(), callback => { callbacks.push(callback); }); for (const c of callbacks) await c(); } await this.query(`ALTER TABLE files DROP COLUMN expires_at`); } }