in R/R/executeInSQL.R [222:325]
execute <- function(connection, script, ...)
{
queryResult <- NULL
# Check if the connection is a connection string or an odbc connection object (S4 object)
#
if (class(connection) == "character")
{
if (nchar(connection) < 1)
{
stop(paste0("Invalid connection string: ", connection), call. = FALSE)
}
}
else if (typeof(connection) != "S4")
{
stop("Invalid connection string has to be a character string or odbc handle", call. = FALSE)
}
tryCatch(
{
# If we have a connection string, connect, then disconnect on exit.
# If we have an actual connection object, use it but don't disconnect on exit.
#
if (class(connection) == "character")
{
hodbc <- connectToServer(connection)
on.exit(dbDisconnect(hodbc), add = TRUE)
}
else
{
hodbc <- connection
}
queryResult <- dbSendQuery(hodbc, script)
# Bind parameterized queries
#
if(length(list(...)) != 0)
{
dbBind(queryResult, ...)
}
res <- dbFetch(queryResult)
binVal <- res$returnVal
},
error = function(e)
{
stop(paste0("Error in SQL Execution: ", e, "\n"))
},
finally =
{
if (!is.null(queryResult))
{
dbClearResult(queryResult)
}
})
binVal <- res$returnVal
if (!is.null(binVal))
{
resVal <- unserialize(unlist(lapply(lapply(as.character(binVal),as.hexmode), as.raw)))
len <- length(resVal)
# Each piece of the returned value is a different part of the output
# 1. The result of the function
# 2. The output of the function (e.g. from print())
# 3. The warnings of the function
# 4. The errors of the function
# We raise warnings and errors, print any output, and return the actual function results to the user
#
if (len > 1)
{
output <- resVal[[2]]
for (o in output)
{
cat(paste0(o,"\n"))
}
}
if (len > 2)
{
warnings <- resVal[[3]]
for (w in warnings)
{
warning(w)
}
}
if (len > 3)
{
errors <- resVal[[4]]
for (e in errors)
{
stop(paste0("Error in script: ", e))
}
}
res <- resVal
}
return(res)
}