Skip to content

Instantly share code, notes, and snippets.

@jeroen
Last active August 29, 2015 14:14
Show Gist options
  • Save jeroen/56031d0aa93cb8f5f979 to your computer and use it in GitHub Desktop.
Save jeroen/56031d0aa93cb8f5f979 to your computer and use it in GitHub Desktop.
Simple example of running sql.js in R with V8
# Requires recent version of V8:
if( ! require(V8) || packageVersion("V8") < "0.5"){
install.packages("V8")
}
# Create JavaScript context and load sql.js
ct <- new_context()
ct$source("https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js")
# Evaluate JavaScript code
ct$eval('
var db = new SQL.Database()
db.run("CREATE TABLE hello (person char, age int);")
db.run("INSERT INTO hello VALUES (\'jerry\', 34);")
db.run("INSERT INTO hello VALUES (\'mary\', 27);")
db.run("INSERT INTO hello VALUES (\'joe\', 65);")
db.run("INSERT INTO hello VALUES (\'anna\', 18);")
// query:
var out = []
var stmt = db.prepare("SELECT * FROM hello WHERE age < 40");
while (stmt.step()) out.push(stmt.getAsObject());
')
# Copy the object from JavaScript to R
data <- ct$get("out")
print(data)
@timelyportfolio
Copy link

had to change line 7 to eliminate error "Error: ReferenceError: print is not defined"

ct <- new_context("window")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment