56 lines
1.3 KiB
Rust
56 lines
1.3 KiB
Rust
use serde::Serialize;
|
|
use sqlx::{sqlite::SqliteQueryResult, FromRow, SqlitePool};
|
|
|
|
#[derive(FromRow, Serialize, Clone)]
|
|
pub struct Family {
|
|
id: i64,
|
|
}
|
|
|
|
#[derive(Serialize, Clone)]
|
|
pub struct FamilyWithMembers {
|
|
id: i64,
|
|
names: Option<String>,
|
|
}
|
|
|
|
impl Family {
|
|
pub async fn all(db: &SqlitePool) -> Vec<Self> {
|
|
sqlx::query_as!(Self, "SELECT id FROM role")
|
|
.fetch_all(db)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
pub async fn new(db: &SqlitePool) -> i64 {
|
|
let result: SqliteQueryResult = sqlx::query("INSERT INTO family DEFAULT VALUES")
|
|
.execute(db)
|
|
.await
|
|
.unwrap();
|
|
|
|
result.last_insert_rowid()
|
|
}
|
|
|
|
pub async fn all_with_members(db: &SqlitePool) -> Vec<FamilyWithMembers> {
|
|
sqlx::query_as!(
|
|
FamilyWithMembers,
|
|
"
|
|
SELECT
|
|
family.id as id,
|
|
GROUP_CONCAT(user.name, ', ') as names
|
|
FROM family
|
|
LEFT JOIN
|
|
user ON family.id = user.family_id
|
|
GROUP BY family.id;"
|
|
)
|
|
.fetch_all(db)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
pub async fn find_by_id(db: &SqlitePool, id: i32) -> Option<Self> {
|
|
sqlx::query_as!(Self, "SELECT id FROM family WHERE id like ?", id)
|
|
.fetch_one(db)
|
|
.await
|
|
.ok()
|
|
}
|
|
}
|