From a940bf1599a451689a605927d257ebef2f603467 Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Sat, 8 May 2021 23:32:22 +0200 Subject: [PATCH] Add C/PostgreSQL version --- Makefile | 6 ++++ dcb_c_psql.c | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 Makefile create mode 100644 dcb_c_psql.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b841b44 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ +CFLAGS=-I/usr/include/postgresql -O3 + +all: dcb_c_psql + +dcb_c_psql: dcb_c_psql.o + $(CC) -o $@ $^ -lpq diff --git a/dcb_c_psql.c b/dcb_c_psql.c new file mode 100644 index 0000000..3024031 --- /dev/null +++ b/dcb_c_psql.c @@ -0,0 +1,88 @@ +/* + * This program is based on + * src/test/examples/testlibpq.c (example 33.1) + * from section 33.21 of the PostgreSQL documentation + * (https://www.postgresql.org/docs/13/libpq-example.html) + * + */ +#include +#include +#include +#include "libpq-fe.h" + +static void +exit_nicely(PGconn *conn) +{ + PQfinish(conn); + exit(1); +} + +int +main(int argc, char **argv) +{ + const char *conninfo; + PGconn *conn; + PGresult *res; + int nFields; + int i, + j; + struct timespec ts0, ts1, ts2, ts3, ts4; + + /* + * If the user supplies a parameter on the command line, use it as the + * conninfo string; otherwise default to setting dbname=postgres and using + * environment variables or defaults for all other connection parameters. + */ + if (argc > 1) + conninfo = argv[1]; + else + conninfo = ""; + + clock_gettime(CLOCK_MONOTONIC, &ts0); + + /* Make a connection to the database */ + conn = PQconnectdb(conninfo); + + /* Check to see that the backend connection was successfully made */ + if (PQstatus(conn) != CONNECTION_OK) + { + fprintf(stderr, "Connection to database failed: %s", + PQerrorMessage(conn)); + exit_nicely(conn); + } + clock_gettime(CLOCK_MONOTONIC, &ts1); + + res = PQexec(conn, "select current_timestamp"); + if (PQresultStatus(res) != PGRES_TUPLES_OK) + { + fprintf(stderr, "Select command failed: %s", PQerrorMessage(conn)); + PQclear(res); + exit_nicely(conn); + } + + /* first, print out the attribute names */ + nFields = PQnfields(res); + for (i = 0; i < nFields; i++) + printf("%-15s", PQfname(res, i)); + printf("\n\n"); + + /* next, print out the rows */ + for (i = 0; i < PQntuples(res); i++) + { + for (j = 0; j < nFields; j++) + printf("%-15s", PQgetvalue(res, i, j)); + printf("\n"); + } + + PQclear(res); + clock_gettime(CLOCK_MONOTONIC, &ts2); + + /* close the connection to the database and cleanup */ + PQfinish(conn); + clock_gettime(CLOCK_MONOTONIC, &ts3); + printf("%f connect\n", (ts1.tv_sec - ts0.tv_sec) + (ts1.tv_nsec - ts0.tv_nsec) * 1E-9); + printf("%f session\n", (ts3.tv_sec - ts0.tv_sec) + (ts3.tv_nsec - ts0.tv_nsec) * 1E-9); + + return 0; +} +