Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(database): keep startup resilient to slug backfill failures
Ahmet Ömer42e5a7ff1082
diff --git a/apps/self-hosted/server/utils/db.ts b/apps/self-hosted/server/utils/db.tsindex d6679e3c..0da12695 100644--- a/apps/self-hosted/server/utils/db.ts+++ b/apps/self-hosted/server/utils/db.ts@@ -1,6 +1,7 @@import { existsSync } from 'node:fs'import { resolve } from 'node:path'import { openDatabase } from '@chronoframe/database'+import { logger } from './logger'export { tables } from '@chronoframe/database'export type {User,@@ -17,6 +18,7 @@ export type {export { eq, and, or, inArray } from 'drizzle-orm'let connection: ReturnType<typeof openDatabase> | null = null+const databaseLogger = logger.dynamic('db')/** Share the same configured connection for migrations and application queries. */export function useDB() {@@ -33,8 +35,9 @@ export function useDB() {),verbose:process.env.NODE_ENV === 'development'- ? logger.dynamic('db').verbose+ ? databaseLogger.verbose: undefined,+ logger: databaseLogger,})return connection.db}diff --git a/packages/database/src/connection.ts b/packages/database/src/connection.tsindex 1f8e636d..51f81d84 100644--- a/packages/database/src/connection.ts+++ b/packages/database/src/connection.ts@@ -21,10 +21,16 @@ export type AlbumPhoto = typeof schema.albumPhotos.$inferSelectexport type NewAlbumPhoto = typeof schema.albumPhotos.$inferInsertexport type AlbumWithPhotos = Album & { photos: Photo[] }+export interface DatabaseLogger {+ info(message: string): void+ warn(message: string, error?: unknown): void+}+export interface DatabaseOptions {filename: stringmigrationsFolder?: stringverbose?: (message: string) => void+ logger?: DatabaseLogger}/** Open one explicitly configured SQLite connection; the caller owns its lifetime. */@@ -44,14 +50,25 @@ export function openDatabase(options: DatabaseOptions) {sqlite.pragma('cache_size = 1000')sqlite.pragma('temp_store = MEMORY')const db = drizzle(sqlite, { schema })+ const logger = options.logger ?? {+ info: (message: string) => console.info(message),+ warn: (message: string, error?: unknown) => console.warn(message, error),+ }if (options.migrationsFolder) {migrateDatabase(db, options.migrationsFolder, options.filename)const slugTable = db.get<{ present: number }>(sql`SELECT 1 AS present FROM sqlite_master WHERE type='table' AND name='album_slugs'`,)if (slugTable) {- const count = backfillAlbumSlugs(db)- if (count) console.info(`Backfilled album slugs for ${count} album(s)`)+ try {+ const count = backfillAlbumSlugs(db)+ if (count) logger.info(`Backfilled album slugs for ${count} album(s)`)+ } catch (error) {+ logger.warn(+ 'Album slug backfill failed; albums will fall back to numeric URLs',+ error,+ )+ }} else {const albumTable = db.get<{ present: number }>(sql`SELECT 1 AS present FROM sqlite_master WHERE type='table' AND name='albums'`,diff --git a/tests/database-lifecycle.test.ts b/tests/database-lifecycle.test.tsindex a9e1389b..6a0da545 100644--- a/tests/database-lifecycle.test.ts+++ b/tests/database-lifecycle.test.ts@@ -4,6 +4,7 @@ import assert from 'node:assert/strict'import { mkdtemp, rm } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import Database from 'better-sqlite3'import {openDatabase,tables,@@ -95,3 +96,61 @@ test('database connection, repositories, rollback, backup, restart and reentrantawait rm(root, { recursive: true, force: true })}})++test('startup logs backfill failures and keeps slug-less albums readable', async () => {+ const root = await mkdtemp(join(tmpdir(), 'chronoframe-slug-backfill-'))+ const filename = join(root, 'app.sqlite3')+ const infos: string[] = []+ const warnings: Array<{ message: string; error: unknown }> = []+ const logger = {+ info: (message: string) => infos.push(message),+ warn: (message: string, error?: unknown) =>+ warnings.push({ message, error }),+ }+ try {+ openDatabase({ filename, migrationsFolder }).close()++ const raw = new Database(filename)+ raw.prepare("INSERT INTO albums(title) VALUES('No Slug')").run()+ raw.exec(+ "CREATE TRIGGER fail_album_slug_insert BEFORE INSERT ON album_slugs BEGIN SELECT RAISE(ABORT, 'simulated slug failure'); END;",+ )+ raw.close()++ const failed = openDatabase({ filename, migrationsFolder, logger })+ try {+ assert.equal(warnings.length, 1)+ assert.match(warnings[0]!.message, /backfill failed/i)+ assert.ok(warnings[0]!.error instanceof Error)+ assert.equal(infos.length, 0)+ const albums = await createSqliteResourceRepository(+ failed.db,+ DEFAULT_SITE,+ ).listAlbums()+ assert.equal(albums.length, 1)+ assert.equal(albums[0]!.resource.slug, undefined)+ } finally {+ failed.close()+ }++ const rawAgain = new Database(filename)+ rawAgain.exec('DROP TRIGGER fail_album_slug_insert')+ rawAgain.close()++ const recovered = openDatabase({ filename, migrationsFolder, logger })+ try {+ assert.equal(warnings.length, 1)+ assert.equal(infos.length, 1)+ assert.match(infos[0]!, /Backfilled album slugs for 1 album/)+ const albums = await createSqliteResourceRepository(+ recovered.db,+ DEFAULT_SITE,+ ).listAlbums()+ assert.equal(albums[0]!.resource.slug, 'no-slug')+ } finally {+ recovered.close()+ }+ } finally {+ await rm(root, { recursive: true, force: true })+ }+})