Added accounts API.

This commit is contained in:
2026-09-27 10:26:11 +02:00
parent 5f4c9bdf90
commit 4e1eea5849
18 changed files with 540 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
use uuid::Uuid;
use super::dtos::{AccountRow, Delete, Upsert};
pub struct Query {
pub limit: Option<i64>,
pub offset: Option<i64>,
}
pub async fn query<'e, E>(executor: E, query: Query) -> Result<Vec<AccountRow>, sqlx::Error>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
ORDER BY name DESC, id DESC
LIMIT $1
OFFSET $2
"#,
query.limit,
query.offset,
)
.fetch_all(executor)
.await
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<AccountRow>, sqlx::Error>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
WHERE id = $1
"#,
id,
)
.fetch_optional(executor)
.await
}
pub async fn upsert<'e, E>(
executor: E,
account: AccountRow,
) -> Result<Upsert<AccountRow>, sqlx::Error>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO accounts (id, name)
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
new_row.id AS "id!",
new_row.name AS "name!"
"#,
account.id,
account.name,
)
.fetch_one(executor)
.await?;
let account = AccountRow {
id: row.id,
name: row.name,
};
if row.old_id.is_some() {
Ok(Upsert::Updated(account))
} else {
Ok(Upsert::Created(account))
}
}
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Delete, sqlx::Error>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!("DELETE FROM accounts WHERE id = $1 RETURNING id", id)
.fetch_optional(executor)
.await?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
}
+2
View File
@@ -1,7 +1,9 @@
mod account;
mod recurring_transaction;
mod results;
mod transaction;
pub use account::*;
pub use recurring_transaction::*;
pub use results::*;
pub use transaction::*;
+6
View File
@@ -0,0 +1,6 @@
use uuid::Uuid;
pub struct AccountRow {
pub id: Uuid,
pub name: String,
}