From 8878b1d92bdd8ee9b51ecde7e9cc88f62f264841 Mon Sep 17 00:00:00 2001 From: Mateus Cruz Date: Mon, 5 Feb 2024 11:06:46 -0300 Subject: move routes handler module to its own file --- lib/query.ml | 76 +++++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 50 insertions(+), 26 deletions(-) (limited to 'lib/query.ml') diff --git a/lib/query.ml b/lib/query.ml index 0fb6f7e..85f91f0 100644 --- a/lib/query.ml +++ b/lib/query.ml @@ -1,37 +1,61 @@ type pool = ((module Rapper_helper.CONNECTION), Caqti_error.t) Caqti_eio.Pool.t -let transaction_query = - [%rapper - execute - {sql| +module Q = struct + let transaction = + [%rapper + execute + {sql| INSERT INTO transactions (client_id, value, type, description) VALUES (%int{client_id}, %int{value}, %Operation.TransactionType{transaction_type}, %string{description}) |sql}] -;; + ;; -let client_query = - let open Client in - [%rapper - get_opt - {sql| - SELECT @int{id}, @int{mov_limit} FROM clients WHERE id = %int{id} - |sql} - record_out] -;; + let debit = + [%rapper + execute + {sql| + UPDATE balances SET value = value - %int{value} WHERE client_id = %int{client_id} + |sql}] + ;; + + let credit = + [%rapper + execute + {sql| + UPDATE balances SET value = value + %int{value} WHERE client_id = %int{client_id} + |sql}] + ;; + + let client = + let open Client in + [%rapper + get_opt + {sql| + SELECT @int{id}, @int{mov_limit} FROM clients WHERE id = %int{id} + |sql} + record_out] + ;; + + let balance = + [%rapper + get_opt + {sql| + SELECT @int{value}, @ptime{now()} as time FROM balances WHERE client_id = %int{client_id} + |sql}] + ;; +end + +let ( let* ) = Result.bind -let execute_operation ~client_id ~(op : Operation.t) pool = +let execute_operation ~client_id ~(op : Operation.t) conn = match op with - | Transaction data -> - Caqti_eio.Pool.use - (fun conn -> - transaction_query - ~client_id - ~value:data.value - ~transaction_type:data.transaction_type - ~description:data.description - conn) - pool + | Transaction { value; description; transaction_type } -> + let* () = Q.transaction ~client_id ~value ~description conn ~transaction_type in + (match transaction_type with + | Credit -> Q.credit ~value ~client_id conn + | Debit -> Q.debit ~value ~client_id conn) | _ -> failwith "TODO" ;; -let find_client id pool = Caqti_eio.Pool.use (fun conn -> client_query ~id conn) pool +let find_client id conn = Q.client ~id conn +let balance client_id conn = Q.balance ~client_id conn -- cgit v1.2.3