PostgreSQLClientKit querying database

93 Views Asked by At

Is there a short way to prepare the statements and execute them, if you are trying to run multiple queries and you are not concerned with the results that are generated by those statements.

Forexample I want to execute these two statements, is there any short way to write these two statements and execute them.

do{
        let load_age_statement = try connection.prepareStatement(text: "Load 'age';")
        let set_path_statement = try connection.prepareStatement(text: "SET search_path = ag_catalog, '$user', public;")
    
        var cursor = try load_age_statement.execute()
        load_age_statement.close()
        cursor  = try set_path_statement.execute()
        
}catch{
        print(error)
}
2

There are 2 best solutions below

0
On

You can execute multiple statements in a single query in PostgresqlClientKit. Here's the example:

do {
    let multiStatement = """
                            LOAD 'age';
                            SET search_path = ag_catalog, '$user', public;
                            """
    try connection.query(multiStatement)
} catch {
    print(error)
}

The important thing is that this is only helpful when executed statements do not return any result otherwise you cannot use this multi-statement technique and you have to handle their results separately.

0
On

You can try creating a utility function for implementing multiple queries. Try the below example which accepts a list of queries

import Foundation

func executeMultipleStatements(connection: Connection, queries: [String]) {
    for query in queries {
        do {
            let statement = try connection.prepareStatement(text: query)
            let _ = try statement.execute()
            statement.close()
        } catch {
            print("Error executing query '\(query)': \(error)")
        }
    }
}

do {
    let connection = try Connection()
    let queries = [
        "LOAD 'age';",
        "SET search_path = ag_catalog, '$user', public;"
    ]
    executeMultipleStatements(connection: connection, queries: queries)
} catch {
    print("Error: \(error)")
}