-2

I'm trying to use the PQprint function from libpq (PostgreSQL 14) to print a query on terminal, which requires a PQprintOpt struct instance as an argument. I've followed what pretty much is the only example I could find (which isn't even on the documentation since PQprint over there has a very basic example):

int main(int argc, char* argv[]) {
    [...] // Irrelevant connection procedure

    PGresult* res = PQexec(conn, "SELECT * FROM progetto");
    checkResults(res, conn); // Just a function for checking results
    
    PQprintOpt options = {0};
    options.header = 1;
    options.align = 1;
    options.fieldSep = "|"; // This gives the warning/error

    PQprint(stdout, res, &options);

    PQclear(res);
    PQfinish(conn);

    return 0;
}

I knew something was weird given that it's using " for what should be a char in the struct, but either way it won't work. If it's a string it gives the warning on title, compiling but not printing anything, if I replace the double quotes with single quotes it just errors out on compile: error: invalid conversion from 'char' to 'char*'

I honestly have no idea on what to do at this point.

JHBonarius
  • 8,837
  • 3
  • 16
  • 32
Gyarik
  • 1
  • 1
  • The member variable is declared as `char* fieldSep`, see https://github.com/postgres/postgres/blob/ebc8b7d4416d8e0dfb7c05132ef6182fd3daf885/src/interfaces/libpq/libpq-fe.h#L211 ; Someone probably forgot to make the types their pointers point to "as const as possible", i.e. didn't declare the variable as `char const*`. Consult the documentation on whether the function takes ownership of any of the strings; otherwise just make a modifiable copy of the string in a local variable `char fieldSepModifiable[] = "|"; options.fieldSep = filedSepModifiable;` – fabian May 14 '22 at 11:44
  • Depending on the actual use of the var, adding a const cast could be sufficient btw... – fabian May 14 '22 at 11:44
  • This is an oversight on PQ's side, just as they take the argument as `const PQprintOpt *po`, they could have declared those `char *` fields as `const char *`. But they haven't. The downvotes are somewhat just though, searching for the message, `ISO C++ forbids converting a string constant to 'char*'` has plenty of [results](https://stackoverflow.com/search?q=ISO+C%2B%2B+forbids+converting+a+string+constant+to+%27char*%27) – tevemadar May 14 '22 at 12:30
  • @tevemadar I did check those answers actually, and came out more confused as it would still print nothing, and with no warnings nonetheless, so at this point I think it's not even a `PQprintOpt` issue, but a `PQprint` one. Reading the source, it seems as if none of the print options work properly, or rather, aren't compatible with what I'm trying to do. So instead I've done my own print and called it a day. Still, at least I understand how much more important is const than I thought, so thanks. – Gyarik May 14 '22 at 12:46

0 Answers0