Added accounts API.
This commit is contained in:
@@ -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
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user