first commit
This commit is contained in:
commit
9536cf0dbe
16 files changed
+5170
No files matched your search
@@ -0,0 +1,249 @@
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow};
|
||||
use sqlx::Row;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Suggestion, Unit};
|
||||
|
||||
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")?,
|
||||
})
|
||||
}
|
||||
|
||||
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")?,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn lists(pool: &SqlitePool) -> Result<Vec<ShoppingList>, sqlx::Error> {
|
||||
sqlx::query("SELECT id, name, color, created_at FROM lists ORDER BY id")
|
||||
.fetch_all(pool)
|
||||
.await?
|
||||
.iter()
|
||||
.map(list_from_row)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn create_list(pool: &SqlitePool, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
|
||||
let row = sqlx::query("INSERT INTO lists (name, color) VALUES (?, ?) RETURNING id")
|
||||
.bind(name)
|
||||
.bind(color.as_str())
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
row.try_get("id")
|
||||
}
|
||||
|
||||
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 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()
|
||||
}
|
||||
|
||||
/// Remembers the product in the catalog so it can be suggested later.
|
||||
async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO catalog (name, icon, category, use_count) VALUES (?, ?, ?, 1)
|
||||
ON CONFLICT(name) DO UPDATE SET
|
||||
icon = excluded.icon,
|
||||
category = excluded.category,
|
||||
use_count = use_count + 1",
|
||||
)
|
||||
.bind(&input.name)
|
||||
.bind(input.icon.as_str())
|
||||
.bind(input.category.as_str())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn add_item(pool: &SqlitePool, 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(pool)
|
||||
.await?;
|
||||
record_in_catalog(pool, input).await?;
|
||||
row.try_get("id")
|
||||
}
|
||||
|
||||
pub async fn update_item(pool: &SqlitePool, 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(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_item(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
|
||||
.bind(checked)
|
||||
.bind(id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Most used catalog products not already on the list.
|
||||
pub async fn suggestions(pool: &SqlitePool, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
|
||||
sqlx::query(
|
||||
"SELECT name, icon, category FROM catalog c
|
||||
WHERE 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(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()
|
||||
}
|
||||
|
||||
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 item_crud_and_toggle() {
|
||||
let pool = pool().await;
|
||||
let list = lists(&pool).await.unwrap()[0].id;
|
||||
|
||||
let id = add_item(&pool, list, &input("Avocats")).await.unwrap();
|
||||
let mut edited = input("Avocats");
|
||||
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
|
||||
update_item(&pool, id, &edited).await.unwrap();
|
||||
set_checked(&pool, 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(&pool, id).await.unwrap();
|
||||
assert!(items(&pool, list).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn suggestions_skip_items_on_list() {
|
||||
let pool = pool().await;
|
||||
let list = lists(&pool).await.unwrap()[0].id;
|
||||
add_item(&pool, list, &input("beurre")).await.unwrap();
|
||||
|
||||
let names: Vec<_> = suggestions(&pool, 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 list = create_list(&pool, "Apéro", ListColor::Pink).await.unwrap();
|
||||
add_item(&pool, list, &input("Chips")).await.unwrap();
|
||||
delete_list(&pool, list).await.unwrap();
|
||||
assert!(items(&pool, list).await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user