use super::Database; use crate::models::*; use sqlx::Row; use uuid::Uuid; impl Database { // ── 查询 ── pub async fn get_all_albums(&self) -> Result, 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::("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"), tags: vec![], persons: vec![], } }).collect()) } /// 组合过滤搜索(懒加载):仅返回符合条件的相册,避免全量加载 /// /// 支持按 tag / person / 标题关键词 任意组合过滤(AND 关系)。 /// 参数传空字符串或 None 表示不过滤该维度。 /// 全参数为空时等价于 get_all_albums。 pub async fn search_albums_with_filters( &self, tag: Option<&str>, person: Option<&str>, title_q: Option<&str>, limit: i64, offset: i64, ) -> Result, sqlx::Error> { let has_tag = tag.map(|s| !s.is_empty()).unwrap_or(false); let has_person = person.map(|s| !s.is_empty()).unwrap_or(false); let has_q = title_q.map(|s| !s.is_empty()).unwrap_or(false); if !has_tag && !has_person && !has_q { // 无过滤条件 → 走缓存路径,这里回退到全量查询 return self.get_all_albums().await; } // 动态构建 SQL let sql = { let mut s = String::from( "SELECT DISTINCT a.id, a.title, a.document, a.description, \ a.cover_image_id, a.image_count, a.created_at \ FROM albums a" ); let mut joins = Vec::new(); let mut wheres = Vec::new(); if has_tag { joins.push("JOIN album_tags t ON a.id = t.album_id"); wheres.push("t.tag = ?"); } if has_person { joins.push("JOIN person_albums pa ON a.id = pa.album_id"); joins.push("JOIN persons p ON pa.person_id = p.id"); wheres.push("(p.name = ? OR p.name LIKE ?)"); } if has_q { wheres.push("a.title LIKE ?"); } for j in &joins { s.push(' '); s.push_str(j); } if !wheres.is_empty() { s.push_str(" WHERE "); s.push_str(&wheres.join(" AND ")); } s.push_str(" ORDER BY a.created_at DESC"); if limit > 0 { s.push_str(" LIMIT ? OFFSET ?"); } s }; let mut q = sqlx::query(&sql); if has_tag { q = q.bind(tag.unwrap()); } if has_person { let p = person.unwrap(); q = q.bind(p).bind(format!("%{}%", p)); } if has_q { q = q.bind(format!("%{}%", title_q.unwrap())); } if limit > 0 { q = q.bind(limit).bind(offset); } let rows = q.fetch_all(&self.pool).await?; Ok(rows.iter().map(|r| { AlbumInfo { id: Uuid::parse_str(&r.get::("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"), tags: vec![], persons: vec![], } }).collect()) } pub async fn get_album_with_images(&self, album_id: Uuid) -> Result, 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::("id"); let id = Uuid::parse_str(&id_str).unwrap_or_else(|_| Uuid::nil()); let cover = row.get::, _>("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"), }; 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::("id")).unwrap_or_else(|_| Uuid::nil()); let aid = Uuid::parse_str(&r.get::("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 { let rows = sqlx::query( r#"SELECT id, title, cover_image_id, image_count FROM albums"# ).fetch_all(&self.pool).await.unwrap_or_default(); rows.iter().map(|r| AlbumMeta { id: r.get("id"), title: r.get("title"), cover_image_id: r.get("cover_image_id"), image_count: r.get("image_count"), }).collect() } /// 按 ID 列表批量查询相册元数据 pub async fn get_albums_by_ids(&self, ids: &[String]) -> Vec { if ids.is_empty() { return Vec::new(); } let placeholders: Vec = (0..ids.len()).map(|_| "?".to_string()).collect(); let sql = format!( "SELECT id, title, cover_image_id, image_count FROM albums WHERE id IN ({})", placeholders.join(", ") ); let mut query = sqlx::query(&sql); for id in ids { query = query.bind(id); } let rows = query.fetch_all(&self.pool).await.unwrap_or_default(); rows.iter().map(|r| AlbumMeta { id: r.get("id"), title: r.get("title"), cover_image_id: r.get("cover_image_id"), image_count: r.get("image_count"), }).collect() } /// 获取所有未处理的相册 ID(processed_at IS NULL),用于管线收集新相册 pub async fn get_unprocessed_album_ids(&self) -> Vec { let rows = sqlx::query_scalar::<_, String>( "SELECT id FROM albums WHERE processed_at IS NULL" ).fetch_all(&self.pool).await.unwrap_or_default(); rows } // ── 写入 ── pub async fn create_album(&self, album: CreateAlbum) -> Result { let _guard = self.write_lock.lock().await; 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> { let _guard = self.write_lock.lock().await; 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 { sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM images WHERE album_id = ?") .bind(album_id.to_string()).fetch_one(&self.pool).await } }