I am trying to setup a simple JDBC client to talk with a database in Ballerina.
However the "compile" ( VSCode ) error that is shown says:
invalid remote method call: expected a client object, but found (ballerinax/java.jdbc:1.7.0:Client|ballerina/sql:1.7.1:Error)(BCE2421)
Here is my full source code:
import ballerinax/java.jdbc;
import ballerina/sql;
public type User record {|
int id?;
string name;
string username;
string email;
int? client_id;
|};
configurable string USER = ?;
configurable string PASSWORD = ?;
configurable string HOST = ?;
configurable int PORT = ?;
configurable string DATABASE = ?;
final jdbc:Client|sql:Error dbClient = new (
url="", user=USER, password=PASSWORD
);
isolated function getUser(int id) returns User|error {
sql:ParameterizedQuery query = `select * from users where ${id} = ?`;
User user = dbClient->query(query); // <--- THIS IS THE LINE THAT SHOWS ERROR
return user;
}
2
Answers
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
getUser()
functiondbClient
may be eitherjdbc:Client
orsql:Error
. You can call the remote methodquery()
only if the variable is of typejdbc:Client
. You should narrow the type of thedbClient
before the remote method is invoked.Alternatively, you can use check keyword to narrow the type as
sql:Error
is an error type in Ballerina.For more details on handling errors with check expression see Ballerina By Example: Check Expression.
Changing the isolated function as follows worked for me. I think due to the error handling of ballerina you should either return the error so that the needed type is left or otherwise you should use the ‘check’ to do the same.