###################################################
### chunk number 1: setup
###################################################
#line 17 "UsingSQLiteInR.Rnw"
options(width = 40)


###################################################
### chunk number 2: driverUsageAndListTables
###################################################
#line 318 "UsingSQLiteInR.Rnw"
library(RSQLite) #loads DBI too, (but we need both)
drv <- SQLite()
con <- dbConnect(drv, dbname=system.file("extdata", 
                 "mm9KG.sqlite", package="AdvancedR2011"))
dbListTables(con)
dbListFields(con,"transcript")


###################################################
### chunk number 3: dbGetQuery
###################################################
#line 331 "UsingSQLiteInR.Rnw"
dbGetQuery(con, "SELECT * FROM transcript LIMIT 3")


###################################################
### chunk number 4: dbSendQuery
###################################################
#line 340 "UsingSQLiteInR.Rnw"
res <- dbSendQuery(con, "SELECT * FROM transcript")
fetch(res, n= 3)
dbClearResult(res)


###################################################
### chunk number 5: dbDisconnect
###################################################
#line 364 "UsingSQLiteInR.Rnw"
   dbDisconnect(con)


###################################################
### chunk number 6: makeNewDb
###################################################
#line 370 "UsingSQLiteInR.Rnw"
drv <- SQLite()
con <- dbConnect(drv, dbname="myNewDb.sqlite")


###################################################
### chunk number 7: CreateNewTable
###################################################
#line 375 "UsingSQLiteInR.Rnw"
dbGetQuery(con, "CREATE Table foo (id INTEGER, string TEXT)")


###################################################
### chunk number 8: LabelledPreparedQueries
###################################################
#line 416 "UsingSQLiteInR.Rnw"
data <- data.frame(c(226089,66745),
                  c("C030046E11Rik","Trpd52l3"), 
                  stringsAsFactors=FALSE)
names(data) <- c("id","string")
sql <- "INSERT INTO foo VALUES ($id, $string)"
dbBeginTransaction(con)
dbGetPreparedQuery(con, sql, bind.data = data)
dbCommit(con)


###################################################
### chunk number 9: ATTACH
###################################################
#line 460 "UsingSQLiteInR.Rnw"
db <- system.file("extdata", "mm9KG.sqlite", 
                  package="AdvancedR2011")
dbGetQuery(con, sprintf("ATTACH '%s' AS db",db))


###################################################
### chunk number 10: ATTACHJoin
###################################################
#line 477 "UsingSQLiteInR.Rnw"
  sql <- "SELECT * FROM db.gene AS dbg, 
          foo AS f WHERE dbg.gene_id=f.id"
  res <- dbGetQuery(con, sql)
  res


###################################################
### chunk number 11: cleanup
###################################################
#line 567 "UsingSQLiteInR.Rnw"
 file.remove("myNewDb.sqlite")


