0

I am trying to fetch the count of rows from the PostgreSQL database using PostgresClientKit but I am getting the following error Value of type 'Any' has no member 'int'.

This is the code

let rows = fetchSQL(statement: "SELECT count(*) FROM ag_graph WHERE name='" + graphName + "'", connection: connection);
        
        let row_counts = rows[0] as! [Any];
        let count = try row_counts[0].int();
        if count < 1{
            // My Code
        }

I have tried printing the rows. It is

[[1]]

The definition of fetchSQL function is as follow

func fetchSQL(statement:String, connection:Connection)-> [Any]{
    var rows:[Any] = [];
    do{
        let statement = try connection.prepareStatement(text: statement)
        defer { statement.close() }
        
        let cursor = try statement.execute()
        defer { cursor.close() }

        for row in cursor {
            rows.append(try row.get().columns);
        }
    }catch{
        print(error)
    }
    
    return rows;
}
Fahad Zaheer
  • 47
  • 1
  • 7
  • Have your tried this: `let count = rows.count` then `print("\(count)")`. Note there is no need for the `;` in Swift – workingdog support Ukraine Feb 13 '23 at 11:27
  • Well you need to adjust your cast to what you actually get back, what about debugging or adding some print statements to fetchSQL to see what the content is of a row (I would guess it's simply an Int since you are returning the result of `count(*)` but that is just my guess). Also what type has a function int()`? Looks like you are actually expecting a specific type here. – Joakim Danielson Feb 13 '23 at 11:30
  • @workingdogsupportUkraine That is always 1 since the sql query is returning one row. – Joakim Danielson Feb 13 '23 at 11:32
  • Yes the issue is resolved. PostgreSQLClientKit returns a specific type of PostgresValue that can be converted to int using int() funciton – Fahad Zaheer Feb 13 '23 at 11:36

2 Answers2

0

The issue looks like you are trying to call the int() method on an instance of Any which doesn't have that method. Try casting the value to the appropriate type first.

let row_counts = rows[0] as! [Any]
let count = row_counts[0] as! Int // cast to Int instead of using int()
Safi50
  • 379
  • 1
  • 7
-1

Try this way . It will probably help.

 let rows = fetchSQL(statement: "SELECT count(*) FROM ag_graph WHERE name='" + graphName + "'", connection: connection);
            print(rows)
            let row_counts = rows[0] as! [PostgresValue];
            let count = try row_counts[0].int();
            if count < 1{
                // your code
            }