Skip to content

Commit

Permalink
Merge pull request jpmens#339 from jklimke/postgres_reconnect
Browse files Browse the repository at this point in the history
Try postgres reconnect on database connection lost
  • Loading branch information
jpmens authored Apr 20, 2018
2 parents 0481e4f + 24a4f20 commit 2eeee36
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions be-postgres.c
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ int be_pg_getuser(void *handle, const char *username, const char *password, char

if (PQresultStatus(res) != PGRES_TUPLES_OK) {
_log(LOG_DEBUG, "%s\n", PQresultErrorMessage(res));
if(PQstatus(conf->conn) == CONNECTION_BAD){
_log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n");
//try to reinitiate the database connection
PQreset(conf->conn);
}

goto out;
}
if ((nrows = PQntuples(res)) != 1) {
Expand All @@ -194,7 +200,7 @@ int be_pg_getuser(void *handle, const char *username, const char *password, char
}
if ((v = PQgetvalue(res, 0, 0)) == NULL) {
goto out;
}
}
value = (v) ? strdup(v) : NULL;


Expand Down Expand Up @@ -233,6 +239,13 @@ int be_pg_superuser(void *handle, const char *username)
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "%s\n", PQresultErrorMessage(res));
issuper = BACKEND_ERROR;
//try to reset connection if failing because of database connection lost
if(PQstatus(conf->conn) == CONNECTION_BAD){
_log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n");
//try to reinitiate the database connection
PQreset(conf->conn);
}

goto out;
}
if ((nrows = PQntuples(res)) != 1) {
Expand Down Expand Up @@ -296,6 +309,14 @@ int be_pg_aclcheck(void *handle, const char *clientid, const char *username, con
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "%s\n", PQresultErrorMessage(res));
match = BACKEND_ERROR;

//try to reset connection if failing because of database connection lost
if(PQstatus(conf->conn) == CONNECTION_BAD){
_log(LOG_NOTICE, "Noticed a postgres connection loss. Trying to reconnect ...\n");
//try to reinitiate the database connection
PQreset(conf->conn);
}

goto out;
}
if (PQnfields(res) != 1) {
Expand Down Expand Up @@ -413,8 +434,8 @@ int addKeyValue(char **keywords, char **values, char *key, char *value,
n++;

// In case of not zero-terminated dictionary
keywords[n] = '\0';
values[n] = '\0';
keywords[n] = 0;
values[n] = 0;

return n;
}
Expand Down

0 comments on commit 2eeee36

Please sign in to comment.