Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

refactor: extract SQLite database package and unify connection lifecycle

HoshinoSuzumiBot8df8ed9a14d1
diff --git a/Dockerfile b/Dockerfile
index 3cec0f87..ff331d6b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -9,6 +9,7 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages/webgl-image/package.json ./packages/webgl-image/
COPY packages/contracts/package.json ./packages/contracts/
COPY packages/core/package.json ./packages/core/
+COPY packages/database/package.json ./packages/database/
COPY packages/storage/package.json ./packages/storage/
COPY packages/media/package.json ./packages/media/
COPY packages/geocoding/package.json ./packages/geocoding/
@@ -47,7 +48,7 @@ COPY --from=runtime_deps /etc/ssl /etc/ssl
COPY --from=runtime_deps --chmod=1777 /opt/runtime-tmp /tmp
COPY --from=build /usr/src/app/.output ./.output
-COPY --from=build /usr/src/app/server/database/migrations ./server/database/migrations
+COPY --from=build /usr/src/app/packages/database/migrations ./server/database/migrations
EXPOSE 3000
VOLUME ["/app/data"]
diff --git a/drizzle.config.ts b/drizzle.config.ts
index 9e1396de..1332498e 100644
--- a/drizzle.config.ts
+++ b/drizzle.config.ts
@@ -2,9 +2,9 @@ import { defineConfig } from 'drizzle-kit'
export default defineConfig({
dialect: 'sqlite',
- schema: './server/database/schema.ts',
- out: './server/database/migrations',
+ schema: './packages/database/src/schema.ts',
+ out: './packages/database/migrations',
dbCredentials: {
- url: 'file:./data/app.sqlite3',
+ url: process.env.DATABASE_URL || './data/app.sqlite3',
},
})
diff --git a/package.json b/package.json
index 4aa3b358..60a55d2e 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,7 @@
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
- "check:packages": "node scripts/check-package-boundaries.mjs && pnpm --filter @chronoframe/core --filter @chronoframe/contracts --filter @chronoframe/storage --filter @chronoframe/media --filter @chronoframe/geocoding type-check",
+ "check:packages": "node scripts/check-package-boundaries.mjs && pnpm --filter @chronoframe/database --filter @chronoframe/core --filter @chronoframe/contracts --filter @chronoframe/storage --filter @chronoframe/media --filter @chronoframe/geocoding type-check",
"test": "node --experimental-strip-types --test tests/*.test.ts"
},
"dependencies": {
@@ -88,7 +88,8 @@
"@chronoframe/media": "workspace:*",
"@chronoframe/geocoding": "workspace:*",
"@chronoframe/core": "workspace:*",
- "h3": "^1.15.11"
+ "h3": "^1.15.11",
+ "@chronoframe/database": "workspace:*"
},
"packageManager": "[email protected]",
"devDependencies": {
diff --git a/packages/contracts/package.json b/packages/contracts/package.json
index 5f268d5b..965635a2 100644
--- a/packages/contracts/package.json
+++ b/packages/contracts/package.json
@@ -10,7 +10,8 @@
"./photo": "./src/photo.ts",
"./location": "./src/location.ts",
"./resources": "./src/resources.ts",
- "./settings": "./src/settings.ts"
+ "./settings": "./src/settings.ts",
+ "./queue": "./src/queue.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
diff --git a/packages/contracts/src/queue.ts b/packages/contracts/src/queue.ts
new file mode 100644
index 00000000..3973a38c
--- /dev/null
+++ b/packages/contracts/src/queue.ts
@@ -0,0 +1,17 @@
+/**
+ * Warning codes attached to completed pipeline queue tasks.
+ *
+ * The values are persisted in `pipeline_queue.warning_code` and returned by
+ * the queue APIs. Keep them stable.
+ */
+
+export const QueueWarningCode = {
+ AlbumMissing: 'album-missing',
+} as const
+
+export type QueueWarningCode =
+ (typeof QueueWarningCode)[keyof typeof QueueWarningCode]
+
+export const QUEUE_WARNING_CODES: [QueueWarningCode, ...QueueWarningCode[]] = [
+ QueueWarningCode.AlbumMissing,
+]
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c09962a1..8fb82707 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -15,7 +15,10 @@ export interface PhotoMembership {
/** Async boundary allows both embedded SQLite and future asynchronous adapters. */
export interface ResourceReadRepository {
- listPhotos(excludedIds?: string[]): Promise<Photo[]>
+ listPhotos(
+ excludedIds?: string[],
+ page?: { limit: number; offset: number },
+ ): Promise<Photo[]>
listAlbums(): Promise<AlbumReadRecord[]>
getAlbum(id: number): Promise<AlbumReadRecord | null>
listAlbumPhotos(id: number): Promise<Photo[]>
diff --git a/packages/database/README.md b/packages/database/README.md
new file mode 100644
index 00000000..d2409ae1
--- /dev/null
+++ b/packages/database/README.md
@@ -0,0 +1,7 @@
+# Database
+
+SQLite schema, migration history, DTO projection and repository implementations for the self-hosted application. The application supplies the database filename, migration directory, logging and close hook. `openDatabase` owns no global singleton and supports consistent online backups.
+
+Core repository methods return promises so callers await persistence; SQLite executes each transaction synchronously and never holds it across asynchronous object I/O. A future PostgreSQL adapter must implement the same atomic repository operations, rather than exposing driver transactions to core. `persistenceErrorCode` maps constraint and contention failures without returning raw SQL messages to clients.
+
+Migrations are canonical here. `server/database/migrations` remains a compatibility symlink for existing commands; production images copy these files to the historical runtime path. Do not edit released migrations. Back up the database and its committed WAL with the SQLite backup API before upgrading. Restore a backup using the matching application version when a migration changes constraints.
diff --git a/server/database/migrations/0000_curvy_scarlet_witch.sql b/packages/database/migrations/0000_curvy_scarlet_witch.sql
similarity index 100%
rename from server/database/migrations/0000_curvy_scarlet_witch.sql
rename to packages/database/migrations/0000_curvy_scarlet_witch.sql
diff --git a/server/database/migrations/0001_narrow_spot.sql b/packages/database/migrations/0001_narrow_spot.sql
similarity index 100%
rename from server/database/migrations/0001_narrow_spot.sql
rename to packages/database/migrations/0001_narrow_spot.sql
diff --git a/server/database/migrations/0002_faulty_tyrannus.sql b/packages/database/migrations/0002_faulty_tyrannus.sql
similarity index 100%
rename from server/database/migrations/0002_faulty_tyrannus.sql
rename to packages/database/migrations/0002_faulty_tyrannus.sql
diff --git a/server/database/migrations/0003_nifty_hellcat.sql b/packages/database/migrations/0003_nifty_hellcat.sql
similarity index 100%
rename from server/database/migrations/0003_nifty_hellcat.sql
rename to packages/database/migrations/0003_nifty_hellcat.sql
diff --git a/server/database/migrations/0004_absent_lockheed.sql b/packages/database/migrations/0004_absent_lockheed.sql
similarity index 100%
rename from server/database/migrations/0004_absent_lockheed.sql
rename to packages/database/migrations/0004_absent_lockheed.sql
diff --git a/server/database/migrations/0005_light_stranger.sql b/packages/database/migrations/0005_light_stranger.sql
similarity index 100%
rename from server/database/migrations/0005_light_stranger.sql
rename to packages/database/migrations/0005_light_stranger.sql
diff --git a/server/database/migrations/0006_flaky_the_enforcers.sql b/packages/database/migrations/0006_flaky_the_enforcers.sql
similarity index 100%
rename from server/database/migrations/0006_flaky_the_enforcers.sql
rename to packages/database/migrations/0006_flaky_the_enforcers.sql
diff --git a/server/database/migrations/0007_uneven_spectrum.sql b/packages/database/migrations/0007_uneven_spectrum.sql
similarity index 100%
rename from server/database/migrations/0007_uneven_spectrum.sql
rename to packages/database/migrations/0007_uneven_spectrum.sql
diff --git a/server/database/migrations/0008_nervous_taskmaster.sql b/packages/database/migrations/0008_nervous_taskmaster.sql
similarity index 100%
rename from server/database/migrations/0008_nervous_taskmaster.sql
rename to packages/database/migrations/0008_nervous_taskmaster.sql
diff --git a/server/database/migrations/0009_careful_ultragirl.sql b/packages/database/migrations/0009_careful_ultragirl.sql
similarity index 100%
rename from server/database/migrations/0009_careful_ultragirl.sql
rename to packages/database/migrations/0009_careful_ultragirl.sql
diff --git a/server/database/migrations/0010_bent_retro_girl.sql b/packages/database/migrations/0010_bent_retro_girl.sql
similarity index 100%
rename from server/database/migrations/0010_bent_retro_girl.sql
rename to packages/database/migrations/0010_bent_retro_girl.sql
diff --git a/server/database/migrations/0011_update_location_language_enum.sql b/packages/database/migrations/0011_update_location_language_enum.sql
similarity index 100%
rename from server/database/migrations/0011_update_location_language_enum.sql
rename to packages/database/migrations/0011_update_location_language_enum.sql
diff --git a/server/database/migrations/0012_medical_raider.sql b/packages/database/migrations/0012_medical_raider.sql
similarity index 100%
rename from server/database/migrations/0012_medical_raider.sql
rename to packages/database/migrations/0012_medical_raider.sql
diff --git a/server/database/migrations/0013_empty_vermin.sql b/packages/database/migrations/0013_empty_vermin.sql
similarity index 100%
rename from server/database/migrations/0013_empty_vermin.sql
rename to packages/database/migrations/0013_empty_vermin.sql
diff --git a/server/database/migrations/0014_photo_access_keys.sql b/packages/database/migrations/0014_photo_access_keys.sql
similarity index 100%
rename from server/database/migrations/0014_photo_access_keys.sql
rename to packages/database/migrations/0014_photo_access_keys.sql
diff --git a/server/database/migrations/0015_smart_titanium_man.sql b/packages/database/migrations/0015_smart_titanium_man.sql
similarity index 100%
rename from server/database/migrations/0015_smart_titanium_man.sql
rename to packages/database/migrations/0015_smart_titanium_man.sql
diff --git a/server/database/migrations/0016_upload_album_membership.sql b/packages/database/migrations/0016_upload_album_membership.sql
similarity index 100%
rename from server/database/migrations/0016_upload_album_membership.sql
rename to packages/database/migrations/0016_upload_album_membership.sql
diff --git a/server/database/migrations/0017_location_components.sql b/packages/database/migrations/0017_location_components.sql
similarity index 100%
rename from server/database/migrations/0017_location_components.sql
rename to packages/database/migrations/0017_location_components.sql
diff --git a/server/database/migrations/meta/0000_snapshot.json b/packages/database/migrations/meta/0000_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0000_snapshot.json
rename to packages/database/migrations/meta/0000_snapshot.json
diff --git a/server/database/migrations/meta/0001_snapshot.json b/packages/database/migrations/meta/0001_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0001_snapshot.json
rename to packages/database/migrations/meta/0001_snapshot.json
diff --git a/server/database/migrations/meta/0002_snapshot.json b/packages/database/migrations/meta/0002_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0002_snapshot.json
rename to packages/database/migrations/meta/0002_snapshot.json
diff --git a/server/database/migrations/meta/0003_snapshot.json b/packages/database/migrations/meta/0003_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0003_snapshot.json
rename to packages/database/migrations/meta/0003_snapshot.json
diff --git a/server/database/migrations/meta/0004_snapshot.json b/packages/database/migrations/meta/0004_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0004_snapshot.json
rename to packages/database/migrations/meta/0004_snapshot.json
diff --git a/server/database/migrations/meta/0005_snapshot.json b/packages/database/migrations/meta/0005_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0005_snapshot.json
rename to packages/database/migrations/meta/0005_snapshot.json
diff --git a/server/database/migrations/meta/0006_snapshot.json b/packages/database/migrations/meta/0006_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0006_snapshot.json
rename to packages/database/migrations/meta/0006_snapshot.json
diff --git a/server/database/migrations/meta/0007_snapshot.json b/packages/database/migrations/meta/0007_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0007_snapshot.json
rename to packages/database/migrations/meta/0007_snapshot.json
diff --git a/server/database/migrations/meta/0008_snapshot.json b/packages/database/migrations/meta/0008_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0008_snapshot.json
rename to packages/database/migrations/meta/0008_snapshot.json
diff --git a/server/database/migrations/meta/0009_snapshot.json b/packages/database/migrations/meta/0009_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0009_snapshot.json
rename to packages/database/migrations/meta/0009_snapshot.json
diff --git a/server/database/migrations/meta/0010_snapshot.json b/packages/database/migrations/meta/0010_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0010_snapshot.json
rename to packages/database/migrations/meta/0010_snapshot.json
diff --git a/server/database/migrations/meta/0012_snapshot.json b/packages/database/migrations/meta/0012_snapshot.json
similarity index 100%
rename from server/database/migrations/meta/0012_snapshot.json
rename to packages/database/migrations/meta/0012_snapshot.json
diff --git a/server/database/migrations/meta/0013_snapshot.json b/packages/database/migrations/meta/0013_snapshot.json
similarity index 95%
rename from server/database/migrations/meta/0013_snapshot.json
rename to packages/database/migrations/meta/0013_snapshot.json
index f79a879f..c0dc634e 100644
--- a/server/database/migrations/meta/0013_snapshot.json
+++ b/packages/database/migrations/meta/0013_snapshot.json
@@ -51,12 +51,8 @@
"name": "album_photos_album_id_albums_id_fk",
"tableFrom": "album_photos",
"tableTo": "albums",
- "columnsFrom": [
- "album_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["album_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -64,12 +60,8 @@
"name": "album_photos_photo_id_photos_id_fk",
"tableFrom": "album_photos",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -155,12 +147,8 @@
"name": "albums_cover_photo_id_photos_id_fk",
"tableFrom": "albums",
"tableTo": "photos",
- "columnsFrom": [
- "cover_photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cover_photo_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -237,12 +225,8 @@
"name": "photo_reactions_photo_id_photos_id_fk",
"tableFrom": "photo_reactions",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -427,9 +411,7 @@
"indexes": {
"photos_id_unique": {
"name": "photos_id_unique",
- "columns": [
- "id"
- ],
+ "columns": ["id"],
"isUnique": true
}
},
@@ -634,10 +616,7 @@
"indexes": {
"idx_namespace_key": {
"name": "idx_namespace_key",
- "columns": [
- "namespace",
- "key"
- ],
+ "columns": ["namespace", "key"],
"isUnique": true
}
},
@@ -646,12 +625,8 @@
"name": "settings_updated_by_users_id_fk",
"tableFrom": "settings",
"tableTo": "users",
- "columnsFrom": [
- "updated_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["updated_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -771,16 +746,12 @@
"indexes": {
"users_name_unique": {
"name": "users_name_unique",
- "columns": [
- "name"
- ],
+ "columns": ["name"],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
- "columns": [
- "email"
- ],
+ "columns": ["email"],
"isUnique": true
}
},
@@ -800,4 +771,4 @@
"internal": {
"indexes": {}
}
-}
\ No newline at end of file
+}
diff --git a/server/database/migrations/meta/0014_snapshot.json b/packages/database/migrations/meta/0014_snapshot.json
similarity index 94%
rename from server/database/migrations/meta/0014_snapshot.json
rename to packages/database/migrations/meta/0014_snapshot.json
index 92b73f82..9573c8bc 100644
--- a/server/database/migrations/meta/0014_snapshot.json
+++ b/packages/database/migrations/meta/0014_snapshot.json
@@ -51,12 +51,8 @@
"name": "album_photos_album_id_albums_id_fk",
"tableFrom": "album_photos",
"tableTo": "albums",
- "columnsFrom": [
- "album_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["album_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -64,12 +60,8 @@
"name": "album_photos_photo_id_photos_id_fk",
"tableFrom": "album_photos",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -155,12 +147,8 @@
"name": "albums_cover_photo_id_photos_id_fk",
"tableFrom": "albums",
"tableTo": "photos",
- "columnsFrom": [
- "cover_photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cover_photo_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -190,9 +178,7 @@
"indexes": {
"idx_photo_access_keys_photo_id": {
"name": "idx_photo_access_keys_photo_id",
- "columns": [
- "photo_id"
- ],
+ "columns": ["photo_id"],
"isUnique": false
}
},
@@ -201,22 +187,15 @@
"name": "photo_access_keys_photo_id_photos_id_fk",
"tableFrom": "photo_access_keys",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"photo_access_keys_access_key_photo_id_pk": {
- "columns": [
- "access_key",
- "photo_id"
- ],
+ "columns": ["access_key", "photo_id"],
"name": "photo_access_keys_access_key_photo_id_pk"
}
},
@@ -291,12 +270,8 @@
"name": "photo_reactions_photo_id_photos_id_fk",
"tableFrom": "photo_reactions",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -481,9 +456,7 @@
"indexes": {
"photos_id_unique": {
"name": "photos_id_unique",
- "columns": [
- "id"
- ],
+ "columns": ["id"],
"isUnique": true
}
},
@@ -688,10 +661,7 @@
"indexes": {
"idx_namespace_key": {
"name": "idx_namespace_key",
- "columns": [
- "namespace",
- "key"
- ],
+ "columns": ["namespace", "key"],
"isUnique": true
}
},
@@ -700,12 +670,8 @@
"name": "settings_updated_by_users_id_fk",
"tableFrom": "settings",
"tableTo": "users",
- "columnsFrom": [
- "updated_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["updated_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -825,16 +791,12 @@
"indexes": {
"users_name_unique": {
"name": "users_name_unique",
- "columns": [
- "name"
- ],
+ "columns": ["name"],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
- "columns": [
- "email"
- ],
+ "columns": ["email"],
"isUnique": true
}
},
@@ -854,4 +816,4 @@
"internal": {
"indexes": {}
}
-}
\ No newline at end of file
+}
diff --git a/server/database/migrations/meta/0015_snapshot.json b/packages/database/migrations/meta/0015_snapshot.json
similarity index 94%
rename from server/database/migrations/meta/0015_snapshot.json
rename to packages/database/migrations/meta/0015_snapshot.json
index 6c139707..237b4e39 100644
--- a/server/database/migrations/meta/0015_snapshot.json
+++ b/packages/database/migrations/meta/0015_snapshot.json
@@ -51,12 +51,8 @@
"name": "album_photos_album_id_albums_id_fk",
"tableFrom": "album_photos",
"tableTo": "albums",
- "columnsFrom": [
- "album_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["album_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -64,12 +60,8 @@
"name": "album_photos_photo_id_photos_id_fk",
"tableFrom": "album_photos",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -155,12 +147,8 @@
"name": "albums_cover_photo_id_photos_id_fk",
"tableFrom": "albums",
"tableTo": "photos",
- "columnsFrom": [
- "cover_photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cover_photo_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -190,9 +178,7 @@
"indexes": {
"idx_photo_access_keys_photo_id": {
"name": "idx_photo_access_keys_photo_id",
- "columns": [
- "photo_id"
- ],
+ "columns": ["photo_id"],
"isUnique": false
}
},
@@ -201,22 +187,15 @@
"name": "photo_access_keys_photo_id_photos_id_fk",
"tableFrom": "photo_access_keys",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"photo_access_keys_access_key_photo_id_pk": {
- "columns": [
- "access_key",
- "photo_id"
- ],
+ "columns": ["access_key", "photo_id"],
"name": "photo_access_keys_access_key_photo_id_pk"
}
},
@@ -291,12 +270,8 @@
"name": "photo_reactions_photo_id_photos_id_fk",
"tableFrom": "photo_reactions",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -481,9 +456,7 @@
"indexes": {
"photos_id_unique": {
"name": "photos_id_unique",
- "columns": [
- "id"
- ],
+ "columns": ["id"],
"isUnique": true
}
},
@@ -583,11 +556,7 @@
"indexes": {
"idx_pipeline_queue_pending": {
"name": "idx_pipeline_queue_pending",
- "columns": [
- "\"priority\" DESC",
- "created_at",
- "id"
- ],
+ "columns": ["\"priority\" DESC", "created_at", "id"],
"isUnique": false,
"where": "\"pipeline_queue\".\"status\" = 'pending'"
}
@@ -707,10 +676,7 @@
"indexes": {
"idx_namespace_key": {
"name": "idx_namespace_key",
- "columns": [
- "namespace",
- "key"
- ],
+ "columns": ["namespace", "key"],
"isUnique": true
}
},
@@ -719,12 +685,8 @@
"name": "settings_updated_by_users_id_fk",
"tableFrom": "settings",
"tableTo": "users",
- "columnsFrom": [
- "updated_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["updated_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -844,16 +806,12 @@
"indexes": {
"users_name_unique": {
"name": "users_name_unique",
- "columns": [
- "name"
- ],
+ "columns": ["name"],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
- "columns": [
- "email"
- ],
+ "columns": ["email"],
"isUnique": true
}
},
diff --git a/server/database/migrations/meta/0016_snapshot.json b/packages/database/migrations/meta/0016_snapshot.json
similarity index 94%
rename from server/database/migrations/meta/0016_snapshot.json
rename to packages/database/migrations/meta/0016_snapshot.json
index 9af6fbc7..8669c0dd 100644
--- a/server/database/migrations/meta/0016_snapshot.json
+++ b/packages/database/migrations/meta/0016_snapshot.json
@@ -48,10 +48,7 @@
"indexes": {
"album_photos_album_photo_unique": {
"name": "album_photos_album_photo_unique",
- "columns": [
- "album_id",
- "photo_id"
- ],
+ "columns": ["album_id", "photo_id"],
"isUnique": true
}
},
@@ -60,12 +57,8 @@
"name": "album_photos_album_id_albums_id_fk",
"tableFrom": "album_photos",
"tableTo": "albums",
- "columnsFrom": [
- "album_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["album_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -73,12 +66,8 @@
"name": "album_photos_photo_id_photos_id_fk",
"tableFrom": "album_photos",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -164,12 +153,8 @@
"name": "albums_cover_photo_id_photos_id_fk",
"tableFrom": "albums",
"tableTo": "photos",
- "columnsFrom": [
- "cover_photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cover_photo_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -199,9 +184,7 @@
"indexes": {
"idx_photo_access_keys_photo_id": {
"name": "idx_photo_access_keys_photo_id",
- "columns": [
- "photo_id"
- ],
+ "columns": ["photo_id"],
"isUnique": false
}
},
@@ -210,22 +193,15 @@
"name": "photo_access_keys_photo_id_photos_id_fk",
"tableFrom": "photo_access_keys",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"photo_access_keys_access_key_photo_id_pk": {
- "columns": [
- "access_key",
- "photo_id"
- ],
+ "columns": ["access_key", "photo_id"],
"name": "photo_access_keys_access_key_photo_id_pk"
}
},
@@ -300,12 +276,8 @@
"name": "photo_reactions_photo_id_photos_id_fk",
"tableFrom": "photo_reactions",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -490,9 +462,7 @@
"indexes": {
"photos_id_unique": {
"name": "photos_id_unique",
- "columns": [
- "id"
- ],
+ "columns": ["id"],
"isUnique": true
}
},
@@ -599,11 +569,7 @@
"indexes": {
"idx_pipeline_queue_pending": {
"name": "idx_pipeline_queue_pending",
- "columns": [
- "\"priority\" DESC",
- "created_at",
- "id"
- ],
+ "columns": ["\"priority\" DESC", "created_at", "id"],
"isUnique": false,
"where": "\"pipeline_queue\".\"status\" = 'pending'"
}
@@ -723,10 +689,7 @@
"indexes": {
"idx_namespace_key": {
"name": "idx_namespace_key",
- "columns": [
- "namespace",
- "key"
- ],
+ "columns": ["namespace", "key"],
"isUnique": true
}
},
@@ -735,12 +698,8 @@
"name": "settings_updated_by_users_id_fk",
"tableFrom": "settings",
"tableTo": "users",
- "columnsFrom": [
- "updated_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["updated_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -860,16 +819,12 @@
"indexes": {
"users_name_unique": {
"name": "users_name_unique",
- "columns": [
- "name"
- ],
+ "columns": ["name"],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
- "columns": [
- "email"
- ],
+ "columns": ["email"],
"isUnique": true
}
},
@@ -897,4 +852,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/server/database/migrations/meta/0017_snapshot.json b/packages/database/migrations/meta/0017_snapshot.json
similarity index 94%
rename from server/database/migrations/meta/0017_snapshot.json
rename to packages/database/migrations/meta/0017_snapshot.json
index 1b5591d0..0d963ae0 100644
--- a/server/database/migrations/meta/0017_snapshot.json
+++ b/packages/database/migrations/meta/0017_snapshot.json
@@ -48,10 +48,7 @@
"indexes": {
"album_photos_album_photo_unique": {
"name": "album_photos_album_photo_unique",
- "columns": [
- "album_id",
- "photo_id"
- ],
+ "columns": ["album_id", "photo_id"],
"isUnique": true
}
},
@@ -60,12 +57,8 @@
"name": "album_photos_album_id_albums_id_fk",
"tableFrom": "album_photos",
"tableTo": "albums",
- "columnsFrom": [
- "album_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["album_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
},
@@ -73,12 +66,8 @@
"name": "album_photos_photo_id_photos_id_fk",
"tableFrom": "album_photos",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -164,12 +153,8 @@
"name": "albums_cover_photo_id_photos_id_fk",
"tableFrom": "albums",
"tableTo": "photos",
- "columnsFrom": [
- "cover_photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["cover_photo_id"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -199,9 +184,7 @@
"indexes": {
"idx_photo_access_keys_photo_id": {
"name": "idx_photo_access_keys_photo_id",
- "columns": [
- "photo_id"
- ],
+ "columns": ["photo_id"],
"isUnique": false
}
},
@@ -210,22 +193,15 @@
"name": "photo_access_keys_photo_id_photos_id_fk",
"tableFrom": "photo_access_keys",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"photo_access_keys_access_key_photo_id_pk": {
- "columns": [
- "access_key",
- "photo_id"
- ],
+ "columns": ["access_key", "photo_id"],
"name": "photo_access_keys_access_key_photo_id_pk"
}
},
@@ -300,12 +276,8 @@
"name": "photo_reactions_photo_id_photos_id_fk",
"tableFrom": "photo_reactions",
"tableTo": "photos",
- "columnsFrom": [
- "photo_id"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["photo_id"],
+ "columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
@@ -497,9 +469,7 @@
"indexes": {
"photos_id_unique": {
"name": "photos_id_unique",
- "columns": [
- "id"
- ],
+ "columns": ["id"],
"isUnique": true
}
},
@@ -606,11 +576,7 @@
"indexes": {
"idx_pipeline_queue_pending": {
"name": "idx_pipeline_queue_pending",
- "columns": [
- "\"priority\" DESC",
- "created_at",
- "id"
- ],
+ "columns": ["\"priority\" DESC", "created_at", "id"],
"isUnique": false,
"where": "\"pipeline_queue\".\"status\" = 'pending'"
}
@@ -730,10 +696,7 @@
"indexes": {
"idx_namespace_key": {
"name": "idx_namespace_key",
- "columns": [
- "namespace",
- "key"
- ],
+ "columns": ["namespace", "key"],
"isUnique": true
}
},
@@ -742,12 +705,8 @@
"name": "settings_updated_by_users_id_fk",
"tableFrom": "settings",
"tableTo": "users",
- "columnsFrom": [
- "updated_by"
- ],
- "columnsTo": [
- "id"
- ],
+ "columnsFrom": ["updated_by"],
+ "columnsTo": ["id"],
"onDelete": "set null",
"onUpdate": "no action"
}
@@ -867,16 +826,12 @@
"indexes": {
"users_name_unique": {
"name": "users_name_unique",
- "columns": [
- "name"
- ],
+ "columns": ["name"],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
- "columns": [
- "email"
- ],
+ "columns": ["email"],
"isUnique": true
}
},
@@ -904,4 +859,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/server/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
similarity index 99%
rename from server/database/migrations/meta/_journal.json
rename to packages/database/migrations/meta/_journal.json
index ed7c4de2..36979a8d 100644
--- a/server/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -129,4 +129,4 @@
"breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/packages/database/package.json b/packages/database/package.json
new file mode 100644
index 00000000..e05f9d36
--- /dev/null
+++ b/packages/database/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@chronoframe/database",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./schema": "./src/schema.ts",
+ "./repositories": "./src/repositories.ts",
+ "./dto": "./src/dto.ts"
+ },
+ "scripts": {
+ "type-check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@chronoframe/contracts": "workspace:*",
+ "@chronoframe/core": "workspace:*",
+ "better-sqlite3": "^12.11.1",
+ "drizzle-orm": "^0.45.4"
+ },
+ "devDependencies": {
+ "@types/better-sqlite3": "^9.6.0",
+ "typescript": "^5.9.3",
+ "@types/node": "^22.20.5"
+ }
+}
diff --git a/packages/database/src/connection.ts b/packages/database/src/connection.ts
new file mode 100644
index 00000000..262fc344
--- /dev/null
+++ b/packages/database/src/connection.ts
@@ -0,0 +1,72 @@
+import { mkdirSync } from 'node:fs'
+import { dirname } from 'node:path'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import * as schema from './schema.ts'
+
+export const tables = schema
+export type AppDatabase = ReturnType<typeof drizzle<typeof schema>>
+export type User = typeof schema.users.$inferSelect
+export type Photo = typeof schema.photos.$inferSelect
+export type PipelineQueueItem = typeof schema.pipelineQueue.$inferSelect
+export type NewPipelineQueueItem = typeof schema.pipelineQueue.$inferInsert
+export type PhotoReaction = typeof schema.photoReactions.$inferSelect
+export type Album = typeof schema.albums.$inferSelect
+export type NewAlbum = typeof schema.albums.$inferInsert
+export type AlbumPhoto = typeof schema.albumPhotos.$inferSelect
+export type NewAlbumPhoto = typeof schema.albumPhotos.$inferInsert
+export type AlbumWithPhotos = Album & { photos: Photo[] }
+
+export interface DatabaseOptions {
+ filename: string
+ migrationsFolder?: string
+ verbose?: (message: string) => void
+}
+
+/** Open one explicitly configured SQLite connection; the caller owns its lifetime. */
+export function openDatabase(options: DatabaseOptions) {
+ if (options.filename !== ':memory:')
+ mkdirSync(dirname(options.filename), { recursive: true })
+ const sqlite = new Database(options.filename, {
+ verbose: options.verbose
+ ? (message) => options.verbose!(String(message))
+ : undefined,
+ })
+ try {
+ sqlite.pragma('journal_mode = WAL')
+ sqlite.pragma('foreign_keys = ON')
+ sqlite.pragma('busy_timeout = 5000')
+ sqlite.pragma('synchronous = NORMAL')
+ sqlite.pragma('cache_size = 1000')
+ sqlite.pragma('temp_store = MEMORY')
+ const db = drizzle(sqlite, { schema })
+ if (options.migrationsFolder)
+ migrate(db, { migrationsFolder: options.migrationsFolder })
+ return {
+ db,
+ /** SQLite backup includes committed WAL data and does not mutate the source. */
+ backup: (filename: string) => sqlite.backup(filename),
+ close: () => {
+ if (sqlite.open) sqlite.close()
+ },
+ }
+ } catch (error) {
+ sqlite.close()
+ throw error
+ }
+}
+
+/** Stable persistence categories without exposing driver messages to clients. */
+export function persistenceErrorCode(error: unknown) {
+ const code = (error as { code?: string } | null)?.code ?? ''
+ if (
+ code.startsWith('SQLITE_CONSTRAINT_UNIQUE') ||
+ code === 'SQLITE_CONSTRAINT_PRIMARYKEY'
+ )
+ return 'conflict'
+ if (code.startsWith('SQLITE_CONSTRAINT')) return 'invalid-relation'
+ if (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED'))
+ return 'retryable'
+ return 'internal'
+}
diff --git a/packages/database/src/dto.ts b/packages/database/src/dto.ts
new file mode 100644
index 00000000..89a5bd2a
--- /dev/null
+++ b/packages/database/src/dto.ts
@@ -0,0 +1,82 @@
+import type {
+ Photo,
+ Album,
+ UserSummary,
+} from '@chronoframe/contracts/resources'
+import type {
+ Photo as PhotoRow,
+ Album as AlbumRow,
+ User as UserRow,
+} from './connection.ts'
+
+/** Expose only the declared photo contract fields, excluding internal database columns. */
+export function toPhotoDto(photo: PhotoRow): Photo {
+ return {
+ id: photo.id,
+ title: photo.title,
+ description: photo.description,
+ width: photo.width,
+ height: photo.height,
+ aspectRatio: photo.aspectRatio,
+ dateTaken: photo.dateTaken,
+ storageKey: photo.storageKey,
+ thumbnailKey: photo.thumbnailKey,
+ fileSize: photo.fileSize,
+ lastModified: photo.lastModified,
+ originalUrl: photo.originalUrl,
+ thumbnailUrl: photo.thumbnailUrl,
+ thumbnailHash: photo.thumbnailHash,
+ tags: photo.tags,
+ exif: photo.exif,
+ latitude: photo.latitude,
+ longitude: photo.longitude,
+ country: photo.country,
+ city: photo.city,
+ locationName: photo.locationName,
+ geocoding: photo.geocoding,
+ isLivePhoto: photo.isLivePhoto,
+ livePhotoVideoUrl: photo.livePhotoVideoUrl,
+ livePhotoVideoKey: photo.livePhotoVideoKey,
+ }
+}
+
+/** Serialize album dates and expose password presence without its hash. */
+export function toAlbumDto(album: AlbumRow): Album {
+ return {
+ id: album.id,
+ title: album.title,
+ description: album.description,
+ coverPhotoId: album.coverPhotoId,
+ isHidden: album.isHidden,
+ position: album.position,
+ createdAt: album.createdAt.toISOString(),
+ updatedAt: album.updatedAt.toISOString(),
+ hasPassword: Boolean(album.passwordHash),
+ }
+}
+
+/** Build a session-safe user summary without password material. */
+export function toUserSummary(user: UserRow): UserSummary {
+ return {
+ id: user.id,
+ username: user.username,
+ email: user.email,
+ avatar: user.avatar,
+ createdAt: user.createdAt.toISOString(),
+ isAdmin: user.isAdmin,
+ }
+}
+
+/** Serialize an administrator-only provider response; configuration may contain secrets. */
+export function toStorageProviderDto(
+ provider: typeof import('./schema.ts').settings_storage_providers.$inferSelect,
+): import('@chronoframe/contracts/settings').SettingStorageProvider {
+ return {
+ id: provider.id,
+ name: provider.name,
+ provider: provider.provider,
+ config: provider.config,
+ createdAt: provider.createdAt.toISOString(),
+ updatedAt: provider.updatedAt.toISOString(),
+ }
+}
diff --git a/packages/database/src/index.ts b/packages/database/src/index.ts
new file mode 100644
index 00000000..e9ad633b
--- /dev/null
+++ b/packages/database/src/index.ts
@@ -0,0 +1,2 @@
+export * from './connection.ts'
+export * from './repositories.ts'
diff --git a/packages/database/src/repositories.ts b/packages/database/src/repositories.ts
new file mode 100644
index 00000000..a7b03dd6
--- /dev/null
+++ b/packages/database/src/repositories.ts
@@ -0,0 +1,3 @@
+export * from './sqlite-resources.ts'
+export * from './sqlite-mutations.ts'
+export * from './sqlite-uploads.ts'
diff --git a/packages/database/src/schema.ts b/packages/database/src/schema.ts
new file mode 100644
index 00000000..e89c81e7
--- /dev/null
+++ b/packages/database/src/schema.ts
@@ -0,0 +1,262 @@
+import type { NormalizedLocation } from '@chronoframe/contracts/location'
+import { sql } from 'drizzle-orm'
+import {
+ index,
+ integer,
+ primaryKey,
+ real,
+ sqliteTable,
+ text,
+ uniqueIndex,
+} from 'drizzle-orm/sqlite-core'
+import { QUEUE_WARNING_CODES } from '@chronoframe/contracts/queue'
+import type { NeededExif } from '@chronoframe/contracts/photo'
+import type { StorageConfig } from '@chronoframe/contracts/storage'
+
+type PipelineQueuePayload =
+ | { type: 'location-migration' }
+ | {
+ type: 'photo'
+ storageKey: string
+ eraseLocation?: boolean
+ albumId?: number
+ }
+ | {
+ type: 'live-photo-video'
+ storageKey: string
+ }
+ | {
+ type: 'photo-reverse-geocoding'
+ migrationOnly?: boolean
+ photoId: string
+ latitude?: number | null
+ longitude?: number | null
+ }
+ | {
+ type: 'photo-erase-location'
+ photoId: string
+ }
+
+export const users = sqliteTable('users', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ username: text('name').notNull().unique(),
+ email: text('email').notNull().unique(),
+ password: text('password'),
+ avatar: text('avatar'),
+ createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
+ isAdmin: integer('is_admin').default(0).notNull(),
+})
+
+export const photos = sqliteTable('photos', {
+ id: text('id').primaryKey().unique(),
+ title: text('title'),
+ description: text('description'),
+ width: integer('width'),
+ height: integer('height'),
+ aspectRatio: real('aspect_ratio'),
+ dateTaken: text('date_taken'),
+ storageKey: text('storage_key'),
+ thumbnailKey: text('thumbnail_key'),
+ fileSize: integer('file_size'),
+ lastModified: text('last_modified'),
+ originalUrl: text('original_url'),
+ thumbnailUrl: text('thumbnail_url'),
+ thumbnailHash: text('thumbnail_hash'),
+ tags: text('tags', { mode: 'json' }).$type<string[]>(),
+ exif: text('exif', { mode: 'json' }).$type<NeededExif>(),
+ // 地理位置信息
+ latitude: real('latitude'),
+ longitude: real('longitude'),
+ country: text('country'),
+ city: text('city'),
+ locationName: text('location_name'),
+ geocoding: text('geocoding', { mode: 'json' }).$type<NormalizedLocation>(),
+ // LivePhoto 相关字段
+ isLivePhoto: integer('is_live_photo').default(0).notNull(),
+ livePhotoVideoUrl: text('live_photo_video_url'),
+ livePhotoVideoKey: text('live_photo_video_key'),
+})
+
+// One row per string an image request may use to identify a photo: the photo
+// id, each storage key, each public URL, and the tidied form of those paths.
+// Photos insert/update/delete triggers (migration 0014) keep the rows in sync.
+// Album checks look up this indexed key instead of reading every photos row.
+export const photoAccessKeys = sqliteTable(
+ 'photo_access_keys',
+ {
+ accessKey: text('access_key').notNull(),
+ photoId: text('photo_id')
+ .notNull()
+ .references(() => photos.id, { onDelete: 'cascade' }),
+ },
+ (t) => [
+ primaryKey({ columns: [t.accessKey, t.photoId] }),
+ index('idx_photo_access_keys_photo_id').on(t.photoId),
+ ],
+)
+
+export const pipelineQueue = sqliteTable(
+ 'pipeline_queue',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ payload: text('payload', { mode: 'json' })
+ .$type<PipelineQueuePayload>()
+ .notNull()
+ .default({
+ type: 'photo',
+ storageKey: '',
+ } satisfies PipelineQueuePayload),
+ priority: integer('priority').default(0).notNull(),
+ availableAt: integer('available_at', { mode: 'timestamp_ms' })
+ .notNull()
+ .default(sql`0`),
+ attempts: integer('attempts').default(0).notNull(),
+ maxAttempts: integer('max_attempts').default(3).notNull(),
+ status: text('status', {
+ enum: [
+ 'pending', // Waiting to be processed
+ 'in-stages', // Currently being processed
+ 'completed', // Successfully processed
+ 'failed', // Processing failed
+ ],
+ })
+ .notNull()
+ .default('pending'),
+ statusStage: text('status_stage', {
+ enum: [
+ 'preprocessing',
+ 'metadata',
+ 'thumbnail',
+ 'exif',
+ 'motion-photo',
+ 'reverse-geocoding',
+ 'live-photo',
+ 'location-erase',
+ ],
+ }),
+ errorMessage: text('error_message'),
+ warningCode: text('warning_code', { enum: QUEUE_WARNING_CODES }),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ completedAt: integer('completed_at', { mode: 'timestamp' }),
+ },
+ (t) => [
+ index('idx_pipeline_queue_pending')
+ .on(sql`${t.priority} DESC`, t.createdAt, t.id)
+ .where(sql`${t.status} = 'pending'`),
+ ],
+)
+
+// 照片表态表
+export const photoReactions = sqliteTable('photo_reactions', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ photoId: text('photo_id')
+ .notNull()
+ .references(() => photos.id, { onDelete: 'cascade' }),
+ reactionType: text('reaction_type', {
+ enum: ['like', 'love', 'amazing', 'funny', 'wow', 'sad', 'fire', 'sparkle'],
+ }).notNull(),
+ // 使用指纹而不是 IP 地址,更准确且支持匿名用户
+ fingerprint: text('fingerprint').notNull(),
+ ipAddress: text('ip_address'),
+ userAgent: text('user_agent'),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+})
+
+// 相簿表
+export const albums = sqliteTable('albums', {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ title: text('title').notNull(),
+ description: text('description'),
+ coverPhotoId: text('cover_photo_id').references(() => photos.id, {
+ onDelete: 'set null',
+ }),
+ isHidden: integer('is_hidden', { mode: 'boolean' }).default(false).notNull(),
+ passwordHash: text('password_hash'),
+ // Album sort position (ascending; smaller value appears first)
+ position: real('position').notNull().default(0),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+})
+
+// 相簿-照片 多对多关系表
+export const albumPhotos = sqliteTable(
+ 'album_photos',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ albumId: integer('album_id')
+ .notNull()
+ .references(() => albums.id, { onDelete: 'cascade' }),
+ photoId: text('photo_id')
+ .notNull()
+ .references(() => photos.id, { onDelete: 'cascade' }),
+ position: real('position').notNull().default(1000000),
+ addedAt: integer('added_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+ (t) => [
+ uniqueIndex('album_photos_album_photo_unique').on(t.albumId, t.photoId),
+ ],
+)
+
+export const settings = sqliteTable(
+ 'settings',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ namespace: text('namespace').notNull().default('common'),
+ key: text('key').notNull(),
+ type: text('type', {
+ enum: ['string', 'number', 'boolean', 'json'],
+ }).notNull(),
+ value: text('value'),
+ defaultValue: text('default_value'),
+ label: text('label'),
+ description: text('description'),
+ isPublic: integer('is_public', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ isReadonly: integer('is_readonly', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ isSecret: integer('is_secret', { mode: 'boolean' })
+ .default(false)
+ .notNull(),
+ enum: text('enum', { mode: 'json' }).$type<string[] | null>(),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedBy: integer('updated_by').references(() => users.id, {
+ onDelete: 'set null',
+ }),
+ },
+ (t) => [uniqueIndex('idx_namespace_key').on(t.namespace, t.key)],
+)
+
+export const settings_storage_providers = sqliteTable(
+ 'settings_storage_providers',
+ {
+ id: integer('id').primaryKey({ autoIncrement: true }),
+ name: text('name').notNull(),
+ provider: text('provider', {
+ enum: ['s3', 'local', 'openlist'],
+ }).notNull(),
+ config: text('config', { mode: 'json' }).$type<StorageConfig>().notNull(),
+ createdAt: integer('created_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ updatedAt: integer('updated_at', { mode: 'timestamp' })
+ .notNull()
+ .default(sql`(unixepoch())`),
+ },
+)
diff --git a/packages/database/src/sqlite-mutations.ts b/packages/database/src/sqlite-mutations.ts
new file mode 100644
index 00000000..64927bb4
--- /dev/null
+++ b/packages/database/src/sqlite-mutations.ts
@@ -0,0 +1,166 @@
+import { and, eq, min } from 'drizzle-orm'
+import type {
+ AlbumWriteRepository,
+ PhotoWriteRepository,
+} from '@chronoframe/core'
+import { tables, type AppDatabase } from './connection.ts'
+import { toAlbumDto, toPhotoDto } from './dto.ts'
+
+/** Keep album row and membership changes inside synchronous SQLite transactions. */
+export function createSqliteAlbumWriteRepository(
+ db: AppDatabase,
+): AlbumWriteRepository {
+ return {
+ async exists(id) {
+ return Boolean(
+ db
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get(),
+ )
+ },
+ async createFirst(data, photoIds) {
+ return db.transaction((tx) => {
+ const row = tx
+ .select({ min: min(tables.albums.position) })
+ .from(tables.albums)
+ .get()
+ const album = tx
+ .insert(tables.albums)
+ .values({ ...data, position: (row?.min ?? 1000) - 1000 })
+ .returning()
+ .get()
+ photoIds.forEach((photoId, index) =>
+ tx
+ .insert(tables.albumPhotos)
+ .values({
+ albumId: album.id,
+ photoId,
+ position: 1000000 + (index + 1) * 10,
+ })
+ .onConflictDoNothing()
+ .run(),
+ )
+ return toAlbumDto(album)
+ })
+ },
+ async update(id, data, photoIds) {
+ return db.transaction((tx) => {
+ const exists = tx
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()
+ if (!exists) return null
+ tx.update(tables.albums).set(data).where(eq(tables.albums.id, id)).run()
+ if (photoIds !== undefined) {
+ tx.delete(tables.albumPhotos)
+ .where(eq(tables.albumPhotos.albumId, id))
+ .run()
+ photoIds.forEach((photoId, index) =>
+ tx
+ .insert(tables.albumPhotos)
+ .values({
+ albumId: id,
+ photoId,
+ position: 1000000 + (index + 1) * 10,
+ })
+ .onConflictDoNothing()
+ .run(),
+ )
+ }
+ return toAlbumDto(
+ tx
+ .select()
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()!,
+ )
+ })
+ },
+ async delete(id) {
+ return db.transaction((tx) => {
+ if (
+ !tx
+ .select({ id: tables.albums.id })
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()
+ )
+ return false
+ tx.delete(tables.albumPhotos)
+ .where(eq(tables.albumPhotos.albumId, id))
+ .run()
+ tx.delete(tables.albums).where(eq(tables.albums.id, id)).run()
+ return true
+ })
+ },
+ async reorder(ids) {
+ db.transaction((tx) => {
+ ids.forEach((id, index) =>
+ tx
+ .update(tables.albums)
+ .set({ position: index * 1000 })
+ .where(eq(tables.albums.id, id))
+ .run(),
+ )
+ })
+ },
+ async removePhoto(id, photoId, updatedAt) {
+ return db.transaction((tx) => {
+ const predicate = and(
+ eq(tables.albumPhotos.albumId, id),
+ eq(tables.albumPhotos.photoId, photoId),
+ )
+ if (
+ !tx
+ .select({ id: tables.albumPhotos.id })
+ .from(tables.albumPhotos)
+ .where(predicate)
+ .get()
+ )
+ return false
+ tx.delete(tables.albumPhotos).where(predicate).run()
+ tx.update(tables.albums)
+ .set({ coverPhotoId: null, updatedAt })
+ .where(
+ and(
+ eq(tables.albums.id, id),
+ eq(tables.albums.coverPhotoId, photoId),
+ ),
+ )
+ .run()
+ return true
+ })
+ },
+ }
+}
+
+/** Map photo writes at the existing connection boundary without changing its lifecycle. */
+export function createSqlitePhotoWriteRepository(
+ db: AppDatabase,
+): PhotoWriteRepository {
+ return {
+ async get(id) {
+ const photo = db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get()
+ return photo ? toPhotoDto(photo) : null
+ },
+ async update(id, update) {
+ db.update(tables.photos).set(update).where(eq(tables.photos.id, id)).run()
+ const photo = db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get()
+ return photo ? toPhotoDto(photo) : null
+ },
+ async delete(id) {
+ db.delete(tables.photos).where(eq(tables.photos.id, id)).run()
+ },
+ }
+}
diff --git a/packages/database/src/sqlite-resources.ts b/packages/database/src/sqlite-resources.ts
new file mode 100644
index 00000000..17e6dc36
--- /dev/null
+++ b/packages/database/src/sqlite-resources.ts
@@ -0,0 +1,96 @@
+import { asc, desc, eq, getTableColumns, notInArray } from 'drizzle-orm'
+import type { ResourceReadRepository } from '@chronoframe/core'
+import { tables, type AppDatabase } from './connection.ts'
+import { toAlbumDto, toPhotoDto } from './dto.ts'
+
+/** Adapt existing SQLite queries without changing connections, schema or lifecycle. */
+export function createSqliteResourceRepository(
+ db: AppDatabase,
+): ResourceReadRepository {
+ const albumRecord = (row: typeof tables.albums.$inferSelect) => ({
+ resource: toAlbumDto(row),
+ passwordHash: row.passwordHash,
+ })
+ return {
+ async listPhotos(excludedIds = [], page) {
+ if (
+ page &&
+ (!Number.isSafeInteger(page.limit) ||
+ page.limit < 1 ||
+ !Number.isSafeInteger(page.offset) ||
+ page.offset < 0)
+ )
+ throw new RangeError('Invalid pagination')
+ return db
+ .select()
+ .from(tables.photos)
+ .where(
+ excludedIds.length
+ ? notInArray(tables.photos.id, excludedIds)
+ : undefined,
+ )
+ .orderBy(desc(tables.photos.dateTaken), asc(tables.photos.id))
+ .limit(page?.limit ?? -1)
+ .offset(page?.offset ?? 0)
+ .all()
+ .map(toPhotoDto)
+ },
+ async listAlbums() {
+ return db
+ .select()
+ .from(tables.albums)
+ .orderBy(asc(tables.albums.position), desc(tables.albums.createdAt))
+ .all()
+ .map(albumRecord)
+ },
+ async getAlbum(id) {
+ const row = db
+ .select()
+ .from(tables.albums)
+ .where(eq(tables.albums.id, id))
+ .get()
+ return row ? albumRecord(row) : null
+ },
+ async listAlbumPhotoIds(id) {
+ return db
+ .select({ id: tables.albumPhotos.photoId })
+ .from(tables.albumPhotos)
+ .where(eq(tables.albumPhotos.albumId, id))
+ .orderBy(asc(tables.albumPhotos.position))
+ .all()
+ .map((row) => row.id)
+ },
+ async listAlbumPhotos(id) {
+ return db
+ .select(getTableColumns(tables.photos))
+ .from(tables.photos)
+ .innerJoin(
+ tables.albumPhotos,
+ eq(tables.photos.id, tables.albumPhotos.photoId),
+ )
+ .where(eq(tables.albumPhotos.albumId, id))
+ .orderBy(asc(tables.albumPhotos.position))
+ .all()
+ .map(toPhotoDto)
+ },
+ async listMemberships() {
+ return db
+ .select({
+ photoId: tables.albumPhotos.photoId,
+ albumId: tables.albums.id,
+ hidden: tables.albums.isHidden,
+ passwordHash: tables.albums.passwordHash,
+ })
+ .from(tables.albumPhotos)
+ .innerJoin(
+ tables.albums,
+ eq(tables.albumPhotos.albumId, tables.albums.id),
+ )
+ .all()
+ .map(({ passwordHash, ...membership }) => ({
+ ...membership,
+ protected: passwordHash !== null,
+ }))
+ },
+ }
+}
diff --git a/packages/database/src/sqlite-uploads.ts b/packages/database/src/sqlite-uploads.ts
new file mode 100644
index 00000000..3cde4730
--- /dev/null
+++ b/packages/database/src/sqlite-uploads.ts
@@ -0,0 +1,45 @@
+import { eq } from 'drizzle-orm'
+import type { DuplicatePhoto } from '@chronoframe/core'
+import type { Photo } from '@chronoframe/contracts/resources'
+import { tables, type AppDatabase } from './connection.ts'
+
+/** Project only fields used by authenticated duplicate checks. */
+export function createSqliteUploadRepository(db: AppDatabase) {
+ const summary = {
+ id: tables.photos.id,
+ title: tables.photos.title,
+ storageKey: tables.photos.storageKey,
+ originalUrl: tables.photos.originalUrl,
+ thumbnailUrl: tables.photos.thumbnailUrl,
+ dateTaken: tables.photos.dateTaken,
+ }
+ return {
+ async findDuplicate(id: string): Promise<DuplicatePhoto | null> {
+ return (
+ db
+ .select(summary)
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get() || null
+ )
+ },
+ async findDetails(
+ id: string,
+ ): Promise<
+ (DuplicatePhoto & Pick<Photo, 'fileSize' | 'width' | 'height'>) | null
+ > {
+ return (
+ db
+ .select({
+ ...summary,
+ fileSize: tables.photos.fileSize,
+ width: tables.photos.width,
+ height: tables.photos.height,
+ })
+ .from(tables.photos)
+ .where(eq(tables.photos.id, id))
+ .get() || null
+ )
+ },
+ }
+}
diff --git a/packages/database/tsconfig.json b/packages/database/tsconfig.json
new file mode 100644
index 00000000..e79cde15
--- /dev/null
+++ b/packages/database/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "strict": true,
+ "noEmit": true,
+ "allowImportingTsExtensions": true,
+ "types": ["node"],
+ "lib": ["ES2022", "DOM"],
+ "skipLibCheck": true,
+ "noUncheckedIndexedAccess": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 71243ec3..abfb162e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
'@chronoframe/core':
specifier: workspace:*
version: link:packages/core
+ '@chronoframe/database':
+ specifier: workspace:*
+ version: link:packages/database
'@chronoframe/geocoding':
specifier: workspace:*
version: link:packages/geocoding
@@ -261,6 +264,31 @@ importers:
specifier: ^5.9.3
version: 5.9.3
+ packages/database:
+ dependencies:
+ '@chronoframe/contracts':
+ specifier: workspace:*
+ version: link:../contracts
+ '@chronoframe/core':
+ specifier: workspace:*
+ version: link:../core
+ better-sqlite3:
+ specifier: ^12.11.1
+ version: 12.11.1
+ drizzle-orm:
+ specifier: ^0.45.4
+ version: 0.45.4(@cloudflare/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])
+ devDependencies:
+ '@types/node':
+ specifier: ^22.20.5
+ version: 22.20.5
+ '@types/better-sqlite3':
+ specifier: ^9.6.0
+ version: 9.6.0
+ typescript:
+ specifier: ^5.9.3
+ version: 5.9.3
+
packages/geocoding:
dependencies:
'@chronoframe/contracts':
diff --git a/scripts/check-package-boundaries.mjs b/scripts/check-package-boundaries.mjs
index 2419d26b..6ffa79e0 100644
--- a/scripts/check-package-boundaries.mjs
+++ b/scripts/check-package-boundaries.mjs
@@ -3,7 +3,14 @@ import path from 'node:path'
import { builtinModules } from 'node:module'
import ts from 'typescript'
-const packageNames = ['contracts', 'core', 'storage', 'media', 'geocoding']
+const packageNames = [
+ 'contracts',
+ 'core',
+ 'database',
+ 'storage',
+ 'media',
+ 'geocoding',
+]
const builtins = new Set(
builtinModules.map((name) => name.replace(/^node:/, '')),
)
diff --git a/server/database/migrations b/server/database/migrations
new file mode 120000
index 00000000..ca30818f
--- /dev/null
+++ b/server/database/migrations
@@ -0,0 +1 @@
+../../packages/database/migrations
\ No newline at end of file
diff --git a/server/database/schema.ts b/server/database/schema.ts
index 6b0ee008..97c2cb4f 100644
--- a/server/database/schema.ts
+++ b/server/database/schema.ts
@@ -1,262 +1,2 @@
-import type { NormalizedLocation } from '../../shared/types/location'
-import { sql } from 'drizzle-orm'
-import {
- index,
- integer,
- primaryKey,
- real,
- sqliteTable,
- text,
- uniqueIndex,
-} from 'drizzle-orm/sqlite-core'
-import { QUEUE_WARNING_CODES } from '../../shared/utils/queue-warning.ts'
-import type { NeededExif } from '~~/shared/types/photo'
-import type { StorageConfig } from '../services/storage'
-
-type PipelineQueuePayload =
- | { type: 'location-migration' }
- | {
- type: 'photo'
- storageKey: string
- eraseLocation?: boolean
- albumId?: number
- }
- | {
- type: 'live-photo-video'
- storageKey: string
- }
- | {
- type: 'photo-reverse-geocoding'
- migrationOnly?: boolean
- photoId: string
- latitude?: number | null
- longitude?: number | null
- }
- | {
- type: 'photo-erase-location'
- photoId: string
- }
-
-export const users = sqliteTable('users', {
- id: integer('id').primaryKey({ autoIncrement: true }),
- username: text('name').notNull().unique(),
- email: text('email').notNull().unique(),
- password: text('password'),
- avatar: text('avatar'),
- createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
- isAdmin: integer('is_admin').default(0).notNull(),
-})
-
-export const photos = sqliteTable('photos', {
- id: text('id').primaryKey().unique(),
- title: text('title'),
- description: text('description'),
- width: integer('width'),
- height: integer('height'),
- aspectRatio: real('aspect_ratio'),
- dateTaken: text('date_taken'),
- storageKey: text('storage_key'),
- thumbnailKey: text('thumbnail_key'),
- fileSize: integer('file_size'),
- lastModified: text('last_modified'),
- originalUrl: text('original_url'),
- thumbnailUrl: text('thumbnail_url'),
- thumbnailHash: text('thumbnail_hash'),
- tags: text('tags', { mode: 'json' }).$type<string[]>(),
- exif: text('exif', { mode: 'json' }).$type<NeededExif>(),
- // 地理位置信息
- latitude: real('latitude'),
- longitude: real('longitude'),
- country: text('country'),
- city: text('city'),
- locationName: text('location_name'),
- geocoding: text('geocoding', { mode: 'json' }).$type<NormalizedLocation>(),
- // LivePhoto 相关字段
- isLivePhoto: integer('is_live_photo').default(0).notNull(),
- livePhotoVideoUrl: text('live_photo_video_url'),
- livePhotoVideoKey: text('live_photo_video_key'),
-})
-
-// One row per string an image request may use to identify a photo: the photo
-// id, each storage key, each public URL, and the tidied form of those paths.
-// Photos insert/update/delete triggers (migration 0014) keep the rows in sync.
-// Album checks look up this indexed key instead of reading every photos row.
-export const photoAccessKeys = sqliteTable(
- 'photo_access_keys',
- {
- accessKey: text('access_key').notNull(),
- photoId: text('photo_id')
- .notNull()
- .references(() => photos.id, { onDelete: 'cascade' }),
- },
- (t) => [
- primaryKey({ columns: [t.accessKey, t.photoId] }),
- index('idx_photo_access_keys_photo_id').on(t.photoId),
- ],
-)
-
-export const pipelineQueue = sqliteTable(
- 'pipeline_queue',
- {
- id: integer('id').primaryKey({ autoIncrement: true }),
- payload: text('payload', { mode: 'json' })
- .$type<PipelineQueuePayload>()
- .notNull()
- .default({
- type: 'photo',
- storageKey: '',
- } satisfies PipelineQueuePayload),
- priority: integer('priority').default(0).notNull(),
- availableAt: integer('available_at', { mode: 'timestamp_ms' })
- .notNull()
- .default(sql`0`),
- attempts: integer('attempts').default(0).notNull(),
- maxAttempts: integer('max_attempts').default(3).notNull(),
- status: text('status', {
- enum: [
- 'pending', // Waiting to be processed
- 'in-stages', // Currently being processed
- 'completed', // Successfully processed
- 'failed', // Processing failed
- ],
- })
- .notNull()
- .default('pending'),
- statusStage: text('status_stage', {
- enum: [
- 'preprocessing',
- 'metadata',
- 'thumbnail',
- 'exif',
- 'motion-photo',
- 'reverse-geocoding',
- 'live-photo',
- 'location-erase',
- ],
- }),
- errorMessage: text('error_message'),
- warningCode: text('warning_code', { enum: QUEUE_WARNING_CODES }),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- completedAt: integer('completed_at', { mode: 'timestamp' }),
- },
- (t) => [
- index('idx_pipeline_queue_pending')
- .on(sql`${t.priority} DESC`, t.createdAt, t.id)
- .where(sql`${t.status} = 'pending'`),
- ],
-)
-
-// 照片表态表
-export const photoReactions = sqliteTable('photo_reactions', {
- id: integer('id').primaryKey({ autoIncrement: true }),
- photoId: text('photo_id')
- .notNull()
- .references(() => photos.id, { onDelete: 'cascade' }),
- reactionType: text('reaction_type', {
- enum: ['like', 'love', 'amazing', 'funny', 'wow', 'sad', 'fire', 'sparkle'],
- }).notNull(),
- // 使用指纹而不是 IP 地址,更准确且支持匿名用户
- fingerprint: text('fingerprint').notNull(),
- ipAddress: text('ip_address'),
- userAgent: text('user_agent'),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
-})
-
-// 相簿表
-export const albums = sqliteTable('albums', {
- id: integer('id').primaryKey({ autoIncrement: true }),
- title: text('title').notNull(),
- description: text('description'),
- coverPhotoId: text('cover_photo_id').references(() => photos.id, {
- onDelete: 'set null',
- }),
- isHidden: integer('is_hidden', { mode: 'boolean' }).default(false).notNull(),
- passwordHash: text('password_hash'),
- // Album sort position (ascending; smaller value appears first)
- position: real('position').notNull().default(0),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
-})
-
-// 相簿-照片 多对多关系表
-export const albumPhotos = sqliteTable(
- 'album_photos',
- {
- id: integer('id').primaryKey({ autoIncrement: true }),
- albumId: integer('album_id')
- .notNull()
- .references(() => albums.id, { onDelete: 'cascade' }),
- photoId: text('photo_id')
- .notNull()
- .references(() => photos.id, { onDelete: 'cascade' }),
- position: real('position').notNull().default(1000000),
- addedAt: integer('added_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- },
- (t) => [
- uniqueIndex('album_photos_album_photo_unique').on(t.albumId, t.photoId),
- ],
-)
-
-export const settings = sqliteTable(
- 'settings',
- {
- id: integer('id').primaryKey({ autoIncrement: true }),
- namespace: text('namespace').notNull().default('common'),
- key: text('key').notNull(),
- type: text('type', {
- enum: ['string', 'number', 'boolean', 'json'],
- }).notNull(),
- value: text('value'),
- defaultValue: text('default_value'),
- label: text('label'),
- description: text('description'),
- isPublic: integer('is_public', { mode: 'boolean' })
- .default(false)
- .notNull(),
- isReadonly: integer('is_readonly', { mode: 'boolean' })
- .default(false)
- .notNull(),
- isSecret: integer('is_secret', { mode: 'boolean' })
- .default(false)
- .notNull(),
- enum: text('enum', { mode: 'json' }).$type<string[] | null>(),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedBy: integer('updated_by').references(() => users.id, {
- onDelete: 'set null',
- }),
- },
- (t) => [uniqueIndex('idx_namespace_key').on(t.namespace, t.key)],
-)
-
-export const settings_storage_providers = sqliteTable(
- 'settings_storage_providers',
- {
- id: integer('id').primaryKey({ autoIncrement: true }),
- name: text('name').notNull(),
- provider: text('provider', {
- enum: ['s3', 'local', 'openlist'],
- }).notNull(),
- config: text('config', { mode: 'json' }).$type<StorageConfig>().notNull(),
- createdAt: integer('created_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- updatedAt: integer('updated_at', { mode: 'timestamp' })
- .notNull()
- .default(sql`(unixepoch())`),
- },
-)
+// Compatibility entry; schema ownership belongs to the database package.
+export * from '@chronoframe/database/schema'
diff --git a/server/plugins/0.db-migrate.ts b/server/plugins/0.db-migrate.ts
index 0ea15552..c02816dd 100644
--- a/server/plugins/0.db-migrate.ts
+++ b/server/plugins/0.db-migrate.ts
@@ -1,38 +1,20 @@
-import { mkdirSync } from 'node:fs'
-import { dirname, resolve } from 'node:path'
-
-import Database from 'better-sqlite3'
-import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { resolve } from 'node:path'
import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { useDB, closeDB } from '../utils/db'
-let migrationPromise: Promise<void> | null = null
-const migrationLogger = logger.dynamic('db-migrate')
-
-async function runMigrations() {
- const dbPath = resolve(process.env.DATABASE_URL || './data/app.sqlite3')
-
- mkdirSync(dirname(dbPath), { recursive: true })
-
- const sqlite = new Database(dbPath)
-
+export default defineNitroPlugin((nitroApp) => {
try {
- const db = drizzle(sqlite)
- await migrate(db, {
- migrationsFolder: resolve('./server/database/migrations'),
+ migrate(useDB(), {
+ migrationsFolder: resolve(
+ process.env.DATABASE_MIGRATIONS || './server/database/migrations',
+ ),
})
- migrationLogger.info('Database migration finished successfully')
- } finally {
- sqlite.close()
+ logger
+ .dynamic('db-migrate')
+ .info('Database migration finished successfully')
+ } catch (error) {
+ closeDB()
+ throw error
}
-}
-
-export default defineNitroPlugin(async () => {
- if (!migrationPromise) {
- migrationPromise = runMigrations().catch((error) => {
- migrationLogger.error('Database migration failed', error)
- throw error
- })
- }
-
- await migrationPromise
+ nitroApp.hooks.hook('close', closeDB)
})
diff --git a/server/repositories/sqlite-mutations.ts b/server/repositories/sqlite-mutations.ts
index c065970f..bfbcb447 100644
--- a/server/repositories/sqlite-mutations.ts
+++ b/server/repositories/sqlite-mutations.ts
@@ -1,166 +1 @@
-import { and, eq, min } from 'drizzle-orm'
-import type {
- AlbumWriteRepository,
- PhotoWriteRepository,
-} from '@chronoframe/core'
-import { tables, type useDB } from '../utils/db.ts'
-import { toAlbumDto, toPhotoDto } from '../utils/dto.ts'
-
-/** Keep album row and membership changes inside synchronous SQLite transactions. */
-export function createSqliteAlbumWriteRepository(
- db: ReturnType<typeof useDB>,
-): AlbumWriteRepository {
- return {
- async exists(id) {
- return Boolean(
- db
- .select({ id: tables.albums.id })
- .from(tables.albums)
- .where(eq(tables.albums.id, id))
- .get(),
- )
- },
- async createFirst(data, photoIds) {
- return db.transaction((tx) => {
- const row = tx
- .select({ min: min(tables.albums.position) })
- .from(tables.albums)
- .get()
- const album = tx
- .insert(tables.albums)
- .values({ ...data, position: (row?.min ?? 1000) - 1000 })
- .returning()
- .get()
- photoIds.forEach((photoId, index) =>
- tx
- .insert(tables.albumPhotos)
- .values({
- albumId: album.id,
- photoId,
- position: 1000000 + (index + 1) * 10,
- })
- .onConflictDoNothing()
- .run(),
- )
- return toAlbumDto(album)
- })
- },
- async update(id, data, photoIds) {
- return db.transaction((tx) => {
- const exists = tx
- .select({ id: tables.albums.id })
- .from(tables.albums)
- .where(eq(tables.albums.id, id))
- .get()
- if (!exists) return null
- tx.update(tables.albums).set(data).where(eq(tables.albums.id, id)).run()
- if (photoIds !== undefined) {
- tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
- .run()
- photoIds.forEach((photoId, index) =>
- tx
- .insert(tables.albumPhotos)
- .values({
- albumId: id,
- photoId,
- position: 1000000 + (index + 1) * 10,
- })
- .onConflictDoNothing()
- .run(),
- )
- }
- return toAlbumDto(
- tx
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, id))
- .get()!,
- )
- })
- },
- async delete(id) {
- return db.transaction((tx) => {
- if (
- !tx
- .select({ id: tables.albums.id })
- .from(tables.albums)
- .where(eq(tables.albums.id, id))
- .get()
- )
- return false
- tx.delete(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
- .run()
- tx.delete(tables.albums).where(eq(tables.albums.id, id)).run()
- return true
- })
- },
- async reorder(ids) {
- db.transaction((tx) => {
- ids.forEach((id, index) =>
- tx
- .update(tables.albums)
- .set({ position: index * 1000 })
- .where(eq(tables.albums.id, id))
- .run(),
- )
- })
- },
- async removePhoto(id, photoId, updatedAt) {
- return db.transaction((tx) => {
- const predicate = and(
- eq(tables.albumPhotos.albumId, id),
- eq(tables.albumPhotos.photoId, photoId),
- )
- if (
- !tx
- .select({ id: tables.albumPhotos.id })
- .from(tables.albumPhotos)
- .where(predicate)
- .get()
- )
- return false
- tx.delete(tables.albumPhotos).where(predicate).run()
- tx.update(tables.albums)
- .set({ coverPhotoId: null, updatedAt })
- .where(
- and(
- eq(tables.albums.id, id),
- eq(tables.albums.coverPhotoId, photoId),
- ),
- )
- .run()
- return true
- })
- },
- }
-}
-
-/** Map photo writes at the existing connection boundary without changing its lifecycle. */
-export function createSqlitePhotoWriteRepository(
- db: ReturnType<typeof useDB>,
-): PhotoWriteRepository {
- return {
- async get(id) {
- const photo = db
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, id))
- .get()
- return photo ? toPhotoDto(photo) : null
- },
- async update(id, update) {
- db.update(tables.photos).set(update).where(eq(tables.photos.id, id)).run()
- const photo = db
- .select()
- .from(tables.photos)
- .where(eq(tables.photos.id, id))
- .get()
- return photo ? toPhotoDto(photo) : null
- },
- async delete(id) {
- db.delete(tables.photos).where(eq(tables.photos.id, id)).run()
- },
- }
-}
+export * from '@chronoframe/database/repositories'
diff --git a/server/repositories/sqlite-resources.ts b/server/repositories/sqlite-resources.ts
index e721da20..bfbcb447 100644
--- a/server/repositories/sqlite-resources.ts
+++ b/server/repositories/sqlite-resources.ts
@@ -1,86 +1 @@
-import { asc, desc, eq, getTableColumns, notInArray } from 'drizzle-orm'
-import type { ResourceReadRepository } from '@chronoframe/core'
-import { tables, type useDB } from '../utils/db.ts'
-import { toAlbumDto, toPhotoDto } from '../utils/dto.ts'
-
-/** Adapt existing SQLite queries without changing connections, schema or lifecycle. */
-export function createSqliteResourceRepository(
- db: ReturnType<typeof useDB>,
-): ResourceReadRepository {
- const albumRecord = (row: typeof tables.albums.$inferSelect) => ({
- resource: toAlbumDto(row),
- passwordHash: row.passwordHash,
- })
- return {
- async listPhotos(excludedIds = []) {
- return db
- .select()
- .from(tables.photos)
- .where(
- excludedIds.length
- ? notInArray(tables.photos.id, excludedIds)
- : undefined,
- )
- .orderBy(desc(tables.photos.dateTaken))
- .all()
- .map(toPhotoDto)
- },
- async listAlbums() {
- return db
- .select()
- .from(tables.albums)
- .orderBy(asc(tables.albums.position), desc(tables.albums.createdAt))
- .all()
- .map(albumRecord)
- },
- async getAlbum(id) {
- const row = db
- .select()
- .from(tables.albums)
- .where(eq(tables.albums.id, id))
- .get()
- return row ? albumRecord(row) : null
- },
- async listAlbumPhotoIds(id) {
- return db
- .select({ id: tables.albumPhotos.photoId })
- .from(tables.albumPhotos)
- .where(eq(tables.albumPhotos.albumId, id))
- .orderBy(asc(tables.albumPhotos.position))
- .all()
- .map((row) => row.id)
- },
- async listAlbumPhotos(id) {
- return db
- .select(getTableColumns(tables.photos))
- .from(tables.photos)
- .innerJoin(
- tables.albumPhotos,
- eq(tables.photos.id, tables.albumPhotos.photoId),
- )
- .where(eq(tables.albumPhotos.albumId, id))
- .orderBy(asc(tables.albumPhotos.position))
- .all()
- .map(toPhotoDto)
- },
- async listMemberships() {
- return db
- .select({
- photoId: tables.albumPhotos.photoId,
- albumId: tables.albums.id,
- hidden: tables.albums.isHidden,
- passwordHash: tables.albums.passwordHash,
- })
- .from(tables.albumPhotos)
- .innerJoin(
- tables.albums,
- eq(tables.albumPhotos.albumId, tables.albums.id),
- )
- .all()
- .map(({ passwordHash, ...membership }) => ({
- ...membership,
- protected: passwordHash !== null,
- }))
- },
- }
-}
+export * from '@chronoframe/database/repositories'
diff --git a/server/repositories/sqlite-uploads.ts b/server/repositories/sqlite-uploads.ts
index 080c31aa..bfbcb447 100644
--- a/server/repositories/sqlite-uploads.ts
+++ b/server/repositories/sqlite-uploads.ts
@@ -1,45 +1 @@
-import { eq } from 'drizzle-orm'
-import type { DuplicatePhoto } from '@chronoframe/core'
-import type { Photo } from '@chronoframe/contracts/resources'
-import { tables, type useDB } from '../utils/db.ts'
-
-/** Project only fields used by authenticated duplicate checks. */
-export function createSqliteUploadRepository(db: ReturnType<typeof useDB>) {
- const summary = {
- id: tables.photos.id,
- title: tables.photos.title,
- storageKey: tables.photos.storageKey,
- originalUrl: tables.photos.originalUrl,
- thumbnailUrl: tables.photos.thumbnailUrl,
- dateTaken: tables.photos.dateTaken,
- }
- return {
- async findDuplicate(id: string): Promise<DuplicatePhoto | null> {
- return (
- db
- .select(summary)
- .from(tables.photos)
- .where(eq(tables.photos.id, id))
- .get() || null
- )
- },
- async findDetails(
- id: string,
- ): Promise<
- (DuplicatePhoto & Pick<Photo, 'fileSize' | 'width' | 'height'>) | null
- > {
- return (
- db
- .select({
- ...summary,
- fileSize: tables.photos.fileSize,
- width: tables.photos.width,
- height: tables.photos.height,
- })
- .from(tables.photos)
- .where(eq(tables.photos.id, id))
- .get() || null
- )
- },
- }
-}
+export * from '@chronoframe/database/repositories'
diff --git a/server/utils/db.ts b/server/utils/db.ts
index d3b768c1..1471d3d2 100644
--- a/server/utils/db.ts
+++ b/server/utils/db.ts
@@ -1,58 +1,35 @@
-import { drizzle } from 'drizzle-orm/better-sqlite3'
-import Database from 'better-sqlite3'
-
-import * as schema from '../database/schema.ts'
-
-export const tables = schema
+import { resolve } from 'node:path'
+import { openDatabase } from '@chronoframe/database'
+export { tables } from '@chronoframe/database'
+export type {
+ User,
+ Photo,
+ PipelineQueueItem,
+ NewPipelineQueueItem,
+ PhotoReaction,
+ Album,
+ NewAlbum,
+ AlbumPhoto,
+ NewAlbumPhoto,
+ AlbumWithPhotos,
+} from '@chronoframe/database'
export { eq, and, or, inArray } from 'drizzle-orm'
-// 创建单例数据库连接
-let dbInstance: ReturnType<typeof drizzle> | null = null
-let sqliteInstance: Database.Database | null = null
+let connection: ReturnType<typeof openDatabase> | null = null
+/** Share the same configured connection for migrations and application queries. */
export function useDB() {
- if (!dbInstance || !sqliteInstance) {
- // 创建数据库连接,启用WAL模式以提高并发性能
- sqliteInstance = new Database('data/app.sqlite3', {
- verbose:
- process.env.NODE_ENV === 'development'
- ? logger.dynamic('db').verbose
- : undefined,
- })
-
- // 启用WAL模式以提高并发性能
- sqliteInstance.pragma('journal_mode = WAL')
- sqliteInstance.pragma('synchronous = NORMAL')
- sqliteInstance.pragma('cache_size = 1000')
- sqliteInstance.pragma('temp_store = MEMORY')
-
- dbInstance = drizzle(sqliteInstance, { schema })
- }
-
- return dbInstance
+ connection ??= openDatabase({
+ filename: resolve(process.env.DATABASE_URL || './data/app.sqlite3'),
+ verbose:
+ process.env.NODE_ENV === 'development'
+ ? logger.dynamic('db').verbose
+ : undefined,
+ })
+ return connection.db
}
-// 优雅关闭数据库连接
export function closeDB() {
- if (sqliteInstance) {
- sqliteInstance.close()
- sqliteInstance = null
- dbInstance = null
- }
-}
-
-export type User = typeof schema.users.$inferSelect
-export type Photo = typeof schema.photos.$inferSelect
-
-export type PipelineQueueItem = typeof schema.pipelineQueue.$inferSelect
-export type NewPipelineQueueItem = typeof schema.pipelineQueue.$inferInsert
-
-export type PhotoReaction = typeof schema.photoReactions.$inferSelect
-
-export type Album = typeof schema.albums.$inferSelect
-export type NewAlbum = typeof schema.albums.$inferInsert
-export type AlbumPhoto = typeof schema.albumPhotos.$inferSelect
-export type NewAlbumPhoto = typeof schema.albumPhotos.$inferInsert
-export type AlbumWithPhotos = Album & {
- photos: Photo[]
+ connection?.close()
+ connection = null
}
diff --git a/server/utils/dto.ts b/server/utils/dto.ts
index 52e7f960..7b396340 100644
--- a/server/utils/dto.ts
+++ b/server/utils/dto.ts
@@ -1,82 +1 @@
-import type {
- Photo,
- Album,
- UserSummary,
-} from '@chronoframe/contracts/resources'
-import type {
- Photo as PhotoRow,
- Album as AlbumRow,
- User as UserRow,
-} from './db'
-
-/** Expose only the declared photo contract fields, excluding internal database columns. */
-export function toPhotoDto(photo: PhotoRow): Photo {
- return {
- id: photo.id,
- title: photo.title,
- description: photo.description,
- width: photo.width,
- height: photo.height,
- aspectRatio: photo.aspectRatio,
- dateTaken: photo.dateTaken,
- storageKey: photo.storageKey,
- thumbnailKey: photo.thumbnailKey,
- fileSize: photo.fileSize,
- lastModified: photo.lastModified,
- originalUrl: photo.originalUrl,
- thumbnailUrl: photo.thumbnailUrl,
- thumbnailHash: photo.thumbnailHash,
- tags: photo.tags,
- exif: photo.exif,
- latitude: photo.latitude,
- longitude: photo.longitude,
- country: photo.country,
- city: photo.city,
- locationName: photo.locationName,
- geocoding: photo.geocoding,
- isLivePhoto: photo.isLivePhoto,
- livePhotoVideoUrl: photo.livePhotoVideoUrl,
- livePhotoVideoKey: photo.livePhotoVideoKey,
- }
-}
-
-/** Serialize album dates and expose password presence without its hash. */
-export function toAlbumDto(album: AlbumRow): Album {
- return {
- id: album.id,
- title: album.title,
- description: album.description,
- coverPhotoId: album.coverPhotoId,
- isHidden: album.isHidden,
- position: album.position,
- createdAt: album.createdAt.toISOString(),
- updatedAt: album.updatedAt.toISOString(),
- hasPassword: Boolean(album.passwordHash),
- }
-}
-
-/** Build a session-safe user summary without password material. */
-export function toUserSummary(user: UserRow): UserSummary {
- return {
- id: user.id,
- username: user.username,
- email: user.email,
- avatar: user.avatar,
- createdAt: user.createdAt.toISOString(),
- isAdmin: user.isAdmin,
- }
-}
-
-/** Serialize an administrator-only provider response; configuration may contain secrets. */
-export function toStorageProviderDto(
- provider: import('../types/settings').StorageProviderRow,
-): import('@chronoframe/contracts/settings').SettingStorageProvider {
- return {
- id: provider.id,
- name: provider.name,
- provider: provider.provider,
- config: provider.config,
- createdAt: provider.createdAt.toISOString(),
- updatedAt: provider.updatedAt.toISOString(),
- }
-}
+export * from '@chronoframe/database/dto'
diff --git a/shared/utils/queue-warning.ts b/shared/utils/queue-warning.ts
index 3973a38c..01d4f371 100644
--- a/shared/utils/queue-warning.ts
+++ b/shared/utils/queue-warning.ts
@@ -1,17 +1 @@
-/**
- * Warning codes attached to completed pipeline queue tasks.
- *
- * The values are persisted in `pipeline_queue.warning_code` and returned by
- * the queue APIs. Keep them stable.
- */
-
-export const QueueWarningCode = {
- AlbumMissing: 'album-missing',
-} as const
-
-export type QueueWarningCode =
- (typeof QueueWarningCode)[keyof typeof QueueWarningCode]
-
-export const QUEUE_WARNING_CODES: [QueueWarningCode, ...QueueWarningCode[]] = [
- QueueWarningCode.AlbumMissing,
-]
+export * from '@chronoframe/contracts/queue'
diff --git a/tests/database-lifecycle.test.ts b/tests/database-lifecycle.test.ts
new file mode 100644
index 00000000..44333e35
--- /dev/null
+++ b/tests/database-lifecycle.test.ts
@@ -0,0 +1,96 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ openDatabase,
+ tables,
+ persistenceErrorCode,
+} from '../packages/database/src/connection.ts'
+import {
+ createSqliteResourceRepository,
+ createSqliteAlbumWriteRepository,
+} from '../packages/database/src/repositories.ts'
+
+const migrationsFolder = './packages/database/migrations'
+test('database connection, repositories, rollback, backup, restart and reentrant migrations', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'chronoframe-database-'))
+ let connection = openDatabase({
+ filename: join(root, 'app.sqlite3'),
+ migrationsFolder,
+ })
+ try {
+ const { db } = connection
+ db.insert(tables.photos)
+ .values([
+ { id: 'a', title: null, dateTaken: '2020-01-01' },
+ { id: 'b', title: 'newest', dateTaken: '2025-01-01' },
+ { id: 'c', dateTaken: null },
+ ])
+ .run()
+ const reader = createSqliteResourceRepository(db)
+ assert.deepEqual(
+ (await reader.listPhotos()).map((p) => p.id),
+ ['b', 'a', 'c'],
+ )
+ assert.deepEqual(
+ (await reader.listPhotos(['b'])).map((p) => p.id),
+ ['a', 'c'],
+ )
+ assert.deepEqual(
+ (await reader.listPhotos([], { limit: 1, offset: 1 })).map((p) => p.id),
+ ['a'],
+ )
+ await assert.rejects(
+ reader.listPhotos([], { limit: 0, offset: 0 }),
+ RangeError,
+ )
+ const writer = createSqliteAlbumWriteRepository(db)
+ const createdAt = new Date('2025-01-01T00:00:00Z')
+ const album = await writer.createFirst(
+ { title: 'fixture', createdAt, updatedAt: createdAt },
+ ['a', 'b'],
+ )
+ assert.equal(album.createdAt, createdAt.toISOString())
+ assert.deepEqual(await reader.listAlbumPhotoIds(album.id), ['a', 'b'])
+ await assert.rejects(
+ writer.createFirst(
+ { title: 'rollback', createdAt, updatedAt: createdAt },
+ ['missing'],
+ ),
+ (error) => persistenceErrorCode(error) === 'invalid-relation',
+ )
+ assert.equal((await reader.listAlbums()).length, 1)
+ assert.throws(
+ () => db.insert(tables.photos).values({ id: 'a' }).run(),
+ (error) => persistenceErrorCode(error) === 'conflict',
+ )
+ await connection.backup(join(root, 'backup.sqlite3'))
+ connection.close()
+ connection = openDatabase({
+ filename: join(root, 'app.sqlite3'),
+ migrationsFolder,
+ })
+ assert.equal(connection.db.select().from(tables.photos).all().length, 3)
+ const restored = openDatabase({
+ filename: join(root, 'backup.sqlite3'),
+ migrationsFolder,
+ })
+ try {
+ assert.deepEqual(
+ restored.db.select().from(tables.photos).all(),
+ connection.db.select().from(tables.photos).all(),
+ )
+ assert.deepEqual(
+ restored.db.select().from(tables.albumPhotos).all(),
+ connection.db.select().from(tables.albumPhotos).all(),
+ )
+ } finally {
+ restored.close()
+ }
+ } finally {
+ connection.close()
+ await rm(root, { recursive: true, force: true })
+ }
+})