Reputation: 1480
I am trying to connect a PostgreSQL database using it. I have the following code:
import ballerina/io;
import ballerinax/java.jdbc;
import ballerina/sql;
public function main() {
io:println("Hola mundo");
jdbc:Client|sql:Error dbClient =
new("jdbc:postgresql://localhost:5432/GenteDB","gente","GenteDB123!");
io:println(dbClient);
sql:ExecutionResult result =
check dbClient->execute(`CREATE TABLE student (
id INT AUTO_INCREMENT,
age INT,
name VARCHAR(255),
PRIMARY KEY (id)
)`);
}
This doesn't compile and I get the following error:
ERROR [main.bal:(13:23,18:45)] invalid remote method call: expected a client object, but found '(ballerinax/java.jdbc:1.4.1:Client|ballerina/sql:1.4.1:Error)'
Unfortunately, documentation is scarce, google turned up exactly 0 results for this error message (a first in my lifetime). The line with the error (check dbClient->execute...) was copied directly from ballerina's JDBC driver GitHub page. I have no idea what this error means. What am I missing? Any help will be appreciated.
Upvotes: 1
Views: 186
Reputation: 1445
This is because of Ballerina Error Handling is different from other languages, For more details on error handling see Ballerina By Example: Error Handling.
To look into this specific case. When invoking execute()
method dbClient
may be either jdbc:Client
or sql:Error
. You can call the remote method only if the variable is of type jdbc:Client
. You should narrow the type of the dbClient
before the remote method is invoked.
if dbClient is error {
// handle the error
} else {
// Type of `dbClient` will be `jdbc:Client` here.
sql:ExecutionResult result =
check dbClient->execute(`...`);
}
Alternatively, you can use check keyword to narrow the type as sql:Error
is an error type in Ballerina.
jdbc:Client dbClient = check new("jdbc:postgresql://localhost:5432/GenteDB","gente","GenteDB123!");
For more details on handling errors with check expression see Ballerina By Example: Check Expression.
Do note, the check with return the error. Here, the main function needs to be updated as follows,
import ballerina/io;
import ballerinax/java.jdbc;
import ballerina/sql;
public function main() returns error? {
io:println("Hola mundo");
jdbc:Client dbClient = check new("jdbc:postgresql://localhost:5432/GenteDB","gente","GenteDB123!");
io:println(dbClient);
sql:ExecutionResult result =
check dbClient->execute(`CREATE TABLE student (
id INT AUTO_INCREMENT,
age INT,
name VARCHAR(255),
PRIMARY KEY (id)
)`);
}
Upvotes: 2