5
5
#include "transaction.h"
6
6
#include <zmq.h>
7
7
8
- int receive_message (int LEN , char * buffer , char * json ) {
9
- int size = zmq_recv (zmq_responder , buffer , LEN , 0 );
10
- if (size == -1 ){
11
- return 0 ;
12
- }
13
- int i = 0 ;
14
- while (i <= LEN + 1 ) {
15
- if (buffer [i ] == '}' ) {
16
- buffer [i + 1 ] = '\0' ;
17
- LEN = i + 1 ;
18
- break ;
19
- }
20
- i += 1 ;
21
- }
22
- int j = 0 ;
23
- while (j <=LEN ) {
24
- json [j ] = buffer [j ];
25
- j += 1 ;
26
- }
27
- return LEN ;
28
- }
8
+ enum direction {in ,out };
29
9
30
10
void transaction () {
31
11
json_value * value ;
32
- int LEN = 50 ;
12
+ int LEN = 1028 ;
33
13
char * buffer = (char * ) malloc (LEN );
34
14
char * json = (char * ) malloc (LEN );
35
15
LEN = receive_message (LEN , buffer , json );
@@ -41,11 +21,16 @@ void transaction() {
41
21
const char * error = "{\"error\":\"Unable to parse data\"}" ;
42
22
zmq_send (zmq_responder , error , strlen (error ), 0 );
43
23
}else {
44
- const char * param_values [2 ];
45
- const char * keys [] = {"user" , "amount" };
46
- for (int i = 0 ; i < 2 ; ++ i ) {
24
+ int param_len = 3 ;
25
+ const char * param_values [param_len ];
26
+ const char * keys [] = {"user" , "amount" , "direction" };
27
+ for (int i = 0 ; i < param_len ; ++ i ) {
47
28
if (strncasecmp (value -> u .object .values [i ].name , keys [i ], strlen (keys [i ])) == 0 ) {
48
29
param_values [i ] = value -> u .object .values [i ].value -> u .string .ptr ;
30
+ if (i == 2 && strncasecmp (value -> u .object .values [i ].value -> u .string .ptr , "in" , strlen ("in" )) == 0 ) {
31
+ param_values [i ] = "1" ;
32
+ }else if (i == 2 && strncasecmp (value -> u .object .values [i ].value -> u .string .ptr , "out" , strlen ("out" )) == 0 )
33
+ param_values [i ]= "0" ;
49
34
}
50
35
}
51
36
transactional (param_values );
@@ -77,9 +62,12 @@ void transactional(const char *const *param_values) {
77
62
78
63
}
79
64
if (rollback == 0 ) {
80
- // Update user balance and subtract the withdraw amount
81
- char * udt = "UPDATE account SET balance = balance - $2 WHERE user_id=$1" ;
82
- response = PQexecParams (conn , udt , 2 , NULL , param_values , NULL , NULL , 0 );
65
+ char * udt [] = {"UPDATE account SET balance=balance-$2 WHERE user_id=$1" ,
66
+ "UPDATE account SET balance=balance+$2 WHERE user_id=$1" };
67
+ if (strncasecmp (param_values [2 ], "0" , 1 )== 0 )
68
+ response = PQexecParams (conn , udt [0 ], 2 , NULL , param_values , NULL , NULL , 0 );
69
+ if (strncasecmp (param_values [2 ], "1" , 1 )== 0 )
70
+ response = PQexecParams (conn , udt [1 ], 2 , NULL , param_values , NULL , NULL , 0 );
83
71
command_error_handler (conn , response );
84
72
PQclear (response );
85
73
0 commit comments