How to ignore the error from attempting to drop tables that don't exist using RODBC? - sql

I have a function that catches errors resulting from odbcQuery. How would one make it so that attempting to drop tables that don't exist does not throw an error?
The function:
runQuery <- function(script, channel, errors = T) {
run <- odbcQuery(channel, script)
# if the function has returned an error
if (run == -1L) {
if (errors) {
err <- odbcGetErrMsg(channel)
cat("\nobdcQuery() encountered an error running the following SQL ")
cat("query:\n\n", script, "\n\nError from Oracle server:\n")
return(err)
} else {
err <- invisible(run)
}
}
}

Related

Test throw case in RxJava 3

I'm trying to test case when my rx chain should throw an exception but facing problem with it. When I'm trying to call assertError(error) it says that no error found. Here's example:
fun isAvailable(): Single<String> {
return mapper.getSymbol().map { symbol ->
if (repository.isAvailable(symbol)) {
symbol
} else {
throw Exception("Symbol is not available")
}
}
}
In test I mock repository to return false and after do something like:
val error = Exception("Symbol is not available")
whenever(mapper.getSymbol()).thenReturn(
Single.just(
symbol
)
)
whenever(repository.isAvailable(symbol)).thenReturn(false)
val test = symbolsRepository.isAvailable().test()
test.await()
.assertError(error)
But when I run test I see
Error not present (latch = 0, values = 0, errors = 1, completions = 0)
Caused by: java.lang.Exception: Symbol is not available
As #gpunto said, assertError does equals check on the Exception and those are not implemented by default beyond reference equality in standard Java.
You could use two other overloads of assertError to check for both the exception class and its message:
test.awaitDone()
.assertError(error.getClass())
.assertError({ it.getMessage().equals(error.getMessage()) })

How to get detailed error msg from monetdbe_query

Looking at the C examples for monetdbe_query in the GitHub repository: https://github.com/MonetDBSolutions/monetdbe-examples
The prescribed way to run queries is to run SQL queries in an IF statement that captures Null return values as shown below:
if (monetdbe_query(db, "SELECT * FROM mystrings", &result, NULL) != NULL) {
fprintf(stderr, "Failed to run select query\n");
goto cleanup;
}
is it possible to get any detailed information regarding why the SQL statement failed?
Many monetdbe_ functions return an error message if something went wrong, or NULL otherwise. So, just catch the return value. See the example copy_into.c in monetdbe-examples:
if((err=monetdbe_query(db, sql, NULL, NULL)) != NULL) {
printf("%s\r\n", err);
return -1;
}
grep for err in the examples for more.

gorm raw sql query execution

Am running a query to check if a table exists or not using the gorm orm for golang. Below is my code.
package main
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
_ "github.com/lib/pq"
)
// App sets up and runs the app
type App struct {
DB *gorm.DB
}
`const tableCreationQuery = `SELECT count (*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'api_test') AND (TABLE_NAME = 'Users')`
func ensureTableExists() {
if err := a.DB.Exec(tableCreationQuery); err != nil {
log.Fatal(err)
}
}`
The expected response should be either 1 or 0. I got this from another SO answer. Instead I get this
2020/09/03 00:27:18 &{0xc000148900 1 0xc000119ba0 0}
exit status 1
FAIL go-auth 0.287s
My untrained mind says its a pointer but how do I reference the returned values to determine what was contained within?
If you want to check if your SQL statement was successfully executed in GORM you can use the following:
tx := DB.Exec(sqlStr, args...)
if tx.Error != nil {
return false
}
return true
However in your example are using a SELECT statement then you need to check the result, which will be better suited to use the DB.Raw() method like below
var exists bool
DB.Raw(sqlStr).Row().Scan(&exists)
return exists

How do I insert a row into an SQLite database using swift?

I have a SQLITE3 database with two tables, main and activities. I am trying to insert a row into the main table just to check it works, using the sql command on terminal I am able to insert, but not through swift. The database is connected and allows me to read from the database using swift but not write to it.
let insertStatementString = "INSERT INTO main (DATE) VALUES (?);"
func insert() {
var insertStatement: OpaquePointer?
//1
if sqlite3_prepare_v2(mySQLDB,insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {
let date: NSString = "14071999"
sqlite3_bind_text(insertStatement,1,date.utf8String, -1, nil)
if sqlite3_step(insertStatement) == SQLITE_DONE {
print("\nSuccessfully inserted row")
} else
{ print("\nCould not insert a row")
}
}
else
{ print("\nInsert statement not prepared")
}
sqlite3_finalize(insertStatement)
}
When the program reaches 'if sqlite3_step(insertStatement) == SQLITE_DONE' it then skips to 'Could not insert row'.
Can anyone see why this is going wrong?
If your insert failed, you should print the error message, sqlite3_errmsg, which will tell you precisely what went wrong.
FWIW, your code worked for me, so it’s probably something not included in your question, for example how you opened the database and/or how the table was defined. Possible problems include:
inserting into a read-only database (e.g., opened database in the bundle which is read-only, explicitly opened with sqlite3_open_v2 in read-only mode, etc.);
your bind statement failed (you really should check for success there, too);
having a unique key on this column and already having this value somewhere; or
having other required (NOT NULL) columns that were not supplied.
Regardless, logging the error message will remove any ambiguity.
E.g.
func insert() {
var insertStatement: OpaquePointer?
guard sqlite3_prepare_v2(mySQLDB, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK else {
printError(with: "INSERT statement not prepared")
return
}
defer { sqlite3_finalize(insertStatement) }
let date = "14071999"
guard sqlite3_bind_text(insertStatement, 1, date.cString(using: .utf8), -1, SQLITE_TRANSIENT) == SQLITE_OK else {
printError(with: "Bind for INSERT failed")
return
}
guard sqlite3_step(insertStatement) == SQLITE_DONE else {
printError(with: "Could not insert a row")
return
}
print("Successfully inserted row")
}
func printError(with message: String) {
let errmsg = sqlite3_errmsg(mySQLDB).flatMap { String(cString: $0) } ?? "Unknown error"
print(message, errmsg)
}
Where
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
While I structured this with guard statements, even if you stay with your if pattern, make sure you only sqlite3_finalize if the prepare statement succeeded. There’s no point in finalizing if the prepare failed.
It’s also prudent to use SQLITE_TRANSIENT for bound parameters.

Checking if update query affected rows perl

I have an "UPDATE" query and I want to check if this query has affected any rows and if it has I would like to send an email to myself. I'm not really experienced with perl or sql. (I'm using postgresql).
EDIT: I know that UPDATE returns "count" which tells how many rows if any have been updated, but I still don't know how to get to it.
The code looks like this:
my $updateQuery - //UPDATE query
if(//updateQuery has effected rows){
//send mail
}else
//do nothing
The problem is I don't know what to put into the if, what flag should I set? Is there any easy check that answers "has effected rows"?
Shortcut version using do()
my $update_query = '...';
my $ret = $dbh->do($update_query);
if ($ret) {
if ($ret eq '0E0') {
# no rows updated
} else {
# rows updated
}
} else {
# error
}
Full prepare()/execute() version.
my $update_query = '...';
my $sth = $dbh->prepare($update_query);
my $ret = $sth->execute;
if ($ret) {
if ($ret eq '0E0') {
# no rows updated
} else {
# rows updated
}
} else {
# error
}