/* qureje is a database managment tool. Copyright (C) 2022 Alessandro Iezzi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include "database.h" #include "utils.h" static char * parameter(const char *key, char *value) { int vsize = 0; char *param = NULL; if (value == NULL || (vsize = strlen(value)) <= 0) return NULL; param = strcrt(strlen(key) + vsize + 2); strcat(param, key); strcat(param, "="); strcat(param, value); strcat(param, " "); return param; } static void prmcat(char *conninfo, char *prm) { if (prm != NULL) { strcat(conninfo, prm); free(prm); } } static char * create_connection_info(qureje_conn *conn) { int strsize = 0; char *conninfo, *prmusr = NULL, *prmdb = NULL; if ((prmusr = parameter("user", conn->user)) != NULL) { strsize += strlen(prmusr); } if ((prmdb = parameter("dbname", conn->dbname)) != NULL) { strsize += strlen(prmdb); } conninfo = strcrt(strsize + 1); prmcat(conninfo, prmusr); prmcat(conninfo, prmdb ); return conninfo; } int qureje_psql_connect(qureje_conn *conn) { char *conninfo = NULL; PGconn *pgconn; if (conn == NULL) return 1; conninfo = create_connection_info(conn); /* * Using an empty connectstring will use default values for everything. * If set, the environment variables PGHOST, PGDATABASE, PGPORT and * PGUSER will be used. */ pgconn = PQconnectdb(conninfo); free(conninfo); /* * This can only happen if there is not enough memory * to allocate the PGconn structure. */ if (pgconn == NULL) { fprintf(stderr, "Out of memory connecting to PostgreSQL.\n"); return 1; } /* check if the connection attempt worked */ if (PQstatus(pgconn) != CONNECTION_OK) { fprintf(stderr, "%s\n", PQerrorMessage(pgconn)); /* * Even if the connection failed, the PGconn structure has been * allocated and must be freed. */ PQfinish(pgconn); return 1; } /* this program expects the database to return data in UTF-8 */ PQsetClientEncoding(pgconn, "UTF8"); conn->conn = pgconn; return 0; }