Made accounts and their transaction accessible to account members only.

This commit is contained in:
2026-10-11 13:28:16 +02:00
parent 21f0c17af9
commit 3faea141dd
34 changed files with 462 additions and 295 deletions
@@ -1,40 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE id = ANY($1)\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "accounts",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text",
"origin": {
"Table": {
"table": "accounts",
"name": "name"
}
}
}
],
"parameters": {
"Left": [
"UuidArray"
]
},
"nullable": [
false,
false
]
},
"hash": "016dcd0136e2284546f7ad4db96cadba51847776866997f0e978cff9c869c635"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO recurring_transactions (\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n account_id = EXCLUDED.account_id,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n recurrence_every = EXCLUDED.recurrence_every,\n recurrence_unit = EXCLUDED.recurrence_unit,\n weekend_adjustment = EXCLUDED.weekend_adjustment\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.name, new_row.name) AS \"old_name!\",\n COALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n COALESCE(old_row.amount_cents, new_row.amount_cents) AS \"old_amount_cents!\",\n COALESCE(old_row.direction, new_row.direction) AS \"old_direction!\",\n COALESCE(old_row.starts_at, new_row.starts_at) AS \"old_starts_at!\",\n old_row.ends_at AS \"old_ends_at?\",\n COALESCE(old_row.recurrence_every, new_row.recurrence_every) AS \"old_recurrence_every!\",\n COALESCE(old_row.recurrence_unit, new_row.recurrence_unit) AS \"old_recurrence_unit!\",\n old_row.weekend_adjustment AS \"old_weekend_adjustment?\",\n new_row.id AS \"id!\",\n new_row.name AS \"name!\",\n new_row.account_id AS \"account_id!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.starts_at AS \"starts_at!\",\n new_row.ends_at AS \"ends_at?\",\n new_row.recurrence_every AS \"recurrence_every!\",\n new_row.recurrence_unit AS \"recurrence_unit!\",\n new_row.weekend_adjustment AS \"weekend_adjustment?\"\n ",
"query": "\n INSERT INTO recurring_transactions (\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n )\n SELECT $2, $3, $4, $5, $6, $7, $8, $9, $10, $11\n FROM accessible_accounts($1) AS accounts\n WHERE accounts.id = $4\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n account_id = EXCLUDED.account_id,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n recurrence_every = EXCLUDED.recurrence_every,\n recurrence_unit = EXCLUDED.recurrence_unit,\n weekend_adjustment = EXCLUDED.weekend_adjustment\n WHERE recurring_transactions.account_id IN (SELECT id FROM accessible_accounts($1))\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.name, new_row.name) AS \"old_name!\",\n COALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n COALESCE(old_row.amount_cents, new_row.amount_cents) AS \"old_amount_cents!\",\n COALESCE(old_row.direction, new_row.direction) AS \"old_direction!\",\n COALESCE(old_row.starts_at, new_row.starts_at) AS \"old_starts_at!\",\n old_row.ends_at AS \"old_ends_at?\",\n COALESCE(old_row.recurrence_every, new_row.recurrence_every) AS \"old_recurrence_every!\",\n COALESCE(old_row.recurrence_unit, new_row.recurrence_unit) AS \"old_recurrence_unit!\",\n old_row.weekend_adjustment AS \"old_weekend_adjustment?\",\n new_row.id AS \"id!\",\n new_row.name AS \"name!\",\n new_row.account_id AS \"account_id!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.starts_at AS \"starts_at!\",\n new_row.ends_at AS \"ends_at?\",\n new_row.recurrence_every AS \"recurrence_every!\",\n new_row.recurrence_unit AS \"recurrence_unit!\",\n new_row.weekend_adjustment AS \"weekend_adjustment?\"\n ",
"describe": {
"columns": [
{
@@ -191,6 +191,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Text",
"Uuid",
@@ -226,5 +227,5 @@
true
]
},
"hash": "8bc3dbca6ff74e9775321d64337db88dfab2bf30f8128fcb81a8c980337da483"
"hash": "129ff47c0d29ccba81eac0d40d7e9f2325911fb33b361300cd44073e1d0e3ed3"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n ORDER BY starts_at DESC, id DESC\n LIMIT $1 OFFSET $2\n ",
"query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n WHERE account_id IN (SELECT id FROM accessible_accounts($1))\n ORDER BY starts_at DESC, id DESC\n LIMIT $2 OFFSET $3\n ",
"describe": {
"columns": [
{
@@ -116,6 +116,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Int8",
"Int8"
]
@@ -133,5 +134,5 @@
true
]
},
"hash": "f4b604ad13d3424a7f3fc32bb40aa91981fe861b661169ac5310e9df0e7b99d9"
"hash": "216e891a0ad648d1b23a0c9ba158a26b51f67b3ef7715d2b6b0e252e7e321743"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM transactions\n WHERE id = $1\n RETURNING id, account_id, amount_cents, direction, date, description\n ",
"query": "\n DELETE FROM transactions\n WHERE account_id IN (SELECT id FROM accessible_accounts($1))\n AND id = $2\n RETURNING id, account_id, amount_cents, direction, date, description\n ",
"describe": {
"columns": [
{
@@ -72,6 +72,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -84,5 +85,5 @@
false
]
},
"hash": "0c75096fe78c303e4676880840fc768b4150dfb9a0654229bf6581bd67494eb3"
"hash": "445ce23e4d76c2311b18c2a44d8d7199c5b4e865d60b0e39f5cd5101fbf60b57"
}
@@ -0,0 +1,31 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id AS \"id!\", name AS \"name!\"\n\t\tFROM accessible_accounts($1)\n\t\tWHERE id = $2\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Uuid",
"origin": "Expression"
},
{
"ordinal": 1,
"name": "name!",
"type_info": "Text",
"origin": "Expression"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
null,
null
]
},
"hash": "4ab020caa34fd1b6a1479e2da759d26ad6c944ca01992430ba03c21cbe0764e0"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM recurring_transactions\n WHERE id = $1\n RETURNING\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n ",
"query": "\n DELETE FROM recurring_transactions\n WHERE account_id IN (SELECT id FROM accessible_accounts($1))\n AND id = $2\n RETURNING\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n ",
"describe": {
"columns": [
{
@@ -116,6 +116,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -132,5 +133,5 @@
true
]
},
"hash": "be72d1cc51b27ae37afd44d85fe29e9226bcf428701dd931f9d03673729f11a2"
"hash": "590bd11fc994d0d22bb238ff7c140b1c48c4e31c34c18505c1d2a6aad01ddcdd"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO transactions (id, account_id, amount_cents, direction, date, description)\n VALUES ($1, $2, $3, $4, $5, $6)\n\t\tON CONFLICT (id) DO UPDATE SET\n account_id = EXCLUDED.account_id,\n\t\t\tamount_cents = EXCLUDED.amount_cents,\n\t\t\tdirection = EXCLUDED.direction,\n\t\t\tdate = EXCLUDED.date,\n\t\t\tdescription = EXCLUDED.description\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tCOALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n\t\t\tCOALESCE(old_row.amount_cents, new_row.amount_cents) AS \"old_amount_cents!\",\n\t\t\tCOALESCE(old_row.direction, new_row.direction) AS \"old_direction!\",\n\t\t\tCOALESCE(old_row.date, new_row.date) AS \"old_date!\",\n\t\t\tCOALESCE(old_row.description, new_row.description) AS \"old_description!\",\n\t\t\tnew_row.id AS \"id!\",\n new_row.account_id AS \"account_id!\",\n\t\t\tnew_row.amount_cents AS \"amount_cents!\",\n\t\t\tnew_row.direction AS \"direction!\",\n\t\t\tnew_row.date AS \"date!\",\n\t\t\tnew_row.description AS \"description!\"\n\t\t",
"query": "\n INSERT INTO transactions (id, account_id, amount_cents, direction, date, description)\n SELECT $2, $3, $4, $5, $6, $7\n FROM accessible_accounts($1) AS accounts\n WHERE accounts.id = $3\n ON CONFLICT (id) DO UPDATE SET\n account_id = EXCLUDED.account_id,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n date = EXCLUDED.date,\n description = EXCLUDED.description\n WHERE transactions.account_id IN (SELECT id FROM accessible_accounts($1))\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n COALESCE(old_row.amount_cents, new_row.amount_cents) AS \"old_amount_cents!\",\n COALESCE(old_row.direction, new_row.direction) AS \"old_direction!\",\n COALESCE(old_row.date, new_row.date) AS \"old_date!\",\n COALESCE(old_row.description, new_row.description) AS \"old_description!\",\n new_row.id AS \"id!\",\n new_row.account_id AS \"account_id!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.date AS \"date!\",\n new_row.description AS \"description!\"\n ",
"describe": {
"columns": [
{
@@ -113,6 +113,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Uuid",
"Int8",
@@ -136,5 +137,5 @@
false
]
},
"hash": "26a5b764d38ca78508087d1e793ae81530064a3ae661ff3c73c7cd686097aa81"
"hash": "644b5254e749e03696892b2234c1e8feee5d852e443c4fe0c1c71cdddfab3f6e"
}
@@ -1,42 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE ($1::text IS NULL OR name ILIKE '%' || $1 || '%')\n\t\tORDER BY name DESC, id DESC\n\t\tLIMIT $2\n\t\tOFFSET $3\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "accounts",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text",
"origin": {
"Table": {
"table": "accounts",
"name": "name"
}
}
}
],
"parameters": {
"Left": [
"Text",
"Int8",
"Int8"
]
},
"nullable": [
false,
false
]
},
"hash": "9b5267c3bd09fb64717565c5c7e3084195d09c0a30f7e963a2497892398c6adc"
}
@@ -0,0 +1,33 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id AS \"id!\", name AS \"name!\"\n\t\tFROM accessible_accounts($1)\n\t\tWHERE ($2::text IS NULL OR name ILIKE '%' || $2 || '%')\n\t\tORDER BY name DESC, id DESC\n\t\tLIMIT $3\n\t\tOFFSET $4\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Uuid",
"origin": "Expression"
},
{
"ordinal": 1,
"name": "name!",
"type_info": "Text",
"origin": "Expression"
}
],
"parameters": {
"Left": [
"Uuid",
"Text",
"Int8",
"Int8"
]
},
"nullable": [
null,
null
]
},
"hash": "9d072194b9f245f29ec5d97b3363e7a9b069cf38ed1fecdb739b85715cba26ca"
}
@@ -0,0 +1,31 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id AS \"id!\", name AS \"name!\"\n\t\tFROM accessible_accounts($1)\n\t\tWHERE id = ANY($2)\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id!",
"type_info": "Uuid",
"origin": "Expression"
},
{
"ordinal": 1,
"name": "name!",
"type_info": "Text",
"origin": "Expression"
}
],
"parameters": {
"Left": [
"Uuid",
"UuidArray"
]
},
"nullable": [
null,
null
]
},
"hash": "b83902d6b3ccb3163c88ba684663a6774dd446a3dbd5301513e9f64cda75a325"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tINSERT INTO accounts (id, name)\n\t\tVALUES ($1, $2)\n\t\tON CONFLICT (id) DO UPDATE SET\n\t\t\tname = EXCLUDED.name\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tCOALESCE(old_row.name, new_row.name) AS \"old_name!\",\n\t\t\tnew_row.id AS \"id!\",\n\t\t\tnew_row.name AS \"name!\"\n\t\t",
"query": "\n\t\tINSERT INTO accounts (id, name)\n\t\tVALUES ($2, $3)\n\t\tON CONFLICT (id) DO UPDATE SET\n\t\t\tname = EXCLUDED.name\n\t\tWHERE accounts.id IN (SELECT id FROM accessible_accounts($1))\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tCOALESCE(old_row.name, new_row.name) AS \"old_name!\",\n\t\t\tnew_row.id AS \"id!\",\n\t\t\tnew_row.name AS \"name!\"\n\t\t",
"describe": {
"columns": [
{
@@ -45,6 +45,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Text"
]
@@ -56,5 +57,5 @@
false
]
},
"hash": "3b4b5bac598a8ef53be0c31ae751fb7e69f2e0b2ee18d628035fc198dadb4b9c"
"hash": "c5a2016942aadfafee38e7b4ad2926684d3d846a36d99bc0b33a48ae8a3076a9"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n WHERE id = $1\n ",
"query": "\n SELECT\n id,\n name,\n account_id,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n WHERE account_id IN (SELECT id FROM accessible_accounts($1))\n AND id = $2\n ",
"describe": {
"columns": [
{
@@ -116,6 +116,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -132,5 +133,5 @@
true
]
},
"hash": "ed9ae08575930c5b161d3f0c0f50479e51b54e348e1651f4a4e9b8328741cec7"
"hash": "cb4d0185f7464e4c7e6f4e0cb6bc40be6a56076c88d8356bf034838f1e22f2e3"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tWHERE id = $1\n\t\t",
"query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tWHERE account_id IN (SELECT id FROM accessible_accounts($1))\n\t\tAND id = $2\n\t\t",
"describe": {
"columns": [
{
@@ -72,6 +72,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -84,5 +85,5 @@
false
]
},
"hash": "6fbffb56421dfc314468e6f7ea5b76594dfcdb06bd5d82ba61330fb8e51e88dc"
"hash": "cbb576c1e4d8404059a4ea5972027c2845a7de913052d076744ffde8383fdf86"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM accounts WHERE id = $1 RETURNING id, name",
"query": "\n\t\tDELETE FROM accounts\n\t\tWHERE id IN (SELECT id FROM accessible_accounts($1))\n\t\tAND id = $2\n\t\tRETURNING id, name\n\t\t",
"describe": {
"columns": [
{
@@ -28,6 +28,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
@@ -36,5 +37,5 @@
false
]
},
"hash": "910c19f1022dcf5923c64f43cd3c55b6cf7a41a4907fc70d09b0b4770209acc3"
"hash": "d1774b1ccd955a93433e1149be03fad7ab09afd5eaa67a87e042b26d0a52e450"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tORDER BY date DESC, id DESC\n\t\tLIMIT $1\n\t\tOFFSET $2\n\t\t",
"query": "\n SELECT id, account_id, amount_cents, direction, date, description\n\t\tFROM transactions\n\t\tWHERE account_id IN (SELECT id FROM accessible_accounts($1))\n\t\tORDER BY date DESC, id DESC\n\t\tLIMIT $2\n\t\tOFFSET $3\n\t\t",
"describe": {
"columns": [
{
@@ -72,6 +72,7 @@
],
"parameters": {
"Left": [
"Uuid",
"Int8",
"Int8"
]
@@ -85,5 +86,5 @@
false
]
},
"hash": "a962ef0282ca37bb5eba2ee1b0bd93da2527f7e5a0c4332527f1e533f3ecd4f0"
"hash": "d4a872e24aaff164619557665960013cf838d38e407ef5730a26dfe00a0dd96b"
}
@@ -1,40 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE id = $1\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "accounts",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text",
"origin": {
"Table": {
"table": "accounts",
"name": "name"
}
}
}
],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": [
false,
false
]
},
"hash": "f671ec25a4bc22127ea7d3a63be134719dc4aa4eb4c96d7c4d64388cfb658fa8"
}
@@ -1,6 +1,6 @@
CREATE TABLE account_members (
id UUID DEFAULT gen_random_uuid (),
account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id),
account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id) ON DELETE CASCADE,
user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id),
PRIMARY KEY (id, account_id),
CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id)
@@ -0,0 +1,10 @@
CREATE FUNCTION accessible_accounts (p_user_id UUID) RETURNS SETOF accounts LANGUAGE sql STABLE AS $$
SELECT accounts.*
FROM accounts
WHERE EXISTS (
SELECT 1
FROM account_members
WHERE account_members.account_id = accounts.id
AND account_members.user_id = p_user_id
)
$$;
+55 -21
View File
@@ -11,20 +11,25 @@ pub struct Query {
pub offset: Option<i64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<AccountRow>, DatabaseError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<AccountRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
WHERE ($1::text IS NULL OR name ILIKE '%' || $1 || '%')
SELECT id AS "id!", name AS "name!"
FROM accessible_accounts($1)
WHERE ($2::text IS NULL OR name ILIKE '%' || $2 || '%')
ORDER BY name DESC, id DESC
LIMIT $2
OFFSET $3
LIMIT $3
OFFSET $4
"#,
user_id,
query.name,
query.limit,
query.offset,
@@ -34,17 +39,22 @@ where
.map_err(DatabaseError::from)
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<AccountRow>, DatabaseError>
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<AccountRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
WHERE id = $1
SELECT id AS "id!", name AS "name!"
FROM accessible_accounts($1)
WHERE id = $2
"#,
user_id,
id,
)
.fetch_optional(executor)
@@ -52,17 +62,22 @@ where
.map_err(DatabaseError::from)
}
pub async fn get_by_ids<'e, E>(executor: E, ids: &[Uuid]) -> Result<Vec<AccountRow>, DatabaseError>
pub async fn get_by_ids<'e, E>(
executor: E,
user_id: Uuid,
ids: &[Uuid],
) -> Result<Vec<AccountRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
WHERE id = ANY($1)
SELECT id AS "id!", name AS "name!"
FROM accessible_accounts($1)
WHERE id = ANY($2)
"#,
user_id,
ids,
)
.fetch_all(executor)
@@ -72,30 +87,39 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
account: AccountRow,
) -> Result<Upsert<AccountRow>, DatabaseError>
) -> Result<Option<Upsert<AccountRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO accounts (id, name)
VALUES ($1, $2)
VALUES ($2, $3)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name
WHERE accounts.id IN (SELECT id FROM accessible_accounts($1))
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.name, new_row.name) AS "old_name!",
new_row.id AS "id!",
new_row.name AS "name!"
"#,
user_id,
account.id,
account.name,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the account is not accessible, or when the id belongs to a row in an
// account that is not accessible.
let Some(row) = row else {
return Ok(None);
};
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
// coalesced with the new row's values in case there was no previous row. This enables static
// typing on the previous row instead of having to check nullability for each old field in code.
@@ -104,22 +128,32 @@ where
name: row.old_name,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: AccountRow {
id: row.id,
name: row.name,
},
})
}))
}
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<AccountRow>, DatabaseError>
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<AccountRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
"DELETE FROM accounts WHERE id = $1 RETURNING id, name",
r#"
DELETE FROM accounts
WHERE id IN (SELECT id FROM accessible_accounts($1))
AND id = $2
RETURNING id, name
"#,
user_id,
id,
)
.fetch_optional(executor)
+29 -8
View File
@@ -12,6 +12,7 @@ pub struct Query {
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<RecurringTransactionRow>, DatabaseError>
where
@@ -32,9 +33,11 @@ where
recurrence_unit,
weekend_adjustment
FROM recurring_transactions
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
ORDER BY starts_at DESC, id DESC
LIMIT $1 OFFSET $2
LIMIT $2 OFFSET $3
"#,
user_id,
query.limit,
query.offset,
)
@@ -45,6 +48,7 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<RecurringTransactionRow>, DatabaseError>
where
@@ -65,8 +69,10 @@ where
recurrence_unit,
weekend_adjustment
FROM recurring_transactions
WHERE id = $1
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND id = $2
"#,
user_id,
id,
)
.fetch_optional(executor)
@@ -76,8 +82,9 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
transaction: RecurringTransactionRow,
) -> Result<Upsert<RecurringTransactionRow>, DatabaseError>
) -> Result<Option<Upsert<RecurringTransactionRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -95,7 +102,9 @@ where
recurrence_unit,
weekend_adjustment
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
SELECT $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
FROM accessible_accounts($1) AS accounts
WHERE accounts.id = $4
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
account_id = EXCLUDED.account_id,
@@ -106,6 +115,7 @@ where
recurrence_every = EXCLUDED.recurrence_every,
recurrence_unit = EXCLUDED.recurrence_unit,
weekend_adjustment = EXCLUDED.weekend_adjustment
WHERE recurring_transactions.account_id IN (SELECT id FROM accessible_accounts($1))
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.name, new_row.name) AS "old_name!",
@@ -128,6 +138,7 @@ where
new_row.recurrence_unit AS "recurrence_unit!",
new_row.weekend_adjustment AS "weekend_adjustment?"
"#,
user_id,
transaction.id,
transaction.name,
transaction.account_id,
@@ -139,13 +150,20 @@ where
transaction.recurrence_unit,
transaction.weekend_adjustment,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the account is not accessible, or when the id belongs to a row in an
// account that is not accessible.
let Some(row) = row else {
return Ok(None);
};
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
// coalesced with the new row's values in case there was no previous row. This enables static
// typing on the previous row instead of having to check nullability for each old field in code.
// `ends_at` and `weekend_adjustment` are genuinely nullable and stay optional.
let previous = row.old_id.map(|id| RecurringTransactionRow {
id,
name: row.old_name,
@@ -159,7 +177,7 @@ where
weekend_adjustment: row.old_weekend_adjustment,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: RecurringTransactionRow {
id: row.id,
@@ -173,11 +191,12 @@ where
recurrence_unit: row.recurrence_unit,
weekend_adjustment: row.weekend_adjustment,
},
})
}))
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<RecurringTransactionRow>, DatabaseError>
where
@@ -187,7 +206,8 @@ where
RecurringTransactionRow,
r#"
DELETE FROM recurring_transactions
WHERE id = $1
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND id = $2
RETURNING
id,
name,
@@ -200,6 +220,7 @@ where
recurrence_unit,
weekend_adjustment
"#,
user_id,
id,
)
.fetch_optional(executor)
+51 -28
View File
@@ -10,7 +10,11 @@ pub struct Query {
pub offset: Option<i64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<TransactionRow>, DatabaseError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<TransactionRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -19,10 +23,12 @@ where
r#"
SELECT id, account_id, amount_cents, direction, date, description
FROM transactions
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
ORDER BY date DESC, id DESC
LIMIT $1
OFFSET $2
LIMIT $2
OFFSET $3
"#,
user_id,
query.limit,
query.offset,
)
@@ -33,6 +39,7 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<TransactionRow>, DatabaseError>
where
@@ -43,8 +50,10 @@ where
r#"
SELECT id, account_id, amount_cents, direction, date, description
FROM transactions
WHERE id = $1
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND id = $2
"#,
user_id,
id,
)
.fetch_optional(executor)
@@ -54,35 +63,40 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
transaction: TransactionRow,
) -> Result<Upsert<TransactionRow>, DatabaseError>
) -> Result<Option<Upsert<TransactionRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO transactions (id, account_id, amount_cents, direction, date, description)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (id) DO UPDATE SET
SELECT $2, $3, $4, $5, $6, $7
FROM accessible_accounts($1) AS accounts
WHERE accounts.id = $3
ON CONFLICT (id) DO UPDATE SET
account_id = EXCLUDED.account_id,
amount_cents = EXCLUDED.amount_cents,
direction = EXCLUDED.direction,
date = EXCLUDED.date,
description = EXCLUDED.description
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!",
COALESCE(old_row.amount_cents, new_row.amount_cents) AS "old_amount_cents!",
COALESCE(old_row.direction, new_row.direction) AS "old_direction!",
COALESCE(old_row.date, new_row.date) AS "old_date!",
COALESCE(old_row.description, new_row.description) AS "old_description!",
new_row.id AS "id!",
amount_cents = EXCLUDED.amount_cents,
direction = EXCLUDED.direction,
date = EXCLUDED.date,
description = EXCLUDED.description
WHERE transactions.account_id IN (SELECT id FROM accessible_accounts($1))
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!",
COALESCE(old_row.amount_cents, new_row.amount_cents) AS "old_amount_cents!",
COALESCE(old_row.direction, new_row.direction) AS "old_direction!",
COALESCE(old_row.date, new_row.date) AS "old_date!",
COALESCE(old_row.description, new_row.description) AS "old_description!",
new_row.id AS "id!",
new_row.account_id AS "account_id!",
new_row.amount_cents AS "amount_cents!",
new_row.direction AS "direction!",
new_row.date AS "date!",
new_row.description AS "description!"
"#,
new_row.amount_cents AS "amount_cents!",
new_row.direction AS "direction!",
new_row.date AS "date!",
new_row.description AS "description!"
"#,
user_id,
transaction.id,
transaction.account_id,
transaction.amount_cents,
@@ -90,10 +104,16 @@ where
transaction.date,
transaction.description,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the account is not accessible, or when the id belongs to a row in an
// account that is not accessible.
let Some(row) = row else {
return Ok(None);
};
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
// coalesced with the new row's values in case there was no previous row. This enables static
// typing on the previous row instead of having to check nullability for each old field in code.
@@ -106,7 +126,7 @@ where
description: row.old_description,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: TransactionRow {
id: row.id,
@@ -116,11 +136,12 @@ where
date: row.date,
description: row.description,
},
})
}))
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<TransactionRow>, DatabaseError>
where
@@ -130,9 +151,11 @@ where
TransactionRow,
r#"
DELETE FROM transactions
WHERE id = $1
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND id = $2
RETURNING id, account_id, amount_cents, direction, date, description
"#,
user_id,
id,
)
.fetch_optional(executor)
+16 -1
View File
@@ -2,7 +2,19 @@ use crate::{domain::DomainError, repository::RepositoryError, routes::extractors
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("app id is already in use")]
#[error("account id already exists")]
AccountIdAlreadyExists,
#[error("account id not found")]
AccountIdNotFound,
#[error("transaction id already exists")]
TransactionIdAlreadyExists,
#[error("scheduled transaction id already exists")]
ScheduledTransactionIdAlreadyExists,
#[error("app id already exists")]
AppIdAlreadyExists,
#[error("invalid client credentials")]
@@ -11,6 +23,9 @@ pub enum AppError {
#[error("invalid refresh token")]
InvalidRefreshToken,
#[error("cannot remove the last member of an account")]
LastAccountMemberRemoval,
#[error("not found")]
NotFound,
+30 -33
View File
@@ -17,7 +17,11 @@ pub struct Query {
pub offset: Option<u64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<Account>, RepositoryError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -33,7 +37,7 @@ where
.transpose()?,
};
let accounts = db::list(executor, query)
let accounts = db::list(executor, user_id, query)
.await?
.into_iter()
.map(decode)
@@ -42,17 +46,25 @@ where
Ok(accounts)
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<Account>, RepositoryError>
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let account = db::get_by_id(executor, id).await?.map(decode).transpose()?;
let account = db::get_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
Ok(account)
}
pub async fn get_by_ids<'e, E>(
executor: E,
user_id: Uuid,
ids: &[Uuid],
) -> Result<HashMap<Uuid, Account>, RepositoryError>
where
@@ -62,7 +74,7 @@ where
return Ok(HashMap::new());
}
let accounts = db::get_by_ids(executor, ids)
let accounts = db::get_by_ids(executor, user_id, ids)
.await?
.into_iter()
.map(decode)
@@ -78,24 +90,30 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
account: Account,
) -> Result<Upsert<Account>, RepositoryError>
) -> Result<Option<Upsert<Account>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let account = db::upsert(executor, encode(account))
let upserted = db::upsert(executor, user_id, encode(account))
.await?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(account)
Ok(upserted)
}
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<Account>, RepositoryError>
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<Account>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let account = db::delete_by_id(executor, id)
let account = db::delete_by_id(executor, user_id, id)
.await
.map_err(classify_delete_error)?
.map(decode)
@@ -106,14 +124,6 @@ where
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
match &error {
DatabaseError::ForeignKeyViolation {
constraint: Constraint::AccountMemberAccount,
..
} => RepositoryError::ReferenceViolation {
relation: ReferenceRelation::AccountMember,
kind: ReferenceViolationKind::StillReferenced,
source: error,
},
DatabaseError::ForeignKeyViolation {
constraint: Constraint::TransactionAccount,
..
@@ -161,19 +171,6 @@ mod tests {
}
}
#[test]
fn classifies_account_member_account_delete_foreign_key_constraint() {
let error = classify_delete_error(foreign_key_violation(Constraint::AccountMemberAccount));
assert!(matches!(
error,
RepositoryError::ReferenceViolation {
relation: ReferenceRelation::AccountMember,
kind: ReferenceViolationKind::StillReferenced,
..
}
));
}
#[test]
fn classifies_account_delete_foreign_key_constraint() {
let error = classify_delete_error(foreign_key_violation(
@@ -22,6 +22,7 @@ pub struct Query {
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<RecurringTransaction>, RepositoryError>
where
@@ -38,7 +39,7 @@ where
.transpose()?,
};
let transactions = db::list(executor, query)
let transactions = db::list(executor, user_id, query)
.await?
.into_iter()
.map(decode)
@@ -49,30 +50,36 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<RecurringTransaction>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::get_by_id(executor, id).await?.map(decode).transpose()?;
let transaction = db::get_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
Ok(transaction)
}
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
transaction: RecurringTransaction,
) -> Result<Upsert<RecurringTransaction>, RepositoryError>
) -> Result<Option<Upsert<RecurringTransaction>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::upsert(executor, encode(transaction))
let upserted = db::upsert(executor, user_id, encode(transaction))
.await
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(transaction)
Ok(upserted)
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
@@ -96,12 +103,13 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<RecurringTransaction>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::delete_by_id(executor, id)
let transaction = db::delete_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
+24 -10
View File
@@ -15,7 +15,11 @@ pub struct Query {
pub offset: Option<u64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<Transaction>, RepositoryError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<Transaction>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -30,7 +34,7 @@ where
.transpose()?,
};
let transactions = db::list(executor, query)
let transactions = db::list(executor, user_id, query)
.await?
.into_iter()
.map(decode)
@@ -39,29 +43,38 @@ where
Ok(transactions)
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<Transaction>, RepositoryError>
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<Transaction>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::get_by_id(executor, id).await?.map(decode).transpose()?;
let transaction = db::get_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
Ok(transaction)
}
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
transaction: Transaction,
) -> Result<Upsert<Transaction>, RepositoryError>
) -> Result<Option<Upsert<Transaction>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::upsert(executor, encode(transaction))
let upserted = db::upsert(executor, user_id, encode(transaction))
.await
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(transaction)
Ok(upserted)
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
@@ -80,12 +93,13 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<Transaction>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let transaction = db::delete_by_id(executor, id)
let transaction = db::delete_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
+21 -6
View File
@@ -44,7 +44,7 @@ async fn list_account_members(
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_exists(&mut tx, account_id).await?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let members = repository::account_members::list(&mut *tx, query)
.await?
.into_iter()
@@ -63,7 +63,7 @@ async fn get_account_member(
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
) -> Result<Json<AccountMemberResponse>, AppError> {
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_exists(&mut tx, account_id).await?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let member = repository::account_members::get_by_id(&mut *tx, account_id, member_id)
.await?
.ok_or(AppError::NotFound)?;
@@ -83,7 +83,7 @@ async fn upsert_account_member(
let member = member.into_domain(member_id, account_id)?;
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_exists(&mut tx, account_id).await?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let upserted = repository::account_members::upsert(&mut *tx, member).await?;
tx.commit().await.map_err(RepositoryError::from)?;
@@ -104,7 +104,21 @@ async fn delete_account_member(
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, AppError> {
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_exists(&mut tx, account_id).await?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let members = repository::account_members::list(
&mut *tx,
repository::account_members::Query {
account_id,
limit: Some(2),
offset: None,
},
)
.await?;
if let [only] = members.as_slice()
&& only.id == member_id
{
return Err(AppError::LastAccountMemberRemoval);
}
let deleted =
repository::account_members::delete_by_id(&mut *tx, account_id, member_id).await?;
tx.commit().await.map_err(RepositoryError::from)?;
@@ -114,11 +128,12 @@ async fn delete_account_member(
Ok(StatusCode::NO_CONTENT)
}
async fn ensure_account_exists(
async fn ensure_account_ownership(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
account_id: Uuid,
) -> Result<(), AppError> {
repository::accounts::get_by_id(&mut *connection, account_id)
repository::accounts::get_by_id(&mut *connection, user_id, account_id)
.await?
.map(|_| ())
.ok_or(AppError::NotFound)
+27 -14
View File
@@ -7,7 +7,7 @@ use super::{
dtos::account::{AccountRequest, AccountResponse},
extractors::{Auth, Json, Path, Query},
};
use crate::{error::AppError, repository};
use crate::{domain::AccountMember, error::AppError, repository};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
@@ -34,27 +34,18 @@ async fn list_accounts(
State(pool): State<PgPool>,
Query(query): Query<QueryParams>,
) -> Result<Json<Vec<AccountResponse>>, AppError> {
let mut tx = pool
.begin()
.await
.map_err(repository::RepositoryError::from)?;
let query = repository::accounts::Query {
name: query.name,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
};
let accounts = repository::accounts::list(&mut *tx, query)
let accounts = repository::accounts::list(&pool, auth.user_id(), query)
.await?
.into_iter()
.map(AccountResponse::from)
.collect();
tx.commit()
.await
.map_err(repository::RepositoryError::from)?;
Ok(Json(accounts))
}
@@ -65,7 +56,7 @@ async fn get_account(
State(pool): State<PgPool>,
Path(id): Path<Uuid>,
) -> Result<Json<AccountResponse>, AppError> {
let account = repository::accounts::get_by_id(&pool, id)
let account = repository::accounts::get_by_id(&pool, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
@@ -80,9 +71,31 @@ async fn upsert_account(
Path(id): Path<Uuid>,
Json(account): Json<AccountRequest>,
) -> Result<(StatusCode, Json<AccountResponse>), AppError> {
let user_id = auth.user_id();
let account = account.into_domain(id)?;
let upserted = repository::accounts::upsert(&pool, account).await?;
let mut tx = pool
.begin()
.await
.map_err(repository::RepositoryError::from)?;
let upserted = repository::accounts::upsert(&mut *tx, user_id, account)
.await?
.ok_or(AppError::AccountIdAlreadyExists)?;
if upserted.previous.is_none() {
let member = AccountMember {
id: Uuid::new_v4(),
account_id: id,
user_id,
};
repository::account_members::upsert(&mut *tx, member).await?;
}
tx.commit()
.await
.map_err(repository::RepositoryError::from)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
} else {
@@ -99,7 +112,7 @@ async fn delete_account(
Path(id): Path<Uuid>,
State(pool): State<PgPool>,
) -> Result<StatusCode, AppError> {
repository::accounts::delete_by_id(&pool, id)
repository::accounts::delete_by_id(&pool, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
+18
View File
@@ -25,12 +25,30 @@ impl IntoResponse for AppError {
impl ClientError for AppError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::AccountIdAlreadyExists => {
(StatusCode::CONFLICT, "Account ID already exists".into())
}
Self::AccountIdNotFound => (
StatusCode::UNPROCESSABLE_ENTITY,
"Account ID cannot be found".into(),
),
Self::TransactionIdAlreadyExists => {
(StatusCode::CONFLICT, "Transaction ID already exists".into())
}
Self::ScheduledTransactionIdAlreadyExists => (
StatusCode::CONFLICT,
"Scheduled transaction ID already exists".into(),
),
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App ID already exists".into()),
Self::InvalidClientCredentials => (
StatusCode::UNAUTHORIZED,
"Invalid client credentials".into(),
),
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".into()),
Self::LastAccountMemberRemoval => (
StatusCode::CONFLICT,
"Cannot remove the last member of an account".into(),
),
Self::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
Self::Domain(error) => error.client_response(),
Self::Extractor(error) => error.client_response(),
+18 -9
View File
@@ -49,8 +49,9 @@ async fn list_scheduled_transactions(
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let transactions = repository::recurring_transactions::list(&mut *tx, query).await?;
let accounts = get_accounts_for_transactions(&mut tx, &transactions).await?;
let transactions =
repository::recurring_transactions::list(&mut *tx, auth.user_id(), query).await?;
let accounts = get_accounts_for_transactions(&mut tx, auth.user_id(), &transactions).await?;
tx.commit().await.map_err(RepositoryError::from)?;
let responses = transactions
@@ -69,11 +70,12 @@ async fn get_scheduled_transaction(
Path(id): Path<Uuid>,
) -> Result<Json<ScheduledTransactionResponse>, AppError> {
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let transaction = repository::recurring_transactions::get_by_id(&mut *tx, id)
let transaction = repository::recurring_transactions::get_by_id(&mut *tx, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
let accounts =
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
get_accounts_for_transactions(&mut tx, auth.user_id(), std::slice::from_ref(&transaction))
.await?;
tx.commit().await.map_err(RepositoryError::from)?;
Ok(Json(create_response(transaction, &accounts, Utc::now())?))
@@ -91,9 +93,13 @@ async fn upsert_scheduled_transaction(
let transaction = transaction.into_domain(id)?;
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let upserted = repository::recurring_transactions::upsert(&mut *tx, transaction).await?;
let accounts =
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&upserted.current)).await?;
let account = accounts::get_by_id(&mut *tx, auth.user_id(), transaction.account_id)
.await?
.ok_or(AppError::AccountIdNotFound)?;
let upserted =
repository::recurring_transactions::upsert(&mut *tx, auth.user_id(), transaction)
.await?
.ok_or(AppError::ScheduledTransactionIdAlreadyExists)?;
tx.commit().await.map_err(RepositoryError::from)?;
let status = if upserted.previous.is_some() {
@@ -102,6 +108,8 @@ async fn upsert_scheduled_transaction(
StatusCode::CREATED
};
let accounts = HashMap::from([(account.id, account)]);
Ok((
status,
Json(create_response(upserted.current, &accounts, Utc::now())?),
@@ -115,7 +123,7 @@ async fn delete_scheduled_transaction(
State(pool): State<PgPool>,
Path(id): Path<Uuid>,
) -> Result<StatusCode, AppError> {
repository::recurring_transactions::delete_by_id(&pool, id)
repository::recurring_transactions::delete_by_id(&pool, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
@@ -124,6 +132,7 @@ async fn delete_scheduled_transaction(
async fn get_accounts_for_transactions(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
transactions: &[domain::RecurringTransaction],
) -> Result<HashMap<Uuid, domain::Account>, AppError> {
let account_ids = transactions
@@ -133,7 +142,7 @@ async fn get_accounts_for_transactions(
.into_iter()
.collect::<Vec<_>>();
Ok(accounts::get_by_ids(connection, &account_ids).await?)
Ok(accounts::get_by_ids(connection, user_id, &account_ids).await?)
}
fn create_response(
+16 -9
View File
@@ -45,8 +45,8 @@ async fn list_transactions(
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let transactions = repository::transactions::list(&mut *tx, query).await?;
let accounts = get_accounts_for_transactions(&mut tx, &transactions).await?;
let transactions = repository::transactions::list(&mut *tx, auth.user_id(), query).await?;
let accounts = get_accounts_for_transactions(&mut tx, auth.user_id(), &transactions).await?;
tx.commit().await.map_err(RepositoryError::from)?;
let responses = transactions
@@ -65,11 +65,12 @@ async fn get_transaction(
Path(id): Path<Uuid>,
) -> Result<Json<TransactionResponse>, AppError> {
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let transaction = repository::transactions::get_by_id(&mut *tx, id)
let transaction = repository::transactions::get_by_id(&mut *tx, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
let accounts =
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
get_accounts_for_transactions(&mut tx, auth.user_id(), std::slice::from_ref(&transaction))
.await?;
tx.commit().await.map_err(RepositoryError::from)?;
Ok(Json(create_response(transaction, &accounts)?))
@@ -86,9 +87,12 @@ async fn upsert_transaction(
let transaction = transaction.into_domain(id)?;
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let upserted = repository::transactions::upsert(&mut *tx, transaction).await?;
let accounts =
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&upserted.current)).await?;
let account = repository::accounts::get_by_id(&mut *tx, auth.user_id(), transaction.account_id)
.await?
.ok_or(AppError::AccountIdNotFound)?;
let upserted = repository::transactions::upsert(&mut *tx, auth.user_id(), transaction)
.await?
.ok_or(AppError::TransactionIdAlreadyExists)?;
tx.commit().await.map_err(RepositoryError::from)?;
let status = if upserted.previous.is_some() {
@@ -97,6 +101,8 @@ async fn upsert_transaction(
StatusCode::CREATED
};
let accounts = HashMap::from([(account.id, account)]);
Ok((status, Json(create_response(upserted.current, &accounts)?)))
}
@@ -107,7 +113,7 @@ async fn delete_transaction(
Path(id): Path<Uuid>,
State(pool): State<PgPool>,
) -> Result<StatusCode, AppError> {
repository::transactions::delete_by_id(&pool, id)
repository::transactions::delete_by_id(&pool, auth.user_id(), id)
.await?
.ok_or(AppError::NotFound)?;
@@ -116,6 +122,7 @@ async fn delete_transaction(
async fn get_accounts_for_transactions(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
transactions: &[domain::Transaction],
) -> Result<HashMap<Uuid, domain::Account>, AppError> {
let account_ids = transactions
@@ -125,7 +132,7 @@ async fn get_accounts_for_transactions(
.into_iter()
.collect::<Vec<_>>();
Ok(repository::accounts::get_by_ids(connection, &account_ids).await?)
Ok(repository::accounts::get_by_ids(connection, user_id, &account_ids).await?)
}
fn create_response(