diff --git a/src/backend/common/database/appMigrations/001_lifecycleLoc.ts b/src/backend/common/database/appMigrations/001_lifecycleLoc.ts new file mode 100644 index 00000000..a8fa51e7 --- /dev/null +++ b/src/backend/common/database/appMigrations/001_lifecycleLoc.ts @@ -0,0 +1,63 @@ +import type { SqliteDatabase, Migration } from 'sqlite-up'; +import { MigrateBaseContext } from '../appMigrator.js'; +import { plays as drizzlePlays } from '../drizzle/schema/schema.js'; +import clone from 'clone'; +import { eq } from 'drizzle-orm'; + + +export const up: Migration['up'] = async (db: SqliteDatabase, ctx: MigrateBaseContext): Promise => { + + ctx.logger.info('Migrating Play lifecycle data to top-level location. This may take some time...'); + + let more = true; + let offset = 0, + processed = 0, + updated = 0; + while (more) { + const playRows = await ctx.db.select().from(drizzlePlays).limit(100).offset(offset); + for (const row of playRows) { + try { + const { + meta: { + lifecycle, + lifecycle: { + steps = [], + scrobble + } = {} + } = {} + } = row.play; + if (lifecycle === undefined) { + // already migrated or unneeded + processed++; + continue; + } + if (steps.length > 0) { + row.play.lifecycle = clone(steps); + } + if (scrobble !== undefined) { + row.play.scrobble = clone(scrobble); + } + delete row.play.meta.lifecycle; + await ctx.db.update(drizzlePlays).set({ play: row.play }).where(eq(drizzlePlays.id, row.id)); + updated++; + processed++; + } catch (e) { + ctx.logger.warn(new Error(`Failed to migrate Play ${row.id} (${row.uid})`, { cause: e })); + } + } + offset += 100; + ctx.logger.verbose(`Migration Progress: Processed ${processed} | Updated ${updated}`); + if(playRows.length < 100) { + more = false; + } + } + + + // Migration code here + // context is passed as ctx +}; + +export const down: Migration['down'] = async (db: SqliteDatabase, ctx: MigrateBaseContext): Promise => { + // Rollback code here + // context is passed as ctx +}; \ No newline at end of file diff --git a/src/backend/common/database/appMigrator.ts b/src/backend/common/database/appMigrator.ts index e91473f4..f2d63a39 100644 --- a/src/backend/common/database/appMigrator.ts +++ b/src/backend/common/database/appMigrator.ts @@ -40,7 +40,7 @@ export const migrateApp = async (db: DbConcrete, opts: {logger?: Logger, migrati logger: parentLogger = loggerNoop, migrationsAppFolder = path.resolve(projectDir, 'src/backend/common/database/appMigrations') } = opts; - const logger = childLogger(parentLogger, 'App'); + const logger = childLogger(parentLogger, ['App', 'Migrations']); const migrator = new Migrator({ db: db.$client,