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_encode2.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, fsize;
49
50 switch (PQresultStatus(res)) {
51 case PGRES_TUPLES_OK:
52 n_rows = PQntuples(res);
53 n_cols = PQnfields(res);
54 ei_x_encode_tuple_header(x, 2);
55 encode_ok(x);
56 ei_x_encode_list_header(x, 1);
57 for (col = 0; col < n_cols; ++col) {
58 ei_x_encode_list_header(x, 1);
59 ei_x_encode_string(x, PQfname(res, col));
60 }
61 ei_x_encode_empty_list(x);
62 for (row = 0; row < n_rows; ++row) {
63 ei_x_encode_list_header(x, 1);
64 for (col = 0; col < n_cols; ++col) {
65 ei_x_encode_list_header(x, 1);
66 fsize = PQgetlength(res, row, col);
67 ei_x_encode_binary(x, PQgetvalue(res, row, col), fsize);
68 }
69 ei_x_encode_empty_list(x);
70 }
71 ei_x_encode_empty_list(x);
72 break;
73 case PGRES_COMMAND_OK:
74 ei_x_encode_tuple_header(x, 2);
75 encode_ok(x);
76 ei_x_encode_string(x, PQcmdTuples(res));
77 break;
78 default:
79 encode_error(x, conn);
80 break;
81 }
82 }
83
84