update
This commit is contained in:
132
src/db/album.rs
Normal file
132
src/db/album.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use super::Database;
|
||||
use crate::models::*;
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl Database {
|
||||
// ── 查询 ──
|
||||
|
||||
pub async fn get_all_albums(&self) -> Result<Vec<AlbumInfo>, sqlx::Error> {
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT id, title, document, description, cover_image_id, image_count, created_at
|
||||
FROM albums ORDER BY created_at DESC"#
|
||||
).fetch_all(&self.pool).await?;
|
||||
|
||||
Ok(rows.iter().map(|r| {
|
||||
let id_str = r.get::<String, _>("id");
|
||||
AlbumInfo {
|
||||
id: Uuid::parse_str(&id_str).unwrap_or_else(|_| Uuid::nil()),
|
||||
title: r.get("title"),
|
||||
document: r.get("document"),
|
||||
description: r.get("description"),
|
||||
cover_image_id: r.get("cover_image_id"),
|
||||
image_count: r.get("image_count"),
|
||||
created_at: r.get("created_at"),
|
||||
}
|
||||
}).collect())
|
||||
}
|
||||
|
||||
pub async fn get_album_with_images(&self, album_id: Uuid) -> Result<Option<AlbumWithImages>, sqlx::Error> {
|
||||
let row = sqlx::query("SELECT * FROM albums WHERE id = ?")
|
||||
.bind(album_id.to_string())
|
||||
.fetch_optional(&self.pool).await?;
|
||||
|
||||
let Some(row) = row else { return Ok(None) };
|
||||
|
||||
let id_str = row.get::<String, _>("id");
|
||||
let id = Uuid::parse_str(&id_str).unwrap_or_else(|_| Uuid::nil());
|
||||
let cover = row.get::<Option<String>, _>("cover_image_id")
|
||||
.and_then(|s| Uuid::parse_str(&s).ok());
|
||||
|
||||
let album = Album {
|
||||
id,
|
||||
title: row.get("title"),
|
||||
description: row.get("description"),
|
||||
cover_image_id: cover,
|
||||
image_count: row.get("image_count"),
|
||||
created_at: row.get("created_at"),
|
||||
updated_at: row.get("updated_at"),
|
||||
person_name_cleaned: row.get("person_name_cleaned"),
|
||||
tags: row.get("tags"),
|
||||
};
|
||||
|
||||
let img_rows = sqlx::query("SELECT * FROM images WHERE album_id = ?")
|
||||
.bind(album_id.to_string()).fetch_all(&self.pool).await?;
|
||||
|
||||
let mut images = Vec::new();
|
||||
for r in &img_rows {
|
||||
let img_id = Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil());
|
||||
let aid = Uuid::parse_str(&r.get::<String, _>("album_id")).unwrap_or_else(|_| Uuid::nil());
|
||||
images.push(super::image::Image {
|
||||
id: img_id, album_id: aid,
|
||||
filename: r.get("filename"),
|
||||
original_url: r.get("original_url"),
|
||||
title: r.get("title"),
|
||||
description: r.get("description"),
|
||||
file_size: r.get("file_size"),
|
||||
width: r.get("width"),
|
||||
height: r.get("height"),
|
||||
mime_type: r.get("mime_type"),
|
||||
created_at: r.get("created_at"),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Some(AlbumWithImages { album, images: images.clone(), image_count: images.len() as i64 }))
|
||||
}
|
||||
|
||||
pub async fn get_all_albums_full(&self) -> Vec<AlbumMeta> {
|
||||
let has_col = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('albums') WHERE name = 'person_name_original'"
|
||||
).fetch_one(&self.pool).await.unwrap_or(0);
|
||||
if has_col == 0 { return Vec::new(); }
|
||||
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT id, title, person_name_original, person_name_cleaned, tags, all_words, raw_title, processed_at, image_count
|
||||
FROM albums ORDER BY created_at DESC"#
|
||||
).fetch_all(&self.pool).await.unwrap_or_default();
|
||||
|
||||
rows.iter().map(|r| AlbumMeta {
|
||||
id: r.get("id"), title: r.get("title"),
|
||||
person_name_original: r.get("person_name_original"),
|
||||
person_name_cleaned: r.get("person_name_cleaned"),
|
||||
tags: r.get("tags"), all_words: r.get("all_words"),
|
||||
raw_title: r.get("raw_title"), processed_at: r.get("processed_at"),
|
||||
image_count: r.get("image_count"),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
// ── 写入 ──
|
||||
|
||||
pub async fn create_album(&self, album: CreateAlbum) -> Result<Uuid, sqlx::Error> {
|
||||
let id = Uuid::new_v4();
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
sqlx::query(
|
||||
"INSERT INTO albums (id, title, document, description, image_count, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)"
|
||||
).bind(id.to_string()).bind(album.title).bind(album.document).bind(album.description).bind(&now).bind(&now)
|
||||
.execute(&self.pool).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub async fn delete_album(&self, album_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("DELETE FROM albums WHERE id = ?").bind(album_id.to_string()).execute(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_album_cover(&self, album_id: Uuid, image_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE albums SET cover_image_id = ? WHERE id = ?")
|
||||
.bind(image_id.to_string()).bind(album_id.to_string()).execute(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_album_image_count(&self, album_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
r#"UPDATE albums SET image_count = (SELECT COUNT(*) FROM images WHERE album_id = ?), updated_at = datetime('now') WHERE id = ?"#
|
||||
).bind(album_id.to_string()).bind(album_id.to_string()).execute(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_album_image_count(&self, album_id: Uuid) -> Result<i64, sqlx::Error> {
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM images WHERE album_id = ?")
|
||||
.bind(album_id.to_string()).fetch_one(&self.pool).await
|
||||
}
|
||||
}
|
||||
63
src/db/connection.rs
Normal file
63
src/db/connection.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use sqlx::{SqlitePool, sqlite::SqlitePoolOptions};
|
||||
use crate::config::Config;
|
||||
|
||||
pub struct Database {
|
||||
pub pool: SqlitePool,
|
||||
pub config: Config,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub async fn new(config: &Config) -> Result<Self, sqlx::Error> {
|
||||
let url = &config.database.url;
|
||||
let file_path = if url.starts_with("sqlite:") { &url[7..] } else { url };
|
||||
|
||||
if let Some(parent) = std::path::Path::new(file_path).parent() {
|
||||
if !parent.exists() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
}
|
||||
if !std::path::Path::new(file_path).exists() {
|
||||
std::fs::File::create(file_path)?;
|
||||
println!("创建新的数据库文件: {}", file_path);
|
||||
}
|
||||
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(10)
|
||||
.min_connections(2)
|
||||
.acquire_timeout(std::time::Duration::from_secs(5))
|
||||
.idle_timeout(std::time::Duration::from_secs(300))
|
||||
.max_lifetime(std::time::Duration::from_secs(1800))
|
||||
.connect(url)
|
||||
.await?;
|
||||
|
||||
// SQLite 性能优化
|
||||
sqlx::query("PRAGMA journal_mode=WAL;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA wal_autocheckpoint=4000;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA synchronous=NORMAL;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA cache_size=-64000;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA mmap_size=268435456;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA temp_store=MEMORY;").execute(&pool).await?;
|
||||
sqlx::query("PRAGMA foreign_keys=ON;").execute(&pool).await?;
|
||||
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
|
||||
let db = Database { pool, config: config.clone() };
|
||||
db.ensure_image_count_field().await?;
|
||||
Ok(db)
|
||||
}
|
||||
|
||||
/// 确保 image_count 字段存在
|
||||
async fn ensure_image_count_field(&self) -> Result<(), sqlx::Error> {
|
||||
let has_col = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('albums') WHERE name = 'image_count'"
|
||||
).fetch_one(&self.pool).await.unwrap_or(0);
|
||||
|
||||
if has_col == 0 {
|
||||
sqlx::query("ALTER TABLE albums ADD COLUMN image_count INTEGER DEFAULT 0").execute(&self.pool).await?;
|
||||
println!("✅ image_count 字段已添加");
|
||||
} else {
|
||||
println!("ℹ️ image_count字段已存在,跳过初始化");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
67
src/db/favorite.rs
Normal file
67
src/db/favorite.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use super::Database;
|
||||
use crate::models::*;
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl Database {
|
||||
pub async fn get_user_favorites(&self, user_id: &str) -> Result<Vec<FavoriteWithImage>, sqlx::Error> {
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT f.id, f.user_id, f.image_id, f.album_id, f.created_at,
|
||||
i.album_id as img_album_id, i.filename, i.original_url, i.title, i.description,
|
||||
i.file_size, i.width, i.height, i.mime_type, i.created_at as img_created_at,
|
||||
a.title as album_title
|
||||
FROM favorites f
|
||||
JOIN images i ON f.image_id = i.id
|
||||
JOIN albums a ON f.album_id = a.id
|
||||
WHERE f.user_id = ? ORDER BY f.created_at DESC"#
|
||||
).bind(user_id).fetch_all(&self.pool).await?;
|
||||
|
||||
Ok(rows.iter().map(|r| {
|
||||
let fav_id = Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil());
|
||||
let img_id = Uuid::parse_str(&r.get::<String, _>("image_id")).unwrap_or_else(|_| Uuid::nil());
|
||||
let aid = Uuid::parse_str(&r.get::<String, _>("album_id")).unwrap_or_else(|_| Uuid::nil());
|
||||
let img_aid = Uuid::parse_str(&r.get::<String, _>("img_album_id")).unwrap_or_else(|_| Uuid::nil());
|
||||
FavoriteWithImage {
|
||||
favorite: Favorite { id: fav_id, user_id: r.get("user_id"), image_id: img_id, album_id: aid, created_at: r.get("created_at") },
|
||||
image: crate::models::image::Image {
|
||||
id: img_id, album_id: img_aid,
|
||||
filename: r.get("filename"), original_url: r.get("original_url"),
|
||||
title: r.get("title"), description: r.get("description"),
|
||||
file_size: r.get("file_size"), width: r.get("width"),
|
||||
height: r.get("height"), mime_type: r.get("mime_type"),
|
||||
created_at: r.get("img_created_at"),
|
||||
},
|
||||
album_title: r.get("album_title"),
|
||||
}
|
||||
}).collect())
|
||||
}
|
||||
|
||||
pub async fn get_favorite_status(&self, user_id: &str, image_id: Uuid) -> Result<FavoriteStatus, sqlx::Error> {
|
||||
let row = sqlx::query("SELECT id FROM favorites WHERE user_id = ? AND image_id = ?")
|
||||
.bind(user_id).bind(image_id.to_string()).fetch_optional(&self.pool).await?;
|
||||
Ok(FavoriteStatus {
|
||||
is_favorited: row.is_some(),
|
||||
favorite_id: row.map(|r| Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil())),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn add_favorite(&self, user_id: &str, fav: CreateFavorite) -> Result<Uuid, sqlx::Error> {
|
||||
let id = Uuid::new_v4();
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
sqlx::query("INSERT INTO favorites (id, user_id, image_id, album_id, created_at) VALUES (?, ?, ?, ?, ?)")
|
||||
.bind(id.to_string()).bind(user_id).bind(fav.image_id.to_string()).bind(fav.album_id.to_string()).bind(&now)
|
||||
.execute(&self.pool).await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub async fn remove_favorite(&self, favorite_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("DELETE FROM favorites WHERE id = ?").bind(favorite_id.to_string()).execute(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn remove_favorite_by_image(&self, user_id: &str, image_id: Uuid) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("DELETE FROM favorites WHERE user_id = ? AND image_id = ?")
|
||||
.bind(user_id).bind(image_id.to_string()).execute(&self.pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
74
src/db/image.rs
Normal file
74
src/db/image.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use super::Database;
|
||||
use crate::models::*;
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// 重新导出用于 cross-module access
|
||||
pub use crate::models::image::Image;
|
||||
|
||||
impl Database {
|
||||
pub async fn add_images(&self, images: Vec<CreateImage>) -> Result<Vec<Uuid>, sqlx::Error> {
|
||||
if images.is_empty() { return Ok(Vec::new()); }
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let mut ids = Vec::new();
|
||||
let first_album_id = images.first().map(|img| img.album_id);
|
||||
|
||||
for img in &images {
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query(
|
||||
"INSERT INTO images (id, album_id, filename, original_url, title, description, file_size, width, height, mime_type, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
).bind(id.to_string()).bind(img.album_id.to_string()).bind(&img.filename)
|
||||
.bind(&img.original_url).bind(&img.title).bind(&img.description)
|
||||
.bind(img.file_size).bind(img.width).bind(img.height).bind(&img.mime_type).bind(&now)
|
||||
.execute(&self.pool).await?;
|
||||
ids.push(id);
|
||||
}
|
||||
|
||||
if let Some(aid) = first_album_id {
|
||||
self.update_album_image_count(aid).await?;
|
||||
let count = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM images WHERE album_id = ?")
|
||||
.bind(aid.to_string()).fetch_one(&self.pool).await?;
|
||||
if count == images.len() as i64 {
|
||||
self.update_album_cover(aid, ids[0]).await?;
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub async fn get_image(&self, image_id: Uuid) -> Result<Option<Image>, sqlx::Error> {
|
||||
let row = sqlx::query("SELECT * FROM images WHERE id = ?")
|
||||
.bind(image_id.to_string()).fetch_optional(&self.pool).await?;
|
||||
let Some(r) = row else { return Ok(None) };
|
||||
Ok(Some(Image {
|
||||
id: image_id,
|
||||
album_id: Uuid::parse_str(&r.get::<String, _>("album_id")).unwrap_or_else(|_| Uuid::nil()),
|
||||
filename: r.get("filename"),
|
||||
original_url: r.get("original_url"),
|
||||
title: r.get("title"),
|
||||
description: r.get("description"),
|
||||
file_size: r.get("file_size"),
|
||||
width: r.get("width"),
|
||||
height: r.get("height"),
|
||||
mime_type: r.get("mime_type"),
|
||||
created_at: r.get("created_at"),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn get_unprocessed_images(&self, limit: i64) -> Result<Vec<Image>, sqlx::Error> {
|
||||
let rows = sqlx::query("SELECT * FROM images WHERE file_size > 0 LIMIT ?")
|
||||
.bind(limit).fetch_all(&self.pool).await?;
|
||||
Ok(rows.iter().map(|r| Image {
|
||||
id: Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil()),
|
||||
album_id: Uuid::parse_str(&r.get::<String, _>("album_id")).unwrap_or_else(|_| Uuid::nil()),
|
||||
filename: r.get("filename"),
|
||||
original_url: r.get("original_url"),
|
||||
title: r.get("title"),
|
||||
description: r.get("description"),
|
||||
file_size: r.get("file_size"),
|
||||
width: r.get("width"),
|
||||
height: r.get("height"),
|
||||
mime_type: r.get("mime_type"),
|
||||
created_at: r.get("created_at"),
|
||||
}).collect())
|
||||
}
|
||||
}
|
||||
203
src/db/metadata.rs
Normal file
203
src/db/metadata.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
use super::Database;
|
||||
use crate::models::*;
|
||||
use sqlx::Row;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl Database {
|
||||
// ── 人员查询 ──
|
||||
|
||||
pub async fn get_all_person_names(&self) -> Vec<(String, i64)> {
|
||||
sqlx::query("SELECT p.name, p.total_albums FROM persons p ORDER BY p.total_albums DESC")
|
||||
.fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (r.get::<String, _>("name"), r.get::<i64, _>("total_albums"))).collect()
|
||||
}
|
||||
|
||||
pub async fn get_all_aliases(&self) -> Vec<(String, String)> {
|
||||
sqlx::query("SELECT a.alias_name, p.name as person_name FROM person_aliases a JOIN persons p ON a.person_id = p.id")
|
||||
.fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (r.get::<String, _>("alias_name"), r.get::<String, _>("person_name"))).collect()
|
||||
}
|
||||
|
||||
pub async fn get_all_persons_with_counts(&self) -> Vec<(i64, String, i64, i64)> {
|
||||
sqlx::query("SELECT id, name, total_albums, total_images FROM persons ORDER BY total_albums DESC")
|
||||
.fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (r.get::<i64, _>("id"), r.get::<String, _>("name"), r.get::<i64, _>("total_albums"), r.get::<i64, _>("total_images"))).collect()
|
||||
}
|
||||
|
||||
pub async fn get_person_by_name(&self, name: &str) -> Option<Person> {
|
||||
let r = sqlx::query("SELECT * FROM persons WHERE name = ?").bind(name).fetch_optional(&self.pool).await.ok()??;
|
||||
Some(Person {
|
||||
id: r.get("id"), name: r.get("name"), display_name: r.get("display_name"),
|
||||
total_albums: r.get("total_albums"), total_images: r.get("total_images"),
|
||||
original_names: r.get("original_names"), created_at: r.get("created_at"), updated_at: r.get("updated_at"),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_person_albums(&self, person_id: i64) -> Vec<AlbumInfo> {
|
||||
sqlx::query(
|
||||
r#"SELECT a.id, a.title, a.document, a.description, a.cover_image_id, a.image_count, a.created_at
|
||||
FROM albums a JOIN person_albums pa ON a.id = pa.album_id WHERE pa.person_id = ? ORDER BY a.created_at DESC"#
|
||||
).bind(person_id).fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| AlbumInfo {
|
||||
id: Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil()),
|
||||
title: r.get("title"), document: r.get("document"),
|
||||
description: r.get("description"), cover_image_id: r.get("cover_image_id"),
|
||||
image_count: r.get("image_count"), created_at: r.get("created_at"),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub async fn get_person_aliases(&self, person_id: i64) -> Vec<PersonAlias> {
|
||||
sqlx::query("SELECT * FROM person_aliases WHERE person_id = ?").bind(person_id)
|
||||
.fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| PersonAlias {
|
||||
id: r.get("id"), person_id: r.get("person_id"),
|
||||
alias_type: r.get("alias_type"), alias_name: r.get("alias_name"),
|
||||
created_at: r.get("created_at"),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub async fn search_persons(&self, query: &str) -> Vec<PersonWithCounts> {
|
||||
let pattern = format!("%{}%", query);
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT DISTINCT p.id, p.name, p.display_name, p.total_albums, p.total_images
|
||||
FROM persons p LEFT JOIN person_aliases a ON p.id = a.person_id
|
||||
WHERE p.name LIKE ? OR a.alias_name LIKE ? ORDER BY p.total_albums DESC"#
|
||||
).bind(&pattern).bind(&pattern).fetch_all(&self.pool).await.unwrap_or_default();
|
||||
|
||||
let mut results = Vec::new();
|
||||
for r in &rows {
|
||||
let pid = r.get::<i64, _>("id");
|
||||
let aliases = self.get_person_aliases(pid).await;
|
||||
results.push(PersonWithCounts {
|
||||
id: pid, name: r.get("name"), display_name: r.get("display_name"),
|
||||
total_albums: r.get("total_albums"), total_images: r.get("total_images"),
|
||||
aliases: aliases.into_iter().map(|a| a.alias_name).collect(),
|
||||
});
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
pub async fn get_all_persons_with_aliases(&self) -> Vec<PersonWithCounts> {
|
||||
let rows = sqlx::query("SELECT id, name, display_name, total_albums, total_images FROM persons ORDER BY total_albums DESC")
|
||||
.fetch_all(&self.pool).await.unwrap_or_default();
|
||||
let mut results = Vec::new();
|
||||
for r in &rows {
|
||||
let pid = r.get::<i64, _>("id");
|
||||
let aliases = self.get_person_aliases(pid).await;
|
||||
results.push(PersonWithCounts {
|
||||
id: pid, name: r.get("name"), display_name: r.get("display_name"),
|
||||
total_albums: r.get("total_albums"), total_images: r.get("total_images"),
|
||||
aliases: aliases.into_iter().map(|a| a.alias_name).collect(),
|
||||
});
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
// ── 标签查询 ──
|
||||
|
||||
pub async fn get_popular_tags(&self, limit: i64) -> Vec<TagStat> {
|
||||
sqlx::query(
|
||||
r#"SELECT tag, COUNT(*) as cnt, COUNT(DISTINCT album_id) as album_cnt
|
||||
FROM album_tags GROUP BY tag ORDER BY cnt DESC LIMIT ?"#
|
||||
).bind(limit).fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| TagStat {
|
||||
tag: r.get("tag"), count: r.get("cnt"), album_count: r.get("album_cnt"),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub async fn get_tag_co_occurrences(&self, tag: &str, limit: i64) -> Vec<TagCoOccurrence> {
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT t2.tag as co_tag, COUNT(*) as cnt
|
||||
FROM album_tags t1 JOIN album_tags t2 ON t1.album_id = t2.album_id
|
||||
WHERE t1.tag = ? AND t2.tag != ? GROUP BY t2.tag ORDER BY cnt DESC LIMIT ?"#
|
||||
).bind(tag).bind(tag).bind(limit).fetch_all(&self.pool).await.unwrap_or_default();
|
||||
|
||||
let total = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM album_tags WHERE tag = ?")
|
||||
.bind(tag).fetch_one(&self.pool).await.unwrap_or(1);
|
||||
rows.iter().map(|r| {
|
||||
let cnt: i64 = r.get("cnt");
|
||||
TagCoOccurrence {
|
||||
tag: tag.to_string(), co_tag: r.get("co_tag"),
|
||||
count: cnt, score: cnt as f64 / total as f64,
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub async fn search_albums_by_tag(&self, tag: &str) -> Vec<AlbumInfo> {
|
||||
sqlx::query(
|
||||
r#"SELECT a.id, a.title, a.document, a.description, a.cover_image_id, a.image_count, a.created_at
|
||||
FROM albums a JOIN album_tags t ON a.id = t.album_id WHERE t.tag = ? ORDER BY a.created_at DESC"#
|
||||
).bind(tag).fetch_all(&self.pool).await.unwrap_or_default()
|
||||
.iter().map(|r| AlbumInfo {
|
||||
id: Uuid::parse_str(&r.get::<String, _>("id")).unwrap_or_else(|_| Uuid::nil()),
|
||||
title: r.get("title"), document: r.get("document"),
|
||||
description: r.get("description"), cover_image_id: r.get("cover_image_id"),
|
||||
image_count: r.get("image_count"), created_at: r.get("created_at"),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
// ── 统计 ──
|
||||
|
||||
pub async fn get_metadata_stats(&self) -> MetadataStats {
|
||||
MetadataStats {
|
||||
total_persons: sqlx::query_scalar("SELECT COUNT(*) FROM persons").fetch_one(&self.pool).await.unwrap_or(0),
|
||||
total_aliases: sqlx::query_scalar("SELECT COUNT(*) FROM person_aliases").fetch_one(&self.pool).await.unwrap_or(0),
|
||||
total_albums_with_person: sqlx::query_scalar("SELECT COUNT(*) FROM albums WHERE person_name_original IS NOT NULL AND person_name_original != ''").fetch_one(&self.pool).await.unwrap_or(0),
|
||||
total_albums_without_person: sqlx::query_scalar("SELECT COUNT(*) FROM albums WHERE person_name_original IS NULL OR person_name_original = ''").fetch_one(&self.pool).await.unwrap_or(0),
|
||||
total_tags: sqlx::query_scalar("SELECT COUNT(*) FROM album_tags").fetch_one(&self.pool).await.unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
// ── 写入 ──
|
||||
|
||||
pub async fn insert_person(&self, name: &str, display_name: Option<&str>) -> i64 {
|
||||
if let Some(p) = self.get_person_by_name(name).await { return p.id; }
|
||||
sqlx::query("INSERT OR IGNORE INTO persons (name, display_name) VALUES (?, ?)")
|
||||
.bind(name).bind(display_name).execute(&self.pool).await.ok();
|
||||
self.get_person_by_name(name).await.map(|p| p.id).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub async fn insert_person_alias(&self, person_id: i64, alias_type: &str, alias_name: &str) {
|
||||
sqlx::query("INSERT OR IGNORE INTO person_aliases (person_id, alias_type, alias_name) VALUES (?, ?, ?)")
|
||||
.bind(person_id).bind(alias_type).bind(alias_name).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
pub async fn insert_person_album(&self, person_id: i64, album_id: &str) {
|
||||
sqlx::query("INSERT OR IGNORE INTO person_albums (person_id, album_id) VALUES (?, ?)")
|
||||
.bind(person_id).bind(album_id).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
pub async fn delete_person_albums(&self, person_id: i64) {
|
||||
sqlx::query("DELETE FROM person_albums WHERE person_id = ?").bind(person_id).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
pub async fn update_album_person(&self, album_id: &str, person_name_original: &str, person_name_cleaned: &str) {
|
||||
sqlx::query("UPDATE albums SET person_name_original = ?, person_name_cleaned = ?, processed_at = datetime('now') WHERE id = ?")
|
||||
.bind(person_name_original).bind(person_name_cleaned).bind(album_id).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
pub async fn update_album_tags(&self, album_id: &str, tags_json: &str, all_words_json: &str) {
|
||||
sqlx::query("UPDATE albums SET tags = ?, all_words = ?, processed_at = datetime('now') WHERE id = ?")
|
||||
.bind(tags_json).bind(all_words_json).bind(album_id).execute(&self.pool).await.ok();
|
||||
sqlx::query("DELETE FROM album_tags WHERE album_id = ?").bind(album_id).execute(&self.pool).await.ok();
|
||||
if let Ok(tags) = serde_json::from_str::<Vec<String>>(tags_json) {
|
||||
for tag in &tags {
|
||||
sqlx::query("INSERT OR IGNORE INTO album_tags (album_id, tag) VALUES (?, ?)")
|
||||
.bind(album_id).bind(tag).execute(&self.pool).await.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_person_counts(&self, person_id: i64) {
|
||||
sqlx::query(
|
||||
r#"UPDATE persons SET total_albums = (SELECT COUNT(*) FROM person_albums WHERE person_id = ?),
|
||||
total_images = (SELECT COALESCE(SUM(a.image_count), 0) FROM albums a JOIN person_albums pa ON a.id = pa.album_id WHERE pa.person_id = ?),
|
||||
updated_at = datetime('now') WHERE id = ?"#
|
||||
).bind(person_id).bind(person_id).bind(person_id).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
/// 获取所有相册 ID 集合(用于迁移)
|
||||
pub async fn get_all_album_ids(&self) -> Vec<String> {
|
||||
sqlx::query_scalar::<_, String>("SELECT id FROM albums").fetch_all(&self.pool).await.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
161
src/db/migration.rs
Normal file
161
src/db/migration.rs
Normal file
@@ -0,0 +1,161 @@
|
||||
//! 从老数据库(Python 项目 persons.db)迁移元数据到新数据库
|
||||
//!
|
||||
//! 迁移策略:
|
||||
//! 1. 读取老 DB 的 persons/aliases/albums 数据
|
||||
//! 2. 按 album_id 对齐新 DB 中的相册
|
||||
//! 3. 批量插入人员、别名、标签、关联
|
||||
|
||||
use super::Database;
|
||||
use sqlx::sqlite::SqlitePoolOptions;
|
||||
use sqlx::Row;
|
||||
|
||||
/// 迁移结果统计
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MigrationStats {
|
||||
pub persons_imported: usize,
|
||||
pub persons_skipped: usize,
|
||||
pub aliases_imported: usize,
|
||||
pub albums_updated: usize,
|
||||
pub albums_missing: usize,
|
||||
pub tags_imported: usize,
|
||||
pub person_albums_created: usize,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// 从老数据库迁移元数据
|
||||
pub async fn migrate_from_old_db(&self, old_db_path: &str) -> Result<MigrationStats, String> {
|
||||
if !std::path::Path::new(old_db_path).exists() {
|
||||
return Err(format!("老数据库不存在: {}", old_db_path));
|
||||
}
|
||||
|
||||
println!("[迁移] 打开老数据库: {}", old_db_path);
|
||||
let old_pool = SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&format!("sqlite:{}", old_db_path))
|
||||
.await
|
||||
.map_err(|e| format!("连接老数据库失败: {}", e))?;
|
||||
|
||||
// 先获取新 DB 中所有相册 ID
|
||||
let new_album_ids: std::collections::HashSet<String> = self.get_all_album_ids().await.into_iter().collect();
|
||||
println!("[迁移] 新数据库中有 {} 个相册", new_album_ids.len());
|
||||
|
||||
let mut stats = MigrationStats::default();
|
||||
|
||||
// ── 1. 迁移人员 ──
|
||||
println!("[迁移] 步骤 1/4: 迁移人员...");
|
||||
let old_persons: Vec<(i64, String, Option<String>, i64, i64, Option<String>)> = sqlx::query(
|
||||
"SELECT id, name, display_name, total_albums, total_images, original_names FROM persons"
|
||||
).fetch_all(&old_pool).await.map_err(|e| format!("读取老人员失败: {}", e))?
|
||||
.iter().map(|r| (
|
||||
r.get("id"), r.get("name"), r.get("display_name"),
|
||||
r.get("total_albums"), r.get("total_images"), r.get("original_names"),
|
||||
)).collect();
|
||||
|
||||
let mut old_to_new_person: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
|
||||
|
||||
for (old_pid, name, display_name, _albums, _images, original_names) in &old_persons {
|
||||
let new_pid = self.insert_person(name, display_name.as_deref()).await;
|
||||
if new_pid > 0 {
|
||||
old_to_new_person.insert(*old_pid, new_pid);
|
||||
// 更新 original_names
|
||||
if let Some(on) = original_names {
|
||||
sqlx::query("UPDATE persons SET original_names = ? WHERE id = ?")
|
||||
.bind(on).bind(new_pid).execute(&self.pool).await.ok();
|
||||
}
|
||||
stats.persons_imported += 1;
|
||||
} else {
|
||||
stats.persons_skipped += 1;
|
||||
}
|
||||
}
|
||||
println!("[迁移] 导入 {} 人,跳过 {} 人", stats.persons_imported, stats.persons_skipped);
|
||||
|
||||
// ── 2. 迁移别名 ──
|
||||
println!("[迁移] 步骤 2/4: 迁移别名...");
|
||||
let old_aliases: Vec<(i64, String, String)> = sqlx::query(
|
||||
"SELECT person_id, alias_type, alias_name FROM person_aliases"
|
||||
).fetch_all(&old_pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (r.get("person_id"), r.get("alias_type"), r.get("alias_name"))).collect();
|
||||
|
||||
for (old_pid, alias_type, alias_name) in &old_aliases {
|
||||
if let Some(&new_pid) = old_to_new_person.get(old_pid) {
|
||||
self.insert_person_alias(new_pid, alias_type, alias_name).await;
|
||||
stats.aliases_imported += 1;
|
||||
}
|
||||
}
|
||||
println!("[迁移] 导入 {} 个别名", stats.aliases_imported);
|
||||
|
||||
// ── 3. 迁移相册人员标签 ──
|
||||
println!("[迁移] 步骤 3/4: 迁移相册人员+标签...");
|
||||
let old_albums: Vec<(String, Option<String>, Option<String>, Option<String>, Option<String>, Option<String>)> = sqlx::query(
|
||||
"SELECT id, title, person_name_original, person_name_cleaned, tags, all_words FROM albums"
|
||||
).fetch_all(&old_pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (
|
||||
r.get("id"), r.get("title"), r.get("person_name_original"),
|
||||
r.get("person_name_cleaned"), r.get("tags"), r.get("all_words"),
|
||||
)).collect();
|
||||
|
||||
for (album_id, _title, person_orig, person_cleaned, tags, all_words) in &old_albums {
|
||||
if !new_album_ids.contains(album_id) {
|
||||
stats.albums_missing += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 更新人员信息
|
||||
if let (Some(po), Some(pc)) = (person_orig, person_cleaned) {
|
||||
if !po.is_empty() {
|
||||
self.update_album_person(album_id, po, pc).await;
|
||||
stats.albums_updated += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新标签
|
||||
if let Some(t) = tags {
|
||||
if t != "[]" && !t.is_empty() {
|
||||
let aw = all_words.clone().unwrap_or_else(|| "[]".to_string());
|
||||
self.update_album_tags(album_id, t, &aw).await;
|
||||
stats.tags_imported += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("[迁移] 更新 {} 个相册,{} 个不在新库中,{} 个标签导入",
|
||||
stats.albums_updated, stats.albums_missing, stats.tags_imported);
|
||||
|
||||
// ── 4. 迁移人物-相册关联 ──
|
||||
println!("[迁移] 步骤 4/4: 迁移人物-相册关联...");
|
||||
let old_person_albums: Vec<(i64, String)> = sqlx::query(
|
||||
"SELECT person_id, album_id FROM person_albums"
|
||||
).fetch_all(&old_pool).await.unwrap_or_default()
|
||||
.iter().map(|r| (r.get("person_id"), r.get("album_id"))).collect();
|
||||
|
||||
for (old_pid, album_id) in &old_person_albums {
|
||||
if let Some(&new_pid) = old_to_new_person.get(old_pid) {
|
||||
if new_album_ids.contains(album_id) {
|
||||
self.insert_person_album(new_pid, album_id).await;
|
||||
stats.person_albums_created += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("[迁移] 创建 {} 个关联", stats.person_albums_created);
|
||||
|
||||
// 更新所有人员的计数
|
||||
println!("[迁移] 更新人员统计...");
|
||||
for &new_pid in old_to_new_person.values() {
|
||||
self.update_person_counts(new_pid).await;
|
||||
}
|
||||
|
||||
println!("[迁移] ✅ 完成!");
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
/// 获取迁移统计摘要
|
||||
pub fn migration_summary(&self, stats: &MigrationStats) -> String {
|
||||
format!(
|
||||
"迁移完成:\n - 人员: {} 导入, {} 跳过\n - 别名: {} 导入\n - 相册: {} 更新, {} 缺失\n - 标签: {} 导入\n - 关联: {} 创建",
|
||||
stats.persons_imported, stats.persons_skipped,
|
||||
stats.aliases_imported,
|
||||
stats.albums_updated, stats.albums_missing,
|
||||
stats.tags_imported,
|
||||
stats.person_albums_created,
|
||||
)
|
||||
}
|
||||
}
|
||||
15
src/db/mod.rs
Normal file
15
src/db/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
//! 数据库操作层 — 按领域拆分
|
||||
|
||||
mod connection;
|
||||
pub mod album;
|
||||
pub mod image;
|
||||
pub mod favorite;
|
||||
pub mod metadata;
|
||||
pub mod migration;
|
||||
|
||||
pub use connection::Database;
|
||||
pub use album::*;
|
||||
pub use image::*;
|
||||
pub use favorite::*;
|
||||
pub use metadata::*;
|
||||
pub use migration::MigrationStats;
|
||||
Reference in New Issue
Block a user