summaryrefslogtreecommitdiff
path: root/lib/query.ml
diff options
context:
space:
mode:
authorMateus Cruz <mateuscolvr@gmail.com>2024-02-05 11:06:46 -0300
committerMateus Cruz <mateuscolvr@gmail.com>2024-02-05 11:06:46 -0300
commit8878b1d92bdd8ee9b51ecde7e9cc88f62f264841 (patch)
tree46d6c47dfc820689baa552d97255adeda4c98b15 /lib/query.ml
parent5a2f5bf9a12b270e15757df48afeb1c1db5b34b3 (diff)
move routes handler module to its own file
Diffstat (limited to 'lib/query.ml')
-rw-r--r--lib/query.ml76
1 files changed, 50 insertions, 26 deletions
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