1 /*
2  * %CopyrightBegin%
3  *
4  * Copyright Ericsson AB 2006-2016. All Rights Reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * %CopyrightEnd%
19  */
20 #include <erl_driver.h>
21 
22 #include <libpq-fe.h>
23 
24 #include <ei.h>
25 
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 
30 #include "pg_encode.h"
31 
encode_ok(ei_x_buff * x)32 void encode_ok(ei_x_buff* x)
33 {
34     const char* k_ok = "ok";
35     ei_x_encode_atom(x, k_ok);
36 }
37 
encode_error(ei_x_buff * x,PGconn * conn)38 void encode_error(ei_x_buff* x, PGconn* conn)
39 {
40     const char* k_error = "error";
41     ei_x_encode_tuple_header(x, 2);
42     ei_x_encode_atom(x, k_error);
43     ei_x_encode_string(x, PQerrorMessage(conn));
44 }
45 
encode_result(ei_x_buff * x,PGresult * res,PGconn * conn)46 void encode_result(ei_x_buff* x, PGresult* res, PGconn* conn)
47 {
48     int row, n_rows, col, n_cols;
49     switch (PQresultStatus(res)) {
50     case PGRES_TUPLES_OK:
51 	n_rows = PQntuples(res);
52 	n_cols = PQnfields(res);
53 	ei_x_encode_tuple_header(x, 2);
54 	encode_ok(x);
55 	ei_x_encode_list_header(x, n_rows+1);
56  	ei_x_encode_list_header(x, n_cols);
57 	for (col = 0; col < n_cols; ++col) {
58 	    ei_x_encode_string(x, PQfname(res, col));
59 	}
60 	ei_x_encode_empty_list(x);
61 	for (row = 0; row < n_rows; ++row) {
62 	    ei_x_encode_list_header(x, n_cols);
63 	    for (col = 0; col < n_cols; ++col) {
64 		ei_x_encode_string(x, PQgetvalue(res, row, col));
65 	    }
66 	    ei_x_encode_empty_list(x);
67 	}
68 	ei_x_encode_empty_list(x);
69 	break;
70     case PGRES_COMMAND_OK:
71 	ei_x_encode_tuple_header(x, 2);
72         encode_ok(x);
73 	ei_x_encode_string(x, PQcmdTuples(res));
74         break;
75     default:
76 	encode_error(x, conn);
77 	break;
78     }
79 }
80 
81