initial vibe coded app
This commit is contained in:
@@ -0,0 +1,967 @@
|
||||
use std::{
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use rand::{RngCore, rngs::OsRng};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use sha2::{Digest, Sha256};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum DbError {
|
||||
#[error("database error: {0}")]
|
||||
Message(String),
|
||||
#[error("record not found")]
|
||||
NotFound,
|
||||
#[error("record already exists")]
|
||||
Conflict,
|
||||
#[error("database worker failed: {0}")]
|
||||
Worker(String),
|
||||
}
|
||||
|
||||
pub type DbResult<T> = Result<T, DbError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Database {
|
||||
connection: Arc<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub display_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SessionUser {
|
||||
pub user: User,
|
||||
pub csrf_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GroceryList {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub owner_id: String,
|
||||
pub revision: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ListAccess {
|
||||
pub list: GroceryList,
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ListSummary {
|
||||
pub list: GroceryList,
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Item {
|
||||
pub id: String,
|
||||
pub list_id: String,
|
||||
pub name: String,
|
||||
pub quantity: String,
|
||||
pub note: String,
|
||||
pub category_id: Option<String>,
|
||||
pub checked: bool,
|
||||
pub version: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Category {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InvitationInfo {
|
||||
pub list_name: String,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub fn open(path: impl AsRef<Path>) -> DbResult<Self> {
|
||||
let connection = Connection::open(path).map_err(sql_error)?;
|
||||
configure(&connection)?;
|
||||
migrate(&connection)?;
|
||||
|
||||
Ok(Self {
|
||||
connection: Arc::new(Mutex::new(connection)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn open_in_memory() -> DbResult<Self> {
|
||||
Self::open(":memory:")
|
||||
}
|
||||
|
||||
async fn call<T, F>(&self, operation: F) -> DbResult<T>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&mut Connection) -> DbResult<T> + Send + 'static,
|
||||
{
|
||||
let connection = Arc::clone(&self.connection);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut connection = connection
|
||||
.lock()
|
||||
.map_err(|error| DbError::Worker(error.to_string()))?;
|
||||
operation(&mut connection)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| DbError::Worker(error.to_string()))?
|
||||
}
|
||||
|
||||
pub async fn create_user(
|
||||
&self,
|
||||
email: String,
|
||||
display_name: String,
|
||||
password_hash: String,
|
||||
) -> DbResult<User> {
|
||||
self.call(move |connection| {
|
||||
let user = User {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
email,
|
||||
display_name,
|
||||
};
|
||||
|
||||
let result = connection.execute(
|
||||
"INSERT INTO users (id, email, display_name, password_hash, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![user.id, user.email, user.display_name, password_hash, now()],
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(_) => Ok(user),
|
||||
Err(error) if error.to_string().contains("UNIQUE") => Err(DbError::Conflict),
|
||||
Err(error) => Err(sql_error(error)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn find_user_by_email(&self, email: String) -> DbResult<Option<(User, String)>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT id, email, display_name, password_hash
|
||||
FROM users WHERE email = ?1 COLLATE NOCASE",
|
||||
params![email],
|
||||
|row| {
|
||||
Ok((
|
||||
User {
|
||||
id: row.get(0)?,
|
||||
email: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
},
|
||||
row.get(3)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn has_users(&self) -> DbResult<bool> {
|
||||
self.call(|connection| {
|
||||
connection
|
||||
.query_row("SELECT EXISTS(SELECT 1 FROM users)", [], |row| {
|
||||
Ok(row.get::<_, i64>(0)? != 0)
|
||||
})
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_session(&self, user_id: String) -> DbResult<(String, String)> {
|
||||
self.call(move |connection| {
|
||||
let session_token = new_secret();
|
||||
let csrf_token = new_secret();
|
||||
connection
|
||||
.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![
|
||||
hash_secret(&session_token),
|
||||
user_id,
|
||||
csrf_token,
|
||||
now() + 60 * 60 * 24 * 30
|
||||
],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok((session_token, csrf_token))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn session_user(&self, session_token: String) -> DbResult<Option<SessionUser>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT u.id, u.email, u.display_name, s.csrf_token
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ?1 AND s.expires_at > ?2",
|
||||
params![hash_secret(&session_token), now()],
|
||||
|row| {
|
||||
Ok(SessionUser {
|
||||
user: User {
|
||||
id: row.get(0)?,
|
||||
email: row.get(1)?,
|
||||
display_name: row.get(2)?,
|
||||
},
|
||||
csrf_token: row.get(3)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_session(&self, session_token: String) -> DbResult<()> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = ?1",
|
||||
params![hash_secret(&session_token)],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_summaries(&self, user_id: String) -> DbResult<Vec<ListSummary>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT l.id, l.name, l.owner_id, l.revision, m.role
|
||||
FROM lists l
|
||||
JOIN list_members m ON m.list_id = l.id
|
||||
WHERE m.user_id = ?1
|
||||
ORDER BY l.created_at DESC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map(params![user_id], |row| {
|
||||
Ok(ListSummary {
|
||||
list: GroceryList {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
owner_id: row.get(2)?,
|
||||
revision: row.get(3)?,
|
||||
},
|
||||
role: row.get(4)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_list(&self, owner_id: String, name: String) -> DbResult<GroceryList> {
|
||||
self.call(move |connection| {
|
||||
let list = GroceryList {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
name,
|
||||
owner_id: owner_id.clone(),
|
||||
revision: 0,
|
||||
};
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO lists (id, name, owner_id, revision, created_at)
|
||||
VALUES (?1, ?2, ?3, 0, ?4)",
|
||||
params![list.id, list.name, owner_id, now()],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO list_members (list_id, user_id, role)
|
||||
VALUES (?1, ?2, 'owner')",
|
||||
params![list.id, list.owner_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
for (position, category_name) in DEFAULT_CATEGORIES.iter().enumerate() {
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO categories (id, list_id, name, position, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![
|
||||
Uuid::new_v4().to_string(),
|
||||
list.id,
|
||||
category_name,
|
||||
position as i64,
|
||||
now()
|
||||
],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
}
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(list)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_access(
|
||||
&self,
|
||||
list_id: String,
|
||||
user_id: String,
|
||||
) -> DbResult<Option<ListAccess>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT l.id, l.name, l.owner_id, l.revision, m.role
|
||||
FROM lists l
|
||||
JOIN list_members m ON m.list_id = l.id
|
||||
WHERE l.id = ?1 AND m.user_id = ?2",
|
||||
params![list_id, user_id],
|
||||
|row| {
|
||||
Ok(ListAccess {
|
||||
list: GroceryList {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
owner_id: row.get(2)?,
|
||||
revision: row.get(3)?,
|
||||
},
|
||||
role: row.get(4)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn items(&self, list_id: String) -> DbResult<Vec<Item>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT id, list_id, name, quantity, note, category_id, checked, version
|
||||
FROM items
|
||||
WHERE list_id = ?1
|
||||
ORDER BY position ASC, created_at ASC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map(params![list_id], |row| {
|
||||
Ok(Item {
|
||||
id: row.get(0)?,
|
||||
list_id: row.get(1)?,
|
||||
name: row.get(2)?,
|
||||
quantity: row.get(3)?,
|
||||
note: row.get(4)?,
|
||||
category_id: row.get(5)?,
|
||||
checked: row.get::<_, i64>(6)? != 0,
|
||||
version: row.get(7)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn categories(&self, list_id: String) -> DbResult<Vec<Category>> {
|
||||
self.call(move |connection| {
|
||||
let mut statement = connection
|
||||
.prepare(
|
||||
"SELECT id, name
|
||||
FROM categories
|
||||
WHERE list_id = ?1
|
||||
ORDER BY position ASC, name COLLATE NOCASE ASC",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let rows = statement
|
||||
.query_map(params![list_id], |row| {
|
||||
Ok(Category {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
})
|
||||
})
|
||||
.map_err(sql_error)?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_category(&self, list_id: String, name: String) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let position: i64 = transaction
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(position), -1) + 1
|
||||
FROM categories WHERE list_id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let result = transaction.execute(
|
||||
"INSERT INTO categories (id, list_id, name, position, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![Uuid::new_v4().to_string(), list_id, name, position, now()],
|
||||
);
|
||||
match result {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.to_string().contains("UNIQUE") => {
|
||||
return Err(DbError::Conflict);
|
||||
}
|
||||
Err(error) => return Err(sql_error(error)),
|
||||
}
|
||||
let revision = bump_revision(&transaction, &list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn add_item(
|
||||
&self,
|
||||
list_id: String,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<String>,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let category_id = category_id.filter(|category_id| !category_id.is_empty());
|
||||
ensure_category(&transaction, &list_id, category_id.as_deref())?;
|
||||
let position: i64 = transaction
|
||||
.query_row(
|
||||
"SELECT COALESCE(MAX(position), -1) + 1 FROM items WHERE list_id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO items
|
||||
(id, list_id, name, quantity, note, category_id, checked, version, position, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, 1, ?7, ?8, ?8)",
|
||||
params![
|
||||
Uuid::new_v4().to_string(),
|
||||
list_id,
|
||||
name,
|
||||
quantity,
|
||||
note,
|
||||
category_id,
|
||||
position,
|
||||
now()
|
||||
],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
let revision = bump_revision(&transaction, &list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn set_item_checked(
|
||||
&self,
|
||||
list_id: String,
|
||||
item_id: String,
|
||||
checked: bool,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"UPDATE items
|
||||
SET checked = ?1, version = version + 1, updated_at = ?2
|
||||
WHERE id = ?3 AND list_id = ?4",
|
||||
params![checked as i64, now(), item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, &list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_item(
|
||||
&self,
|
||||
list_id: String,
|
||||
item_id: String,
|
||||
name: String,
|
||||
quantity: String,
|
||||
note: String,
|
||||
category_id: Option<String>,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let category_id = category_id.filter(|category_id| !category_id.is_empty());
|
||||
ensure_category(&transaction, &list_id, category_id.as_deref())?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"UPDATE items
|
||||
SET name = ?1, quantity = ?2, note = ?3, category_id = ?4,
|
||||
version = version + 1, updated_at = ?5
|
||||
WHERE id = ?6 AND list_id = ?7",
|
||||
params![name, quantity, note, category_id, now(), item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, &list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete_item(&self, list_id: String, item_id: String) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let changed = transaction
|
||||
.execute(
|
||||
"DELETE FROM items WHERE id = ?1 AND list_id = ?2",
|
||||
params![item_id, list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
if changed == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
let revision = bump_revision(&transaction, &list_id)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_invitation(
|
||||
&self,
|
||||
list_id: String,
|
||||
created_by: String,
|
||||
token: String,
|
||||
) -> DbResult<i64> {
|
||||
self.call(move |connection| {
|
||||
let expires_at = now() + 60 * 60 * 24 * 7;
|
||||
connection
|
||||
.execute(
|
||||
"INSERT INTO invitations (token_hash, list_id, created_by, expires_at)
|
||||
VALUES (?1, ?2, ?3, ?4)",
|
||||
params![hash_secret(&token), list_id, created_by, expires_at],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
Ok(expires_at)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn invitation(&self, token: String) -> DbResult<Option<InvitationInfo>> {
|
||||
self.call(move |connection| {
|
||||
connection
|
||||
.query_row(
|
||||
"SELECT l.name
|
||||
FROM invitations i
|
||||
JOIN lists l ON l.id = i.list_id
|
||||
WHERE i.token_hash = ?1 AND i.expires_at > ?2",
|
||||
params![hash_secret(&token), now()],
|
||||
|row| {
|
||||
Ok(InvitationInfo {
|
||||
list_name: row.get(0)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn accept_invitation(&self, token: String, user_id: String) -> DbResult<String> {
|
||||
self.call(move |connection| {
|
||||
let transaction = connection.transaction().map_err(sql_error)?;
|
||||
let invitation = transaction
|
||||
.query_row(
|
||||
"SELECT list_id FROM invitations
|
||||
WHERE token_hash = ?1 AND expires_at > ?2",
|
||||
params![hash_secret(&token), now()],
|
||||
|row| row.get::<_, String>(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)?
|
||||
.ok_or(DbError::NotFound)?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT OR IGNORE INTO list_members (list_id, user_id, role)
|
||||
VALUES (?1, ?2, 'member')",
|
||||
params![invitation, user_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.execute(
|
||||
"DELETE FROM invitations WHERE token_hash = ?1",
|
||||
params![hash_secret(&token)],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction.commit().map_err(sql_error)?;
|
||||
Ok(invitation)
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
fn configure(connection: &Connection) -> DbResult<()> {
|
||||
connection
|
||||
.pragma_update(None, "foreign_keys", true)
|
||||
.map_err(sql_error)?;
|
||||
connection
|
||||
.pragma_update(None, "journal_mode", "WAL")
|
||||
.map_err(sql_error)?;
|
||||
connection
|
||||
.busy_timeout(std::time::Duration::from_secs(5))
|
||||
.map_err(sql_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn migrate(connection: &Connection) -> DbResult<()> {
|
||||
connection
|
||||
.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
csrf_token TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS list_members (
|
||||
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL CHECK (role IN ('owner', 'member')),
|
||||
PRIMARY KEY (list_id, user_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id TEXT PRIMARY KEY,
|
||||
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL COLLATE NOCASE,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE (list_id, name)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS invitations (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
created_by TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
quantity TEXT NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
category_id TEXT REFERENCES categories(id) ON DELETE SET NULL,
|
||||
checked INTEGER NOT NULL DEFAULT 0,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS items_list_idx ON items(list_id);
|
||||
CREATE INDEX IF NOT EXISTS categories_list_idx ON categories(list_id);
|
||||
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS list_members_user_idx ON list_members(user_id);",
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
|
||||
if !has_column(connection, "items", "category_id")? {
|
||||
connection
|
||||
.execute(
|
||||
"ALTER TABLE items ADD COLUMN category_id TEXT REFERENCES categories(id) ON DELETE SET NULL",
|
||||
[],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_column(connection: &Connection, table: &str, wanted: &str) -> DbResult<bool> {
|
||||
let mut statement = connection
|
||||
.prepare(&format!("PRAGMA table_info({table})"))
|
||||
.map_err(sql_error)?;
|
||||
let mut rows = statement.query([]).map_err(sql_error)?;
|
||||
while let Some(row) = rows.next().map_err(sql_error)? {
|
||||
if row.get::<_, String>(1).map_err(sql_error)? == wanted {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn ensure_category(
|
||||
transaction: &rusqlite::Transaction<'_>,
|
||||
list_id: &str,
|
||||
category_id: Option<&str>,
|
||||
) -> DbResult<()> {
|
||||
let Some(category_id) = category_id else {
|
||||
return Ok(());
|
||||
};
|
||||
let exists = transaction
|
||||
.query_row(
|
||||
"SELECT 1 FROM categories WHERE id = ?1 AND list_id = ?2",
|
||||
params![category_id, list_id],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.optional()
|
||||
.map_err(sql_error)?;
|
||||
if exists.is_none() {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const DEFAULT_CATEGORIES: &[&str] = &[
|
||||
"Produce",
|
||||
"Meat & seafood",
|
||||
"Dairy & eggs",
|
||||
"Pantry",
|
||||
"Frozen",
|
||||
"Household",
|
||||
];
|
||||
|
||||
fn bump_revision(transaction: &rusqlite::Transaction<'_>, list_id: &str) -> DbResult<i64> {
|
||||
transaction
|
||||
.execute(
|
||||
"UPDATE lists SET revision = revision + 1 WHERE id = ?1",
|
||||
params![list_id],
|
||||
)
|
||||
.map_err(sql_error)?;
|
||||
transaction
|
||||
.query_row(
|
||||
"SELECT revision FROM lists WHERE id = ?1",
|
||||
params![list_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(sql_error)
|
||||
}
|
||||
|
||||
fn sql_error(error: impl std::fmt::Display) -> DbError {
|
||||
DbError::Message(error.to_string())
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
pub fn new_secret() -> String {
|
||||
let mut bytes = [0_u8; 32];
|
||||
OsRng.fill_bytes(&mut bytes);
|
||||
hex::encode(bytes)
|
||||
}
|
||||
|
||||
pub fn hash_secret(secret: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(secret.as_bytes());
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_list_and_item() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let user = database
|
||||
.create_user("test@example.com".into(), "Test User".into(), "hash".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let list = database
|
||||
.create_list(user.id.clone(), "Weekly shop".into())
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Milk".into(),
|
||||
"2 litres".into(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let items = database.items(list.id).await.unwrap();
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].name, "Milk");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_and_invitations_are_scoped_to_users() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let owner = database
|
||||
.create_user("owner@example.com".into(), "Owner".into(), "hash".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let member = database
|
||||
.create_user("member@example.com".into(), "Member".into(), "hash".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let list = database
|
||||
.create_list(owner.id.clone(), "Household".into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(database.categories(list.id.clone()).await.unwrap().len(), 6);
|
||||
let (session_token, csrf_token) = database.create_session(owner.id.clone()).await.unwrap();
|
||||
|
||||
let session = database
|
||||
.session_user(session_token.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(session.user.id, owner.id);
|
||||
assert_eq!(session.csrf_token, csrf_token);
|
||||
|
||||
let invitation_token = "test-invitation".to_owned();
|
||||
database
|
||||
.create_invitation(list.id.clone(), owner.id, invitation_token.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
database
|
||||
.invitation(invitation_token.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.list_name,
|
||||
"Household"
|
||||
);
|
||||
|
||||
let accepted_list = database
|
||||
.accept_invitation(invitation_token.clone(), member.id.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(accepted_list, list.id);
|
||||
assert!(
|
||||
database
|
||||
.invitation(invitation_token)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
database
|
||||
.list_access(list.id, member.id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.role,
|
||||
"member"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checked_state_is_set_not_toggled() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let user = database
|
||||
.create_user("check@example.com".into(), "Checker".into(), "hash".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let list = database.create_list(user.id, "List".into()).await.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Coffee".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let item = database.items(list.id.clone()).await.unwrap().remove(0);
|
||||
|
||||
database
|
||||
.set_item_checked(list.id.clone(), item.id.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.set_item_checked(list.id.clone(), item.id.clone(), true)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let item = database.items(list.id).await.unwrap().remove(0);
|
||||
assert!(item.checked);
|
||||
assert_eq!(item.version, 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checking_an_item_does_not_change_list_order() {
|
||||
let database = Database::open_in_memory().unwrap();
|
||||
let user = database
|
||||
.create_user(
|
||||
"order@example.com".into(),
|
||||
"Order Tester".into(),
|
||||
"hash".into(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let list = database.create_list(user.id, "List".into()).await.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"First".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
database
|
||||
.add_item(
|
||||
list.id.clone(),
|
||||
"Second".into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first_item = database.items(list.id.clone()).await.unwrap().remove(0);
|
||||
|
||||
database
|
||||
.set_item_checked(list.id.clone(), first_item.id, true)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let items = database.items(list.id).await.unwrap();
|
||||
assert_eq!(items[0].name, "First");
|
||||
assert!(items[0].checked);
|
||||
assert_eq!(items[1].name, "Second");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user