|
| 1 | +use super::{post::PostService, search_query::SearchQuery}; |
| 2 | +use anyhow::Context; |
| 3 | +use r2d2::Pool; |
| 4 | +use r2d2_sqlite::SqliteConnectionManager; |
| 5 | +use rusqlite::Row; |
| 6 | +use tokio::task; |
| 7 | + |
| 8 | +#[derive(Clone, Debug)] |
| 9 | +pub struct SearchService { |
| 10 | + pool: Pool<SqliteConnectionManager>, |
| 11 | +} |
| 12 | + |
| 13 | +impl SearchService { |
| 14 | + pub fn new(pool: Pool<SqliteConnectionManager>) -> Self { |
| 15 | + Self { pool } |
| 16 | + } |
| 17 | + |
| 18 | + fn row_to_post(row: &Row) -> rusqlite::Result<crate::post::Post> { |
| 19 | + PostService::row_to_post(row) |
| 20 | + } |
| 21 | + |
| 22 | + pub async fn search( |
| 23 | + &self, |
| 24 | + query: &SearchQuery, |
| 25 | + page: usize, |
| 26 | + per_page: usize, |
| 27 | + ) -> anyhow::Result<(Vec<crate::post::Post>, usize)> { |
| 28 | + // Create a full clone of the query data to move into the thread |
| 29 | + let owned_query = SearchQuery { |
| 30 | + text_query: query.text_query.clone(), |
| 31 | + tags: query.tags.clone(), |
| 32 | + from_date: query.from_date.clone(), |
| 33 | + to_date: query.to_date.clone(), |
| 34 | + }; |
| 35 | + let offset = (page - 1) * per_page; |
| 36 | + let pool = self.pool.clone(); |
| 37 | + |
| 38 | + let (posts, total) = task::spawn_blocking(move || { |
| 39 | + let conn = pool.get()?; |
| 40 | + let base_query = if owned_query.text_query.is_empty() { |
| 41 | + "FROM posts".to_string() |
| 42 | + } else { |
| 43 | + "FROM posts INNER JOIN posts_fts ON posts.rowid = posts_fts.rowid".to_string() |
| 44 | + }; |
| 45 | + |
| 46 | + let mut conditions = vec![]; |
| 47 | + let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![]; |
| 48 | + |
| 49 | + if !owned_query.text_query.is_empty() { |
| 50 | + conditions.push("posts_fts MATCH ?".to_string()); |
| 51 | + params.push(Box::new(owned_query.text_query.clone())); |
| 52 | + } |
| 53 | + |
| 54 | + for tag in &owned_query.tags { |
| 55 | + conditions.push("EXISTS (SELECT 1 FROM json_each(posts.tags) WHERE value = ?)".to_string()); |
| 56 | + params.push(Box::new(tag)); |
| 57 | + } |
| 58 | + |
| 59 | + if let Some(date) = &owned_query.from_date { |
| 60 | + conditions.push("posts.date >= ?".to_string()); |
| 61 | + params.push(Box::new(date)); |
| 62 | + } |
| 63 | + if let Some(date) = &owned_query.to_date { |
| 64 | + conditions.push("posts.date <= ?".to_string()); |
| 65 | + params.push(Box::new(date)); |
| 66 | + } |
| 67 | + |
| 68 | + let where_clause = if !conditions.is_empty() { |
| 69 | + format!("WHERE {}", conditions.join(" AND ")) |
| 70 | + } else { |
| 71 | + "".to_string() |
| 72 | + }; |
| 73 | + |
| 74 | + let order_clause = if owned_query.text_query.is_empty() { |
| 75 | + "ORDER BY date DESC".to_string() |
| 76 | + } else { |
| 77 | + "ORDER BY rank".to_string() |
| 78 | + }; |
| 79 | + |
| 80 | + // Prepare count query first (borrows params immutably) |
| 81 | + let count_query = format!( |
| 82 | + "SELECT COUNT(*) |
| 83 | + {} |
| 84 | + {}", |
| 85 | + base_query, where_clause |
| 86 | + ); |
| 87 | + let total: i64 = conn.query_row( |
| 88 | + &count_query, |
| 89 | + rusqlite::params_from_iter(params.iter().map(|p| &**p)), |
| 90 | + |r| r.get(0), |
| 91 | + )?; |
| 92 | + |
| 93 | + // Main query to fetch posts (takes ownership of params) |
| 94 | + let posts_query = format!( |
| 95 | + "SELECT posts.* |
| 96 | + {} |
| 97 | + {} |
| 98 | + {} |
| 99 | + LIMIT ? OFFSET ?", |
| 100 | + base_query, where_clause, order_clause |
| 101 | + ); |
| 102 | + |
| 103 | + let mut stmt = conn.prepare(&posts_query)?; |
| 104 | + params.push(Box::new(per_page as i64)); |
| 105 | + params.push(Box::new(offset as i64)); |
| 106 | + |
| 107 | + // Execute query and collect results |
| 108 | + let iter = stmt.query_map( |
| 109 | + rusqlite::params_from_iter(params.iter().map(|p| &**p)), |
| 110 | + Self::row_to_post, |
| 111 | + )?; |
| 112 | + let mut posts = Vec::new(); |
| 113 | + for post in iter { |
| 114 | + posts.push(post?); |
| 115 | + } |
| 116 | + |
| 117 | + Ok::<_, anyhow::Error>((posts, total as usize)) |
| 118 | + }) |
| 119 | + .await? |
| 120 | + .context("Search execution failed")?; |
| 121 | + |
| 122 | + let post_service = PostService::new(self.pool.clone()); |
| 123 | + let posts_with_commits = post_service.bulk_convert_to_posts(posts).await?; |
| 124 | + |
| 125 | + Ok((posts_with_commits, total)) |
| 126 | + } |
| 127 | +} |
0 commit comments