I have a function to read the Notifiers
table in my db and check if there is a user by a userId. If the user is there, I return that user's last seen time, if the user is not present, I write a new entry to the db. The code is as follows:
isolated function getNotifier(string user_name) returns time:Utc|error {
anydata result = check dbClient->queryRow(
SELECT * FROM Notifier WHERE user_name = ${user_name}
);
if result is Notifier {
io:println(result.last_seen);
return result.last_seen;
} else if result is sql:NoRowsError {
time:Utc lastseen = time:utcNow();
_ = check dbClient->execute(
INSERT INTO Notifier (user_name, last_seen)
VALUES (${user_name}, ${time:utcNow()});
);
return last_seen;
} else {
return error("Unable to obtain notifier");
}
}
However, it seems that the program does not reach the if block at all and returns an error from the first result. Why does this happen?
When you use check
as you've done with the select query, if the expression with which check
is used evaluates to an error, it would cause the function execution to stop immediately and return the error value from the function.
sql:NoRowsError
is an error value. Therefore, if the query returns sql:NoRowsError
(or any other error value), the function execution won't go past the first statement.
Also see check
semantics.