codewinsdotcom/PostgresClientKit

getting Query result in an Array

pwascheul opened this issue · 3 comments

Hi @pitfield,
probably a dumb questions but I am novice.
i am trying to get my query results into an Array so it is very flexible and can use the function for any queries.
however I am not able to succeed, any advise ?

private func dbquery(SQLQuery: String) -> Array<Any> {
    var resultArray: Array<Any>
      
    do{
        var configuration = PostgresClientKit.ConnectionConfiguration()
        configuration.host = "my host"
        configuration.database = "mydb"
        configuration.user = "dbuser"
        configuration.credential = .md5Password(password: dbpwd)
        print("""
              attempting connection @ \(configuration.host), on \(configuration.database)with user \(configuration.user)
              """)
        let connection = try PostgresClientKit.Connection(configuration: configuration)
        print ("connection established")
        defer{ connection.close() }
        

        let statement = try connection.prepareStatement(text: SQLQuery)
        
        defer{ statement.close() }
        
        let cursor = try statement.execute()
        defer{ cursor.close() }
        
        for row in cursor {
            let columns = try row.get().columns
            let values = try row.get().decodeByColumnIndex(columns)
            print (values)
            resultArray.append(values)
        }

    } catch{
        print(error)
    }
    return resultArray``

I am getting an error in Let Values .... : Cannot convert value of Type '[PostGresValue]' to expected argument type 'T.Type'

Your code snippet is close. You'll need:

var resultArray = [[PostgresValue]]()

which is shorthand for Array<Array<PostgresValue>>() to create a two dimensional array. Then:

let columns = try row.get().columns
resultArray.append(columns)

(decodeByColumnIndex is used when you want to create an instance of a type with a separate stored property for each selected column; see Playgrounds/DecodeByColumnIndex for an example)

Thanks Pit,
using your snippet fills the array with "raw data" : [1, Doe, John, john_doe@gmail.com, jdoe, t, 03/11/2022 15:00:00, nil, 1, echo123]. is there a possibility to get data filled with appropriate type , for the same example it should be [Int, String, String, String, String, Bool, Date, Date,Int, string] ?

There isn't a 1:1 mapping between SQL data types and Swift types. (See the last question in the FAQ.)

So you need to specify the desired Swift type, either using the methods on PostgresValue or by using the decodeByColumnName and decodeByColumnIndex methods on Row. There are examples of each approach in the Playgrounds folder.