Files
lisette/src/db.rs
T
Romulus21andClaude Opus 5.5 6c593b0201 Enregistre les changements d'articles par lots en arrière-plan
Cocher, ajouter, modifier ou supprimer un article s'affiche aussitôt :
le changement attend dans une file, fusionné avec les précédents, puis
part avec les autres en une seule requête, une à la fois. Le serveur
applique le lot dans une transaction et résout les ids temporaires des
articles ajoutés. Sans réseau, le lot est gardé et renvoyé plus tard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 08:47:25 +02:00

617 lines
21 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow};
use sqlx::{Row, SqliteConnection};
use std::str::FromStr;
use crate::model::{
Account, Category, Icon, Item, ItemInput, ItemOp, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
};
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
let options = SqliteConnectOptions::from_str(url)?
.create_if_missing(true)
.foreign_keys(true);
// Each connection to `:memory:` opens a distinct database.
let max = if url.contains(":memory:") { 1 } else { 5 };
let pool = SqlitePoolOptions::new()
.max_connections(max)
.connect_with(options)
.await?;
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
fn decode<T>(value: Option<T>, column: &str) -> Result<T, sqlx::Error> {
value.ok_or_else(|| sqlx::Error::Decode(format!("invalid value in column `{column}`").into()))
}
fn list_from_row(row: &SqliteRow) -> Result<ShoppingList, sqlx::Error> {
Ok(ShoppingList {
id: row.try_get("id")?,
name: row.try_get("name")?,
color: decode(ListColor::parse(row.try_get("color")?), "color")?,
created_at: row.try_get("created_at")?,
is_owner: row.try_get("is_owner")?,
owner_name: row.try_get("owner_name")?,
})
}
fn item_from_row(row: &SqliteRow) -> Result<Item, sqlx::Error> {
let amount: Option<f64> = row.try_get("amount")?;
let unit: Option<String> = row.try_get("unit")?;
let quantity = match (amount, unit) {
(Some(amount), Some(unit)) => Some(Quantity {
amount,
unit: decode(Unit::parse(&unit), "unit")?,
}),
_ => None,
};
Ok(Item {
id: row.try_get("id")?,
list_id: row.try_get("list_id")?,
name: row.try_get("name")?,
quantity,
icon: decode(Icon::parse(row.try_get("icon")?), "icon")?,
category: decode(Category::parse(row.try_get("category")?), "category")?,
checked: row.try_get("checked")?,
})
}
fn user_from_row(row: &SqliteRow) -> Result<User, sqlx::Error> {
Ok(User {
id: row.try_get("id")?,
name: row.try_get("name")?,
email: row.try_get("email")?,
is_admin: row.try_get("is_admin")?,
})
}
// --- Users & sessions -------------------------------------------------------
/// Products offered as suggestions to every new account.
const STARTER_CATALOG: &[(&str, Icon, Category)] = &[
("Beurre", Icon::Cheese, Category::Frais),
("Œufs", Icon::Egg, Category::Frais),
("Citrons", Icon::Lemon, Category::FruitsLegumes),
("Pain complet", Icon::Bread, Category::Boulangerie),
("Bananes", Icon::Banana, Category::FruitsLegumes),
("Café en grains", Icon::Coffee, Category::Epicerie),
];
/// Creates the account with a first list and starter suggestions; the very
/// first account is an admin. Fails with a unique violation if the email is taken.
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
let mut tx = pool.begin().await?;
let user_id: i64 = sqlx::query(
"INSERT INTO users (email, name, password_hash, is_admin)
VALUES (?, ?, ?, NOT EXISTS (SELECT 1 FROM users)) RETURNING id",
)
.bind(email)
.bind(name)
.bind(password_hash)
.fetch_one(&mut *tx)
.await?
.try_get("id")?;
// Lists created before accounts existed go to the first user.
let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL")
.bind(user_id)
.execute(&mut *tx)
.await?
.rows_affected();
if claimed == 0 {
insert_list(&mut tx, user_id, "Courses de la semaine", ListColor::Lime).await?;
}
for (product, icon, category) in STARTER_CATALOG {
sqlx::query("INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)")
.bind(user_id)
.bind(product)
.bind(icon.as_str())
.bind(category.as_str())
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(user_id)
}
/// The user and their password hash.
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> {
sqlx::query("SELECT id, name, email, is_admin, password_hash FROM users WHERE email = ?")
.bind(email)
.fetch_optional(pool)
.await?
.map(|row| Ok((user_from_row(&row)?, row.try_get("password_hash")?)))
.transpose()
}
pub async fn create_session(pool: &SqlitePool, token_hash: &str, user_id: i64, days: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM sessions WHERE expires_at <= datetime('now')")
.execute(pool)
.await?;
sqlx::query("INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, datetime('now', ?))")
.bind(token_hash)
.bind(user_id)
.bind(format!("+{days} days"))
.execute(pool)
.await?;
Ok(())
}
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
sqlx::query(
"SELECT u.id, u.name, u.email, u.is_admin FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
)
.bind(token_hash)
.fetch_optional(pool)
.await?
.as_ref()
.map(user_from_row)
.transpose()
}
pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM sessions WHERE token_hash = ?")
.bind(token_hash)
.execute(pool)
.await?;
Ok(())
}
// --- Administration ---------------------------------------------------------
pub async fn has_users(pool: &SqlitePool) -> Result<bool, sqlx::Error> {
sqlx::query("SELECT EXISTS (SELECT 1 FROM users) AS has_users")
.fetch_one(pool)
.await?
.try_get("has_users")
}
pub async fn accounts(pool: &SqlitePool) -> Result<Vec<Account>, sqlx::Error> {
sqlx::query("SELECT id, name, email, is_admin, date(created_at) AS created_at FROM users ORDER BY id")
.fetch_all(pool)
.await?
.iter()
.map(|row| Ok(Account { user: user_from_row(row)?, created_at: row.try_get("created_at")? }))
.collect()
}
/// Fails with a unique violation if the email is taken.
pub async fn update_user(pool: &SqlitePool, id: i64, name: &str, email: &str, is_admin: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE users SET name = ?, email = ?, is_admin = ? WHERE id = ?")
.bind(name)
.bind(email)
.bind(is_admin)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
/// Changes the password and signs the user out everywhere.
pub async fn set_password(pool: &SqlitePool, id: i64, password_hash: &str) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("UPDATE users SET password_hash = ? WHERE id = ?")
.bind(password_hash)
.bind(id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = ?")
.bind(id)
.execute(&mut *tx)
.await?;
tx.commit().await
}
/// Deletes the account with its sessions, suggestions and the lists it owns.
pub async fn delete_user(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM users WHERE id = ?").bind(id).execute(pool).await?;
Ok(())
}
// --- Lists & sharing --------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
Owner,
Member,
}
pub async fn list_role(pool: &SqlitePool, user_id: i64, list_id: i64) -> Result<Option<Role>, sqlx::Error> {
let row = sqlx::query(
"SELECT owner_id = ?1 AS is_owner FROM lists l
WHERE l.id = ?2 AND (
l.owner_id = ?1
OR EXISTS (SELECT 1 FROM list_members m WHERE m.list_id = l.id AND m.user_id = ?1)
)",
)
.bind(user_id)
.bind(list_id)
.fetch_optional(pool)
.await?;
row.map(|row| Ok(if row.try_get("is_owner")? { Role::Owner } else { Role::Member }))
.transpose()
}
/// Lists owned by or shared with the user.
pub async fn lists(pool: &SqlitePool, user_id: i64) -> Result<Vec<ShoppingList>, sqlx::Error> {
sqlx::query(
"SELECT l.id, l.name, l.color, l.created_at, l.owner_id = ?1 AS is_owner, u.name AS owner_name
FROM lists l JOIN users u ON u.id = l.owner_id
WHERE l.owner_id = ?1
OR EXISTS (SELECT 1 FROM list_members m WHERE m.list_id = l.id AND m.user_id = ?1)
ORDER BY l.id",
)
.bind(user_id)
.fetch_all(pool)
.await?
.iter()
.map(list_from_row)
.collect()
}
async fn insert_list(conn: &mut SqliteConnection, owner_id: i64, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
sqlx::query("INSERT INTO lists (name, color, owner_id) VALUES (?, ?, ?) RETURNING id")
.bind(name)
.bind(color.as_str())
.bind(owner_id)
.fetch_one(conn)
.await?
.try_get("id")
}
pub async fn create_list(pool: &SqlitePool, owner_id: i64, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
insert_list(&mut *pool.acquire().await?, owner_id, name, color).await
}
pub async fn rename_list(pool: &SqlitePool, id: i64, name: &str) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE lists SET name = ? WHERE id = ?")
.bind(name)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM lists WHERE id = ?").bind(id).execute(pool).await?;
Ok(())
}
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
sqlx::query(
"SELECT u.id, u.name, u.email, u.is_admin FROM list_members m JOIN users u ON u.id = m.user_id
WHERE m.list_id = ? ORDER BY u.name",
)
.bind(list_id)
.fetch_all(pool)
.await?
.iter()
.map(|row| {
let user = user_from_row(row)?;
Ok(Member { user_id: user.id, name: user.name, email: user.email })
})
.collect()
}
pub async fn add_member(pool: &SqlitePool, list_id: i64, user_id: i64) -> Result<(), sqlx::Error> {
sqlx::query("INSERT OR IGNORE INTO list_members (list_id, user_id) VALUES (?, ?)")
.bind(list_id)
.bind(user_id)
.execute(pool)
.await?;
Ok(())
}
pub async fn remove_member(pool: &SqlitePool, list_id: i64, user_id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM list_members WHERE list_id = ? AND user_id = ?")
.bind(list_id)
.bind(user_id)
.execute(pool)
.await?;
Ok(())
}
/// Everyone who can see the list: its owner and members.
pub async fn list_audience(pool: &SqlitePool, list_id: i64) -> Result<Vec<i64>, sqlx::Error> {
sqlx::query(
"SELECT owner_id AS user_id FROM lists WHERE id = ?1 AND owner_id IS NOT NULL
UNION SELECT user_id FROM list_members WHERE list_id = ?1",
)
.bind(list_id)
.fetch_all(pool)
.await?
.iter()
.map(|row| row.try_get("user_id"))
.collect()
}
// --- Items ------------------------------------------------------------------
pub async fn items(pool: &SqlitePool, list_id: i64) -> Result<Vec<Item>, sqlx::Error> {
sqlx::query(
"SELECT id, list_id, name, amount, unit, icon, category, checked
FROM items WHERE list_id = ? ORDER BY id",
)
.bind(list_id)
.fetch_all(pool)
.await?
.iter()
.map(item_from_row)
.collect()
}
pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result<Option<i64>, sqlx::Error> {
sqlx::query("SELECT list_id FROM items WHERE id = ?")
.bind(item_id)
.fetch_optional(pool)
.await?
.map(|row| row.try_get("list_id"))
.transpose()
}
/// Remembers the product in the user's catalog so it can be suggested later.
async fn record_in_catalog(conn: &mut SqliteConnection, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
ON CONFLICT(user_id, name) DO UPDATE SET
icon = excluded.icon,
category = excluded.category,
use_count = use_count + 1",
)
.bind(user_id)
.bind(&input.name)
.bind(input.icon.as_str())
.bind(input.category.as_str())
.execute(&mut *conn)
.await?;
Ok(())
}
async fn add_item(conn: &mut SqliteConnection, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
let row = sqlx::query(
"INSERT INTO items (list_id, name, amount, unit, icon, category)
VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
)
.bind(list_id)
.bind(&input.name)
.bind(input.quantity.map(|q| q.amount))
.bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str())
.bind(input.category.as_str())
.fetch_one(&mut *conn)
.await?;
record_in_catalog(conn, user_id, input).await?;
row.try_get("id")
}
async fn update_item(conn: &mut SqliteConnection, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query(
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
)
.bind(&input.name)
.bind(input.quantity.map(|q| q.amount))
.bind(input.quantity.map(|q| q.unit.as_str()))
.bind(input.icon.as_str())
.bind(input.category.as_str())
.bind(id)
.execute(conn)
.await?;
Ok(())
}
async fn delete_item(conn: &mut SqliteConnection, id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(conn).await?;
Ok(())
}
async fn set_checked(conn: &mut SqliteConnection, id: i64, checked: bool) -> Result<(), sqlx::Error> {
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
.bind(checked)
.bind(id)
.execute(conn)
.await?;
Ok(())
}
/// Applies the changes, in order, in one transaction. Ops may target items
/// added earlier in the batch by their temporary id; returns the
/// (temporary id, real id) of each added item.
pub async fn apply_item_ops(pool: &SqlitePool, user_id: i64, ops: &[ItemOp]) -> Result<Vec<(i64, i64)>, sqlx::Error> {
let mut tx = pool.begin().await?;
let mut created: Vec<(i64, i64)> = Vec::new();
for op in ops {
let id = created
.iter()
.find(|&&(temp, _)| temp == op.id())
.map_or(op.id(), |&(_, real)| real);
match op {
ItemOp::Add { id: temp, list_id, input } => {
created.push((*temp, add_item(&mut tx, user_id, *list_id, input).await?));
}
ItemOp::Update { input, .. } => update_item(&mut tx, id, input).await?,
ItemOp::Delete { .. } => delete_item(&mut tx, id).await?,
ItemOp::SetChecked { checked, .. } => set_checked(&mut tx, id, *checked).await?,
}
}
tx.commit().await?;
Ok(created)
}
/// The user's most used products not already on the list.
pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
sqlx::query(
"SELECT name, icon, category FROM catalog c
WHERE c.user_id = ? AND NOT EXISTS (
SELECT 1 FROM items i WHERE i.list_id = ? AND i.name = c.name COLLATE NOCASE
)
ORDER BY use_count DESC, name
LIMIT ?",
)
.bind(user_id)
.bind(list_id)
.bind(limit)
.fetch_all(pool)
.await?
.iter()
.map(|row| {
Ok(Suggestion {
name: row.try_get("name")?,
icon: decode(Icon::parse(row.try_get("icon")?), "icon")?,
category: decode(Category::parse(row.try_get("category")?), "category")?,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
async fn pool() -> SqlitePool {
connect("sqlite::memory:").await.unwrap()
}
/// The in-memory pool has a single connection: drop it before using the pool.
async fn conn(pool: &SqlitePool) -> sqlx::pool::PoolConnection<sqlx::Sqlite> {
pool.acquire().await.unwrap()
}
async fn user(pool: &SqlitePool, email: &str) -> i64 {
register(pool, email, "Test", "hash").await.unwrap()
}
fn input(name: &str) -> ItemInput {
ItemInput {
name: name.into(),
quantity: Some(Quantity { amount: 3.0, unit: Unit::Piece }),
icon: Icon::Apple,
category: Category::FruitsLegumes,
}
}
#[tokio::test]
async fn first_user_claims_seed_list_others_get_their_own() {
let pool = pool().await;
let first = user(&pool, "a@x.fr").await;
let second = user(&pool, "b@x.fr").await;
let a = lists(&pool, first).await.unwrap();
let b = lists(&pool, second).await.unwrap();
assert_eq!(a.len(), 1);
assert_eq!(b.len(), 1);
assert_ne!(a[0].id, b[0].id);
assert_eq!(list_role(&pool, second, a[0].id).await.unwrap(), None);
}
#[tokio::test]
async fn duplicate_email_is_rejected_case_insensitively() {
let pool = pool().await;
user(&pool, "a@x.fr").await;
assert!(register(&pool, "A@X.fr", "Autre", "hash").await.is_err());
}
#[tokio::test]
async fn sessions_resolve_to_user() {
let pool = pool().await;
let id = user(&pool, "a@x.fr").await;
create_session(&pool, "tok", id, 30).await.unwrap();
assert_eq!(user_by_session(&pool, "tok").await.unwrap().unwrap().id, id);
delete_session(&pool, "tok").await.unwrap();
assert!(user_by_session(&pool, "tok").await.unwrap().is_none());
}
#[tokio::test]
async fn sharing_grants_member_access() {
let pool = pool().await;
let owner = user(&pool, "a@x.fr").await;
let friend = user(&pool, "b@x.fr").await;
let list = create_list(&pool, owner, "Apéro", ListColor::Pink).await.unwrap();
add_member(&pool, list, friend).await.unwrap();
assert_eq!(list_role(&pool, friend, list).await.unwrap(), Some(Role::Member));
assert_eq!(list_role(&pool, owner, list).await.unwrap(), Some(Role::Owner));
let shared = lists(&pool, friend).await.unwrap();
assert!(shared.iter().any(|l| l.id == list && !l.is_owner && l.owner_name == "Test"));
assert_eq!(members(&pool, list).await.unwrap().len(), 1);
remove_member(&pool, list, friend).await.unwrap();
assert_eq!(list_role(&pool, friend, list).await.unwrap(), None);
}
#[tokio::test]
async fn item_crud_and_toggle() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
let id = add_item(&mut *conn(&pool).await, me, list, &input("Avocats")).await.unwrap();
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
let mut edited = input("Avocats");
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
update_item(&mut *conn(&pool).await, id, &edited).await.unwrap();
set_checked(&mut *conn(&pool).await, id, true).await.unwrap();
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].quantity.unwrap().label(), "×4");
assert!(all[0].checked);
delete_item(&mut *conn(&pool).await, id).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}
#[tokio::test]
async fn batch_resolves_temporary_ids() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
let mut edited = input("Pommes");
edited.quantity = None;
let ops = [
ItemOp::Add { id: -1, list_id: list, input: input("Pommes") },
ItemOp::Add { id: -2, list_id: list, input: input("Poires") },
ItemOp::Update { id: -1, input: edited },
ItemOp::SetChecked { id: -1, checked: true },
ItemOp::Delete { id: -2 },
];
let created = apply_item_ops(&pool, me, &ops).await.unwrap();
assert_eq!(created.len(), 2);
let all = items(&pool, list).await.unwrap();
assert_eq!(all.len(), 1);
assert_eq!(all[0].id, created[0].1);
assert_eq!(all[0].quantity, None);
assert!(all[0].checked);
}
#[tokio::test]
async fn suggestions_skip_items_on_list() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
add_item(&mut *conn(&pool).await, me, list, &input("beurre")).await.unwrap();
let names: Vec<_> = suggestions(&pool, me, list, 3)
.await
.unwrap()
.into_iter()
.map(|s| s.name)
.collect();
assert!(!names.iter().any(|n| n.eq_ignore_ascii_case("beurre")));
assert_eq!(names.len(), 3);
}
#[tokio::test]
async fn deleting_list_cascades() {
let pool = pool().await;
let me = user(&pool, "a@x.fr").await;
let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
add_item(&mut *conn(&pool).await, me, list, &input("Chips")).await.unwrap();
delete_list(&pool, list).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty());
}
}