From cd316de7293f5a31f125fb62611af4df7259aff4 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Mon, 3 Oct 2022 21:48:52 +0200 Subject: Add model search by fields --- src/models/model.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'src/models/model.rs') diff --git a/src/models/model.rs b/src/models/model.rs index 47864d9..30ccc84 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -39,6 +39,13 @@ pub struct ModelCreate { pub material: Option, } +/// Payload used for model searching +#[derive(Deserialize)] +pub struct ModelFilter { + /// Stands for "query" + pub q: String, +} + #[derive(Serialize, sqlx::FromRow)] pub struct ModelUser { pub id: i32, @@ -203,6 +210,34 @@ impl Model { Ok(rows) } + /// Filter models by some cols + pub async fn filter(page: i64, query: String) -> Result, AppError> { + let pool = unsafe { get_client() }; + let rows: Vec = sqlx::query_as( + r#" + SELECT + models.*, + json_build_object('id', users.id, 'name', users.name, 'email', users.email, 'username', users.username, 'is_staff', users.is_staff, 'avatar', users.avatar) as author, + json_agg(uploads.*) filter (where uploads.* is not null) as uploads, + json_agg(likes.*) filter (where likes.* is not null) as likes + FROM models + JOIN users ON users.id = models.author_id + LEFT JOIN uploads ON uploads.model_id = models.id + LEFT JOIN likes ON likes.model_id = models.id + WHERE models.name ILIKE $1 OR description ILIKE $1 OR printer ILIKE $1 OR material ILIKE $1 + GROUP BY models.id, users.id + ORDER BY id DESC + LIMIT $2 OFFSET $3 + "#) + .bind(format!("%{}%", query)) + .bind(CONFIG.page_limit) + .bind(CONFIG.page_limit * page) + .fetch_all(pool) + .await?; + + Ok(rows) + } + /// List author's models pub async fn list_from_author(page: i64, author: i32) -> Result, AppError> { let pool = unsafe { get_client() }; @@ -269,6 +304,23 @@ impl Model { let count: i64 = cursor.try_get(0).unwrap(); Ok(count) } + + /// Return the number of models filtered by query + pub async fn count_filter(query: String) -> Result { + let pool = unsafe { get_client() }; + let cursor = sqlx::query( + r#" + SELECT COUNT(id) as count FROM models + WHERE models.name ILIKE $1 OR description ILIKE $1 OR printer ILIKE $1 OR material ILIKE $1 + "# + ) + .bind(format!("%{}%", query)) + .fetch_one(pool) + .await?; + + let count: i64 = cursor.try_get(0).unwrap(); + Ok(count) + } } impl ModelUser { -- cgit v1.2.3-71-g8e6c