Skip to content

Commit

Permalink
Add sqlite extfuns. Fixes #17
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed May 20, 2013
1 parent 7065aa9 commit 3e60b9e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Imports:
utils
Suggests:
RSQLite,
RSQLite.extfuns,
plyr,
data.table
Depends:
Expand Down
6 changes: 6 additions & 0 deletions R/source-sqlite.r
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,14 @@ source_sqlite <- function(path, table) {
if (!require("RSQLite")) {
stop("RSQLite package required to connect to sqlite db", call. = FALSE)
}
if (!require("RSQLite.extfuns")) {
stop("RSQLite.extfuns package required to effectively use sqlite db",
call. = FALSE)
}

con <- dbConnect(dbDriver("SQLite"), dbname = path)
RSQLite.extfuns::init_extensions(con)

if (!(table %in% dbListTables(con))) {
stop("Table ", table, " not found in database ", path, call. = FALSE)
}
Expand Down
22 changes: 22 additions & 0 deletions R/translate-sql.r
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ sql_unary <- function(f) {
sprintf("%s(%s)", f, xsql)
}
}
sql_binary <- function(f) {
f <- toupper(f)
function(x, y) {
xsql <- to_sql(substitute(x))
ysql <- to_sql(substitute(y))
sprintf("%s(%s, %s)", f, xsql, ysql)
}
}
sql_atomic <- function(x) {
if (is.character(x)) x <- paste0('"', x, '"')
if (is.double(x) && any(is.wholenumber(x))) {
Expand Down Expand Up @@ -159,3 +167,17 @@ sqlite <- list(
"c" = function(...) sql_atomic(c(...)),
":" = function(from, to) sql_atomic(from:to)
)

# Functions added by RSQLite.extfuns --------------------
math_unary <- c("acos", "acosh", "asin", "asinh", "atan", "atanh",
"cos", "cosh", "exp", "floor", "log", "log10", "sign", "sin",
"sinh", "sqrt", "tan", "tanh")
for(f in math_unary) sqlite[[f]] <- sql_unary(f)

sqlite$ceiling <- sql_unary("ceil")
sqlite$atan2 <- sql_binary("atan2")
sqlite[["^"]] <- sql_binary("power")

sqlite$sd <- sql_unary("stdev")
sqlite$var <- sql_unary("variance")
sqlite$median <- sql_unary("median")

0 comments on commit 3e60b9e

Please sign in to comment.