Calling PQprint from Postgres C ibpq library

I am bridging libpq-fe.h to connect to a postgres database.

#import <libpq-fe.h>

in my swift code, i execute...

let conn = PQconnectdb("dbname=paul port=5432 user=paul host=localhost".cString(using: .utf8))
if PQstatus(conn) == CONNECTION_OK {
    let result = PQexec(conn, "SELECT * FROM user_accounts")
    for i in 0 ..< PQnfields(result) {
        guard let value = PQfname(result, i) else {continue}
        let columnName = String(cString: value)
        print("\(columnName) | ", terminator:"")
    }
    print()
    var printOptions = PQprintOpt()
    printOptions.header = 1
    withUnsafePointer(to: &printOptions) {
        PQprint(stdout, result, UnsafePointer($0))
    }
    PQclear(result)
}
PQfinish(conn)

The output for PQfname works and provides the expected output

user_id | username | password | email | created_on | last_login |

however, i'm unable to get PQprint to work. It compiles, but throws a run-time exception
thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
when calling PQprint

Am I casting the options struct incorrectly? How should it be called?

Hm. You shouldn't need the extra conversion to UnsafePointer; that might be what's throwing it off. The other thing I can think of is if it wants you to provide all the strings in the PQprintOpt struct, but that seems unlikely.

@jrose, thanks for the hint. I needed to initialize the string separator in the struct to a non-nil value

var printOptions = PQprintOpt()
printOptions.header = 1
let cString = strdup("|")  
printOptions.fieldSep = cString

The function now works.

Terms of Service

Privacy Policy

Cookie Policy