#include <postgresql/libpq-fe.h>
#include <unistd.h>
#include <iostream>

using namespace std;

const char* connInfo = nullptr;

bool
reconnect  (PGconn*& dbh)
{
    if (dbh) PQfinish (dbh);
    dbh = PQconnectdb (connInfo);
    return PQstatus (dbh) == CONNECTION_OK;
}

bool
reset (PGconn*& dbh)
{
    PQreset (dbh);
    return PQstatus (dbh) == CONNECTION_OK;
}

int
main (int argc, char** argv)
{
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " CONN-INFO" << endl;
        exit (1);
    }

    connInfo = argv[1];
    int status = 1;
    PGconn* dbh = nullptr;
    reconnect (dbh);

    while (true) {
        if (PQstatus (dbh) != CONNECTION_OK) {
            cerr << "Error @" << (void*) PQerrorMessage (dbh) << ": " << PQerrorMessage (dbh);
            reset (dbh);
        } else {
            auto* res = PQexec (dbh, "select now()");
            if (PQresultStatus (res) != PGRES_TUPLES_OK) {
                cerr << "Query error: " << PQresultErrorMessage (res);
            } else {
                cout << '.' << flush;
            }
            if (res) PQclear (res);
        }
        sleep (1);
    }

    if (dbh) PQfinish (dbh);
    exit (status);
}
