DBI/0000755000176200001440000000000014160037606010653 5ustar liggesusersDBI/NAMESPACE0000644000176200001440000000466514157661564012121 0ustar liggesusers# Generated by roxygen2: do not edit by hand S3method("[",SQL) S3method("[[",SQL) S3method(toString,Id) export(.SQL92Keywords) export(ANSI) export(Id) export(SQL) export(SQLKeywords) export(dbAppendTable) export(dbBegin) export(dbBind) export(dbBreak) export(dbCallProc) export(dbCanConnect) export(dbClearResult) export(dbColumnInfo) export(dbCommit) export(dbConnect) export(dbCreateTable) export(dbDataType) export(dbDisconnect) export(dbDriver) export(dbExecute) export(dbExistsTable) export(dbFetch) export(dbGetConnectArgs) export(dbGetDBIVersion) export(dbGetException) export(dbGetInfo) export(dbGetQuery) export(dbGetRowCount) export(dbGetRowsAffected) export(dbGetStatement) export(dbHasCompleted) export(dbIsReadOnly) export(dbIsValid) export(dbListConnections) export(dbListFields) export(dbListObjects) export(dbListResults) export(dbListTables) export(dbQuoteIdentifier) export(dbQuoteLiteral) export(dbQuoteString) export(dbReadTable) export(dbRemoveTable) export(dbRollback) export(dbSendQuery) export(dbSendStatement) export(dbSetDataMappings) export(dbUnloadDriver) export(dbUnquoteIdentifier) export(dbWithTransaction) export(dbWriteTable) export(fetch) export(isSQLKeyword) export(isSQLKeyword.default) export(make.db.names) export(make.db.names.default) export(sqlAppendTable) export(sqlAppendTableTemplate) export(sqlColumnToRownames) export(sqlCommentSpec) export(sqlCreateTable) export(sqlData) export(sqlInterpolate) export(sqlParseVariables) export(sqlParseVariablesImpl) export(sqlQuoteSpec) export(sqlRownamesToColumn) exportClasses(DBIConnection) exportClasses(DBIConnector) exportClasses(DBIDriver) exportClasses(DBIObject) exportClasses(DBIResult) exportClasses(SQL) exportMethods(dbAppendTable) exportMethods(dbCanConnect) exportMethods(dbConnect) exportMethods(dbCreateTable) exportMethods(dbDataType) exportMethods(dbExecute) exportMethods(dbExistsTable) exportMethods(dbFetch) exportMethods(dbGetConnectArgs) exportMethods(dbGetQuery) exportMethods(dbListFields) exportMethods(dbListObjects) exportMethods(dbQuoteIdentifier) exportMethods(dbQuoteLiteral) exportMethods(dbQuoteString) exportMethods(dbReadTable) exportMethods(dbRemoveTable) exportMethods(dbSendStatement) exportMethods(dbUnquoteIdentifier) exportMethods(dbWithTransaction) exportMethods(dbWriteTable) exportMethods(show) exportMethods(sqlAppendTable) exportMethods(sqlCreateTable) exportMethods(sqlData) exportMethods(sqlInterpolate) exportMethods(sqlParseVariables) import(methods) DBI/.Rinstignore0000644000176200001440000000002514064774575013174 0ustar liggesusersinst/doc/figure1.pdf DBI/README.md0000644000176200001440000001371714157702245012147 0ustar liggesusers # DBI [![rcc](https://github.com/r-dbi/DBI/workflows/rcc/badge.svg)](https://github.com/r-dbi/DBI/actions) [![Coverage Status](https://codecov.io/gh/r-dbi/DBI/branch/main/graph/badge.svg)](https://codecov.io/github/r-dbi/DBI?branch=main) [![CRAN\_Status\_Badge](https://www.r-pkg.org/badges/version/DBI)](https://cran.r-project.org/package=DBI) [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/1882/badge)](https://bestpractices.coreinfrastructure.org/projects/1882) The DBI package helps connecting R to database management systems (DBMS). DBI separates the connectivity to the DBMS into a “front-end” and a “back-end”. The package defines an interface that is implemented by *DBI backends* such as: - [RPostgres](https://rpostgres.r-dbi.org), - [RMariaDB](https://rmariadb.r-dbi.org), - [RSQLite](https://rsqlite.r-dbi.org), - [odbc](https://github.com/r-dbi/odbc), - [bigrquery](https://github.com/r-dbi/bigrquery), and many more, see the [list of backends](https://github.com/r-dbi/backends#readme). R scripts and packages use DBI to access various databases through their DBI backends. The interface defines a small set of classes and methods similar in spirit to Perl’s [DBI](https://dbi.perl.org/), Java’s [JDBC](https://www.oracle.com/java/technologies/javase/javase-tech-database.html), Python’s [DB-API](https://www.python.org/dev/peps/pep-0249/), and Microsoft’s [ODBC](https://en.wikipedia.org/wiki/ODBC). It supports the following operations: - connect/disconnect to the DBMS - create and execute statements in the DBMS - extract results/output from statements - error/exception handling - information (meta-data) from database objects - transaction management (optional) ## Installation Most users who want to access a database do not need to install DBI directly. It will be installed automatically when you install one of the database backends: - [RPostgres](https://rpostgres.r-dbi.org) for PostgreSQL, - [RMariaDB](https://rmariadb.r-dbi.org) for MariaDB or MySQL, - [RSQLite](https://rsqlite.r-dbi.org) for SQLite, - [odbc](https://github.com/r-dbi/odbc) for databases that you can access via [ODBC](https://en.wikipedia.org/wiki/Open_Database_Connectivity), - [bigrquery](https://github.com/r-dbi/bigrquery), - … . You can install the released version of DBI from [CRAN](https://CRAN.R-project.org) with: ``` r install.packages("DBI") ``` And the development version from [GitHub](https://github.com/) with: ``` r # install.packages("devtools") devtools::install_github("r-dbi/DBI") ``` ## Example The following example illustrates some of the DBI capabilities: ``` r library(DBI) # Create an ephemeral in-memory RSQLite database con <- dbConnect(RSQLite::SQLite(), dbname = ":memory:") dbListTables(con) #> character(0) dbWriteTable(con, "mtcars", mtcars) dbListTables(con) #> [1] "mtcars" dbListFields(con, "mtcars") #> [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" #> [11] "carb" dbReadTable(con, "mtcars") #> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 #> 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 #> 3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 #> 4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 #> 5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 #> 6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 #> 7 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 #> 8 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 #> 9 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 #> [ reached 'max' / getOption("max.print") -- omitted 23 rows ] # You can fetch all results: res <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") dbFetch(res) #> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 #> 2 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 #> 3 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 #> 4 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 #> 5 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 #> 6 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 #> 7 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 #> 8 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 #> 9 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 #> [ reached 'max' / getOption("max.print") -- omitted 2 rows ] dbClearResult(res) # Or a chunk at a time res <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") while(!dbHasCompleted(res)){ chunk <- dbFetch(res, n = 5) print(nrow(chunk)) } #> [1] 5 #> [1] 5 #> [1] 1 dbClearResult(res) dbDisconnect(con) ``` ## Class structure There are four main DBI classes. Three which are each extended by individual database backends: - `DBIObject`: a common base class for all DBI. - `DBIDriver`: a base class representing overall DBMS properties. Typically generator functions instantiate the driver objects like `RSQLite()`, `RPostgreSQL()`, `RMySQL()` etc. - `DBIConnection`: represents a connection to a specific database - `DBIResult`: the result of a DBMS query or statement. All classes are *virtual*: they cannot be instantiated directly and instead must be subclassed. ## Further Reading - [Databases using R](https://db.rstudio.com/) describes the tools and best practices in this ecosystem. - The [DBI project site](https://www.r-dbi.org/) hosts a blog where recent developments are presented. - [A history of DBI](https://r-dbi.github.io/DBI/articles/DBI-history.html) by David James, the driving force behind the development of DBI, and many of the packages that implement it. ------------------------------------------------------------------------ Please note that the *DBI* project is released with a [Contributor Code of Conduct](https://dbi.r-dbi.org/code_of_conduct). By contributing to this project, you agree to abide by its terms. DBI/man/0000755000176200001440000000000014157701453011432 5ustar liggesusersDBI/man/dbQuoteLiteral.Rd0000644000176200001440000000573714157672512014660 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbQuoteLiteral.R \name{dbQuoteLiteral} \alias{dbQuoteLiteral} \title{Quote literal values} \usage{ dbQuoteLiteral(conn, x, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{x}{A vector to quote as string.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbQuoteLiteral()} returns an object that can be coerced to \link{character}, of the same length as the input. For an empty integer, numeric, character, logical, date, time, or blob vector, this function returns a length-0 object. When passing the returned object again to \code{dbQuoteLiteral()} as \code{x} argument, it is returned unchanged. Passing objects of class \link{SQL} should also return them unchanged. (For backends it may be most convenient to return \link{SQL} objects to achieve this behavior, but this is not required.) } \description{ Call these methods to generate a string that is suitable for use in a query as a literal value of the correct type, to make sure that you generate valid SQL and protect against SQL injection attacks. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbQuoteLiteral")} } \section{Failure modes}{ Passing a list for the \code{x} argument raises an error. } \section{Specification}{ The returned expression can be used in a \verb{SELECT ...} query, and the value of \code{dbGetQuery(paste0("SELECT ", dbQuoteLiteral(x)))[[1]]} must be equal to \code{x} for any scalar integer, numeric, string, and logical. If \code{x} is \code{NA}, the result must merely satisfy \code{\link[=is.na]{is.na()}}. The literals \code{"NA"} or \code{"NULL"} are not treated specially. \code{NA} should be translated to an unquoted SQL \code{NULL}, so that the query \verb{SELECT * FROM (SELECT 1) a WHERE ... IS NULL} returns one row. } \examples{ # Quoting ensures that arbitrary input is safe for use in a query name <- "Robert'); DROP TABLE Students;--" dbQuoteLiteral(ANSI(), name) # NAs become NULL dbQuoteLiteral(ANSI(), c(1:3, NA)) # Logicals become integers by default dbQuoteLiteral(ANSI(), c(TRUE, FALSE, NA)) # Raw vectors become hex strings by default dbQuoteLiteral(ANSI(), list(as.raw(1:3), NULL)) # SQL vectors are always passed through as is var_name <- SQL("select") var_name dbQuoteLiteral(ANSI(), var_name) # This mechanism is used to prevent double escaping dbQuoteLiteral(ANSI(), dbQuoteLiteral(ANSI(), name)) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/sqlAppendTable.Rd0000644000176200001440000000520514157672512014625 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sqlAppendTable.R, R/sqlAppendTableTemplate.R \name{sqlAppendTable} \alias{sqlAppendTable} \alias{sqlAppendTableTemplate} \title{Compose query to insert rows into a table} \usage{ sqlAppendTable(con, table, values, row.names = NA, ...) sqlAppendTableTemplate( con, table, values, row.names = NA, prefix = "?", ..., pattern = "" ) } \arguments{ \item{con}{A database connection.} \item{table}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{values}{A data frame. Factors will be converted to character vectors. Character vectors will be escaped with \code{\link[=dbQuoteString]{dbQuoteString()}}.} \item{row.names}{Either \code{TRUE}, \code{FALSE}, \code{NA} or a string. If \code{TRUE}, always translate row names to a column called "row_names". If \code{FALSE}, never translate row names. If \code{NA}, translate rownames only if they're a character vector. A string is equivalent to \code{TRUE}, but allows you to override the default name. For backward compatibility, \code{NULL} is equivalent to \code{FALSE}.} \item{...}{Other arguments used by individual methods.} \item{prefix}{Parameter prefix to use for placeholders.} \item{pattern}{Parameter pattern to use for placeholders: \itemize{ \item \code{""}: no pattern \item \code{"1"}: position \item anything else: field name }} } \description{ \code{sqlAppendTable()} generates a single SQL string that inserts a data frame into an existing table. \code{sqlAppendTableTemplate()} generates a template suitable for use with \code{\link[=dbBind]{dbBind()}}. The default methods are ANSI SQL 99 compliant. These methods are mostly useful for backend implementers. } \details{ The \code{row.names} argument must be passed explicitly in order to avoid a compatibility warning. The default will be changed in a later release. } \examples{ sqlAppendTable(ANSI(), "iris", head(iris)) sqlAppendTable(ANSI(), "mtcars", head(mtcars)) sqlAppendTable(ANSI(), "mtcars", head(mtcars), row.names = FALSE) sqlAppendTableTemplate(ANSI(), "iris", iris) sqlAppendTableTemplate(ANSI(), "mtcars", mtcars) sqlAppendTableTemplate(ANSI(), "mtcars", mtcars, row.names = FALSE) } \concept{SQL generation} DBI/man/SQL.Rd0000644000176200001440000000360414157672512012366 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/SQL.R \docType{class} \name{SQL} \alias{SQL} \alias{SQL-class} \title{SQL quoting} \usage{ SQL(x, ..., names = NULL) } \arguments{ \item{x}{A character vector to label as being escaped SQL.} \item{...}{Other arguments passed on to methods. Not otherwise used.} \item{names}{Names for the returned object, must have the same length as \code{x}.} } \value{ An object of class \code{SQL}. } \description{ This set of classes and generics make it possible to flexibly deal with SQL escaping needs. By default, any user supplied input to a query should be escaped using either \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or \code{\link[=dbQuoteString]{dbQuoteString()}} depending on whether it refers to a table or variable name, or is a literal string. These functions may return an object of the \code{SQL} class, which tells DBI functions that a character string does not need to be escaped anymore, to prevent double escaping. The \code{SQL} class has associated the \code{SQL()} constructor function. } \section{Implementation notes}{ DBI provides default generics for SQL-92 compatible quoting. If the database uses a different convention, you will need to provide your own methods. Note that because of the way that S4 dispatch finds methods and because SQL inherits from character, if you implement (e.g.) a method for \code{dbQuoteString(MyConnection, character)}, you will also need to implement \code{dbQuoteString(MyConnection, SQL)} - this should simply return \code{x} unchanged. } \examples{ dbQuoteIdentifier(ANSI(), "SELECT") dbQuoteString(ANSI(), "SELECT") # SQL vectors are always passed through as is var_name <- SQL("SELECT") var_name dbQuoteIdentifier(ANSI(), var_name) dbQuoteString(ANSI(), var_name) # This mechanism is used to prevent double escaping dbQuoteString(ANSI(), dbQuoteString(ANSI(), "SELECT")) } DBI/man/dbCanConnect.Rd0000644000176200001440000000314014157672512014243 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbCanConnect.R \name{dbCanConnect} \alias{dbCanConnect} \title{Check if a connection to a DBMS can be established} \usage{ dbCanConnect(drv, ...) } \arguments{ \item{drv}{an object that inherits from \linkS4class{DBIDriver}, or an existing \linkS4class{DBIConnection} object (in order to clone an existing connection).} \item{...}{authentication arguments needed by the DBMS instance; these typically include \code{user}, \code{password}, \code{host}, \code{port}, \code{dbname}, etc. For details see the appropriate \code{DBIDriver}.} } \value{ A scalar logical. If \code{FALSE}, the \code{"reason"} attribute indicates a reason for failure. } \description{ Like \code{\link[=dbConnect]{dbConnect()}}, but only checks validity without actually returning a connection object. The default implementation opens a connection and disconnects on success, but individual backends might implement a lighter-weight check. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbCanConnect")} } \examples{ # SQLite only needs a path to the database. (Here, ":memory:" is a special # path that creates an in-memory database.) Other database drivers # will require more details (like user, password, host, port, etc.) dbCanConnect(RSQLite::SQLite(), ":memory:") } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} } \concept{DBIDriver generics} DBI/man/Id.Rd0000644000176200001440000000335714157701453012265 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Id.R \docType{class} \name{Id-class} \alias{Id-class} \alias{Id} \title{Refer to a table nested in a hierarchy (e.g. within a schema)} \usage{ Id(...) } \arguments{ \item{...}{Components of the hierarchy, e.g. \code{schema}, \code{table}, or \code{cluster}, \code{catalog}, \code{schema}, \code{table}, depending on the database backend. For more on these concepts, see \url{https://stackoverflow.com/questions/7022755/}} } \description{ Objects of class \code{Id} have a single slot \code{name}, which is a named character vector. The \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} method converts \code{Id} objects to strings. Support for \code{Id} objects depends on the database backend. They can be used in the following methods as \code{name} or \code{table} argument: \itemize{ \item \code{\link[=dbCreateTable]{dbCreateTable()}} \item \code{\link[=dbAppendTable]{dbAppendTable()}} \item \code{\link[=dbReadTable]{dbReadTable()}} \item \code{\link[=dbWriteTable]{dbWriteTable()}} \item \code{\link[=dbExistsTable]{dbExistsTable()}} \item \code{\link[=dbRemoveTable]{dbRemoveTable()}} } Objects of this class are also returned from \code{\link[=dbListObjects]{dbListObjects()}}. } \examples{ # Identifies a table in a specific schema: Id(schema = "dbo", table = "Customer") # Identifies a table in a specific cluster, catalog, and schema: Id(cluster = "mycluster", catalog = "mycatalog", schema = "myschema", table = "mytable") # Create a SQL expression for an identifier: dbQuoteIdentifier(ANSI(), Id(schema = "nycflights13", table = "flights")) # Write a table in a specific schema: \dontrun{ dbWriteTable(con, Id(schema = "myschema", table = "mytable"), data.frame(a = 1)) } } DBI/man/dbGetException.Rd0000644000176200001440000000247314157672512014636 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetException.R \name{dbGetException} \alias{dbGetException} \title{Get DBMS exceptions} \usage{ dbGetException(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \value{ a list with elements \code{errorNum} (an integer error number) and \code{errorMsg} (a character string) describing the last error in the connection \code{conn}. } \description{ DEPRECATED. Backends should use R's condition system to signal errors and warnings. } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} \keyword{internal} DBI/man/sqlCreateTable.Rd0000644000176200001440000000445514157672512014627 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sqlCreateTable.R \name{sqlCreateTable} \alias{sqlCreateTable} \title{Compose query to create a simple table} \usage{ sqlCreateTable(con, table, fields, row.names = NA, temporary = FALSE, ...) } \arguments{ \item{con}{A database connection.} \item{table}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{fields}{Either a character vector or a data frame. A named character vector: Names are column names, values are types. Names are escaped with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Field types are unescaped. A data frame: field types are generated using \code{\link[=dbDataType]{dbDataType()}}.} \item{row.names}{Either \code{TRUE}, \code{FALSE}, \code{NA} or a string. If \code{TRUE}, always translate row names to a column called "row_names". If \code{FALSE}, never translate row names. If \code{NA}, translate rownames only if they're a character vector. A string is equivalent to \code{TRUE}, but allows you to override the default name. For backward compatibility, \code{NULL} is equivalent to \code{FALSE}.} \item{temporary}{If \code{TRUE}, will generate a temporary table statement.} \item{...}{Other arguments used by individual methods.} } \description{ Exposes an interface to simple \verb{CREATE TABLE} commands. The default method is ANSI SQL 99 compliant. This method is mostly useful for backend implementers. } \details{ The \code{row.names} argument must be passed explicitly in order to avoid a compatibility warning. The default will be changed in a later release. } \examples{ sqlCreateTable(ANSI(), "my-table", c(a = "integer", b = "text")) sqlCreateTable(ANSI(), "my-table", iris) # By default, character row names are converted to a row_names colum sqlCreateTable(ANSI(), "mtcars", mtcars[, 1:5]) sqlCreateTable(ANSI(), "mtcars", mtcars[, 1:5], row.names = FALSE) } DBI/man/sqlInterpolate.Rd0000644000176200001440000000630214157672512014733 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sqlInterpolate.R \name{sqlInterpolate} \alias{sqlInterpolate} \title{Safely interpolate values into an SQL string} \usage{ sqlInterpolate(conn, sql, ..., .dots = list()) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{sql}{A SQL string containing variables to interpolate. Variables must start with a question mark and can be any valid R identifier, i.e. it must start with a letter or \code{.}, and be followed by a letter, digit, \code{.} or \verb{_}.} \item{..., .dots}{Values (for \code{...}) or a list (for \code{.dots}) to interpolate into a string. Names are required if \code{sql} uses the \code{?name} syntax for placeholders. All values will be first escaped with \code{\link[=dbQuoteLiteral]{dbQuoteLiteral()}} prior to interpolation to protect against SQL injection attacks. Arguments created by \code{\link[=SQL]{SQL()}} or \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} remain unchanged.} } \value{ The \code{sql} query with the values from \code{...} and \code{.dots} safely embedded. } \description{ Accepts a query string with placeholders for values, and returns a string with the values embedded. The function is careful to quote all of its inputs with \code{\link[=dbQuoteLiteral]{dbQuoteLiteral()}} to protect against SQL injection attacks. Placeholders can be specified with one of two syntaxes: \itemize{ \item \verb{?}: each occurrence of a standalone \verb{?} is replaced with a value \item \code{?name1}, \code{?name2}, ...: values are given as named arguments or a named list, the names are used to match the values } Mixing \verb{?} and \code{?name} syntaxes is an error. The number and names of values supplied must correspond to the placeholders used in the query. } \section{Backend authors}{ If you are implementing an SQL backend with non-ANSI quoting rules, you'll need to implement a method for \code{\link[=sqlParseVariables]{sqlParseVariables()}}. Failure to do so does not expose you to SQL injection attacks, but will (rarely) result in errors matching supplied and interpolated variables. } \examples{ sql <- "SELECT * FROM X WHERE name = ?name" sqlInterpolate(ANSI(), sql, name = "Hadley") # This is safe because the single quote has been double escaped sqlInterpolate(ANSI(), sql, name = "H'); DROP TABLE--;") # Using paste0() could lead to dangerous SQL with carefully crafted inputs # (SQL injection) name <- "H'); DROP TABLE--;" paste0("SELECT * FROM X WHERE name = '", name, "'") # Use SQL() or dbQuoteIdentifier() to avoid escaping sql2 <- "SELECT * FROM ?table WHERE name in ?names" sqlInterpolate(ANSI(), sql2, table = dbQuoteIdentifier(ANSI(), "X"), names = SQL("('a', 'b')") ) # Don't use SQL() to escape identifiers to avoid SQL injection sqlInterpolate(ANSI(), sql2, table = SQL("X; DELETE FROM X; SELECT * FROM X"), names = SQL("('a', 'b')") ) # Use dbGetQuery() or dbExecute() to process these queries: if (requireNamespace("RSQLite", quietly = TRUE)) { con <- dbConnect(RSQLite::SQLite()) sql <- "SELECT ?value AS value" query <- sqlInterpolate(con, sql, value = 3) print(dbGetQuery(con, query)) dbDisconnect(con) } } DBI/man/sqlData.Rd0000644000176200001440000000264014157672512013317 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sqlData.R \name{sqlData} \alias{sqlData} \title{Convert a data frame into form suitable for upload to an SQL database} \usage{ sqlData(con, value, row.names = NA, ...) } \arguments{ \item{con}{A database connection.} \item{value}{A data frame} \item{row.names}{Either \code{TRUE}, \code{FALSE}, \code{NA} or a string. If \code{TRUE}, always translate row names to a column called "row_names". If \code{FALSE}, never translate row names. If \code{NA}, translate rownames only if they're a character vector. A string is equivalent to \code{TRUE}, but allows you to override the default name. For backward compatibility, \code{NULL} is equivalent to \code{FALSE}.} \item{...}{Other arguments used by individual methods.} } \description{ This is a generic method that coerces R objects into vectors suitable for upload to the database. The output will vary a little from method to method depending on whether the main upload device is through a single SQL string or multiple parameterized queries. This method is mostly useful for backend implementers. } \details{ The default method: \itemize{ \item Converts factors to characters \item Quotes all strings \item Converts all columns to strings \item Replaces NA with NULL } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") sqlData(con, head(iris)) sqlData(con, head(mtcars)) dbDisconnect(con) } DBI/man/dbSendQuery.Rd0000644000176200001440000001424314157672512014155 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbSendQuery.R \name{dbSendQuery} \alias{dbSendQuery} \title{Execute a query on a given database connection} \usage{ dbSendQuery(conn, statement, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{statement}{a character string containing SQL.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbSendQuery()} returns an S4 object that inherits from \linkS4class{DBIResult}. The result set can be used with \code{\link[=dbFetch]{dbFetch()}} to extract records. Once you have finished using a result, make sure to clear it with \code{\link[=dbClearResult]{dbClearResult()}}. } \description{ The \code{dbSendQuery()} method only submits and synchronously executes the SQL query to the database engine. It does \emph{not} extract any records --- for that you need to use the \code{\link[=dbFetch]{dbFetch()}} method, and then you must call \code{\link[=dbClearResult]{dbClearResult()}} when you finish fetching the records you need. For interactive use, you should almost always prefer \code{\link[=dbGetQuery]{dbGetQuery()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbSendQuery")} } \details{ This method is for \code{SELECT} queries only. Some backends may support data manipulation queries through this method for compatibility reasons. However, callers are strongly encouraged to use \code{\link[=dbSendStatement]{dbSendStatement()}} for data manipulation statements. The query is submitted to the database server and the DBMS executes it, possibly generating vast amounts of data. Where these data live is driver-specific: some drivers may choose to leave the output on the server and transfer them piecemeal to R, others may transfer all the data to the client -- but not necessarily to the memory that R manages. See individual drivers' \code{dbSendQuery()} documentation for details. } \section{Failure modes}{ An error is raised when issuing a query over a closed or invalid connection, or if the query is not a non-\code{NA} string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the \code{params} argument) or the \code{immediate} argument is set to \code{TRUE}. } \section{Additional arguments}{ The following arguments are not part of the \code{dbSendQuery()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{params} (default: \code{NULL}) \item \code{immediate} (default: \code{NULL}) } They must be provided as named arguments. See the "Specification" sections for details on their usage. } \section{Specification}{ No warnings occur under normal conditions. When done, the DBIResult object must be cleared with a call to \code{\link[=dbClearResult]{dbClearResult()}}. Failure to clear the result set leads to a warning when the connection is closed. If the backend supports only one open result set per connection, issuing a second query invalidates an already open result set and raises a warning. The newly opened result set is valid and must be cleared with \code{dbClearResult()}. The \code{param} argument allows passing query parameters, see \code{\link[=dbBind]{dbBind()}} for details. } \section{Specification for the \code{immediate} argument}{ The \code{immediate} argument supports distinguishing between "direct" and "prepared" APIs offered by many database drivers. Passing \code{immediate = TRUE} leads to immediate execution of the query or statement, via the "direct" API (if supported by the driver). The default \code{NULL} means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct \code{immediate} argument. Examples for possible behaviors: \enumerate{ \item DBI backend defaults to \code{immediate = TRUE} internally \enumerate{ \item A query without parameters is passed: query is executed \item A query with parameters is passed: \enumerate{ \item \code{params} not given: rejected immediately by the database because of a syntax error in the query, the backend tries \code{immediate = FALSE} (and gives a message) \item \code{params} given: query is executed using \code{immediate = FALSE} } } \item DBI backend defaults to \code{immediate = FALSE} internally \enumerate{ \item A query without parameters is passed: \enumerate{ \item simple query: query is executed \item "special" query (such as setting a config options): fails, the backend tries \code{immediate = TRUE} (and gives a message) } \item A query with parameters is passed: \enumerate{ \item \code{params} not given: waiting for parameters via \code{\link[=dbBind]{dbBind()}} \item \code{params} given: query is executed } } } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") dbFetch(rs) dbClearResult(rs) # Pass one set of values with the param argument: rs <- dbSendQuery( con, "SELECT * FROM mtcars WHERE cyl = ?", params = list(4L) ) dbFetch(rs) dbClearResult(rs) # Pass multiple sets of values with dbBind(): rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = ?") dbBind(rs, list(6L)) dbFetch(rs) dbBind(rs, list(8L)) dbFetch(rs) dbClearResult(rs) dbDisconnect(con) } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbCallProc.Rd0000644000176200001440000000125014157672512013727 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbCallProc.R \name{dbCallProc} \alias{dbCallProc} \title{Call an SQL stored procedure} \usage{ dbCallProc(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \description{ \strong{Deprecated since 2014} } \details{ The recommended way of calling a stored procedure is now \enumerate{ \item{\code{\link{dbGetQuery}} if a result set is returned} \item{\code{\link{dbExecute}} for data manipulation and other cases where no result set is returned} } } \keyword{internal} DBI/man/dbGetInfo.Rd0000644000176200001440000000763614157672512013601 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIResult.R, R/dbGetInfo.R \name{dbGetInfo} \alias{dbGetInfo} \title{Get DBMS metadata} \usage{ dbGetInfo(dbObj, ...) } \arguments{ \item{dbObj}{An object inheriting from \linkS4class{DBIObject}, i.e. \linkS4class{DBIDriver}, \linkS4class{DBIConnection}, or a \linkS4class{DBIResult}} \item{...}{Other arguments to methods.} } \value{ For objects of class \linkS4class{DBIDriver}, \code{dbGetInfo()} returns a named list that contains at least the following components: \itemize{ \item \code{driver.version}: the package version of the DBI backend, \item \code{client.version}: the version of the DBMS client library. } For objects of class \linkS4class{DBIConnection}, \code{dbGetInfo()} returns a named list that contains at least the following components: \itemize{ \item \code{db.version}: version of the database server, \item \code{dbname}: database name, \item \code{username}: username to connect to the database, \item \code{host}: hostname of the database server, \item \code{port}: port on the database server. It must not contain a \code{password} component. Components that are not applicable should be set to \code{NA}. } For objects of class \linkS4class{DBIResult}, \code{dbGetInfo()} returns a named list that contains at least the following components: \itemize{ \item \code{statatment}: the statement used with \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbExecute]{dbExecute()}}, as returned by \code{\link[=dbGetStatement]{dbGetStatement()}}, \item \code{row.count}: the number of rows fetched so far (for queries), as returned by \code{\link[=dbGetRowCount]{dbGetRowCount()}}, \item \code{rows.affected}: the number of rows affected (for statements), as returned by \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} \item \code{has.completed}: a logical that indicates if the query or statement has completed, as returned by \code{\link[=dbHasCompleted]{dbHasCompleted()}}. } } \description{ Retrieves information on objects of class \linkS4class{DBIDriver}, \linkS4class{DBIConnection} or \linkS4class{DBIResult}. } \section{Implementation notes}{ The default implementation for \verb{DBIResult objects} constructs such a list from the return values of the corresponding methods, \code{\link[=dbGetStatement]{dbGetStatement()}}, \code{\link[=dbGetRowCount]{dbGetRowCount()}}, \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}}, and \code{\link[=dbHasCompleted]{dbHasCompleted()}}. } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIConnection generics} \concept{DBIDriver generics} \concept{DBIResult generics} DBI/man/dbAppendTable.Rd0000644000176200001440000001364114157672512014416 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbAppendTable.R \name{dbAppendTable} \alias{dbAppendTable} \title{Insert rows into a table} \usage{ dbAppendTable(conn, name, value, ..., row.names = NULL) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{value}{A data frame of values. The column names must be consistent with those in the target table in the database.} \item{...}{Other parameters passed on to methods.} \item{row.names}{Must be \code{NULL}.} } \value{ \code{dbAppendTable()} returns a scalar numeric. } \description{ The \code{dbAppendTable()} method assumes that the table has been created beforehand, e.g. with \code{\link[=dbCreateTable]{dbCreateTable()}}. The default implementation calls \code{\link[=sqlAppendTableTemplate]{sqlAppendTableTemplate()}} and then \code{\link[=dbExecute]{dbExecute()}} with the \code{param} argument. Backends compliant to ANSI SQL 99 which use \verb{?} as a placeholder for prepared queries don't need to override it. Backends with a different SQL syntax which use \verb{?} as a placeholder for prepared queries can override \code{\link[=sqlAppendTable]{sqlAppendTable()}}. Other backends (with different placeholders or with entirely different ways to create tables) need to override the \code{dbAppendTable()} method. } \details{ The \code{row.names} argument is not supported by this method. Process the values with \code{\link[=sqlRownamesToColumn]{sqlRownamesToColumn()}} before calling this method. } \section{Failure modes}{ If the table does not exist, or the new data in \code{values} is not a data frame or has different column names, an error is raised; the remote table remains unchanged. An error is raised when calling this method for a closed or invalid connection. An error is also raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. Invalid values for the \code{row.names} argument (non-scalars, unsupported data types, \code{NA}) also raise an error. Passing a \code{value} argument different to \code{NULL} to the \code{row.names} argument (in particular \code{TRUE}, \code{NA}, and a string) raises an error. } \section{Specification}{ SQL keywords can be used freely in table names, column names, and data. Quotes, commas, spaces, and other special characters such as newlines and tabs, can also be used in the data, and, if the database supports non-syntactic identifiers, also for table names and column names. The following data types must be supported at least, and be read identically with \code{\link[=dbReadTable]{dbReadTable()}}: \itemize{ \item integer \item numeric (the behavior for \code{Inf} and \code{NaN} is not specified) \item logical \item \code{NA} as NULL \item 64-bit values (using \code{"bigint"} as field type); the result can be \itemize{ \item converted to a numeric, which may lose precision, \item converted a character vector, which gives the full decimal representation \item written to another table and read again unchanged } \item character (in both UTF-8 and native encodings), supporting empty strings (before and after non-empty strings) \item factor (returned as character, with a warning) \item list of raw (if supported by the database) \item objects of type \link[blob:blob]{blob::blob} (if supported by the database) \item date (if supported by the database; returned as \code{Date}) also for dates prior to 1970 or 1900 or after 2038 \item time (if supported by the database; returned as objects that inherit from \code{difftime}) \item timestamp (if supported by the database; returned as \code{POSIXct} respecting the time zone but not necessarily preserving the input time zone), also for timestamps prior to 1970 or 1900 or after 2038 respecting the time zone but not necessarily preserving the input time zone) } Mixing column types in the same table is supported. The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbAppendTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done to support databases that allow non-syntactic names for their objects: } The \code{row.names} argument must be \code{NULL}, the default value. Row names are ignored. The \code{value} argument must be a data frame with a subset of the columns of the existing table. The order of the columns does not matter. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbAppendTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbCreateTable.Rd0000644000176200001440000001155714157672512014416 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbCreateTable.R \name{dbCreateTable} \alias{dbCreateTable} \title{Create a table in the database} \usage{ dbCreateTable(conn, name, fields, ..., row.names = NULL, temporary = FALSE) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{fields}{Either a character vector or a data frame. A named character vector: Names are column names, values are types. Names are escaped with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Field types are unescaped. A data frame: field types are generated using \code{\link[=dbDataType]{dbDataType()}}.} \item{...}{Other parameters passed on to methods.} \item{row.names}{Must be \code{NULL}.} \item{temporary}{If \code{TRUE}, will generate a temporary table statement.} } \value{ \code{dbCreateTable()} returns \code{TRUE}, invisibly. } \description{ The default \code{dbCreateTable()} method calls \code{\link[=sqlCreateTable]{sqlCreateTable()}} and \code{\link[=dbExecute]{dbExecute()}}. Backends compliant to ANSI SQL 99 don't need to override it. Backends with a different SQL syntax can override \code{sqlCreateTable()}, backends with entirely different ways to create tables need to override this method. } \details{ The \code{row.names} argument is not supported by this method. Process the values with \code{\link[=sqlRownamesToColumn]{sqlRownamesToColumn()}} before calling this method. The argument order is different from the \code{sqlCreateTable()} method, the latter will be adapted in a later release of DBI. } \section{Failure modes}{ If the table exists, an error is raised; the remote table remains unchanged. An error is raised when calling this method for a closed or invalid connection. An error is also raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. Invalid values for the \code{row.names} and \code{temporary} arguments (non-scalars, unsupported data types, \code{NA}, incompatible values, duplicate names) also raise an error. } \section{Additional arguments}{ The following arguments are not part of the \code{dbCreateTable()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{temporary} (default: \code{FALSE}) } They must be provided as named arguments. See the "Specification" and "Value" sections for details on their usage. } \section{Specification}{ The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbCreateTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done } If the \code{temporary} argument is \code{TRUE}, the table is not available in a second connection and is gone after reconnecting. Not all backends support this argument. A regular, non-temporary table is visible in a second connection, in a pre-existing connection, and after reconnecting to the database. SQL keywords can be used freely in table names, column names, and data. Quotes, commas, and spaces can also be used for table names and column names, if the database supports non-syntactic identifiers. The \code{row.names} argument must be missing or \code{NULL}, the default value. All other values for the \code{row.names} argument (in particular \code{TRUE}, \code{NA}, and a string) raise an error. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/ANSI.Rd0000644000176200001440000000046014157554705012461 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ANSI.R \name{ANSI} \alias{ANSI} \title{A dummy DBI connector that simulates ANSI-SQL compliance} \usage{ ANSI() } \description{ A dummy DBI connector that simulates ANSI-SQL compliance } \examples{ ANSI() } \keyword{internal} DBI/man/dbListResults.Rd0000644000176200001440000000253014157672512014527 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbListResults.R \name{dbListResults} \alias{dbListResults} \title{A list of all pending results} \usage{ dbListResults(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \value{ a list. If no results are active, an empty list. If only a single result is active, a list with one element. } \description{ DEPRECATED. DBI currenty supports only one open result set per connection, you need to keep track of the result sets you open if you need this functionality. } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} \keyword{internal} DBI/man/dbExecute.Rd0000644000176200001440000001173714157672512013645 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbExecute.R \name{dbExecute} \alias{dbExecute} \title{Execute an update statement, query number of rows affected, and then close result set} \usage{ dbExecute(conn, statement, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{statement}{a character string containing SQL.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbExecute()} always returns a scalar numeric that specifies the number of rows affected by the statement. } \description{ Executes a statement and returns the number of rows affected. \code{dbExecute()} comes with a default implementation (which should work with most backends) that calls \code{\link[=dbSendStatement]{dbSendStatement()}}, then \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}}, ensuring that the result is always free-d by \code{\link[=dbClearResult]{dbClearResult()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbExecute")} } \details{ You can also use \code{dbExecute()} to call a stored procedure that performs data manipulation or other actions that do not return a result set. To execute a stored procedure that returns a result set use \code{\link[=dbGetQuery]{dbGetQuery()}} instead. } \section{Implementation notes}{ Subclasses should override this method only if they provide some sort of performance optimization. } \section{Failure modes}{ An error is raised when issuing a statement over a closed or invalid connection, if the syntax of the statement is invalid, or if the statement is not a non-\code{NA} string. } \section{Additional arguments}{ The following arguments are not part of the \code{dbExecute()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{params} (default: \code{NULL}) \item \code{immediate} (default: \code{NULL}) } They must be provided as named arguments. See the "Specification" sections for details on their usage. } \section{Specification}{ The \code{param} argument allows passing query parameters, see \code{\link[=dbBind]{dbBind()}} for details. } \section{Specification for the \code{immediate} argument}{ The \code{immediate} argument supports distinguishing between "direct" and "prepared" APIs offered by many database drivers. Passing \code{immediate = TRUE} leads to immediate execution of the query or statement, via the "direct" API (if supported by the driver). The default \code{NULL} means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct \code{immediate} argument. Examples for possible behaviors: \enumerate{ \item DBI backend defaults to \code{immediate = TRUE} internally \enumerate{ \item A query without parameters is passed: query is executed \item A query with parameters is passed: \enumerate{ \item \code{params} not given: rejected immediately by the database because of a syntax error in the query, the backend tries \code{immediate = FALSE} (and gives a message) \item \code{params} given: query is executed using \code{immediate = FALSE} } } \item DBI backend defaults to \code{immediate = FALSE} internally \enumerate{ \item A query without parameters is passed: \enumerate{ \item simple query: query is executed \item "special" query (such as setting a config options): fails, the backend tries \code{immediate = TRUE} (and gives a message) } \item A query with parameters is passed: \enumerate{ \item \code{params} not given: waiting for parameters via \code{\link[=dbBind]{dbBind()}} \item \code{params} given: query is executed } } } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cars", head(cars, 3)) dbReadTable(con, "cars") # there are 3 rows dbExecute( con, "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" ) dbReadTable(con, "cars") # there are now 6 rows # Pass values using the param argument: dbExecute( con, "INSERT INTO cars (speed, dist) VALUES (?, ?)", params = list(4:7, 5:8) ) dbReadTable(con, "cars") # there are now 10 rows dbDisconnect(con) } \seealso{ For queries: \code{\link[=dbSendQuery]{dbSendQuery()}} and \code{\link[=dbGetQuery]{dbGetQuery()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/DBIObject-class.Rd0000644000176200001440000000317114157672512014556 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIObject.R \docType{class} \name{DBIObject-class} \alias{DBIObject-class} \title{DBIObject class} \description{ Base class for all other DBI classes (e.g., drivers, connections). This is a virtual Class: No objects may be created from it. } \details{ More generally, the DBI defines a very small set of classes and generics that allows users and applications access DBMS with a common interface. The virtual classes are \code{DBIDriver} that individual drivers extend, \code{DBIConnection} that represent instances of DBMS connections, and \code{DBIResult} that represent the result of a DBMS statement. These three classes extend the basic class of \code{DBIObject}, which serves as the root or parent of the class hierarchy. } \section{Implementation notes}{ An implementation MUST provide methods for the following generics: \itemize{ \item \code{\link[=dbGetInfo]{dbGetInfo()}}. } It MAY also provide methods for: \itemize{ \item \code{\link[=summary]{summary()}}. Print a concise description of the object. The default method invokes \code{dbGetInfo(dbObj)} and prints the name-value pairs one per line. Individual implementations may tailor this appropriately. } } \examples{ drv <- RSQLite::SQLite() con <- dbConnect(drv) rs <- dbSendQuery(con, "SELECT 1") is(drv, "DBIObject") ## True is(con, "DBIObject") ## True is(rs, "DBIObject") dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIConnector-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIResult-class}} } \concept{DBI classes} DBI/man/dbIsValid.Rd0000644000176200001440000000655214157672512013575 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbIsValid.R \name{dbIsValid} \alias{dbIsValid} \title{Is this DBMS object still valid?} \usage{ dbIsValid(dbObj, ...) } \arguments{ \item{dbObj}{An object inheriting from \linkS4class{DBIObject}, i.e. \linkS4class{DBIDriver}, \linkS4class{DBIConnection}, or a \linkS4class{DBIResult}} \item{...}{Other arguments to methods.} } \value{ \code{dbIsValid()} returns a logical scalar, \code{TRUE} if the object specified by \code{dbObj} is valid, \code{FALSE} otherwise. A \linkS4class{DBIConnection} object is initially valid, and becomes invalid after disconnecting with \code{\link[=dbDisconnect]{dbDisconnect()}}. For an invalid connection object (e.g., for some drivers if the object is saved to a file and then restored), the method also returns \code{FALSE}. A \linkS4class{DBIResult} object is valid after a call to \code{\link[=dbSendQuery]{dbSendQuery()}}, and stays valid even after all rows have been fetched; only clearing it with \code{\link[=dbClearResult]{dbClearResult()}} invalidates it. A \linkS4class{DBIResult} object is also valid after a call to \code{\link[=dbSendStatement]{dbSendStatement()}}, and stays valid after querying the number of rows affected; only clearing it with \code{\link[=dbClearResult]{dbClearResult()}} invalidates it. If the connection to the database system is dropped (e.g., due to connectivity problems, server failure, etc.), \code{dbIsValid()} should return \code{FALSE}. This is not tested automatically. } \description{ This generic tests whether a database object is still valid (i.e. it hasn't been disconnected or cleared). \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbIsValid")} } \examples{ dbIsValid(RSQLite::SQLite()) con <- dbConnect(RSQLite::SQLite(), ":memory:") dbIsValid(con) rs <- dbSendQuery(con, "SELECT 1") dbIsValid(rs) dbClearResult(rs) dbIsValid(rs) dbDisconnect(con) dbIsValid(con) } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbListConnections}()} Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIConnection generics} \concept{DBIDriver generics} \concept{DBIResult generics} DBI/man/dbGetRowCount.Rd0000644000176200001440000000427314157672512014460 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetRowCount.R \name{dbGetRowCount} \alias{dbGetRowCount} \title{The number of rows fetched so far} \usage{ dbGetRowCount(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbGetRowCount()} returns a scalar number (integer or numeric), the number of rows fetched so far. After calling \code{\link[=dbSendQuery]{dbSendQuery()}}, the row count is initially zero. After a call to \code{\link[=dbFetch]{dbFetch()}} without limit, the row count matches the total number of rows returned. Fetching a limited number of rows increases the number of rows by the number of rows returned, even if fetching past the end of the result set. For queries with an empty result set, zero is returned even after fetching. For data manipulation statements issued with \code{\link[=dbSendStatement]{dbSendStatement()}}, zero is returned before and after calling \code{dbFetch()}. } \description{ Returns the total number of rows actually fetched with calls to \code{\link[=dbFetch]{dbFetch()}} for this result set. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetRowCount")} } \section{Failure modes}{ Attempting to get the row count for a result set cleared with \code{\link[=dbClearResult]{dbClearResult()}} gives an error. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQuery(con, "SELECT * FROM mtcars") dbGetRowCount(rs) ret1 <- dbFetch(rs, 10) dbGetRowCount(rs) ret2 <- dbFetch(rs) dbGetRowCount(rs) nrow(ret1) + nrow(ret2) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbReadTable.Rd0000644000176200001440000001072514157672512014062 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbReadTable.R \name{dbReadTable} \alias{dbReadTable} \title{Copy data frames from database tables} \usage{ dbReadTable(conn, name, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbReadTable()} returns a data frame that contains the complete data from the remote table, effectively the result of calling \code{\link[=dbGetQuery]{dbGetQuery()}} with \verb{SELECT * FROM }. An empty table is returned as a data frame with zero rows. The presence of \link{rownames} depends on the \code{row.names} argument, see \code{\link[=sqlColumnToRownames]{sqlColumnToRownames()}} for details: \itemize{ \item If \code{FALSE} or \code{NULL}, the returned data frame doesn't have row names. \item If \code{TRUE}, a column named "row_names" is converted to row names. } \itemize{ \item If \code{NA}, a column named "row_names" is converted to row names if it exists, otherwise no translation occurs. \item If a string, this specifies the name of the column in the remote table that contains the row names. } The default is \code{row.names = FALSE}. If the database supports identifiers with special characters, the columns in the returned data frame are converted to valid R identifiers if the \code{check.names} argument is \code{TRUE}, If \code{check.names = FALSE}, the returned table has non-syntactic column names without quotes. } \description{ Reads a database table to a data frame, optionally converting a column to row names and converting the column names to valid R identifiers. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbReadTable")} } \section{Failure modes}{ An error is raised if the table does not exist. An error is raised if \code{row.names} is \code{TRUE} and no "row_names" column exists, An error is raised if \code{row.names} is set to a string and and no corresponding column exists. An error is raised when calling this method for a closed or invalid connection. An error is raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. Unsupported values for \code{row.names} and \code{check.names} (non-scalars, unsupported data types, \code{NA} for \code{check.names}) also raise an error. } \section{Additional arguments}{ The following arguments are not part of the \code{dbReadTable()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{row.names} (default: \code{FALSE}) \item \code{check.names} } They must be provided as named arguments. See the "Value" section for details on their usage. } \section{Specification}{ The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbReadTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars[1:10, ]) dbReadTable(con, "mtcars") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbQuoteIdentifier.Rd0000644000176200001440000000665014157672512015341 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbQuoteIdentifier.R \name{dbQuoteIdentifier} \alias{dbQuoteIdentifier} \title{Quote identifiers} \usage{ dbQuoteIdentifier(conn, x, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{x}{A character vector, \link{SQL} or \link{Id} object to quote as identifier.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbQuoteIdentifier()} returns an object that can be coerced to \link{character}, of the same length as the input. For an empty character vector this function returns a length-0 object. The names of the input argument are preserved in the output. When passing the returned object again to \code{dbQuoteIdentifier()} as \code{x} argument, it is returned unchanged. Passing objects of class \link{SQL} should also return them unchanged. (For backends it may be most convenient to return \link{SQL} objects to achieve this behavior, but this is not required.) } \description{ Call this method to generate a string that is suitable for use in a query as a column or table name, to make sure that you generate valid SQL and protect against SQL injection attacks. The inverse operation is \code{\link[=dbUnquoteIdentifier]{dbUnquoteIdentifier()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbQuoteIdentifier")} } \section{Failure modes}{ An error is raised if the input contains \code{NA}, but not for an empty string. } \section{Specification}{ Calling \code{\link[=dbGetQuery]{dbGetQuery()}} for a query of the format \verb{SELECT 1 AS ...} returns a data frame with the identifier, unquoted, as column name. Quoted identifiers can be used as table and column names in SQL queries, in particular in queries like \verb{SELECT 1 AS ...} and \verb{SELECT * FROM (SELECT 1) ...}. The method must use a quoting mechanism that is unambiguously different from the quoting mechanism used for strings, so that a query like \verb{SELECT ... FROM (SELECT 1 AS ...)} throws an error if the column names do not match. The method can quote column names that contain special characters such as a space, a dot, a comma, or quotes used to mark strings or identifiers, if the database supports this. In any case, checking the validity of the identifier should be performed only when executing a query, and not by \code{dbQuoteIdentifier()}. } \examples{ # Quoting ensures that arbitrary input is safe for use in a query name <- "Robert'); DROP TABLE Students;--" dbQuoteIdentifier(ANSI(), name) # Use Id() to specify other components such as the schema id_name <- Id(schema = "schema_name", table = "table_name") id_name dbQuoteIdentifier(ANSI(), id_name) # SQL vectors are always passed through as is var_name <- SQL("select") var_name dbQuoteIdentifier(ANSI(), var_name) # This mechanism is used to prevent double escaping dbQuoteIdentifier(ANSI(), dbQuoteIdentifier(ANSI(), name)) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbGetStatement.Rd0000644000176200001440000000314714157672512014643 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetStatement.R \name{dbGetStatement} \alias{dbGetStatement} \title{Get the statement associated with a result set} \usage{ dbGetStatement(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbGetStatement()} returns a string, the query used in either \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbSendStatement]{dbSendStatement()}}. } \description{ Returns the statement that was passed to \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbSendStatement]{dbSendStatement()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetStatement")} } \section{Failure modes}{ Attempting to query the statement for a result set cleared with \code{\link[=dbClearResult]{dbClearResult()}} gives an error. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQuery(con, "SELECT * FROM mtcars") dbGetStatement(rs) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbSetDataMappings.Rd0000644000176200001440000000165114157672512015261 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbSetDataMappings.R \name{dbSetDataMappings} \alias{dbSetDataMappings} \title{Set data mappings between an DBMS and R.} \usage{ dbSetDataMappings(res, flds, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{flds}{a field description object as returned by \code{dbColumnInfo}.} \item{...}{Other arguments passed on to methods.} } \description{ This generic is deprecated since no working implementation was ever produced. } \details{ Sets one or more conversion functions to handle the translation of DBMS data types to R objects. This is only needed for non-primitive data, since all DBI drivers handle the common base types (integers, numeric, strings, etc.) The details on conversion functions (e.g., arguments, whether they can invoke initializers and/or destructors) have not been specified. } \keyword{internal} DBI/man/dbColumnInfo.Rd0000644000176200001440000000441214157672512014304 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbColumnInfo.R \name{dbColumnInfo} \alias{dbColumnInfo} \title{Information about result types} \usage{ dbColumnInfo(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbColumnInfo()} returns a data frame with at least two columns \code{"name"} and \code{"type"} (in that order) (and optional columns that start with a dot). The \code{"name"} and \code{"type"} columns contain the names and types of the R columns of the data frame that is returned from \code{\link[=dbFetch]{dbFetch()}}. The \code{"type"} column is of type \code{character} and only for information. Do not compute on the \code{"type"} column, instead use \code{dbFetch(res, n = 0)} to create a zero-row data frame initialized with the correct data types. } \description{ Produces a data.frame that describes the output of a query. The data.frame should have as many rows as there are output fields in the result set, and each column in the data.frame describes an aspect of the result set field (field name, type, etc.) } \section{Failure modes}{ An attempt to query columns for a closed result set raises an error. } \section{Specification}{ A column named \code{row_names} is treated like any other column. The column names are always consistent with the data returned by \code{dbFetch()}. If the query returns unnamed columns, non-empty and non-\code{NA} names are assigned. Column names that correspond to SQL or R keywords are left unchanged. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") rs <- dbSendQuery(con, "SELECT 1 AS a, 2 AS b") dbColumnInfo(rs) dbFetch(rs) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbListTables.Rd0000644000176200001440000000400714157672512014301 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbListTables.R \name{dbListTables} \alias{dbListTables} \title{List remote tables} \usage{ dbListTables(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbListTables()} returns a character vector that enumerates all tables and views in the database. Tables added with \code{\link[=dbWriteTable]{dbWriteTable()}} are part of the list. As soon a table is removed from the database, it is also removed from the list of database tables. The same applies to temporary tables if supported by the database. The returned names are suitable for quoting with \code{dbQuoteIdentifier()}. } \description{ Returns the unquoted names of remote tables accessible through this connection. This should include views and temporary objects, but not all database backends (in particular \pkg{RMariaDB} and \pkg{RMySQL}) support this. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbListTables")} } \section{Failure modes}{ An error is raised when calling this method for a closed or invalid connection. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListTables(con) dbWriteTable(con, "mtcars", mtcars) dbListTables(con) dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/sqlParseVariables.Rd0000644000176200001440000000315414157672512015352 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interpolate.R, R/sqlParseVariables.R \name{sqlCommentSpec} \alias{sqlCommentSpec} \alias{sqlQuoteSpec} \alias{sqlParseVariablesImpl} \alias{sqlParseVariables} \title{Parse interpolated variables from SQL.} \usage{ sqlCommentSpec(start, end, endRequired) sqlQuoteSpec(start, end, escape = "", doubleEscape = TRUE) sqlParseVariablesImpl(sql, quotes, comments) sqlParseVariables(conn, sql, ...) } \arguments{ \item{start, end}{Start and end characters for quotes and comments} \item{endRequired}{Is the ending character of a comment required?} \item{escape}{What character can be used to escape quoting characters? Defaults to \code{""}, i.e. nothing.} \item{doubleEscape}{Can quoting characters be escaped by doubling them? Defaults to \code{TRUE}.} \item{sql}{SQL to parse (a character string)} \item{quotes}{A list of \code{QuoteSpec} calls defining the quoting specification.} \item{comments}{A list of \code{CommentSpec} calls defining the commenting specification.} } \description{ If you're implementing a backend that uses non-ANSI quoting or commenting rules, you'll need to implement a method for \code{sqlParseVariables} that calls \code{sqlParseVariablesImpl} with the appropriate quote and comment specifications. } \examples{ # Use [] for quoting and no comments sqlParseVariablesImpl("[?a]", list(sqlQuoteSpec("[", "]", "\\\\", FALSE)), list() ) # Standard quotes, use # for commenting sqlParseVariablesImpl("# ?a\n?b", list(sqlQuoteSpec("'", "'"), sqlQuoteSpec('"', '"')), list(sqlCommentSpec("#", "\n", FALSE)) ) } \keyword{internal} DBI/man/dbDriver.Rd0000644000176200001440000000445414157672512013474 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbDriver.R, R/dbUnloadDriver.R \name{dbDriver} \alias{dbDriver} \alias{dbUnloadDriver} \title{Load and unload database drivers} \usage{ dbDriver(drvName, ...) dbUnloadDriver(drv, ...) } \arguments{ \item{drvName}{character name of the driver to instantiate.} \item{...}{any other arguments are passed to the driver \code{drvName}.} \item{drv}{an object that inherits from \code{DBIDriver} as created by \code{dbDriver}.} } \value{ In the case of \code{dbDriver}, an driver object whose class extends \code{DBIDriver}. This object may be used to create connections to the actual DBMS engine. In the case of \code{dbUnloadDriver}, a logical indicating whether the operation succeeded or not. } \description{ These methods are deprecated, please consult the documentation of the individual backends for the construction of driver instances. \code{dbDriver()} is a helper method used to create an new driver object given the name of a database or the corresponding R package. It works through convention: all DBI-extending packages should provide an exported object with the same name as the package. \code{dbDriver()} just looks for this object in the right places: if you know what database you are connecting to, you should call the function directly. \code{dbUnloadDriver()} is not implemented for modern backends. } \details{ The client part of the database communication is initialized (typically dynamically loading C code, etc.) but note that connecting to the database engine itself needs to be done through calls to \code{dbConnect}. } \examples{ # Create a RSQLite driver with a string d <- dbDriver("SQLite") d # But better, access the object directly RSQLite::SQLite() } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} } \concept{DBIDriver generics} \keyword{internal} DBI/man/dbDisconnect.Rd0000644000176200001440000000323214157672512014323 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbDisconnect.R \name{dbDisconnect} \alias{dbDisconnect} \title{Disconnect (close) a connection} \usage{ dbDisconnect(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbDisconnect()} returns \code{TRUE}, invisibly. } \description{ This closes the connection, discards all pending work, and frees resources (e.g., memory, sockets). \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbDisconnect")} } \section{Failure modes}{ A warning is issued on garbage collection when a connection has been released without calling \code{dbDisconnect()}, but this cannot be tested automatically. A warning is issued immediately when calling \code{dbDisconnect()} on an already disconnected or invalid connection. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbClearResult.Rd0000644000176200001440000000352314157672512014462 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbClearResult.R \name{dbClearResult} \alias{dbClearResult} \title{Clear a result set} \usage{ dbClearResult(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbClearResult()} returns \code{TRUE}, invisibly, for result sets obtained from both \code{dbSendQuery()} and \code{dbSendStatement()}. } \description{ Frees all resources (local and remote) associated with a result set. In some cases (e.g., very large result sets) this can be a critical step to avoid exhausting resources (memory, file descriptors, etc.) \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbClearResult")} } \section{Failure modes}{ An attempt to close an already closed result set issues a warning in both cases. } \section{Specification}{ \code{dbClearResult()} frees all resources associated with retrieving the result of a query or update operation. The DBI backend can expect a call to \code{dbClearResult()} for each \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbSendStatement]{dbSendStatement()}} call. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") rs <- dbSendQuery(con, "SELECT 1") print(dbFetch(rs)) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/DBI-package.Rd0000644000176200001440000000462614157672512013723 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBI-package.R \docType{package} \name{DBI-package} \alias{DBI} \alias{DBI-package} \title{DBI: R Database Interface} \description{ DBI defines an interface for communication between R and relational database management systems. All classes in this package are virtual and need to be extended by the various R/DBMS implementations (so-called \emph{DBI backends}). } \section{Definition}{ A DBI backend is an R package which imports the \pkg{DBI} and \pkg{methods} packages. For better or worse, the names of many existing backends start with \sQuote{R}, e.g., \pkg{RSQLite}, \pkg{RMySQL}, \pkg{RSQLServer}; it is up to the backend author to adopt this convention or not. } \section{DBI classes and methods}{ A backend defines three classes, which are subclasses of \linkS4class{DBIDriver}, \linkS4class{DBIConnection}, and \linkS4class{DBIResult}. The backend provides implementation for all methods of these base classes that are defined but not implemented by DBI. All methods defined in \pkg{DBI} are reexported (so that the package can be used without having to attach \pkg{DBI}), and have an ellipsis \code{...} in their formals for extensibility. } \section{Construction of the DBIDriver object}{ The backend must support creation of an instance of its \linkS4class{DBIDriver} subclass with a \dfn{constructor function}. By default, its name is the package name without the leading \sQuote{R} (if it exists), e.g., \code{SQLite} for the \pkg{RSQLite} package. However, backend authors may choose a different name. The constructor must be exported, and it must be a function that is callable without arguments. DBI recommends to define a constructor with an empty argument list. } \examples{ RSQLite::SQLite() } \seealso{ Important generics: \code{\link[=dbConnect]{dbConnect()}}, \code{\link[=dbGetQuery]{dbGetQuery()}}, \code{\link[=dbReadTable]{dbReadTable()}}, \code{\link[=dbWriteTable]{dbWriteTable()}}, \code{\link[=dbDisconnect]{dbDisconnect()}} Formal specification (currently work in progress and incomplete): \code{vignette("spec", package = "DBI")} } \author{ \strong{Maintainer}: Kirill Müller \email{krlmlr+r@mailbox.org} (\href{https://orcid.org/0000-0002-1416-3412}{ORCID}) Authors: \itemize{ \item R Special Interest Group on Databases (R-SIG-DB) \item Hadley Wickham } Other contributors: \itemize{ \item R Consortium [funder] } } DBI/man/dbWithTransaction.Rd0000644000176200001440000000640014157672512015353 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbWithTransaction.R, % R/dbWithTransaction_DBIConnection.R \name{dbWithTransaction} \alias{dbWithTransaction} \alias{dbBreak} \title{Self-contained SQL transactions} \usage{ dbWithTransaction(conn, code, ...) dbBreak() } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{code}{An arbitrary block of R code.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbWithTransaction()} returns the value of the executed code. } \description{ Given that \link{transactions} are implemented, this function allows you to pass in code that is run in a transaction. The default method of \code{dbWithTransaction()} calls \code{\link[=dbBegin]{dbBegin()}} before executing the code, and \code{\link[=dbCommit]{dbCommit()}} after successful completion, or \code{\link[=dbRollback]{dbRollback()}} in case of an error. The advantage is that you don't have to remember to do \code{dbBegin()} and \code{dbCommit()} or \code{dbRollback()} -- that is all taken care of. The special function \code{dbBreak()} allows an early exit with rollback, it can be called only inside \code{dbWithTransaction()}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbWithTransaction")} } \details{ DBI implements \code{dbWithTransaction()}, backends should need to override this generic only if they implement specialized handling. } \section{Failure modes}{ Failure to initiate the transaction (e.g., if the connection is closed or invalid of if \code{\link[=dbBegin]{dbBegin()}} has been called already) gives an error. } \section{Specification}{ \code{dbWithTransaction()} initiates a transaction with \code{dbBegin()}, executes the code given in the \code{code} argument, and commits the transaction with \code{\link[=dbCommit]{dbCommit()}}. If the code raises an error, the transaction is instead aborted with \code{\link[=dbRollback]{dbRollback()}}, and the error is propagated. If the code calls \code{dbBreak()}, execution of the code stops and the transaction is silently aborted. All side effects caused by the code (such as the creation of new variables) propagate to the calling environment. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cash", data.frame(amount = 100)) dbWriteTable(con, "account", data.frame(amount = 2000)) # All operations are carried out as logical unit: dbWithTransaction( con, { withdrawal <- 300 dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) } ) # The code is executed as if in the curent environment: withdrawal # The changes are committed to the database after successful execution: dbReadTable(con, "cash") dbReadTable(con, "account") # Rolling back with dbBreak(): dbWithTransaction( con, { withdrawal <- 5000 dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) if (dbReadTable(con, "account")$amount < 0) { dbBreak() } } ) # These changes were not committed to the database: dbReadTable(con, "cash") dbReadTable(con, "account") dbDisconnect(con) } DBI/man/dbConnect.Rd0000644000176200001440000000726014157672512013630 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbConnect.R \name{dbConnect} \alias{dbConnect} \title{Create a connection to a DBMS} \usage{ dbConnect(drv, ...) } \arguments{ \item{drv}{an object that inherits from \linkS4class{DBIDriver}, or an existing \linkS4class{DBIConnection} object (in order to clone an existing connection).} \item{...}{authentication arguments needed by the DBMS instance; these typically include \code{user}, \code{password}, \code{host}, \code{port}, \code{dbname}, etc. For details see the appropriate \code{DBIDriver}.} } \value{ \code{dbConnect()} returns an S4 object that inherits from \linkS4class{DBIConnection}. This object is used to communicate with the database engine. A \code{\link[=format]{format()}} method is defined for the connection object. It returns a string that consists of a single line of text. } \description{ Connect to a DBMS going through the appropriate authentication procedure. Some implementations may allow you to have multiple connections open, so you may invoke this function repeatedly assigning its output to different objects. The authentication mechanism is left unspecified, so check the documentation of individual drivers for details. Use \code{\link[=dbCanConnect]{dbCanConnect()}} to check if a connection can be established. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbConnect")} } \section{Specification}{ DBI recommends using the following argument names for authentication parameters, with \code{NULL} default: \itemize{ \item \code{user} for the user name (default: current user) \item \code{password} for the password \item \code{host} for the host name (default: local connection) \item \code{port} for the port number (default: local connection) \item \code{dbname} for the name of the database on the host, or the database file name } The defaults should provide reasonable behavior, in particular a local connection for \code{host = NULL}. For some DBMS (e.g., PostgreSQL), this is different to a TCP/IP connection to \code{localhost}. In addition, DBI supports the \code{bigint} argument that governs how 64-bit integer data is returned. The following values are supported: \itemize{ \item \code{"integer"}: always return as \code{integer}, silently overflow \item \code{"numeric"}: always return as \code{numeric}, silently round \item \code{"character"}: always return the decimal representation as \code{character} \item \code{"integer64"}: return as a data type that can be coerced using \code{\link[=as.integer]{as.integer()}} (with warning on overflow), \code{\link[=as.numeric]{as.numeric()}} and \code{\link[=as.character]{as.character()}} } } \examples{ # SQLite only needs a path to the database. (Here, ":memory:" is a special # path that creates an in-memory database.) Other database drivers # will require more details (like user, password, host, port, etc.) con <- dbConnect(RSQLite::SQLite(), ":memory:") con dbListTables(con) dbDisconnect(con) # Bad, for subtle reasons: # This code fails when RSQLite isn't loaded yet, # because dbConnect() doesn't know yet about RSQLite. dbListTables(con <- dbConnect(RSQLite::SQLite(), ":memory:")) } \seealso{ \code{\link[=dbDisconnect]{dbDisconnect()}} to disconnect from a database. Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} Other DBIConnector generics: \code{\link{DBIConnector-class}}, \code{\link{dbDataType}()}, \code{\link{dbGetConnectArgs}()}, \code{\link{dbIsReadOnly}()} } \concept{DBIConnector generics} \concept{DBIDriver generics} DBI/man/rownames.Rd0000644000176200001440000000267714157672262013575 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rownames.R \name{rownames} \alias{rownames} \alias{sqlRownamesToColumn} \alias{sqlColumnToRownames} \title{Convert row names back and forth between columns} \usage{ sqlRownamesToColumn(df, row.names = NA) sqlColumnToRownames(df, row.names = NA) } \arguments{ \item{df}{A data frame} \item{row.names}{Either \code{TRUE}, \code{FALSE}, \code{NA} or a string. If \code{TRUE}, always translate row names to a column called "row_names". If \code{FALSE}, never translate row names. If \code{NA}, translate rownames only if they're a character vector. A string is equivalent to \code{TRUE}, but allows you to override the default name. For backward compatibility, \code{NULL} is equivalent to \code{FALSE}.} } \description{ These functions provide a reasonably automatic way of preserving the row names of data frame during back-and-forth translation to an SQL table. By default, row names will be converted to an explicit column called "row_names", and any query returning a column called "row_names" will have those automatically set as row names. These methods are mostly useful for backend implementers. } \examples{ # If have row names sqlRownamesToColumn(head(mtcars)) sqlRownamesToColumn(head(mtcars), FALSE) sqlRownamesToColumn(head(mtcars), "ROWNAMES") # If don't have sqlRownamesToColumn(head(iris)) sqlRownamesToColumn(head(iris), TRUE) sqlRownamesToColumn(head(iris), "ROWNAMES") } DBI/man/DBIResult-class.Rd0000644000176200001440000000263314157672512014630 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIResult.R \docType{class} \name{DBIResult-class} \alias{DBIResult-class} \title{DBIResult class} \description{ This virtual class describes the result and state of execution of a DBMS statement (any statement, query or non-query). The result set keeps track of whether the statement produces output how many rows were affected by the operation, how many rows have been fetched (if statement is a query), whether there are more rows to fetch, etc. } \section{Implementation notes}{ Individual drivers are free to allow single or multiple active results per connection. The default show method displays a summary of the query using other DBI generics. } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIConnector-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIObject-class}} Other DBIResult generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBI classes} \concept{DBIResult generics} DBI/man/dbExistsTable.Rd0000644000176200001440000000552214157672512014465 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbExistsTable.R \name{dbExistsTable} \alias{dbExistsTable} \title{Does a table exist?} \usage{ dbExistsTable(conn, name, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbExistsTable()} returns a logical scalar, \code{TRUE} if the table or view specified by the \code{name} argument exists, \code{FALSE} otherwise. This includes temporary tables if supported by the database. } \description{ Returns if a table given by name exists in the database. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbExistsTable")} } \section{Failure modes}{ An error is raised when calling this method for a closed or invalid connection. An error is also raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. } \section{Specification}{ The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbExistsTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done } For all tables listed by \code{\link[=dbListTables]{dbListTables()}}, \code{dbExistsTable()} returns \code{TRUE}. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/hidden_aliases.Rd0000644000176200001440000002056014157672512014663 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ANSI.R, R/SQLKeywords_DBIObject.R, % R/SQLKeywords_missing.R, R/dbAppendTable_DBIConnection.R, % R/dbCanConnect_DBIDriver.R, R/dbConnect_DBIConnector.R, % R/dbCreateTable_DBIConnection.R, R/dbDataType_DBIConnector.R, % R/dbDataType_DBIObject.R, R/dbDriver_character.R, % R/dbExecute_DBIConnection_character.R, R/dbExistsTable_DBIConnection_Id.R, % R/dbFetch_DBIResult.R, R/dbGetConnectArgs_DBIConnector.R, % R/dbGetInfo_DBIResult.R, R/dbGetQuery_DBIConnection_character.R, % R/dbIsReadOnly_DBIConnector.R, R/dbIsReadOnly_DBIObject.R, % R/dbListFields_DBIConnection_Id.R, R/dbListFields_DBIConnection_character.R, % R/dbListObjects_DBIConnection_ANY.R, % R/dbQuoteIdentifier_DBIConnection.R, R/dbQuoteLiteral_DBIConnection.R, % R/dbQuoteString_DBIConnection.R, R/dbReadTable_DBIConnection_Id.R, % R/dbReadTable_DBIConnection_character.R, R/dbRemoveTable_DBIConnection_Id.R, % R/dbSendStatement_DBIConnection_character.R, % R/dbUnquoteIdentifier_DBIConnection.R, R/dbWithTransaction_DBIConnection.R, % R/dbWriteTable_DBIConnection_Id_ANY.R, R/isSQLKeyword_DBIObject_character.R, % R/make.db.names_DBIObject_character.R, R/show_AnsiConnection.R, % R/show_DBIConnection.R, R/show_DBIConnector.R, % R/show_DBIDriver.R, R/show_DBIResult.R, R/show_Id.R, R/show_SQL.R, % R/sqlAppendTable_DBIConnection.R, R/sqlCreateTable_DBIConnection.R, % R/sqlData_DBIConnection.R, R/sqlInterpolate_DBIConnection.R, % R/sqlParseVariables_DBIConnection.R \docType{methods} \name{hidden_aliases} \alias{hidden_aliases} \alias{SQLKeywords_DBIObject} \alias{SQLKeywords,DBIObject-method} \alias{SQLKeywords_missing} \alias{SQLKeywords,missing-method} \alias{dbAppendTable_DBIConnection} \alias{dbAppendTable,DBIConnection-method} \alias{dbCanConnect_DBIDriver} \alias{dbCanConnect,DBIDriver-method} \alias{dbConnect_DBIConnector} \alias{dbConnect,DBIConnector-method} \alias{dbCreateTable_DBIConnection} \alias{dbCreateTable,DBIConnection-method} \alias{dbDataType_DBIConnector} \alias{dbDataType,DBIConnector-method} \alias{dbDataType_DBIObject} \alias{dbDataType,DBIObject-method} \alias{dbDriver_character} \alias{dbDriver,character-method} \alias{dbExecute_DBIConnection_character} \alias{dbExecute,DBIConnection,character-method} \alias{dbExistsTable_DBIConnection_Id} \alias{dbExistsTable,DBIConnection,Id-method} \alias{dbFetch_DBIResult} \alias{dbFetch,DBIResult-method} \alias{dbGetConnectArgs_DBIConnector} \alias{dbGetConnectArgs,DBIConnector-method} \alias{dbGetInfo_DBIResult} \alias{dbGetInfo,DBIResult-method} \alias{dbGetQuery_DBIConnection_character} \alias{dbGetQuery,DBIConnection,character-method} \alias{dbIsReadOnly_DBIConnector} \alias{dbIsReadOnly,DBIConnector-method} \alias{dbIsReadOnly_DBIObject} \alias{dbIsReadOnly,DBIObject-method} \alias{dbListFields_DBIConnection_Id} \alias{dbListFields,DBIConnection,Id-method} \alias{dbListFields_DBIConnection_character} \alias{dbListFields,DBIConnection,character-method} \alias{dbListObjects_DBIConnection_ANY} \alias{dbListObjects,DBIConnection-method} \alias{dbQuoteIdentifier_DBIConnection} \alias{dbQuoteIdentifier,DBIConnection,ANY-method} \alias{dbQuoteIdentifier,DBIConnection,character-method} \alias{dbQuoteIdentifier,DBIConnection,SQL-method} \alias{dbQuoteIdentifier,DBIConnection,Id-method} \alias{dbQuoteLiteral_DBIConnection} \alias{dbQuoteLiteral,DBIConnection-method} \alias{dbQuoteString_DBIConnection} \alias{dbQuoteString,DBIConnection,ANY-method} \alias{dbQuoteString,DBIConnection,character-method} \alias{dbQuoteString,DBIConnection,SQL-method} \alias{dbReadTable_DBIConnection_Id} \alias{dbReadTable,DBIConnection,Id-method} \alias{dbReadTable_DBIConnection_character} \alias{dbReadTable,DBIConnection,character-method} \alias{dbRemoveTable_DBIConnection_Id} \alias{dbRemoveTable,DBIConnection,Id-method} \alias{dbSendStatement_DBIConnection_character} \alias{dbSendStatement,DBIConnection,character-method} \alias{dbUnquoteIdentifier_DBIConnection} \alias{dbUnquoteIdentifier,DBIConnection-method} \alias{dbWithTransaction_DBIConnection} \alias{dbWithTransaction,DBIConnection-method} \alias{dbWriteTable_DBIConnection_Id_ANY} \alias{dbWriteTable,DBIConnection,Id-method} \alias{isSQLKeyword_DBIObject_character} \alias{isSQLKeyword,DBIObject,character-method} \alias{make.db.names_DBIObject_character} \alias{make.db.names,DBIObject,character-method} \alias{show_AnsiConnection} \alias{show,AnsiConnection-method} \alias{show_DBIConnection} \alias{show,DBIConnection-method} \alias{show_DBIConnector} \alias{show,DBIConnector-method} \alias{show_DBIDriver} \alias{show,DBIDriver-method} \alias{show_DBIResult} \alias{show,DBIResult-method} \alias{show_Id} \alias{show,Id-method} \alias{show_SQL} \alias{show,SQL-method} \alias{sqlAppendTable_DBIConnection} \alias{sqlAppendTable,DBIConnection-method} \alias{sqlCreateTable_DBIConnection} \alias{sqlCreateTable,DBIConnection-method} \alias{sqlData_DBIConnection} \alias{sqlData,DBIConnection-method} \alias{sqlInterpolate_DBIConnection} \alias{sqlInterpolate,DBIConnection-method} \alias{sqlParseVariables_DBIConnection} \alias{sqlParseVariables,DBIConnection-method} \title{Internal page for hidden aliases} \usage{ \S4method{SQLKeywords}{DBIObject}(dbObj, ...) \S4method{SQLKeywords}{missing}(dbObj, ...) \S4method{dbAppendTable}{DBIConnection}(conn, name, value, ..., row.names = NULL) \S4method{dbCanConnect}{DBIDriver}(drv, ...) \S4method{dbConnect}{DBIConnector}(drv, ...) \S4method{dbCreateTable}{DBIConnection}(conn, name, fields, ..., row.names = NULL, temporary = FALSE) \S4method{dbDataType}{DBIConnector}(dbObj, obj, ...) \S4method{dbDataType}{DBIObject}(dbObj, obj, ...) \S4method{dbDriver}{character}(drvName, ...) \S4method{dbExecute}{DBIConnection,character}(conn, statement, ...) \S4method{dbExistsTable}{DBIConnection,Id}(conn, name, ...) \S4method{dbFetch}{DBIResult}(res, n = -1, ...) \S4method{dbGetConnectArgs}{DBIConnector}(drv, eval = TRUE, ...) \S4method{dbGetInfo}{DBIResult}(dbObj, ...) \S4method{dbGetQuery}{DBIConnection,character}(conn, statement, ..., n = -1L) \S4method{dbIsReadOnly}{DBIConnector}(dbObj, ...) \S4method{dbIsReadOnly}{DBIObject}(dbObj, ...) \S4method{dbListFields}{DBIConnection,Id}(conn, name, ...) \S4method{dbListFields}{DBIConnection,character}(conn, name, ...) \S4method{dbListObjects}{DBIConnection}(conn, prefix = NULL, ...) \S4method{dbQuoteIdentifier}{DBIConnection,ANY}(conn, x, ...) \S4method{dbQuoteIdentifier}{DBIConnection,character}(conn, x, ...) \S4method{dbQuoteIdentifier}{DBIConnection,SQL}(conn, x, ...) \S4method{dbQuoteIdentifier}{DBIConnection,Id}(conn, x, ...) \S4method{dbQuoteLiteral}{DBIConnection}(conn, x, ...) \S4method{dbQuoteString}{DBIConnection,ANY}(conn, x, ...) \S4method{dbQuoteString}{DBIConnection,character}(conn, x, ...) \S4method{dbQuoteString}{DBIConnection,SQL}(conn, x, ...) \S4method{dbReadTable}{DBIConnection,Id}(conn, name, ...) \S4method{dbReadTable}{DBIConnection,character}(conn, name, ..., row.names = FALSE, check.names = TRUE) \S4method{dbRemoveTable}{DBIConnection,Id}(conn, name, ...) \S4method{dbSendStatement}{DBIConnection,character}(conn, statement, ...) \S4method{dbUnquoteIdentifier}{DBIConnection}(conn, x, ...) \S4method{dbWithTransaction}{DBIConnection}(conn, code) \S4method{dbWriteTable}{DBIConnection,Id}(conn, name, value, ...) \S4method{isSQLKeyword}{DBIObject,character}( dbObj, name, keywords = .SQL92Keywords, case = c("lower", "upper", "any")[3], ... ) \S4method{make.db.names}{DBIObject,character}( dbObj, snames, keywords = .SQL92Keywords, unique = TRUE, allow.keywords = TRUE, ... ) \S4method{show}{AnsiConnection}(object) \S4method{show}{DBIConnection}(object) \S4method{show}{DBIConnector}(object) \S4method{show}{DBIDriver}(object) \S4method{show}{DBIResult}(object) \S4method{show}{Id}(object) \S4method{show}{SQL}(object) \S4method{sqlAppendTable}{DBIConnection}(con, table, values, row.names = NA, ...) \S4method{sqlCreateTable}{DBIConnection}(con, table, fields, row.names = NA, temporary = FALSE, ...) \S4method{sqlData}{DBIConnection}(con, value, row.names = NA, ...) \S4method{sqlInterpolate}{DBIConnection}(conn, sql, ..., .dots = list()) \S4method{sqlParseVariables}{DBIConnection}(conn, sql, ...) } \arguments{ \item{n}{Number of rows to fetch, default -1} \item{object}{Table object to print} } \description{ For S4 methods that require a documentation entry but only clutter the index. } \keyword{internal} DBI/man/make.db.names.Rd0000644000176200001440000000671014157672512014333 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/deprecated.R, R/isSQLKeyword.R, % R/make.db.names.R \name{make.db.names.default} \alias{make.db.names.default} \alias{isSQLKeyword.default} \alias{isSQLKeyword} \alias{make.db.names} \alias{SQLKeywords} \title{Make R identifiers into legal SQL identifiers} \usage{ make.db.names.default( snames, keywords = .SQL92Keywords, unique = TRUE, allow.keywords = TRUE ) isSQLKeyword.default( name, keywords = .SQL92Keywords, case = c("lower", "upper", "any")[3] ) isSQLKeyword( dbObj, name, keywords = .SQL92Keywords, case = c("lower", "upper", "any")[3], ... ) make.db.names( dbObj, snames, keywords = .SQL92Keywords, unique = TRUE, allow.keywords = TRUE, ... ) } \arguments{ \item{snames}{a character vector of R identifiers (symbols) from which we need to make SQL identifiers.} \item{keywords}{a character vector with SQL keywords, by default it's \code{.SQL92Keywords} defined by the DBI.} \item{unique}{logical describing whether the resulting set of SQL names should be unique. Its default is \code{TRUE}. Following the SQL 92 standard, uniqueness of SQL identifiers is determined regardless of whether letters are upper or lower case.} \item{allow.keywords}{logical describing whether SQL keywords should be allowed in the resulting set of SQL names. Its default is \code{TRUE}} \item{name}{a character vector with database identifier candidates we need to determine whether they are legal SQL identifiers or not.} \item{case}{a character string specifying whether to make the comparison as lower case, upper case, or any of the two. it defaults to \code{any}.} \item{dbObj}{any DBI object (e.g., \code{DBIDriver}).} \item{\dots}{any other argument are passed to the driver implementation.} } \value{ \code{make.db.names} returns a character vector of legal SQL identifiers corresponding to its \code{snames} argument. \code{SQLKeywords} returns a character vector of all known keywords for the database-engine associated with \code{dbObj}. \code{isSQLKeyword} returns a logical vector parallel to \code{name}. } \description{ These methods are DEPRECATED. Please use \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} (or possibly \code{\link[=dbQuoteString]{dbQuoteString()}}) instead. } \details{ The algorithm in \code{make.db.names} first invokes \code{make.names} and then replaces each occurrence of a dot \code{.} by an underscore \verb{_}. If \code{allow.keywords} is \code{FALSE} and identifiers collide with SQL keywords, a small integer is appended to the identifier in the form of \code{"_n"}. The set of SQL keywords is stored in the character vector \code{.SQL92Keywords} and reflects the SQL ANSI/ISO standard as documented in "X/Open SQL and RDA", 1994, ISBN 1-872630-68-8. Users can easily override or update this vector. } \section{Bugs}{ The current mapping is not guaranteed to be fully reversible: some SQL identifiers that get mapped into R identifiers with \code{make.names} and then back to SQL with \code{\link[=make.db.names]{make.db.names()}} will not be equal to the original SQL identifiers (e.g., compound SQL identifiers of the form \code{username.tablename} will loose the dot ``.''). } \references{ The set of SQL keywords is stored in the character vector \code{.SQL92Keywords} and reflects the SQL ANSI/ISO standard as documented in "X/Open SQL and RDA", 1994, ISBN 1-872630-68-8. Users can easily override or update this vector. } \keyword{internal} DBI/man/dbGetRowsAffected.Rd0000644000176200001440000000356214157672512015254 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetRowsAffected.R \name{dbGetRowsAffected} \alias{dbGetRowsAffected} \title{The number of rows affected} \usage{ dbGetRowsAffected(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbGetRowsAffected()} returns a scalar number (integer or numeric), the number of rows affected by a data manipulation statement issued with \code{\link[=dbSendStatement]{dbSendStatement()}}. The value is available directly after the call and does not change after calling \code{\link[=dbFetch]{dbFetch()}}. For queries issued with \code{\link[=dbSendQuery]{dbSendQuery()}}, zero is returned before and after the call to \code{dbFetch()}. } \description{ This method returns the number of rows that were added, deleted, or updated by a data manipulation statement. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetRowsAffected")} } \section{Failure modes}{ Attempting to get the rows affected for a result set cleared with \code{\link[=dbClearResult]{dbClearResult()}} gives an error. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendStatement(con, "DELETE FROM mtcars") dbGetRowsAffected(rs) nrow(mtcars) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbListObjects.Rd0000644000176200001440000001013514157672512014457 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbListObjects.R \name{dbListObjects} \alias{dbListObjects} \title{List remote objects} \usage{ dbListObjects(conn, prefix = NULL, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{prefix}{A fully qualified path in the database's namespace, or \code{NULL}. This argument will be processed with \code{\link[=dbUnquoteIdentifier]{dbUnquoteIdentifier()}}. If given the method will return all objects accessible through this prefix.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbListObjects()} returns a data frame with columns \code{table} and \code{is_prefix} (in that order), optionally with other columns with a dot (\code{.}) prefix. The \code{table} column is of type list. Each object in this list is suitable for use as argument in \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. The \code{is_prefix} column is a logical. This data frame contains one row for each object (schema, table and view) accessible from the prefix (if passed) or from the global namespace (if prefix is omitted). Tables added with \code{\link[=dbWriteTable]{dbWriteTable()}} are part of the data frame. As soon a table is removed from the database, it is also removed from the data frame of database objects. The same applies to temporary objects if supported by the database. The returned names are suitable for quoting with \code{dbQuoteIdentifier()}. } \description{ Returns the names of remote objects accessible through this connection as a data frame. This should include temporary objects, but not all database backends (in particular \pkg{RMariaDB} and \pkg{RMySQL}) support this. Compared to \code{\link[=dbListTables]{dbListTables()}}, this method also enumerates tables and views in schemas, and returns fully qualified identifiers to access these objects. This allows exploration of all database objects available to the current user, including those that can only be accessed by giving the full namespace. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbListObjects")} } \section{Failure modes}{ An error is raised when calling this method for a closed or invalid connection. } \section{Specification}{ The \code{table} object can be quoted with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. The result of quoting can be passed to \code{\link[=dbUnquoteIdentifier]{dbUnquoteIdentifier()}}. The unquoted results are equal to the original \code{table} object. (For backends it may be convenient to use the \link{Id} class, but this is not required.) The \code{prefix} column indicates if the \code{table} value refers to a table or a prefix. For a call with the default \code{prefix = NULL}, the \code{table} values that have \code{is_prefix == FALSE} correspond to the tables returned from \code{\link[=dbListTables]{dbListTables()}}, Values in \code{table} column that have \code{is_prefix == TRUE} can be passed as the \code{prefix} argument to another call to \code{dbListObjects()}. For the data frame returned from a \code{dbListObject()} call with the \code{prefix} argument set, all \code{table} values where \code{is_prefix} is \code{FALSE} can be used in a call to \code{\link[=dbExistsTable]{dbExistsTable()}} which returns \code{TRUE}. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListObjects(con) dbWriteTable(con, "mtcars", mtcars) dbListObjects(con) dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbListFields.Rd0000644000176200001440000000534614157672512014304 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbListFields.R \name{dbListFields} \alias{dbListFields} \title{List field names of a remote table} \usage{ dbListFields(conn, name, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbListFields()} returns a character vector that enumerates all fields in the table in the correct order. This also works for temporary tables if supported by the database. The returned names are suitable for quoting with \code{dbQuoteIdentifier()}. } \description{ List field names of a remote table } \section{Failure modes}{ If the table does not exist, an error is raised. Invalid types for the \code{name} argument (e.g., \code{character} of length not equal to one, or numeric) lead to an error. An error is also raised when calling this method for a closed or invalid connection. } \section{Specification}{ The \code{name} argument can be \itemize{ \item a string \item the return value of \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} \item a value from the \code{table} column from the return value of \code{\link[=dbListObjects]{dbListObjects()}} where \code{is_prefix} is \code{FALSE} } A column named \code{row_names} is treated like any other column. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbListFields(con, "mtcars") dbDisconnect(con) } \seealso{ \code{\link[=dbColumnInfo]{dbColumnInfo()}} to get the type of the fields. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbDataType.Rd0000644000176200001440000001111314157672512013742 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbDataType.R \name{dbDataType} \alias{dbDataType} \title{Determine the SQL data type of an object} \usage{ dbDataType(dbObj, obj, ...) } \arguments{ \item{dbObj}{A object inheriting from \linkS4class{DBIDriver} or \linkS4class{DBIConnection}} \item{obj}{An R object whose SQL type we want to determine.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbDataType()} returns the SQL type that corresponds to the \code{obj} argument as a non-empty character string. For data frames, a character vector with one element per column is returned. } \description{ Returns an SQL string that describes the SQL data type to be used for an object. The default implementation of this generic determines the SQL type of an R object according to the SQL 92 specification, which may serve as a starting point for driver implementations. DBI also provides an implementation for data.frame which will return a character vector giving the type for each column in the dataframe. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbDataType")} } \details{ The data types supported by databases are different than the data types in R, but the mapping between the primitive types is straightforward: \itemize{ \item Any of the many fixed and varying length character types are mapped to character vectors \item Fixed-precision (non-IEEE) numbers are mapped into either numeric or integer vectors. } Notice that many DBMS do not follow IEEE arithmetic, so there are potential problems with under/overflows and loss of precision. } \section{Failure modes}{ An error is raised for invalid values for the \code{obj} argument such as a \code{NULL} value. } \section{Specification}{ The backend can override the \code{\link[=dbDataType]{dbDataType()}} generic for its driver class. This generic expects an arbitrary object as second argument. To query the values returned by the default implementation, run \code{example(dbDataType, package = "DBI")}. If the backend needs to override this generic, it must accept all basic R data types as its second argument, namely \link{logical}, \link{integer}, \link{numeric}, \link{character}, dates (see \link{Dates}), date-time (see \link{DateTimeClasses}), and \link{difftime}. If the database supports blobs, this method also must accept lists of \link{raw} vectors, and \link[blob:blob]{blob::blob} objects. As-is objects (i.e., wrapped by \code{\link[=I]{I()}}) must be supported and return the same results as their unwrapped counterparts. The SQL data type for \link{factor} and \link{ordered} is the same as for character. The behavior for other object types is not specified. All data types returned by \code{dbDataType()} are usable in an SQL statement of the form \code{"CREATE TABLE test (a ...)"}. } \examples{ dbDataType(ANSI(), 1:5) dbDataType(ANSI(), 1) dbDataType(ANSI(), TRUE) dbDataType(ANSI(), Sys.Date()) dbDataType(ANSI(), Sys.time()) dbDataType(ANSI(), Sys.time() - as.POSIXct(Sys.Date())) dbDataType(ANSI(), c("x", "abc")) dbDataType(ANSI(), list(raw(10), raw(20))) dbDataType(ANSI(), I(3)) dbDataType(ANSI(), iris) con <- dbConnect(RSQLite::SQLite(), ":memory:") dbDataType(con, 1:5) dbDataType(con, 1) dbDataType(con, TRUE) dbDataType(con, Sys.Date()) dbDataType(con, Sys.time()) dbDataType(con, Sys.time() - as.POSIXct(Sys.Date())) dbDataType(con, c("x", "abc")) dbDataType(con, list(raw(10), raw(20))) dbDataType(con, I(3)) dbDataType(con, iris) dbDisconnect(con) } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} Other DBIConnector generics: \code{\link{DBIConnector-class}}, \code{\link{dbConnect}()}, \code{\link{dbGetConnectArgs}()}, \code{\link{dbIsReadOnly}()} } \concept{DBIConnection generics} \concept{DBIConnector generics} \concept{DBIDriver generics} DBI/man/dbRemoveTable.Rd0000644000176200001440000000747514157672512014454 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbRemoveTable.R \name{dbRemoveTable} \alias{dbRemoveTable} \title{Remove a table from the database} \usage{ dbRemoveTable(conn, name, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbRemoveTable()} returns \code{TRUE}, invisibly. } \description{ Remove a remote table (e.g., created by \code{\link[=dbWriteTable]{dbWriteTable()}}) from the database. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbRemoveTable")} } \section{Failure modes}{ If the table does not exist, an error is raised. An attempt to remove a view with this function may result in an error. An error is raised when calling this method for a closed or invalid connection. An error is also raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. } \section{Additional arguments}{ The following arguments are not part of the \code{dbRemoveTable()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{temporary} (default: \code{FALSE}) \item \code{fail_if_missing} (default: \code{TRUE}) } These arguments must be provided as named arguments. If \code{temporary} is \code{TRUE}, the call to \code{dbRemoveTable()} will consider only temporary tables. Not all backends support this argument. In particular, permanent tables of the same name are left untouched. If \code{fail_if_missing} is \code{FALSE}, the call to \code{dbRemoveTable()} succeeds if the table does not exist. } \section{Specification}{ A table removed by \code{dbRemoveTable()} doesn't appear in the list of tables returned by \code{\link[=dbListTables]{dbListTables()}}, and \code{\link[=dbExistsTable]{dbExistsTable()}} returns \code{FALSE}. The removal propagates immediately to other connections to the same database. This function can also be used to remove a temporary table. The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbRemoveTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbRemoveTable(con, "iris") dbExistsTable(con, "iris") dbDisconnect(con) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbBind.Rd0000644000176200001440000001740714157672512013117 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbBind.R \name{dbBind} \alias{dbBind} \title{Bind values to a parameterized/prepared statement} \usage{ dbBind(res, params, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{params}{A list of bindings, named or unnamed.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbBind()} returns the result set, invisibly, for queries issued by \code{\link[=dbSendQuery]{dbSendQuery()}} and also for data manipulation statements issued by \code{\link[=dbSendStatement]{dbSendStatement()}}. } \description{ For parametrized or prepared statements, the \code{\link[=dbSendQuery]{dbSendQuery()}} and \code{\link[=dbSendStatement]{dbSendStatement()}} functions can be called with statements that contain placeholders for values. The \code{dbBind()} function binds these placeholders to actual values, and is intended to be called on the result set before calling \code{\link[=dbFetch]{dbFetch()}} or \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbBind")} } \details{ \pkg{DBI} supports parametrized (or prepared) queries and statements via the \code{dbBind()} generic. Parametrized queries are different from normal queries in that they allow an arbitrary number of placeholders, which are later substituted by actual values. Parametrized queries (and statements) serve two purposes: \itemize{ \item The same query can be executed more than once with different values. The DBMS may cache intermediate information for the query, such as the execution plan, and execute it faster. \item Separation of query syntax and parameters protects against SQL injection. } The placeholder format is currently not specified by \pkg{DBI}; in the future, a uniform placeholder syntax may be supported. Consult the backend documentation for the supported formats. For automated testing, backend authors specify the placeholder syntax with the \code{placeholder_pattern} tweak. Known examples are: \itemize{ \item \verb{?} (positional matching in order of appearance) in \pkg{RMySQL} and \pkg{RSQLite} \item \verb{$1} (positional matching by index) in \pkg{RPostgres} and \pkg{RSQLite} \item \verb{:name} and \verb{$name} (named matching) in \pkg{RSQLite} } } \section{Failure modes}{ Calling \code{dbBind()} for a query without parameters raises an error. Binding too many or not enough values, or parameters with wrong names or unequal length, also raises an error. If the placeholders in the query are named, all parameter values must have names (which must not be empty or \code{NA}), and vice versa, otherwise an error is raised. The behavior for mixing placeholders of different types (in particular mixing positional and named placeholders) is not specified. Calling \code{dbBind()} on a result set already cleared by \code{\link[=dbClearResult]{dbClearResult()}} also raises an error. } \section{Specification}{ \pkg{DBI} clients execute parametrized statements as follows: \enumerate{ \item Call \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbSendStatement]{dbSendStatement()}} with a query or statement that contains placeholders, store the returned \linkS4class{DBIResult} object in a variable. Mixing placeholders (in particular, named and unnamed ones) is not recommended. It is good practice to register a call to \code{\link[=dbClearResult]{dbClearResult()}} via \code{\link[=on.exit]{on.exit()}} right after calling \code{dbSendQuery()} or \code{dbSendStatement()} (see the last enumeration item). Until \code{dbBind()} has been called, the returned result set object has the following behavior: \itemize{ \item \code{\link[=dbFetch]{dbFetch()}} raises an error (for \code{dbSendQuery()}) \item \code{\link[=dbGetRowCount]{dbGetRowCount()}} returns zero (for \code{dbSendQuery()}) \item \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} returns an integer \code{NA} (for \code{dbSendStatement()}) \item \code{\link[=dbIsValid]{dbIsValid()}} returns \code{TRUE} \item \code{\link[=dbHasCompleted]{dbHasCompleted()}} returns \code{FALSE} } \item Construct a list with parameters that specify actual values for the placeholders. The list must be named or unnamed, depending on the kind of placeholders used. Named values are matched to named parameters, unnamed values are matched by position in the list of parameters. All elements in this list must have the same lengths and contain values supported by the backend; a \link{data.frame} is internally stored as such a list. The parameter list is passed to a call to \code{dbBind()} on the \code{DBIResult} object. \item Retrieve the data or the number of affected rows from the \code{DBIResult} object. \itemize{ \item For queries issued by \code{dbSendQuery()}, call \code{\link[=dbFetch]{dbFetch()}}. \item For statements issued by \code{dbSendStatements()}, call \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}}. (Execution begins immediately after the \code{dbBind()} call, the statement is processed entirely before the function returns.) } \item Repeat 2. and 3. as necessary. \item Close the result set via \code{\link[=dbClearResult]{dbClearResult()}}. } The elements of the \code{params} argument do not need to be scalars, vectors of arbitrary length (including length 0) are supported. For queries, calling \code{dbFetch()} binding such parameters returns concatenated results, equivalent to binding and fetching for each set of values and connecting via \code{\link[=rbind]{rbind()}}. For data manipulation statements, \code{dbGetRowsAffected()} returns the total number of rows affected if binding non-scalar parameters. \code{dbBind()} also accepts repeated calls on the same result set for both queries and data manipulation statements, even if no results are fetched between calls to \code{dbBind()}, for both queries and data manipulation statements. If the placeholders in the query are named, their order in the \code{params} argument is not important. At least the following data types are accepted on input (including \link{NA}): \itemize{ \item \link{integer} \item \link{numeric} \item \link{logical} for Boolean values \item \link{character} (also with special characters such as spaces, newlines, quotes, and backslashes) \item \link{factor} (bound as character, with warning) \item \link{Date} (also when stored internally as integer) \item \link{POSIXct} timestamps \item \link{POSIXlt} timestamps \item \link{difftime} values (also with units other than seconds and with the value stored as integer) \item lists of \link{raw} for blobs (with \code{NULL} entries for SQL NULL values) \item objects of type \link[blob:blob]{blob::blob} } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "iris", iris) # Using the same query for different values iris_result <- dbSendQuery(con, "SELECT * FROM iris WHERE [Petal.Width] > ?") dbBind(iris_result, list(2.3)) dbFetch(iris_result) dbBind(iris_result, list(3)) dbFetch(iris_result) dbClearResult(iris_result) # Executing the same statement with different values at once iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = $species") dbBind(iris_result, list(species = c("setosa", "versicolor", "unknown"))) dbGetRowsAffected(iris_result) dbClearResult(iris_result) nrow(dbReadTable(con, "iris")) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbGetConnectArgs.Rd0000644000176200001440000000226614157672512015106 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetConnectArgs.R \name{dbGetConnectArgs} \alias{dbGetConnectArgs} \title{Get connection arguments} \usage{ dbGetConnectArgs(drv, eval = TRUE, ...) } \arguments{ \item{drv}{A object inheriting from \linkS4class{DBIConnector}.} \item{eval}{Set to \code{FALSE} to return the functions that generate the argument instead of evaluating them.} \item{...}{Other arguments passed on to methods. Not otherwise used.} } \description{ Returns the arguments stored in a \linkS4class{DBIConnector} object for inspection, optionally evaluating them. This function is called by \code{\link[=dbConnect]{dbConnect()}} and usually does not need to be called directly. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetConnectArgs")} } \examples{ cnr <- new("DBIConnector", .drv = RSQLite::SQLite(), .conn_args = list(dbname = ":memory:", password = function() "supersecret") ) dbGetConnectArgs(cnr) dbGetConnectArgs(cnr, eval = FALSE) } \seealso{ Other DBIConnector generics: \code{\link{DBIConnector-class}}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbIsReadOnly}()} } \concept{DBIConnector generics} DBI/man/DBIConnection-class.Rd0000644000176200001440000000275314157672512015454 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIConnection.R \docType{class} \name{DBIConnection-class} \alias{DBIConnection-class} \title{DBIConnection class} \description{ This virtual class encapsulates the connection to a DBMS, and it provides access to dynamic queries, result sets, DBMS session management (transactions), etc. } \section{Implementation note}{ Individual drivers are free to implement single or multiple simultaneous connections. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") con dbDisconnect(con) \dontrun{ con <- dbConnect(RPostgreSQL::PostgreSQL(), "username", "passsword") con dbDisconnect(con) } } \seealso{ Other DBI classes: \code{\link{DBIConnector-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIObject-class}}, \code{\link{DBIResult-class}} Other DBIConnection generics: \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBI classes} \concept{DBIConnection generics} DBI/man/dbFetch.Rd0000644000176200001440000001312314157672512013263 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbFetch.R, R/fetch.R \name{dbFetch} \alias{dbFetch} \alias{fetch} \title{Fetch records from a previously executed query} \usage{ dbFetch(res, n = -1, ...) fetch(res, n = -1, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}, created by \code{\link[=dbSendQuery]{dbSendQuery()}}.} \item{n}{maximum number of records to retrieve per fetch. Use \code{n = -1} or \code{n = Inf} to retrieve all pending records. Some implementations may recognize other special values.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbFetch()} always returns a \link{data.frame} with as many rows as records were fetched and as many columns as fields in the result set, even if the result is a single value or has one or zero rows. } \description{ Fetch the next \code{n} elements (rows) from the result set and return them as a data.frame. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbFetch")} } \details{ \code{fetch()} is provided for compatibility with older DBI clients - for all new code you are strongly encouraged to use \code{dbFetch()}. The default implementation for \code{dbFetch()} calls \code{fetch()} so that it is compatible with existing code. Modern backends should implement for \code{dbFetch()} only. } \section{Failure modes}{ An attempt to fetch from a closed result set raises an error. If the \code{n} argument is not an atomic whole number greater or equal to -1 or Inf, an error is raised, but a subsequent call to \code{dbFetch()} with proper \code{n} argument succeeds. Calling \code{dbFetch()} on a result set from a data manipulation query created by \code{\link[=dbSendStatement]{dbSendStatement()}} can be fetched and return an empty data frame, with a warning. } \section{Specification}{ Fetching multi-row queries with one or more columns by default returns the entire result. Multi-row queries can also be fetched progressively by passing a whole number (\link{integer} or \link{numeric}) as the \code{n} argument. A value of \link{Inf} for the \code{n} argument is supported and also returns the full result. If more rows than available are fetched, the result is returned in full without warning. If fewer rows than requested are returned, further fetches will return a data frame with zero rows. If zero rows are fetched, the columns of the data frame are still fully typed. Fetching fewer rows than available is permitted, no warning is issued when clearing the result set. A column named \code{row_names} is treated like any other column. The column types of the returned data frame depend on the data returned: \itemize{ \item \link{integer} (or coercible to an integer) for integer values between -2^31 and 2^31 - 1, with \link{NA} for SQL \code{NULL} values \item \link{numeric} for numbers with a fractional component, with NA for SQL \code{NULL} values \item \link{logical} for Boolean values (some backends may return an integer); with NA for SQL \code{NULL} values \item \link{character} for text, with NA for SQL \code{NULL} values \item lists of \link{raw} for blobs with \link{NULL} entries for SQL NULL values \item coercible using \code{\link[=as.Date]{as.Date()}} for dates, with NA for SQL \code{NULL} values (also applies to the return value of the SQL function \code{current_date}) \item coercible using \code{\link[hms:hms]{hms::as_hms()}} for times, with NA for SQL \code{NULL} values (also applies to the return value of the SQL function \code{current_time}) \item coercible using \code{\link[=as.POSIXct]{as.POSIXct()}} for timestamps, with NA for SQL \code{NULL} values (also applies to the return value of the SQL function \code{current_timestamp}) } If dates and timestamps are supported by the backend, the following R types are used: \itemize{ \item \link{Date} for dates (also applies to the return value of the SQL function \code{current_date}) \item \link{POSIXct} for timestamps (also applies to the return value of the SQL function \code{current_timestamp}) } R has no built-in type with lossless support for the full range of 64-bit or larger integers. If 64-bit integers are returned from a query, the following rules apply: \itemize{ \item Values are returned in a container with support for the full range of valid 64-bit values (such as the \code{integer64} class of the \pkg{bit64} package) \item Coercion to numeric always returns a number that is as close as possible to the true value \item Loss of precision when converting to numeric gives a warning \item Conversion to character always returns a lossless decimal representation of the data } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) # Fetch all results rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") dbFetch(rs) dbClearResult(rs) # Fetch in chunks rs <- dbSendQuery(con, "SELECT * FROM mtcars") while (!dbHasCompleted(rs)) { chunk <- dbFetch(rs, 10) print(nrow(chunk)) } dbClearResult(rs) dbDisconnect(con) } \seealso{ Close the result set with \code{\link[=dbClearResult]{dbClearResult()}} as soon as you finish retrieving the records you want. Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbSendStatement.Rd0000644000176200001440000001405714157672512015017 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbSendStatement.R \name{dbSendStatement} \alias{dbSendStatement} \title{Execute a data manipulation statement on a given database connection} \usage{ dbSendStatement(conn, statement, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{statement}{a character string containing SQL.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbSendStatement()} returns an S4 object that inherits from \linkS4class{DBIResult}. The result set can be used with \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} to determine the number of rows affected by the query. Once you have finished using a result, make sure to clear it with \code{\link[=dbClearResult]{dbClearResult()}}. } \description{ The \code{dbSendStatement()} method only submits and synchronously executes the SQL data manipulation statement (e.g., \code{UPDATE}, \code{DELETE}, \verb{INSERT INTO}, \verb{DROP TABLE}, ...) to the database engine. To query the number of affected rows, call \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} on the returned result object. You must also call \code{\link[=dbClearResult]{dbClearResult()}} after that. For interactive use, you should almost always prefer \code{\link[=dbExecute]{dbExecute()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbSendStatement")} } \details{ \code{\link[=dbSendStatement]{dbSendStatement()}} comes with a default implementation that simply forwards to \code{\link[=dbSendQuery]{dbSendQuery()}}, to support backends that only implement the latter. } \section{Failure modes}{ An error is raised when issuing a statement over a closed or invalid connection, or if the statement is not a non-\code{NA} string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the \code{params} argument) or the \code{immediate} argument is set to \code{TRUE}. } \section{Additional arguments}{ The following arguments are not part of the \code{dbSendStatement()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{params} (default: \code{NULL}) \item \code{immediate} (default: \code{NULL}) } They must be provided as named arguments. See the "Specification" sections for details on their usage. } \section{Specification}{ No warnings occur under normal conditions. When done, the DBIResult object must be cleared with a call to \code{\link[=dbClearResult]{dbClearResult()}}. Failure to clear the result set leads to a warning when the connection is closed. If the backend supports only one open result set per connection, issuing a second query invalidates an already open result set and raises a warning. The newly opened result set is valid and must be cleared with \code{dbClearResult()}. The \code{param} argument allows passing query parameters, see \code{\link[=dbBind]{dbBind()}} for details. } \section{Specification for the \code{immediate} argument}{ The \code{immediate} argument supports distinguishing between "direct" and "prepared" APIs offered by many database drivers. Passing \code{immediate = TRUE} leads to immediate execution of the query or statement, via the "direct" API (if supported by the driver). The default \code{NULL} means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct \code{immediate} argument. Examples for possible behaviors: \enumerate{ \item DBI backend defaults to \code{immediate = TRUE} internally \enumerate{ \item A query without parameters is passed: query is executed \item A query with parameters is passed: \enumerate{ \item \code{params} not given: rejected immediately by the database because of a syntax error in the query, the backend tries \code{immediate = FALSE} (and gives a message) \item \code{params} given: query is executed using \code{immediate = FALSE} } } \item DBI backend defaults to \code{immediate = FALSE} internally \enumerate{ \item A query without parameters is passed: \enumerate{ \item simple query: query is executed \item "special" query (such as setting a config options): fails, the backend tries \code{immediate = TRUE} (and gives a message) } \item A query with parameters is passed: \enumerate{ \item \code{params} not given: waiting for parameters via \code{\link[=dbBind]{dbBind()}} \item \code{params} given: query is executed } } } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cars", head(cars, 3)) rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" ) dbHasCompleted(rs) dbGetRowsAffected(rs) dbClearResult(rs) dbReadTable(con, "cars") # there are now 6 rows # Pass one set of values directly using the param argument: rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (?, ?)", params = list(4L, 5L) ) dbClearResult(rs) # Pass multiple sets of values using dbBind(): rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (?, ?)" ) dbBind(rs, list(5:6, 6:7)) dbBind(rs, list(7L, 8L)) dbClearResult(rs) dbReadTable(con, "cars") # there are now 10 rows dbDisconnect(con) } \seealso{ For queries: \code{\link[=dbSendQuery]{dbSendQuery()}} and \code{\link[=dbGetQuery]{dbGetQuery()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/transactions.Rd0000644000176200001440000000742114157672512014440 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbBegin.R, R/dbCommit.R, R/dbRollback.R, % R/transactions.R \name{dbBegin} \alias{dbBegin} \alias{dbCommit} \alias{dbRollback} \alias{transactions} \title{Begin/commit/rollback SQL transactions} \usage{ dbBegin(conn, ...) dbCommit(conn, ...) dbRollback(conn, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbBegin()}, \code{dbCommit()} and \code{dbRollback()} return \code{TRUE}, invisibly. } \description{ A transaction encapsulates several SQL statements in an atomic unit. It is initiated with \code{dbBegin()} and either made persistent with \code{dbCommit()} or undone with \code{dbRollback()}. In any case, the DBMS guarantees that either all or none of the statements have a permanent effect. This helps ensuring consistency of write operations to multiple tables. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("transactions")} } \details{ Not all database engines implement transaction management, in which case these methods should not be implemented for the specific \linkS4class{DBIConnection} subclass. } \section{Failure modes}{ The implementations are expected to raise an error in case of failure, but this is not tested. In any way, all generics throw an error with a closed or invalid connection. In addition, a call to \code{dbCommit()} or \code{dbRollback()} without a prior call to \code{dbBegin()} raises an error. Nested transactions are not supported by DBI, an attempt to call \code{dbBegin()} twice yields an error. } \section{Specification}{ Actual support for transactions may vary between backends. A transaction is initiated by a call to \code{dbBegin()} and committed by a call to \code{dbCommit()}. Data written in a transaction must persist after the transaction is committed. For example, a record that is missing when the transaction is started but is created during the transaction must exist both during and after the transaction, and also in a new connection. A transaction can also be aborted with \code{dbRollback()}. All data written in such a transaction must be removed after the transaction is rolled back. For example, a record that is missing when the transaction is started but is created during the transaction must not exist anymore after the rollback. Disconnection from a connection with an open transaction effectively rolls back the transaction. All data written in such a transaction must be removed after the transaction is rolled back. The behavior is not specified if other arguments are passed to these functions. In particular, \pkg{RSQLite} issues named transactions with support for nesting if the \code{name} argument is set. The transaction isolation level is not specified by DBI. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cash", data.frame(amount = 100)) dbWriteTable(con, "account", data.frame(amount = 2000)) # All operations are carried out as logical unit: dbBegin(con) withdrawal <- 300 dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) dbCommit(con) dbReadTable(con, "cash") dbReadTable(con, "account") # Rolling back after detecting negative value on account: dbBegin(con) withdrawal <- 5000 dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) if (dbReadTable(con, "account")$amount >= 0) { dbCommit(con) } else { dbRollback(con) } dbReadTable(con, "cash") dbReadTable(con, "account") dbDisconnect(con) } \seealso{ Self-contained transactions: \code{\link[=dbWithTransaction]{dbWithTransaction()}} } DBI/man/dbUnquoteIdentifier.Rd0000644000176200001440000000650014157672512015676 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbUnquoteIdentifier.R \name{dbUnquoteIdentifier} \alias{dbUnquoteIdentifier} \title{Unquote identifiers} \usage{ dbUnquoteIdentifier(conn, x, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{x}{An \link{SQL} or \link{Id} object.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbUnquoteIdentifier()} returns a list of objects of the same length as the input. For an empty character vector this function returns a length-0 object. The names of the input argument are preserved in the output. When passing the first element of a returned object again to \code{dbUnquoteIdentifier()} as \code{x} argument, it is returned unchanged (but wrapped in a list). Passing objects of class \link{Id} should also return them unchanged (but wrapped in a list). (For backends it may be most convenient to return \link{Id} objects to achieve this behavior, but this is not required.) } \description{ Call this method to convert a \link{SQL} object created by \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} back to a list of \link{Id} objects. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbUnquoteIdentifier")} } \section{Failure modes}{ An error is raised if plain character vectors are passed as the \code{x} argument. } \section{Specification}{ For any character vector of length one, quoting (with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}) then unquoting then quoting the first element is identical to just quoting. This is also true for strings that contain special characters such as a space, a dot, a comma, or quotes used to mark strings or identifiers, if the database supports this. Unquoting simple strings (consisting of only letters) wrapped with \code{\link[=SQL]{SQL()}} and then quoting via \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} gives the same result as just quoting the string. Similarly, unquoting expressions of the form \code{SQL("schema.table")} and then quoting gives the same result as quoting the identifier constructed by \code{Id(schema = "schema", table = "table")}. } \examples{ # Unquoting allows to understand the structure of a # possibly complex quoted identifier dbUnquoteIdentifier( ANSI(), SQL(c('"Catalog"."Schema"."Table"', '"Schema"."Table"', '"UnqualifiedTable"')) ) # The returned object is always a list, # also for Id objects dbUnquoteIdentifier( ANSI(), Id(catalog = "Catalog", schema = "Schema", table = "Table") ) # Quoting is the inverse operation to unquoting the elements # of the returned list dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]] ) dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), Id(schema = "Schema", table = "Table"))[[1]] ) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBIResult generics} DBI/man/dbListConnections.Rd0000644000176200001440000000147714157672512015361 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbListConnections.R \name{dbListConnections} \alias{dbListConnections} \title{List currently open connections} \usage{ dbListConnections(drv, ...) } \arguments{ \item{drv}{A object inheriting from \linkS4class{DBIDriver}} \item{...}{Other arguments passed on to methods.} } \value{ a list } \description{ DEPRECATED, drivers are no longer required to implement this method. Keep track of the connections you opened if you require a list. } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()} } \concept{DBIDriver generics} \keyword{internal} DBI/man/dbHasCompleted.Rd0000644000176200001440000000467514157672512014616 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbHasCompleted.R \name{dbHasCompleted} \alias{dbHasCompleted} \title{Completion status} \usage{ dbHasCompleted(res, ...) } \arguments{ \item{res}{An object inheriting from \linkS4class{DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbHasCompleted()} returns a logical scalar. For a query initiated by \code{\link[=dbSendQuery]{dbSendQuery()}} with non-empty result set, \code{dbHasCompleted()} returns \code{FALSE} initially and \code{TRUE} after calling \code{\link[=dbFetch]{dbFetch()}} without limit. For a query initiated by \code{\link[=dbSendStatement]{dbSendStatement()}}, \code{dbHasCompleted()} always returns \code{TRUE}. } \description{ This method returns if the operation has completed. A \code{SELECT} query is completed if all rows have been fetched. A data manipulation statement is always completed. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbHasCompleted")} } \section{Failure modes}{ Attempting to query completion status for a result set cleared with \code{\link[=dbClearResult]{dbClearResult()}} gives an error. } \section{Specification}{ The completion status for a query is only guaranteed to be set to \code{FALSE} after attempting to fetch past the end of the entire result. Therefore, for a query with an empty result set, the initial return value is unspecified, but the result value is \code{TRUE} after trying to fetch only one row. Similarly, for a query with a result set of length n, the return value is unspecified after fetching n rows, but the result value is \code{TRUE} after trying to fetch only one more row. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQuery(con, "SELECT * FROM mtcars") dbHasCompleted(rs) ret1 <- dbFetch(rs, 10) dbHasCompleted(rs) ret2 <- dbFetch(rs) dbHasCompleted(rs) dbClearResult(rs) dbDisconnect(con) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbGetDBIVersion.Rd0000644000176200001440000000045514157554705014645 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/deprecated.R \name{dbGetDBIVersion} \alias{dbGetDBIVersion} \title{Determine the current version of the package.} \usage{ dbGetDBIVersion() } \description{ Determine the current version of the package. } \keyword{internal} DBI/man/DBIConnector-class.Rd0000644000176200001440000000273514157672512015307 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIConnector.R \docType{class} \name{DBIConnector-class} \alias{DBIConnector-class} \title{DBIConnector class} \description{ Wraps objects of the \linkS4class{DBIDriver} class to include connection options. The purpose of this class is to store both the driver and the connection options. A database connection can be established with a call to \code{\link[=dbConnect]{dbConnect()}}, passing only that object without additional arguments. } \details{ To prevent leakage of passwords and other credentials, this class supports delayed evaluation. All arguments can optionally be a function (callable without arguments). In such a case, the function is evaluated transparently when connecting in \code{\link[=dbGetConnectArgs]{dbGetConnectArgs()}}. } \examples{ # Create a connector: cnr <- new("DBIConnector", .drv = RSQLite::SQLite(), .conn_args = list(dbname = ":memory:") ) cnr # Establish a connection through this connector: con <- dbConnect(cnr) con # Access the database through this connection: dbGetQuery(con, "SELECT 1 AS a") dbDisconnect(con) } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIObject-class}}, \code{\link{DBIResult-class}} Other DBIConnector generics: \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbGetConnectArgs}()}, \code{\link{dbIsReadOnly}()} } \concept{DBI classes} \concept{DBIConnector generics} DBI/man/dbQuoteString.Rd0000644000176200001440000000573514157672512014530 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbQuoteString.R \name{dbQuoteString} \alias{dbQuoteString} \title{Quote literal strings} \usage{ dbQuoteString(conn, x, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{x}{A character vector to quote as string.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbQuoteString()} returns an object that can be coerced to \link{character}, of the same length as the input. For an empty character vector this function returns a length-0 object. When passing the returned object again to \code{dbQuoteString()} as \code{x} argument, it is returned unchanged. Passing objects of class \link{SQL} should also return them unchanged. (For backends it may be most convenient to return \link{SQL} objects to achieve this behavior, but this is not required.) } \description{ Call this method to generate a string that is suitable for use in a query as a string literal, to make sure that you generate valid SQL and protect against SQL injection attacks. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbQuoteString")} } \section{Failure modes}{ Passing a numeric, integer, logical, or raw vector, or a list for the \code{x} argument raises an error. } \section{Specification}{ The returned expression can be used in a \verb{SELECT ...} query, and for any scalar character \code{x} the value of \code{dbGetQuery(paste0("SELECT ", dbQuoteString(x)))[[1]]} must be identical to \code{x}, even if \code{x} contains spaces, tabs, quotes (single or double), backticks, or newlines (in any combination) or is itself the result of a \code{dbQuoteString()} call coerced back to character (even repeatedly). If \code{x} is \code{NA}, the result must merely satisfy \code{\link[=is.na]{is.na()}}. The strings \code{"NA"} or \code{"NULL"} are not treated specially. \code{NA} should be translated to an unquoted SQL \code{NULL}, so that the query \verb{SELECT * FROM (SELECT 1) a WHERE ... IS NULL} returns one row. } \examples{ # Quoting ensures that arbitrary input is safe for use in a query name <- "Robert'); DROP TABLE Students;--" dbQuoteString(ANSI(), name) # NAs become NULL dbQuoteString(ANSI(), c("x", NA)) # SQL vectors are always passed through as is var_name <- SQL("select") var_name dbQuoteString(ANSI(), var_name) # This mechanism is used to prevent double escaping dbQuoteString(ANSI(), dbQuoteString(ANSI(), name)) } \seealso{ Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbUnquoteIdentifier}()} } \concept{DBIResult generics} DBI/man/dbWriteTable.Rd0000644000176200001440000002007414157701453014274 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbWriteTable.R \name{dbWriteTable} \alias{dbWriteTable} \title{Copy data frames to database tables} \usage{ dbWriteTable(conn, name, value, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{name}{The table name, passed on to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}. Options are: \itemize{ \item a character string with the unquoted DBMS table name, e.g. \code{"table_name"}, \item a call to \code{\link[=Id]{Id()}} with components to the fully qualified table name, e.g. \code{Id(schema = "my_schema", table = "table_name")} \item a call to \code{\link[=SQL]{SQL()}} with the quoted and fully qualified table name given verbatim, e.g. \code{SQL('"my_schema"."table_name"')} }} \item{value}{a \link{data.frame} (or coercible to data.frame).} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbWriteTable()} returns \code{TRUE}, invisibly. } \description{ Writes, overwrites or appends a data frame to a database table, optionally converting row names to a column and specifying SQL data types for fields. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbWriteTable")} } \details{ This function is useful if you want to create and load a table at the same time. Use \code{\link[=dbAppendTable]{dbAppendTable()}} for appending data to a table, and \code{\link[=dbCreateTable]{dbCreateTable()}}, \code{\link[=dbExistsTable]{dbExistsTable()}} and \code{\link[=dbRemoveTable]{dbRemoveTable()}} for more control over the individual operations. DBI only standardizes writing data frames. Some backends might implement methods that can consume CSV files or other data formats. For details, see the documentation for the individual methods. } \section{Failure modes}{ If the table exists, and both \code{append} and \code{overwrite} arguments are unset, or \code{append = TRUE} and the data frame with the new data has different column names, an error is raised; the remote table remains unchanged. An error is raised when calling this method for a closed or invalid connection. An error is also raised if \code{name} cannot be processed with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} or if this results in a non-scalar. Invalid values for the additional arguments \code{row.names}, \code{overwrite}, \code{append}, \code{field.types}, and \code{temporary} (non-scalars, unsupported data types, \code{NA}, incompatible values, duplicate or missing names, incompatible columns) also raise an error. } \section{Additional arguments}{ The following arguments are not part of the \code{dbWriteTable()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{row.names} (default: \code{FALSE}) \item \code{overwrite} (default: \code{FALSE}) \item \code{append} (default: \code{FALSE}) \item \code{field.types} (default: \code{NULL}) \item \code{temporary} (default: \code{FALSE}) } They must be provided as named arguments. See the "Specification" and "Value" sections for details on their usage. } \section{Specification}{ The \code{name} argument is processed as follows, to support databases that allow non-syntactic names for their objects: \itemize{ \item If an unquoted table name as string: \code{dbWriteTable()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}}: no more quoting is done } The \code{value} argument must be a data frame with a subset of the columns of the existing table if \code{append = TRUE}. The order of the columns does not matter with \code{append = TRUE}. If the \code{overwrite} argument is \code{TRUE}, an existing table of the same name will be overwritten. This argument doesn't change behavior if the table does not exist yet. If the \code{append} argument is \code{TRUE}, the rows in an existing table are preserved, and the new data are appended. If the table doesn't exist yet, it is created. If the \code{temporary} argument is \code{TRUE}, the table is not available in a second connection and is gone after reconnecting. Not all backends support this argument. A regular, non-temporary table is visible in a second connection, in a pre-existing connection, and after reconnecting to the database. SQL keywords can be used freely in table names, column names, and data. Quotes, commas, spaces, and other special characters such as newlines and tabs, can also be used in the data, and, if the database supports non-syntactic identifiers, also for table names and column names. The following data types must be supported at least, and be read identically with \code{\link[=dbReadTable]{dbReadTable()}}: \itemize{ \item integer \item numeric (the behavior for \code{Inf} and \code{NaN} is not specified) \item logical \item \code{NA} as NULL \item 64-bit values (using \code{"bigint"} as field type); the result can be \itemize{ \item converted to a numeric, which may lose precision, \item converted a character vector, which gives the full decimal representation \item written to another table and read again unchanged } \item character (in both UTF-8 and native encodings), supporting empty strings before and after a non-empty string \item factor (returned as character) \item list of raw (if supported by the database) \item objects of type \link[blob:blob]{blob::blob} (if supported by the database) \item date (if supported by the database; returned as \code{Date}), also for dates prior to 1970 or 1900 or after 2038 \item time (if supported by the database; returned as objects that inherit from \code{difftime}) \item timestamp (if supported by the database; returned as \code{POSIXct} respecting the time zone but not necessarily preserving the input time zone), also for timestamps prior to 1970 or 1900 or after 2038 respecting the time zone but not necessarily preserving the input time zone) } Mixing column types in the same table is supported. The \code{field.types} argument must be a named character vector with at most one entry for each column. It indicates the SQL data type to be used for a new column. If a column is missed from \code{field.types}, the type is inferred from the input data with \code{\link[=dbDataType]{dbDataType()}}. The interpretation of \link{rownames} depends on the \code{row.names} argument, see \code{\link[=sqlRownamesToColumn]{sqlRownamesToColumn()}} for details: \itemize{ \item If \code{FALSE} or \code{NULL}, row names are ignored. \item If \code{TRUE}, row names are converted to a column named "row_names", even if the input data frame only has natural row names from 1 to \code{nrow(...)}. \item If \code{NA}, a column named "row_names" is created if the data has custom row names, no extra column is created in the case of natural row names. \item If a string, this specifies the name of the column in the remote table that contains the row names, even if the input data frame only has natural row names. } The default is \code{row.names = FALSE}. } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars[1:5, ]) dbReadTable(con, "mtcars") dbWriteTable(con, "mtcars", mtcars[6:10, ], append = TRUE) dbReadTable(con, "mtcars") dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE) dbReadTable(con, "mtcars") # No row names dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE, row.names = FALSE) dbReadTable(con, "mtcars") } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()} } \concept{DBIConnection generics} DBI/man/dbGetQuery.Rd0000644000176200001440000001400714157672512014001 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetQuery.R \name{dbGetQuery} \alias{dbGetQuery} \title{Send query, retrieve results and then clear result set} \usage{ dbGetQuery(conn, statement, ...) } \arguments{ \item{conn}{A \linkS4class{DBIConnection} object, as returned by \code{\link[=dbConnect]{dbConnect()}}.} \item{statement}{a character string containing SQL.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbGetQuery()} always returns a \link{data.frame} with as many rows as records were fetched and as many columns as fields in the result set, even if the result is a single value or has one or zero rows. } \description{ Returns the result of a query as a data frame. \code{dbGetQuery()} comes with a default implementation (which should work with most backends) that calls \code{\link[=dbSendQuery]{dbSendQuery()}}, then \code{\link[=dbFetch]{dbFetch()}}, ensuring that the result is always free-d by \code{\link[=dbClearResult]{dbClearResult()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetQuery")} } \details{ This method is for \code{SELECT} queries only (incl. other SQL statements that return a \code{SELECT}-alike result, e. g. execution of a stored procedure). To execute a stored procedure that does not return a result set, use \code{\link[=dbExecute]{dbExecute()}}. Some backends may support data manipulation statements through this method for compatibility reasons. However, callers are strongly advised to use \code{\link[=dbExecute]{dbExecute()}} for data manipulation statements. } \section{Implementation notes}{ Subclasses should override this method only if they provide some sort of performance optimization. } \section{Failure modes}{ An error is raised when issuing a query over a closed or invalid connection, if the syntax of the query is invalid, or if the query is not a non-\code{NA} string. If the \code{n} argument is not an atomic whole number greater or equal to -1 or Inf, an error is raised, but a subsequent call to \code{dbGetQuery()} with proper \code{n} argument succeeds. } \section{Additional arguments}{ The following arguments are not part of the \code{dbGetQuery()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{n} (default: -1) \item \code{params} (default: \code{NULL}) \item \code{immediate} (default: \code{NULL}) } They must be provided as named arguments. See the "Specification" and "Value" sections for details on their usage. } \section{Specification}{ A column named \code{row_names} is treated like any other column. The \code{n} argument specifies the number of rows to be fetched. If omitted, fetching multi-row queries with one or more columns returns the entire result. A value of \link{Inf} for the \code{n} argument is supported and also returns the full result. If more rows than available are fetched (by passing a too large value for \code{n}), the result is returned in full without warning. If zero rows are requested, the columns of the data frame are still fully typed. Fetching fewer rows than available is permitted, no warning is issued. The \code{param} argument allows passing query parameters, see \code{\link[=dbBind]{dbBind()}} for details. } \section{Specification for the \code{immediate} argument}{ The \code{immediate} argument supports distinguishing between "direct" and "prepared" APIs offered by many database drivers. Passing \code{immediate = TRUE} leads to immediate execution of the query or statement, via the "direct" API (if supported by the driver). The default \code{NULL} means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct \code{immediate} argument. Examples for possible behaviors: \enumerate{ \item DBI backend defaults to \code{immediate = TRUE} internally \enumerate{ \item A query without parameters is passed: query is executed \item A query with parameters is passed: \enumerate{ \item \code{params} not given: rejected immediately by the database because of a syntax error in the query, the backend tries \code{immediate = FALSE} (and gives a message) \item \code{params} given: query is executed using \code{immediate = FALSE} } } \item DBI backend defaults to \code{immediate = FALSE} internally \enumerate{ \item A query without parameters is passed: \enumerate{ \item simple query: query is executed \item "special" query (such as setting a config options): fails, the backend tries \code{immediate = TRUE} (and gives a message) } \item A query with parameters is passed: \enumerate{ \item \code{params} not given: waiting for parameters via \code{\link[=dbBind]{dbBind()}} \item \code{params} given: query is executed } } } } \examples{ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbGetQuery(con, "SELECT * FROM mtcars") dbGetQuery(con, "SELECT * FROM mtcars", n = 6) # Pass values using the param argument: # (This query runs eight times, once for each different # parameter. The resulting rows are combined into a single # data frame.) dbGetQuery( con, "SELECT COUNT(*) FROM mtcars WHERE cyl = ?", params = list(1:8) ) dbDisconnect(con) } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/DBIDriver-class.Rd0000644000176200001440000000172214157672512014603 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/DBIDriver.R \docType{class} \name{DBIDriver-class} \alias{DBIDriver-class} \title{DBIDriver class} \description{ Base class for all DBMS drivers (e.g., RSQLite, MySQL, PostgreSQL). The virtual class \code{DBIDriver} defines the operations for creating connections and defining data type mappings. Actual driver classes, for instance \code{RPostgres}, \code{RMariaDB}, etc. implement these operations in a DBMS-specific manner. } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIConnector-class}}, \code{\link{DBIObject-class}}, \code{\link{DBIResult-class}} Other DBIDriver generics: \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} } \concept{DBI classes} \concept{DBIDriver generics} DBI/man/dbIsReadOnly.Rd0000644000176200001440000000421514157672512014245 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbIsReadOnly.R \name{dbIsReadOnly} \alias{dbIsReadOnly} \title{Is this DBMS object read only?} \usage{ dbIsReadOnly(dbObj, ...) } \arguments{ \item{dbObj}{An object inheriting from \linkS4class{DBIObject}, i.e. \linkS4class{DBIDriver}, \linkS4class{DBIConnection}, or a \linkS4class{DBIResult}} \item{...}{Other arguments to methods.} } \description{ This generic tests whether a database object is read only. } \examples{ dbIsReadOnly(ANSI()) } \seealso{ Other DBIDriver generics: \code{\link{DBIDriver-class}}, \code{\link{dbCanConnect}()}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbDriver}()}, \code{\link{dbGetInfo}()}, \code{\link{dbIsValid}()}, \code{\link{dbListConnections}()} Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()} Other DBIResult generics: \code{\link{DBIResult-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbColumnInfo}()}, \code{\link{dbFetch}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetRowCount}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbGetStatement}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()}, \code{\link{dbUnquoteIdentifier}()} Other DBIConnector generics: \code{\link{DBIConnector-class}}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbGetConnectArgs}()} } \concept{DBIConnection generics} \concept{DBIConnector generics} \concept{DBIDriver generics} \concept{DBIResult generics} DBI/DESCRIPTION0000644000176200001440000001152514160037606012365 0ustar liggesusersPackage: DBI Title: R Database Interface Version: 1.1.2 Date: 2021-12-19 Authors@R: c( person("R Special Interest Group on Databases (R-SIG-DB)", role = "aut"), person("Hadley", "Wickham", role = "aut"), person("Kirill", "Müller", , "krlmlr+r@mailbox.org", role = c("aut", "cre"), comment = c(ORCID = "0000-0002-1416-3412")), person("R Consortium", role = "fnd") ) Description: A database interface definition for communication between R and relational database management systems. All classes in this package are virtual and need to be extended by the various R/DBMS implementations. License: LGPL (>= 2.1) URL: https://dbi.r-dbi.org, https://github.com/r-dbi/DBI BugReports: https://github.com/r-dbi/DBI/issues Depends: methods, R (>= 3.0.0) Suggests: blob, covr, DBItest, dbplyr, downlit, dplyr, glue, hms, knitr, magrittr, RMariaDB, rmarkdown, rprojroot, RSQLite (>= 1.1-2), testthat, xml2 VignetteBuilder: knitr Config/autostyle/scope: line_breaks Config/autostyle/strict: false Config/Needs/check: r-dbi/DBItest Encoding: UTF-8 RoxygenNote: 7.1.2 Config/Needs/website: r-dbi/DBItest, AzureKusto, bigrquery, DatabaseConnector, dittodb, duckdb, implyr, lazysf, odbc, pool, RAthena, RClickhouse, RH2, RJDBC, RMariaDB, RMySQL, RPostgres, RPostgreSQL, RPresto, RSQLite, sergeant, sparklyr Collate: 'DBIObject.R' 'DBIDriver.R' 'Id.R' 'DBIConnection.R' 'ANSI.R' 'DBI-package.R' 'DBIConnector.R' 'DBIResult.R' 'SQL.R' 'SQLKeywords.R' 'SQLKeywords_DBIObject.R' 'SQLKeywords_missing.R' 'data-types.R' 'data.R' 'dbAppendTable.R' 'dbAppendTable_DBIConnection.R' 'dbBegin.R' 'dbBind.R' 'dbCallProc.R' 'dbCanConnect.R' 'dbCanConnect_DBIDriver.R' 'dbClearResult.R' 'dbColumnInfo.R' 'dbCommit.R' 'dbConnect.R' 'dbConnect_DBIConnector.R' 'dbCreateTable.R' 'dbCreateTable_DBIConnection.R' 'dbDataType.R' 'dbDataType_DBIConnector.R' 'dbDataType_DBIObject.R' 'dbDisconnect.R' 'dbDriver.R' 'dbDriver_character.R' 'dbExecute.R' 'dbExecute_DBIConnection_character.R' 'dbExistsTable.R' 'dbExistsTable_DBIConnection_Id.R' 'dbFetch.R' 'dbFetch_DBIResult.R' 'dbGetConnectArgs.R' 'dbGetConnectArgs_DBIConnector.R' 'dbGetException.R' 'dbGetInfo.R' 'dbGetInfo_DBIResult.R' 'dbGetQuery.R' 'dbGetQuery_DBIConnection_character.R' 'dbGetRowCount.R' 'dbGetRowsAffected.R' 'dbGetStatement.R' 'dbHasCompleted.R' 'dbIsReadOnly.R' 'dbIsReadOnly_DBIConnector.R' 'dbIsReadOnly_DBIObject.R' 'dbIsValid.R' 'dbListConnections.R' 'dbListFields.R' 'dbListFields_DBIConnection_Id.R' 'dbListFields_DBIConnection_character.R' 'dbListObjects.R' 'dbListObjects_DBIConnection_ANY.R' 'dbListResults.R' 'dbListTables.R' 'dbQuoteIdentifier.R' 'dbQuoteIdentifier_DBIConnection.R' 'dbQuoteLiteral.R' 'dbQuoteLiteral_DBIConnection.R' 'dbQuoteString.R' 'dbQuoteString_DBIConnection.R' 'dbReadTable.R' 'dbReadTable_DBIConnection_Id.R' 'dbReadTable_DBIConnection_character.R' 'dbRemoveTable.R' 'dbRemoveTable_DBIConnection_Id.R' 'dbRollback.R' 'dbSendQuery.R' 'dbSendStatement.R' 'dbSendStatement_DBIConnection_character.R' 'dbSetDataMappings.R' 'dbUnloadDriver.R' 'dbUnquoteIdentifier.R' 'dbUnquoteIdentifier_DBIConnection.R' 'dbWithTransaction.R' 'dbWithTransaction_DBIConnection.R' 'dbWriteTable.R' 'dbWriteTable_DBIConnection_Id_ANY.R' 'dbiDataType.R' 'dbiDataType_AsIs.R' 'dbiDataType_Date.R' 'dbiDataType_POSIXct.R' 'dbiDataType_character.R' 'dbiDataType_data.frame.R' 'dbiDataType_difftime.R' 'dbiDataType_integer.R' 'dbiDataType_list.R' 'dbiDataType_logical.R' 'dbiDataType_numeric.R' 'deprecated.R' 'fetch.R' 'hms.R' 'interpolate.R' 'isSQLKeyword.R' 'isSQLKeyword_DBIObject_character.R' 'make.db.names.R' 'make.db.names_DBIObject_character.R' 'methods_as_rd.R' 'rownames.R' 'show_AnsiConnection.R' 'show_DBIConnection.R' 'show_DBIConnector.R' 'show_DBIDriver.R' 'show_DBIResult.R' 'show_Id.R' 'show_SQL.R' 'sqlAppendTable.R' 'sqlAppendTableTemplate.R' 'sqlAppendTable_DBIConnection.R' 'sqlCreateTable.R' 'sqlCreateTable_DBIConnection.R' 'sqlData.R' 'sqlData_DBIConnection.R' 'sqlInterpolate.R' 'sqlInterpolate_DBIConnection.R' 'sqlParseVariables.R' 'sqlParseVariables_DBIConnection.R' 'summary.R' 'summary_DBIObject.R' 'transactions.R' NeedsCompilation: no Packaged: 2021-12-19 20:43:28 UTC; kirill Author: R Special Interest Group on Databases (R-SIG-DB) [aut], Hadley Wickham [aut], Kirill Müller [aut, cre] (), R Consortium [fnd] Maintainer: Kirill Müller Repository: CRAN Date/Publication: 2021-12-20 08:32:06 UTC DBI/build/0000755000176200001440000000000014157714560011761 5ustar liggesusersDBI/build/vignette.rds0000644000176200001440000000064514157714560014325 0ustar liggesusersS;O0vū0`h%~BTT,UM6"8PuoP.:aGfF |6xItQvw)@O*\Yix[ubIEC o#nK3a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doL>e̟O;$ueetvKshہy3 jKҜ> stream xڝ_0yQm[n eS#IF}b;7&'( O SAmo(?  `c:<38rB`AY 0NǂH|Rlgvvn1.¥B~m =8t<A IWjS`$'q-)Y2\ȶvEk%.P ƨVX3Α^SlY)^j\,¹ qzU/3!3Ez٭xL*]Zt&FQ.@Fy6mc{ tm;S3=BGJ_vesNj'넫A<8eڮM òUd2}ݪ ^aQRَ3nU/ S.ZwnWطDg۔o%wXsD<+ 9)__4wf$/Iv#J9K?~ǍR~H2Zneĺbζ[ң^ w=S>wHBR*]s̶ /h N endstream endobj 220 0 obj << /Length 532 /Filter /FlateDecode >> stream xڥr0<W21GB u'm&tt2ĭ\Kni)DRr߿+ 5w'`0 Dp a h߼=؃;$QP [K +rw~^-\sWGQ#W"'Y~y}y3({\\i[UH'm9%gK!Ad~9-LfDV='ͼ rq[ w^!7bJm2M)[qs*![w˾WT9׽g&q1^J%%[ %sXLx9V~=έѕH#cjn}EKv@ry:: ;7KjS@owXQ{%aasE W0qFa^3Gd;zk endstream endobj 228 0 obj << /Length 701 /Filter /FlateDecode >> stream xVR0+.@av >v<$*~!2}%'%t&sν8dz374"ok#7Aϱ83M?y~.t-ô#$A"j `2*+h읢vb9(( ԗ] 7"58I)HڰK *Z&ВIUP'g ALzW)YdNIC85'sz Ble\^\-L%\fryz$|kN M/2gd`k3W\OtDkNSlMlRG뉉/>Դ&?̊lK]oytj 7OaR}+(TͶDBD2vl^#_Vɼly/0p>3GejrTD/FiM;@OQ!\'?.$f`G9TTEH_X>1eOK(hwn3 o9ڱjۡKu uw;7##כ0uaG Џ7dCr.n OH~"\vqmaAֶ&l<[o^oJ)o}< Hf endstream endobj 283 0 obj << /Length 983 /Filter /FlateDecode >> stream xMo8:JEѴ.q݃b12JnKQY ŲR4̼LN'/.yD4wAJH<9IxFE|_7n TI.{vmղbIX6J?vӘM˔H9!Y.EXSg)yD1'/0t$ Z:w?2#a4voiPLq^ 9B=Buuu&$CA7fef殉,M%E$IXAeH~L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zN+(7/4C;7wS'/e슗*4;)t|0o4~f@]Z#a`;= UnL +PY7{7~*:=S տѪQI{U=bOt~1I"~6gg;{$? M'j endstream endobj 373 0 obj << /Length 2323 /Filter /FlateDecode >> stream xڥY[۶~_!2fDRSVlM✗(d9%rHYExDQ\ލx\X]<#$bz4#OFy߬UlV8N-\M> Ȉ\v׫ bL8^gmJbL{!D}E( bH1-M_3s]ԪjK&Z/k|ʋD)ş[z(96©EQBx$QWΪe1h \44&Q_nmLNLHD%H1C^5f )Ӻnܦ 77ߙN[+UU*]PQf[V6-60 B_X:ثn<'~e eP0%kԉ9TDv=X.)]PHkp vj&53cYզ<"1nn J)$ ĥ3yo*k)QLx m"\qmxHt?F&Ig[jDڋ4 x|NX&ak>B#a-z3'bڱ?5e) S1C?o۝nZk]%y(qZ٭ڧ%DtT'Dس_8e/S^ؾG 1 1"㮓%I„d6e*Eתƭm JcuǶ\KۣJ l&H[c8/ ĄuabfpeXZ6{铘cȰDEp7i [c Me#P]/P@nPZw:$mKOm'RSt՜תIVO7G덁 wĦ j5doY_}rG5[l,\B\&I!8y!6>{4\Ix1p."q`lo(l+)J;PCYuzZ阺*3Uף6dSUu.PީCyo[/Mͻm`! o6 a[!-0y䜓 O ?<}(o@$qSt[h7I+zJO .f~pй6 mӬn@h$;(Ϲ^2'"s(!5v! '#??Xy|_Cx@G |1` MBpxT;T2bՇO.'RKA8!dHDZ-r 9'ow endstream endobj 213 0 obj << /Type /ObjStm /N 100 /First 906 /Length 2474 /Filter /FlateDecode >> stream xZn}l.*HGv4 Jhc+jekxĞv.fQ.8 E%8wumr+4 Zv){TqM1 Bߊ{DXpГ߈E҄ v].&>bptQ"@W̎C:(z! >rf/]}B^b˜3c/l|/që%W/fq~jWجxM˫r=.㭿,Oώ_~t0"яnxNciF{irgSܙCgEΪ~ŬTAYeCФL4I ujL6%3=CKh>C".<51̐dSDSJM*3$#"7+:֊v$SEab)t# *3DfT$ <uT0 Al$E;'Y/9|~TKO/gֲ:e._w2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au!m }j}|Al P/ha5.ѶϤDPvTC i_` m3,8aqAl.\`0-ư"A8zj. c Z^zq3 G_.]q3 Gh@y<QNkD;֍[M+ub}΅8#W6W|z+_I⛺6"~{G%pB *܅pķn um ]zA%Βb_I b$ Ă0)1uK`R… A /^ǺW /8nY| Vr!oU| >2+^.DkCCkC</a/^a/B Qv󠪙 endstream endobj 2939 0 obj << /Type /ObjStm /N 100 /First 1014 /Length 1881 /Filter /FlateDecode >> stream xڽM]7 +l7 C m-ttPJ! !]ͦ /Iϑe|©W(d9dAt'$׹ ; ˨8UaS&G xaBHb"5bS)璋粋sŖ2 GT'-b+\ƈ]*QV\A,AyXޥ`X.srM>M+ȗ* 5WjV+\ pgqQyx\1[>_]J tMSTRDؙ$ . ANtiBrBtiBR!4]Z9H 1ӥKetiBR!4]ZCؘHRi}Lt/'BEhd#Pܯ&B+>HgDY3r%dQ ;O "@Ȕo`ؚ)/oȭ2"?' !UV& C!$J ҃h7ïJ)Si؀8 ij"R A QKRʄhB,)eBR BhZSJ iZ *L_J-R&D\z4!tقK_M*+]*H6B<.aK"H 1ӥ Q ҄z̘KKsmROPq;DgM9k0My 浣 Sbk/_!f/füv!k1mqAkBd75.@J qy %賸D,v'|-`LN[M \-ṭZMx+qmB"nA bylm c3m[ cB_0q$UR%= M웚 S"o.95!gtA֩ N읚;?`06C>P\kwzk ]AKɐgU,_Pi ZL~pMY,FhݚZLxU7ff:ua6l?T/bi|85Beg543d!ΐ"hcd-5;T( b [bA endstream endobj 2940 0 obj << /Type /ObjStm /N 100 /First 1014 /Length 1969 /Filter /FlateDecode >> stream xڽKd7+7JKh ffe{x1C1=sB%){R.tqn(t*Z )H/Z7 ).(_pYBBi{,P`H.3 R>Qj> q֒_X pTј|xs&G-}#| T} 7g /jĪ )(sR"ՠDգI *ũ# &4j)M4h# ԩ$C r(5j4+ɣ)梪[0w~B6=jSy4ǘά9dC fr)}rK>Px4P/PXkJe) bXPSi|g:PŜRPs,@#[hɧ;z\Pt==f=kx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ûwM}O𗟿Ao!䨈(PB7Bp9 d?!R< `Ȑ(a`ZCԍw&CBx#ɑ4a QpZݔ% BALDQp":Z[AÓzR^!F#\!p9 z\BFK0"Q%8OqLf3f#^"O%3T J kE:njx!DvwhzG-AqgBDm8ԸdU(5!q ;C6;w5K'0bLBFWfZZB( JCZ3,Qʛΐ ZԵ&;dzASY$ ]yATtQN꣢#+qgTtaTt+{VtbTtK9!gun@nx@5!x@x Q{᠜!aagu=CL\B1??y 7h+=φLT;>_!CQ DdL S.k`,RơV[-ar(!jT(1)˄*3YUj>̀'$iNByB$BZ'㡐 ^ 'XTI(m0,!U^H9!0WUpQ R sb3]6mxԥh<]?hO T у ل0lϧWik@"^#%㨨y| Ilm }2AO>H_Bd?H}'% bg. =Q[BlA݄胺%Va|r4 \xh=^/W t»CK{;z:>&Ln7a@wo5 endstream endobj 3141 0 obj << /Length 118 /Filter /FlateDecode >> stream x3135R0PT01V02U0PH1*24 ()Lr.'~8PKLz*r;8+r(D*ry(T0 ?`AՓ+ ,L endstream endobj 3149 0 obj << /Length1 2911 /Length2 20917 /Length3 0 /Length 22376 /Filter /FlateDecode >> stream xڜwT\۶%,{.;p 'Cp !tnr_ݣcg|ϵ94j,N '; ] p99rh=\5 72 B:֗tC$Rf3-@y8x @+: m-l@M3Wg2GĐb 0s(}aI%z\f.YPSN=xoeց9qfjI~ % 04#b+w t2 ICyifpVWäd;pZ~ߑ~^#  BPQl 9u-C'sd ~NܷswIMdyM||jz\&fRu8%.j韨y3'uUo4 w&(==4r}/҆d8xEa/?9"u+_,p7/"Nx0XBFjЧR-&Do8q\a2\!Ȏp2>xˤ (yxD_81x\-v&pp.bH[oYQM vo8oC d *[]jс &|!v )9Vt>;c<ѯ,8+oě22d{38.ܱ'&PAd=p3bӶ!:, B3:f ).^e%aXa4e4Oݦ"4y[ӦY+r:F7ZjrܹIX϶@ၗ6_cetƁ+$8`m7Bv57_@XMqXqW 2Lhą U(FTkȸ4mF״GW [Y;=\HHtDSՂkC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ЧQ%~Zx pX2]$^qnaK??q FqMyc0=) &l(mi,3|d &\c ]͹&ӈ9w{d-tx\ \cΜekqLJs?<@>qhx .׷8wl~1V<*m"mmDa endstream endobj 3165 0 obj << /Length 664 /Filter /FlateDecode >> stream xmTMo0WxvB+8l[jWHL7RI;onDo3ތ?n~<&Y$ŝK_IsE77E[^N\5sߖ;7|[lzmS_*7F?h3΃;mc-bB`ew\_7oK׽;(2Z.ETz}ܟ~o9V^MVK7-\f\S}[S!pcSs|TXo1/ȡ aeuC> stream xmTMo0WxvB+8l[+ML7RI;onDo3ތ?n~<&YվI|/ŋ;t硋nn\3<:Wj\=?-wn6pGۦ|Tnʽgxté7~qzxKlqrnX7UޞMjuSAxHiQ,'wͱ 1}hW7q{UEݥ-rG*F>NNL7u]tNhWS;wE )b,#TTHy=)9>*QKr7P:MȡQ^s$LD6aȑ*s.$S56`>ƄmÁ#TL 5kd}WXssc*zRh/#? bE$L|ږ8^y>eSQc̯bV̯cNa'_OAJ195kd3EH@8ܰ%~As*=F 0`{RLPh33Y$LƹǬ oqMsȼ tx\ \cΜ-eksL ?"@>qhx ׷=l~1֍>*]!MBa endstream endobj 3167 0 obj << /Length 665 /Filter /FlateDecode >> stream xmTn0C6U@"mTt@;olvR3ތm~<&YվI|+œ;t羋<]3;Wj|{}[ mmᆂMv{Kt=c_~B?zxoBS6wBJ)X7UaMuSxHiQV,4$O;nC-bD/OCnC_n^ѻs׽9X2Z.ET~{~ʶrn_~߼h!R,6ew*ؔb%k e+Kӄ$a"1x*s.$S56P>Ƅm„A Fs 5577vرϾ+uaя6R:!,əCxg+ѧy*JcL|*m:fvuiWUꧏɩ\g%<Ϛ"sÖ0_:3x0kjhyIYx0aCnOg3$cx0<<v5O#ܵu7A 6*sZ ZcΜ-ܠeYksL ?"@>qh|tngk;dGGM@c endstream endobj 3168 0 obj << /Length 665 /Filter /FlateDecode >> stream xmTn0C6U@"mTt@;olvR3ތm~<&YվI|+œ;t羋<]3;Wj|{}[ mmᆂMv{Kt=cߚ~B?zxoBS6wBJ)X7UaMuSxHiQV,4$O;nC-bD/OCnC_n^ѻs׽9X2Z.ET~{~ʶrn_~߼h!R,6ew*ؔb%k e+Kӄ$a"1x*s.$S56P>Ƅm„A Fs 5577vرϾ+uaя6R:!,əCxg+ѧy*JcL|*m:fvuiWUꧏɩ\g%<Ϛ"sÖ0_:3x0kjhyIYx0aCnOg3$cx0<<v5O#ܵu7A 6*sZ ZcΜ-ܠeYksL ?"@>qh|tngk;dGGMc endstream endobj 3169 0 obj << /Length 799 /Filter /FlateDecode >> stream xuUn@+HɁkc{!5&Q^ үル!zya/W7/~jyld}{9}N=C'u\W;oέO*k`~?''3Ɖt3\;WS]Q?SVk ]{9FSѤoG^ 32j$WC0h޼O~wC4Sy<&>U]Rn·ÛB~,{_=ڰfhm_}4zu|sH]Wb MLD!E!B FAC\dQQ(%T<#h^QqKƊL0cF F͌a._Q mPG9'+X38)+ι7\'~5:r%%Β뤧$1$܋a %aN*Atg&W̡`92/X[B|fAlI)dKdgI$[d$[H$[hv-|9~ddK%[w-t--d ~)BO)Rd dK|ɖNK)K)++Ζ]Rd]Oz͜|x8?<ᤥNO]?p@}_:h? endstream endobj 3170 0 obj << /Length 550 /Filter /FlateDecode >> stream xmSˎ0+$1$#8h@Bܰp`~ +8*=SJ]sCM&ESݮ`w z\ħmbo'ޚr028~}uHXz_z.XA_`1o"xR:bct\$7҈٘TmH@ ]W0ywznͩV+1r]oś}X 6g1ͭnm{!^ ' bނP48YhC`୤\UY=0ZĎiơ 7([4r;"A"e"qDgs"2dK$#В%#KDDNs5&]J[/G endstream endobj 3133 0 obj << /Type /ObjStm /N 100 /First 964 /Length 3327 /Filter /FlateDecode >> stream x[ko7_1(<I (SNyB'6Ѧ{.9QOK6 hH%%K^*$t)԰ВS(4xUXo /<5D% }AK4J7M#r4-}y*MABhRB:(d!4XC(UDEBXGT8aeipLnBzSR|t*W*X Ӑo! –HJi jJ(QEqU")1=" @D*+ ᐆ]%eKP*C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,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(ŢR,J(Ţr!~j5"CkXְajâaM\bȆ7 ɍuh *k℆Padc6f* j;AaoCo^PPOذq75 n94xhX~а a=Dʈ5 %M4y$q[òȆ8`Y_:(FnXذĵq]Դa}c"ղm<'`qVúކ} j A6,lXNذ$ah=|`mdÂچZW~^sy3̛Պ79or]q[ztΛ7CΛ:fXyfDˮ#MlyW&6Ê4WB4CxFv5ݰK .qӵjM׹y'#aDN^4_zM =& G_}?O/: o-]h_J KaTeh>< KkywNp> ˤۼ |XȆaŵ ͇.ݼ224/C24҆Ÿ24Iu24/C24׆Ea Po'H='H=נ'H=A ROz 'H=A ROz g %\VignetteIndexEntry{A Common Database Interface (DBI)} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- This document describes a common interface between the S language (in its R and S-Plus implementations) and database management systems (DBMS). The interface defines a small set of classes and methods similar in spirit to Perl’s DBI, Java’s JDBC, Python’s DB-API, and Microsoft’s ODBC. # Version {#sec:version} This document describes version 0.1-6 of the database interface API (application programming interface). # Introduction {#sec:intro} The database interface (DBI) separates the connectivity to the DBMS into a “front-end” and a “back-end”. Applications use only the exposed “front-end” API. The facilities that communicate with specific DBMS (Oracle, PostgreSQL, etc.) are provided by “device drivers” that get invoked automatically by the S language evaluator. The following example illustrates some of the DBI capabilities: ```R ## Choose the proper DBMS driver and connect to the server drv <- dbDriver("ODBC") con <- dbConnect(drv, "dsn", "usr", "pwd") ## The interface can work at a higher level importing tables ## as data.frames and exporting data.frames as DBMS tables. dbListTables(con) dbListFields(con, "quakes") if(dbExistsTable(con, "new_results")) dbRemoveTable(con, "new_results") dbWriteTable(con, "new_results", new.output) ## The interface allows lower-level interface to the DBMS res <- dbSendQuery(con, paste( "SELECT g.id, g.mirror, g.diam, e.voltage", "FROM geom_table as g, elec_measures as e", "WHERE g.id = e.id and g.mirrortype = 'inside'", "ORDER BY g.diam")) out <- NULL while(!dbHasCompleted(res)){ chunk <- fetch(res, n = 10000) out <- c(out, doit(chunk)) } ## Free up resources dbClearResult(res) dbDisconnect(con) dbUnloadDriver(drv) ``` (only the first 2 expressions are DBMS-specific – all others are independent of the database engine itself). Individual DBI drivers need not implement all the features we list below (we indicate those that are optional). Furthermore, drivers may extend the core DBI facilities, but we suggest to have these extensions clearly indicated and documented. The following are the elements of the DBI: 1. A set of classes and methods (Section [sec:DBIClasses]) that defines what operations are possible and how they are defined, e.g.: - connect/disconnect to the DBMS - create and execute statements in the DBMS - extract results/output from statements - error/exception handling - information (meta-data) from database objects - transaction management (optional) Some things are left explicitly unspecified, e.g., authentication and even the query language, although it is hard to avoid references to SQL and relational database management systems (RDBMS). 2. Drivers Drivers are collection of functions that implement the functionality defined above in the context of specific DBMS, e.g., mSQL, Informix. 3. Data type mappings (Section [sec:data-mappings].) Mappings and conversions between DBMS data types and R/S objects. All drivers should implement the “basic” primitives (see below), but may chose to add user-defined conversion function to handle more generic objects (e.g., factors, ordered factors, time series, arrays, images). 4. Utilities (Section [sec:utilities].) These facilities help with details such as mapping of identifiers between S and DBMS (e.g., `_` is illegal in R/S names, and `.` is used for constructing compound SQL identifiers), etc. # DBI Classes and Methods {#sec:DBIClasses} The following are the main DBI classes. They need to be extended by individual database back-ends (Sybase, Oracle, etc.) Individual drivers need to provide methods for the generic functions listed here (those methods that are optional are so indicated). *Note: Although R releases prior to 1.4 do not have a formal concept of classes, we will use the syntax of the S Version 4 classes and methods (available in R releases 1.4 and later as library `methods`) to convey precisely the DBI class hierarchy, its methods, and intended behavior.* The DBI classes are `DBIObject`, `DBIDriver`, `DBIConnection` and `DBIResult`. All these are *virtual* classes. Drivers define new classes that extend these, e.g., `PgSQLDriver`, `PgSQLConnection`, and so on. ![Class hierarchy for the DBI. The top two layers are comprised of virtual classes and each lower layer represents a set of driver-specific implementation classes that provide the functionality defined by the virtual classes above.](hierarchy.png) `DBIObject`: : Virtual class[^1] that groups all other DBI classes. `DBIDriver`: : Virtual class that groups all DBMS drivers. Each DBMS driver extends this class. Typically generator functions instantiate the actual driver objects, e.g., `PgSQL`, `HDF5`, `BerkeleyDB`. `DBIConnection`: : Virtual class that encapsulates connections to DBMS. `DBIResult`: : Virtual class that describes the result of a DBMS query or statement. [Q: Should we distinguish between a simple result of DBMS statements e.g., as `delete` from DBMS queries (i.e., those that generate data).] The methods `format`, `print`, `show`, `dbGetInfo`, and `summary` are defined (and *implemented* in the `DBI` package) for the `DBIObject` base class, thus available to all implementations; individual drivers, however, are free to override them as they see fit. `format(x, ...)`: : produces a concise character representation (label) for the `DBIObject` `x`. `print(x, ...)`/`show(x)`: : prints a one-line identification of the object `x`. `summary(object, ...)`: : produces a concise description of the object. The default method for `DBIObject` simply invokes `dbGetInfo(dbObj)` and prints the name-value pairs one per line. Individual implementations may tailor this appropriately. `dbGetInfo(dbObj, ...)`: : extracts information (meta-data) relevant for the `DBIObject` `dbObj`. It may return a list of key/value pairs, individual meta-data if supplied in the call, or `NULL` if the requested meta-data is not available. *Hint:* Driver implementations may choose to allow an argument `what` to specify individual meta-data, e.g., `dbGetInfo(drv, what = max.connections)`. In the next few sub-sections we describe in detail each of these classes and their methods. ## Class `DBIObject` {#sec:DBIObject} This class simply groups all DBI classes, and thus all extend it. ## Class `DBIDriver` {#sec:DBIDriver} This class identifies the database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.) The DBI provides the generator `dbDriver(driverName)` which simply invokes the function `driverName`, which in turn instantiates the corresponding driver object. The `DBIDriver` class defines the following methods: `driverName`: : [meth:driverName] initializes the driver code. The name `driverName` refers to the actual generator function for the DBMS, e.g., `RPgSQL`, `RODBC`, `HDF5`. The driver instance object is used with `dbConnect` (see page ) for opening one or possibly more connections to one or more DBMS. `dbListConnections(drv, ...)`: : list of current connections being handled by the `drv` driver. May be `NULL` if there are no open connections. Drivers that do not support multiple connections may return the one open connection. `dbGetInfo(dbObj, ...)`: : returns a list of name-value pairs of information about the driver. *Hint:* Useful entries could include `name`: : the driver name (e.g., `RODBC`, `RPgSQL`); `driver.version`: : version of the driver; `DBI.version`: : the version of the DBI that the driver implements, e.g., `0.1-2`; `client.version`: : of the client DBMS libraries (e.g., version of the `libpq` library in the case of `RPgSQL`); `max.connections`: : maximum number of simultaneous connections; plus any other relevant information about the implementation, for instance, how the driver handles upper/lower case in identifiers. `dbUnloadDriver(driverName)` (optional): : frees all resources (local and remote) used by the driver. Returns a logical to indicate if it succeeded or not. ## Class `DBIConnection` {#sec:DBIConnection} This virtual class encapsulates the connection to a DBMS, and it provides access to dynamic queries, result sets, DBMS session management (transactions), etc. *Note:* Individual drivers are free to implement single or multiple simultaneous connections. The methods defined by the `DBIConnection` class include: `dbConnect(drv, ...)`: : [meth:dbConnect] creates and opens a connection to the database implemented by the driver `drv` (see Section [sec:DBIDriver]). Each driver will define what other arguments are required, e.g., `dbname` or `dsn` for the database name, `user`, and `password`. It returns an object that extends `DBIConnection` in a driver-specific manner (e.g., the MySQL implementation could create an object of class `MySQLConnection` that extends `DBIConnection`). `dbDisconnect(conn, ...)`: : closes the connection, discards all pending work, and frees resources (e.g., memory, sockets). Returns a logical indicating whether it succeeded or not. `dbSendQuery(conn, statement, ...)`: : submits one statement to the DBMS. It returns a `DBIResult` object. This object is needed for fetching data in case the statement generates output (see `fetch` on page ), and it may be used for querying the state of the operation; see `dbGetInfo` and other meta-data methods on page . `dbGetQuery(conn, statement, ...)`: : submit, execute, and extract output in one operation. The resulting object may be a `data.frame` if the `statement` generates output. Otherwise the return value should be a logical indicating whether the query succeeded or not. `dbGetException(conn, ...)`: : returns a list with elements `errNum` and `errMsg` with the status of the last DBMS statement sent on a given connection (this information may also be provided by the `dbGetInfo` meta-data function on the `conn` object. *Hint:* The ANSI SQL-92 defines both a status code and an status message that could be return as members of the list. `dbGetInfo(dbObj, ...)`: : returns a list of name-value pairs describing the state of the connection; it may return one or more meta-data, the actual driver method allows to specify individual pieces of meta-data (e.g., maximum number of open results/cursors). *Hint:* Useful entries could include `dbname`: : the name of the database in use; `db.version`: : the DBMS server version (e.g., “Oracle 8.1.7 on Solaris”; `host`: : host where the database server resides; `user`: : user name; `password`: : password (is this safe?); plus any other arguments related to the connection (e.g., thread id, socket or TCP connection type). `dbListResults(conn, ...)`: : list of `DBIResult` objects currently active on the connection `conn`. May be `NULL` if no result set is active on `conn`. Drivers that implement only one result set per connection could return that one object (no need to wrap it in a list). *Note: The following are convenience methods that simplify the import/export of (mainly) data.frames. The first five methods implement the core methods needed to `attach` remote DBMS to the S search path. (For details, see @data-management:1991 [@database-classes:1999].)* *Hint:* For relational DBMS these methods may be easily implemented using the core DBI methods `dbConnect`, `dbSendQuery`, and `fetch`, due to SQL reflectance (i.e., one easily gets this meta-data by querying the appropriate tables on the RDBMS). `dbListTables(conn, ...)`: : returns a character vector (possibly of zero-length) of object (table) names available on the `conn` connection. `dbReadTable(conn, name, ...)`: : imports the data stored remotely in the table `name` on connection `conn`. Use the field `row.names` as the `row.names` attribute of the output data.frame. Returns a `data.frame`. [Q: should we spell out how row.names should be created? E.g., use a field (with unique values) as row.names? Also, should `dbReadTable` reproduce a data.frame exported with `dbWriteTable`?] `dbWriteTable(conn, name, value, ...)`: : write the object `value` (perhaps after coercing it to data.frame) into the remote object `name` in connection `conn`. Returns a logical indicating whether the operation succeeded or not. `dbExistsTable(conn, name, ...)`: : does remote object `name` exist on `conn`? Returns a logical. `dbRemoveTable(conn, name, ...)`: : removes remote object `name` on connection `conn`. Returns a logical indicating whether the operation succeeded or not. `dbListFields(conn, name, ...)`: : returns a character vector listing the field names of the remote table `name` on connection `conn` (see `dbColumnInfo()` for extracting data type on a table). *Note: The following methods deal with transactions and stored procedures. All these functions are optional.* `dbCommit(conn, ...)`(optional): : commits pending transaction on the connection and returns `TRUE` or `FALSE` depending on whether the operation succeeded or not. `dbRollback(conn, ...)`(optional): : undoes current transaction on the connection and returns `TRUE` or `FALSE` depending on whether the operation succeeded or not. `dbCallProc(conn, storedProc, ...)`(optional): : invokes a stored procedure in the DBMS and returns a `DBIResult` object. [Stored procedures are *not* part of the ANSI SQL-92 standard and vary substantially from one RDBMS to another.] **Deprecated since 2014:** The recommended way of calling a stored procedure is now - `dbGetQuery` if a result set is returned and - `dbExecute` for data manipulation and other cases that do not return a result set. ## Class `DBIResult` {#sec:DBIResult} This virtual class describes the result and state of execution of a DBMS statement (any statement, query or non-query). The result set `res` keeps track of whether the statement produces output for R/S, how many rows were affected by the operation, how many rows have been fetched (if statement is a query), whether there are more rows to fetch, etc. *Note: Individual drivers are free to allow single or multiple active results per connection.* [Q: Should we distinguish between results that return no data from those that return data?] The class `DBIResult` defines the following methods: `fetch(res, n, ...)`: : [meth:fetch] fetches the next `n` elements (rows) from the result set `res` and return them as a data.frame. A value of `n=-1` is interpreted as “return all elements/rows”. `dbClearResult(res, ...)`: : flushes any pending data and frees all resources (local and remote) used by the object `res` on both sides of the connection. Returns a logical indicating success or not. `dbGetInfo(dbObj, ...)`: : returns a name-value list with the state of the result set. *Hint:* Useful entries could include `statement`: : a character string representation of the statement being executed; `rows.affected`: : number of affected records (changed, deleted, inserted, or extracted); `row.count`: : number of rows fetched so far; `has.completed`: : has the statement (query) finished? `is.select`: : a logical describing whether or not the statement generates output; plus any other relevant driver-specific meta-data. `dbColumnInfo(res, ...)`: : produces a data.frame that describes the output of a query. The data.frame should have as many rows as there are output fields in the result set, and each column in the data.frame should describe an aspect of the result set field (field name, type, etc.) *Hint:* The data.frame columns could include `field.name`: : DBMS field label; `field.type`: : DBMS field type (implementation-specific); `data.type`: : corresponding R/S data type, e.g., `integer`; `precision`/`scale`: : (as in ODBC terminology), display width and number of decimal digits, respectively; `nullable`: : whether the corresponding field may contain (DBMS) `NULL` values; plus other driver-specific information. `dbSetDataMappings(flds, ...)`(optional): : defines a conversion between internal DBMS data types and R/S classes. We expect the default mappings (see Section [sec:data-mappings]) to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. [This topic needs further discussion.] *Note: The following are convenience methods that extract information from the result object (they may be implemented by invoking `dbGetInfo` with appropriate arguments).* `dbGetStatement(res, ...)`(optional): : returns the DBMS statement (as a character string) associated with the result `res`. `dbGetRowsAffected(res, ...)`(optional): : returns the number of rows affected by the executed statement (number of records deleted, modified, extracted, etc.) `dbHasCompleted(res, ...)`(optional): : returns a logical that indicates whether the operation has been completed (e.g., are there more records to be fetched?). `dbGetRowCount(res, ...)`(optional): : returns the number of rows fetched so far. # Data Type Mappings {#sec:data-mappings} The data types supported by databases are different than the data types in R and S, but the mapping between the “primitive” types is straightforward: Any of the many fixed and varying length character types are mapped to R/S `character`. Fixed-precision (non-IEEE) numbers are mapped into either doubles (`numeric`) or long (`integer`). Notice that many DBMS do not follow the so-called IEEE arithmetic, so there are potential problems with under/overflows and loss of precision, but given the R/S primitive types we cannot do too much but identify these situations and warn the application (how?). By default dates and date-time objects are mapped to character using the appropriate `TO_CHAR` function in the DBMS (which should take care of any locale information). Some RDBMS support the type `CURRENCY` or `MONEY` which should be mapped to `numeric` (again with potential round off errors). Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion (as has been done in other inter-systems packages [^2]). Specifying user-defined conversion functions still needs to be defined. # Utilities {#sec:utilities} The core DBI implementation should make available to all drivers some common basic utilities. For instance: `dbGetDBIVersion`: : returns the version of the currently attached DBI as a string. `dbDataType(dbObj, obj, ...)`: : returns a string with the (approximately) appropriate data type for the R/S object `obj`. The DBI can implement this following the ANSI-92 standard, but individual drivers may want/need to extend it to make use of DBMS-specific types. `make.db.names(dbObj, snames, ...)`: : maps R/S names (identifiers) to SQL identifiers replacing illegal characters (as `.`) by the legal SQL `_`. `SQLKeywords(dbObj, ...)`: : returns a character vector of SQL keywords (reserved words). The default method returns the list of `.SQL92Keywords`, but drivers should update this vector with the DBMS-specific additional reserved words. `isSQLKeyword(dbObj, name, ...)`: : for each element in the character vector `name` determine whether or not it is an SQL keyword, as reported by the generic function `SQLKeywords`. Returns a logical vector parallel to the input object `name`. # Open Issues and Limitations {#sec:open-issues} There are a number of issues and limitations that the current DBI conscientiously does not address on the interest of simplicity. We do list here the most important ones. Non-SQL: : Is it realistic to attempt to encompass non-relational databases, like HDF5, Berkeley DB, etc.? Security: : allowing users to specify their passwords on R/S scripts may be unacceptable for some applications. We need to consider alternatives where users could store authentication on files (perhaps similar to ODBC’s `odbc.ini`) with more stringent permissions. Exceptions: : the exception mechanism is a bit too simple, and it does not provide for information when problems stem from the DBMS interface itself. For instance, under/overflow or loss of precision as we move numeric data from DBMS to the more limited primitives in R/S. Asynchronous communication: : most DBMS support both synchronous and asynchronous communications, allowing applications to submit a query and proceed while the database server process the query. The application is then notified (or it may need to poll the server) when the query has completed. For large computations, this could be very useful, but the DBI would need to specify how to interrupt the server (if necessary) plus other details. Also, some DBMS require applications to use threads to implement asynchronous communication, something that neither R nor S-Plus currently addresses. SQL scripts: : the DBI only defines how to execute one SQL statement at a time, forcing users to split SQL scripts into individual statements. We need a mechanism by which users can submit SQL scripts that could possibly generate multiple result sets; in this case we may need to introduce new methods to loop over multiple results (similar to Python’s `nextResultSet`). BLOBS/CLOBS: : large objects (both character and binary) present some challenges both to R and S-Plus. It is becoming more common to store images, sounds, and other data types as binary objects in DBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects. Transactions: : transaction management is not fully described. Additional methods: : Do we need any additional methods? (e.g., `dbListDatabases(conn)`, `dbListTableIndices(conn, name)`, how do we list all available drivers?) Bind variables: : the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of R/S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement /* SQL */ SELECT * from emp_table where emp_id = :sampleEmployee would take the vector `sampleEmployee` and iterate over each of its elements to get the result. Perhaps the DBI could at some point in the future implement this feature. # Resources {#sec:resources} The idea of a common interface to databases has been successfully implemented in various environments, for instance: Java’s Database Connectivity (JDBC) ([www.javasoft.com](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/)). In C through the Open Database Connectivity (ODBC) ([www.unixodbc.org](http://www.unixodbc.org/)). Python’s Database Application Programming Interface ([www.python.org](https://wiki.python.org/moin/DatabaseProgramming)). Perl’s Database Interface ([dbi.perl.org](https://dbi.perl.org)). [^1]: A virtual class allows us to group classes that share some common characteristics, even if their implementations are radically different. [^2]: Duncan Temple Lang has volunteered to port the data conversion code found in R-Java, R-Perl, and R-Python packages to the DBI DBI/vignettes/hierarchy.png0000644000176200001440000022345514064774575015402 0ustar liggesusersPNG  IHDRJPwFiCCPICC Profile(c``RH,(a``+) rwRR` \\À|/­+JI-N8;1doyId$e @"- v:}¾V dl&]| SR@0$AIjE v/,L(QpTg^)(!?ÓQ B bs$20A20,a`S3d`g`7' j #1!>CI pHYsgR@IDATx |չHH&  hPTIe K [B@?JQ[*P-޲IPH,H s dO&3gY|uf9K<@@@@@<4@ذaǻt `\,/@@D% 7nL6M#8T':^*C@Hzڏ uԑiԨH` 8u D@(Sfgp     $Jݼi    -@l#@@@@@7 QL@@@@@leq    R7`    e (-ۈ3@@@@@Hy<@@@@([DiF    n.@;!    @$J6 @@@@psn4@@@@ QZg     (uy     PҲ8@@@@\Dw0C@@@@Hm     $Jݼi    -@l#@@@@@7 QL@@@@@leq    R7`    e (-ۈ3@@@@@Hy<@@@@([DiF    n.y 6liӦN>}z"    QhqCX~R[xڵR_E@k\__t[Q>G@-GI) M믿[Y&+)IrѶnZZ֯RCO~;i>VsbDZU @@L,@ĝG  sr%=zWn4[lH{*;O~-HlZb™#ẻҩ;^fj#~ [I{9)4E@՛,}#`9nqv\N$%Jbbw 40   ++  PQ$[=[̅$wy!""=.nڟ]f7LSx %ݝrIrL_P-G$*($2%}dOjM,JçΖ-}1Yp XBs˜n 3[S},~5RXğ8+\>(CW4ms5ںrĆ @1Z<ت3IOmeOl=%@,**Y\3om|^T<mX}@d>v}uMD 욾 5Jݻm*a݆^ =KOd\4ٿȽIKWHU[1)*[k>[#z^-[lۏr2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V< @U숀;k= 0vZuNҁRd     (CvzIENDB`DBI/vignettes/DBI-advanced.Rmd0000644000176200001440000002640514155273064015503 0ustar liggesusers--- title: "Advanced DBI Usage" author: "James Wondrasek, Kirill Müller" date: "17/03/2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"Advanced DBI Usage"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) knit_print.data.frame <- function(x, ...) { print(head(x, 3)) if (nrow(x) > 3) { cat("Showing 3 out of", nrow(x), "rows.\n") } invisible(x) } registerS3method("knit_print", "data.frame", "knit_print.data.frame") ``` ## Who this tutorial is for This tutorial is for you if you need to use a richer set of SQL features such as data manipulation queries, parameterized queries and queries performed using SQL's transaction features. See `vignette("DBI", package = "DBI")` for a more basic tutorial covering connecting to DBMS and executing simple queries. ## How to run more complex queries using DBI `dbGetQuery()` works by calling a number of functions behind the scenes. If you need more control you can manually build your own query, retrieve results at your selected rate, and release the resources involved by calling the same functions. These functions are: - `dbSendQuery()` sends the SQL query to the DBMS and returns a `result` object. The query is limited to `SELECT` statements. If you want to send other statements, such as `INSERT`, `UPDATE`, `DELETE`, etc, use `dbSendStatement()`. - `dbFetch()` is called with the `result` object returned by `dbSendQuery()`. It also accepts an argument specifying the number of rows to be returned, e.g. `n = 200`. If you want to fetch all the rows, use `n = -1`. - `dbClearResult()` is called when you have finished retrieving data. It releases the resources associated with the `result` object. ```{r} library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = 'G'") df <- dbFetch(res, n = 3) dbClearResult(res) head(df, 3) ``` ## How to read part of a table from a database If your dataset is large you may want to fetch a limited number of rows at a time. As demonstrated below, this can be accomplished by using a while loop where the function `dbHasCompleted()` is used to check for ongoing rows, and `dbFetch()` is used with the `n = X` argument, specifying how many rows to return on each iteration. Again, we call `dbClearResult()` at the end to release resources. ```{r} res <- dbSendQuery(con, "SELECT * FROM film") while (!dbHasCompleted(res)) { chunk <- dbFetch(res, n = 300) print(nrow(chunk)) } dbClearResult(res) ``` ## How to use parameters (safely) in SQL queries `dbSendQuery()` can be used with parameterized SQL queries. DBI supports two ways to avoid SQL injection attacks from user-supplied parameters: quoting and parameterized queries. ### Quoting Quoting of parameter values is performed using the function `dbQuoteLiteral()`, which supports many R data types, including date and time.[^quote-string] [^quote-string]: An older method, `dbQuoteString()`, was used to quote string values only. The `dbQuoteLiteral()` method forwards to `dbQuoteString()` for character vectors. Users do not need to distinguish between these two cases. In cases where users may be supplying table or column names to use in the query for data retrieval, those names or identifiers must also be escaped. As there may be DBMS-specific rules for escaping these identifiers, DBI provides the function `dbQuoteIdentifier()` to generate a safe string representation. ```{r quote} safe_id <- dbQuoteIdentifier(con, "rating") safe_param <- dbQuoteLiteral(con, "G") query <- paste0("SELECT title, ", safe_id, " FROM film WHERE ", safe_id, " = ", safe_param ) query res <- dbSendQuery(con, query) dbFetch(res) dbClearResult(res) ``` The same result can be had by using `glue::glue_sql()`. It performs the same safe quoting on any variable or R statement appearing between braces within the query string. ```{r} id <- "rating" param <- "G" query <- glue::glue_sql("SELECT title, {`id`} FROM film WHERE {`id`} = {param}", .con = con) df <- dbGetQuery(con, query) head(df, 3) ``` ### Parameterized queries Rather than performing the parameter substitution ourselves, we can push it to the DBMS by including placeholders in the query. Different DBMS use different placeholder schemes, DBI passes through the SQL expression unchanged. MariaDB uses a question mark (?) as placeholder and expects an unnamed list of parameter values. Other DBMS may use named parameters. We recommend consulting the documentation for the DBMS you are using. As an example, a web search for "mariadb parameterized queries" leads to the documentation for the [`PREPARE` statement](https://mariadb.com/kb/en/prepare-statement/) which mentions: > Within the statement, "?" characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it. Currently there is no list of which placeholder scheme a particular DBMS supports. Placeholders only work for literal values. Other parts of the query, e.g. table or column identifiers, still need to be quoted with `dbQuoteIdentifier()`. For a single set of parameters, the `params` argument to `dbSendQuery()` or `dbGetQuery()` can be used. It takes a list and its members are substituted in order for the placeholders within the query. ```{r params} params <- list("G") safe_id <- dbQuoteIdentifier(con, "rating") query <- paste0("SELECT * FROM film WHERE ", safe_id, " = ?") query res <- dbSendQuery(con, query, params = params) dbFetch(res, n = 3) dbClearResult(res) ``` Below is an example query using multiple placeholders with the MariaDB driver. The placeholders are supplied as a list of values ordered to match the position of the placeholders in the query. ```{r multi-param} q_params <- list("G", 90) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ``` When you wish to perform the same query with different sets of parameter values, `dbBind()` is used. There are two ways to use `dbBind()`. Firstly, it can be used multiple times with same query. ```{r dbbind} res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list("G")) dbFetch(res, n = 3) dbBind(res, list("PG")) dbFetch(res, n = 3) dbClearResult(res) ``` Secondly, `dbBind()` can be used to execute the same statement with multiple values at once. ```{r bind_quotestring} res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list(c("G", "PG"))) dbFetch(res, n = 3) dbClearResult(res) ``` Use a list of vectors if your query has multiple parameters: ```{r bind-multi-param} q_params <- list(c("G", "PG"), c(90, 120)) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ``` Always disconnect from the database when done. ```{r disconnect} dbDisconnect(con) ``` ## SQL data manipulation - UPDATE, DELETE and friends For SQL queries that affect the underlying database, such as UPDATE, DELETE, INSERT INTO, and DROP TABLE, DBI provides two functions. `dbExecute()` passes the SQL statement to the DBMS for execution and returns the number of rows affected. `dbSendStatement()` performs in the same manner, but returns a result object. Call `dbGetRowsAffected()` with the result object to get the count of the affected rows. You then need to call `dbClearResult()` with the result object afterwards to release resources. In actuality, `dbExecute()` is a convenience function that calls `dbSendStatement()`, `dbGetRowsAffected()`, and `dbClearResult()`. You can use these functions if you need more control over the query process. The subsequent examples use an in-memory SQL database provided by `RSQLite::SQLite()`, because the remote database used in above examples does not allow writing. ```{r} library(DBI) con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cars", head(cars, 3)) dbExecute( con, "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" ) rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (4, 4), (5, 5), (6, 6)" ) dbGetRowsAffected(rs) dbClearResult(rs) dbReadTable(con, "cars") dbDisconnect(con) ``` ## SQL transactions with DBI DBI allows you to group multiple queries into a single atomic transaction. Transactions are initiated with `dbBegin()` and either made persistent with `dbCommit()` or undone with `dbRollback()`. The example below updates two tables and ensures that either both tables are updated, or no changes are persisted to the database and an error is thrown. ```{r} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cash", data.frame(amount = 100)) dbWriteTable(con, "account", data.frame(amount = 2000)) withdraw <- function(amount) { # All operations must be carried out as logical unit: dbExecute(con, "UPDATE cash SET amount = amount + ?", list(amount)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(amount)) } withdraw_transacted <- function(amount) { # Ensure atomicity dbBegin(con) # Perform operation withdraw(amount) # Persist results dbCommit(con) } withdraw_transacted(300) ``` After withdrawing 300 credits, the cash is increased and the account is decreased by this amount. The transaction ensures that either both operations succeed, or no change occurs. ```{r} dbReadTable(con, "cash") dbReadTable(con, "account") ``` We can roll back changes manually if necessary. Do not forget to call `dbRollback()` in case of error, otherwise the transaction remains open indefinitely. ```{r} withdraw_if_funds <- function(amount) { dbBegin(con) withdraw(amount) # Rolling back after detecting negative value on account: if (dbReadTable(con, "account")$amount >= 0) { dbCommit(con) TRUE } else { message("Insufficient funds") dbRollback(con) FALSE } } withdraw_if_funds(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ``` `dbWithTransaction()` simplifies using transactions. Pass it a connection and the code you want to run as a transaction. It will execute the code and call `dbCommit()` on success and call `dbRollback()` if an error is thrown. ```{r error = TRUE} withdraw_safely <- function(amount) { dbWithTransaction(con, { withdraw(amount) if (dbReadTable(con, "account")$amount < 0) { stop("Error: insufficient funds", call. = FALSE) } }) } withdraw_safely(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ``` As usual, do not forget to disconnect from the database when done. ```{r} dbDisconnect(con) ``` ## Conclusion That concludes the major features of DBI. For more details on the library functions covered in this tutorial and the `vignette("DBI", package = "DBI")` introductory tutorial see the DBI specification at `vignette("spec", package = "DBI")`. If you are after a data manipulation library that works at a higher level of abstraction, check out [dplyr](https://dplyr.tidyverse.org). It is a grammar of data manipulation that can work with local dataframes and remote databases and uses DBI under the hood. DBI/vignettes/DBI-proposal.Rmd0000644000176200001440000006643614064774575015621 0ustar liggesusers--- title: "A Common Interface to Relational Databases from R and S -- A Proposal" author: "David James" date: "March 16, 2000" output: rmarkdown::html_vignette bibliography: biblio.bib vignette: > %\VignetteIndexEntry{A Common Interface to Relational Databases from R and S -- A Proposal} %\VignetteEngine{knitr::rmarkdown} --- For too long S and similar data analysis environments have lacked good interfaces to relational database systems (RDBMS). For the last twenty years or so these RDBMS have evolved into highly optimized client-server systems for data storage and manipulation, and currently they serve as repositories for most of the business, industrial, and research “raw” data that analysts work with. Other analysis packages, such as SAS, have traditionally provided good data connectivity, but S and GNU R have relied on intermediate text files as means of importing data (but see @R.imp-exp and @R-dbms.) Although this simple approach works well for relatively modest amounts of mostly static data, it does not scale up to larger amounts of data distributed over machines and locations, nor does it scale up to data that is highly dynamic – situations that are becoming increasingly common. We want to propose a common interface between R/S and RDBMS that would allow users to access data stored on database servers in a uniform and predictable manner irrespective of the database engine. The interface defines a small set of classes and methods similar in spirit to Python’s DB-API, Java’s JDBC, Microsoft’s ODBC, Perl’s DBI, etc., but it conforms to the “whole-object” philosophy so natural in S and R. # Computing with Distributed Data {#sec:distr} As data analysts, we are increasingly faced with the challenge of larger data sources distributed over machines and locations; most of these data sources reside in relational database management systems (RDBMS). These relational databases represent a mature client-server distributed technology that we as analysts could be exploiting more that we’ve done in the past. The relational technology provides a well-defined standard, the ANSI SQL-92 @sql92, both for defining and manipulating data in a highly optimized fashion from virtually any application. In contrast, S and Splus have provided somewhat limited tools for coping with the challenges of larger and distributed data sets (Splus does provide an `import` function to import from databases, but it is quite limited in terms of SQL facilities). The R community has been more resourceful and has developed a number of good libraries for connecting to mSQL, MySQL, PostgreSQL, and ODBC; each library, however, has defined its own interface to each database engine a bit differently. We think it would be to everybody’s advantage to coordinate the definition of a common interface, an effort not unlike those taken in the Python and Perl communities. The goal of a common, seamless access to distributed data is a modest one in our evolution towards a fully distributed computing environment. We recognize the greater goal of distributed computing as the means to fully integrate diverse systems – not just databases – into a truly flexible analysis environment. Good connectivity to databases, however, is of immediate necessity both in practical terms and as a means to help us transition from monolithic, self-contained systems to those in which computations, not only the data, can be carried out in parallel over a wide number of computers and/or systems @duncan2000. Issues of reliability, security, location transparency, persistence, etc., will be new to most of us and working with distributed data may provide a more gradual change to ease in the ultimate goal of full distributed computing. # A Common Interface {#sec:rs-dbi} We believe that a common interface to databases can help users easily access data stored in RDBMS. A common interface would describe, in a uniform way, how to connect to RDBMS, extract meta-data (such as list of available databases, tables, etc.) as well as a uniform way to execute SQL statements and import their output into R and S. The current emphasis is on querying databases and not so much in a full low-level interface for database development as in JDBC or ODBC, but unlike these, we want to approach the interface from the “whole-object” perspective @S4 so natural to R/S and Python – for instance, by fetching all fields and records simultaneously into a single object. The basic idea is to split the interface into a front-end consisting of a few classes and generic functions that users invoke and a back-end set of database-specific classes and methods that implement the actual communication. (This is a very well-known pattern in software engineering, and another good verbatim is the device-independent graphics in R/S where graphics functions produce similar output on a variety of different devices, such X displays, Postscript, etc.) The following verbatim shows the front-end: ``` > mgr <- dbManager("Oracle") > con <- dbConnect(mgr, user = "user", passwd = "passwd") > rs <- dbExecStatement(con, "select fld1, fld2, fld3 from MY_TABLE") > tbls <- fetch(rs, n = 100) > hasCompleted(rs) [1] T > close(rs) > rs <- dbExecStatement(con, "select id_name, q25, q50 from liv2") > res <- fetch(rs) > getRowCount(rs) [1] 73 > close(con) ``` Such scripts should work with other RDBMS (say, MySQL) by replacing the first line with ``` > mgr <- dbManager("MySQL") ``` ## Interface Classes {#sec:rs-dbi-classes} The following are the main RS-DBI classes. They need to be extended by individual database back-ends (MySQL, Oracle, etc.) `dbManager` : Virtual class[^2] extended by actual database managers, e.g., Oracle, MySQL, Informix. `dbConnection` : Virtual class that captures a connection to a database instance[^3]. `dbResult` : Virtual class that describes the result of an SQL statement. `dbResultSet` : Virtual class, extends `dbResult` to fully describe the output of those statements that produce output records, i.e., `SELECT` (or `SELECT`-like) SQL statement. All these classes should implement the methods `show`, `describe`, and `getInfo`: `show` : (`print` in R) prints a one-line identification of the object. `describe` : prints a short summary of the meta-data of the specified object (like `summary` in R/S). `getInfo` : takes an object of one of the above classes and a string specifying a meta-data item, and it returns the corresponding information (`NULL` if unavailable). > mgr <- dbManager("MySQL") > getInfo(mgr, "version") > con <- dbConnect(mgr, ...) > getInfo(con, "type") The reason we implement the meta-data through `getInfo` in this way is to simplify the writing of database back-ends. We don’t want to overwhelm the developers of drivers (ourselves, most likely) with hundreds of methods as in the case of JDBC. In addition, the following methods should also be implemented: `getDatabases` : lists all available databases known to the `dbManager`. `getTables` : lists tables in a database. `getTableFields` : lists the fields in a table in a database. `getTableIndices` : lists the indices defined for a table in a database. These methods may be implemented using the appropriate `getInfo` method above. In the next few sections we describe in detail each of these classes and their methods. ### Class `dbManager` {#sec:dbManager} This class identifies the relational database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.) The `dbManager` class defines the following methods: `load` : initializes the driver code. We suggest having the generator, `dbManager(driver)`, automatically load the driver. `unload` : releases whatever resources the driver is using. `getVersion` : returns the version of the RS-DBI currently implemented, plus any other relevant information about the implementation itself and the RDBMS being used. ### Class `dbConnection` {#sec:dbConnection} This virtual class captures a connection to a RDBMS, and it provides access to dynamic SQL, result sets, RDBMS session management (transactions), etc. Note that the `dbManager` may or may not allow multiple simultaneous connections. The methods it defines include: `dbConnect` : opens a connection to the database `dbname`. Other likely arguments include `host`, `user`, and `password`. It returns an object that extends `dbConnection` in a driver-specific manner (e.g., the MySQL implementation creates a connection of class `MySQLConnection` that extends `dbConnection`). Note that we could separate the steps of connecting to a RDBMS and opening a database there (i.e., opening an *instance*). For simplicity we do the 2 steps in this method. If the user needs to open another instance in the same RDBMS, just open a new connection. `close` : closes the connection and discards all pending work. `dbExecStatement` : submits one SQL statement. It returns a `dbResult` object, and in the case of a `SELECT` statement, the object also inherits from `dbResultSet`. This `dbResultSet` object is needed for fetching the output rows of `SELECT` statements. The result of a non-`SELECT` statement (e.g., `UPDATE, DELETE, CREATE, ALTER`, ...) is defined as the number of rows affected (this seems to be common among RDBMS). `commit` : commits pending transaction (optional). `rollback` : undoes current transaction (optional). `callProc` : invokes a stored procedure in the RDBMS (tentative). Stored procedures are *not* part of the ANSI SQL-92 standard and possibly vary substantially from one RDBMS to another. For instance, Oracle seems to have a fairly decent implementation of stored procedures, but MySQL currently does not support them. `dbExec` : submit an SQL “script” (multiple statements). May be implemented by looping with `dbExecStatement`. `dbNextResultSet` : When running SQL scripts (multiple statements), it closes the current result set in the `dbConnection`, executes the next statement and returns its result set. ### Class `dbResult` {#sec:dbResult} This virtual class describes the result of an SQL statement (any statement) and the state of the operation. Non-query statements (e.g., `CREATE`, `UPDATE`, `DELETE`) set the “completed” state to 1, while `SELECT` statements to 0. Error conditions set this slot to a negative number. The `dbResult` class defines the following methods: `getStatement` : returns the SQL statement associated with the result set. `getDBConnection` : returns the `dbConnection` associated with the result set. `getRowsAffected` : returns the number of rows affected by the operation. `hasCompleted` : was the operation completed? `SELECT`’s, for instance, are not completed until their output rows are all fetched. `getException` : returns the status of the last SQL statement on a given connection as a list with two members, status code and status description. ### Class `dbResultSet` {#sec:dbResultSet} This virtual class extends `dbResult`, and it describes additional information from the result of a `SELECT` statement and the state of the operation. The `completed` state is set to 0 so long as there are pending rows to fetch. The `dbResultSet` class defines the following additional methods: `getRowCount` : returns the number of rows fetched so far. `getNullOk` : returns a logical vector with as many elements as there are fields in the result set, each element describing whether the corresponding field accepts `NULL` values. `getFields` : describes the `SELECT`ed fields. The description includes field names, RDBMS internal data types, internal length, internal precision and scale, null flag (i.e., column allows `NULL`’s), and corresponding S classes (which can be over-ridden with user-provided classes). The current MySQL and Oracle implementations define a `dbResultSet` as a named list with the following elements: `connection`: : the connection object associated with this result set; `statement`: : a string with the SQL statement being processed; `description`: : a field description `data.frame` with as many rows as there are fields in the `SELECT` output, and columns specifying the `name`, `type`, `length`, `precision`, `scale`, `Sclass` of the corresponding output field. `rowsAffected`: : the number of rows that were affected; `rowCount`: : the number of rows so far fetched; `completed`: : a logical value describing whether the operation has completed or not. `nullOk`: : a logical vector specifying whether the corresponding column may take NULL values. The methods above are implemented as accessor functions to this list in the obvious way. `setDataMappings` : defines a conversion between internal RDBMS data types and R/S classes. We expect the default mappings to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. (See Section [sec:mappings] for details.) `close` : closes the result set and frees resources both in R/S and the RDBMS. `fetch` : extracts the next `max.rec` records (-1 means all). ## Data Type Mappings {#sec:mappings} The data types supported by databases are slightly different than the data types in R and S, but the mapping between them is straightforward: Any of the many fixed and varying length character types are mapped to R/S `character`. Fixed-precision (non-IEEE) numbers are mapped into either doubles (`numeric`) or long (`integer`). Dates are mapped to character using the appropriate `TO_CHAR` function in the RDBMS (which should take care of any locale information). Some RDBMS support the type `CURRENCY` or `MONEY` which should be mapped to `numeric`. Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion as follows: 1. run the query (either with `dbExec` or `dbExecStatement`): > rs <- dbExecStatement(con, "select whatever-You-need") 2. extract the output field definitions > flds <- getFields(rs) 3. replace the class generator in the, say 3rd field, by the user own generator: > flds[3, "Sclass"] # default mapping [1] "character" by > flds[3, "Sclass"] <- "myOwnGeneratorFunction" 4. set the new data mapping prior to fetching > setDataMappings(resutlSet, flds) 5. fetch the rows and store in a `data.frame` > data <- fetch(resultSet) ## Open Issues {#sec:open-issues} We may need to provide some additional utilities, for instance to convert dates, to escape characters such as quotes and slashes in query strings, to strip excessive blanks from some character fields, etc. We need to decide whether we provide hooks so these conversions are done at the C level, or do all the post-processing in R or S. Another issue is what kind of data object is the output of an SQL query. Currently the MySQL and Oracle implementations return data as a `data.frame`; data frames have the slight inconvenience that they automatically re-label the fields according to R/S syntax, changing the actual RDBMS labels of the variables; the issue of non-numeric data being coerced into factors automatically “at the drop of a hat” (as someone in s-news wrote) is also annoying. The execution of SQL scripts is not fully described. The method that executes scripts could run individual statements without returning until it encounters a query (`SELECT`-like) statement. At that point it could return that one result set. The application is then responsible for fetching these rows, and then for invoking `dbNextResultSet` on the opened `dbConnection` object to repeat the `dbExec`/`fetch` loop until it encounters the next `dbResultSet`. And so on. Another (potentially very expensive) alternative would be to run all statements sequentially and return a list of `data.frame`s, each element of the list storing the result of each statement. Binary objects and large objects present some challenges both to R and S. It is becoming more common to store images, sounds, and other data types as binary objects in RDBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects – perhaps tentatively not in full generality. Large objects could be fetched by repeatedly invoking a specified R/S function that takes as argument chunks of a specified number of raw bytes. In the case of S4 (and Splus5.x) the RS-DBI implementation can write into an opened connection for which the user has defined a reader (but can we guarantee that we won’t overflow the connection?). In the case of R it is not clear what data type binary large objects (BLOB) should be mapped into. ## Limitations {#sec:limitations} These are some of the limitations of the current interface definition: - we only allow one SQL statement at a time, forcing users to split SQL scripts into individual statements; - transaction management is not fully described; - the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement /* SQL */ SELECT * from emp_table where emp_id = :sampleEmployee would take the vector `sampleEmployee` and iterate over each of its elements to get the result. Perhaps RS-DBI could at some point in the future implement this feature. # Other Approaches The high-level, front-end description of RS-DBI is the more critical aspect of the interface. Details on how to actually implement this interface may change over time. The approach described in this document based on one back-end driver per RDBMS is reasonable, but not the only approach – we simply felt that a simpler approach based on well-understood and self-contained tools (R, S, and C API’s) would be a better start. Nevertheless we want to briefly mention a few alternatives that we considered and tentatively decided against, but may quite possibly re-visit in the near future. ## Open Database Connectivity (ODBC) {#sec:odbc} The ODBC protocol was developed by Microsoft to allow connectivity among C/C++ applications and RDBMS. As you would expect, originally implementations of the ODBC were only available under Windows environments. There are various effort to create a Unix implementation (see [the Unix ODBC](http://www.unixodbc.org/) web-site and @odbc.lj). This approach looks promising because it allows us to write only one back-end, instead of one per RDBMS. Since most RDBMS already provide ODBC drivers, this could greatly simplify development. Unfortunately, the Unix implementation of ODBC was not mature enough at the time we looked at it, a situation we expect will change in the next year or so. At that point we will need to re-evaluate it to make sure that such an ODBC interface does not penalize the interface in terms of performance, ease of use, portability among the various Unix versions, etc. ## Java Database Connectivity (JDBC) {#sec:jdbc} Another protocol, the Java database connectivity, is very well-done and supported by just about every RDBMS. The issue with JDBC is that as of today neither S nor R (which are written in C) interfaces cleanly with Java. There are several efforts (some in a quite fairly advanced state) to allow S and R to invoke Java methods. Once this interface is widely available in Splus5x and R we will need to re-visit this issue again and study the performance, usability, etc., of JDBC as a common back-end to the RS-DBI. ## CORBA and a 3-tier Architecture {#sec:corba} Yet another approach is to move the interface to RDBMS out of R and S altogether into a separate system or server that would serve as a proxy between R/S and databases. The communication to this middle-layer proxy could be done through CORBA [@s-corba.98, @corba:siegel.96], Java’s RMI, or some other similar technology. Such a design could be very flexible, but the CORBA facilities both in R and S are not widely available yet, and we do not know whether this will be made available to Splus5 users from MathSoft. Also, my experience with this technology is rather limited. On the other hand, this 3-tier architecture seem to offer the most flexibility to cope with very large distributed databases, not necessarily relational. # Resources {#sec:resources} The latest documentation and software on the RS-DBI was available at www.omegahat.net (link dead now: `https://www.omegahat.net/contrib/RS-DBI/index.html`). The R community has developed interfaces to some databases: [RmSQL](https://cran.r-project.org/src/contrib/Archive/RmSQL/) is an interface to the [mSQL](https://www.Hughes.com.au) database written by Torsten Hothorn; [RPgSQL](https://sites.cns.utexas.edu/keittlab/software-0) is an interface to [PostgreSQL](https://www.postgreSQL.org) and was written by Timothy H. Keitt; [RODBC](https://www.stats.ox.ac.uk/pub/bdr/) is an interface to ODBC, and it was written by [Michael Lapsley](mailto:mlapsley@sthelier.sghms.ac.uk). (For more details on all these see @R.imp-exp.) The are R and S-Plus interfaces to [MySQL](https://dev.mysql.com/) that follow the propose RS-DBI API described here; also, there’s an S-Plus interface SOracle @RS-Oracle to [Oracle](https://www.oracle.com/) (we expect to have an R implementation soon.) The idea of a common interface to databases has been successfully implemented in Java’s Database Connectivity (JDBC) ([www.javasoft.com](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/)), in C through the Open Database Connectivity (ODBC) ([www.unixodbc.org](http://www.unixodbc.org/)), in Python’s Database Application Programming Interface ([www.python.org](https://www.python.org)), and in Perl’s Database Interface ([www.cpan.org](https://www.cpan.org)). # Acknowledgements The R/S database interface came about from suggestions, comments, and discussions with [John M. Chambers](mailto:jmc@research.bell-labs.com) and [Duncan Temple Lang](mailto:duncan@research.bell-labs.com) in the context of the Omega Project for Statistical Computing. [Doug Bates](mailto:bates@stat.wisc.edu) and [Saikat DebRoy](mailto:saikat@stat.wisc.edu) ported (and greatly improved) the first MySQL implementation to R. # The S Version 4 Definitions The following code is meant to serve as a detailed description of the R/S to database interface. We decided to use S4 (instead of R or S version 3) because its clean syntax help us to describe easily the classes and methods that form the RS-DBI, and also to convey the inter-class relationships. ```R ## Define all the classes and methods to be used by an ## implementation of the RS-DataBase Interface. Mostly, ## these classes are virtual and each driver should extend ## them to provide the actual implementation. ## Class: dbManager ## This class identifies the DataBase Management System ## (Oracle, MySQL, Informix, PostgreSQL, etc.) setClass("dbManager", VIRTUAL) setGeneric("load", def = function(dbMgr,...) standardGeneric("load") ) setGeneric("unload", def = function(dbMgr,...) standardGeneric("unload") ) setGeneric("getVersion", def = function(dbMgr,...) standardGeneric("getVersion") ) ## Class: dbConnections ## This class captures a connection to a database instance. setClass("dbConnection", VIRTUAL) setGeneric("dbConnection", def = function(dbMgr, ...) standardGeneric("dbConnection") ) setGeneric("dbConnect", def = function(dbMgr, ...) standardGeneric("dbConnect") ) setGeneric("dbExecStatement", def = function(con, statement, ...) standardGeneric("dbExecStatement") ) setGeneric("dbExec", def = function(con, statement, ...) standardGeneric("dbExec") ) setGeneric("getResultSet", def = function(con, ..) standardGeneric("getResultSet") ) setGeneric("commit", def = function(con, ...) standardGeneric("commit") ) setGeneric("rollback", def = function(con, ...) standardGeneric("rollback") ) setGeneric("callProc", def = function(con, ...) standardGeneric("callProc") ) setMethod("close", signature = list(con="dbConnection", type="missing"), def = function(con, type) NULL ) ## Class: dbResult ## This is a base class for arbitrary results from the RDBMS ## (INSERT, UPDATE, DELETE). SELECTs (and SELECT-like) ## statements produce "dbResultSet" objects, which extend ## dbResult. setClass("dbResult", VIRTUAL) setMethod("close", signature = list(con="dbResult", type="missing"), def = function(con, type) NULL ) ## Class: dbResultSet ## Note that we define a resultSet as the result of a ## SELECT SQL statement. setClass("dbResultSet", "dbResult") setGeneric("fetch", def = function(resultSet,n,...) standardGeneric("fetch") ) setGeneric("hasCompleted", def = function(object, ...) standardGeneric("hasCompleted") ) setGeneric("getException", def = function(object, ...) standardGeneric("getException") ) setGeneric("getDBconnection", def = function(object, ...) standardGeneric("getDBconnection") ) setGeneric("setDataMappings", def = function(resultSet, ...) standardGeneric("setDataMappings") ) setGeneric("getFields", def = function(object, table, dbname, ...) standardGeneric("getFields") ) setGeneric("getStatement", def = function(object, ...) standardGeneric("getStatement") ) setGeneric("getRowsAffected", def = function(object, ...) standardGeneric("getRowsAffected") ) setGeneric("getRowCount", def = function(object, ...) standardGeneric("getRowCount") ) setGeneric("getNullOk", def = function(object, ...) standardGeneric("getNullOk") ) ## Meta-data: setGeneric("getInfo", def = function(object, ...) standardGeneric("getInfo") ) setGeneric("describe", def = function(object, verbose=F, ...) standardGeneric("describe") ) setGeneric("getCurrentDatabase", def = function(object, ...) standardGeneric("getCurrentDatabase") ) setGeneric("getDatabases", def = function(object, ...) standardGeneric("getDatabases") ) setGeneric("getTables", def = function(object, dbname, ...) standardGeneric("getTables") ) setGeneric("getTableFields", def = function(object, table, dbname, ...) standardGeneric("getTableFields") ) setGeneric("getTableIndices", def = function(object, table, dbname, ...) standardGeneric("getTableIndices") ) ``` [^2]: A virtual class allows us to group classes that share some common functionality, e.g., the virtual class “`dbConnection`” groups all the connection implementations by Informix, Ingres, DB/2, Oracle, etc. Although the details will vary from one RDBMS to another, the defining characteristic of these objects is what a virtual class captures. R and S version 3 do not explicitly define virtual classes, but they can easily implement the idea through inheritance. [^3]: The term “database” is sometimes (confusingly) used both to denote the RDBMS, such as Oracle, MySQL, and also to denote a particular database instance under a RDBMS, such as “opto” or “sales” databases under the same RDBMS. DBI/vignettes/biblio.bib0000644000176200001440000001772214064774575014632 0ustar liggesusers@string{jcgs="Journal of Computational and Graphical Statistics"} @inproceedings{s-corba.98, author = "Chambers, John M. and Hansen, Mark H. and James, David A. and Temple Lang, Duncan", title = "Distributed Computing with Data: A CORBA-based Approach", booktitle = "Computing Science and Statistics", year = 1998, organization = "Inteface Foundation of North America" } @book{S.88, author = "Becker, R. A. and Chambers, J. M. and Wilks, A. R", year = "1988", title = "The New S Language", publisher = "Wadsworth", address = "Pacific Grove, California" } @book{S.92, editor = "Chambers, J. M. and Hastie, T.", year = 1992, title = "Statistical Models in S", publisher = "Wadsworth", address = "Pacific Grove, California" } @book{S4, author = "Chambers, J. M.", title = "Programming with Data: A Guide to the S Language", publisher = "Springer", address = "New York", year = 1998 } @article{R.96, author = "Ihaka, Ross and Gentleman, Robert", title = "R: A Language for Data Analysis and Graphics", journal = jcgs, volume = 5, number = 3, year = 1996, pages = "299-314" } @book{corba:siegel.96, author = "Siegel, Jon", title = "CORBA Fundamentals and Programming", publisher = "Wiley", address = "New York", year = 1996 } @book{pvm, title = "PVM: Parallel Virtual Machine. A User's Guide and Tutorial for Networked Parallel Computing", author="Geist, A. and Beguelin, A. and Dongarra, J. and Jiang, W. and Mancheck, R. and Sunderam, V.", year = 1994, publisher = "MIT Press", address = "Cambridge, MA" } @manual{splus, title = "S-PLUS Software Documentation", key = "S-PLUS", organization = "StatSci Division of MathSoft Inc.", note = "Version 3.3", year = 1995, address = "Seattle, WA", } @book{tierney.90, author = "Tierney, Luke", year = 1990, title = "LISP-STAT: An Object-Oriented Environment for Statistical Computing and Dynamic Graphics", publisher = "Wiley", address = "New York" } @article{tierney.96, author = "Tierney, Luke", title = "Recent Development and Future Directions in {LispStat}", journal = jcgs, volume = 5, number = 3, year = 1996, pages = "250-262" } @article{odbc.lj, author = "Harvey, Peter", title = "{Open Database Connectivity}", journal = "{Linux Journal}", year = 1999, volume = "Nov.", number = 67, pages = "68-72" } @article{duncan2000, author = "Temple Lang, Duncan", title = "{The Omegahat Environment: New Possibilities for Statistical Computing}", journal = jcgs, volume = "to appear", year = 2000, number = "" } @manual{sql92, title = "{X/Open CAE Specification: SQL and RDA}", organization = "X/Open Company Ltd.", address = "Reading, UK", year = 1994 } @book{MySQL, author = "DuBois, Paul", title = "{MySQL}", publisher = "New Riders Publishing", year = 2000 } @manual{R.ext, title = "Writing {R} Extensions", organization = "{R} Development Core Team", note = "Version 1.2.1 (2001-01-15)", year = 2001 } @manual{R.imp-exp, title = "{R} Data Import/Export", organization = "R-Development Core Team", note = "Version 1.2.1 (2001-01-15)", year = 2001 } @manual{R-dbms, title = "Using Relational Database Systems with {R}", organization = "R-Developemt Core Team", note = "Draft", year = 2000 } @manual{bates.mysql, title = "Using Relational Database Systems with {R}", organization = "R-Developemt Core Team", note = "Draft", year = 2000 } @techreport{proxyDBMS, author = "James, David A.", title = "Proxy Database Object in the S Language", institution = "Bell Labs, Lucent Technologies", year = "In preparation" } @techreport{RS-DBI, author = "James, David A.", title = "A Common Interface to Relational Database Management Sysmtems from {R} and {S} --- A Proposal", institution = "Bell Labs, Lucent Technologies", year = "2000", address = "www.omegahat.org" } @techreport{RS-MySQL, author = "James, David A.", title = "An {R}/{S} Interface to the {MySQL} Database", institution = "Bell Labs, Lucent Technologies", year = "2001", address = "www.omegahat.org" } @techreport{RS-Oracle, author = "James, David A.", title = "An {R}/{S} Interface to the {Oracle} Database", institution = "Bell Labs, Lucent Technologies", year = "In preparation", address = "www.omegahat.org" } @manual{r-data-imp:2001, author = {R Development Core Team}, title = {R Data Import/Export}, year = {2001}, address = {\url{https://www.r-project.org}} } @manual{mysql:2000, author = "Axmark, David and Widenius, Michael and Cole, Jeremy and DuBois, Paul", title = {MySQL Reference Manual}, year = {2001}, address = {\url{https://www.mysql.com/documentation/mysql}} } @manual{jdbc:2000, author = "Ellis, Jon and Ho, Linda and Fisher, Maydene", title = {JDBC 3.0 Specification}, organization = {Sun Microsystems, Inc}, year = {2000}, address = {\url{https://java.sun.com/Download4}} } @article{using-data:2001, author = "Ripley, Brian D.", title = {Using Databases with {R}}, journal = {R {N}ews}, year = {2001}, month = {January}, volume = {1}, number = {1}, pages = {18--20}, address = {\url{https://www.r-project.org/doc/Rnews/}} } @Manual{odbc:2001, title = {Microsoft {ODBC}}, organization = {Microsoft Inc}, address = {\url{https://www.microsoft.com/data/odbc/}}, year = 2001 } @Book{PerlDBI:2000, author = "Descartes, Alligator and Bunce, Tim", title = {Programming the {P}erl {DBI}}, publisher = {O'Reilly}, year = 2000 } @Book{Reese:2000, author = "Reese, George", title = {Database Programming with {JDBC} and {J}ava}, publisher = {O'Reilly}, year = 2000, edition = {second} } @book{Xopen-sql, author = {X/Open Company Ltd.}, title = {X/Open SQL and RDA Specification}, publisher = {X/Open Company Ltd.}, year = 1994 } @book{mysql-dubois, author = "DuBois, Paul", title = {MySQL}, publisher = {New Riders}, year = 2000 } @techreport{data-management:1991, author = "Chambers, John M.", title = {Data Management in {S}}, institution = {Bell Labs, Lucent Technologies}, year = 1991 } @techreport{database-classes:1999, author = "Chambers, John M.", title = {Database Classes}, institution = {Bell Labs, Lucent Technologies}, year = 1998 } @inproceedings{R-dcom, author = "Neuwirth, Erich and Baier, Thomas", title = {Embedding {R} in Standard Software, and the other way around}, organization = {Vienna University of Technology}, year = 2001, booktitle = {Proceedings of the Distributed Statistical Computing 2001 Workshop}, address = {\url{http://www.ci.tuwien.ac.at/Conferences/DSC-2001}} } @inproceedings{R-tcltk, author = "Dalgaard, Peter", title = {The {R}-{T}cl/{T}k Interface}, organization = {Vienna University of Technology}, year = 2001, booktitle = {Proceedings of the Distributed Statistical Computing 2001 Workshop}, address = {\url{http://www.ci.tuwien.ac.at/Conferences/DSC-2001}} } @inproceedings{duncan-dsc2001, author = "Temple Lang, Duncan", title = {Embedding {S} in Other Languages and Environments}, organization = {Vienna University of Technology}, year = 2001, booktitle = {Proceedings of the Distributed Statistical Computing 2001 Workshop}, address = {\url{http://www.ci.tuwien.ac.at/Conferences/DSC-2001}} } @inproceedings{BDR-RMR, author = "Ripley, B. D. and Ripley, R. M.", title = {Applications of {R} Clients and Servers}, organization = {Vienna University of Technology}, year = 2001, booktitle = {Proceedings of the Distributed Statistical Computing 2001 Workshop}, address = {\url{http://www.ci.tuwien.ac.at/Conferences/DSC-2001}} } @inproceedings{rsdbi-dsc2001, author = "Hothorn, Torsten and James, David A. and Ripley, Brian D.", title = {{R}/{S} Interfaces to Databases}, organization = {Vienna University of Technology}, year = 2001, booktitle = {Proceedings of the Distributed Statistical Computing 2001 Workshop}, address = {\url{http://www.ci.tuwien.ac.at/Conferences/DSC-2001}} } DBI/vignettes/backend.Rmd0000644000176200001440000002414014064774575014737 0ustar liggesusers --- title: "Implementing a new backend" author: "Hadley Wickham, Kirill Müller" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Implementing a new backend} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE} library(DBI) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` The goal of this document is to help you implement a new backend for DBI. If you are writing a package that connects a database to R, I highly recommend that you make it DBI compatible because it makes your life easier by spelling out exactly what you need to do. The consistent interface provided by DBI makes it easier for you to implement the package (because you have fewer arbitrary choices to make), and easier for your users (because it follows a familiar pattern). In addition, the `DBItest` package provides test cases which you can easily incorporate in your package. I'll illustrate the process using a fictional database called Kazam. ## Getting started Start by creating a package. It's up to you what to call the package, but following the existing pattern of `RSQLite`, `RMySQL`, `RPostgres` and `ROracle` will make it easier for people to find it. For this example, I'll call my package `RKazam`. A ready-to-use template package is available at https://github.com/r-dbi/RKazam/. You can start by creating a new GitHub repository from this template, or by copying the package code. Rename "Kazam" to your desired name everywhere. The template package already contains dummy implementations for all classes and methods. If you chose to create the package manually, make sure to include in your `DESCRIPTION`: ```yaml Imports: DBI (>= 0.3.0), methods Suggests: DBItest, testthat ``` Importing `DBI` is fine, because your users are not supposed to *attach* your package anyway; the preferred method is to attach `DBI` and use explicit qualification via `::` to access the driver in your package (which needs to be done only once). ## Testing Why testing at this early stage? Because testing should be an integral part of the software development cycle. Test right from the start, add automated tests as you go, finish faster (because tests are automated) while maintaining superb code quality (because tests also check corner cases that you might not be aware of). Don't worry: if some test cases are difficult or impossible to satisfy, or take too long to run, you can just turn them off. Take the time now to head over to the `DBItest` vignette at `vignette("test", package = "DBItest")`. You will find a vast amount of ready-to-use test cases that will help you in the process of implementing your new DBI backend. Add custom tests that are not covered by `DBItest` at your discretion, or enhance `DBItest` and file a pull request if the test is generic enough to be useful for many DBI backends. ## Driver Start by making a driver class which inherits from `DBIDriver`. This class doesn't need to do anything, it's just used to dispatch other generics to the right method. Users don't need to know about this, so you can remove it from the default help listing with `@keywords internal`: ```{r} #' Driver for Kazam database. #' #' @keywords internal #' @export #' @import DBI #' @import methods setClass("KazamDriver", contains = "DBIDriver") ``` The driver class was more important in older versions of DBI, so you should also provide a dummy `dbUnloadDriver()` method. ```{r} #' @export #' @rdname Kazam-class setMethod("dbUnloadDriver", "KazamDriver", function(drv, ...) { TRUE }) ``` If your package needs global setup or tear down, do this in the `.onLoad()` and `.onUnload()` functions. You might also want to add a show method so the object prints nicely: ```{r} setMethod("show", "KazamDriver", function(object) { cat("\n") }) ``` Next create `Kazam()` which instantiates this class. ```{r} #' @export Kazam <- function() { new("KazamDriver") } Kazam() ``` ## Connection Next create a connection class that inherits from `DBIConnection`. This should store all the information needed to connect to the database. If you're talking to a C api, this will include a slot that holds an external pointer. ```{r} #' Kazam connection class. #' #' @export #' @keywords internal setClass("KazamConnection", contains = "DBIConnection", slots = list( host = "character", username = "character", # and so on ptr = "externalptr" ) ) ``` Now you have some of the boilerplate out of the way, you can start work on the connection. The most important method here is `dbConnect()` which allows you to connect to a specified instance of the database. Note the use of `@rdname Kazam`. This ensures that `Kazam()` and the connect method are documented together. ```{r} #' @param drv An object created by \code{Kazam()} #' @rdname Kazam #' @export #' @examples #' \dontrun{ #' db <- dbConnect(RKazam::Kazam()) #' dbWriteTable(db, "mtcars", mtcars) #' dbGetQuery(db, "SELECT * FROM mtcars WHERE cyl == 4") #' } setMethod("dbConnect", "KazamDriver", function(drv, ...) { # ... new("KazamConnection", host = host, ...) }) ``` * Replace `...` with the arguments needed to connect to your database. You'll always need to include `...` in the arguments, even if you don't use it, for compatibility with the generic. * This is likely to be where people first come for help, so the examples should show how to connect to the database, and how to query it. (Obviously these examples won't work yet.) Ideally, include examples that can be run right away (perhaps relying on a publicly hosted database), but failing that surround in `\dontrun{}` so people can at least see the code. Next, implement `show()` and `dbDisconnect()` methods. ## Results Finally, you're ready to implement the meat of the system: fetching results of a query into a data frame. First define a results class: ```{r} #' Kazam results class. #' #' @keywords internal #' @export setClass("KazamResult", contains = "DBIResult", slots = list(ptr = "externalptr") ) ``` Then write a `dbSendQuery()` method. This takes a connection and SQL string as arguments, and returns a result object. Again `...` is needed for compatibility with the generic, but you can add other arguments if you need them. ```{r} #' Send a query to Kazam. #' #' @export #' @examples #' # This is another good place to put examples setMethod("dbSendQuery", "KazamConnection", function(conn, statement, ...) { # some code new("KazamResult", ...) }) ``` Next, implement `dbClearResult()`, which should close the result set and free all resources associated with it: ```{r} #' @export setMethod("dbClearResult", "KazamResult", function(res, ...) { # free resources TRUE }) ``` The hardest part of every DBI package is writing the `dbFetch()` method. This needs to take a result set and (optionally) number of records to return, and create a dataframe. Mapping R's data types to those of your database may require a custom implementation of the `dbDataType()` method for your connection class: ```{r} #' Retrieve records from Kazam query #' @export setMethod("dbFetch", "KazamResult", function(res, n = -1, ...) { ... }) # (optionally) #' Find the database data type associated with an R object #' @export setMethod("dbDataType", "KazamConnection", function(dbObj, obj, ...) { ... }) ``` Next, implement `dbHasCompleted()` which should return a `logical` indicating if there are any rows remaining to be fetched. ```{r} #' @export setMethod("dbHasCompleted", "KazamResult", function(res, ...) { }) ``` With these four methods in place, you can now use the default `dbGetQuery()` to send a query to the database, retrieve results if available and then clean up. Spend some time now making sure this works with an existing database, or relax and let the `DBItest` package do the work for you. ## SQL methods You're now on the home stretch, and can make your wrapper substantially more useful by implementing methods that wrap around variations in SQL across databases: * `dbQuoteString()` and `dbQuoteIdentifer()` are used to safely quote strings and identifiers to avoid SQL injection attacks. Note that the former must be vectorized, but not the latter. * `dbWriteTable()` creates a database table given an R dataframe. I'd recommend using the functions prefixed with `sql` in this package to generate the SQL. These functions are still a work in progress so please let me know if you have problems. * `dbReadTable()`: a simple wrapper around `SELECT * FROM table`. Use `dbQuoteIdentifer()` to safely quote the table name and prevent mismatches between the names allowed by R and the database. * `dbListTables()` and `dbExistsTable()` let you determine what tables are available. If not provided by your database's API, you may need to generate sql that inspects the system tables. * `dbListFields()` shows which fields are available in a given table. * `dbRemoveTable()` wraps around `DROP TABLE`. Start with `SQL::sqlTableDrop()`. * `dbBegin()`, `dbCommit()` and `dbRollback()`: implement these three functions to provide basic transaction support. This functionality is currently not tested in the `DBItest` package. ## Metadata methods There are a lot of extra metadata methods for result sets (and one for the connection) that you might want to implement. They are described in the following. * `dbIsValid()` returns if a connection or a result set is open (`TRUE`) or closed (`FALSE`). All further methods in this section are valid for result sets only. * `dbGetStatement()` returns the issued query as a character value. * `dbColumnInfo()` lists the names and types of the result set's columns. * `dbGetRowCount()` and `dbGetRowsAffected()` returns the number of rows returned or altered in a `SELECT` or `INSERT`/`UPDATE` query, respectively. * `dbBind()` allows using parametrised queries. Take a look at `sqlInterpolate()` and `sqlParseVariables()` if your SQL engine doesn't offer native parametrised queries. ## Full DBI compliance By now, your package should implement all methods defined in the DBI specification. If you want to walk the extra mile, offer a read-only mode that allows your users to be sure that their valuable data doesn't get destroyed inadvertently. DBI/vignettes/spec.Rmd0000644000176200001440000001173514064774575014310 0ustar liggesusers--- title: "DBI specification" author: "Kirill Müller" output: rmarkdown::html_vignette abstract: > The DBI package defines the generic DataBase Interface for R. The connection to individual DBMS is provided by other packages that import DBI (so-called *DBI backends*). This document formalizes the behavior expected by the methods declared in DBI and implemented by the individual backends. To ensure maximum portability and exchangeability, and to reduce the effort for implementing a new DBI backend, the DBItest package defines a comprehensive set of test cases that test conformance to the DBI specification. This document is derived from comments in the test definitions of the DBItest package. Any extensions or updates to the tests will be reflected in this document. vignette: > %\VignetteIndexEntry{DBI specification} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo = FALSE} library(magrittr) library(xml2) knitr::opts_chunk$set(echo = FALSE) r <- rprojroot::is_r_package$make_fix_file() ``` ```{r error=TRUE} rd_db <- tools::Rd_db(dir = r()) Links <- tools::findHTMLlinks() html_topic <- function(name) { rd <- rd_db[[paste0(name, ".Rd")]] conn <- textConnection(NULL, "w") on.exit(close(conn)) #tools::Rd2HTML(rd, conn, Links = Links) tools::Rd2HTML(rd, conn) textConnectionValue(conn) } xml_topic <- function(name, patcher) { html <- html_topic(name) x <- read_html(paste(html, collapse = "\n")) # No idea why this is necessary when embedding HTML in Markdown codes <- x %>% xml_find_all("//code[contains(., '$')]") xml_text(codes) <- gsub("[$]", "\\\\$", xml_text(codes)) xx <- x %>% xml_find_first("/html/body") xx %>% xml_find_first("//table") %>% xml_remove() xx %>% xml_find_all("//pre") %>% xml_set_attr("class", "r") patcher(xx) } out_topic <- function(name, patcher = identity) { xml <- lapply(name, xml_topic, patcher = patcher) sapply(xml, as.character) %>% paste(collapse = "\n") } patch_package_doc <- function(x) { x %>% xml_find_first("//h3") %>% xml_remove remove_see_also_section(x) remove_authors_section(x) x } move_contents_of_usage_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 usage_contents <- x %>% xml_find_all( "//h3[.='Usage']/following-sibling::node() [not(self::h3)] [count(preceding-sibling::h3)=2]") usage_text <- usage_contents %>% xml_find_first("//pre") %>% xml_text h3 <- x %>% xml_find_first("//h3") intro_text <- read_xml( paste0( "

This section describes the behavior of the following method", if (length(grep("[(]", strsplit(usage_text, "\n")[[1]])) > 1) "s" else "", ":

") ) xml_add_sibling( h3, intro_text, .where = "before") lapply(usage_contents, xml_add_sibling, .x = h3, .copy = FALSE, .where = "before") x %>% xml_find_first("//h3[.='Usage']") %>% xml_remove x } move_additional_arguments_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error additional_arguments <- x %>% xml_find_all( "//h3[.='Additional arguments'] | //h3[.='Additional arguments']/following-sibling::node()[following-sibling::h3]") after_arg <- x %>% xml_find_first("//h3[text()='Arguments']/following-sibling::h3") lapply(additional_arguments, xml_add_sibling, .x = after_arg, .copy = FALSE, .where = "before") x } remove_see_also_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='See Also'] | //h3[.='See Also']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } remove_authors_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='Author(s)'] | //h3[.='Author(s)']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } patch_method_doc <- function(x) { move_contents_of_usage_section(x) remove_see_also_section(x) move_additional_arguments_section(x) x } topics <- c( "dbDataType", "dbConnect", "dbDisconnect", "dbSendQuery", "dbFetch", "dbClearResult", "dbBind", "dbGetQuery", "dbSendStatement", "dbExecute", "dbQuoteString", "dbQuoteIdentifier", "dbReadTable", "dbWriteTable", "dbListTables", "dbExistsTable", "dbRemoveTable", "dbListFields", "dbIsValid", "dbHasCompleted", "dbGetStatement", "dbGetRowCount", "dbGetRowsAffected", "dbColumnInfo", "transactions", "dbWithTransaction" ) html <- c( out_topic("DBI-package", patch_package_doc), out_topic(topics, patch_method_doc) ) temp_html <- tempfile(fileext = ".html") temp_md <- tempfile(fileext = ".md") #temp_html <- "out.html" #temp_md <- "out.md" #html <- '
\na\nb\n
' writeLines(html, temp_html) rmarkdown::pandoc_convert(temp_html, "gfm", verbose = FALSE, output = temp_md) knitr::asis_output(paste(readLines(temp_md), collapse = "\n")) ``` DBI/vignettes/DBI-history.Rmd0000644000176200001440000001221614064774575015446 0ustar liggesusers--- title: "History of DBI" author: "David James" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"History of DBI"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- The following history of DBI was contributed by David James, the driving force behind the development of DBI, and many of the packages that implement it. The idea/work of interfacing S (originally S3 and S4) to RDBMS goes back to the mid- and late 1990's in Bell Labs. The first toy interface I did was to implement John Chamber's early concept of "Data Management in S" (1991). The implementation followed that interface pretty closely and immediately showed some of the limitations when dealing with very large databases; if my memory serves me, the issue was the instance-based of the language back then, e.g., if you attached an RDBMS to the `search()` path and then needed to resolve a symbol "foo", you effectively had to bring all the objects in the database to check their mode/class, i.e., the instance object had the metadata in itself as attributes. The experiment showed that the S3 implementation of "data management" was not really suitable to large external RDBMS (probably it was never intended to do that anyway). (Note however, that since then, John and Duncan Temple Lang generalized the data management in S4 a lot, including Duncan's implementation in his RObjectTables package where he considered a lot of synchronization/caching issues relevant to DBI and, more generally, to most external interfaces). Back then we were working very closely with Lucent's microelectronics manufacturing --- our colleagues there had huge Oracle (mostly) databases that we needed to constantly query via [SQL*Plus](https://en.wikipedia.org/wiki/SQL*Plus). My colleague Jake Luciani was developing advanced applications in C and SQL, and the two of us came up with the first implementation of S3 directly connecting with Oracle. What I remember is that the Linux [PRO*C](https://en.wikipedia.org/wiki/Pro*C) pre-compiler (that embedded SQL in C code) was very buggy --- we spent a lot of time looking for workarounds and tricks until we got the C interface running. At the time, other projects within Bell Labs began using MySQL, and we moved to MySQL (with the help of Doug Bates' student Saikat DebRoy, then a summer intern) with no intentions of looking back at the very difficult Oracle interface. It was at this time that I moved all the code from S3 methods to S4 classes and methods and begun reaching out to the S/R community for suggestions, ideas, etc. All (most) of this work was on Bell Labs versions of S3 and S4, but I made sure it worked with S-Plus. At some point around 2000 (I don't remember exactly when), I ported all the code to R regressing to S3 methods, and later on (once S4 classes and methods were available in R) I re-implemented everything back to S4 classes and methods in R (a painful back-and-forth). It was at this point that I decided to drop S-Plus altogether. Around that time, I came across a very early implementation of SQLite and I was quite interested and thought it was a very nice RDBMS that could be used for all kinds of experimentation, etc., so it was pretty easy to implement on top of the DBI. Within the R community, there were quite a number of people that showed interest on defining a common interface to databases, but only a few folks actually provided code/suggestions/etc. (Tim Keitt was most active with the dbi/PostgreSQL packages --- he also was considering what he called "proxy" objects, which was reminiscent of what Duncan had been doing). Kurt Hornick, Vincent Carey, Robert Gentleman, and others provided suggestions/comments/support for the DBI definition. By around 2003, the DBI was more or less implemented as it is today. I'm sure I'll forget some (most should be in the THANKS sections of the various packages), but the names that come to my mind at this moment are Jake Luciani (ROracle), Don MacQueen and other early ROracle users (super helpful), Doug Bates and his student Saikat DebRoy for RMySQL, Fei Chen (at the time a student of Prof. Ripley) also contributed to RMySQL, Tim Keitt (working on an early S3 interface to PostgrSQL), Torsten Hothorn (worked with mSQL and also MySQL), Prof. Ripley working/extending the RODBC package, in addition to John Chambers and Duncan Temple-Lang who provided very important comments and suggestions. Actually, the real impetus behind the DBI was always to do distributed statistical computing --- *not* to provide a yet-another import/export mechanism --- and this perspective was driven by John and Duncan's vision and work on inter-system computing, COM, CORBA, etc. I'm not sure many of us really appreciated (even now) the full extent of those ideas and concepts. Just like in other languages (C's ODBC, Java's JDBC, Perl's DBI/DBD, Python dbapi), R/S DBI was meant to unify the interfacing to RDBMS so that R/S applications could be developed on top of the DBI and not be hard coded to any one relation database. The interface I tried to follow the closest was the Python's DBAPI --- I haven't worked on this topic for a while, but I still feel Python's DBAPI is the cleanest and most relevant for the S language. DBI/vignettes/DBI.Rmd0000644000176200001440000001627614157713767013760 0ustar liggesusers--- title: "Introduction to DBI" author: "James Wondrasek, Katharina Brunner, Kirill Müller" date: "27 February 2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"Introduction to DBI"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE,warning=FALSE, message=FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) ``` ## Who this tutorial is for This tutorial is for you if you want to access or manipulate data in a database that may be on your machine or on a different computer on the internet, and you have found libraries that use a higher level of abstraction, such as [dbplyr](https://dbplyr.tidyverse.org/), are not suitable for your purpose. Depending on what you want to achieve, you may find it useful to have an understanding of SQL before using DBI. The DBI (**D**ata**B**ase **I**nterface) package provides a simple, consistent interface between R and database management systems (DBMS). Each supported DBMS is supported by its own R package that implements the DBI specification in `vignette("spec", package = "DBI")`. DBI currently supports about 30 DBMS, including: * MySQL, using the R-package [RMySQL](https://github.com/r-dbi/RMySQL) * MariaDB, using the R-package [RMariaDB](https://github.com/r-dbi/RMariaDB) * Postgres, using the R-package [RPostgres](https://github.com/r-dbi/RPostgres) * SQLite, using the R-package [RSQLite](https://github.com/r-dbi/RSQLite) For a more complete list of supported DBMS visit [https://github.com/r-dbi/backends](https://github.com/r-dbi/backends#readme). You may need to install the package specific to your DBMS. The functionality currently supported for each of these DBMS's includes: - manage a connection to a database - list the tables in a database - list the column names in a table - read a table into a data frame For more advanced features, such as parameterized queries, transactions, and more see `vignette("DBI-advanced", package = "DBI")`. ## How to connect to a database using DBI The following code establishes a connection to the Sakila database hosted by the Relational Dataset Repository at `https://relational.fit.cvut.cz/dataset/Sakila`, lists all tables on the database, and closes the connection. The database represents a fictional movie rental business and includes tables describing films, actors, customers, stores, etc.: ```{r} library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) dbListTables(con) dbDisconnect(con) ``` Connections to databases are created using the `dbConnect()` function. The first argument to the function is the driver for the DBMS you are connecting to. In the example above we are connecting to a MariaDB instance, so we use the `RMariaDB::MariaDB()` driver. The other arguments depend on the authentication required by the DBMS. In the example host, port, username, password, and dbname are required. See the documentation for the DBMS driver package that you are using for specifics. The function `dbListTables()` takes a database connection as its only argument and returns a character vector with all table and view names in the database. After completing a session with a DBMS, always release the connection with a call to `dbDisconnect()`. ### Secure password storage The above example contains the password in the code, which should be avoided for databases with secured access. One way to use the credentials securely is to store it in your system's credential store and then query it with the [keyring](https://github.com/r-lib/keyring#readme) package. The code to connect to the database could then look like this: ```{r eval = FALSE} con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = keyring::key_get("relational.fit.cvut.cz", "guest"), dbname = "sakila" ) ``` ## How to retrieve column names for a table We can list the column names for a table with the function `dbListFields()`. It takes as arguments a database connection and a table name and returns a character vector of the column names in order. ```{r} con <- dbConnect(RMariaDB::MariaDB(), username = "guest", password = "relational", host = "relational.fit.cvut.cz", port = 3306, dbname = "sakila") dbListFields(con, "film") ``` ## Read a table into a data frame The function `dbReadTable()` reads an entire table and returns it as a data frame. It is equivalent to the SQL query `SELECT * FROM `. The columns of the returned data frame share the same names as the columns in the table. DBI and the database backends do their best to coerce data to equivalent R data types. ```{r} df <- dbReadTable(con, "film") head(df, 3) ``` ## Read only selected rows and columns into a data frame To read a subset of the data in a table into a data frame, DBI provides functions to run custom SQL queries and manage the results. For small datasets where you do not need to manage the number of results being returned, the function `dbGetQuery()` takes a SQL `SELECT` query to execute and returns a data frame. Below is a basic query that specifies the columns we require (`film_id`, `title` and `description`) and which rows (records) we are interested in. Here we retrieve films released in the year 2006. ```{r} df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006") head(df, 3) ``` We could also retrieve movies released in 2006 that are rated "G". Note that character strings must be quoted. As the query itself is contained within double quotes, we use single quotes around the rating. See `dbQuoteLiteral()` for programmatically converting arbitrary R values to SQL. This is covered in more detail in `vignette("DBI-advanced", package = "DBI")`. ```{r} df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006 AND rating = 'G'") head(df,3) ``` The equivalent operation using `dplyr` reconstructs the SQL query using three functions to specify the table (`tbl()`), the subset of the rows (`filter()`), and the columns we require (`select()`). Note that dplyr takes care of the quoting. ```{r message=FALSE} library(dplyr) lazy_df <- tbl(con, "film") %>% filter(release_year == 2006 & rating == "G") %>% select(film_id, title, description) head(lazy_df, 3) ``` If you want to perform other data manipulation queries such as `UPDATE`s and `DELETE`s, see `dbSendStatement()` in `vignette("DBI-advanced", package = "DBI")`. ## How to end a DBMS session When finished accessing the DBMS, always close the connection using `dbDisconnect()`. ```{r} dbDisconnect(con) ``` ## Conclusion This tutorial has given you the basic techniques for accessing data in any supported DBMS. If you need to work with databases that will not fit in memory, or want to run more complex queries, including parameterized queries, please see `vignette("DBI-advanced", package = "DBI")`. ## Further Reading * An overview on [working with databases in R on Rstudio.com](https://db.rstudio.com/) * The DBI specification: `vignette("spec", package = "DBI")` * [List of supported DBMS](https://github.com/r-dbi/backends#readme) DBI/R/0000755000176200001440000000000014157701464011062 5ustar liggesusersDBI/R/dbCanConnect.R0000644000176200001440000000165214157672512013533 0ustar liggesusers#' Check if a connection to a DBMS can be established #' #' Like [dbConnect()], but only checks validity without actually returning #' a connection object. The default implementation opens a connection #' and disconnects on success, but individual backends might implement #' a lighter-weight check. #' #' @template methods #' @templateVar method_name dbCanConnect #' #' @return A scalar logical. If `FALSE`, the `"reason"` attribute indicates #' a reason for failure. #' #' @inheritParams dbConnect #' @family DBIDriver generics #' @export #' @examples #' # SQLite only needs a path to the database. (Here, ":memory:" is a special #' # path that creates an in-memory database.) Other database drivers #' # will require more details (like user, password, host, port, etc.) #' dbCanConnect(RSQLite::SQLite(), ":memory:") setGeneric("dbCanConnect", def = function(drv, ...) standardGeneric("dbCanConnect"), valueClass = "logical" ) DBI/R/dbListFields_DBIConnection_character.R0000644000176200001440000000042714157672512020273 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbListFields_DBIConnection_character <- function(conn, name, ...) { list_fields(conn, name) } #' @rdname hidden_aliases #' @export setMethod("dbListFields", signature("DBIConnection", "character"), dbListFields_DBIConnection_character) DBI/R/dbWithTransaction_DBIConnection.R0000644000176200001440000000247114157672512017337 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbWithTransaction_DBIConnection <- function(conn, code) { ## needs to be a closure, because it accesses conn rollback_because <- function(e) { call <- dbRollback(conn) if (identical(call, FALSE)) { stop( paste( "Failed to rollback transaction.", "Tried to roll back because an error", "occurred:", conditionMessage(e) ), call. = FALSE ) } if (inherits(e, "error")) { stop(e) } } ## check if each operation is successful call <- dbBegin(conn) if (identical(call, FALSE)) { stop("Failed to begin transaction", call. = FALSE) } tryCatch( { res <- force(code) call <- dbCommit(conn) if (identical(call, FALSE)) { stop("Failed to commit transaction", call. = FALSE) } res }, dbi_abort = rollback_because, error = rollback_because ) } #' @rdname hidden_aliases #' @export setMethod("dbWithTransaction", signature("DBIConnection"), dbWithTransaction_DBIConnection) #' @export #' @rdname dbWithTransaction dbBreak <- function() { signalCondition( structure( list(message = "Aborting DBI processing", call = NULL), class = c("dbi_abort", "condition") ) ) stop("Invalid usage of dbBreak().", call. = FALSE) } DBI/R/DBIResult.R0000644000176200001440000000270714157672512013011 0ustar liggesusersNULL #' DBIResult class #' #' This virtual class describes the result and state of execution of #' a DBMS statement (any statement, query or non-query). The result set #' keeps track of whether the statement produces output how many rows were #' affected by the operation, how many rows have been fetched (if statement is #' a query), whether there are more rows to fetch, etc. #' #' @section Implementation notes: #' Individual drivers are free to allow single or multiple #' active results per connection. #' #' The default show method displays a summary of the query using other #' DBI generics. #' #' @name DBIResult-class #' @docType class #' @family DBI classes #' @family DBIResult generics #' @export setClass("DBIResult", contains = c("DBIObject", "VIRTUAL")) show_result <- function(object) { cat("<", is(object)[1], ">\n", sep = "") if (!dbIsValid(object)) { cat("EXPIRED\n") } else { cat(" SQL ", dbGetStatement(object), "\n", sep = "") done <- if (dbHasCompleted(object)) "complete" else "incomplete" cat(" ROWS Fetched: ", dbGetRowCount(object), " [", done, "]\n", sep = "") cat(" Changed: ", dbGetRowsAffected(object), "\n", sep = "") } } #' @name dbGetInfo #' @section Implementation notes: #' The default implementation for `DBIResult objects` #' constructs such a list from the return values of the corresponding methods, #' [dbGetStatement()], [dbGetRowCount()], #' [dbGetRowsAffected()], and [dbHasCompleted()]. NULL DBI/R/show_DBIConnector.R0000644000176200001440000000051114157672512014514 0ustar liggesusers#' @rdname hidden_aliases #' @param object Object to display #' @usage NULL show_DBIConnector <- function(object) { cat("") show(object@.drv) cat("Arguments:\n") show(object@.conn_args) invisible(NULL) } #' @rdname hidden_aliases #' @export setMethod("show", signature("DBIConnector"), show_DBIConnector) DBI/R/transactions.R0000644000176200001440000000362214157672512013721 0ustar liggesusers#' Begin/commit/rollback SQL transactions #' #' A transaction encapsulates several SQL statements in an atomic unit. #' It is initiated with `dbBegin()` and either made persistent with `dbCommit()` #' or undone with `dbRollback()`. #' In any case, the DBMS guarantees that either all or none of the statements #' have a permanent effect. #' This helps ensuring consistency of write operations to multiple tables. #' #' Not all database engines implement transaction management, in which case #' these methods should not be implemented for the specific #' [DBIConnection-class] subclass. #' #' @template methods #' @templateVar method_name transactions #' #' @inherit DBItest::spec_transaction_begin_commit_rollback return #' @inheritSection DBItest::spec_transaction_begin_commit_rollback Failure modes #' @inheritSection DBItest::spec_transaction_begin_commit_rollback Specification #' #' @inheritParams dbGetQuery #' @seealso Self-contained transactions: [dbWithTransaction()] #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "cash", data.frame(amount = 100)) #' dbWriteTable(con, "account", data.frame(amount = 2000)) #' #' # All operations are carried out as logical unit: #' dbBegin(con) #' withdrawal <- 300 #' dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) #' dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) #' dbCommit(con) #' #' dbReadTable(con, "cash") #' dbReadTable(con, "account") #' #' # Rolling back after detecting negative value on account: #' dbBegin(con) #' withdrawal <- 5000 #' dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) #' dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) #' if (dbReadTable(con, "account")$amount >= 0) { #' dbCommit(con) #' } else { #' dbRollback(con) #' } #' #' dbReadTable(con, "cash") #' dbReadTable(con, "account") #' #' dbDisconnect(con) NULL DBI/R/dbDisconnect.R0000644000176200001440000000111314157672512013601 0ustar liggesusers#' Disconnect (close) a connection #' #' This closes the connection, discards all pending work, and frees #' resources (e.g., memory, sockets). #' #' @template methods #' @templateVar method_name dbDisconnect #' #' @inherit DBItest::spec_connection_disconnect return #' @inheritSection DBItest::spec_connection_disconnect Failure modes #' #' @inheritParams dbGetQuery #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbDisconnect(con) setGeneric("dbDisconnect", def = function(conn, ...) standardGeneric("dbDisconnect") ) DBI/R/rownames.R0000644000176200001440000000526214157672512013046 0ustar liggesusers#' Convert row names back and forth between columns #' #' These functions provide a reasonably automatic way of preserving the row #' names of data frame during back-and-forth translation to an SQL table. #' By default, row names will be converted to an explicit column #' called "row_names", and any query returning a column called "row_names" #' will have those automatically set as row names. #' These methods are mostly useful for backend implementers. #' #' @param df A data frame #' @param row.names Either `TRUE`, `FALSE`, `NA` or a string. #' #' If `TRUE`, always translate row names to a column called "row_names". #' If `FALSE`, never translate row names. If `NA`, translate #' rownames only if they're a character vector. #' #' A string is equivalent to `TRUE`, but allows you to override the #' default name. #' #' For backward compatibility, `NULL` is equivalent to `FALSE`. #' @name rownames #' @examples #' # If have row names #' sqlRownamesToColumn(head(mtcars)) #' sqlRownamesToColumn(head(mtcars), FALSE) #' sqlRownamesToColumn(head(mtcars), "ROWNAMES") #' #' # If don't have #' sqlRownamesToColumn(head(iris)) #' sqlRownamesToColumn(head(iris), TRUE) #' sqlRownamesToColumn(head(iris), "ROWNAMES") NULL #' @export #' @rdname rownames sqlRownamesToColumn <- function(df, row.names = NA) { name <- guessRowName(df, row.names) if (is.null(name)) { rownames(df) <- NULL return(df) } rn <- stats::setNames(list(row.names(df)), name) df <- c(rn, df) class(df) <- "data.frame" attr(df, "row.names") <- .set_row_names(length(rn[[1]])) df } #' @export #' @rdname rownames sqlColumnToRownames <- function(df, row.names = NA) { name <- guessColName(df, row.names) if (is.null(name)) return(df) if (!(name %in% names(df))) { stop("Column ", name, " not present in output", call. = FALSE) } row.names(df) <- df[[name]] df[[name]] <- NULL df } guessRowName <- function(df, row.names) { if (identical(row.names, TRUE)) { "row_names" } else if (identical(row.names, FALSE) || is.null(row.names)) { NULL } else if (identical(row.names, NA)) { is_char <- is.character(attr(df, "row.names")) if (is_char) { "row_names" } else { NULL } } else if (is.character(row.names)) { row.names[1] } else { stop("Unknown input") } } guessColName <- function(df, row.names) { if (identical(row.names, TRUE)) { "row_names" } else if (identical(row.names, FALSE) || is.null(row.names)) { NULL } else if (identical(row.names, NA)) { if ("row_names" %in% names(df)) { "row_names" } else { NULL } } else if (is.character(row.names)) { row.names[1] } else { stop("Unknown input") } } DBI/R/dbiDataType_character.R0000644000176200001440000000030614157672512015413 0ustar liggesusersdbiDataType_character <- function(x) { "TEXT" } setMethod("dbiDataType", signature("character"), dbiDataType_character) setMethod("dbiDataType", signature("factor"), dbiDataType_character) DBI/R/dbFetch_DBIResult.R0000644000176200001440000000033314157672512014421 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbFetch_DBIResult <- function(res, n = -1, ...) { fetch(res, n = n, ...) } #' @rdname hidden_aliases #' @export setMethod("dbFetch", signature("DBIResult"), dbFetch_DBIResult) DBI/R/dbDriver.R0000644000176200001440000000324614157672512012754 0ustar liggesusers#' Load and unload database drivers #' #' @description #' These methods are deprecated, please consult the documentation of the #' individual backends for the construction of driver instances. #' #' `dbDriver()` is a helper method used to create an new driver object #' given the name of a database or the corresponding R package. It works #' through convention: all DBI-extending packages should provide an exported #' object with the same name as the package. `dbDriver()` just looks for #' this object in the right places: if you know what database you are connecting #' to, you should call the function directly. #' #' @details #' The client part of the database communication is #' initialized (typically dynamically loading C code, etc.) but note that #' connecting to the database engine itself needs to be done through calls to #' `dbConnect`. #' #' @param drvName character name of the driver to instantiate. #' @param drv an object that inherits from `DBIDriver` as created by #' `dbDriver`. #' @param ... any other arguments are passed to the driver `drvName`. #' @return In the case of `dbDriver`, an driver object whose class extends #' `DBIDriver`. This object may be used to create connections to the #' actual DBMS engine. #' #' In the case of `dbUnloadDriver`, a logical indicating whether the #' operation succeeded or not. #' @import methods #' @family DBIDriver generics #' @export #' @keywords internal #' @examples #' # Create a RSQLite driver with a string #' d <- dbDriver("SQLite") #' d #' #' # But better, access the object directly #' RSQLite::SQLite() setGeneric("dbDriver", def = function(drvName, ...) standardGeneric("dbDriver"), valueClass = "DBIDriver" ) DBI/R/dbIsReadOnly_DBIObject.R0000644000176200001440000000027514157672512015336 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbIsReadOnly_DBIObject <- function(dbObj, ...) { FALSE } #' @rdname hidden_aliases setMethod("dbIsReadOnly", "DBIObject", dbIsReadOnly_DBIObject) DBI/R/dbDriver_character.R0000644000176200001440000000032114157672512014757 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbDriver_character <- function(drvName, ...) { findDriver(drvName)(...) } #' @rdname hidden_aliases setMethod("dbDriver", signature("character"), dbDriver_character) DBI/R/show_DBIDriver.R0000644000176200001440000000061114157672512014016 0ustar liggesusers#' @rdname hidden_aliases #' @param object Object to display #' @usage NULL show_DBIDriver <- function(object) { tryCatch( # to protect drivers that fail to implement the required methods (e.g., # RPostgreSQL) show_driver(object), error = function(e) NULL ) invisible(NULL) } #' @rdname hidden_aliases #' @export setMethod("show", signature("DBIDriver"), show_DBIDriver) DBI/R/dbGetInfo_DBIResult.R0000644000176200001440000000055014157672512014724 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetInfo_DBIResult <- function(dbObj, ...) { list( statement = dbGetStatement(dbObj), row.count = dbGetRowCount(dbObj), rows.affected = dbGetRowsAffected(dbObj), has.completed = dbHasCompleted(dbObj) ) } #' @rdname hidden_aliases setMethod("dbGetInfo", signature("DBIResult"), dbGetInfo_DBIResult) DBI/R/show_DBIConnection.R0000644000176200001440000000061214157672512014663 0ustar liggesusers#' @rdname hidden_aliases #' @param object Object to display #' @usage NULL show_DBIConnection <- function(object) { # to protect drivers that fail to implement the required methods (e.g., # RPostgreSQL) tryCatch( show_connection(object), error = function(e) NULL ) invisible(NULL) } #' @rdname hidden_aliases #' @export setMethod("show", "DBIConnection", show_DBIConnection) DBI/R/dbiDataType_list.R0000644000176200001440000000037514157672512014440 0ustar liggesusersdbiDataType_list <- function(x) { is_raw <- vapply(x, is.raw, logical(1)) if (!all(is_raw)) { stop("Only lists of raw vectors are currently supported", call. = FALSE) } "BLOB" } setMethod("dbiDataType", signature("list"), dbiDataType_list) DBI/R/dbListTables.R0000644000176200001440000000144414157672512013565 0ustar liggesusers#' List remote tables #' #' Returns the unquoted names of remote tables accessible through this #' connection. #' This should include views and temporary objects, but not all database backends #' (in particular \pkg{RMariaDB} and \pkg{RMySQL}) support this. #' #' @template methods #' @templateVar method_name dbListTables #' #' @inherit DBItest::spec_sql_list_tables return #' @inheritSection DBItest::spec_sql_list_tables Failure modes #' #' @inheritParams dbGetQuery #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbListTables(con) #' dbWriteTable(con, "mtcars", mtcars) #' dbListTables(con) #' #' dbDisconnect(con) setGeneric("dbListTables", def = function(conn, ...) standardGeneric("dbListTables"), valueClass = "character" ) DBI/R/dbUnquoteIdentifier_DBIConnection.R0000644000176200001440000000223614157672512017660 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbUnquoteIdentifier_DBIConnection <- function(conn, x, ...) { if (is(x, "SQL")) { id_rx <- '(?:"((?:[^"]|"")+)"|([^". ]+))' rx <- paste0( "^", "(?:|(?:|", id_rx, "[.])", id_rx, "[.])", "(?:|", id_rx, ")", "$" ) bad <- grep(rx, x, invert = TRUE) if (length(bad) > 0) { stop("Can't unquote ", x[bad[[1]]], call. = FALSE) } catalog <- gsub(rx, "\\1\\2", x) catalog <- gsub('""', '"', catalog) schema <- gsub(rx, "\\3\\4", x) schema <- gsub('""', '"', schema) table <- gsub(rx, "\\5\\6", x) table <- gsub('""', '"', table) ret <- Map(catalog, schema, table, f = as_table) names(ret) <- names(x) return(ret) } if (is(x, "Id")) { return(list(x)) } stop("x must be SQL or Id", call. = FALSE) } #' @rdname hidden_aliases #' @export setMethod("dbUnquoteIdentifier", signature("DBIConnection"), dbUnquoteIdentifier_DBIConnection) as_table <- function(catalog, schema, table) { args <- c(catalog = catalog, schema = schema, table = table) # Also omits NA args args <- args[!is.na(args) & args != ""] do.call(Id, as.list(args)) } DBI/R/dbListFields_DBIConnection_Id.R0000644000176200001440000000040214157672512016664 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbListFields_DBIConnection_Id <- function(conn, name, ...) { list_fields(conn, name) } #' @rdname hidden_aliases #' @export setMethod("dbListFields", signature("DBIConnection", "Id"), dbListFields_DBIConnection_Id) DBI/R/dbColumnInfo.R0000644000176200001440000000155114157672512013567 0ustar liggesusers#' Information about result types #' #' Produces a data.frame that describes the output of a query. The data.frame #' should have as many rows as there are output fields in the result set, and #' each column in the data.frame describes an aspect of the result set #' field (field name, type, etc.) #' #' @inheritParams dbClearResult #' #' @inherit DBItest::spec_meta_column_info return #' @inheritSection DBItest::spec_meta_column_info Failure modes #' @inheritSection DBItest::spec_meta_column_info Specification #' #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' rs <- dbSendQuery(con, "SELECT 1 AS a, 2 AS b") #' dbColumnInfo(rs) #' dbFetch(rs) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbColumnInfo", def = function(res, ...) standardGeneric("dbColumnInfo"), valueClass = "data.frame" ) DBI/R/dbSendStatement.R0000644000176200001440000000435714157672512014303 0ustar liggesusers#' Execute a data manipulation statement on a given database connection #' #' The `dbSendStatement()` method only submits and synchronously executes the #' SQL data manipulation statement (e.g., `UPDATE`, `DELETE`, #' `INSERT INTO`, `DROP TABLE`, ...) to the database engine. To query #' the number of affected rows, call [dbGetRowsAffected()] on the #' returned result object. You must also call [dbClearResult()] after #' that. For interactive use, you should almost always prefer #' [dbExecute()]. #' #' [dbSendStatement()] comes with a default implementation that simply #' forwards to [dbSendQuery()], to support backends that only #' implement the latter. #' #' @template methods #' @templateVar method_name dbSendStatement #' #' @inherit DBItest::spec_result_send_statement return #' @inheritSection DBItest::spec_result_send_statement Failure modes #' @inheritSection DBItest::spec_result_send_statement Additional arguments #' @inheritSection DBItest::spec_result_send_statement Specification #' @inheritSection DBItest::spec_result_send_statement Specification for the `immediate` argument #' #' @inheritParams dbGetQuery #' @param statement a character string containing SQL. #' #' @family DBIConnection generics #' @seealso For queries: [dbSendQuery()] and [dbGetQuery()]. #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "cars", head(cars, 3)) #' #' rs <- dbSendStatement( #' con, #' "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" #' ) #' dbHasCompleted(rs) #' dbGetRowsAffected(rs) #' dbClearResult(rs) #' dbReadTable(con, "cars") # there are now 6 rows #' #' # Pass one set of values directly using the param argument: #' rs <- dbSendStatement( #' con, #' "INSERT INTO cars (speed, dist) VALUES (?, ?)", #' params = list(4L, 5L) #' ) #' dbClearResult(rs) #' #' # Pass multiple sets of values using dbBind(): #' rs <- dbSendStatement( #' con, #' "INSERT INTO cars (speed, dist) VALUES (?, ?)" #' ) #' dbBind(rs, list(5:6, 6:7)) #' dbBind(rs, list(7L, 8L)) #' dbClearResult(rs) #' dbReadTable(con, "cars") # there are now 10 rows #' #' dbDisconnect(con) #' @export setGeneric("dbSendStatement", def = function(conn, statement, ...) standardGeneric("dbSendStatement"), valueClass = "DBIResult" ) DBI/R/dbSendStatement_DBIConnection_character.R0000644000176200001440000000045714157672512021012 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbSendStatement_DBIConnection_character <- function(conn, statement, ...) { dbSendQuery(conn, statement, ...) } #' @rdname hidden_aliases #' @export setMethod("dbSendStatement", signature("DBIConnection", "character"), dbSendStatement_DBIConnection_character) DBI/R/dbGetInfo.R0000644000176200001440000000104614157672512013050 0ustar liggesusers#' Get DBMS metadata #' #' Retrieves information on objects of class [DBIDriver-class], #' [DBIConnection-class] or [DBIResult-class]. #' #' @param dbObj An object inheriting from [DBIObject-class], #' i.e. [DBIDriver-class], [DBIConnection-class], #' or a [DBIResult-class] #' @param ... Other arguments to methods. #' @family DBIDriver generics #' @family DBIConnection generics #' @family DBIResult generics #' @inherit DBItest::spec_get_info return #' @export setGeneric("dbGetInfo", def = function(dbObj, ...) standardGeneric("dbGetInfo") ) DBI/R/dbExistsTable_DBIConnection_Id.R0000644000176200001440000000044514157672512017060 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbExistsTable_DBIConnection_Id <- function(conn, name, ...) { dbExistsTable(conn, dbQuoteIdentifier(conn, name), ...) } #' @rdname hidden_aliases #' @export setMethod("dbExistsTable", signature("DBIConnection", "Id"), dbExistsTable_DBIConnection_Id) DBI/R/dbiDataType_POSIXct.R0000644000176200001440000000020314157672512014704 0ustar liggesusers#' @usage NULL dbiDataType_POSIXct <- function(x) "TIMESTAMP" setMethod("dbiDataType", signature("POSIXct"), dbiDataType_POSIXct) DBI/R/interpolate.R0000644000176200001440000000745114157672512013543 0ustar liggesusersNULL #' @export #' @rdname sqlParseVariables sqlCommentSpec <- function(start, end, endRequired) { list(start = start, end = end, endRequired = endRequired) } #' @export #' @rdname sqlParseVariables sqlQuoteSpec <- function(start, end, escape = "", doubleEscape = TRUE) { list(start = start, end = end, escape = escape, doubleEscape = doubleEscape) } #' @export #' @rdname sqlParseVariables #' @param sql SQL to parse (a character string) #' @param quotes A list of `QuoteSpec` calls defining the quoting #' specification. #' @param comments A list of `CommentSpec` calls defining the commenting #' specification. sqlParseVariablesImpl <- function(sql, quotes, comments) { str_to_vec <- function(s) strsplit(s, "", fixed = TRUE)[[1L]] sql_arr <- c(str_to_vec(as.character(sql)), " ") # characters valid in variable names var_chars <- c(LETTERS, letters, 0:9, "_") # return values var_pos_start <- integer() var_pos_end <- integer() # internal helper variables quote_spec_offset <- 0L comment_spec_offset <- 0L sql_variable_start <- 0L # prepare comments & quotes for quicker comparisions for (c in seq_along(comments)) { comments[[c]][["start"]] <- str_to_vec(comments[[c]][["start"]]) comments[[c]][["end"]] <- str_to_vec(comments[[c]][["end"]]) } for (q in seq_along(quotes)) { quotes[[q]][["hasEscape"]] <- nchar(quotes[[q]][["escape"]]) > 0L } state <- "default" i <- 0L while (i < length(sql_arr)) { i <- i + 1L switch(state, default = { # variable if (sql_arr[[i]] == "?") { sql_variable_start <- i state <- "variable" next } # starting quoted area for (q in seq_along(quotes)) { if (identical(sql_arr[[i]], quotes[[q]][["start"]])) { quote_spec_offset <- q state <- "quote" break } } # we can abort here if the state has changed if (state != "default") next # starting comment for (c in seq_along(comments)) { comment_start_arr <- comments[[c]][["start"]] comment_start_length <- length(comment_start_arr) if (identical(sql_arr[i:(i + comment_start_length - 1L)], comment_start_arr)) { comment_spec_offset <- c i <- i + comment_start_length state <- "comment" break } } }, variable = { if (!(sql_arr[[i]] %in% var_chars)) { # append current variable offsets to return vectors var_pos_start <- c(var_pos_start, sql_variable_start) # we have already read too much, go back i <- i - 1L var_pos_end <- c(var_pos_end, i) state <- "default" } }, quote = { # if we see backslash-like escapes, ignore next character if (quotes[[quote_spec_offset]][["hasEscape"]] && identical(sql_arr[[i]], quotes[[quote_spec_offset]][[3]])) { i <- i + 1L next } # end quoted area if (identical(sql_arr[[i]], quotes[[quote_spec_offset]][["end"]])) { quote_spec_offset <- 0L state <- "default" } }, comment = { # end commented area comment_end_arr <- comments[[comment_spec_offset]][["end"]] comment_end_length <- length(comment_end_arr) if (identical(sql_arr[i:(i + comment_end_length - 1L)], comment_end_arr)) { i <- i + (comment_end_length - 1) comment_spec_offset <- 0L state <- "default" } } ) # } # if (quote_spec_offset > 0L) { stop("Unterminated literal") } if (comment_spec_offset > 0L && comments[[comment_spec_offset]][["endRequired"]]) { stop("Unterminated comment") } list(start = var_pos_start, end = var_pos_end) } DBI/R/sqlCreateTable.R0000644000176200001440000000335114157672512014103 0ustar liggesusers#' Compose query to create a simple table #' #' Exposes an interface to simple `CREATE TABLE` commands. The default #' method is ANSI SQL 99 compliant. #' This method is mostly useful for backend implementers. #' #' The `row.names` argument must be passed explicitly in order to avoid #' a compatibility warning. The default will be changed in a later release. #' #' @param con A database connection. #' @param table The table name, passed on to [dbQuoteIdentifier()]. Options are: #' - a character string with the unquoted DBMS table name, #' e.g. `"table_name"`, #' - a call to [Id()] with components to the fully qualified table name, #' e.g. `Id(schema = "my_schema", table = "table_name")` #' - a call to [SQL()] with the quoted and fully qualified table name #' given verbatim, e.g. `SQL('"my_schema"."table_name"')` #' @param fields Either a character vector or a data frame. #' #' A named character vector: Names are column names, values are types. #' Names are escaped with [dbQuoteIdentifier()]. #' Field types are unescaped. #' #' A data frame: field types are generated using #' [dbDataType()]. #' @param temporary If `TRUE`, will generate a temporary table statement. #' @inheritParams rownames #' @param ... Other arguments used by individual methods. #' @export #' @examples #' sqlCreateTable(ANSI(), "my-table", c(a = "integer", b = "text")) #' sqlCreateTable(ANSI(), "my-table", iris) #' #' # By default, character row names are converted to a row_names colum #' sqlCreateTable(ANSI(), "mtcars", mtcars[, 1:5]) #' sqlCreateTable(ANSI(), "mtcars", mtcars[, 1:5], row.names = FALSE) setGeneric("sqlCreateTable", def = function(con, table, fields, row.names = NA, temporary = FALSE, ...) standardGeneric("sqlCreateTable") ) DBI/R/summary_DBIObject.R0000644000176200001440000000063214157672512014511 0ustar liggesusers#' @usage NULL summary_DBIObject <- function(object, ...) { info <- dbGetInfo(dbObj = object, ...) cat(class(object), "\n") print_list_pairs(info) invisible(info) } setMethod("summary", "DBIObject", summary_DBIObject) print_list_pairs <- function(x, ...) { for (key in names(x)) { value <- format(x[[key]]) if (identical(value, "")) next cat(key, "=", value, "\n") } invisible(x) } DBI/R/dbDataType_DBIConnector.R0000644000176200001440000000036614157672512015565 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbDataType_DBIConnector <- function(dbObj, obj, ...) { dbDataType(dbObj@.drv, obj, ...) } #' @rdname hidden_aliases #' @export setMethod("dbDataType", signature("DBIConnector"), dbDataType_DBIConnector) DBI/R/dbWriteTable.R0000644000176200001440000000332114157701453013552 0ustar liggesusers#' Copy data frames to database tables #' #' Writes, overwrites or appends a data frame to a database table, optionally #' converting row names to a column and specifying SQL data types for fields. #' #' @details #' This function is useful if you want to create and load a table at the same time. #' Use [dbAppendTable()] for appending data to a table, #' and [dbCreateTable()], [dbExistsTable()] and [dbRemoveTable()] #' for more control over the individual operations. #' #' DBI only standardizes writing data frames. #' Some backends might implement methods that can consume CSV files #' or other data formats. #' For details, see the documentation for the individual methods. #' #' @template methods #' @templateVar method_name dbWriteTable #' #' @inherit DBItest::spec_sql_write_table return #' @inheritSection DBItest::spec_sql_write_table Failure modes #' @inheritSection DBItest::spec_sql_write_table Additional arguments #' @inheritSection DBItest::spec_sql_write_table Specification #' #' @inheritParams dbGetQuery #' @inheritParams dbReadTable #' @param value a [data.frame] (or coercible to data.frame). #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars[1:5, ]) #' dbReadTable(con, "mtcars") #' #' dbWriteTable(con, "mtcars", mtcars[6:10, ], append = TRUE) #' dbReadTable(con, "mtcars") #' #' dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE) #' dbReadTable(con, "mtcars") #' #' # No row names #' dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE, row.names = FALSE) #' dbReadTable(con, "mtcars") #' @export setGeneric("dbWriteTable", def = function(conn, name, value, ...) standardGeneric("dbWriteTable") ) DBI/R/deprecated.R0000644000176200001440000001025414157672512013310 0ustar liggesusersNULL ## produce legal SQL identifiers from strings in a character vector ## unique, in this function, means unique regardless of lower/upper case #' @rdname make.db.names #' @export make.db.names.default <- function(snames, keywords = .SQL92Keywords, unique = TRUE, allow.keywords = TRUE) { makeUnique <- function(x, sep = "_") { if (length(x) == 0) return(x) out <- x lc <- make.names(tolower(x), unique = FALSE) i <- duplicated(lc) lc <- make.names(lc, unique = TRUE) out[i] <- paste(out[i], substring(lc[i], first = nchar(out[i]) + 1), sep = sep) out } ## Note: SQL identifiers *can* be enclosed in double or single quotes ## when they are equal to reserverd keywords. fc <- substring(snames, 1, 1) lc <- substring(snames, nchar(snames)) i <- match(fc, c("'", '"'), 0) > 0 & match(lc, c("'", '"'), 0) > 0 snames[!i] <- make.names(snames[!i], unique = FALSE) if (unique) { snames[!i] <- makeUnique(snames[!i]) } if (!allow.keywords) { kwi <- match(keywords, toupper(snames), nomatch = 0L) snames[kwi] <- paste('"', snames[kwi], '"', sep = "") } gsub("\\.", "_", snames) } #' @rdname make.db.names #' @export isSQLKeyword.default <- function(name, keywords = .SQL92Keywords, case = c("lower", "upper", "any")[3]) { n <- pmatch(case, c("lower", "upper", "any"), nomatch = 0) if (n == 0) { stop('case must be one of "lower", "upper", or "any"') } kw <- switch(c("lower", "upper", "any")[n], lower = tolower(keywords), upper = toupper(keywords), any = toupper(keywords) ) if (n == 3) { name <- toupper(name) } match(name, keywords, nomatch = 0) > 0 } #' @export .SQL92Keywords <- c( "ABSOLUTE", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHARACTER_LENGTH", "CHAR_LENGTH", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "COUNT", "CREATE", "CURRENT", "CURRENT_DATE", "CURRENT_TIMESTAMP", "CURRENT_TYPE", "CURSOR", "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR", "DIAGNOSTICS", "DICONNECT", "DICTIONATRY", "DISPLACEMENT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP", "ELSE", "END", "END-EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL", "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IGNORE", "IMMEDIATE", "IN", "INCLUDE", "INDEX", "INDICATOR", "INITIALLY", "INNER", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO", "IS", "ISOLATION", "JOIN", "KEY", "LANGUAGE", "LAST", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER", "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH", "NAMES", "NATIONAL", "NCHAR", "NEXT", "NOT", "NULL", "NULLIF", "NUMERIC", "OCTECT_LENGTH", "OF", "OFF", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS", "PARTIAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL", "REFERENCES", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK", "ROWS", "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SET", "SIZE", "SMALLINT", "SOME", "SQL", "SQLCA", "SQLCODE", "SQLERROR", "SQLSTATE", "SQLWARNING", "SUBSTRING", "SUM", "SYSTEM", "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USAGE", "USER", "USING", "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE", "YEAR", "ZONE" ) #' Determine the current version of the package. #' #' @export #' @keywords internal dbGetDBIVersion <- function() { .Deprecated("packageVersion('DBI')") utils::packageVersion("DBI") } DBI/R/dbiDataType_Date.R0000644000176200001440000000016514157672512014337 0ustar liggesusers#' @usage NULL dbiDataType_Date <- function(x) "DATE" setMethod("dbiDataType", signature("Date"), dbiDataType_Date) DBI/R/dbGetConnectArgs_DBIConnector.R0000644000176200001440000000061414157672512016714 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetConnectArgs_DBIConnector <- function(drv, eval = TRUE, ...) { conn_args <- drv@.conn_args if (isTRUE(eval)) { conn_args <- lapply(conn_args, function(x) { if (is.function(x)) x() else x }) } conn_args } #' @rdname hidden_aliases #' @export setMethod("dbGetConnectArgs", signature("DBIConnector"), dbGetConnectArgs_DBIConnector) DBI/R/sqlParseVariables_DBIConnection.R0000644000176200001440000000067414157672512017336 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL sqlParseVariables_DBIConnection <- function(conn, sql, ...) { sqlParseVariablesImpl( sql, list( sqlQuoteSpec('"', '"'), sqlQuoteSpec("'", "'") ), list( sqlCommentSpec("/*", "*/", TRUE), sqlCommentSpec("--", "\n", FALSE) ) ) } #' @rdname hidden_aliases #' @export setMethod("sqlParseVariables", signature("DBIConnection"), sqlParseVariables_DBIConnection) DBI/R/DBIConnector.R0000644000176200001440000000275014157672512013463 0ustar liggesusersNULL #' DBIConnector class #' #' Wraps objects of the [DBIDriver-class] class to include connection options. #' The purpose of this class is to store both the driver #' and the connection options. #' A database connection can be established #' with a call to [dbConnect()], passing only that object #' without additional arguments. #' #' To prevent leakage of passwords and other credentials, #' this class supports delayed evaluation. #' All arguments can optionally be a function (callable without arguments). #' In such a case, the function is evaluated transparently when connecting in #' [dbGetConnectArgs()]. #' # FIXME: Include this # Database backends can take advantage of this feature by returning an # instance of this class instead of `DBIDriver`. # See the implementation of [RSQLite::SQLite()] for an example. #' #' @docType class #' @name DBIConnector-class #' @family DBI classes #' @family DBIConnector generics #' @export #' @examples #' # Create a connector: #' cnr <- new("DBIConnector", #' .drv = RSQLite::SQLite(), #' .conn_args = list(dbname = ":memory:") #' ) #' cnr #' #' # Establish a connection through this connector: #' con <- dbConnect(cnr) #' con #' #' # Access the database through this connection: #' dbGetQuery(con, "SELECT 1 AS a") #' dbDisconnect(con) setClass("DBIConnector", slots = c(".drv" = "DBIDriver", ".conn_args" = "list"), contains = c("DBIObject") ) names2 <- function(x) { if (is.null(names(x))) { rep("", length(x)) } else { names(x) } } DBI/R/make.db.names_DBIObject_character.R0000644000176200001440000000057314157672512017437 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL make.db.names_DBIObject_character <- function(dbObj, snames, keywords, unique, allow.keywords, ...) { make.db.names.default(snames, keywords, unique, allow.keywords) } #' @rdname hidden_aliases setMethod("make.db.names", signature(dbObj = "DBIObject", snames = "character"), make.db.names_DBIObject_character, valueClass = "character") DBI/R/sqlParseVariables.R0000644000176200001440000000214014157672512014626 0ustar liggesusers#' Parse interpolated variables from SQL. #' #' If you're implementing a backend that uses non-ANSI quoting or commenting #' rules, you'll need to implement a method for `sqlParseVariables` that #' calls `sqlParseVariablesImpl` with the appropriate quote and #' comment specifications. #' #' #' @param start,end Start and end characters for quotes and comments #' @param endRequired Is the ending character of a comment required? #' @param doubleEscape Can quoting characters be escaped by doubling them? #' Defaults to `TRUE`. #' @param escape What character can be used to escape quoting characters? #' Defaults to `""`, i.e. nothing. #' @keywords internal #' @export #' @examples #' # Use [] for quoting and no comments #' sqlParseVariablesImpl("[?a]", #' list(sqlQuoteSpec("[", "]", "\\", FALSE)), #' list() #' ) #' #' # Standard quotes, use # for commenting #' sqlParseVariablesImpl("# ?a\n?b", #' list(sqlQuoteSpec("'", "'"), sqlQuoteSpec('"', '"')), #' list(sqlCommentSpec("#", "\n", FALSE)) #' ) setGeneric("sqlParseVariables", def = function(conn, sql, ...) standardGeneric("sqlParseVariables") ) DBI/R/sqlInterpolate.R0000644000176200001440000000576214157672512014226 0ustar liggesusers#' Safely interpolate values into an SQL string #' #' @description #' Accepts a query string with placeholders for values, and returns a string #' with the values embedded. #' The function is careful to quote all of its inputs with [dbQuoteLiteral()] #' to protect against SQL injection attacks. #' #' Placeholders can be specified with one of two syntaxes: #' #' - `?`: each occurrence of a standalone `?` is replaced with a value #' - `?name1`, `?name2`, ...: values are given as named arguments or a #' named list, the names are used to match the values #' #' Mixing `?` and `?name` syntaxes is an error. #' The number and names of values supplied must correspond to the placeholders #' used in the query. #' #' @section Backend authors: #' If you are implementing an SQL backend with non-ANSI quoting rules, you'll #' need to implement a method for [sqlParseVariables()]. Failure to #' do so does not expose you to SQL injection attacks, but will (rarely) result #' in errors matching supplied and interpolated variables. #' #' @inheritParams dbGetQuery #' @param sql A SQL string containing variables to interpolate. #' Variables must start with a question mark and can be any valid R #' identifier, i.e. it must start with a letter or `.`, and be followed #' by a letter, digit, `.` or `_`. #' @param ...,.dots Values (for `...`) or a list (for `.dots`) #' to interpolate into a string. #' Names are required if `sql` uses the `?name` syntax for placeholders. #' All values will be first escaped with [dbQuoteLiteral()] prior #' to interpolation to protect against SQL injection attacks. #' Arguments created by [SQL()] or [dbQuoteIdentifier()] remain unchanged. #' @return The `sql` query with the values from `...` and `.dots` safely #' embedded. #' @export #' @examples #' sql <- "SELECT * FROM X WHERE name = ?name" #' sqlInterpolate(ANSI(), sql, name = "Hadley") #' #' # This is safe because the single quote has been double escaped #' sqlInterpolate(ANSI(), sql, name = "H'); DROP TABLE--;") #' #' # Using paste0() could lead to dangerous SQL with carefully crafted inputs #' # (SQL injection) #' name <- "H'); DROP TABLE--;" #' paste0("SELECT * FROM X WHERE name = '", name, "'") #' #' # Use SQL() or dbQuoteIdentifier() to avoid escaping #' sql2 <- "SELECT * FROM ?table WHERE name in ?names" #' sqlInterpolate(ANSI(), sql2, #' table = dbQuoteIdentifier(ANSI(), "X"), #' names = SQL("('a', 'b')") #' ) #' #' # Don't use SQL() to escape identifiers to avoid SQL injection #' sqlInterpolate(ANSI(), sql2, #' table = SQL("X; DELETE FROM X; SELECT * FROM X"), #' names = SQL("('a', 'b')") #' ) #' #' # Use dbGetQuery() or dbExecute() to process these queries: #' if (requireNamespace("RSQLite", quietly = TRUE)) { #' con <- dbConnect(RSQLite::SQLite()) #' sql <- "SELECT ?value AS value" #' query <- sqlInterpolate(con, sql, value = 3) #' print(dbGetQuery(con, query)) #' dbDisconnect(con) #' } setGeneric("sqlInterpolate", def = function(conn, sql, ..., .dots = list()) standardGeneric("sqlInterpolate") ) DBI/R/dbReadTable_DBIConnection_character.R0000644000176200001440000000155214157672512020054 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbReadTable_DBIConnection_character <- function(conn, name, ..., row.names = FALSE, check.names = TRUE) { sql_name <- dbQuoteIdentifier(conn, x = name, ...) if (length(sql_name) != 1L) { stop("Invalid name: ", format(name), call. = FALSE) } if (!is.null(row.names)) { stopifnot(length(row.names) == 1L) stopifnot(is.logical(row.names) || is.character(row.names)) } stopifnot(length(check.names) == 1L) stopifnot(is.logical(check.names)) stopifnot(!is.na(check.names)) out <- dbGetQuery(conn, paste0("SELECT * FROM ", sql_name)) out <- sqlColumnToRownames(out, row.names) if (check.names) { names(out) <- make.names(names(out), unique = TRUE) } out } #' @rdname hidden_aliases #' @export setMethod("dbReadTable", signature("DBIConnection", "character"), dbReadTable_DBIConnection_character) DBI/R/dbQuoteLiteral.R0000644000176200001440000000253714157672512014135 0ustar liggesusers#' Quote literal values #' #' @description #' Call these methods to generate a string that is suitable for #' use in a query as a literal value of the correct type, to make sure that you #' generate valid SQL and protect against SQL injection attacks. #' #' @inheritParams dbQuoteString #' @param x A vector to quote as string. #' #' @template methods #' @templateVar method_name dbQuoteLiteral #' #' @inherit DBItest::spec_sql_quote_literal return #' @inheritSection DBItest::spec_sql_quote_literal Failure modes #' @inheritSection DBItest::spec_sql_quote_literal Specification #' #' @family DBIResult generics #' @export #' @examples #' # Quoting ensures that arbitrary input is safe for use in a query #' name <- "Robert'); DROP TABLE Students;--" #' dbQuoteLiteral(ANSI(), name) #' #' # NAs become NULL #' dbQuoteLiteral(ANSI(), c(1:3, NA)) #' #' # Logicals become integers by default #' dbQuoteLiteral(ANSI(), c(TRUE, FALSE, NA)) #' #' # Raw vectors become hex strings by default #' dbQuoteLiteral(ANSI(), list(as.raw(1:3), NULL)) #' #' # SQL vectors are always passed through as is #' var_name <- SQL("select") #' var_name #' dbQuoteLiteral(ANSI(), var_name) #' #' # This mechanism is used to prevent double escaping #' dbQuoteLiteral(ANSI(), dbQuoteLiteral(ANSI(), name)) setGeneric("dbQuoteLiteral", def = function(conn, x, ...) standardGeneric("dbQuoteLiteral") ) DBI/R/dbHasCompleted.R0000644000176200001440000000170514157672512014067 0ustar liggesusers#' Completion status #' #' This method returns if the operation has completed. #' A `SELECT` query is completed if all rows have been fetched. #' A data manipulation statement is always completed. #' #' @template methods #' @templateVar method_name dbHasCompleted #' #' @inherit DBItest::spec_meta_has_completed return #' @inheritSection DBItest::spec_meta_has_completed Failure modes #' @inheritSection DBItest::spec_meta_has_completed Specification #' #' @inheritParams dbClearResult #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendQuery(con, "SELECT * FROM mtcars") #' #' dbHasCompleted(rs) #' ret1 <- dbFetch(rs, 10) #' dbHasCompleted(rs) #' ret2 <- dbFetch(rs) #' dbHasCompleted(rs) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbHasCompleted", def = function(res, ...) standardGeneric("dbHasCompleted"), valueClass = "logical" ) DBI/R/dbGetConnectArgs.R0000644000176200001440000000167614157672512014374 0ustar liggesusers#' Get connection arguments #' #' Returns the arguments stored in a [DBIConnector-class] object for inspection, #' optionally evaluating them. #' This function is called by [dbConnect()] #' and usually does not need to be called directly. #' #' @template methods #' @templateVar method_name dbGetConnectArgs #' #' @param drv A object inheriting from [DBIConnector-class]. #' @param eval Set to `FALSE` to return the functions that generate the argument #' instead of evaluating them. #' @param ... Other arguments passed on to methods. Not otherwise used. #' @family DBIConnector generics #' @examples #' cnr <- new("DBIConnector", #' .drv = RSQLite::SQLite(), #' .conn_args = list(dbname = ":memory:", password = function() "supersecret") #' ) #' dbGetConnectArgs(cnr) #' dbGetConnectArgs(cnr, eval = FALSE) #' @export setGeneric("dbGetConnectArgs", def = function(drv, eval = TRUE, ...) standardGeneric("dbGetConnectArgs"), valueClass = "list" ) DBI/R/dbiDataType.R0000644000176200001440000000012414157672512013375 0ustar liggesuserssetGeneric("dbiDataType", def = function(x, ...) standardGeneric("dbiDataType") ) DBI/R/dbiDataType_difftime.R0000644000176200001440000000020114157672512015240 0ustar liggesusers#' @usage NULL dbiDataType_difftime <- function(x) "TIME" setMethod("dbiDataType", signature("difftime"), dbiDataType_difftime) DBI/R/DBI-package.R0000644000176200001440000000140414157672512013174 0ustar liggesusers#' @description #' DBI defines an interface for communication between R and relational database #' management systems. #' All classes in this package are virtual and need to be extended by #' the various R/DBMS implementations (so-called *DBI backends*). #' #' @inheritSection DBItest::spec_getting_started Definition #' @inheritSection DBItest::spec_compliance_methods DBI classes and methods #' @inheritSection DBItest::spec_driver_constructor Construction of the DBIDriver object #' #' @examples #' RSQLite::SQLite() #' @seealso #' Important generics: [dbConnect()], [dbGetQuery()], #' [dbReadTable()], [dbWriteTable()], [dbDisconnect()] #' #' Formal specification (currently work in progress and incomplete): #' `vignette("spec", package = "DBI")` "_PACKAGE" DBI/R/show_SQL.R0000644000176200001440000000033114157672512012702 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL show_SQL <- function(object) { cat(paste0(" ", object@.Data, collapse = "\n"), "\n", sep = "") } #' @rdname hidden_aliases #' @export setMethod("show", "SQL", show_SQL) DBI/R/dbDataType_DBIObject.R0000644000176200001440000000033514157672512015035 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbDataType_DBIObject <- function(dbObj, obj, ...) { dbiDataType(obj) } #' @rdname hidden_aliases #' @export setMethod("dbDataType", signature("DBIObject"), dbDataType_DBIObject) DBI/R/dbGetException.R0000644000176200001440000000073314157672512014115 0ustar liggesusers#' Get DBMS exceptions #' #' DEPRECATED. Backends should use R's condition system to signal errors and #' warnings. #' #' @inheritParams dbGetQuery #' @family DBIConnection generics #' @return a list with elements `errorNum` (an integer error number) and #' `errorMsg` (a character string) describing the last error in the #' connection `conn`. #' @export #' @keywords internal setGeneric("dbGetException", def = function(conn, ...) standardGeneric("dbGetException") ) DBI/R/dbCanConnect_DBIDriver.R0000644000176200001440000000062714157672512015366 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbCanConnect_DBIDriver <- function(drv, ...) { tryCatch( { con <- dbConnect(drv, ...) dbDisconnect(con) TRUE }, error = function(e) { structure( FALSE, reason = conditionMessage(e) ) } ) } #' @rdname hidden_aliases #' @export setMethod("dbCanConnect", signature("DBIDriver"), dbCanConnect_DBIDriver) DBI/R/dbDataType.R0000644000176200001440000000463614157672512013240 0ustar liggesusers#' Determine the SQL data type of an object #' #' Returns an SQL string that describes the SQL data type to be used for an #' object. #' The default implementation of this generic determines the SQL type of an #' R object according to the SQL 92 specification, which may serve as a starting #' point for driver implementations. DBI also provides an implementation #' for data.frame which will return a character vector giving the type for each #' column in the dataframe. #' #' The data types supported by databases are different than the data types in R, #' but the mapping between the primitive types is straightforward: #' - Any of the many fixed and varying length character types are mapped to #' character vectors #' - Fixed-precision (non-IEEE) numbers are mapped into either numeric or #' integer vectors. #' #' Notice that many DBMS do not follow IEEE arithmetic, so there are potential #' problems with under/overflows and loss of precision. #' #' @template methods #' @templateVar method_name dbDataType #' #' @inherit DBItest::spec_driver_data_type return #' @inheritSection DBItest::spec_driver_data_type Failure modes #' @inheritSection DBItest::spec_driver_data_type Specification #' @inheritSection DBItest::spec_result_create_table_with_data_type Specification #' #' @inheritParams dbListConnections #' @param dbObj A object inheriting from [DBIDriver-class] #' or [DBIConnection-class] #' @param obj An R object whose SQL type we want to determine. #' @family DBIDriver generics #' @family DBIConnection generics #' @family DBIConnector generics #' @examples #' dbDataType(ANSI(), 1:5) #' dbDataType(ANSI(), 1) #' dbDataType(ANSI(), TRUE) #' dbDataType(ANSI(), Sys.Date()) #' dbDataType(ANSI(), Sys.time()) #' dbDataType(ANSI(), Sys.time() - as.POSIXct(Sys.Date())) #' dbDataType(ANSI(), c("x", "abc")) #' dbDataType(ANSI(), list(raw(10), raw(20))) #' dbDataType(ANSI(), I(3)) #' #' dbDataType(ANSI(), iris) #' #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbDataType(con, 1:5) #' dbDataType(con, 1) #' dbDataType(con, TRUE) #' dbDataType(con, Sys.Date()) #' dbDataType(con, Sys.time()) #' dbDataType(con, Sys.time() - as.POSIXct(Sys.Date())) #' dbDataType(con, c("x", "abc")) #' dbDataType(con, list(raw(10), raw(20))) #' dbDataType(con, I(3)) #' #' dbDataType(con, iris) #' #' dbDisconnect(con) #' @export setGeneric("dbDataType", def = function(dbObj, obj, ...) standardGeneric("dbDataType"), valueClass = "character" ) DBI/R/dbConnect_DBIConnector.R0000644000176200001440000000135514157672512015442 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbConnect_DBIConnector <- function(drv, ...) { dots_args <- list(...) has_name <- names2(dots_args) != "" # Unnamed dots come first (they are not picked up by modifyList()) unnamed_dots <- dots_args[!has_name] # Named dots come last, an extra drv argument is erased silently named_dots <- dots_args[has_name] named_dots$drv <- NULL # Named dots are supplemented with connector args extra_args <- utils::modifyList( dbGetConnectArgs(drv), named_dots ) all_args <- c( list(drv = drv@.drv), unnamed_dots, extra_args ) do.call(dbConnect, all_args) } #' @rdname hidden_aliases #' @export setMethod("dbConnect", signature("DBIConnector"), dbConnect_DBIConnector) DBI/R/dbSetDataMappings.R0000644000176200001440000000142214157672512014537 0ustar liggesusers#' Set data mappings between an DBMS and R. #' #' This generic is deprecated since no working implementation was ever produced. #' #' Sets one or more conversion functions to handle the translation of DBMS data #' types to R objects. This is only needed for non-primitive data, since all #' DBI drivers handle the common base types (integers, numeric, strings, etc.) #' #' The details on conversion functions (e.g., arguments, whether they can invoke #' initializers and/or destructors) have not been specified. #' #' @inheritParams dbClearResult #' @keywords internal #' @param flds a field description object as returned by `dbColumnInfo`. #' @export setGeneric("dbSetDataMappings", def = function(res, flds, ...) { .Deprecated() standardGeneric("dbSetDataMappings") } ) DBI/R/dbExistsTable.R0000644000176200001440000000132014157672512013737 0ustar liggesusers#' Does a table exist? #' #' Returns if a table given by name exists in the database. #' #' @template methods #' @templateVar method_name dbExistsTable #' #' @inherit DBItest::spec_sql_exists_table return #' @inheritSection DBItest::spec_sql_exists_table Failure modes #' @inheritSection DBItest::spec_sql_exists_table Specification #' #' @inheritParams dbReadTable #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbExistsTable(con, "iris") #' dbWriteTable(con, "iris", iris) #' dbExistsTable(con, "iris") #' #' dbDisconnect(con) setGeneric("dbExistsTable", def = function(conn, name, ...) standardGeneric("dbExistsTable"), valueClass = "logical" ) DBI/R/isSQLKeyword.R0000644000176200001440000000040514157672512013545 0ustar liggesusers#' @rdname make.db.names #' @export setGeneric("isSQLKeyword", def = function(dbObj, name, keywords = .SQL92Keywords, case = c("lower", "upper", "any")[3], ...) standardGeneric("isSQLKeyword"), signature = c("dbObj", "name"), valueClass = "logical" ) DBI/R/dbRemoveTable.R0000644000176200001440000000153514157672512013725 0ustar liggesusers#' Remove a table from the database #' #' Remove a remote table (e.g., created by [dbWriteTable()]) #' from the database. #' #' @template methods #' @templateVar method_name dbRemoveTable #' #' @inherit DBItest::spec_sql_remove_table return #' @inheritSection DBItest::spec_sql_remove_table Failure modes #' @inheritSection DBItest::spec_sql_remove_table Additional arguments #' @inheritSection DBItest::spec_sql_remove_table Specification #' #' @inheritParams dbReadTable #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbExistsTable(con, "iris") #' dbWriteTable(con, "iris", iris) #' dbExistsTable(con, "iris") #' dbRemoveTable(con, "iris") #' dbExistsTable(con, "iris") #' #' dbDisconnect(con) setGeneric("dbRemoveTable", def = function(conn, name, ...) standardGeneric("dbRemoveTable") ) DBI/R/data.R0000644000176200001440000000162214157672512012120 0ustar liggesusersNULL # Coercion rules --------------------------------------------------------------- coerce <- function(sqlvar, from, to) { list(from = from, to = to) } sqlDate <- function() { coerce( function(x) as.integer(x), function(x) { stopifnot(is.integer(x)) structure(x, class = "Date") } ) } sqlDateTime <- function() { coerce( function(x) as.numeric(x), function(x) { stopifnot(is.numeric(x)) structure(x, class = c("POSIXct", "POSIXt"), tzone = "UTC") } ) } sqlSerialize <- function() { coerce( function(x) { lapply(x, serialize, connection = NULL) }, function(x) { lapply(x, unserialize) } ) } sqlBoolean <- function() { coerce( function(x) as.integer(x), function(x) as.logical(x) ) } sqlFactor <- function(levels) { coerce( function(x) as.integer(x), function(x) factor(x, levels = levels) ) } DBI/R/DBIConnection.R0000644000176200001440000000215014157672512013622 0ustar liggesusers#' @include Id.R NULL #' DBIConnection class #' #' This virtual class encapsulates the connection to a DBMS, and it provides #' access to dynamic queries, result sets, DBMS session management #' (transactions), etc. #' #' @section Implementation note: #' Individual drivers are free to implement single or multiple simultaneous #' connections. #' #' @docType class #' @name DBIConnection-class #' @family DBI classes #' @family DBIConnection generics #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' con #' dbDisconnect(con) #' \dontrun{ #' con <- dbConnect(RPostgreSQL::PostgreSQL(), "username", "passsword") #' con #' dbDisconnect(con) #' } #' @export setClass("DBIConnection", contains = c("DBIObject", "VIRTUAL")) show_connection <- function(object) { cat("<", is(object)[1], ">\n", sep = "") if (!dbIsValid(object)) { cat(" DISCONNECTED\n") } } list_fields <- function(conn, name) { rs <- dbSendQuery( conn, paste( "SELECT * FROM ", dbQuoteIdentifier(conn, name), "LIMIT 0" ) ) on.exit(dbClearResult(rs)) names(dbFetch(rs, n = 0, row.names = FALSE)) } DBI/R/DBIDriver.R0000644000176200001440000000276414157672512012771 0ustar liggesusersNULL #' DBIDriver class #' #' Base class for all DBMS drivers (e.g., RSQLite, MySQL, PostgreSQL). #' The virtual class `DBIDriver` defines the operations for creating #' connections and defining data type mappings. Actual driver classes, for #' instance `RPostgres`, `RMariaDB`, etc. implement these operations in a #' DBMS-specific manner. #' #' @docType class #' @name DBIDriver-class #' @family DBI classes #' @family DBIDriver generics #' @export #' @include DBIObject.R setClass("DBIDriver", contains = c("DBIObject", "VIRTUAL")) show_driver <- function(object) { cat("<", is(object)[1], ">\n", sep = "") } findDriver <- function(drvName) { # If it exists in the global environment, use that d <- get2(drvName, globalenv()) if (!is.null(d)) return(d) # Otherwise, see if the appropriately named package is available if (is_attached(drvName)) { d <- get2(drvName, asNamespace(drvName)) if (!is.null(d)) return(d) } pkgName <- paste0("R", drvName) # First, see if package with name R + drvName is available if (is_attached(pkgName)) { d <- get2(drvName, asNamespace(pkgName)) if (!is.null(d)) return(d) } # Can't find it: stop( "Couldn't find driver ", drvName, ". Looked in:\n", "* global namespace\n", "* in package called ", drvName, "\n", "* in package called ", pkgName, call. = FALSE ) } get2 <- function(x, env) { if (!exists(x, envir = env)) return(NULL) get(x, envir = env) } is_attached <- function(x) { x %in% loadedNamespaces() } DBI/R/dbGetRowCount.R0000644000176200001440000000154214157672512013736 0ustar liggesusers#' The number of rows fetched so far #' #' Returns the total number of rows actually fetched with calls to [dbFetch()] #' for this result set. #' #' @template methods #' @templateVar method_name dbGetRowCount #' #' @inherit DBItest::spec_meta_get_row_count return #' @inheritSection DBItest::spec_meta_get_row_count Failure modes #' #' @inheritParams dbClearResult #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendQuery(con, "SELECT * FROM mtcars") #' #' dbGetRowCount(rs) #' ret1 <- dbFetch(rs, 10) #' dbGetRowCount(rs) #' ret2 <- dbFetch(rs) #' dbGetRowCount(rs) #' nrow(ret1) + nrow(ret2) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbGetRowCount", def = function(res, ...) standardGeneric("dbGetRowCount"), valueClass = "numeric" ) DBI/R/sqlCreateTable_DBIConnection.R0000644000176200001440000000166014157672512016602 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL sqlCreateTable_DBIConnection <- function(con, table, fields, row.names = NA, temporary = FALSE, ...) { if (missing(row.names)) { warning("Do not rely on the default value of the row.names argument for sqlCreateTable(), it will change in the future.", call. = FALSE ) } table <- dbQuoteIdentifier(con, table) if (is.data.frame(fields)) { fields <- sqlRownamesToColumn(fields, row.names) fields <- vapply(fields, function(x) DBI::dbDataType(con, x), character(1)) } field_names <- dbQuoteIdentifier(con, names(fields)) field_types <- unname(fields) fields <- paste0(field_names, " ", field_types) SQL(paste0( "CREATE ", if (temporary) "TEMPORARY ", "TABLE ", table, " (\n", " ", paste(fields, collapse = ",\n "), "\n)\n" )) } #' @rdname hidden_aliases #' @export setMethod("sqlCreateTable", signature("DBIConnection"), sqlCreateTable_DBIConnection) DBI/R/hms.R0000644000176200001440000000401014157672512011770 0ustar liggesusers# from hms format_hms <- function(x) { units(x) <- "secs" xx <- decompose(x) ifelse(is.na(x), NA_character_, paste0( ifelse(xx$sign, "-", ""), format_hours(xx$hours), ":", format_two_digits(xx$minute_of_hour), ":", format_two_digits(xx$second_of_minute), format_tics(xx$tics))) } format_hours <- function(x) { # Difference to hms: don't justify here format_two_digits(x) } format_two_digits <- function(x) { formatC(x, format = "f", digits = 0, width = 2, flag = "0") } format_tics <- function(x) { x <- x / TICS_PER_SECOND out <- format(x, scientific = FALSE, digits = SPLIT_SECOND_DIGITS + 1L) digits <- max(min(max(nchar(out) - 2), SPLIT_SECOND_DIGITS), 0) out <- formatC(x, format = "f", digits = digits) gsub("^0", "", out) } SPLIT_SECOND_DIGITS <- 6L TICS_PER_SECOND <- 10^SPLIT_SECOND_DIGITS SECONDS_PER_MINUTE <- 60 MINUTES_PER_HOUR <- 60 HOURS_PER_DAY <- 24 TICS_PER_MINUTE <- SECONDS_PER_MINUTE * TICS_PER_SECOND TICS_PER_HOUR <- MINUTES_PER_HOUR * TICS_PER_MINUTE TICS_PER_DAY <- HOURS_PER_DAY * TICS_PER_HOUR days <- function(x) { trunc(x / TICS_PER_DAY) } hours <- function(x) { trunc(x / TICS_PER_HOUR) } hour_of_day <- function(x) { abs(hours(x) - days(x) * HOURS_PER_DAY) } minutes <- function(x) { trunc(x / TICS_PER_MINUTE) } minute_of_hour <- function(x) { abs(minutes(x) - hours(x) * MINUTES_PER_HOUR) } seconds <- function(x) { trunc(x / TICS_PER_SECOND) } second_of_minute <- function(x) { abs(seconds(x) - minutes(x) * SECONDS_PER_MINUTE) } tics <- function(x) { x } tic_of_second <- function(x) { abs(tics(x) - seconds(x) * TICS_PER_SECOND) } decompose <- function(x) { x <- unclass(x) * TICS_PER_SECOND # #140 xr <- round(x) out <- list( sign = xr < 0 & !is.na(xr), hours = abs(hours(xr)), minute_of_hour = minute_of_hour(xr), second_of_minute = second_of_minute(xr), tics = tic_of_second(xr) ) # #140: Make sure zeros are printed fake_zero <- (out$tics == 0) & (xr != x) out$tics[fake_zero] <- 0.25 out } DBI/R/show_DBIResult.R0000644000176200001440000000060514157672512014044 0ustar liggesusers#' @rdname hidden_aliases #' @param object Object to display #' @usage NULL show_DBIResult <- function(object) { # to protect drivers that fail to implement the required methods (e.g., # RPostgreSQL) tryCatch( show_result(object), error = function(e) NULL ) invisible(NULL) } #' @rdname hidden_aliases #' @export setMethod("show", signature("DBIResult"), show_DBIResult) DBI/R/ANSI.R0000644000176200001440000000075614157672512011750 0ustar liggesusers#' @include DBIConnection.R #' @include DBIDriver.R setClass("AnsiConnection", contains = "DBIConnection") #' A dummy DBI connector that simulates ANSI-SQL compliance #' #' @export #' @keywords internal #' @examples #' ANSI() ANSI <- function() { new("AnsiConnection") } #' Internal page for hidden aliases #' #' For S4 methods that require a documentation entry but only clutter the index. #' #' @usage NULL #' @format NULL #' @keywords internal #' @docType methods hidden_aliases <- NULL DBI/R/dbQuoteIdentifier.R0000644000176200001440000000263014157672512014615 0ustar liggesusers#' Quote identifiers #' #' Call this method to generate a string that is suitable for #' use in a query as a column or table name, to make sure that you #' generate valid SQL and protect against SQL injection attacks. The inverse #' operation is [dbUnquoteIdentifier()]. #' #' @inheritParams dbGetQuery #' @param x A character vector, [SQL] or [Id] object to quote as identifier. #' @param ... Other arguments passed on to methods. #' #' @template methods #' @templateVar method_name dbQuoteIdentifier #' #' @inherit DBItest::spec_sql_quote_identifier return #' @inheritSection DBItest::spec_sql_quote_identifier Failure modes #' @inheritSection DBItest::spec_sql_quote_identifier Specification #' #' @family DBIResult generics #' @export #' @examples #' # Quoting ensures that arbitrary input is safe for use in a query #' name <- "Robert'); DROP TABLE Students;--" #' dbQuoteIdentifier(ANSI(), name) #' #' # Use Id() to specify other components such as the schema #' id_name <- Id(schema = "schema_name", table = "table_name") #' id_name #' dbQuoteIdentifier(ANSI(), id_name) #' #' # SQL vectors are always passed through as is #' var_name <- SQL("select") #' var_name #' dbQuoteIdentifier(ANSI(), var_name) #' #' # This mechanism is used to prevent double escaping #' dbQuoteIdentifier(ANSI(), dbQuoteIdentifier(ANSI(), name)) setGeneric("dbQuoteIdentifier", def = function(conn, x, ...) standardGeneric("dbQuoteIdentifier") ) DBI/R/sqlInterpolate_DBIConnection.R0000644000176200001440000000244714157672512016721 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL sqlInterpolate_DBIConnection <- function(conn, sql, ..., .dots = list()) { pos <- sqlParseVariables(conn, sql) if (length(pos$start) == 0) { return(SQL(sql)) } vars <- substring(sql, pos$start + 1, pos$end) positional_vars <- pos$start == pos$end if (all(positional_vars) != any(positional_vars)) { stop("Can't mix positional (?) and named (?asdf) variables", call. = FALSE) } values <- c(list(...), .dots) if (all(positional_vars)) { if (length(vars) != length(values)) { stop("Supplied values don't match positional vars to interpolate", call. = FALSE) } if (any(names(values) != "")) { stop("Positional variables don't take named arguments") } } else { if (!setequal(vars, names(values))) { stop("Supplied values don't match named vars to interpolate", call. = FALSE) } values <- values[vars] } safe_values <- vapply(values, function(x) dbQuoteLiteral(conn, x), character(1)) for (i in rev(seq_along(vars))) { sql <- paste0( substring(sql, 0, pos$start[i] - 1), safe_values[i], substring(sql, pos$end[i] + 1, nchar(sql)) ) } SQL(sql) } #' @rdname hidden_aliases #' @export setMethod("sqlInterpolate", signature("DBIConnection"), sqlInterpolate_DBIConnection) DBI/R/dbListConnections.R0000644000176200001440000000072414157672512014635 0ustar liggesusers#' List currently open connections #' #' DEPRECATED, drivers are no longer required to implement this method. #' Keep track of the connections you opened if you require a list. #' #' @param drv A object inheriting from [DBIDriver-class] #' @param ... Other arguments passed on to methods. #' @family DBIDriver generics #' @keywords internal #' @export #' @return a list setGeneric("dbListConnections", def = function(drv, ...) standardGeneric("dbListConnections") ) DBI/R/sqlData.R0000644000176200001440000000166714157672512012611 0ustar liggesusers#' Convert a data frame into form suitable for upload to an SQL database #' #' This is a generic method that coerces R objects into vectors suitable for #' upload to the database. The output will vary a little from method to #' method depending on whether the main upload device is through a single #' SQL string or multiple parameterized queries. #' This method is mostly useful for backend implementers. #' #' The default method: #' \itemize{ #' \item Converts factors to characters #' \item Quotes all strings #' \item Converts all columns to strings #' \item Replaces NA with NULL #' } #' #' @inheritParams sqlCreateTable #' @inheritParams rownames #' @param value A data frame #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' sqlData(con, head(iris)) #' sqlData(con, head(mtcars)) #' #' dbDisconnect(con) setGeneric("sqlData", def = function(con, value, row.names = NA, ...) standardGeneric("sqlData") ) DBI/R/dbListResults.R0000644000176200001440000000100614157672512014006 0ustar liggesusers#' A list of all pending results #' #' DEPRECATED. DBI currenty supports only one open result set per connection, #' you need to keep track of the result sets you open if you need this #' functionality. #' #' @inheritParams dbGetQuery #' @family DBIConnection generics #' @return a list. If no results are active, an empty list. If only #' a single result is active, a list with one element. #' @export #' @keywords internal setGeneric("dbListResults", def = function(conn, ...) standardGeneric("dbListResults") ) DBI/R/SQLKeywords_missing.R0000644000176200001440000000033414157672512015126 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL SQLKeywords_missing <- function(dbObj, ...) .SQL92Keywords #' @rdname hidden_aliases setMethod("SQLKeywords", signature("missing"), SQLKeywords_missing, valueClass = "character") DBI/R/show_AnsiConnection.R0000644000176200001440000000032014157672512015153 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL show_AnsiConnection <- function(object) { cat("\n") } #' @rdname hidden_aliases #' @export setMethod("show", "AnsiConnection", show_AnsiConnection) DBI/R/isSQLKeyword_DBIObject_character.R0000644000176200001440000000050714157672512017371 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL isSQLKeyword_DBIObject_character <- function(dbObj, name, keywords, case, ...) isSQLKeyword.default(name, keywords, case) #' @rdname hidden_aliases setMethod("isSQLKeyword", signature(dbObj = "DBIObject", name = "character"), isSQLKeyword_DBIObject_character, valueClass = "logical") DBI/R/dbListFields.R0000644000176200001440000000120114157672512013550 0ustar liggesusers#' List field names of a remote table #' #' @inheritParams dbReadTable #' #' @inherit DBItest::spec_sql_list_fields return #' @inheritSection DBItest::spec_sql_list_fields Failure modes #' @inheritSection DBItest::spec_sql_list_fields Specification #' #' @family DBIConnection generics #' @seealso [dbColumnInfo()] to get the type of the fields. #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' dbListFields(con, "mtcars") #' #' dbDisconnect(con) setGeneric("dbListFields", def = function(conn, name, ...) standardGeneric("dbListFields"), valueClass = "character" ) DBI/R/DBIObject.R0000644000176200001440000000265414157672512012742 0ustar liggesusersNULL #' DBIObject class #' #' Base class for all other DBI classes (e.g., drivers, connections). This #' is a virtual Class: No objects may be created from it. #' #' More generally, the DBI defines a very small set of classes and generics that #' allows users and applications access DBMS with a common interface. The #' virtual classes are `DBIDriver` that individual drivers extend, #' `DBIConnection` that represent instances of DBMS connections, and #' `DBIResult` that represent the result of a DBMS statement. These three #' classes extend the basic class of `DBIObject`, which serves as the root #' or parent of the class hierarchy. #' #' @section Implementation notes: #' An implementation MUST provide methods for the following generics: #' #' \itemize{ #' \item [dbGetInfo()]. #' } #' #' It MAY also provide methods for: #' #' \itemize{ #' \item [summary()]. Print a concise description of the #' object. The default method invokes `dbGetInfo(dbObj)` and prints #' the name-value pairs one per line. Individual implementations may #' tailor this appropriately. #' } #' #' @docType class #' @family DBI classes #' @examples #' drv <- RSQLite::SQLite() #' con <- dbConnect(drv) #' #' rs <- dbSendQuery(con, "SELECT 1") #' is(drv, "DBIObject") ## True #' is(con, "DBIObject") ## True #' is(rs, "DBIObject") #' #' dbClearResult(rs) #' dbDisconnect(con) #' @export #' @name DBIObject-class setClass("DBIObject", "VIRTUAL") DBI/R/Id.R0000644000176200001440000000340314157701453011537 0ustar liggesusersNULL #' @rdname Id setClass("Id", slots = list(name = "character")) #' Refer to a table nested in a hierarchy (e.g. within a schema) #' #' @description #' Objects of class `Id` have a single slot `name`, which is a named #' character vector. #' The [dbQuoteIdentifier()] method converts `Id` objects to strings. #' Support for `Id` objects depends on the database backend. #' They can be used in the following methods as `name` or `table` argument: #' #' - [dbCreateTable()] #' - [dbAppendTable()] #' - [dbReadTable()] #' - [dbWriteTable()] #' - [dbExistsTable()] #' - [dbRemoveTable()] #' #' Objects of this class are also returned from [dbListObjects()]. #' #' @param ... Components of the hierarchy, e.g. `schema`, `table`, #' or `cluster`, `catalog`, `schema`, `table`, #' depending on the database backend. #' For more on these concepts, see #' \url{https://stackoverflow.com/questions/7022755/} #' @export #' @examples #' # Identifies a table in a specific schema: #' Id(schema = "dbo", table = "Customer") #' #' # Identifies a table in a specific cluster, catalog, and schema: #' Id(cluster = "mycluster", catalog = "mycatalog", schema = "myschema", table = "mytable") #' #' # Create a SQL expression for an identifier: #' dbQuoteIdentifier(ANSI(), Id(schema = "nycflights13", table = "flights")) #' #' # Write a table in a specific schema: #' \dontrun{ #' dbWriteTable(con, Id(schema = "myschema", table = "mytable"), data.frame(a = 1)) #' } Id <- function(...) { components <- c(...) if (is.null(names(components)) || any(names(components) == "")) { stop("All arguments to Id() must be named.", call. = FALSE) } new("Id", name = components) } #' @export toString.Id <- function(x, ...) { paste0(" ", paste0(names(x@name), " = ", x@name, collapse = ", ")) } DBI/R/dbListObjects_DBIConnection_ANY.R0000644000176200001440000000072214157672512017147 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbListObjects_DBIConnection_ANY <- function(conn, prefix = NULL, ...) { names <- dbListTables(conn) tables <- lapply(names, function(x) Id(table = x)) ret <- data.frame( table = I(unname(tables)), stringsAsFactors = FALSE ) ret$is_prefix <- rep_len(FALSE, nrow(ret)) ret } #' @rdname hidden_aliases #' @export setMethod("dbListObjects", signature("DBIConnection", "ANY"), dbListObjects_DBIConnection_ANY) DBI/R/dbUnloadDriver.R0000644000176200001440000000034714157672512014116 0ustar liggesusers#' @description #' `dbUnloadDriver()` is not implemented for modern backends. #' @rdname dbDriver #' @family DBIDriver generics #' @export setGeneric("dbUnloadDriver", def = function(drv, ...) standardGeneric("dbUnloadDriver") ) DBI/R/dbGetRowsAffected.R0000644000176200001440000000143114157672512014527 0ustar liggesusers#' The number of rows affected #' #' This method returns the number of rows that were added, deleted, or updated #' by a data manipulation statement. #' #' @template methods #' @templateVar method_name dbGetRowsAffected #' #' @inherit DBItest::spec_meta_get_rows_affected return #' @inheritSection DBItest::spec_meta_get_rows_affected Failure modes #' #' @inheritParams dbClearResult #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendStatement(con, "DELETE FROM mtcars") #' dbGetRowsAffected(rs) #' nrow(mtcars) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbGetRowsAffected", def = function(res, ...) standardGeneric("dbGetRowsAffected"), valueClass = "numeric" ) DBI/R/dbAppendTable_DBIConnection.R0000644000176200001440000000122414157672512016370 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbAppendTable_DBIConnection <- function(conn, name, value, ..., row.names = NULL) { if (!is.null(row.names)) { stop("Can't pass `row.names` to `dbAppendTable()`", call. = FALSE) } stopifnot(is.character(name), length(name) == 1) stopifnot(is.data.frame(value)) query <- sqlAppendTableTemplate( con = conn, table = name, values = value, row.names = row.names, prefix = "?", pattern = "", ... ) dbExecute(conn, query, params = unname(as.list(value))) } #' @rdname hidden_aliases #' @export setMethod("dbAppendTable", signature("DBIConnection"), dbAppendTable_DBIConnection) DBI/R/sqlAppendTable.R0000644000176200001440000000202714157672512014106 0ustar liggesusers#' Compose query to insert rows into a table #' #' `sqlAppendTable()` generates a single SQL string that inserts a #' data frame into an existing table. `sqlAppendTableTemplate()` generates #' a template suitable for use with [dbBind()]. #' The default methods are ANSI SQL 99 compliant. #' These methods are mostly useful for backend implementers. #' #' The `row.names` argument must be passed explicitly in order to avoid #' a compatibility warning. The default will be changed in a later release. #' #' @inheritParams sqlCreateTable #' @inheritParams rownames #' @param values A data frame. Factors will be converted to character vectors. #' Character vectors will be escaped with [dbQuoteString()]. #' @family SQL generation #' @export #' @examples #' sqlAppendTable(ANSI(), "iris", head(iris)) #' #' sqlAppendTable(ANSI(), "mtcars", head(mtcars)) #' sqlAppendTable(ANSI(), "mtcars", head(mtcars), row.names = FALSE) setGeneric("sqlAppendTable", def = function(con, table, values, row.names = NA, ...) standardGeneric("sqlAppendTable") ) DBI/R/show_Id.R0000644000176200001440000000035114157672512012601 0ustar liggesusers#' @rdname hidden_aliases #' @param object Table object to print #' @usage NULL show_Id <- function(object) { cat(toString(object), "\n", sep = "") } #' @rdname hidden_aliases #' @export setMethod("show", signature("Id"), show_Id) DBI/R/dbiDataType_numeric.R0000644000176200001440000000020014157672512015112 0ustar liggesusers#' @usage NULL dbiDataType_numeric <- function(x) "DOUBLE" setMethod("dbiDataType", signature("numeric"), dbiDataType_numeric) DBI/R/dbiDataType_data.frame.R0000644000176200001440000000027214157672512015463 0ustar liggesusersdbiDataType_data.frame <- function(x) { vapply(x, dbiDataType, FUN.VALUE = character(1), USE.NAMES = TRUE) } setMethod("dbiDataType", signature("data.frame"), dbiDataType_data.frame) DBI/R/dbSendQuery.R0000644000176200001440000000470514157672512013441 0ustar liggesusers#' Execute a query on a given database connection #' #' The `dbSendQuery()` method only submits and synchronously executes the #' SQL query to the database engine. It does \emph{not} extract any #' records --- for that you need to use the [dbFetch()] method, and #' then you must call [dbClearResult()] when you finish fetching the #' records you need. For interactive use, you should almost always prefer #' [dbGetQuery()]. #' #' This method is for `SELECT` queries only. Some backends may #' support data manipulation queries through this method for compatibility #' reasons. However, callers are strongly encouraged to use #' [dbSendStatement()] for data manipulation statements. #' #' The query is submitted to the database server and the DBMS executes it, #' possibly generating vast amounts of data. Where these data live #' is driver-specific: some drivers may choose to leave the output on the server #' and transfer them piecemeal to R, others may transfer all the data to the #' client -- but not necessarily to the memory that R manages. See individual #' drivers' `dbSendQuery()` documentation for details. #' #' @template methods #' @templateVar method_name dbSendQuery #' #' @inherit DBItest::spec_result_send_query return #' @inheritSection DBItest::spec_result_send_query Failure modes #' @inheritSection DBItest::spec_result_send_query Additional arguments #' @inheritSection DBItest::spec_result_send_query Specification #' @inheritSection DBItest::spec_result_send_query Specification for the `immediate` argument #' #' @inheritParams dbGetQuery #' @param statement a character string containing SQL. #' #' @family DBIConnection generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") #' dbFetch(rs) #' dbClearResult(rs) #' #' # Pass one set of values with the param argument: #' rs <- dbSendQuery( #' con, #' "SELECT * FROM mtcars WHERE cyl = ?", #' params = list(4L) #' ) #' dbFetch(rs) #' dbClearResult(rs) #' #' # Pass multiple sets of values with dbBind(): #' rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = ?") #' dbBind(rs, list(6L)) #' dbFetch(rs) #' dbBind(rs, list(8L)) #' dbFetch(rs) #' dbClearResult(rs) #' #' dbDisconnect(con) #' @export setGeneric("dbSendQuery", def = function(conn, statement, ...) standardGeneric("dbSendQuery"), valueClass = "DBIResult" ) DBI/R/dbReadTable_DBIConnection_Id.R0000644000176200001440000000043514157672512016453 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbReadTable_DBIConnection_Id <- function(conn, name, ...) { dbReadTable(conn, dbQuoteIdentifier(conn, name), ...) } #' @rdname hidden_aliases #' @export setMethod("dbReadTable", signature("DBIConnection", "Id"), dbReadTable_DBIConnection_Id) DBI/R/sqlAppendTable_DBIConnection.R0000644000176200001440000000155514157672512016611 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL sqlAppendTable_DBIConnection <- function(con, table, values, row.names = NA, ...) { stopifnot(is.list(values)) if (missing(row.names)) { warning("Do not rely on the default value of the row.names argument for sqlAppendTable(), it will change in the future.", call. = FALSE ) } sql_values <- sqlData(con, values, row.names) table <- dbQuoteIdentifier(con, table) fields <- dbQuoteIdentifier(con, names(sql_values)) # Convert fields into a character matrix rows <- do.call(paste, c(unname(sql_values), sep = ", ")) SQL(paste0( "INSERT INTO ", table, "\n", " (", paste(fields, collapse = ", "), ")\n", "VALUES\n", paste0(" (", rows, ")", collapse = ",\n") )) } #' @rdname hidden_aliases #' @export setMethod("sqlAppendTable", signature("DBIConnection"), sqlAppendTable_DBIConnection) DBI/R/make.db.names.R0000644000176200001440000000571614157672512013622 0ustar liggesusers#' Make R identifiers into legal SQL identifiers #' #' These methods are DEPRECATED. Please use [dbQuoteIdentifier()] #' (or possibly [dbQuoteString()]) instead. #' #' The algorithm in `make.db.names` first invokes `make.names` and #' then replaces each occurrence of a dot `.` by an underscore `_`. If #' `allow.keywords` is `FALSE` and identifiers collide with SQL #' keywords, a small integer is appended to the identifier in the form of #' `"_n"`. #' #' The set of SQL keywords is stored in the character vector #' `.SQL92Keywords` and reflects the SQL ANSI/ISO standard as documented #' in "X/Open SQL and RDA", 1994, ISBN 1-872630-68-8. Users can easily #' override or update this vector. #' #' @section Bugs: #' The current mapping is not guaranteed to be fully reversible: some SQL #' identifiers that get mapped into R identifiers with `make.names` and #' then back to SQL with [make.db.names()] will not be equal to the #' original SQL identifiers (e.g., compound SQL identifiers of the form #' `username.tablename` will loose the dot ``.''). #' #' @references The set of SQL keywords is stored in the character vector #' `.SQL92Keywords` and reflects the SQL ANSI/ISO standard as documented #' in "X/Open SQL and RDA", 1994, ISBN 1-872630-68-8. Users can easily #' override or update this vector. #' @aliases #' make.db.names #' SQLKeywords #' isSQLKeyword #' @param dbObj any DBI object (e.g., `DBIDriver`). #' @param snames a character vector of R identifiers (symbols) from which we #' need to make SQL identifiers. #' @param name a character vector with database identifier candidates we need #' to determine whether they are legal SQL identifiers or not. #' @param unique logical describing whether the resulting set of SQL names #' should be unique. Its default is `TRUE`. Following the SQL 92 #' standard, uniqueness of SQL identifiers is determined regardless of whether #' letters are upper or lower case. #' @param allow.keywords logical describing whether SQL keywords should be #' allowed in the resulting set of SQL names. Its default is `TRUE` #' @param keywords a character vector with SQL keywords, by default it's #' `.SQL92Keywords` defined by the DBI. #' @param case a character string specifying whether to make the comparison as #' lower case, upper case, or any of the two. it defaults to `any`. #' @param \dots any other argument are passed to the driver implementation. #' @return `make.db.names` returns a character vector of legal SQL #' identifiers corresponding to its `snames` argument. #' #' `SQLKeywords` returns a character vector of all known keywords for the #' database-engine associated with `dbObj`. #' #' `isSQLKeyword` returns a logical vector parallel to `name`. #' @export #' @keywords internal setGeneric("make.db.names", def = function(dbObj, snames, keywords = .SQL92Keywords, unique = TRUE, allow.keywords = TRUE, ...) standardGeneric("make.db.names"), signature = c("dbObj", "snames"), valueClass = "character" ) DBI/R/SQLKeywords_DBIObject.R0000644000176200001440000000034214157672512015201 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL SQLKeywords_DBIObject <- function(dbObj, ...) .SQL92Keywords #' @rdname hidden_aliases setMethod("SQLKeywords", signature("DBIObject"), SQLKeywords_DBIObject, valueClass = "character") DBI/R/SQLKeywords.R0000644000176200001440000000040014157672512013367 0ustar liggesusers## SQL ANSI 92 (plus ISO's) keywords --- all 220 of them! ## (See pp. 22 and 23 in X/Open SQL and RDA, 1994, isbn 1-872630-68-8) #' @export setGeneric("SQLKeywords", def = function(dbObj, ...) standardGeneric("SQLKeywords"), valueClass = "character" ) DBI/R/fetch.R0000644000176200001440000000021514157672512012275 0ustar liggesusers#' @rdname dbFetch #' @export setGeneric("fetch", def = function(res, n = -1, ...) standardGeneric("fetch"), valueClass = "data.frame" ) DBI/R/dbUnquoteIdentifier.R0000644000176200001440000000260314157672512015160 0ustar liggesusers#' Unquote identifiers #' #' Call this method to convert a [SQL] object created by [dbQuoteIdentifier()] #' back to a list of [Id] objects. #' #' @inheritParams dbGetQuery #' @param x An [SQL] or [Id] object. #' @param ... Other arguments passed on to methods. #' #' @template methods #' @templateVar method_name dbUnquoteIdentifier #' #' @inherit DBItest::spec_sql_unquote_identifier return #' @inheritSection DBItest::spec_sql_unquote_identifier Failure modes #' @inheritSection DBItest::spec_sql_unquote_identifier Specification #' #' @family DBIResult generics #' @export #' @examples #' # Unquoting allows to understand the structure of a #' # possibly complex quoted identifier #' dbUnquoteIdentifier( #' ANSI(), #' SQL(c('"Catalog"."Schema"."Table"', '"Schema"."Table"', '"UnqualifiedTable"')) #' ) #' #' # The returned object is always a list, #' # also for Id objects #' dbUnquoteIdentifier( #' ANSI(), #' Id(catalog = "Catalog", schema = "Schema", table = "Table") #' ) #' #' # Quoting is the inverse operation to unquoting the elements #' # of the returned list #' dbQuoteIdentifier( #' ANSI(), #' dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]] #' ) #' #' dbQuoteIdentifier( #' ANSI(), #' dbUnquoteIdentifier(ANSI(), Id(schema = "Schema", table = "Table"))[[1]] #' ) setGeneric("dbUnquoteIdentifier", def = function(conn, x, ...) standardGeneric("dbUnquoteIdentifier") ) DBI/R/sqlAppendTableTemplate.R0000644000176200001440000000263114157672512015603 0ustar liggesusers#' @rdname sqlAppendTable #' @inheritParams sqlCreateTable #' @inheritParams rownames #' @param prefix Parameter prefix to use for placeholders. #' @param pattern Parameter pattern to use for placeholders: #' - `""`: no pattern #' - `"1"`: position #' - anything else: field name #' @export #' @examples #' sqlAppendTableTemplate(ANSI(), "iris", iris) #' #' sqlAppendTableTemplate(ANSI(), "mtcars", mtcars) #' sqlAppendTableTemplate(ANSI(), "mtcars", mtcars, row.names = FALSE) sqlAppendTableTemplate <- function(con, table, values, row.names = NA, prefix = "?", ..., pattern = "") { if (missing(row.names)) { warning("Do not rely on the default value of the `row.names` argument to `sqlAppendTableTemplate()`, it will change in the future.", call. = FALSE ) } if (length(values) == 0) { stop("Must pass at least one column in `values`", call. = FALSE) } table <- dbQuoteIdentifier(con, table) values <- sqlRownamesToColumn(values[0, , drop = FALSE], row.names) fields <- dbQuoteIdentifier(con, names(values)) if (pattern == "") { suffix <- rep("", length(fields)) } else if (pattern == "1") { suffix <- as.character(seq_along(fields)) } else { suffix <- names(fields) } placeholders <- lapply(paste0(prefix, suffix), SQL) names(placeholders) <- names(values) sqlAppendTable( con = con, table = table, values = placeholders, row.names = row.names ) } DBI/R/dbAppendTable.R0000644000176200001440000000304414157672512013674 0ustar liggesusers#' Insert rows into a table #' #' The `dbAppendTable()` method assumes that the table has been created #' beforehand, e.g. with [dbCreateTable()]. #' The default implementation calls [sqlAppendTableTemplate()] and then #' [dbExecute()] with the `param` argument. Backends compliant to #' ANSI SQL 99 which use `?` as a placeholder for prepared queries don't need #' to override it. Backends with a different SQL syntax which use `?` #' as a placeholder for prepared queries can override [sqlAppendTable()]. #' Other backends (with different placeholders or with entirely different #' ways to create tables) need to override the `dbAppendTable()` method. #' #' The `row.names` argument is not supported by this method. #' Process the values with [sqlRownamesToColumn()] before calling this method. #' #' @inheritParams dbReadTable #' @param value A data frame of values. The column names must be consistent #' with those in the target table in the database. #' @param row.names Must be `NULL`. #' @inheritParams sqlAppendTableTemplate #' #' @inherit DBItest::spec_sql_append_table return #' @inheritSection DBItest::spec_sql_append_table Failure modes #' @inheritSection DBItest::spec_sql_append_table Specification #' #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbCreateTable(con, "iris", iris) #' dbAppendTable(con, "iris", iris) #' dbReadTable(con, "iris") #' dbDisconnect(con) setGeneric("dbAppendTable", def = function(conn, name, value, ..., row.names = NULL) standardGeneric("dbAppendTable") ) DBI/R/dbWithTransaction.R0000644000176200001440000000456614157672512014650 0ustar liggesusers#' Self-contained SQL transactions #' #' Given that \link{transactions} are implemented, this function #' allows you to pass in code that is run in a transaction. #' The default method of `dbWithTransaction()` calls [dbBegin()] #' before executing the code, #' and [dbCommit()] after successful completion, #' or [dbRollback()] in case of an error. #' The advantage is #' that you don't have to remember to do `dbBegin()` and `dbCommit()` or #' `dbRollback()` -- that is all taken care of. #' The special function `dbBreak()` allows an early exit with rollback, #' it can be called only inside `dbWithTransaction()`. #' #' DBI implements `dbWithTransaction()`, backends should need to override this #' generic only if they implement specialized handling. #' #' @template methods #' @templateVar method_name dbWithTransaction #' #' @inherit DBItest::spec_transaction_with_transaction return #' @inheritSection DBItest::spec_transaction_with_transaction Failure modes #' @inheritSection DBItest::spec_transaction_with_transaction Specification #' #' @inheritParams dbGetQuery #' @param code An arbitrary block of R code. #' #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "cash", data.frame(amount = 100)) #' dbWriteTable(con, "account", data.frame(amount = 2000)) #' #' # All operations are carried out as logical unit: #' dbWithTransaction( #' con, #' { #' withdrawal <- 300 #' dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) #' dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) #' } #' ) #' #' # The code is executed as if in the curent environment: #' withdrawal #' #' # The changes are committed to the database after successful execution: #' dbReadTable(con, "cash") #' dbReadTable(con, "account") #' #' # Rolling back with dbBreak(): #' dbWithTransaction( #' con, #' { #' withdrawal <- 5000 #' dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal)) #' dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal)) #' if (dbReadTable(con, "account")$amount < 0) { #' dbBreak() #' } #' } #' ) #' #' # These changes were not committed to the database: #' dbReadTable(con, "cash") #' dbReadTable(con, "account") #' #' dbDisconnect(con) setGeneric("dbWithTransaction", def = function(conn, code, ...) standardGeneric("dbWithTransaction") ) DBI/R/dbGetQuery.R0000644000176200001440000000430614157672512013264 0ustar liggesusers#' Send query, retrieve results and then clear result set #' #' Returns the result of a query as a data frame. #' `dbGetQuery()` comes with a default implementation #' (which should work with most backends) that calls #' [dbSendQuery()], then [dbFetch()], ensuring that #' the result is always free-d by [dbClearResult()]. #' #' This method is for `SELECT` queries only #' (incl. other SQL statements that return a `SELECT`-alike result, #' e. g. execution of a stored procedure). #' #' To execute a stored procedure that does not return a result set, #' use [dbExecute()]. #' #' Some backends may #' support data manipulation statements through this method for compatibility #' reasons. However, callers are strongly advised to use #' [dbExecute()] for data manipulation statements. #' #' @template methods #' @templateVar method_name dbGetQuery #' #' @inherit DBItest::spec_result_get_query return #' @inheritSection DBItest::spec_result_get_query Failure modes #' @inheritSection DBItest::spec_result_get_query Additional arguments #' @inheritSection DBItest::spec_result_get_query Specification #' @inheritSection DBItest::spec_result_get_query Specification for the `immediate` argument #' #' @section Implementation notes: #' Subclasses should override this method only if they provide some sort of #' performance optimization. #' #' @param conn A [DBIConnection-class] object, as returned by #' [dbConnect()]. #' @param statement a character string containing SQL. #' @param ... Other parameters passed on to methods. #' @family DBIConnection generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' dbGetQuery(con, "SELECT * FROM mtcars") #' dbGetQuery(con, "SELECT * FROM mtcars", n = 6) #' #' # Pass values using the param argument: #' # (This query runs eight times, once for each different #' # parameter. The resulting rows are combined into a single #' # data frame.) #' dbGetQuery( #' con, #' "SELECT COUNT(*) FROM mtcars WHERE cyl = ?", #' params = list(1:8) #' ) #' #' dbDisconnect(con) setGeneric("dbGetQuery", def = function(conn, statement, ...) standardGeneric("dbGetQuery") ) DBI/R/dbQuoteIdentifier_DBIConnection.R0000644000176200001440000000266714157672512017325 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbQuoteIdentifier_DBIConnection <- function(conn, x, ...) { # Don't support lists, auto-vectorization violates type stability if (is(x, "SQL")) return(x) if (is(x, "Id")) { return(SQL(paste0(dbQuoteIdentifier(conn, x@name), collapse = "."))) } if (!is.character(x)) stop("x must be character or SQL", call. = FALSE) if (any(is.na(x))) { stop("Cannot pass NA to dbQuoteIdentifier()", call. = FALSE) } # Avoid fixed = TRUE due to https://github.com/r-dbi/DBItest/issues/156 x <- gsub('"', '""', enc2utf8(x)) if (length(x) == 0L) { SQL(character(), names = names(x)) } else { # Not calling encodeString() here to keep things simple SQL(paste('"', x, '"', sep = ""), names = names(x)) } } #' @rdname hidden_aliases #' @export setMethod("dbQuoteIdentifier", signature("DBIConnection"), dbQuoteIdentifier_DBIConnection) # Need to keep other method declarations around for now, because clients might # use getMethod(), see e.g. https://github.com/r-dbi/odbc/pull/149 #' @rdname hidden_aliases #' @export setMethod("dbQuoteIdentifier", signature("DBIConnection", "character"), dbQuoteIdentifier_DBIConnection) #' @rdname hidden_aliases #' @export setMethod("dbQuoteIdentifier", signature("DBIConnection", "SQL"), dbQuoteIdentifier_DBIConnection) #' @rdname hidden_aliases #' @export setMethod("dbQuoteIdentifier", signature("DBIConnection", "Id"), dbQuoteIdentifier_DBIConnection) DBI/R/summary.R0000644000176200001440000000002614157672512012701 0ustar liggesuserssetGeneric("summary") DBI/R/dbBind.R0000644000176200001440000000527414157672512012400 0ustar liggesusers#' Bind values to a parameterized/prepared statement #' #' For parametrized or prepared statements, #' the [dbSendQuery()] and [dbSendStatement()] functions can be called with #' statements that contain placeholders for values. The `dbBind()` function #' binds these placeholders #' to actual values, and is intended to be called on the result set #' before calling [dbFetch()] or [dbGetRowsAffected()]. #' #' \pkg{DBI} supports parametrized (or prepared) queries and statements #' via the `dbBind()` generic. #' Parametrized queries are different from normal queries #' in that they allow an arbitrary number of placeholders, #' which are later substituted by actual values. #' Parametrized queries (and statements) serve two purposes: #' #' - The same query can be executed more than once with different values. #' The DBMS may cache intermediate information for the query, #' such as the execution plan, #' and execute it faster. #' - Separation of query syntax and parameters protects against SQL injection. #' #' The placeholder format is currently not specified by \pkg{DBI}; #' in the future, a uniform placeholder syntax may be supported. #' Consult the backend documentation for the supported formats. #' For automated testing, backend authors specify the placeholder syntax with #' the `placeholder_pattern` tweak. #' Known examples are: #' #' - `?` (positional matching in order of appearance) in \pkg{RMySQL} and \pkg{RSQLite} #' - `$1` (positional matching by index) in \pkg{RPostgres} and \pkg{RSQLite} #' - `:name` and `$name` (named matching) in \pkg{RSQLite} #' #' @template methods #' @templateVar method_name dbBind #' #' @inherit DBItest::spec_meta_bind return #' @inheritSection DBItest::spec_meta_bind Failure modes #' @inheritSection DBItest::spec_meta_bind Specification #' #' @inheritParams dbClearResult #' @param params A list of bindings, named or unnamed. #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "iris", iris) #' #' # Using the same query for different values #' iris_result <- dbSendQuery(con, "SELECT * FROM iris WHERE [Petal.Width] > ?") #' dbBind(iris_result, list(2.3)) #' dbFetch(iris_result) #' dbBind(iris_result, list(3)) #' dbFetch(iris_result) #' dbClearResult(iris_result) #' #' # Executing the same statement with different values at once #' iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = $species") #' dbBind(iris_result, list(species = c("setosa", "versicolor", "unknown"))) #' dbGetRowsAffected(iris_result) #' dbClearResult(iris_result) #' #' nrow(dbReadTable(con, "iris")) #' #' dbDisconnect(con) setGeneric("dbBind", def = function(res, params, ...) standardGeneric("dbBind") ) DBI/R/dbIsReadOnly_DBIConnector.R0000644000176200001440000000035114157672512016055 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbIsReadOnly_DBIConnector <- function(dbObj, ...) { dbIsReadOnly(dbObj@.drv, ...) } #' @rdname hidden_aliases setMethod("dbIsReadOnly", signature("DBIConnector"), dbIsReadOnly_DBIConnector) DBI/R/dbiDataType_AsIs.R0000644000176200001440000000022514157672512014316 0ustar liggesusersdbiDataType_AsIs <- function(x) { oldClass(x) <- oldClass(x)[-1] dbiDataType(x) } setMethod("dbiDataType", signature("AsIs"), dbiDataType_AsIs) DBI/R/dbReadTable.R0000644000176200001440000000243314157672512013341 0ustar liggesusers#' Copy data frames from database tables #' #' Reads a database table to a data frame, optionally converting #' a column to row names and converting the column names to valid #' R identifiers. #' #' @template methods #' @templateVar method_name dbReadTable #' #' @inherit DBItest::spec_sql_read_table return #' @inheritSection DBItest::spec_sql_read_table Failure modes #' @inheritSection DBItest::spec_sql_read_table Additional arguments #' @inheritSection DBItest::spec_sql_read_table Specification #' #' @inheritParams dbGetQuery #' @param name The table name, passed on to [dbQuoteIdentifier()]. Options are: #' - a character string with the unquoted DBMS table name, #' e.g. `"table_name"`, #' - a call to [Id()] with components to the fully qualified table name, #' e.g. `Id(schema = "my_schema", table = "table_name")` #' - a call to [SQL()] with the quoted and fully qualified table name #' given verbatim, e.g. `SQL('"my_schema"."table_name"')` #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars[1:10, ]) #' dbReadTable(con, "mtcars") #' #' dbDisconnect(con) setGeneric("dbReadTable", def = function(conn, name, ...) standardGeneric("dbReadTable"), valueClass = "data.frame" ) DBI/R/methods_as_rd.R0000644000176200001440000000413214157701464014020 0ustar liggesusersmethods_as_rd <- function(method) { if (method == "transactions") { method <- c("dbBegin", "dbCommit", "dbRollback") } if (identical(Sys.getenv("IN_PKGDOWN"), "true") && file.exists("DESCRIPTION")) { packages <- strsplit(read.dcf("DESCRIPTION")[, "Config/Needs/website"], ",( |\n)*", perl = TRUE)[[1]] packages <- grep("/", packages, invert = TRUE, value = TRUE) for (package in packages) { stopifnot(requireNamespace(package, quietly = TRUE)) } } methods <- unlist(lapply(method, methods::findMethods), recursive = FALSE) # Extracted from roxygen2::object_topic.s4method s4_topic <- function(x) { sig <- paste0(x@defined, collapse = ",") sig_text <- paste0('"', x@defined, '"', collapse = ", ") package <- unname(tryCatch( getNamespaceName(environment(x@.Data)), error = function(e) NA )) if (is.na(package) || package == "DBI") { return(data.frame()) } topic <- paste0(x@generic, ",", sig, "-method") call <- paste0(package, "::", x@generic, "(", sig_text, ")") if (identical(Sys.getenv("IN_PKGDOWN"), "true")) { url <- downlit::autolink_url(paste0("?", package, "::`", topic, "`")) } else { url <- NA } data.frame(package, topic, call, url, stringsAsFactors = FALSE) } item_list <- lapply(methods@.Data, s4_topic) items <- do.call(rbind, item_list) if (is.null(items) || ncol(items) == 0) { return("") } items <- items[order(items$call), ] if (identical(Sys.getenv("IN_PKGDOWN"), "true")) { linked <- ifelse(is.na(items$url), items$call, paste0("\\href{", items$url, "}{", items$call, "}")) item_text <- paste0("\\code{", linked, "}") } else { item_text <- paste0("\\code{\\link[=", items$topic, "]{", items$call, "}}") } paste0( "\\subsection{Methods in other packages}{\n\n", "This documentation page describes the generics. ", "Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.", "\\itemize{\n", paste0("\\item ", item_text, "\n", collapse = ""), "}}\n" ) } DBI/R/dbGetQuery_DBIConnection_character.R0000644000176200001440000000062714157672512020000 0ustar liggesusers#' @rdname hidden_aliases #' @param n Number of rows to fetch, default -1 #' @usage NULL dbGetQuery_DBIConnection_character <- function(conn, statement, ..., n = -1L) { rs <- dbSendQuery(conn, statement, ...) on.exit(dbClearResult(rs)) dbFetch(rs, n = n, ...) } #' @rdname hidden_aliases #' @export setMethod("dbGetQuery", signature("DBIConnection", "character"), dbGetQuery_DBIConnection_character) DBI/R/dbConnect.R0000644000176200001440000000340214157672512013104 0ustar liggesusers#' Create a connection to a DBMS #' #' Connect to a DBMS going through the appropriate authentication procedure. #' Some implementations may allow you to have multiple connections open, so you #' may invoke this function repeatedly assigning its output to different #' objects. #' The authentication mechanism is left unspecified, so check the #' documentation of individual drivers for details. #' Use [dbCanConnect()] to check if a connection can be established. #' #' @template methods #' @templateVar method_name dbConnect #' #' @inherit DBItest::spec_driver_connect return #' @inheritSection DBItest::spec_driver_connect Specification #' #' @param drv an object that inherits from [DBIDriver-class], #' or an existing [DBIConnection-class] #' object (in order to clone an existing connection). #' @param ... authentication arguments needed by the DBMS instance; these #' typically include `user`, `password`, `host`, `port`, `dbname`, etc. #' For details see the appropriate `DBIDriver`. #' @seealso [dbDisconnect()] to disconnect from a database. #' @family DBIDriver generics #' @family DBIConnector generics #' @export #' @examples #' # SQLite only needs a path to the database. (Here, ":memory:" is a special #' # path that creates an in-memory database.) Other database drivers #' # will require more details (like user, password, host, port, etc.) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' con #' #' dbListTables(con) #' #' dbDisconnect(con) #' #' # Bad, for subtle reasons: #' # This code fails when RSQLite isn't loaded yet, #' # because dbConnect() doesn't know yet about RSQLite. #' dbListTables(con <- dbConnect(RSQLite::SQLite(), ":memory:")) setGeneric("dbConnect", def = function(drv, ...) standardGeneric("dbConnect"), valueClass = "DBIConnection" ) DBI/R/dbWriteTable_DBIConnection_Id_ANY.R0000644000176200001440000000047614157672512017406 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbWriteTable_DBIConnection_Id_ANY <- function(conn, name, value, ...) { dbWriteTable(conn, dbQuoteIdentifier(conn, name), value, ...) } #' @rdname hidden_aliases #' @export setMethod("dbWriteTable", signature("DBIConnection", "Id", "ANY"), dbWriteTable_DBIConnection_Id_ANY) DBI/R/data-types.R0000644000176200001440000000005514157672512013261 0ustar liggesuserssetOldClass("difftime") setOldClass("AsIs") DBI/R/dbQuoteString_DBIConnection.R0000644000176200001440000000215514157672512016501 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbQuoteString_DBIConnection <- function(conn, x, ...) { if (is(x, "SQL")) return(x) if (!is.character(x)) stop("x must be character or SQL", call. = FALSE) # Avoid fixed = TRUE due to https://github.com/r-dbi/DBItest/issues/156 x <- gsub("'", "''", enc2utf8(x)) if (length(x) == 0L) { SQL(character()) } else { # Not calling encodeString() here, see also https://stackoverflow.com/a/549244/946850 # and especially the comment by Álvaro González str <- paste("'", x, "'", sep = "") str[is.na(x)] <- "NULL" SQL(str) } } # Need to keep other method declarations around for now, because clients might # use getMethod(), see e.g. https://github.com/r-dbi/odbc/pull/149 #' @rdname hidden_aliases #' @export setMethod("dbQuoteString", signature("DBIConnection"), dbQuoteString_DBIConnection) #' @rdname hidden_aliases #' @export setMethod("dbQuoteString", signature("DBIConnection", "character"), dbQuoteString_DBIConnection) #' @rdname hidden_aliases #' @export setMethod("dbQuoteString", signature("DBIConnection", "SQL"), dbQuoteString_DBIConnection) DBI/R/dbFetch.R0000644000176200001440000000340714157672512012551 0ustar liggesusers#' Fetch records from a previously executed query #' #' Fetch the next `n` elements (rows) from the result set and return them #' as a data.frame. #' #' `fetch()` is provided for compatibility with older DBI clients - for all #' new code you are strongly encouraged to use `dbFetch()`. The default #' implementation for `dbFetch()` calls `fetch()` so that it is compatible with #' existing code. Modern backends should implement for `dbFetch()` only. #' #' @template methods #' @templateVar method_name dbFetch #' #' @inherit DBItest::spec_result_fetch return #' @inheritSection DBItest::spec_result_fetch Failure modes #' @inheritSection DBItest::spec_result_fetch Specification #' @inheritSection DBItest::spec_result_roundtrip Specification #' #' @param res An object inheriting from [DBIResult-class], created by #' [dbSendQuery()]. #' @param n maximum number of records to retrieve per fetch. Use `n = -1` #' or `n = Inf` #' to retrieve all pending records. Some implementations may recognize other #' special values. #' @param ... Other arguments passed on to methods. #' @seealso Close the result set with [dbClearResult()] as soon as you #' finish retrieving the records you want. #' @family DBIResult generics #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' #' # Fetch all results #' rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4") #' dbFetch(rs) #' dbClearResult(rs) #' #' # Fetch in chunks #' rs <- dbSendQuery(con, "SELECT * FROM mtcars") #' while (!dbHasCompleted(rs)) { #' chunk <- dbFetch(rs, 10) #' print(nrow(chunk)) #' } #' #' dbClearResult(rs) #' dbDisconnect(con) #' @export setGeneric("dbFetch", def = function(res, n = -1, ...) standardGeneric("dbFetch"), valueClass = "data.frame" ) DBI/R/dbGetStatement.R0000644000176200001440000000135314157672512014122 0ustar liggesusers#' Get the statement associated with a result set #' #' Returns the statement that was passed to [dbSendQuery()] #' or [dbSendStatement()]. #' #' @template methods #' @templateVar method_name dbGetStatement #' #' @inherit DBItest::spec_meta_get_statement return #' @inheritSection DBItest::spec_meta_get_statement Failure modes #' #' @inheritParams dbClearResult #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendQuery(con, "SELECT * FROM mtcars") #' dbGetStatement(rs) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbGetStatement", def = function(res, ...) standardGeneric("dbGetStatement"), valueClass = "character" ) DBI/R/dbClearResult.R0000644000176200001440000000162114157672512013741 0ustar liggesusers#' Clear a result set #' #' Frees all resources (local and remote) associated with a result set. In some #' cases (e.g., very large result sets) this can be a critical step to avoid #' exhausting resources (memory, file descriptors, etc.) #' #' @template methods #' @templateVar method_name dbClearResult #' #' @inherit DBItest::spec_result_clear_result return #' @inheritSection DBItest::spec_result_clear_result Failure modes #' @inheritSection DBItest::spec_result_clear_result Specification #' #' @param res An object inheriting from [DBIResult-class]. #' @param ... Other arguments passed on to methods. #' @family DBIResult generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' rs <- dbSendQuery(con, "SELECT 1") #' print(dbFetch(rs)) #' #' dbClearResult(rs) #' dbDisconnect(con) setGeneric("dbClearResult", def = function(res, ...) standardGeneric("dbClearResult") ) DBI/R/dbCreateTable_DBIConnection.R0000644000176200001440000000105014157672512016361 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbCreateTable_DBIConnection <- function(conn, name, fields, ..., row.names = NULL, temporary = FALSE) { stopifnot(is.null(row.names)) stopifnot(is.logical(temporary), length(temporary) == 1L) query <- sqlCreateTable( con = conn, table = name, fields = fields, row.names = row.names, temporary = temporary, ... ) dbExecute(conn, query) invisible(TRUE) } #' @rdname hidden_aliases #' @export setMethod("dbCreateTable", signature("DBIConnection"), dbCreateTable_DBIConnection) DBI/R/dbCreateTable.R0000644000176200001440000000244714157672512013676 0ustar liggesusers#' Create a table in the database #' #' The default `dbCreateTable()` method calls [sqlCreateTable()] and #' [dbExecute()]. #' Backends compliant to ANSI SQL 99 don't need to override it. #' Backends with a different SQL syntax can override `sqlCreateTable()`, #' backends with entirely different ways to create tables need to #' override this method. #' #' The `row.names` argument is not supported by this method. #' Process the values with [sqlRownamesToColumn()] before calling this method. #' #' The argument order is different from the `sqlCreateTable()` method, the #' latter will be adapted in a later release of DBI. #' #' @inheritParams dbReadTable #' @param row.names Must be `NULL`. #' @inheritParams sqlCreateTable #' #' @inherit DBItest::spec_sql_create_table return #' @inheritSection DBItest::spec_sql_create_table Failure modes #' @inheritSection DBItest::spec_sql_create_table Additional arguments #' @inheritSection DBItest::spec_sql_create_table Specification #' #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbCreateTable(con, "iris", iris) #' dbReadTable(con, "iris") #' dbDisconnect(con) setGeneric("dbCreateTable", def = function(conn, name, fields, ..., row.names = NULL, temporary = FALSE) standardGeneric("dbCreateTable") ) DBI/R/sqlData_DBIConnection.R0000644000176200001440000000133314157701453015272 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL sqlData_DBIConnection <- function(con, value, row.names = NA, ...) { value <- sqlRownamesToColumn(value, row.names) # Convert factors to strings is_factor <- vapply(value, is.factor, logical(1)) value[is_factor] <- lapply(value[is_factor], as.character) # Quote all strings is_char <- vapply(value, is.character, logical(1)) value[is_char] <- lapply(value[is_char], function(x) { enc2utf8(dbQuoteString(con, x)) }) # Convert everything to character and turn NAs into NULL value[!is_char] <- lapply(value[!is_char], dbQuoteLiteral, conn = con) value } #' @rdname hidden_aliases #' @export setMethod("sqlData", signature("DBIConnection"), sqlData_DBIConnection) DBI/R/dbQuoteString.R0000644000176200001440000000225414157672512014003 0ustar liggesusers#' Quote literal strings #' #' Call this method to generate a string that is suitable for #' use in a query as a string literal, to make sure that you #' generate valid SQL and protect against SQL injection attacks. #' #' @inheritParams dbGetQuery #' @param x A character vector to quote as string. #' @param ... Other arguments passed on to methods. #' #' @template methods #' @templateVar method_name dbQuoteString #' #' @inherit DBItest::spec_sql_quote_string return #' @inheritSection DBItest::spec_sql_quote_string Failure modes #' @inheritSection DBItest::spec_sql_quote_string Specification #' #' @family DBIResult generics #' @export #' @examples #' # Quoting ensures that arbitrary input is safe for use in a query #' name <- "Robert'); DROP TABLE Students;--" #' dbQuoteString(ANSI(), name) #' #' # NAs become NULL #' dbQuoteString(ANSI(), c("x", NA)) #' #' # SQL vectors are always passed through as is #' var_name <- SQL("select") #' var_name #' dbQuoteString(ANSI(), var_name) #' #' # This mechanism is used to prevent double escaping #' dbQuoteString(ANSI(), dbQuoteString(ANSI(), name)) setGeneric("dbQuoteString", def = function(conn, x, ...) standardGeneric("dbQuoteString") ) DBI/R/dbIsValid.R0000644000176200001440000000140014157672512013042 0ustar liggesusers#' Is this DBMS object still valid? #' #' This generic tests whether a database object is still valid (i.e. it hasn't #' been disconnected or cleared). #' #' @template methods #' @templateVar method_name dbIsValid #' #' @inherit DBItest::spec_meta_is_valid return #' #' @inheritParams dbGetInfo #' @family DBIDriver generics #' @family DBIConnection generics #' @family DBIResult generics #' @export #' @examples #' dbIsValid(RSQLite::SQLite()) #' #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbIsValid(con) #' #' rs <- dbSendQuery(con, "SELECT 1") #' dbIsValid(rs) #' #' dbClearResult(rs) #' dbIsValid(rs) #' #' dbDisconnect(con) #' dbIsValid(con) setGeneric("dbIsValid", def = function(dbObj, ...) standardGeneric("dbIsValid"), valueClass = "logical" ) DBI/R/dbRemoveTable_DBIConnection_Id.R0000644000176200001440000000044514157672512017036 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbRemoveTable_DBIConnection_Id <- function(conn, name, ...) { dbRemoveTable(conn, dbQuoteIdentifier(conn, name), ...) } #' @rdname hidden_aliases #' @export setMethod("dbRemoveTable", signature("DBIConnection", "Id"), dbRemoveTable_DBIConnection_Id) DBI/R/dbListObjects.R0000644000176200001440000000263414157672512013746 0ustar liggesusers#' List remote objects #' #' Returns the names of remote objects accessible through this connection #' as a data frame. #' This should include temporary objects, but not all database backends #' (in particular \pkg{RMariaDB} and \pkg{RMySQL}) support this. #' Compared to [dbListTables()], this method also enumerates tables and views #' in schemas, and returns fully qualified identifiers to access these objects. #' This allows exploration of all database objects available to the current #' user, including those that can only be accessed by giving the full #' namespace. #' #' @template methods #' @templateVar method_name dbListObjects #' #' @inherit DBItest::spec_sql_list_objects return #' @inheritSection DBItest::spec_sql_list_objects Failure modes #' @inheritSection DBItest::spec_sql_list_objects Specification #' #' @inheritParams dbGetQuery #' @param prefix A fully qualified path in the database's namespace, or `NULL`. #' This argument will be processed with [dbUnquoteIdentifier()]. #' If given the method will return all objects accessible through this prefix. #' @family DBIConnection generics #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbListObjects(con) #' dbWriteTable(con, "mtcars", mtcars) #' dbListObjects(con) #' #' dbDisconnect(con) setGeneric("dbListObjects", def = function(conn, prefix = NULL, ...) standardGeneric("dbListObjects"), valueClass = "data.frame" ) DBI/R/dbiDataType_logical.R0000644000176200001440000000020214157672512015064 0ustar liggesusers#' @usage NULL dbiDataType_logical <- function(x) "SMALLINT" setMethod("dbiDataType", signature("logical"), dbiDataType_logical) DBI/R/dbExecute_DBIConnection_character.R0000644000176200001440000000053414157672512017632 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbExecute_DBIConnection_character <- function(conn, statement, ...) { rs <- dbSendStatement(conn, statement, ...) on.exit(dbClearResult(rs)) dbGetRowsAffected(rs) } #' @rdname hidden_aliases #' @export setMethod("dbExecute", signature("DBIConnection", "character"), dbExecute_DBIConnection_character) DBI/R/dbBegin.R0000644000176200001440000000016214157672512012537 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbBegin", def = function(conn, ...) standardGeneric("dbBegin") ) DBI/R/dbCallProc.R0000644000176200001440000000076014157672512013216 0ustar liggesusers#' Call an SQL stored procedure #' #' **Deprecated since 2014** #' #' The recommended way of calling a stored procedure is now #' #' \enumerate{ #' \item{\code{\link{dbGetQuery}} if a result set is returned} #' \item{\code{\link{dbExecute}} for data manipulation and other cases where no result set is returned} #' } #' #' @inheritParams dbGetQuery #' @keywords internal #' @export setGeneric("dbCallProc", def = function(conn, ...) { .Deprecated() standardGeneric("dbCallProc") } ) DBI/R/dbiDataType_integer.R0000644000176200001440000000017514157672512015120 0ustar liggesusers#' @usage NULL dbiDataType_integer <- function(x) "INT" setMethod("dbiDataType", signature("integer"), dbiDataType_integer) DBI/R/dbExecute.R0000644000176200001440000000370514157672512013123 0ustar liggesusers#' Execute an update statement, query number of rows affected, and then close result set #' #' Executes a statement and returns the number of rows affected. #' `dbExecute()` comes with a default implementation #' (which should work with most backends) that calls #' [dbSendStatement()], then [dbGetRowsAffected()], ensuring that #' the result is always free-d by [dbClearResult()]. #' #' You can also use `dbExecute()` to call a stored procedure #' that performs data manipulation or other actions that do not return a result set. #' To execute a stored procedure that returns a result set use [dbGetQuery()] instead. #' #' @template methods #' @templateVar method_name dbExecute #' #' @section Implementation notes: #' Subclasses should override this method only if they provide some sort of #' performance optimization. #' #' @inherit DBItest::spec_result_execute return #' @inheritSection DBItest::spec_result_execute Failure modes #' @inheritSection DBItest::spec_result_execute Additional arguments #' @inheritSection DBItest::spec_result_execute Specification #' @inheritSection DBItest::spec_result_execute Specification for the `immediate` argument #' #' @inheritParams dbGetQuery #' @param statement a character string containing SQL. #' @family DBIConnection generics #' @seealso For queries: [dbSendQuery()] and [dbGetQuery()]. #' @export #' @examples #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "cars", head(cars, 3)) #' dbReadTable(con, "cars") # there are 3 rows #' dbExecute( #' con, #' "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" #' ) #' dbReadTable(con, "cars") # there are now 6 rows #' #' # Pass values using the param argument: #' dbExecute( #' con, #' "INSERT INTO cars (speed, dist) VALUES (?, ?)", #' params = list(4:7, 5:8) #' ) #' dbReadTable(con, "cars") # there are now 10 rows #' #' dbDisconnect(con) setGeneric("dbExecute", def = function(conn, statement, ...) standardGeneric("dbExecute") ) DBI/R/dbQuoteLiteral_DBIConnection.R0000644000176200001440000000251014157672512016622 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbQuoteLiteral_DBIConnection <- function(conn, x, ...) { # Switchpatching to avoid ambiguous S4 dispatch, so that our method # is used only if no alternatives are available. if (is(x, "SQL")) { return(x) } if (is.factor(x)) { return(dbQuoteString(conn, as.character(x))) } if (is.character(x)) { return(dbQuoteString(conn, x)) } if (inherits(x, "POSIXt")) { return(dbQuoteString( conn, strftime(as.POSIXct(x), "%Y%m%d%H%M%S", tz = "UTC") )) } if (inherits(x, "Date")) { return(dbQuoteString(conn, as.character(x))) } if (inherits(x, "difftime")) { return(dbQuoteString(conn, format_hms(x))) } if (is.list(x)) { blob_data <- vapply( x, function(x) { if (is.null(x)) { "NULL" } else if (is.raw(x)) { paste0("X'", paste(format(x), collapse = ""), "'") } else { stop("Lists must contain raw vectors or NULL", call. = FALSE) } }, character(1) ) return(SQL(blob_data, names = names(x))) } if (is.logical(x)) { x <- as.numeric(x) } x <- as.character(x) x[is.na(x)] <- "NULL" SQL(x, names = names(x)) } #' @rdname hidden_aliases #' @export setMethod("dbQuoteLiteral", signature("DBIConnection"), dbQuoteLiteral_DBIConnection) DBI/R/dbRollback.R0000644000176200001440000000017014157672512013243 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbRollback", def = function(conn, ...) standardGeneric("dbRollback") ) DBI/R/dbIsReadOnly.R0000644000176200001440000000064414157672512013531 0ustar liggesusers#' Is this DBMS object read only? #' #' This generic tests whether a database object is read only. #' #' @inheritParams dbGetInfo #' @family DBIDriver generics #' @family DBIConnection generics #' @family DBIResult generics #' @family DBIConnector generics #' @export #' @examples #' dbIsReadOnly(ANSI()) setGeneric("dbIsReadOnly", def = function(dbObj, ...) standardGeneric("dbIsReadOnly"), valueClass = "logical") DBI/R/dbCommit.R0000644000176200001440000000016414157672512012745 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbCommit", def = function(conn, ...) standardGeneric("dbCommit") ) DBI/R/SQL.R0000644000176200001440000000403614157672512011650 0ustar liggesusers#' SQL quoting #' #' This set of classes and generics make it possible to flexibly deal with SQL #' escaping needs. By default, any user supplied input to a query should be #' escaped using either [dbQuoteIdentifier()] or [dbQuoteString()] #' depending on whether it refers to a table or variable name, or is a literal #' string. #' These functions may return an object of the `SQL` class, #' which tells DBI functions that a character string does not need to be escaped #' anymore, to prevent double escaping. #' The `SQL` class has associated the `SQL()` constructor function. #' #' @section Implementation notes: #' #' DBI provides default generics for SQL-92 compatible quoting. If the database #' uses a different convention, you will need to provide your own methods. #' Note that because of the way that S4 dispatch finds methods and because #' SQL inherits from character, if you implement (e.g.) a method for #' `dbQuoteString(MyConnection, character)`, you will also need to #' implement `dbQuoteString(MyConnection, SQL)` - this should simply #' return `x` unchanged. #' #' @param x A character vector to label as being escaped SQL. #' @param ... Other arguments passed on to methods. Not otherwise used. #' @param names Names for the returned object, must have the same length as `x`. #' @return An object of class `SQL`. #' @export #' @examples #' dbQuoteIdentifier(ANSI(), "SELECT") #' dbQuoteString(ANSI(), "SELECT") #' #' # SQL vectors are always passed through as is #' var_name <- SQL("SELECT") #' var_name #' #' dbQuoteIdentifier(ANSI(), var_name) #' dbQuoteString(ANSI(), var_name) #' #' # This mechanism is used to prevent double escaping #' dbQuoteString(ANSI(), dbQuoteString(ANSI(), "SELECT")) SQL <- function(x, ..., names = NULL) { if (!is.null(names)) { stopifnot(length(x) == length(names)) } names(x) <- names new("SQL", x) } #' @rdname SQL #' @export #' @aliases #' SQL-class setClass("SQL", contains = "character") #' @export `[.SQL` <- function(x, ...) SQL(NextMethod()) #' @export `[[.SQL` <- function(x, ...) SQL(NextMethod()) DBI/NEWS.md0000644000176200001440000004347214157714442011771 0ustar liggesusers # DBI 1.1.2 (2021-12-19) ## Features - Use `dbQuoteLiteral()` in default method for `sqlData()` (#362, #371). - Update specification with changes from DBItest 1.7.2 (#367). ## Documentation - Method documentation on pkgdown is clickable and contains methods from all known DBI backends except ROracle (#360). - `?Id` gains better examples (#295, #370). - Elaborate on status of `dbWriteTable()` in the documentation (#352, #372). - Make method definition more similar to S3. All `setMethod()` calls refer to top-level functions (#368). - The pkgdown documentation for DBI generics (e.g. `?dbConnect`) contains clickable links to many known backends, and an explanatory sentence (#360). - `?dbReadTable` and other pages gain pointers to `Id()` and `SQL()` (#359). # DBI 1.1.1 (2021-01-04) ## Documentation - Expand "Get started" vignette to two tutorials, basic and advanced (#332, @jawond). ## Bug fixes - `dbAppendTable()` now allows columns named `sep` (#336). - `dbAppendTable()` shows a better error message if the input has zero columns (#313). - `sqlInterpolate()` now correctly interprets consecutive comments (#329, @rnorberg). - `dbQuoteLiteral()` works for difftime objects (#325). - `dbQuoteLiteral()` quotes dates as `YYYY-MM-DD` without time zone (#331). ## Internal - Switch to GitHub Actions (#326). - Update URL in `DESCRIPTION`. # DBI 1.1.0 (2019-12-15) ## New features - New `DBIConnector` class (#280). - Specify `immediate` argument to `dbSendQuery()`, `dbGetQuery()`, `dbSendStatement()` and `dbExecute()` (#268). - Use specification for `dbGetInfo()` (#271). - `dbUnquoteIdentifier()` now supports `Id()` objects with `catalog` members (#266, @raffscallion). It also handles unquoted identifiers of the form `table`, `schema.table` or `catalog.schema.table`, for compatibility with dbplyr. ## Documentation - New DBI intro article (#286, @cutterkom). - Add pkgdown reference index (#288). - DBI specification on https://dbi.r-dbi.org/dev/articles/spec now comes with a table of contents and code formatting. - Update examples to refer to `params` instead of `param` (#235). - Improved documentation for `sqlInterpolate()` (#100). Add usage of `SQL()` to `sqlInterpolate()` examples (#259, @renkun-ken). - Improve documentation for `Id`. ## Internal - Add tests for `dbUnquoteIdentifier()` (#279, @baileych). - `sqlInterpolate()` uses `dbQuoteLiteral()` instead of checking the type of the input. - Avoid partial argument match in `dbWriteTable()` (#246, @richfitz). # DBI 1.0.0 (2018-05-02) ## New generics - New `dbAppendTable()` that by default calls `sqlAppendTableTemplate()` and then `dbExecute()` with a `param` argument, without support for `row.names` argument (#74). - New `dbCreateTable()` that by default calls `sqlCreateTable()` and then `dbExecute()`, without support for `row.names` argument (#74). - New `dbCanConnect()` generic with default implementation (#87). - New `dbIsReadOnly()` generic with default implementation (#190, @anhqle). ## Changes - `sqlAppendTable()` now accepts lists for the `values` argument, to support lists of `SQL` objects in R 3.1. - Add default implementation for `dbListFields(DBIConnection, Id)`, this relies on `dbQuoteIdentifier(DBIConnection, Id)` (#75). ## Documentation updates - The DBI specification vignette is rendered correctly from the installed package (#234). - Update docs on how to cope with stored procedures (#242, @aryoda). - Add "Additional arguments" sections and more examples for `dbGetQuery()`, `dbSendQuery()`, `dbExecute()` and `dbSendStatement()`. - The `dbColumnInfo()` method is now fully specified (#75). - The `dbListFields()` method is now fully specified (#75). - The dynamic list of methods in help pages doesn't contain methods in DBI anymore. ## Bug fixes - Pass missing `value` argument to secondary `dbWriteTable()` call (#737, @jimhester). - The `Id` class now uses `` and not `` when printing. - The default `dbUnquoteIdentifier()` implementation now complies to the spec. # DBI 0.8 (2018-02-24) Breaking changes ---------------- - `SQL()` now strips the names from the output if the `names` argument is unset. - The `dbReadTable()`, `dbWriteTable()`, `dbExistsTable()`, `dbRemoveTable()`, and `dbListFields()` generics now specialize over the first two arguments to support implementations with the `Id` S4 class as type for the second argument. Some packages may need to update their documentation to satisfy R CMD check again. New generics ------------ - Schema support: Export `Id()`, new generics `dbListObjects()` and `dbUnquoteIdentifier()`, methods for `Id` that call `dbQuoteIdentifier()` and then forward (#220). - New `dbQuoteLiteral()` generic. The default implementation uses switchpatch to avoid dispatch ambiguities, and forwards to `dbQuoteString()` for character vectors. Backends may override methods that also dispatch on the second argument, but in this case also an override for the `"SQL"` class is necessary (#172). Default implementations ----------------------- - Default implementations of `dbQuoteIdentifier()` and `dbQuoteLiteral()` preserve names, default implementation of `dbQuoteString()` strips names (#173). - Specialized methods for `dbQuoteString()` and `dbQuoteIdentifier()` are available again, for compatibility with clients that use `getMethod()` to access them (#218). - Add default implementation of `dbListFields()`. - The default implementation of `dbReadTable()` now has `row.names = FALSE` as default and also supports `row.names = NULL` (#186). API changes ----------- - The `SQL()` function gains an optional `names` argument which can be used to assign names to SQL strings. Deprecated generics ------------------- - `dbListConnections()` is soft-deprecated by documentation. - `dbListResults()` is deprecated by documentation (#58). - `dbGetException()` is soft-deprecated by documentation (#51). - The deprecated `print.list.pairs()` has been removed. Bug fixes --------- - Fix `dbDataType()` for `AsIs` object (#198, @yutannihilation). - Fix `dbQuoteString()` and `dbQuoteIdentifier()` to ignore invalid UTF-8 strings (r-dbi/DBItest#156). Documentation ------------- - Help pages for generics now contain a dynamic list of methods implemented by DBI backends (#162). - `sqlInterpolate()` now supports both named and positional variables (#216, @hannesmuehleisen). - Point to db.rstudio.com (@wibeasley, #209). - Reflect new 'r-dbi' organization in `DESCRIPTION` (@wibeasley, #207). Internal -------- - Using switchpatch on the second argument for default implementations of `dbQuoteString()` and `dbQuoteIdentifier()`. # DBI 0.7 (2017-06-17) - Import updated specs from `DBItest`. - The default implementation of `dbGetQuery()` now accepts an `n` argument and forwards it to `dbFetch()`. No warning about pending rows is issued anymore (#76). - Require R >= 3.0.0 (for `slots` argument of `setClass()`) (#169, @mvkorpel). # DBI 0.6-1 (2017-04-01) - Fix `dbReadTable()` for backends that do not provide their own implementation (#171). # DBI 0.6 (2017-03-08) - Interface changes - Deprecated `dbDriver()` and `dbUnloadDriver()` by documentation (#21). - Renamed arguments to `sqlInterpolate()` and `sqlParseVariables()` to be more consistent with the rest of the interface, and added `.dots` argument to `sqlParseVariables`. DBI drivers are now expected to implement `sqlParseVariables(conn, sql, ..., .dots)` and `sqlInterpolate(conn, sql, ...)` (#147). - Interface enhancements - Removed `valueClass = "logical"` for those generics where the return value is meaningless, to allow backends to return invisibly (#135). - Avoiding using braces in the definitions of generics if possible, so that standard generics can be detected (#146). - Added default implementation for `dbReadTable()`. - All standard generics are required to have an ellipsis (with test), for future extensibility. - Improved default implementation of `dbQuoteString()` and `dbQuoteIdentifier()` (#77). - Removed `tryCatch()` call in `dbGetQuery()` (#113). - Documentation improvements - Finalized first draft of DBI specification, now in a vignette. - Most methods now draw documentation from `DBItest`, only those where the behavior is not finally decided don't do this yet yet. - Removed `max.connections` requirement from documentation (#56). - Improved `dbBind()` documentation and example (#136). - Change `omegahat.org` URL to `omegahat.net`, the particular document still doesn't exist below the new domain. - Internal - Use roxygen2 inheritance to copy DBI specification to this package. - Use `tic` package for building documentation. - Use markdown in documentation. # DBI 0.5-1 (2016-09-09) - Documentation and example updates. # DBI 0.5 (2016-08-11, CRAN release) - Interface changes - `dbDataType()` maps `character` values to `"TEXT"` by default (#102). - The default implementation of `dbQuoteString()` doesn't call `encodeString()` anymore: Neither SQLite nor Postgres understand e.g. `\n` in a string literal, and all of SQLite, Postgres, and MySQL accept an embedded newline (#121). - Interface enhancements - New `dbSendStatement()` generic, forwards to `dbSendQuery()` by default (#20, #132). - New `dbExecute()`, calls `dbSendStatement()` by default (#109, @bborgesr). - New `dbWithTransaction()` that calls `dbBegin()` and `dbCommit()`, and `dbRollback()` on failure (#110, @bborgesr). - New `dbBreak()` function which allows aborting from within `dbWithTransaction()` (#115, #133). - Export `dbFetch()` and `dbQuoteString()` methods. - Documentation improvements: - One example per function (except functions scheduled for deprecation) (#67). - Consistent layout and identifier naming. - Better documentation of generics by adding links to the class and related generics in the "See also" section under "Other DBI... generics" (#130). S4 documentation is directed to a hidden page to unclutter documentation index (#59). - Fix two minor vignette typos (#124, @mdsumner). - Add package documentation. - Remove misleading parts in `dbConnect()` documentation (#118). - Remove misleading link in `dbDataType()` documentation. - Remove full stop from documentation titles. - New help topic "DBIspec" that contains the full DBI specification (currently work in progress) (#129). - HTML documentation generated by `staticdocs` is now uploaded to https://rstats-db.github.io/DBI for each build of the "production" branch (#131). - Further minor changes and fixes. - Internal - Use `contains` argument instead of `representation()` to denote base classes (#93). - Remove redundant declaration of transaction methods (#110, @bborgesr). # DBI 0.4-1 (2016-05-07, CRAN release) - The default `show()` implementations silently ignore all errors. Some DBI drivers (e.g., RPostgreSQL) might fail to implement `dbIsValid()` or the other methods used. # DBI 0.4 (2016-04-30) * New package maintainer: Kirill Müller. * `dbGetInfo()` gains a default method that extracts the information from `dbGetStatement()`, `dbGetRowsAffected()`, `dbHasCompleted()`, and `dbGetRowCount()`. This means that most drivers should no longer need to implement `dbGetInfo()` (which may be deprecated anyway at some point) (#55). * `dbDataType()` and `dbQuoteString()` are now properly exported. * The default implementation for `dbDataType()` (powered by `dbiDataType()`) now also supports `difftime` and `AsIs` objects and lists of `raw` (#70). * Default `dbGetQuery()` method now always calls `dbFetch()`, in a `tryCatch()` block. * New generic `dbBind()` for binding values to a parameterised query. * DBI gains a number of SQL generation functions. These make it easier to write backends by implementing common operations that are slightly tricky to do absolutely correctly. * `sqlCreateTable()` and `sqlAppendTable()` create tables from a data frame and insert rows into an existing table. These will power most implementations of `dbWriteTable()`. `sqlAppendTable()` is useful for databases that support parameterised queries. * `sqlRownamesToColumn()` and `sqlColumnToRownames()` provide a standard way of translating row names to and from the database. * `sqlInterpolate()` and `sqlParseVariables()` allows databases without native parameterised queries to use parameterised queries to avoid SQL injection attacks. * `sqlData()` is a new generic that converts a data frame into a data frame suitable for sending to the database. This is used to (e.g.) ensure all character vectors are encoded as UTF-8, or to convert R varible types (like factor) to types supported by the database. * The `sqlParseVariablesImpl()` is now implemented purely in R, with full test coverage (#83, @hannesmuehleisen). * `dbiCheckCompliance()` has been removed, the functionality is now available in the `DBItest` package (#80). * Added default `show()` methods for driver, connection and results. * New concrete `ANSIConnection` class and `ANSI()` function to generate a dummy ANSI compliant connection useful for testing. * Default `dbQuoteString()` and `dbQuoteIdentifer()` methods now use `encodeString()` so that special characters like `\n` are correctly escaped. `dbQuoteString()` converts `NA` to (unquoted) NULL. * The initial DBI proposal and DBI version 1 specification are now included as a vignette. These are there mostly for historical interest. * The new `DBItest` package is described in the vignette. * Deprecated `print.list.pairs()`. * Removed unused `dbi_dep()`. # Version 0.3.1 * Actually export `dbIsValid()` :/ * `dbGetQuery()` uses `dbFetch()` in the default implementation. # Version 0.3.0 ## New and enhanced generics * `dbIsValid()` returns a logical value describing whether a connection or result set (or other object) is still valid. (#12). * `dbQuoteString()` and `dbQuoteIdentifier()` to implement database specific quoting mechanisms. * `dbFetch()` added as alias to `fetch()` to provide consistent name. Implementers should define methods for both `fetch()` and `dbFetch()` until `fetch()` is deprecated in 2015. For now, the default method for `dbFetch()` calls `fetch()`. * `dbBegin()` begins a transaction (#17). If not supported, DB specific methods should throw an error (as should `dbCommit()` and `dbRollback()`). ## New default methods * `dbGetStatement()`, `dbGetRowsAffected()`, `dbHasCompleted()`, and `dbGetRowCount()` gain default methods that extract the appropriate elements from `dbGetInfo()`. This means that most drivers should no longer need to implement these methods (#13). * `dbGetQuery()` gains a default method for `DBIConnection` which uses `dbSendQuery()`, `fetch()` and `dbClearResult()`. ## Deprecated features * The following functions are soft-deprecated. They are going away, and developers who use the DBI should begin preparing. The formal deprecation process will begin in July 2015, where these function will emit warnings on use. * `fetch()` is replaced by `dbFetch()`. * `make.db.names()`, `isSQLKeyword()` and `SQLKeywords()`: a black list based approach is fundamentally flawed; instead quote strings and identifiers with `dbQuoteIdentifier()` and `dbQuoteString()`. * `dbGetDBIVersion()` is deprecated since it's now just a thin wrapper around `packageVersion("DBI")`. * `dbSetDataMappings()` (#9) and `dbCallProc()` (#7) are deprecated as no implementations were ever provided. ## Other improvements * `dbiCheckCompliance()` makes it easier for implementors to check that their package is in compliance with the DBI specification. * All examples now use the RSQLite package so that you can easily try out the code samples (#4). * `dbDriver()` gains a more effective search mechanism that doesn't rely on packages being loaded (#1). * DBI has been converted to use roxygen2 for documentation, and now most functions have their own documentation files. I would love your feedback on how we could make the documentation better! # Version 0.2-7 * Trivial changes (updated package fields, daj) # Version 0.2-6 * Removed deprecated \synopsis in some Rd files (thanks to Prof. Ripley) # Version 0.2-5 * Code cleanups contributed by Matthias Burger: avoid partial argument name matching and use TRUE/FALSE, not T/F. * Change behavior of make.db.names.default to quote SQL keywords if allow.keywords is FALSE. Previously, SQL keywords would be name mangled with underscores and a digit. Now they are quoted using '"'. # Version 0.2-4 * Changed license from GPL to LPGL * Fixed a trivial typo in documentation # Version 0.1-10 * Fixed documentation typos. # Version 0.1-9 * Trivial changes. # Version 0.1-8 * A trivial change due to package.description() being deprecated in 1.9.0. # Version 0.1-7 * Had to do a substantial re-formatting of the documentation due to incompatibilities introduced in 1.8.0 S4 method documentation. The contents were not changed (modulo fixing a few typos). Thanks to Kurt Hornik and John Chambers for their help. # Version 0.1-6 * Trivial documentation changes (for R CMD check's sake) # Version 0.1-5 * Removed duplicated setGeneric("dbSetDataMappings") # Version 0.1-4 * Removed the "valueClass" from some generic functions, namely, dbListConnections, dbListResults, dbGetException, dbGetQuery, and dbGetInfo. The reason is that methods for these generics could potentially return different classes of objects (e.g., the call dbGetInfo(res) could return a list of name-value pairs, while dbGetInfo(res, "statement") could be a character vector). * Added 00Index to inst/doc * Added dbGetDBIVersion() (simple wrapper to package.description). # Version 0.1-3 * ??? Minor changes? # Version 0.1-2 * An implementation based on version 4 classes and methods. * Incorporated (mostly Tim Keitt's) comments. DBI/MD50000644000176200001440000003103514160037606011165 0ustar liggesusersd12c52c9c45cea11823ffdca01f4bcb9 *DESCRIPTION 6ff765dc8e0e65b47031bdff02969b04 *NAMESPACE 78876b85ababc9c0654faaf28c40a040 *NEWS.md 817169da9d15d602e848ac9a68165dcf *R/ANSI.R 1e200df98e96fedefa64d7380618c94f *R/DBI-package.R 23e6fe0453728d4ab4cf84ba79433735 *R/DBIConnection.R d1d16ecd735aacef2faaefa9b39de553 *R/DBIConnector.R 70a5f74423c092a6e176c57596a7787b *R/DBIDriver.R 3e331aea5911679a3e5cc3471aded013 *R/DBIObject.R b56706702384fe74719397d7d086f585 *R/DBIResult.R c1b2d78e3b87ad1576adc988ce630bfc *R/Id.R b2f768366db7da783ad65fca06d8012f *R/SQL.R caeed8e6b8e2eb866e8d2adee097cffb *R/SQLKeywords.R 2e3f7c99fc5daf79625510e2639a5243 *R/SQLKeywords_DBIObject.R cc8c512231d31031200e31d760ad008b *R/SQLKeywords_missing.R 4d9aa53c1ba51a9cdc12438530a86b64 *R/data-types.R 19cd20ad37a89a7fd9046bd159252be1 *R/data.R 7572d5880b6036bb71270b53522956b9 *R/dbAppendTable.R 4b08e01ceef1d4884f59fdea1f7343a7 *R/dbAppendTable_DBIConnection.R e900a6ce7e29178aa307ca2169433da4 *R/dbBegin.R fb5874ef851b0f44df5999142f4e4cbb *R/dbBind.R 4d18b71c11b50a6c736046aa8c6b5e81 *R/dbCallProc.R f2521aba6247662240f95bff4a10dcdd *R/dbCanConnect.R 8e74ceea09e2d78e7578dec900608289 *R/dbCanConnect_DBIDriver.R 43f02cce5339f5e1e3c37c7458e9b4f4 *R/dbClearResult.R d212caf25d7a2fdc5c99b225a7226d2c *R/dbColumnInfo.R 1dabdc46053a1f642277624017c1450b *R/dbCommit.R a96028439124488e301b9c16e53c9a0a *R/dbConnect.R 2650c8652de8a83756fedc456a03d476 *R/dbConnect_DBIConnector.R a093bcbb6b6608b3e19447bce475ccaf *R/dbCreateTable.R b4ca03a0e43bed3b3cb9727f60ce8972 *R/dbCreateTable_DBIConnection.R b359c07a2f54c3cfe25cc0ac3b9421ef *R/dbDataType.R e86feef168b8c012513dd50b015fcd9e *R/dbDataType_DBIConnector.R 0c75124e20e8fb03d107b30a27c19760 *R/dbDataType_DBIObject.R 4b7eeb04c2b1c990083f0072a128dfea *R/dbDisconnect.R 9730eb3bd7ce36dadf1f68d425fa0fc4 *R/dbDriver.R 77006a92266de53743b1b27dc2166e52 *R/dbDriver_character.R 61e346f7708cd249448ccc11b5497bda *R/dbExecute.R 0ccf1a45aeaa32d7d277395b2d7c012d *R/dbExecute_DBIConnection_character.R 7987238a2e9e2a8e0f8aab32e1816deb *R/dbExistsTable.R f5c1fa86bf5c8090e849d85127669ba1 *R/dbExistsTable_DBIConnection_Id.R 9b6f933d05160982f8c9969fdc0e6750 *R/dbFetch.R e98adbf9e505b36bceaaea8f3c935573 *R/dbFetch_DBIResult.R 368559ffffca98b8b34631ec7ebe7ca8 *R/dbGetConnectArgs.R 115ea9a3b433f0f7e040f4eba201111e *R/dbGetConnectArgs_DBIConnector.R 2982ccce2dd23ab15b2a6b3d4e0697a3 *R/dbGetException.R 7fdbe0ee4959a6ea241344b4ac934682 *R/dbGetInfo.R 2fd40282c5a9b312901ecc629586f37f *R/dbGetInfo_DBIResult.R fb52c0316ccb3389c1293eac19b411ba *R/dbGetQuery.R 68ae362dc37aa0d769441a1938e027e8 *R/dbGetQuery_DBIConnection_character.R 717dba44caab966637043b82f71d36cb *R/dbGetRowCount.R 634e193018ac1d2572e8b79d768fc471 *R/dbGetRowsAffected.R 2e9928945258271da9dc1df348ce6da7 *R/dbGetStatement.R 7af25f02a15b478ff9dbc72a6618d56d *R/dbHasCompleted.R 90b02cdda38b088e5303833fe2ccc55a *R/dbIsReadOnly.R 20c1c442df9885b1dde2a79b4d5fdc52 *R/dbIsReadOnly_DBIConnector.R 083f467fd264c59ccafacef611d3429d *R/dbIsReadOnly_DBIObject.R 86309cf3ba1e794f4e666da7d719ec0a *R/dbIsValid.R 0b8b92d0d78cebc2b88ba17b3ebe8574 *R/dbListConnections.R bcc26a00d1df4523186b977ececb71e6 *R/dbListFields.R fc143f42ee66f163a2029905c0d0376f *R/dbListFields_DBIConnection_Id.R 7c220952130574853a9892960a784d1b *R/dbListFields_DBIConnection_character.R 9c0d0de577fe8d4a76f75540910cdda0 *R/dbListObjects.R e2cdc2847371073a478df43ff17b5c9d *R/dbListObjects_DBIConnection_ANY.R a465bb1c64e72d5e7fc3c60e39bcacaf *R/dbListResults.R fbe390d4c0a7ab1afeb6792cf40b4827 *R/dbListTables.R 820b117960e8f002b0d4602cd0409af2 *R/dbQuoteIdentifier.R ebbc86a214e4b1a2525965479aaf02e7 *R/dbQuoteIdentifier_DBIConnection.R 1c63676069d58c4bf193742e2d7113b8 *R/dbQuoteLiteral.R 8b9f442229fbe6c60615bdd903ff0c51 *R/dbQuoteLiteral_DBIConnection.R 7d0c587f2e3894ba81e292c1b5d6a5d6 *R/dbQuoteString.R 0974935ea604879e4367f367d0d94bad *R/dbQuoteString_DBIConnection.R df9f88d2916a592bc4a5155650c17c0a *R/dbReadTable.R 1be9fdeeea4c0bfcb3321b534b80097d *R/dbReadTable_DBIConnection_Id.R 6c57c7769430b25aff80bb33964883ff *R/dbReadTable_DBIConnection_character.R 9ab3c4948ea1bcb4a84e2a790de405e5 *R/dbRemoveTable.R f8b15fec3e7da5e74551779fb36d315b *R/dbRemoveTable_DBIConnection_Id.R d1bb64bedf72456c277d755dc3019bd7 *R/dbRollback.R 07b0ca3b57f1a36fd7b060086fd8f504 *R/dbSendQuery.R a2a71a4df9411fef0812dbb7e05d680a *R/dbSendStatement.R f6e93624dcaae0b79400b2dbd19eeff6 *R/dbSendStatement_DBIConnection_character.R ffd26e8de2efd581f655c68e19430651 *R/dbSetDataMappings.R e673e520bbf8d0c8b7635474872211f9 *R/dbUnloadDriver.R 606bbb524a12fedd2ec7a99e0d64b95a *R/dbUnquoteIdentifier.R 72ab01f8f0d5f50db53575c44b18b603 *R/dbUnquoteIdentifier_DBIConnection.R f71dcc590f2b9d2833766bf02a2acb3c *R/dbWithTransaction.R e5c2e8bbef965ec03de7a4b7d4ee783a *R/dbWithTransaction_DBIConnection.R 15fb375f0dd0dc2e351639daa3fdd73d *R/dbWriteTable.R 09a5767589db14c3c3ba73553030ed23 *R/dbWriteTable_DBIConnection_Id_ANY.R 8277fb3db3b97aa958d0c4061de85f30 *R/dbiDataType.R 65e5f21c95d37a35f6c8e9bf26af4924 *R/dbiDataType_AsIs.R e14fcdbe5bd13075c2193fa6ffaf5725 *R/dbiDataType_Date.R ac198cf63328dbe7fd1711cb184b8676 *R/dbiDataType_POSIXct.R 94c34b67f3b9c2182a76f58b514294b9 *R/dbiDataType_character.R c83e452b5b55e1fa6a4db75c846ed422 *R/dbiDataType_data.frame.R 450179c1d1f5a291ff0356d162a16dd3 *R/dbiDataType_difftime.R 6b84efab5913fff83c08e4395add3887 *R/dbiDataType_integer.R 5b77a56457bb158205ed0ba49cf09422 *R/dbiDataType_list.R 2ef2c7e953c5fe370c087dc1a47cb8cd *R/dbiDataType_logical.R 5212cee8aa1f93cb8858891aa051cd6f *R/dbiDataType_numeric.R 13f069da0ab2c570d77639bc362a5c3a *R/deprecated.R 1287ce9bc9bb3a7d8a6c5107427daa38 *R/fetch.R 5651cd8a666eb10359ab0a1796e3436c *R/hms.R 91b19c51abe58a6d1de6a45579350694 *R/interpolate.R 4126e52937f6f393db327b732c514ae6 *R/isSQLKeyword.R 0a88ed941faa636132ad3d52f73af8cf *R/isSQLKeyword_DBIObject_character.R c86571daef158f70da25b27202a5d650 *R/make.db.names.R b41c1f90d364dcc59258aba6b8655a11 *R/make.db.names_DBIObject_character.R d299a8067c3c4c3f324ce07324b41030 *R/methods_as_rd.R 5cf4b10a4073c16226430c1d11978ddf *R/rownames.R d0f80664d65f61b3333651242759530d *R/show_AnsiConnection.R 3517272e0ee5248cb2cda618e5725e06 *R/show_DBIConnection.R 44656888881609c3aaaba36d118bd00b *R/show_DBIConnector.R c56d4e1596bc44c0b69148d3a8e75668 *R/show_DBIDriver.R ea4f9428ed80facc11f600319d096efb *R/show_DBIResult.R c55be6c2418396a61394653ab4d667aa *R/show_Id.R 5b47c215dc77c4743a76852e264e67ce *R/show_SQL.R 16e381cd08503496a478b7a3dba9587f *R/sqlAppendTable.R e825cf3dcced0d263014497aa264dcbe *R/sqlAppendTableTemplate.R b6e559aa5ede9ec6945a695e7dab0600 *R/sqlAppendTable_DBIConnection.R 5ea332514fcdf48a6faacfdd863e2d83 *R/sqlCreateTable.R c04a2ea0203342e3790c5cd77a4ffa75 *R/sqlCreateTable_DBIConnection.R ebebc5daa4c00c0b13e02bb46cded835 *R/sqlData.R 24f1bf8225b3cd27b652ecd726b0b7bf *R/sqlData_DBIConnection.R df4cb8a206a91e026a1e43a4d471f10b *R/sqlInterpolate.R 89177ca946708c77672ede3dc9b2d2ad *R/sqlInterpolate_DBIConnection.R f25218d24f247f5d5b8b70a3d878e082 *R/sqlParseVariables.R a0349cfd6f9eab18042640fae7fcf5c2 *R/sqlParseVariables_DBIConnection.R 42f3ac8f9e3bf2c02205e18b7be385f3 *R/summary.R 85cab3f8e3af768d579592639c24a40c *R/summary_DBIObject.R fb3ba06383b688b96ebf7b64683b73f1 *R/transactions.R adcb4efb1b41ec729982ba34097a7ed3 *README.md 38525c414a41ed0fd51182e3fcd77566 *build/DBI.pdf 15055d033ec2ac0bbf2b735b347fc756 *build/vignette.rds 4e73dc48e922e4e0cb9f624df2dfef44 *inst/doc/DBI-1.Rmd 6be9d59ad1c85da7a898dd38a5895c06 *inst/doc/DBI-1.html b6f1d5dfd18575d046eb0932516b301b *inst/doc/DBI-advanced.R ece6e09a4568608b310470d15c22376c *inst/doc/DBI-advanced.Rmd 6ece8b486cf600a3b47194c8897e7ebd *inst/doc/DBI-advanced.html 34160f59e74b1a554702708396d21474 *inst/doc/DBI-history.Rmd c1404d8b453485d8301e61026e8d3515 *inst/doc/DBI-history.html f85818112b5e279dacd75bfe2238ac77 *inst/doc/DBI-proposal.Rmd 537a3fba4f455eac8d5800f808d00838 *inst/doc/DBI-proposal.html 6f35bbf96dc27c274822df2626cc37ea *inst/doc/DBI.R 6ca33cffb8ee44d0e38ef854a22f9c55 *inst/doc/DBI.Rmd ce733cbc669e7304eb3e29204debe171 *inst/doc/DBI.html 5394693f55b11b3418fb826ba85d10a8 *inst/doc/backend.R 079397ec63b690111df65842436e40ad *inst/doc/backend.Rmd 3c22ede7accecb46919b1c6d4d0ddd36 *inst/doc/backend.html f49cc884006de5d05ea705b6607d6267 *inst/doc/spec.R 8461114d02dc23e5310a0ad07e4c66c0 *inst/doc/spec.Rmd 943d3c4298331a6026c4f445fba5be5c *inst/doc/spec.html 4354c7d19733ce8222bb9c06ef0db20d *man/ANSI.Rd 78ac8f113a64575cf06fd724c43a95c0 *man/DBI-package.Rd 76fed9cf88db1970957a67772538b0cf *man/DBIConnection-class.Rd 5b66a36dbabeb52ab41e0bf3bae58343 *man/DBIConnector-class.Rd d9a7e5de82edb9c413ae1b30b770dcaf *man/DBIDriver-class.Rd f0d210b0e825a0b9c9d86243a9921453 *man/DBIObject-class.Rd 641029116a57fc09492154d263eeeff5 *man/DBIResult-class.Rd 7ab72e2144c52c0fc8dbc61a73a99a0d *man/Id.Rd 0abe5e81e5b910eb92f501e0d12102f5 *man/SQL.Rd 4c2a7a148ba619c69687411ff3070e04 *man/dbAppendTable.Rd 7300d7936dbb648e6b686692ba19f981 *man/dbBind.Rd f087a3da11250b3d4671313d3218da0c *man/dbCallProc.Rd 4d4b0d4b3c61d4188b925e112409d2e6 *man/dbCanConnect.Rd be3cb287a4ca888b8b216c2de911d301 *man/dbClearResult.Rd 8c145c123385d2a455d8b70e92d8caf9 *man/dbColumnInfo.Rd bb247602c8aa40c5c070c60247302f15 *man/dbConnect.Rd a4f82a38469c178f99a23a49a06a9908 *man/dbCreateTable.Rd 83d707affbc8e882db9a5a8afd56c669 *man/dbDataType.Rd 676cd66726832b544159bf027f265a80 *man/dbDisconnect.Rd 9f41ff3a260ef4e852389e194006fab4 *man/dbDriver.Rd a6c3c02521ba78adc10c4bf6540350e1 *man/dbExecute.Rd 33770437f270bddefd5e704726e14aab *man/dbExistsTable.Rd 935d6ca8f19dadc11eec8b1b34e41b3d *man/dbFetch.Rd 4c384dd0715a6501ea6ad25ffd1b5bbd *man/dbGetConnectArgs.Rd 600709b1318e882e99b98e90fa8ba7e7 *man/dbGetDBIVersion.Rd 49955b5cea170a3a5735aac7e4c18dbe *man/dbGetException.Rd a8f50c5f39a269cd62815df4e8d34bf2 *man/dbGetInfo.Rd 59443cf6d8f9a7a689acde9186b37cad *man/dbGetQuery.Rd cf8215ef329ae9ab61cd6c38b320736c *man/dbGetRowCount.Rd dab372a2ea818a96dec8f38845acc767 *man/dbGetRowsAffected.Rd ef73d8b5a98dd0b5cbac5190b82a0a6d *man/dbGetStatement.Rd 41dd16741d8af0b2ac8e3979ae49eafe *man/dbHasCompleted.Rd dad1e166d86b6c09e9f43d48ff10e770 *man/dbIsReadOnly.Rd 38927176b1ea1ce9f2edddf04ad27a99 *man/dbIsValid.Rd 45195aabed941c5835837ef3944a48f6 *man/dbListConnections.Rd da948742d26e60be22f329f9bb023172 *man/dbListFields.Rd 20c6c045dc0af05db7f9de91cf32b513 *man/dbListObjects.Rd ac9ee3c2943e5c9b43215a26d7b20968 *man/dbListResults.Rd 34e0ff4958dc9267152ee6bfd2e855dd *man/dbListTables.Rd 03e339a8a9c94898f7cf15d359b270a3 *man/dbQuoteIdentifier.Rd e31f39f02a1443311dfab4f245861cb8 *man/dbQuoteLiteral.Rd e0ea32af699a921f1165a7dff4351529 *man/dbQuoteString.Rd e4ecbb3d890225096106f3d061c32324 *man/dbReadTable.Rd 9376f30d65f8b385481d5ef053c9d8c5 *man/dbRemoveTable.Rd 19bd0f3b5d96bfdac11bb0c0683bcc1a *man/dbSendQuery.Rd 90e4020778dfaf626af25717bb6aeefe *man/dbSendStatement.Rd 62847b9c4d0251dd8ba14ab4d1f2005f *man/dbSetDataMappings.Rd 4458a14f308996738ea23ab15007f558 *man/dbUnquoteIdentifier.Rd 2e8d6dd4e8286bb4a7f00bcbb35fef5b *man/dbWithTransaction.Rd c730310595d9c6b83172f4a45278c8f6 *man/dbWriteTable.Rd 89079da7ef6fbb2fd77d0128fe2aaf6b *man/hidden_aliases.Rd ffba08bcb57becb6455b5165b6ef441d *man/make.db.names.Rd 4a7f8a265551b2f3dea24c3692721638 *man/rownames.Rd 42d1c012bdf2453fec3b1cef801d3c16 *man/sqlAppendTable.Rd 21ac1cf9bdb8af4dbd8b57ba0006fb73 *man/sqlCreateTable.Rd 74affb7a5fa43b3dced1417109295019 *man/sqlData.Rd b13d07545cc0f0c49f104d50141d359f *man/sqlInterpolate.Rd f0d18acb231943d6f25691e6d1558492 *man/sqlParseVariables.Rd 35fbc85962888441ad956a8cd3768b1e *man/transactions.Rd 01fb93108574d5bb9e66cce0d2185692 *tests/testthat.R a607e1deab234336d12e88ad2b80fd80 *tests/testthat/helper-dummy.R 6d7152ea22dc498b844cb6d912b1c771 *tests/testthat/setup.R 4baa6d1e48c09444fa8a3087f6ea812f *tests/testthat/test-data-type.R 46eb167121b3d1cf03abef8fb187794e *tests/testthat/test-interpolate.R 58549e35e48e852f047d0c6296608ac2 *tests/testthat/test-methods.R dba5332590ae45221440cf8a42a32db6 *tests/testthat/test-quote.R e8afe06a3e597ec1063be9f351b63a6c *tests/testthat/test-quoting.R 936863cb0e7bb14bf6f3e913d28a77d1 *tests/testthat/test-rownames.R 2540cd6a5d6930d4bfcf896c82f92f44 *tests/testthat/test-sql-df.R bfcf23c10db1311fa370686525eaee37 *tests/testthat/test-table-insert.R 4e73dc48e922e4e0cb9f624df2dfef44 *vignettes/DBI-1.Rmd ece6e09a4568608b310470d15c22376c *vignettes/DBI-advanced.Rmd 34160f59e74b1a554702708396d21474 *vignettes/DBI-history.Rmd f85818112b5e279dacd75bfe2238ac77 *vignettes/DBI-proposal.Rmd 6ca33cffb8ee44d0e38ef854a22f9c55 *vignettes/DBI.Rmd 079397ec63b690111df65842436e40ad *vignettes/backend.Rmd 67cca7009a40f5c6bab58418607deb57 *vignettes/biblio.bib 16facd043de5250ab88f5b3badef9ab0 *vignettes/hierarchy.png 8461114d02dc23e5310a0ad07e4c66c0 *vignettes/spec.Rmd DBI/inst/0000755000176200001440000000000014157714560011637 5ustar liggesusersDBI/inst/doc/0000755000176200001440000000000014157714560012404 5ustar liggesusersDBI/inst/doc/DBI-advanced.R0000644000176200001440000001217414157714552014676 0ustar liggesusers## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) knit_print.data.frame <- function(x, ...) { print(head(x, 3)) if (nrow(x) > 3) { cat("Showing 3 out of", nrow(x), "rows.\n") } invisible(x) } registerS3method("knit_print", "data.frame", "knit_print.data.frame") ## ----------------------------------------------------------------------------- library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = 'G'") df <- dbFetch(res, n = 3) dbClearResult(res) head(df, 3) ## ----------------------------------------------------------------------------- res <- dbSendQuery(con, "SELECT * FROM film") while (!dbHasCompleted(res)) { chunk <- dbFetch(res, n = 300) print(nrow(chunk)) } dbClearResult(res) ## ----quote-------------------------------------------------------------------- safe_id <- dbQuoteIdentifier(con, "rating") safe_param <- dbQuoteLiteral(con, "G") query <- paste0("SELECT title, ", safe_id, " FROM film WHERE ", safe_id, " = ", safe_param ) query res <- dbSendQuery(con, query) dbFetch(res) dbClearResult(res) ## ----------------------------------------------------------------------------- id <- "rating" param <- "G" query <- glue::glue_sql("SELECT title, {`id`} FROM film WHERE {`id`} = {param}", .con = con) df <- dbGetQuery(con, query) head(df, 3) ## ----params------------------------------------------------------------------- params <- list("G") safe_id <- dbQuoteIdentifier(con, "rating") query <- paste0("SELECT * FROM film WHERE ", safe_id, " = ?") query res <- dbSendQuery(con, query, params = params) dbFetch(res, n = 3) dbClearResult(res) ## ----multi-param-------------------------------------------------------------- q_params <- list("G", 90) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ## ----dbbind------------------------------------------------------------------- res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list("G")) dbFetch(res, n = 3) dbBind(res, list("PG")) dbFetch(res, n = 3) dbClearResult(res) ## ----bind_quotestring--------------------------------------------------------- res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list(c("G", "PG"))) dbFetch(res, n = 3) dbClearResult(res) ## ----bind-multi-param--------------------------------------------------------- q_params <- list(c("G", "PG"), c(90, 120)) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ## ----disconnect--------------------------------------------------------------- dbDisconnect(con) ## ----------------------------------------------------------------------------- library(DBI) con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cars", head(cars, 3)) dbExecute( con, "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" ) rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (4, 4), (5, 5), (6, 6)" ) dbGetRowsAffected(rs) dbClearResult(rs) dbReadTable(con, "cars") dbDisconnect(con) ## ----------------------------------------------------------------------------- con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cash", data.frame(amount = 100)) dbWriteTable(con, "account", data.frame(amount = 2000)) withdraw <- function(amount) { # All operations must be carried out as logical unit: dbExecute(con, "UPDATE cash SET amount = amount + ?", list(amount)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(amount)) } withdraw_transacted <- function(amount) { # Ensure atomicity dbBegin(con) # Perform operation withdraw(amount) # Persist results dbCommit(con) } withdraw_transacted(300) ## ----------------------------------------------------------------------------- dbReadTable(con, "cash") dbReadTable(con, "account") ## ----------------------------------------------------------------------------- withdraw_if_funds <- function(amount) { dbBegin(con) withdraw(amount) # Rolling back after detecting negative value on account: if (dbReadTable(con, "account")$amount >= 0) { dbCommit(con) TRUE } else { message("Insufficient funds") dbRollback(con) FALSE } } withdraw_if_funds(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ## ----error = TRUE------------------------------------------------------------- withdraw_safely <- function(amount) { dbWithTransaction(con, { withdraw(amount) if (dbReadTable(con, "account")$amount < 0) { stop("Error: insufficient funds", call. = FALSE) } }) } withdraw_safely(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ## ----------------------------------------------------------------------------- dbDisconnect(con) DBI/inst/doc/backend.html0000644000176200001440000010365414157714556014677 0ustar liggesusersImplementing a new backend

Implementing a new backend

Hadley Wickham, Kirill Müller

The goal of this document is to help you implement a new backend for DBI.

If you are writing a package that connects a database to R, I highly recommend that you make it DBI compatible because it makes your life easier by spelling out exactly what you need to do. The consistent interface provided by DBI makes it easier for you to implement the package (because you have fewer arbitrary choices to make), and easier for your users (because it follows a familiar pattern). In addition, the DBItest package provides test cases which you can easily incorporate in your package.

I’ll illustrate the process using a fictional database called Kazam.

Getting started

Start by creating a package. It’s up to you what to call the package, but following the existing pattern of RSQLite, RMySQL, RPostgres and ROracle will make it easier for people to find it. For this example, I’ll call my package RKazam.

A ready-to-use template package is available at https://github.com/r-dbi/RKazam/. You can start by creating a new GitHub repository from this template, or by copying the package code. Rename “Kazam” to your desired name everywhere. The template package already contains dummy implementations for all classes and methods.

If you chose to create the package manually, make sure to include in your DESCRIPTION:

Imports:
  DBI (>= 0.3.0),
  methods
Suggests:
  DBItest, testthat

Importing DBI is fine, because your users are not supposed to attach your package anyway; the preferred method is to attach DBI and use explicit qualification via :: to access the driver in your package (which needs to be done only once).

Testing

Why testing at this early stage? Because testing should be an integral part of the software development cycle. Test right from the start, add automated tests as you go, finish faster (because tests are automated) while maintaining superb code quality (because tests also check corner cases that you might not be aware of). Don’t worry: if some test cases are difficult or impossible to satisfy, or take too long to run, you can just turn them off.

Take the time now to head over to the DBItest vignette at vignette("test", package = "DBItest"). You will find a vast amount of ready-to-use test cases that will help you in the process of implementing your new DBI backend.

Add custom tests that are not covered by DBItest at your discretion, or enhance DBItest and file a pull request if the test is generic enough to be useful for many DBI backends.

Driver

Start by making a driver class which inherits from DBIDriver. This class doesn’t need to do anything, it’s just used to dispatch other generics to the right method. Users don’t need to know about this, so you can remove it from the default help listing with @keywords internal:

#' Driver for Kazam database.
#'
#' @keywords internal
#' @export
#' @import DBI
#' @import methods
setClass("KazamDriver", contains = "DBIDriver")

The driver class was more important in older versions of DBI, so you should also provide a dummy dbUnloadDriver() method.

#' @export
#' @rdname Kazam-class
setMethod("dbUnloadDriver", "KazamDriver", function(drv, ...) {
  TRUE
})

If your package needs global setup or tear down, do this in the .onLoad() and .onUnload() functions.

You might also want to add a show method so the object prints nicely:

setMethod("show", "KazamDriver", function(object) {
  cat("<KazamDriver>\n")
})

Next create Kazam() which instantiates this class.

#' @export
Kazam <- function() {
  new("KazamDriver")
}

Kazam()
#> <KazamDriver>

Connection

Next create a connection class that inherits from DBIConnection. This should store all the information needed to connect to the database. If you’re talking to a C api, this will include a slot that holds an external pointer.

#' Kazam connection class.
#'
#' @export
#' @keywords internal
setClass("KazamConnection",
  contains = "DBIConnection",
  slots = list(
    host = "character",
    username = "character",
    # and so on
    ptr = "externalptr"
  )
)

Now you have some of the boilerplate out of the way, you can start work on the connection. The most important method here is dbConnect() which allows you to connect to a specified instance of the database. Note the use of @rdname Kazam. This ensures that Kazam() and the connect method are documented together.

#' @param drv An object created by \code{Kazam()}
#' @rdname Kazam
#' @export
#' @examples
#' \dontrun{
#' db <- dbConnect(RKazam::Kazam())
#' dbWriteTable(db, "mtcars", mtcars)
#' dbGetQuery(db, "SELECT * FROM mtcars WHERE cyl == 4")
#' }
setMethod("dbConnect", "KazamDriver", function(drv, ...) {
  # ...

  new("KazamConnection", host = host, ...)
})
  • Replace ... with the arguments needed to connect to your database. You’ll always need to include ... in the arguments, even if you don’t use it, for compatibility with the generic.

  • This is likely to be where people first come for help, so the examples should show how to connect to the database, and how to query it. (Obviously these examples won’t work yet.) Ideally, include examples that can be run right away (perhaps relying on a publicly hosted database), but failing that surround in \dontrun{} so people can at least see the code.

Next, implement show() and dbDisconnect() methods.

Results

Finally, you’re ready to implement the meat of the system: fetching results of a query into a data frame. First define a results class:

#' Kazam results class.
#'
#' @keywords internal
#' @export
setClass("KazamResult",
  contains = "DBIResult",
  slots = list(ptr = "externalptr")
)

Then write a dbSendQuery() method. This takes a connection and SQL string as arguments, and returns a result object. Again ... is needed for compatibility with the generic, but you can add other arguments if you need them.

#' Send a query to Kazam.
#'
#' @export
#' @examples
#' # This is another good place to put examples
setMethod("dbSendQuery", "KazamConnection", function(conn, statement, ...) {
  # some code
  new("KazamResult", ...)
})

Next, implement dbClearResult(), which should close the result set and free all resources associated with it:

#' @export
setMethod("dbClearResult", "KazamResult", function(res, ...) {
  # free resources
  TRUE
})

The hardest part of every DBI package is writing the dbFetch() method. This needs to take a result set and (optionally) number of records to return, and create a dataframe. Mapping R’s data types to those of your database may require a custom implementation of the dbDataType() method for your connection class:

#' Retrieve records from Kazam query
#' @export
setMethod("dbFetch", "KazamResult", function(res, n = -1, ...) {
  ...
})

# (optionally)

#' Find the database data type associated with an R object
#' @export
setMethod("dbDataType", "KazamConnection", function(dbObj, obj, ...) {
  ...
})

Next, implement dbHasCompleted() which should return a logical indicating if there are any rows remaining to be fetched.

#' @export
setMethod("dbHasCompleted", "KazamResult", function(res, ...) {

})

With these four methods in place, you can now use the default dbGetQuery() to send a query to the database, retrieve results if available and then clean up. Spend some time now making sure this works with an existing database, or relax and let the DBItest package do the work for you.

SQL methods

You’re now on the home stretch, and can make your wrapper substantially more useful by implementing methods that wrap around variations in SQL across databases:

  • dbQuoteString() and dbQuoteIdentifer() are used to safely quote strings and identifiers to avoid SQL injection attacks. Note that the former must be vectorized, but not the latter.

  • dbWriteTable() creates a database table given an R dataframe. I’d recommend using the functions prefixed with sql in this package to generate the SQL. These functions are still a work in progress so please let me know if you have problems.

  • dbReadTable(): a simple wrapper around SELECT * FROM table. Use dbQuoteIdentifer() to safely quote the table name and prevent mismatches between the names allowed by R and the database.

  • dbListTables() and dbExistsTable() let you determine what tables are available. If not provided by your database’s API, you may need to generate sql that inspects the system tables.

  • dbListFields() shows which fields are available in a given table.

  • dbRemoveTable() wraps around DROP TABLE. Start with SQL::sqlTableDrop().

  • dbBegin(), dbCommit() and dbRollback(): implement these three functions to provide basic transaction support. This functionality is currently not tested in the DBItest package.

Metadata methods

There are a lot of extra metadata methods for result sets (and one for the connection) that you might want to implement. They are described in the following.

  • dbIsValid() returns if a connection or a result set is open (TRUE) or closed (FALSE). All further methods in this section are valid for result sets only.

  • dbGetStatement() returns the issued query as a character value.

  • dbColumnInfo() lists the names and types of the result set’s columns.

  • dbGetRowCount() and dbGetRowsAffected() returns the number of rows returned or altered in a SELECT or INSERT/UPDATE query, respectively.

  • dbBind() allows using parametrised queries. Take a look at sqlInterpolate() and sqlParseVariables() if your SQL engine doesn’t offer native parametrised queries.

Full DBI compliance

By now, your package should implement all methods defined in the DBI specification. If you want to walk the extra mile, offer a read-only mode that allows your users to be sure that their valuable data doesn’t get destroyed inadvertently.

DBI/inst/doc/DBI.R0000644000176200001440000000360714157714556013140 0ustar liggesusers## ----setup, include=FALSE,warning=FALSE, message=FALSE------------------------ knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) ## ----------------------------------------------------------------------------- library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) dbListTables(con) dbDisconnect(con) ## ----eval = FALSE------------------------------------------------------------- # con <- dbConnect( # RMariaDB::MariaDB(), # host = "relational.fit.cvut.cz", # port = 3306, # username = "guest", # password = keyring::key_get("relational.fit.cvut.cz", "guest"), # dbname = "sakila" # ) ## ----------------------------------------------------------------------------- con <- dbConnect(RMariaDB::MariaDB(), username = "guest", password = "relational", host = "relational.fit.cvut.cz", port = 3306, dbname = "sakila") dbListFields(con, "film") ## ----------------------------------------------------------------------------- df <- dbReadTable(con, "film") head(df, 3) ## ----------------------------------------------------------------------------- df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006") head(df, 3) ## ----------------------------------------------------------------------------- df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006 AND rating = 'G'") head(df,3) ## ----message=FALSE------------------------------------------------------------ library(dplyr) lazy_df <- tbl(con, "film") %>% filter(release_year == 2006 & rating == "G") %>% select(film_id, title, description) head(lazy_df, 3) ## ----------------------------------------------------------------------------- dbDisconnect(con) DBI/inst/doc/DBI-1.Rmd0000644000176200001440000006003714064774575013623 0ustar liggesusers--- title: "A Common Database Interface (DBI)" author: "R-Databases Special Interest Group" date: "16 June 2003" output: rmarkdown::html_vignette bibliography: biblio.bib vignette: > %\VignetteIndexEntry{A Common Database Interface (DBI)} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- This document describes a common interface between the S language (in its R and S-Plus implementations) and database management systems (DBMS). The interface defines a small set of classes and methods similar in spirit to Perl’s DBI, Java’s JDBC, Python’s DB-API, and Microsoft’s ODBC. # Version {#sec:version} This document describes version 0.1-6 of the database interface API (application programming interface). # Introduction {#sec:intro} The database interface (DBI) separates the connectivity to the DBMS into a “front-end” and a “back-end”. Applications use only the exposed “front-end” API. The facilities that communicate with specific DBMS (Oracle, PostgreSQL, etc.) are provided by “device drivers” that get invoked automatically by the S language evaluator. The following example illustrates some of the DBI capabilities: ```R ## Choose the proper DBMS driver and connect to the server drv <- dbDriver("ODBC") con <- dbConnect(drv, "dsn", "usr", "pwd") ## The interface can work at a higher level importing tables ## as data.frames and exporting data.frames as DBMS tables. dbListTables(con) dbListFields(con, "quakes") if(dbExistsTable(con, "new_results")) dbRemoveTable(con, "new_results") dbWriteTable(con, "new_results", new.output) ## The interface allows lower-level interface to the DBMS res <- dbSendQuery(con, paste( "SELECT g.id, g.mirror, g.diam, e.voltage", "FROM geom_table as g, elec_measures as e", "WHERE g.id = e.id and g.mirrortype = 'inside'", "ORDER BY g.diam")) out <- NULL while(!dbHasCompleted(res)){ chunk <- fetch(res, n = 10000) out <- c(out, doit(chunk)) } ## Free up resources dbClearResult(res) dbDisconnect(con) dbUnloadDriver(drv) ``` (only the first 2 expressions are DBMS-specific – all others are independent of the database engine itself). Individual DBI drivers need not implement all the features we list below (we indicate those that are optional). Furthermore, drivers may extend the core DBI facilities, but we suggest to have these extensions clearly indicated and documented. The following are the elements of the DBI: 1. A set of classes and methods (Section [sec:DBIClasses]) that defines what operations are possible and how they are defined, e.g.: - connect/disconnect to the DBMS - create and execute statements in the DBMS - extract results/output from statements - error/exception handling - information (meta-data) from database objects - transaction management (optional) Some things are left explicitly unspecified, e.g., authentication and even the query language, although it is hard to avoid references to SQL and relational database management systems (RDBMS). 2. Drivers Drivers are collection of functions that implement the functionality defined above in the context of specific DBMS, e.g., mSQL, Informix. 3. Data type mappings (Section [sec:data-mappings].) Mappings and conversions between DBMS data types and R/S objects. All drivers should implement the “basic” primitives (see below), but may chose to add user-defined conversion function to handle more generic objects (e.g., factors, ordered factors, time series, arrays, images). 4. Utilities (Section [sec:utilities].) These facilities help with details such as mapping of identifiers between S and DBMS (e.g., `_` is illegal in R/S names, and `.` is used for constructing compound SQL identifiers), etc. # DBI Classes and Methods {#sec:DBIClasses} The following are the main DBI classes. They need to be extended by individual database back-ends (Sybase, Oracle, etc.) Individual drivers need to provide methods for the generic functions listed here (those methods that are optional are so indicated). *Note: Although R releases prior to 1.4 do not have a formal concept of classes, we will use the syntax of the S Version 4 classes and methods (available in R releases 1.4 and later as library `methods`) to convey precisely the DBI class hierarchy, its methods, and intended behavior.* The DBI classes are `DBIObject`, `DBIDriver`, `DBIConnection` and `DBIResult`. All these are *virtual* classes. Drivers define new classes that extend these, e.g., `PgSQLDriver`, `PgSQLConnection`, and so on. ![Class hierarchy for the DBI. The top two layers are comprised of virtual classes and each lower layer represents a set of driver-specific implementation classes that provide the functionality defined by the virtual classes above.](hierarchy.png) `DBIObject`: : Virtual class[^1] that groups all other DBI classes. `DBIDriver`: : Virtual class that groups all DBMS drivers. Each DBMS driver extends this class. Typically generator functions instantiate the actual driver objects, e.g., `PgSQL`, `HDF5`, `BerkeleyDB`. `DBIConnection`: : Virtual class that encapsulates connections to DBMS. `DBIResult`: : Virtual class that describes the result of a DBMS query or statement. [Q: Should we distinguish between a simple result of DBMS statements e.g., as `delete` from DBMS queries (i.e., those that generate data).] The methods `format`, `print`, `show`, `dbGetInfo`, and `summary` are defined (and *implemented* in the `DBI` package) for the `DBIObject` base class, thus available to all implementations; individual drivers, however, are free to override them as they see fit. `format(x, ...)`: : produces a concise character representation (label) for the `DBIObject` `x`. `print(x, ...)`/`show(x)`: : prints a one-line identification of the object `x`. `summary(object, ...)`: : produces a concise description of the object. The default method for `DBIObject` simply invokes `dbGetInfo(dbObj)` and prints the name-value pairs one per line. Individual implementations may tailor this appropriately. `dbGetInfo(dbObj, ...)`: : extracts information (meta-data) relevant for the `DBIObject` `dbObj`. It may return a list of key/value pairs, individual meta-data if supplied in the call, or `NULL` if the requested meta-data is not available. *Hint:* Driver implementations may choose to allow an argument `what` to specify individual meta-data, e.g., `dbGetInfo(drv, what = max.connections)`. In the next few sub-sections we describe in detail each of these classes and their methods. ## Class `DBIObject` {#sec:DBIObject} This class simply groups all DBI classes, and thus all extend it. ## Class `DBIDriver` {#sec:DBIDriver} This class identifies the database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.) The DBI provides the generator `dbDriver(driverName)` which simply invokes the function `driverName`, which in turn instantiates the corresponding driver object. The `DBIDriver` class defines the following methods: `driverName`: : [meth:driverName] initializes the driver code. The name `driverName` refers to the actual generator function for the DBMS, e.g., `RPgSQL`, `RODBC`, `HDF5`. The driver instance object is used with `dbConnect` (see page ) for opening one or possibly more connections to one or more DBMS. `dbListConnections(drv, ...)`: : list of current connections being handled by the `drv` driver. May be `NULL` if there are no open connections. Drivers that do not support multiple connections may return the one open connection. `dbGetInfo(dbObj, ...)`: : returns a list of name-value pairs of information about the driver. *Hint:* Useful entries could include `name`: : the driver name (e.g., `RODBC`, `RPgSQL`); `driver.version`: : version of the driver; `DBI.version`: : the version of the DBI that the driver implements, e.g., `0.1-2`; `client.version`: : of the client DBMS libraries (e.g., version of the `libpq` library in the case of `RPgSQL`); `max.connections`: : maximum number of simultaneous connections; plus any other relevant information about the implementation, for instance, how the driver handles upper/lower case in identifiers. `dbUnloadDriver(driverName)` (optional): : frees all resources (local and remote) used by the driver. Returns a logical to indicate if it succeeded or not. ## Class `DBIConnection` {#sec:DBIConnection} This virtual class encapsulates the connection to a DBMS, and it provides access to dynamic queries, result sets, DBMS session management (transactions), etc. *Note:* Individual drivers are free to implement single or multiple simultaneous connections. The methods defined by the `DBIConnection` class include: `dbConnect(drv, ...)`: : [meth:dbConnect] creates and opens a connection to the database implemented by the driver `drv` (see Section [sec:DBIDriver]). Each driver will define what other arguments are required, e.g., `dbname` or `dsn` for the database name, `user`, and `password`. It returns an object that extends `DBIConnection` in a driver-specific manner (e.g., the MySQL implementation could create an object of class `MySQLConnection` that extends `DBIConnection`). `dbDisconnect(conn, ...)`: : closes the connection, discards all pending work, and frees resources (e.g., memory, sockets). Returns a logical indicating whether it succeeded or not. `dbSendQuery(conn, statement, ...)`: : submits one statement to the DBMS. It returns a `DBIResult` object. This object is needed for fetching data in case the statement generates output (see `fetch` on page ), and it may be used for querying the state of the operation; see `dbGetInfo` and other meta-data methods on page . `dbGetQuery(conn, statement, ...)`: : submit, execute, and extract output in one operation. The resulting object may be a `data.frame` if the `statement` generates output. Otherwise the return value should be a logical indicating whether the query succeeded or not. `dbGetException(conn, ...)`: : returns a list with elements `errNum` and `errMsg` with the status of the last DBMS statement sent on a given connection (this information may also be provided by the `dbGetInfo` meta-data function on the `conn` object. *Hint:* The ANSI SQL-92 defines both a status code and an status message that could be return as members of the list. `dbGetInfo(dbObj, ...)`: : returns a list of name-value pairs describing the state of the connection; it may return one or more meta-data, the actual driver method allows to specify individual pieces of meta-data (e.g., maximum number of open results/cursors). *Hint:* Useful entries could include `dbname`: : the name of the database in use; `db.version`: : the DBMS server version (e.g., “Oracle 8.1.7 on Solaris”; `host`: : host where the database server resides; `user`: : user name; `password`: : password (is this safe?); plus any other arguments related to the connection (e.g., thread id, socket or TCP connection type). `dbListResults(conn, ...)`: : list of `DBIResult` objects currently active on the connection `conn`. May be `NULL` if no result set is active on `conn`. Drivers that implement only one result set per connection could return that one object (no need to wrap it in a list). *Note: The following are convenience methods that simplify the import/export of (mainly) data.frames. The first five methods implement the core methods needed to `attach` remote DBMS to the S search path. (For details, see @data-management:1991 [@database-classes:1999].)* *Hint:* For relational DBMS these methods may be easily implemented using the core DBI methods `dbConnect`, `dbSendQuery`, and `fetch`, due to SQL reflectance (i.e., one easily gets this meta-data by querying the appropriate tables on the RDBMS). `dbListTables(conn, ...)`: : returns a character vector (possibly of zero-length) of object (table) names available on the `conn` connection. `dbReadTable(conn, name, ...)`: : imports the data stored remotely in the table `name` on connection `conn`. Use the field `row.names` as the `row.names` attribute of the output data.frame. Returns a `data.frame`. [Q: should we spell out how row.names should be created? E.g., use a field (with unique values) as row.names? Also, should `dbReadTable` reproduce a data.frame exported with `dbWriteTable`?] `dbWriteTable(conn, name, value, ...)`: : write the object `value` (perhaps after coercing it to data.frame) into the remote object `name` in connection `conn`. Returns a logical indicating whether the operation succeeded or not. `dbExistsTable(conn, name, ...)`: : does remote object `name` exist on `conn`? Returns a logical. `dbRemoveTable(conn, name, ...)`: : removes remote object `name` on connection `conn`. Returns a logical indicating whether the operation succeeded or not. `dbListFields(conn, name, ...)`: : returns a character vector listing the field names of the remote table `name` on connection `conn` (see `dbColumnInfo()` for extracting data type on a table). *Note: The following methods deal with transactions and stored procedures. All these functions are optional.* `dbCommit(conn, ...)`(optional): : commits pending transaction on the connection and returns `TRUE` or `FALSE` depending on whether the operation succeeded or not. `dbRollback(conn, ...)`(optional): : undoes current transaction on the connection and returns `TRUE` or `FALSE` depending on whether the operation succeeded or not. `dbCallProc(conn, storedProc, ...)`(optional): : invokes a stored procedure in the DBMS and returns a `DBIResult` object. [Stored procedures are *not* part of the ANSI SQL-92 standard and vary substantially from one RDBMS to another.] **Deprecated since 2014:** The recommended way of calling a stored procedure is now - `dbGetQuery` if a result set is returned and - `dbExecute` for data manipulation and other cases that do not return a result set. ## Class `DBIResult` {#sec:DBIResult} This virtual class describes the result and state of execution of a DBMS statement (any statement, query or non-query). The result set `res` keeps track of whether the statement produces output for R/S, how many rows were affected by the operation, how many rows have been fetched (if statement is a query), whether there are more rows to fetch, etc. *Note: Individual drivers are free to allow single or multiple active results per connection.* [Q: Should we distinguish between results that return no data from those that return data?] The class `DBIResult` defines the following methods: `fetch(res, n, ...)`: : [meth:fetch] fetches the next `n` elements (rows) from the result set `res` and return them as a data.frame. A value of `n=-1` is interpreted as “return all elements/rows”. `dbClearResult(res, ...)`: : flushes any pending data and frees all resources (local and remote) used by the object `res` on both sides of the connection. Returns a logical indicating success or not. `dbGetInfo(dbObj, ...)`: : returns a name-value list with the state of the result set. *Hint:* Useful entries could include `statement`: : a character string representation of the statement being executed; `rows.affected`: : number of affected records (changed, deleted, inserted, or extracted); `row.count`: : number of rows fetched so far; `has.completed`: : has the statement (query) finished? `is.select`: : a logical describing whether or not the statement generates output; plus any other relevant driver-specific meta-data. `dbColumnInfo(res, ...)`: : produces a data.frame that describes the output of a query. The data.frame should have as many rows as there are output fields in the result set, and each column in the data.frame should describe an aspect of the result set field (field name, type, etc.) *Hint:* The data.frame columns could include `field.name`: : DBMS field label; `field.type`: : DBMS field type (implementation-specific); `data.type`: : corresponding R/S data type, e.g., `integer`; `precision`/`scale`: : (as in ODBC terminology), display width and number of decimal digits, respectively; `nullable`: : whether the corresponding field may contain (DBMS) `NULL` values; plus other driver-specific information. `dbSetDataMappings(flds, ...)`(optional): : defines a conversion between internal DBMS data types and R/S classes. We expect the default mappings (see Section [sec:data-mappings]) to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. [This topic needs further discussion.] *Note: The following are convenience methods that extract information from the result object (they may be implemented by invoking `dbGetInfo` with appropriate arguments).* `dbGetStatement(res, ...)`(optional): : returns the DBMS statement (as a character string) associated with the result `res`. `dbGetRowsAffected(res, ...)`(optional): : returns the number of rows affected by the executed statement (number of records deleted, modified, extracted, etc.) `dbHasCompleted(res, ...)`(optional): : returns a logical that indicates whether the operation has been completed (e.g., are there more records to be fetched?). `dbGetRowCount(res, ...)`(optional): : returns the number of rows fetched so far. # Data Type Mappings {#sec:data-mappings} The data types supported by databases are different than the data types in R and S, but the mapping between the “primitive” types is straightforward: Any of the many fixed and varying length character types are mapped to R/S `character`. Fixed-precision (non-IEEE) numbers are mapped into either doubles (`numeric`) or long (`integer`). Notice that many DBMS do not follow the so-called IEEE arithmetic, so there are potential problems with under/overflows and loss of precision, but given the R/S primitive types we cannot do too much but identify these situations and warn the application (how?). By default dates and date-time objects are mapped to character using the appropriate `TO_CHAR` function in the DBMS (which should take care of any locale information). Some RDBMS support the type `CURRENCY` or `MONEY` which should be mapped to `numeric` (again with potential round off errors). Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion (as has been done in other inter-systems packages [^2]). Specifying user-defined conversion functions still needs to be defined. # Utilities {#sec:utilities} The core DBI implementation should make available to all drivers some common basic utilities. For instance: `dbGetDBIVersion`: : returns the version of the currently attached DBI as a string. `dbDataType(dbObj, obj, ...)`: : returns a string with the (approximately) appropriate data type for the R/S object `obj`. The DBI can implement this following the ANSI-92 standard, but individual drivers may want/need to extend it to make use of DBMS-specific types. `make.db.names(dbObj, snames, ...)`: : maps R/S names (identifiers) to SQL identifiers replacing illegal characters (as `.`) by the legal SQL `_`. `SQLKeywords(dbObj, ...)`: : returns a character vector of SQL keywords (reserved words). The default method returns the list of `.SQL92Keywords`, but drivers should update this vector with the DBMS-specific additional reserved words. `isSQLKeyword(dbObj, name, ...)`: : for each element in the character vector `name` determine whether or not it is an SQL keyword, as reported by the generic function `SQLKeywords`. Returns a logical vector parallel to the input object `name`. # Open Issues and Limitations {#sec:open-issues} There are a number of issues and limitations that the current DBI conscientiously does not address on the interest of simplicity. We do list here the most important ones. Non-SQL: : Is it realistic to attempt to encompass non-relational databases, like HDF5, Berkeley DB, etc.? Security: : allowing users to specify their passwords on R/S scripts may be unacceptable for some applications. We need to consider alternatives where users could store authentication on files (perhaps similar to ODBC’s `odbc.ini`) with more stringent permissions. Exceptions: : the exception mechanism is a bit too simple, and it does not provide for information when problems stem from the DBMS interface itself. For instance, under/overflow or loss of precision as we move numeric data from DBMS to the more limited primitives in R/S. Asynchronous communication: : most DBMS support both synchronous and asynchronous communications, allowing applications to submit a query and proceed while the database server process the query. The application is then notified (or it may need to poll the server) when the query has completed. For large computations, this could be very useful, but the DBI would need to specify how to interrupt the server (if necessary) plus other details. Also, some DBMS require applications to use threads to implement asynchronous communication, something that neither R nor S-Plus currently addresses. SQL scripts: : the DBI only defines how to execute one SQL statement at a time, forcing users to split SQL scripts into individual statements. We need a mechanism by which users can submit SQL scripts that could possibly generate multiple result sets; in this case we may need to introduce new methods to loop over multiple results (similar to Python’s `nextResultSet`). BLOBS/CLOBS: : large objects (both character and binary) present some challenges both to R and S-Plus. It is becoming more common to store images, sounds, and other data types as binary objects in DBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects. Transactions: : transaction management is not fully described. Additional methods: : Do we need any additional methods? (e.g., `dbListDatabases(conn)`, `dbListTableIndices(conn, name)`, how do we list all available drivers?) Bind variables: : the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of R/S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement /* SQL */ SELECT * from emp_table where emp_id = :sampleEmployee would take the vector `sampleEmployee` and iterate over each of its elements to get the result. Perhaps the DBI could at some point in the future implement this feature. # Resources {#sec:resources} The idea of a common interface to databases has been successfully implemented in various environments, for instance: Java’s Database Connectivity (JDBC) ([www.javasoft.com](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/)). In C through the Open Database Connectivity (ODBC) ([www.unixodbc.org](http://www.unixodbc.org/)). Python’s Database Application Programming Interface ([www.python.org](https://wiki.python.org/moin/DatabaseProgramming)). Perl’s Database Interface ([dbi.perl.org](https://dbi.perl.org)). [^1]: A virtual class allows us to group classes that share some common characteristics, even if their implementations are radically different. [^2]: Duncan Temple Lang has volunteered to port the data conversion code found in R-Java, R-Perl, and R-Python packages to the DBI DBI/inst/doc/spec.html0000644000176200001440000055376114157714560014245 0ustar liggesusersDBI specification

DBI specification

Kirill Müller

Abstract

The DBI package defines the generic DataBase Interface for R. The connection to individual DBMS is provided by other packages that import DBI (so-called DBI backends). This document formalizes the behavior expected by the methods declared in DBI and implemented by the individual backends. To ensure maximum portability and exchangeability, and to reduce the effort for implementing a new DBI backend, the DBItest package defines a comprehensive set of test cases that test conformance to the DBI specification. This document is derived from comments in the test definitions of the DBItest package. Any extensions or updates to the tests will be reflected in this document.

DBI: R Database Interface

DBI defines an interface for communication between R and relational database management systems. All classes in this package are virtual and need to be extended by the various R/DBMS implementations (so-called DBI backends).

Definition

A DBI backend is an R package which imports the DBI and methods packages. For better or worse, the names of many existing backends start with ‘R’, e.g., RSQLite, RMySQL, RSQLServer; it is up to the backend author to adopt this convention or not.

DBI classes and methods

A backend defines three classes, which are subclasses of DBIDriver, DBIConnection, and DBIResult. The backend provides implementation for all methods of these base classes that are defined but not implemented by DBI. All methods defined in DBI are reexported (so that the package can be used without having to attach DBI), and have an ellipsis ... in their formals for extensibility.

Construction of the DBIDriver object

The backend must support creation of an instance of its DBIDriver subclass with a constructor function. By default, its name is the package name without the leading ‘R’ (if it exists), e.g., SQLite for the RSQLite package. However, backend authors may choose a different name. The constructor must be exported, and it must be a function that is callable without arguments. DBI recommends to define a constructor with an empty argument list.

Examples

RSQLite::SQLite()

Determine the SQL data type of an object

This section describes the behavior of the following method:

dbDataType(dbObj, obj, ...)

Description

Returns an SQL string that describes the SQL data type to be used for an object. The default implementation of this generic determines the SQL type of an R object according to the SQL 92 specification, which may serve as a starting point for driver implementations. DBI also provides an implementation for data.frame which will return a character vector giving the type for each column in the dataframe.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbDataType("MariaDBConnection")

  • RMariaDB::dbDataType("MariaDBDriver")

  • RSQLite::dbDataType("SQLiteConnection")

  • RSQLite::dbDataType("SQLiteDriver")

Arguments

dbObj A object inheriting from DBIDriver or DBIConnection
obj An R object whose SQL type we want to determine.
... Other arguments passed on to methods.

Details

The data types supported by databases are different than the data types in R, but the mapping between the primitive types is straightforward:

  • Any of the many fixed and varying length character types are mapped to character vectors

  • Fixed-precision (non-IEEE) numbers are mapped into either numeric or integer vectors.

Notice that many DBMS do not follow IEEE arithmetic, so there are potential problems with under/overflows and loss of precision.

Value

dbDataType() returns the SQL type that corresponds to the obj argument as a non-empty character string. For data frames, a character vector with one element per column is returned.

Failure modes

An error is raised for invalid values for the obj argument such as a NULL value.

Specification

The backend can override the dbDataType() generic for its driver class.

This generic expects an arbitrary object as second argument. To query the values returned by the default implementation, run example(dbDataType, package = "DBI"). If the backend needs to override this generic, it must accept all basic R data types as its second argument, namely logical, integer, numeric, character, dates (see Dates), date-time (see DateTimeClasses), and difftime. If the database supports blobs, this method also must accept lists of raw vectors, and blob::blob objects. As-is objects (i.e., wrapped by I()) must be supported and return the same results as their unwrapped counterparts. The SQL data type for factor and ordered is the same as for character. The behavior for other object types is not specified.

All data types returned by dbDataType() are usable in an SQL statement of the form "CREATE TABLE test (a ...)".

Examples

dbDataType(ANSI(), 1:5)
dbDataType(ANSI(), 1)
dbDataType(ANSI(), TRUE)
dbDataType(ANSI(), Sys.Date())
dbDataType(ANSI(), Sys.time())
dbDataType(ANSI(), Sys.time() - as.POSIXct(Sys.Date()))
dbDataType(ANSI(), c("x", "abc"))
dbDataType(ANSI(), list(raw(10), raw(20)))
dbDataType(ANSI(), I(3))

dbDataType(ANSI(), iris)

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbDataType(con, 1:5)
dbDataType(con, 1)
dbDataType(con, TRUE)
dbDataType(con, Sys.Date())
dbDataType(con, Sys.time())
dbDataType(con, Sys.time() - as.POSIXct(Sys.Date()))
dbDataType(con, c("x", "abc"))
dbDataType(con, list(raw(10), raw(20)))
dbDataType(con, I(3))

dbDataType(con, iris)

dbDisconnect(con)

Create a connection to a DBMS

This section describes the behavior of the following method:

dbConnect(drv, ...)

Description

Connect to a DBMS going through the appropriate authentication procedure. Some implementations may allow you to have multiple connections open, so you may invoke this function repeatedly assigning its output to different objects. The authentication mechanism is left unspecified, so check the documentation of individual drivers for details. Use dbCanConnect() to check if a connection can be established.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbConnect("MariaDBDriver")

  • RSQLite::dbConnect("SQLiteConnection")

  • RSQLite::dbConnect("SQLiteDriver")

Arguments

drv an object that inherits from DBIDriver, or an existing DBIConnection object (in order to clone an existing connection).
... authentication arguments needed by the DBMS instance; these typically include user, password, host, port, dbname, etc. For details see the appropriate DBIDriver.

Value

dbConnect() returns an S4 object that inherits from DBIConnection. This object is used to communicate with the database engine.

A format() method is defined for the connection object. It returns a string that consists of a single line of text.

Specification

DBI recommends using the following argument names for authentication parameters, with NULL default:

  • user for the user name (default: current user)

  • password for the password

  • host for the host name (default: local connection)

  • port for the port number (default: local connection)

  • dbname for the name of the database on the host, or the database file name

The defaults should provide reasonable behavior, in particular a local connection for host = NULL. For some DBMS (e.g., PostgreSQL), this is different to a TCP/IP connection to localhost.

In addition, DBI supports the bigint argument that governs how 64-bit integer data is returned. The following values are supported:

  • "integer": always return as integer, silently overflow

  • "numeric": always return as numeric, silently round

  • "character": always return the decimal representation as character

  • "integer64": return as a data type that can be coerced using as.integer() (with warning on overflow), as.numeric() and as.character()

Examples

# SQLite only needs a path to the database. (Here, ":memory:" is a special
# path that creates an in-memory database.) Other database drivers
# will require more details (like user, password, host, port, etc.)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
con

dbListTables(con)

dbDisconnect(con)

# Bad, for subtle reasons:
# This code fails when RSQLite isn't loaded yet,
# because dbConnect() doesn't know yet about RSQLite.
dbListTables(con <- dbConnect(RSQLite::SQLite(), ":memory:"))

Disconnect (close) a connection

This section describes the behavior of the following method:

dbDisconnect(conn, ...)

Description

This closes the connection, discards all pending work, and frees resources (e.g., memory, sockets).

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbDisconnect("MariaDBConnection")

  • RSQLite::dbDisconnect("SQLiteConnection")

Arguments

conn A DBIConnection object, as returned by dbConnect().
... Other parameters passed on to methods.

Value

dbDisconnect() returns TRUE, invisibly.

Failure modes

A warning is issued on garbage collection when a connection has been released without calling dbDisconnect(), but this cannot be tested automatically. A warning is issued immediately when calling dbDisconnect() on an already disconnected or invalid connection.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbDisconnect(con)

Execute a query on a given database connection

This section describes the behavior of the following method:

dbSendQuery(conn, statement, ...)

Description

The dbSendQuery() method only submits and synchronously executes the SQL query to the database engine. It does not extract any records — for that you need to use the dbFetch() method, and then you must call dbClearResult() when you finish fetching the records you need. For interactive use, you should almost always prefer dbGetQuery().

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbSendQuery("MariaDBConnection", "character")

  • RSQLite::dbSendQuery("SQLiteConnection", "character")

Arguments

conn A DBIConnection object, as returned by dbConnect().
statement a character string containing SQL.
... Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbSendQuery() generic (to improve compatibility across backends) but are part of the DBI specification:

  • params (default: NULL)

  • immediate (default: NULL)

They must be provided as named arguments. See the “Specification” sections for details on their usage.

Specification

No warnings occur under normal conditions. When done, the DBIResult object must be cleared with a call to dbClearResult(). Failure to clear the result set leads to a warning when the connection is closed.

If the backend supports only one open result set per connection, issuing a second query invalidates an already open result set and raises a warning. The newly opened result set is valid and must be cleared with dbClearResult().

The param argument allows passing query parameters, see dbBind() for details.

Specification for the immediate argument

The immediate argument supports distinguishing between “direct” and “prepared” APIs offered by many database drivers. Passing immediate = TRUE leads to immediate execution of the query or statement, via the “direct” API (if supported by the driver). The default NULL means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct immediate argument. Examples for possible behaviors:

  1. DBI backend defaults to immediate = TRUE internally

    1. A query without parameters is passed: query is executed

    2. A query with parameters is passed:

      1. params not given: rejected immediately by the database because of a syntax error in the query, the backend tries immediate = FALSE (and gives a message)

      2. params given: query is executed using immediate = FALSE

  2. DBI backend defaults to immediate = FALSE internally

    1. A query without parameters is passed:

      1. simple query: query is executed

      2. “special” query (such as setting a config options): fails, the backend tries immediate = TRUE (and gives a message)

    2. A query with parameters is passed:

      1. params not given: waiting for parameters via dbBind()

      2. params given: query is executed

Details

This method is for SELECT queries only. Some backends may support data manipulation queries through this method for compatibility reasons. However, callers are strongly encouraged to use dbSendStatement() for data manipulation statements.

The query is submitted to the database server and the DBMS executes it, possibly generating vast amounts of data. Where these data live is driver-specific: some drivers may choose to leave the output on the server and transfer them piecemeal to R, others may transfer all the data to the client – but not necessarily to the memory that R manages. See individual drivers’ dbSendQuery() documentation for details.

Value

dbSendQuery() returns an S4 object that inherits from DBIResult. The result set can be used with dbFetch() to extract records. Once you have finished using a result, make sure to clear it with dbClearResult().

Failure modes

An error is raised when issuing a query over a closed or invalid connection, or if the query is not a non-NA string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the params argument) or the immediate argument is set to TRUE.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(rs)
dbClearResult(rs)

# Pass one set of values with the param argument:
rs <- dbSendQuery(
  con,
  "SELECT * FROM mtcars WHERE cyl = ?",
  params = list(4L)
)
dbFetch(rs)
dbClearResult(rs)

# Pass multiple sets of values with dbBind():
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = ?")
dbBind(rs, list(6L))
dbFetch(rs)
dbBind(rs, list(8L))
dbFetch(rs)
dbClearResult(rs)

dbDisconnect(con)

Fetch records from a previously executed query

This section describes the behavior of the following methods:

dbFetch(res, n = -1, ...)

fetch(res, n = -1, ...)

Description

Fetch the next n elements (rows) from the result set and return them as a data.frame.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbFetch("MariaDBResult")

  • RSQLite::dbFetch("SQLiteResult")

Arguments

res An object inheriting from DBIResult, created by dbSendQuery().
n maximum number of records to retrieve per fetch. Use n = -1 or n = Inf to retrieve all pending records. Some implementations may recognize other special values.
... Other arguments passed on to methods.

Details

fetch() is provided for compatibility with older DBI clients - for all new code you are strongly encouraged to use dbFetch(). The default implementation for dbFetch() calls fetch() so that it is compatible with existing code. Modern backends should implement for dbFetch() only.

Value

dbFetch() always returns a data.frame with as many rows as records were fetched and as many columns as fields in the result set, even if the result is a single value or has one or zero rows.

Failure modes

An attempt to fetch from a closed result set raises an error. If the n argument is not an atomic whole number greater or equal to -1 or Inf, an error is raised, but a subsequent call to dbFetch() with proper n argument succeeds. Calling dbFetch() on a result set from a data manipulation query created by dbSendStatement() can be fetched and return an empty data frame, with a warning.

Specification

Fetching multi-row queries with one or more columns by default returns the entire result. Multi-row queries can also be fetched progressively by passing a whole number (integer or numeric) as the n argument. A value of Inf for the n argument is supported and also returns the full result. If more rows than available are fetched, the result is returned in full without warning. If fewer rows than requested are returned, further fetches will return a data frame with zero rows. If zero rows are fetched, the columns of the data frame are still fully typed. Fetching fewer rows than available is permitted, no warning is issued when clearing the result set.

A column named row_names is treated like any other column.

The column types of the returned data frame depend on the data returned:

  • integer (or coercible to an integer) for integer values between -2^31 and 2^31 - 1, with NA for SQL NULL values

  • numeric for numbers with a fractional component, with NA for SQL NULL values

  • logical for Boolean values (some backends may return an integer); with NA for SQL NULL values

  • character for text, with NA for SQL NULL values

  • lists of raw for blobs with NULL entries for SQL NULL values

  • coercible using as.Date() for dates, with NA for SQL NULL values (also applies to the return value of the SQL function current_date)

  • coercible using hms::as_hms() for times, with NA for SQL NULL values (also applies to the return value of the SQL function current_time)

  • coercible using as.POSIXct() for timestamps, with NA for SQL NULL values (also applies to the return value of the SQL function current_timestamp)

If dates and timestamps are supported by the backend, the following R types are used:

  • Date for dates (also applies to the return value of the SQL function current_date)

  • POSIXct for timestamps (also applies to the return value of the SQL function current_timestamp)

R has no built-in type with lossless support for the full range of 64-bit or larger integers. If 64-bit integers are returned from a query, the following rules apply:

  • Values are returned in a container with support for the full range of valid 64-bit values (such as the integer64 class of the bit64 package)

  • Coercion to numeric always returns a number that is as close as possible to the true value

  • Loss of precision when converting to numeric gives a warning

  • Conversion to character always returns a lossless decimal representation of the data

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)

# Fetch all results
rs <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(rs)
dbClearResult(rs)

# Fetch in chunks
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
while (!dbHasCompleted(rs)) {
  chunk <- dbFetch(rs, 10)
  print(nrow(chunk))
}

dbClearResult(rs)
dbDisconnect(con)

Clear a result set

This section describes the behavior of the following method:

dbClearResult(res, ...)

Description

Frees all resources (local and remote) associated with a result set. In some cases (e.g., very large result sets) this can be a critical step to avoid exhausting resources (memory, file descriptors, etc.)

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbClearResult("MariaDBResult")

  • RSQLite::dbClearResult("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbClearResult() returns TRUE, invisibly, for result sets obtained from both dbSendQuery() and dbSendStatement().

Failure modes

An attempt to close an already closed result set issues a warning in both cases.

Specification

dbClearResult() frees all resources associated with retrieving the result of a query or update operation. The DBI backend can expect a call to dbClearResult() for each dbSendQuery() or dbSendStatement() call.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

rs <- dbSendQuery(con, "SELECT 1")
print(dbFetch(rs))

dbClearResult(rs)
dbDisconnect(con)

Bind values to a parameterized/prepared statement

This section describes the behavior of the following method:

dbBind(res, params, ...)

Description

For parametrized or prepared statements, the dbSendQuery() and dbSendStatement() functions can be called with statements that contain placeholders for values. The dbBind() function binds these placeholders to actual values, and is intended to be called on the result set before calling dbFetch() or dbGetRowsAffected().

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbBind("MariaDBResult")

  • RSQLite::dbBind("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
params A list of bindings, named or unnamed.
... Other arguments passed on to methods.

Details

DBI supports parametrized (or prepared) queries and statements via the dbBind() generic. Parametrized queries are different from normal queries in that they allow an arbitrary number of placeholders, which are later substituted by actual values. Parametrized queries (and statements) serve two purposes:

  • The same query can be executed more than once with different values. The DBMS may cache intermediate information for the query, such as the execution plan, and execute it faster.

  • Separation of query syntax and parameters protects against SQL injection.

The placeholder format is currently not specified by DBI; in the future, a uniform placeholder syntax may be supported. Consult the backend documentation for the supported formats. For automated testing, backend authors specify the placeholder syntax with the placeholder_pattern tweak. Known examples are:

  • ? (positional matching in order of appearance) in RMySQL and RSQLite

  • \$1 (positional matching by index) in RPostgres and RSQLite

  • :name and \$name (named matching) in RSQLite

Value

dbBind() returns the result set, invisibly, for queries issued by dbSendQuery() and also for data manipulation statements issued by dbSendStatement().

Failure modes

Calling dbBind() for a query without parameters raises an error. Binding too many or not enough values, or parameters with wrong names or unequal length, also raises an error. If the placeholders in the query are named, all parameter values must have names (which must not be empty or NA), and vice versa, otherwise an error is raised. The behavior for mixing placeholders of different types (in particular mixing positional and named placeholders) is not specified.

Calling dbBind() on a result set already cleared by dbClearResult() also raises an error.

Specification

DBI clients execute parametrized statements as follows:

  1. Call dbSendQuery() or dbSendStatement() with a query or statement that contains placeholders, store the returned DBIResult object in a variable. Mixing placeholders (in particular, named and unnamed ones) is not recommended. It is good practice to register a call to dbClearResult() via on.exit() right after calling dbSendQuery() or dbSendStatement() (see the last enumeration item). Until dbBind() has been called, the returned result set object has the following behavior:

    • dbFetch() raises an error (for dbSendQuery())

    • dbGetRowCount() returns zero (for dbSendQuery())

    • dbGetRowsAffected() returns an integer NA (for dbSendStatement())

    • dbIsValid() returns TRUE

    • dbHasCompleted() returns FALSE

  2. Construct a list with parameters that specify actual values for the placeholders. The list must be named or unnamed, depending on the kind of placeholders used. Named values are matched to named parameters, unnamed values are matched by position in the list of parameters. All elements in this list must have the same lengths and contain values supported by the backend; a data.frame is internally stored as such a list. The parameter list is passed to a call to dbBind() on the DBIResult object.

  3. Retrieve the data or the number of affected rows from the DBIResult object.

    • For queries issued by dbSendQuery(), call dbFetch().

    • For statements issued by dbSendStatements(), call dbGetRowsAffected(). (Execution begins immediately after the dbBind() call, the statement is processed entirely before the function returns.)

  4. Repeat 2. and 3. as necessary.

  5. Close the result set via dbClearResult().

The elements of the params argument do not need to be scalars, vectors of arbitrary length (including length 0) are supported. For queries, calling dbFetch() binding such parameters returns concatenated results, equivalent to binding and fetching for each set of values and connecting via rbind(). For data manipulation statements, dbGetRowsAffected() returns the total number of rows affected if binding non-scalar parameters. dbBind() also accepts repeated calls on the same result set for both queries and data manipulation statements, even if no results are fetched between calls to dbBind(), for both queries and data manipulation statements.

If the placeholders in the query are named, their order in the params argument is not important.

At least the following data types are accepted on input (including NA):

  • integer

  • numeric

  • logical for Boolean values

  • character (also with special characters such as spaces, newlines, quotes, and backslashes)

  • factor (bound as character, with warning)

  • Date (also when stored internally as integer)

  • POSIXct timestamps

  • POSIXlt timestamps

  • difftime values (also with units other than seconds and with the value stored as integer)

  • lists of raw for blobs (with NULL entries for SQL NULL values)

  • objects of type blob::blob

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "iris", iris)

# Using the same query for different values
iris_result <- dbSendQuery(con, "SELECT * FROM iris WHERE [Petal.Width] > ?")
dbBind(iris_result, list(2.3))
dbFetch(iris_result)
dbBind(iris_result, list(3))
dbFetch(iris_result)
dbClearResult(iris_result)

# Executing the same statement with different values at once
iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = $species")
dbBind(iris_result, list(species = c("setosa", "versicolor", "unknown")))
dbGetRowsAffected(iris_result)
dbClearResult(iris_result)

nrow(dbReadTable(con, "iris"))

dbDisconnect(con)

Send query, retrieve results and then clear result set

This section describes the behavior of the following method:

dbGetQuery(conn, statement, ...)

Description

Returns the result of a query as a data frame. dbGetQuery() comes with a default implementation (which should work with most backends) that calls dbSendQuery(), then dbFetch(), ensuring that the result is always free-d by dbClearResult().

Arguments

conn A DBIConnection object, as returned by dbConnect().
statement a character string containing SQL.
... Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbGetQuery() generic (to improve compatibility across backends) but are part of the DBI specification:

  • n (default: -1)

  • params (default: NULL)

  • immediate (default: NULL)

They must be provided as named arguments. See the “Specification” and “Value” sections for details on their usage.

Specification

A column named row_names is treated like any other column.

The n argument specifies the number of rows to be fetched. If omitted, fetching multi-row queries with one or more columns returns the entire result. A value of Inf for the n argument is supported and also returns the full result. If more rows than available are fetched (by passing a too large value for n), the result is returned in full without warning. If zero rows are requested, the columns of the data frame are still fully typed. Fetching fewer rows than available is permitted, no warning is issued.

The param argument allows passing query parameters, see dbBind() for details.

Specification for the immediate argument

The immediate argument supports distinguishing between “direct” and “prepared” APIs offered by many database drivers. Passing immediate = TRUE leads to immediate execution of the query or statement, via the “direct” API (if supported by the driver). The default NULL means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct immediate argument. Examples for possible behaviors:

  1. DBI backend defaults to immediate = TRUE internally

    1. A query without parameters is passed: query is executed

    2. A query with parameters is passed:

      1. params not given: rejected immediately by the database because of a syntax error in the query, the backend tries immediate = FALSE (and gives a message)

      2. params given: query is executed using immediate = FALSE

  2. DBI backend defaults to immediate = FALSE internally

    1. A query without parameters is passed:

      1. simple query: query is executed

      2. “special” query (such as setting a config options): fails, the backend tries immediate = TRUE (and gives a message)

    2. A query with parameters is passed:

      1. params not given: waiting for parameters via dbBind()

      2. params given: query is executed

Details

This method is for SELECT queries only (incl. other SQL statements that return a SELECT-alike result, e. g. execution of a stored procedure).

To execute a stored procedure that does not return a result set, use dbExecute().

Some backends may support data manipulation statements through this method for compatibility reasons. However, callers are strongly advised to use dbExecute() for data manipulation statements.

Value

dbGetQuery() always returns a data.frame with as many rows as records were fetched and as many columns as fields in the result set, even if the result is a single value or has one or zero rows.

Implementation notes

Subclasses should override this method only if they provide some sort of performance optimization.

Failure modes

An error is raised when issuing a query over a closed or invalid connection, if the syntax of the query is invalid, or if the query is not a non-NA string. If the n argument is not an atomic whole number greater or equal to -1 or Inf, an error is raised, but a subsequent call to dbGetQuery() with proper n argument succeeds.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
dbGetQuery(con, "SELECT * FROM mtcars")
dbGetQuery(con, "SELECT * FROM mtcars", n = 6)

# Pass values using the param argument:
# (This query runs eight times, once for each different
# parameter. The resulting rows are combined into a single
# data frame.)
dbGetQuery(
  con,
  "SELECT COUNT(*) FROM mtcars WHERE cyl = ?",
  params = list(1:8)
)

dbDisconnect(con)

Execute a data manipulation statement on a given database connection

This section describes the behavior of the following method:

dbSendStatement(conn, statement, ...)

Description

The dbSendStatement() method only submits and synchronously executes the SQL data manipulation statement (e.g., UPDATE, DELETE, INSERT INTO, DROP TABLE, …) to the database engine. To query the number of affected rows, call dbGetRowsAffected() on the returned result object. You must also call dbClearResult() after that. For interactive use, you should almost always prefer dbExecute().

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbSendStatement("MariaDBConnection", "character")

Arguments

conn A DBIConnection object, as returned by dbConnect().
statement a character string containing SQL.
... Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbSendStatement() generic (to improve compatibility across backends) but are part of the DBI specification:

  • params (default: NULL)

  • immediate (default: NULL)

They must be provided as named arguments. See the “Specification” sections for details on their usage.

Specification

No warnings occur under normal conditions. When done, the DBIResult object must be cleared with a call to dbClearResult(). Failure to clear the result set leads to a warning when the connection is closed. If the backend supports only one open result set per connection, issuing a second query invalidates an already open result set and raises a warning. The newly opened result set is valid and must be cleared with dbClearResult().

The param argument allows passing query parameters, see dbBind() for details.

Specification for the immediate argument

The immediate argument supports distinguishing between “direct” and “prepared” APIs offered by many database drivers. Passing immediate = TRUE leads to immediate execution of the query or statement, via the “direct” API (if supported by the driver). The default NULL means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct immediate argument. Examples for possible behaviors:

  1. DBI backend defaults to immediate = TRUE internally

    1. A query without parameters is passed: query is executed

    2. A query with parameters is passed:

      1. params not given: rejected immediately by the database because of a syntax error in the query, the backend tries immediate = FALSE (and gives a message)

      2. params given: query is executed using immediate = FALSE

  2. DBI backend defaults to immediate = FALSE internally

    1. A query without parameters is passed:

      1. simple query: query is executed

      2. “special” query (such as setting a config options): fails, the backend tries immediate = TRUE (and gives a message)

    2. A query with parameters is passed:

      1. params not given: waiting for parameters via dbBind()

      2. params given: query is executed

Details

dbSendStatement() comes with a default implementation that simply forwards to dbSendQuery(), to support backends that only implement the latter.

Value

dbSendStatement() returns an S4 object that inherits from DBIResult. The result set can be used with dbGetRowsAffected() to determine the number of rows affected by the query. Once you have finished using a result, make sure to clear it with dbClearResult().

Failure modes

An error is raised when issuing a statement over a closed or invalid connection, or if the statement is not a non-NA string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the params argument) or the immediate argument is set to TRUE.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cars", head(cars, 3))

rs <- dbSendStatement(
  con,
  "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
dbHasCompleted(rs)
dbGetRowsAffected(rs)
dbClearResult(rs)
dbReadTable(con, "cars")   # there are now 6 rows

# Pass one set of values directly using the param argument:
rs <- dbSendStatement(
  con,
  "INSERT INTO cars (speed, dist) VALUES (?, ?)",
  params = list(4L, 5L)
)
dbClearResult(rs)

# Pass multiple sets of values using dbBind():
rs <- dbSendStatement(
  con,
  "INSERT INTO cars (speed, dist) VALUES (?, ?)"
)
dbBind(rs, list(5:6, 6:7))
dbBind(rs, list(7L, 8L))
dbClearResult(rs)
dbReadTable(con, "cars")   # there are now 10 rows

dbDisconnect(con)

Execute an update statement, query number of rows affected, and then close result set

This section describes the behavior of the following method:

dbExecute(conn, statement, ...)

Description

Executes a statement and returns the number of rows affected. dbExecute() comes with a default implementation (which should work with most backends) that calls dbSendStatement(), then dbGetRowsAffected(), ensuring that the result is always free-d by dbClearResult().

Arguments

conn A DBIConnection object, as returned by dbConnect().
statement a character string containing SQL.
... Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbExecute() generic (to improve compatibility across backends) but are part of the DBI specification:

  • params (default: NULL)

  • immediate (default: NULL)

They must be provided as named arguments. See the “Specification” sections for details on their usage.

Specification

The param argument allows passing query parameters, see dbBind() for details.

Specification for the immediate argument

The immediate argument supports distinguishing between “direct” and “prepared” APIs offered by many database drivers. Passing immediate = TRUE leads to immediate execution of the query or statement, via the “direct” API (if supported by the driver). The default NULL means that the backend should choose whatever API makes the most sense for the database, and (if relevant) tries the other API if the first attempt fails. A successful second attempt should result in a message that suggests passing the correct immediate argument. Examples for possible behaviors:

  1. DBI backend defaults to immediate = TRUE internally

    1. A query without parameters is passed: query is executed

    2. A query with parameters is passed:

      1. params not given: rejected immediately by the database because of a syntax error in the query, the backend tries immediate = FALSE (and gives a message)

      2. params given: query is executed using immediate = FALSE

  2. DBI backend defaults to immediate = FALSE internally

    1. A query without parameters is passed:

      1. simple query: query is executed

      2. “special” query (such as setting a config options): fails, the backend tries immediate = TRUE (and gives a message)

    2. A query with parameters is passed:

      1. params not given: waiting for parameters via dbBind()

      2. params given: query is executed

Details

You can also use dbExecute() to call a stored procedure that performs data manipulation or other actions that do not return a result set. To execute a stored procedure that returns a result set use dbGetQuery() instead.

Value

dbExecute() always returns a scalar numeric that specifies the number of rows affected by the statement.

Implementation notes

Subclasses should override this method only if they provide some sort of performance optimization.

Failure modes

An error is raised when issuing a statement over a closed or invalid connection, if the syntax of the statement is invalid, or if the statement is not a non-NA string.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cars", head(cars, 3))
dbReadTable(con, "cars")   # there are 3 rows
dbExecute(
  con,
  "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
dbReadTable(con, "cars")   # there are now 6 rows

# Pass values using the param argument:
dbExecute(
  con,
  "INSERT INTO cars (speed, dist) VALUES (?, ?)",
  params = list(4:7, 5:8)
)
dbReadTable(con, "cars")   # there are now 10 rows

dbDisconnect(con)

Quote literal strings

This section describes the behavior of the following method:

dbQuoteString(conn, x, ...)

Description

Call this method to generate a string that is suitable for use in a query as a string literal, to make sure that you generate valid SQL and protect against SQL injection attacks.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbQuoteString("MariaDBConnection", "SQL")

  • RMariaDB::dbQuoteString("MariaDBConnection", "character")

Arguments

conn A DBIConnection object, as returned by dbConnect().
x A character vector to quote as string.
... Other arguments passed on to methods.

Value

dbQuoteString() returns an object that can be coerced to character, of the same length as the input. For an empty character vector this function returns a length-0 object.

When passing the returned object again to dbQuoteString() as x argument, it is returned unchanged. Passing objects of class SQL should also return them unchanged. (For backends it may be most convenient to return SQL objects to achieve this behavior, but this is not required.)

Failure modes

Passing a numeric, integer, logical, or raw vector, or a list for the x argument raises an error.

Specification

The returned expression can be used in a SELECT ... query, and for any scalar character x the value of dbGetQuery(paste0("SELECT ", dbQuoteString(x)))[[1]] must be identical to x, even if x contains spaces, tabs, quotes (single or double), backticks, or newlines (in any combination) or is itself the result of a dbQuoteString() call coerced back to character (even repeatedly). If x is NA, the result must merely satisfy is.na(). The strings "NA" or "NULL" are not treated specially.

NA should be translated to an unquoted SQL NULL, so that the query SELECT * FROM (SELECT 1) a WHERE ... IS NULL returns one row.

Examples

# Quoting ensures that arbitrary input is safe for use in a query
name <- "Robert'); DROP TABLE Students;--"
dbQuoteString(ANSI(), name)

# NAs become NULL
dbQuoteString(ANSI(), c("x", NA))

# SQL vectors are always passed through as is
var_name <- SQL("select")
var_name
dbQuoteString(ANSI(), var_name)

# This mechanism is used to prevent double escaping
dbQuoteString(ANSI(), dbQuoteString(ANSI(), name))

Quote identifiers

This section describes the behavior of the following method:

dbQuoteIdentifier(conn, x, ...)

Description

Call this method to generate a string that is suitable for use in a query as a column or table name, to make sure that you generate valid SQL and protect against SQL injection attacks. The inverse operation is dbUnquoteIdentifier().

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbQuoteIdentifier("MariaDBConnection", "Id")

  • RMariaDB::dbQuoteIdentifier("MariaDBConnection", "SQL")

  • RMariaDB::dbQuoteIdentifier("MariaDBConnection", "character")

  • RSQLite::dbQuoteIdentifier("SQLiteConnection", "SQL")

  • RSQLite::dbQuoteIdentifier("SQLiteConnection", "character")

Arguments

conn A DBIConnection object, as returned by dbConnect().
x A character vector, SQL or Id object to quote as identifier.
... Other arguments passed on to methods.

Value

dbQuoteIdentifier() returns an object that can be coerced to character, of the same length as the input. For an empty character vector this function returns a length-0 object. The names of the input argument are preserved in the output. When passing the returned object again to dbQuoteIdentifier() as x argument, it is returned unchanged. Passing objects of class SQL should also return them unchanged. (For backends it may be most convenient to return SQL objects to achieve this behavior, but this is not required.)

Failure modes

An error is raised if the input contains NA, but not for an empty string.

Specification

Calling dbGetQuery() for a query of the format SELECT 1 AS ... returns a data frame with the identifier, unquoted, as column name. Quoted identifiers can be used as table and column names in SQL queries, in particular in queries like SELECT 1 AS ... and SELECT * FROM (SELECT 1) .... The method must use a quoting mechanism that is unambiguously different from the quoting mechanism used for strings, so that a query like SELECT ... FROM (SELECT 1 AS ...) throws an error if the column names do not match.

The method can quote column names that contain special characters such as a space, a dot, a comma, or quotes used to mark strings or identifiers, if the database supports this. In any case, checking the validity of the identifier should be performed only when executing a query, and not by dbQuoteIdentifier().

Examples

# Quoting ensures that arbitrary input is safe for use in a query
name <- "Robert'); DROP TABLE Students;--"
dbQuoteIdentifier(ANSI(), name)

# Use Id() to specify other components such as the schema
id_name <- Id(schema = "schema_name", table = "table_name")
id_name
dbQuoteIdentifier(ANSI(), id_name)

# SQL vectors are always passed through as is
var_name <- SQL("select")
var_name
dbQuoteIdentifier(ANSI(), var_name)

# This mechanism is used to prevent double escaping
dbQuoteIdentifier(ANSI(), dbQuoteIdentifier(ANSI(), name))

Copy data frames from database tables

This section describes the behavior of the following method:

dbReadTable(conn, name, ...)

Description

Reads a database table to a data frame, optionally converting a column to row names and converting the column names to valid R identifiers.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbReadTable("MariaDBConnection", "character")

  • RSQLite::dbReadTable("SQLiteConnection", "character")

Arguments

conn

A DBIConnection object, as returned by dbConnect().

name

The table name, passed on to dbQuoteIdentifier(). Options are:

  • a character string with the unquoted DBMS table name, e.g. “table_name”,

  • a call to Id() with components to the fully qualified table name, e.g. Id(schema = “my_schema”, table = “table_name”)

  • a call to SQL() with the quoted and fully qualified table name given verbatim, e.g. SQL(‘“my_schema”.“table_name”’)

Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbReadTable() generic (to improve compatibility across backends) but are part of the DBI specification:

  • row.names (default: FALSE)

  • check.names

They must be provided as named arguments. See the “Value” section for details on their usage.

Specification

The name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

  • If an unquoted table name as string: dbReadTable() will do the quoting, perhaps by calling dbQuoteIdentifier(conn, x = name)

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done

Value

dbReadTable() returns a data frame that contains the complete data from the remote table, effectively the result of calling dbGetQuery() with SELECT * FROM <name>.

An empty table is returned as a data frame with zero rows.

The presence of rownames depends on the row.names argument, see sqlColumnToRownames() for details:

  • If FALSE or NULL, the returned data frame doesn’t have row names.

  • If TRUE, a column named “row_names” is converted to row names.

  • If NA, a column named “row_names” is converted to row names if it exists, otherwise no translation occurs.

  • If a string, this specifies the name of the column in the remote table that contains the row names.

The default is row.names = FALSE.

If the database supports identifiers with special characters, the columns in the returned data frame are converted to valid R identifiers if the check.names argument is TRUE, If check.names = FALSE, the returned table has non-syntactic column names without quotes.

Failure modes

An error is raised if the table does not exist.

An error is raised if row.names is TRUE and no “row_names” column exists,

An error is raised if row.names is set to a string and and no corresponding column exists.

An error is raised when calling this method for a closed or invalid connection. An error is raised if name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar. Unsupported values for row.names and check.names (non-scalars, unsupported data types, NA for check.names) also raise an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars[1:10, ])
dbReadTable(con, "mtcars")

dbDisconnect(con)

Copy data frames to database tables

This section describes the behavior of the following method:

dbWriteTable(conn, name, value, ...)

Description

Writes, overwrites or appends a data frame to a database table, optionally converting row names to a column and specifying SQL data types for fields.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbWriteTable("MariaDBConnection", "character", "character")

  • RMariaDB::dbWriteTable("MariaDBConnection", "character", "data.frame")

  • RSQLite::dbWriteTable("SQLiteConnection", "character", "character")

  • RSQLite::dbWriteTable("SQLiteConnection", "character", "data.frame")

Arguments

conn

A DBIConnection object, as returned by dbConnect().

name

The table name, passed on to dbQuoteIdentifier(). Options are:

  • a character string with the unquoted DBMS table name, e.g. “table_name”,

  • a call to Id() with components to the fully qualified table name, e.g. Id(schema = “my_schema”, table = “table_name”)

  • a call to SQL() with the quoted and fully qualified table name given verbatim, e.g. SQL(‘“my_schema”.“table_name”’)

value

a data.frame (or coercible to data.frame).

Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbWriteTable() generic (to improve compatibility across backends) but are part of the DBI specification:

  • row.names (default: FALSE)

  • overwrite (default: FALSE)

  • append (default: FALSE)

  • field.types (default: NULL)

  • temporary (default: FALSE)

They must be provided as named arguments. See the “Specification” and “Value” sections for details on their usage.

Specification

The name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

  • If an unquoted table name as string: dbWriteTable() will do the quoting, perhaps by calling dbQuoteIdentifier(conn, x = name)

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done

The value argument must be a data frame with a subset of the columns of the existing table if append = TRUE. The order of the columns does not matter with append = TRUE.

If the overwrite argument is TRUE, an existing table of the same name will be overwritten. This argument doesn’t change behavior if the table does not exist yet.

If the append argument is TRUE, the rows in an existing table are preserved, and the new data are appended. If the table doesn’t exist yet, it is created.

If the temporary argument is TRUE, the table is not available in a second connection and is gone after reconnecting. Not all backends support this argument. A regular, non-temporary table is visible in a second connection, in a pre-existing connection, and after reconnecting to the database.

SQL keywords can be used freely in table names, column names, and data. Quotes, commas, spaces, and other special characters such as newlines and tabs, can also be used in the data, and, if the database supports non-syntactic identifiers, also for table names and column names.

The following data types must be supported at least, and be read identically with dbReadTable():

  • integer

  • numeric (the behavior for Inf and NaN is not specified)

  • logical

  • NA as NULL

  • 64-bit values (using "bigint" as field type); the result can be

    • converted to a numeric, which may lose precision,

    • converted a character vector, which gives the full decimal representation

    • written to another table and read again unchanged

  • character (in both UTF-8 and native encodings), supporting empty strings before and after a non-empty string

  • factor (returned as character)

  • list of raw (if supported by the database)

  • objects of type blob::blob (if supported by the database)

  • date (if supported by the database; returned as Date), also for dates prior to 1970 or 1900 or after 2038

  • time (if supported by the database; returned as objects that inherit from difftime)

  • timestamp (if supported by the database; returned as POSIXct respecting the time zone but not necessarily preserving the input time zone), also for timestamps prior to 1970 or 1900 or after 2038 respecting the time zone but not necessarily preserving the input time zone)

Mixing column types in the same table is supported.

The field.types argument must be a named character vector with at most one entry for each column. It indicates the SQL data type to be used for a new column. If a column is missed from field.types, the type is inferred from the input data with dbDataType().

The interpretation of rownames depends on the row.names argument, see sqlRownamesToColumn() for details:

  • If FALSE or NULL, row names are ignored.

  • If TRUE, row names are converted to a column named “row_names”, even if the input data frame only has natural row names from 1 to nrow(...).

  • If NA, a column named “row_names” is created if the data has custom row names, no extra column is created in the case of natural row names.

  • If a string, this specifies the name of the column in the remote table that contains the row names, even if the input data frame only has natural row names.

The default is row.names = FALSE.

Details

This function is useful if you want to create and load a table at the same time. Use dbAppendTable() for appending data to a table, and dbCreateTable(), dbExistsTable() and dbRemoveTable() for more control over the individual operations.

DBI only standardizes writing data frames. Some backends might implement methods that can consume CSV files or other data formats. For details, see the documentation for the individual methods.

Value

dbWriteTable() returns TRUE, invisibly.

Failure modes

If the table exists, and both append and overwrite arguments are unset, or append = TRUE and the data frame with the new data has different column names, an error is raised; the remote table remains unchanged.

An error is raised when calling this method for a closed or invalid connection. An error is also raised if name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar. Invalid values for the additional arguments row.names, overwrite, append, field.types, and temporary (non-scalars, unsupported data types, NA, incompatible values, duplicate or missing names, incompatible columns) also raise an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars[1:5, ])
dbReadTable(con, "mtcars")

dbWriteTable(con, "mtcars", mtcars[6:10, ], append = TRUE)
dbReadTable(con, "mtcars")

dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE)
dbReadTable(con, "mtcars")

# No row names
dbWriteTable(con, "mtcars", mtcars[1:10, ], overwrite = TRUE, row.names = FALSE)
dbReadTable(con, "mtcars")

List remote tables

This section describes the behavior of the following method:

dbListTables(conn, ...)

Description

Returns the unquoted names of remote tables accessible through this connection. This should include views and temporary objects, but not all database backends (in particular RMariaDB and RMySQL) support this.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbListTables("MariaDBConnection")

  • RSQLite::dbListTables("SQLiteConnection")

Arguments

conn A DBIConnection object, as returned by dbConnect().
... Other parameters passed on to methods.

Value

dbListTables() returns a character vector that enumerates all tables and views in the database. Tables added with dbWriteTable() are part of the list. As soon a table is removed from the database, it is also removed from the list of database tables.

The same applies to temporary tables if supported by the database.

The returned names are suitable for quoting with dbQuoteIdentifier().

Failure modes

An error is raised when calling this method for a closed or invalid connection.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbListTables(con)
dbWriteTable(con, "mtcars", mtcars)
dbListTables(con)

dbDisconnect(con)

Does a table exist?

This section describes the behavior of the following method:

dbExistsTable(conn, name, ...)

Description

Returns if a table given by name exists in the database.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbExistsTable("MariaDBConnection", "character")

  • RSQLite::dbExistsTable("SQLiteConnection", "character")

Arguments

conn

A DBIConnection object, as returned by dbConnect().

name

The table name, passed on to dbQuoteIdentifier(). Options are:

  • a character string with the unquoted DBMS table name, e.g. “table_name”,

  • a call to Id() with components to the fully qualified table name, e.g. Id(schema = “my_schema”, table = “table_name”)

  • a call to SQL() with the quoted and fully qualified table name given verbatim, e.g. SQL(‘“my_schema”.“table_name”’)

Other parameters passed on to methods.

Value

dbExistsTable() returns a logical scalar, TRUE if the table or view specified by the name argument exists, FALSE otherwise.

This includes temporary tables if supported by the database.

Failure modes

An error is raised when calling this method for a closed or invalid connection. An error is also raised if name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar.

Specification

The name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

  • If an unquoted table name as string: dbExistsTable() will do the quoting, perhaps by calling dbQuoteIdentifier(conn, x = name)

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done

For all tables listed by dbListTables(), dbExistsTable() returns TRUE.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbExistsTable(con, "iris")
dbWriteTable(con, "iris", iris)
dbExistsTable(con, "iris")

dbDisconnect(con)

Remove a table from the database

This section describes the behavior of the following method:

dbRemoveTable(conn, name, ...)

Description

Remove a remote table (e.g., created by dbWriteTable()) from the database.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbRemoveTable("MariaDBConnection", "character")

  • RSQLite::dbRemoveTable("SQLiteConnection", "character")

Arguments

conn

A DBIConnection object, as returned by dbConnect().

name

The table name, passed on to dbQuoteIdentifier(). Options are:

  • a character string with the unquoted DBMS table name, e.g. “table_name”,

  • a call to Id() with components to the fully qualified table name, e.g. Id(schema = “my_schema”, table = “table_name”)

  • a call to SQL() with the quoted and fully qualified table name given verbatim, e.g. SQL(‘“my_schema”.“table_name”’)

Other parameters passed on to methods.

Additional arguments

The following arguments are not part of the dbRemoveTable() generic (to improve compatibility across backends) but are part of the DBI specification:

  • temporary (default: FALSE)

  • fail_if_missing (default: TRUE)

These arguments must be provided as named arguments.

If temporary is TRUE, the call to dbRemoveTable() will consider only temporary tables. Not all backends support this argument. In particular, permanent tables of the same name are left untouched.

If fail_if_missing is FALSE, the call to dbRemoveTable() succeeds if the table does not exist.

Specification

A table removed by dbRemoveTable() doesn’t appear in the list of tables returned by dbListTables(), and dbExistsTable() returns FALSE. The removal propagates immediately to other connections to the same database. This function can also be used to remove a temporary table.

The name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

  • If an unquoted table name as string: dbRemoveTable() will do the quoting, perhaps by calling dbQuoteIdentifier(conn, x = name)

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done

Value

dbRemoveTable() returns TRUE, invisibly.

Failure modes

If the table does not exist, an error is raised. An attempt to remove a view with this function may result in an error.

An error is raised when calling this method for a closed or invalid connection. An error is also raised if name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbExistsTable(con, "iris")
dbWriteTable(con, "iris", iris)
dbExistsTable(con, "iris")
dbRemoveTable(con, "iris")
dbExistsTable(con, "iris")

dbDisconnect(con)

List field names of a remote table

This section describes the behavior of the following method:

dbListFields(conn, name, ...)

Description

List field names of a remote table

Arguments

conn

A DBIConnection object, as returned by dbConnect().

name

The table name, passed on to dbQuoteIdentifier(). Options are:

  • a character string with the unquoted DBMS table name, e.g. “table_name”,

  • a call to Id() with components to the fully qualified table name, e.g. Id(schema = “my_schema”, table = “table_name”)

  • a call to SQL() with the quoted and fully qualified table name given verbatim, e.g. SQL(‘“my_schema”.“table_name”’)

Other parameters passed on to methods.

Value

dbListFields() returns a character vector that enumerates all fields in the table in the correct order. This also works for temporary tables if supported by the database. The returned names are suitable for quoting with dbQuoteIdentifier().

Failure modes

If the table does not exist, an error is raised. Invalid types for the name argument (e.g., character of length not equal to one, or numeric) lead to an error. An error is also raised when calling this method for a closed or invalid connection.

Specification

The name argument can be

  • a string

  • the return value of dbQuoteIdentifier()

  • a value from the table column from the return value of dbListObjects() where is_prefix is FALSE

A column named row_names is treated like any other column.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
dbListFields(con, "mtcars")

dbDisconnect(con)

Is this DBMS object still valid?

This section describes the behavior of the following method:

dbIsValid(dbObj, ...)

Description

This generic tests whether a database object is still valid (i.e. it hasn’t been disconnected or cleared).

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbIsValid("MariaDBConnection")

  • RMariaDB::dbIsValid("MariaDBDriver")

  • RMariaDB::dbIsValid("MariaDBResult")

  • RSQLite::dbIsValid("SQLiteConnection")

  • RSQLite::dbIsValid("SQLiteDriver")

  • RSQLite::dbIsValid("SQLiteResult")

Arguments

dbObj An object inheriting from DBIObject, i.e. DBIDriver, DBIConnection, or a DBIResult
... Other arguments to methods.

Value

dbIsValid() returns a logical scalar, TRUE if the object specified by dbObj is valid, FALSE otherwise. A DBIConnection object is initially valid, and becomes invalid after disconnecting with dbDisconnect(). For an invalid connection object (e.g., for some drivers if the object is saved to a file and then restored), the method also returns FALSE. A DBIResult object is valid after a call to dbSendQuery(), and stays valid even after all rows have been fetched; only clearing it with dbClearResult() invalidates it. A DBIResult object is also valid after a call to dbSendStatement(), and stays valid after querying the number of rows affected; only clearing it with dbClearResult() invalidates it. If the connection to the database system is dropped (e.g., due to connectivity problems, server failure, etc.), dbIsValid() should return FALSE. This is not tested automatically.

Examples

dbIsValid(RSQLite::SQLite())

con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbIsValid(con)

rs <- dbSendQuery(con, "SELECT 1")
dbIsValid(rs)

dbClearResult(rs)
dbIsValid(rs)

dbDisconnect(con)
dbIsValid(con)

Completion status

This section describes the behavior of the following method:

dbHasCompleted(res, ...)

Description

This method returns if the operation has completed. A SELECT query is completed if all rows have been fetched. A data manipulation statement is always completed.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbHasCompleted("MariaDBResult")

  • RSQLite::dbHasCompleted("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbHasCompleted() returns a logical scalar. For a query initiated by dbSendQuery() with non-empty result set, dbHasCompleted() returns FALSE initially and TRUE after calling dbFetch() without limit. For a query initiated by dbSendStatement(), dbHasCompleted() always returns TRUE.

Failure modes

Attempting to query completion status for a result set cleared with dbClearResult() gives an error.

Specification

The completion status for a query is only guaranteed to be set to FALSE after attempting to fetch past the end of the entire result. Therefore, for a query with an empty result set, the initial return value is unspecified, but the result value is TRUE after trying to fetch only one row.

Similarly, for a query with a result set of length n, the return value is unspecified after fetching n rows, but the result value is TRUE after trying to fetch only one more row.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")

dbHasCompleted(rs)
ret1 <- dbFetch(rs, 10)
dbHasCompleted(rs)
ret2 <- dbFetch(rs)
dbHasCompleted(rs)

dbClearResult(rs)
dbDisconnect(con)

Get the statement associated with a result set

This section describes the behavior of the following method:

dbGetStatement(res, ...)

Description

Returns the statement that was passed to dbSendQuery() or dbSendStatement().

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbGetStatement("MariaDBResult")

  • RSQLite::dbGetStatement("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbGetStatement() returns a string, the query used in either dbSendQuery() or dbSendStatement().

Failure modes

Attempting to query the statement for a result set cleared with dbClearResult() gives an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")
dbGetStatement(rs)

dbClearResult(rs)
dbDisconnect(con)

The number of rows fetched so far

This section describes the behavior of the following method:

dbGetRowCount(res, ...)

Description

Returns the total number of rows actually fetched with calls to dbFetch() for this result set.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbGetRowCount("MariaDBResult")

  • RSQLite::dbGetRowCount("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbGetRowCount() returns a scalar number (integer or numeric), the number of rows fetched so far. After calling dbSendQuery(), the row count is initially zero. After a call to dbFetch() without limit, the row count matches the total number of rows returned. Fetching a limited number of rows increases the number of rows by the number of rows returned, even if fetching past the end of the result set. For queries with an empty result set, zero is returned even after fetching. For data manipulation statements issued with dbSendStatement(), zero is returned before and after calling dbFetch().

Failure modes

Attempting to get the row count for a result set cleared with dbClearResult() gives an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendQuery(con, "SELECT * FROM mtcars")

dbGetRowCount(rs)
ret1 <- dbFetch(rs, 10)
dbGetRowCount(rs)
ret2 <- dbFetch(rs)
dbGetRowCount(rs)
nrow(ret1) + nrow(ret2)

dbClearResult(rs)
dbDisconnect(con)

The number of rows affected

This section describes the behavior of the following method:

dbGetRowsAffected(res, ...)

Description

This method returns the number of rows that were added, deleted, or updated by a data manipulation statement.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbGetRowsAffected("MariaDBResult")

  • RSQLite::dbGetRowsAffected("SQLiteResult")

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbGetRowsAffected() returns a scalar number (integer or numeric), the number of rows affected by a data manipulation statement issued with dbSendStatement(). The value is available directly after the call and does not change after calling dbFetch(). For queries issued with dbSendQuery(), zero is returned before and after the call to dbFetch().

Failure modes

Attempting to get the rows affected for a result set cleared with dbClearResult() gives an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
rs <- dbSendStatement(con, "DELETE FROM mtcars")
dbGetRowsAffected(rs)
nrow(mtcars)

dbClearResult(rs)
dbDisconnect(con)

Information about result types

This section describes the behavior of the following method:

dbColumnInfo(res, ...)

Description

Produces a data.frame that describes the output of a query. The data.frame should have as many rows as there are output fields in the result set, and each column in the data.frame describes an aspect of the result set field (field name, type, etc.)

Arguments

res An object inheriting from DBIResult.
... Other arguments passed on to methods.

Value

dbColumnInfo() returns a data frame with at least two columns "name" and "type" (in that order) (and optional columns that start with a dot). The "name" and "type" columns contain the names and types of the R columns of the data frame that is returned from dbFetch(). The "type" column is of type character and only for information. Do not compute on the "type" column, instead use dbFetch(res, n = 0) to create a zero-row data frame initialized with the correct data types.

Failure modes

An attempt to query columns for a closed result set raises an error.

Specification

A column named row_names is treated like any other column.

The column names are always consistent with the data returned by dbFetch().

If the query returns unnamed columns, non-empty and non-NA names are assigned.

Column names that correspond to SQL or R keywords are left unchanged.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

rs <- dbSendQuery(con, "SELECT 1 AS a, 2 AS b")
dbColumnInfo(rs)
dbFetch(rs)

dbClearResult(rs)
dbDisconnect(con)

Begin/commit/rollback SQL transactions

This section describes the behavior of the following methods:

dbBegin(conn, ...)

dbCommit(conn, ...)

dbRollback(conn, ...)

Description

A transaction encapsulates several SQL statements in an atomic unit. It is initiated with dbBegin() and either made persistent with dbCommit() or undone with dbRollback(). In any case, the DBMS guarantees that either all or none of the statements have a permanent effect. This helps ensuring consistency of write operations to multiple tables.

Methods in other packages

This documentation page describes the generics. Refer to the documentation pages linked below for the documentation for the methods that are implemented in various backend packages.

  • RMariaDB::dbBegin("MariaDBConnection")

  • RMariaDB::dbCommit("MariaDBConnection")

  • RMariaDB::dbRollback("MariaDBConnection")

  • RSQLite::dbBegin("SQLiteConnection")

  • RSQLite::dbCommit("SQLiteConnection")

  • RSQLite::dbRollback("SQLiteConnection")

Arguments

conn A DBIConnection object, as returned by dbConnect().
... Other parameters passed on to methods.

Details

Not all database engines implement transaction management, in which case these methods should not be implemented for the specific DBIConnection subclass.

Value

dbBegin(), dbCommit() and dbRollback() return TRUE, invisibly.

Failure modes

The implementations are expected to raise an error in case of failure, but this is not tested. In any way, all generics throw an error with a closed or invalid connection. In addition, a call to dbCommit() or dbRollback() without a prior call to dbBegin() raises an error. Nested transactions are not supported by DBI, an attempt to call dbBegin() twice yields an error.

Specification

Actual support for transactions may vary between backends. A transaction is initiated by a call to dbBegin() and committed by a call to dbCommit(). Data written in a transaction must persist after the transaction is committed. For example, a record that is missing when the transaction is started but is created during the transaction must exist both during and after the transaction, and also in a new connection.

A transaction can also be aborted with dbRollback(). All data written in such a transaction must be removed after the transaction is rolled back. For example, a record that is missing when the transaction is started but is created during the transaction must not exist anymore after the rollback.

Disconnection from a connection with an open transaction effectively rolls back the transaction. All data written in such a transaction must be removed after the transaction is rolled back.

The behavior is not specified if other arguments are passed to these functions. In particular, RSQLite issues named transactions with support for nesting if the name argument is set.

The transaction isolation level is not specified by DBI.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cash", data.frame(amount = 100))
dbWriteTable(con, "account", data.frame(amount = 2000))

# All operations are carried out as logical unit:
dbBegin(con)
withdrawal <- 300
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
dbCommit(con)

dbReadTable(con, "cash")
dbReadTable(con, "account")

# Rolling back after detecting negative value on account:
dbBegin(con)
withdrawal <- 5000
dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
if (dbReadTable(con, "account")$amount >= 0) {
  dbCommit(con)
} else {
  dbRollback(con)
}

dbReadTable(con, "cash")
dbReadTable(con, "account")

dbDisconnect(con)

Self-contained SQL transactions

This section describes the behavior of the following methods:

dbWithTransaction(conn, code, ...)

dbBreak()

Description

Given that transactions are implemented, this function allows you to pass in code that is run in a transaction. The default method of dbWithTransaction() calls dbBegin() before executing the code, and dbCommit() after successful completion, or dbRollback() in case of an error. The advantage is that you don’t have to remember to do dbBegin() and dbCommit() or dbRollback() – that is all taken care of. The special function dbBreak() allows an early exit with rollback, it can be called only inside dbWithTransaction().

Arguments

conn A DBIConnection object, as returned by dbConnect().
code An arbitrary block of R code.
... Other parameters passed on to methods.

Details

DBI implements dbWithTransaction(), backends should need to override this generic only if they implement specialized handling.

Value

dbWithTransaction() returns the value of the executed code.

Failure modes

Failure to initiate the transaction (e.g., if the connection is closed or invalid of if dbBegin() has been called already) gives an error.

Specification

dbWithTransaction() initiates a transaction with dbBegin(), executes the code given in the code argument, and commits the transaction with dbCommit(). If the code raises an error, the transaction is instead aborted with dbRollback(), and the error is propagated. If the code calls dbBreak(), execution of the code stops and the transaction is silently aborted. All side effects caused by the code (such as the creation of new variables) propagate to the calling environment.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cash", data.frame(amount = 100))
dbWriteTable(con, "account", data.frame(amount = 2000))

# All operations are carried out as logical unit:
dbWithTransaction(
  con,
  {
    withdrawal <- 300
    dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
    dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
  }
)

# The code is executed as if in the curent environment:
withdrawal

# The changes are committed to the database after successful execution:
dbReadTable(con, "cash")
dbReadTable(con, "account")

# Rolling back with dbBreak():
dbWithTransaction(
  con,
  {
    withdrawal <- 5000
    dbExecute(con, "UPDATE cash SET amount = amount + ?", list(withdrawal))
    dbExecute(con, "UPDATE account SET amount = amount - ?", list(withdrawal))
    if (dbReadTable(con, "account")$amount < 0) {
      dbBreak()
    }
  }
)

# These changes were not committed to the database:
dbReadTable(con, "cash")
dbReadTable(con, "account")

dbDisconnect(con)
DBI/inst/doc/DBI-advanced.Rmd0000644000176200001440000002640514155273064015215 0ustar liggesusers--- title: "Advanced DBI Usage" author: "James Wondrasek, Kirill Müller" date: "17/03/2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"Advanced DBI Usage"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} library(knitr) opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) knit_print.data.frame <- function(x, ...) { print(head(x, 3)) if (nrow(x) > 3) { cat("Showing 3 out of", nrow(x), "rows.\n") } invisible(x) } registerS3method("knit_print", "data.frame", "knit_print.data.frame") ``` ## Who this tutorial is for This tutorial is for you if you need to use a richer set of SQL features such as data manipulation queries, parameterized queries and queries performed using SQL's transaction features. See `vignette("DBI", package = "DBI")` for a more basic tutorial covering connecting to DBMS and executing simple queries. ## How to run more complex queries using DBI `dbGetQuery()` works by calling a number of functions behind the scenes. If you need more control you can manually build your own query, retrieve results at your selected rate, and release the resources involved by calling the same functions. These functions are: - `dbSendQuery()` sends the SQL query to the DBMS and returns a `result` object. The query is limited to `SELECT` statements. If you want to send other statements, such as `INSERT`, `UPDATE`, `DELETE`, etc, use `dbSendStatement()`. - `dbFetch()` is called with the `result` object returned by `dbSendQuery()`. It also accepts an argument specifying the number of rows to be returned, e.g. `n = 200`. If you want to fetch all the rows, use `n = -1`. - `dbClearResult()` is called when you have finished retrieving data. It releases the resources associated with the `result` object. ```{r} library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = 'G'") df <- dbFetch(res, n = 3) dbClearResult(res) head(df, 3) ``` ## How to read part of a table from a database If your dataset is large you may want to fetch a limited number of rows at a time. As demonstrated below, this can be accomplished by using a while loop where the function `dbHasCompleted()` is used to check for ongoing rows, and `dbFetch()` is used with the `n = X` argument, specifying how many rows to return on each iteration. Again, we call `dbClearResult()` at the end to release resources. ```{r} res <- dbSendQuery(con, "SELECT * FROM film") while (!dbHasCompleted(res)) { chunk <- dbFetch(res, n = 300) print(nrow(chunk)) } dbClearResult(res) ``` ## How to use parameters (safely) in SQL queries `dbSendQuery()` can be used with parameterized SQL queries. DBI supports two ways to avoid SQL injection attacks from user-supplied parameters: quoting and parameterized queries. ### Quoting Quoting of parameter values is performed using the function `dbQuoteLiteral()`, which supports many R data types, including date and time.[^quote-string] [^quote-string]: An older method, `dbQuoteString()`, was used to quote string values only. The `dbQuoteLiteral()` method forwards to `dbQuoteString()` for character vectors. Users do not need to distinguish between these two cases. In cases where users may be supplying table or column names to use in the query for data retrieval, those names or identifiers must also be escaped. As there may be DBMS-specific rules for escaping these identifiers, DBI provides the function `dbQuoteIdentifier()` to generate a safe string representation. ```{r quote} safe_id <- dbQuoteIdentifier(con, "rating") safe_param <- dbQuoteLiteral(con, "G") query <- paste0("SELECT title, ", safe_id, " FROM film WHERE ", safe_id, " = ", safe_param ) query res <- dbSendQuery(con, query) dbFetch(res) dbClearResult(res) ``` The same result can be had by using `glue::glue_sql()`. It performs the same safe quoting on any variable or R statement appearing between braces within the query string. ```{r} id <- "rating" param <- "G" query <- glue::glue_sql("SELECT title, {`id`} FROM film WHERE {`id`} = {param}", .con = con) df <- dbGetQuery(con, query) head(df, 3) ``` ### Parameterized queries Rather than performing the parameter substitution ourselves, we can push it to the DBMS by including placeholders in the query. Different DBMS use different placeholder schemes, DBI passes through the SQL expression unchanged. MariaDB uses a question mark (?) as placeholder and expects an unnamed list of parameter values. Other DBMS may use named parameters. We recommend consulting the documentation for the DBMS you are using. As an example, a web search for "mariadb parameterized queries" leads to the documentation for the [`PREPARE` statement](https://mariadb.com/kb/en/prepare-statement/) which mentions: > Within the statement, "?" characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it. Currently there is no list of which placeholder scheme a particular DBMS supports. Placeholders only work for literal values. Other parts of the query, e.g. table or column identifiers, still need to be quoted with `dbQuoteIdentifier()`. For a single set of parameters, the `params` argument to `dbSendQuery()` or `dbGetQuery()` can be used. It takes a list and its members are substituted in order for the placeholders within the query. ```{r params} params <- list("G") safe_id <- dbQuoteIdentifier(con, "rating") query <- paste0("SELECT * FROM film WHERE ", safe_id, " = ?") query res <- dbSendQuery(con, query, params = params) dbFetch(res, n = 3) dbClearResult(res) ``` Below is an example query using multiple placeholders with the MariaDB driver. The placeholders are supplied as a list of values ordered to match the position of the placeholders in the query. ```{r multi-param} q_params <- list("G", 90) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ``` When you wish to perform the same query with different sets of parameter values, `dbBind()` is used. There are two ways to use `dbBind()`. Firstly, it can be used multiple times with same query. ```{r dbbind} res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list("G")) dbFetch(res, n = 3) dbBind(res, list("PG")) dbFetch(res, n = 3) dbClearResult(res) ``` Secondly, `dbBind()` can be used to execute the same statement with multiple values at once. ```{r bind_quotestring} res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?") dbBind(res, list(c("G", "PG"))) dbFetch(res, n = 3) dbClearResult(res) ``` Use a list of vectors if your query has multiple parameters: ```{r bind-multi-param} q_params <- list(c("G", "PG"), c(90, 120)) query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?" res <- dbSendQuery(con, query, params = q_params) dbFetch(res, n = 3) dbClearResult(res) ``` Always disconnect from the database when done. ```{r disconnect} dbDisconnect(con) ``` ## SQL data manipulation - UPDATE, DELETE and friends For SQL queries that affect the underlying database, such as UPDATE, DELETE, INSERT INTO, and DROP TABLE, DBI provides two functions. `dbExecute()` passes the SQL statement to the DBMS for execution and returns the number of rows affected. `dbSendStatement()` performs in the same manner, but returns a result object. Call `dbGetRowsAffected()` with the result object to get the count of the affected rows. You then need to call `dbClearResult()` with the result object afterwards to release resources. In actuality, `dbExecute()` is a convenience function that calls `dbSendStatement()`, `dbGetRowsAffected()`, and `dbClearResult()`. You can use these functions if you need more control over the query process. The subsequent examples use an in-memory SQL database provided by `RSQLite::SQLite()`, because the remote database used in above examples does not allow writing. ```{r} library(DBI) con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cars", head(cars, 3)) dbExecute( con, "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)" ) rs <- dbSendStatement( con, "INSERT INTO cars (speed, dist) VALUES (4, 4), (5, 5), (6, 6)" ) dbGetRowsAffected(rs) dbClearResult(rs) dbReadTable(con, "cars") dbDisconnect(con) ``` ## SQL transactions with DBI DBI allows you to group multiple queries into a single atomic transaction. Transactions are initiated with `dbBegin()` and either made persistent with `dbCommit()` or undone with `dbRollback()`. The example below updates two tables and ensures that either both tables are updated, or no changes are persisted to the database and an error is thrown. ```{r} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "cash", data.frame(amount = 100)) dbWriteTable(con, "account", data.frame(amount = 2000)) withdraw <- function(amount) { # All operations must be carried out as logical unit: dbExecute(con, "UPDATE cash SET amount = amount + ?", list(amount)) dbExecute(con, "UPDATE account SET amount = amount - ?", list(amount)) } withdraw_transacted <- function(amount) { # Ensure atomicity dbBegin(con) # Perform operation withdraw(amount) # Persist results dbCommit(con) } withdraw_transacted(300) ``` After withdrawing 300 credits, the cash is increased and the account is decreased by this amount. The transaction ensures that either both operations succeed, or no change occurs. ```{r} dbReadTable(con, "cash") dbReadTable(con, "account") ``` We can roll back changes manually if necessary. Do not forget to call `dbRollback()` in case of error, otherwise the transaction remains open indefinitely. ```{r} withdraw_if_funds <- function(amount) { dbBegin(con) withdraw(amount) # Rolling back after detecting negative value on account: if (dbReadTable(con, "account")$amount >= 0) { dbCommit(con) TRUE } else { message("Insufficient funds") dbRollback(con) FALSE } } withdraw_if_funds(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ``` `dbWithTransaction()` simplifies using transactions. Pass it a connection and the code you want to run as a transaction. It will execute the code and call `dbCommit()` on success and call `dbRollback()` if an error is thrown. ```{r error = TRUE} withdraw_safely <- function(amount) { dbWithTransaction(con, { withdraw(amount) if (dbReadTable(con, "account")$amount < 0) { stop("Error: insufficient funds", call. = FALSE) } }) } withdraw_safely(5000) dbReadTable(con, "cash") dbReadTable(con, "account") ``` As usual, do not forget to disconnect from the database when done. ```{r} dbDisconnect(con) ``` ## Conclusion That concludes the major features of DBI. For more details on the library functions covered in this tutorial and the `vignette("DBI", package = "DBI")` introductory tutorial see the DBI specification at `vignette("spec", package = "DBI")`. If you are after a data manipulation library that works at a higher level of abstraction, check out [dplyr](https://dplyr.tidyverse.org). It is a grammar of data manipulation that can work with local dataframes and remote databases and uses DBI under the hood. DBI/inst/doc/DBI-1.html0000644000176200001440000043331714157714547014046 0ustar liggesusers A Common Database Interface (DBI)

A Common Database Interface (DBI)

R-Databases Special Interest Group

16 June 2003

This document describes a common interface between the S language (in its R and S-Plus implementations) and database management systems (DBMS). The interface defines a small set of classes and methods similar in spirit to Perl’s DBI, Java’s JDBC, Python’s DB-API, and Microsoft’s ODBC.

Version

This document describes version 0.1-6 of the database interface API (application programming interface).

Introduction

The database interface (DBI) separates the connectivity to the DBMS into a “front-end” and a “back-end.” Applications use only the exposed “front-end” API. The facilities that communicate with specific DBMS (Oracle, PostgreSQL, etc.) are provided by “device drivers” that get invoked automatically by the S language evaluator. The following example illustrates some of the DBI capabilities:

## Choose the proper DBMS driver and connect to the server

drv <- dbDriver("ODBC")
con <- dbConnect(drv, "dsn", "usr", "pwd")

## The interface can work at a higher level importing tables
## as data.frames and exporting data.frames as DBMS tables.

dbListTables(con)
dbListFields(con, "quakes")
if(dbExistsTable(con, "new_results"))
   dbRemoveTable(con, "new_results")
dbWriteTable(con, "new_results", new.output)

## The interface allows lower-level interface to the DBMS
res <- dbSendQuery(con, paste(
            "SELECT g.id, g.mirror, g.diam, e.voltage",
            "FROM geom_table as g, elec_measures as e",
            "WHERE g.id = e.id and g.mirrortype = 'inside'",
            "ORDER BY g.diam"))
out <- NULL
while(!dbHasCompleted(res)){
   chunk <- fetch(res, n = 10000)
   out <- c(out, doit(chunk))
}

## Free up resources
dbClearResult(res)
dbDisconnect(con)
dbUnloadDriver(drv)

(only the first 2 expressions are DBMS-specific – all others are independent of the database engine itself).

Individual DBI drivers need not implement all the features we list below (we indicate those that are optional). Furthermore, drivers may extend the core DBI facilities, but we suggest to have these extensions clearly indicated and documented.

The following are the elements of the DBI:

  1. A set of classes and methods (Section [sec:DBIClasses]) that defines what operations are possible and how they are defined, e.g.:

    • connect/disconnect to the DBMS

    • create and execute statements in the DBMS

    • extract results/output from statements

    • error/exception handling

    • information (meta-data) from database objects

    • transaction management (optional)

    Some things are left explicitly unspecified, e.g., authentication and even the query language, although it is hard to avoid references to SQL and relational database management systems (RDBMS).

  2. Drivers

    Drivers are collection of functions that implement the functionality defined above in the context of specific DBMS, e.g., mSQL, Informix.

  3. Data type mappings (Section [sec:data-mappings].)

    Mappings and conversions between DBMS data types and R/S objects. All drivers should implement the “basic” primitives (see below), but may chose to add user-defined conversion function to handle more generic objects (e.g., factors, ordered factors, time series, arrays, images).

  4. Utilities (Section [sec:utilities].)

    These facilities help with details such as mapping of identifiers between S and DBMS (e.g., _ is illegal in R/S names, and . is used for constructing compound SQL identifiers), etc.

DBI Classes and Methods

The following are the main DBI classes. They need to be extended by individual database back-ends (Sybase, Oracle, etc.) Individual drivers need to provide methods for the generic functions listed here (those methods that are optional are so indicated).

Note: Although R releases prior to 1.4 do not have a formal concept of classes, we will use the syntax of the S Version 4 classes and methods (available in R releases 1.4 and later as library methods) to convey precisely the DBI class hierarchy, its methods, and intended behavior.

The DBI classes are DBIObject, DBIDriver, DBIConnection and DBIResult. All these are virtual classes. Drivers define new classes that extend these, e.g., PgSQLDriver, PgSQLConnection, and so on.

Class hierarchy for the DBI. The top two layers are comprised of virtual classes and each lower layer represents a set of driver-specific implementation classes that provide the functionality defined by the virtual classes above.

DBIObject:

Virtual class1 that groups all other DBI classes.

DBIDriver:

Virtual class that groups all DBMS drivers. Each DBMS driver extends this class. Typically generator functions instantiate the actual driver objects, e.g., PgSQL, HDF5, BerkeleyDB.

DBIConnection:

Virtual class that encapsulates connections to DBMS.

DBIResult:

Virtual class that describes the result of a DBMS query or statement.

[Q: Should we distinguish between a simple result of DBMS statements e.g., as delete from DBMS queries (i.e., those that generate data).]

The methods format, print, show, dbGetInfo, and summary are defined (and implemented in the DBI package) for the DBIObject base class, thus available to all implementations; individual drivers, however, are free to override them as they see fit.

format(x, ...):

produces a concise character representation (label) for the DBIObject x.

print(x, ...)/show(x):

prints a one-line identification of the object x.

summary(object, ...):

produces a concise description of the object. The default method for DBIObject simply invokes dbGetInfo(dbObj) and prints the name-value pairs one per line. Individual implementations may tailor this appropriately.

dbGetInfo(dbObj, ...):

extracts information (meta-data) relevant for the DBIObject dbObj. It may return a list of key/value pairs, individual meta-data if supplied in the call, or NULL if the requested meta-data is not available.

Hint: Driver implementations may choose to allow an argument what to specify individual meta-data, e.g., dbGetInfo(drv, what = max.connections).

In the next few sub-sections we describe in detail each of these classes and their methods.

Class DBIObject

This class simply groups all DBI classes, and thus all extend it.

Class DBIDriver

This class identifies the database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.)

The DBI provides the generator dbDriver(driverName) which simply invokes the function driverName, which in turn instantiates the corresponding driver object.

The DBIDriver class defines the following methods:

driverName:

[meth:driverName] initializes the driver code. The name driverName refers to the actual generator function for the DBMS, e.g., RPgSQL, RODBC, HDF5. The driver instance object is used with dbConnect (see page ) for opening one or possibly more connections to one or more DBMS.

dbListConnections(drv, ...):

list of current connections being handled by the drv driver. May be NULL if there are no open connections. Drivers that do not support multiple connections may return the one open connection.

dbGetInfo(dbObj, ...):

returns a list of name-value pairs of information about the driver.

Hint: Useful entries could include

name:

the driver name (e.g., RODBC, RPgSQL);

driver.version:

version of the driver;

DBI.version:

the version of the DBI that the driver implements, e.g., 0.1-2;

client.version:

of the client DBMS libraries (e.g., version of the libpq library in the case of RPgSQL);

max.connections:

maximum number of simultaneous connections;

plus any other relevant information about the implementation, for instance, how the driver handles upper/lower case in identifiers.

dbUnloadDriver(driverName) (optional):

frees all resources (local and remote) used by the driver. Returns a logical to indicate if it succeeded or not.

Class DBIConnection

This virtual class encapsulates the connection to a DBMS, and it provides access to dynamic queries, result sets, DBMS session management (transactions), etc.

Note: Individual drivers are free to implement single or multiple simultaneous connections.

The methods defined by the DBIConnection class include:

dbConnect(drv, ...):

[meth:dbConnect] creates and opens a connection to the database implemented by the driver drv (see Section [sec:DBIDriver]). Each driver will define what other arguments are required, e.g., dbname or dsn for the database name, user, and password. It returns an object that extends DBIConnection in a driver-specific manner (e.g., the MySQL implementation could create an object of class MySQLConnection that extends DBIConnection).

dbDisconnect(conn, ...):

closes the connection, discards all pending work, and frees resources (e.g., memory, sockets). Returns a logical indicating whether it succeeded or not.

dbSendQuery(conn, statement, ...):

submits one statement to the DBMS. It returns a DBIResult object. This object is needed for fetching data in case the statement generates output (see fetch on page ), and it may be used for querying the state of the operation; see dbGetInfo and other meta-data methods on page .

dbGetQuery(conn, statement, ...):

submit, execute, and extract output in one operation. The resulting object may be a data.frame if the statement generates output. Otherwise the return value should be a logical indicating whether the query succeeded or not.

dbGetException(conn, ...):

returns a list with elements errNum and errMsg with the status of the last DBMS statement sent on a given connection (this information may also be provided by the dbGetInfo meta-data function on the conn object.

Hint: The ANSI SQL-92 defines both a status code and an status message that could be return as members of the list.

dbGetInfo(dbObj, ...):

returns a list of name-value pairs describing the state of the connection; it may return one or more meta-data, the actual driver method allows to specify individual pieces of meta-data (e.g., maximum number of open results/cursors).

Hint: Useful entries could include

dbname:

the name of the database in use;

db.version:

the DBMS server version (e.g., “Oracle 8.1.7 on Solaris”;

host:

host where the database server resides;

user:

user name;

password:

password (is this safe?);

plus any other arguments related to the connection (e.g., thread id, socket or TCP connection type).

dbListResults(conn, ...):

list of DBIResult objects currently active on the connection conn. May be NULL if no result set is active on conn. Drivers that implement only one result set per connection could return that one object (no need to wrap it in a list).

Note: The following are convenience methods that simplify the import/export of (mainly) data.frames. The first five methods implement the core methods needed to attach remote DBMS to the S search path. (For details, see Chambers (1991, 1998).)

Hint: For relational DBMS these methods may be easily implemented using the core DBI methods dbConnect, dbSendQuery, and fetch, due to SQL reflectance (i.e., one easily gets this meta-data by querying the appropriate tables on the RDBMS).

dbListTables(conn, ...):

returns a character vector (possibly of zero-length) of object (table) names available on the conn connection.

dbReadTable(conn, name, ...):

imports the data stored remotely in the table name on connection conn. Use the field row.names as the row.names attribute of the output data.frame. Returns a data.frame.

[Q: should we spell out how row.names should be created? E.g., use a field (with unique values) as row.names? Also, should dbReadTable reproduce a data.frame exported with dbWriteTable?]

dbWriteTable(conn, name, value, ...):

write the object value (perhaps after coercing it to data.frame) into the remote object name in connection conn. Returns a logical indicating whether the operation succeeded or not.

dbExistsTable(conn, name, ...):

does remote object name exist on conn? Returns a logical.

dbRemoveTable(conn, name, ...):

removes remote object name on connection conn. Returns a logical indicating whether the operation succeeded or not.

dbListFields(conn, name, ...):

returns a character vector listing the field names of the remote table name on connection conn (see dbColumnInfo() for extracting data type on a table).

Note: The following methods deal with transactions and stored procedures. All these functions are optional.

dbCommit(conn, ...)(optional):

commits pending transaction on the connection and returns TRUE or FALSE depending on whether the operation succeeded or not.

dbRollback(conn, ...)(optional):

undoes current transaction on the connection and returns TRUE or FALSE depending on whether the operation succeeded or not.

dbCallProc(conn, storedProc, ...)(optional):

invokes a stored procedure in the DBMS and returns a DBIResult object.

[Stored procedures are not part of the ANSI SQL-92 standard and vary substantially from one RDBMS to another.]

Deprecated since 2014:

The recommended way of calling a stored procedure is now

  • dbGetQuery if a result set is returned and
  • dbExecute for data manipulation and other cases that do not return a result set.

Class DBIResult

This virtual class describes the result and state of execution of a DBMS statement (any statement, query or non-query). The result set res keeps track of whether the statement produces output for R/S, how many rows were affected by the operation, how many rows have been fetched (if statement is a query), whether there are more rows to fetch, etc.

Note: Individual drivers are free to allow single or multiple active results per connection.

[Q: Should we distinguish between results that return no data from those that return data?]

The class DBIResult defines the following methods:

fetch(res, n, ...):

[meth:fetch] fetches the next n elements (rows) from the result set res and return them as a data.frame. A value of n=-1 is interpreted as “return all elements/rows.”

dbClearResult(res, ...):

flushes any pending data and frees all resources (local and remote) used by the object res on both sides of the connection. Returns a logical indicating success or not.

dbGetInfo(dbObj, ...):

returns a name-value list with the state of the result set.

Hint: Useful entries could include

statement:

a character string representation of the statement being executed;

rows.affected:

number of affected records (changed, deleted, inserted, or extracted);

row.count:

number of rows fetched so far;

has.completed:

has the statement (query) finished?

is.select:

a logical describing whether or not the statement generates output;

plus any other relevant driver-specific meta-data.

dbColumnInfo(res, ...):

produces a data.frame that describes the output of a query. The data.frame should have as many rows as there are output fields in the result set, and each column in the data.frame should describe an aspect of the result set field (field name, type, etc.)

Hint: The data.frame columns could include

field.name:

DBMS field label;

field.type:

DBMS field type (implementation-specific);

data.type:

corresponding R/S data type, e.g., integer;

precision/scale:

(as in ODBC terminology), display width and number of decimal digits, respectively;

nullable:

whether the corresponding field may contain (DBMS) NULL values;

plus other driver-specific information.

dbSetDataMappings(flds, ...)(optional):

defines a conversion between internal DBMS data types and R/S classes. We expect the default mappings (see Section [sec:data-mappings]) to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. [This topic needs further discussion.]

Note: The following are convenience methods that extract information from the result object (they may be implemented by invoking dbGetInfo with appropriate arguments).

dbGetStatement(res, ...)(optional):

returns the DBMS statement (as a character string) associated with the result res.

dbGetRowsAffected(res, ...)(optional):

returns the number of rows affected by the executed statement (number of records deleted, modified, extracted, etc.)

dbHasCompleted(res, ...)(optional):

returns a logical that indicates whether the operation has been completed (e.g., are there more records to be fetched?).

dbGetRowCount(res, ...)(optional):

returns the number of rows fetched so far.

Data Type Mappings

The data types supported by databases are different than the data types in R and S, but the mapping between the “primitive” types is straightforward: Any of the many fixed and varying length character types are mapped to R/S character. Fixed-precision (non-IEEE) numbers are mapped into either doubles (numeric) or long (integer). Notice that many DBMS do not follow the so-called IEEE arithmetic, so there are potential problems with under/overflows and loss of precision, but given the R/S primitive types we cannot do too much but identify these situations and warn the application (how?).

By default dates and date-time objects are mapped to character using the appropriate TO_CHAR function in the DBMS (which should take care of any locale information). Some RDBMS support the type CURRENCY or MONEY which should be mapped to numeric (again with potential round off errors). Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion (as has been done in other inter-systems packages).2

Specifying user-defined conversion functions still needs to be defined.

Utilities

The core DBI implementation should make available to all drivers some common basic utilities. For instance:

dbGetDBIVersion:

returns the version of the currently attached DBI as a string.

dbDataType(dbObj, obj, ...):

returns a string with the (approximately) appropriate data type for the R/S object obj. The DBI can implement this following the ANSI-92 standard, but individual drivers may want/need to extend it to make use of DBMS-specific types.

make.db.names(dbObj, snames, ...):

maps R/S names (identifiers) to SQL identifiers replacing illegal characters (as .) by the legal SQL _.

SQLKeywords(dbObj, ...):

returns a character vector of SQL keywords (reserved words). The default method returns the list of .SQL92Keywords, but drivers should update this vector with the DBMS-specific additional reserved words.

isSQLKeyword(dbObj, name, ...):

for each element in the character vector name determine whether or not it is an SQL keyword, as reported by the generic function SQLKeywords. Returns a logical vector parallel to the input object name.

Open Issues and Limitations

There are a number of issues and limitations that the current DBI conscientiously does not address on the interest of simplicity. We do list here the most important ones.

Non-SQL:

Is it realistic to attempt to encompass non-relational databases, like HDF5, Berkeley DB, etc.?

Security:

allowing users to specify their passwords on R/S scripts may be unacceptable for some applications. We need to consider alternatives where users could store authentication on files (perhaps similar to ODBC’s odbc.ini) with more stringent permissions.

Exceptions:

the exception mechanism is a bit too simple, and it does not provide for information when problems stem from the DBMS interface itself. For instance, under/overflow or loss of precision as we move numeric data from DBMS to the more limited primitives in R/S.

Asynchronous communication:

most DBMS support both synchronous and asynchronous communications, allowing applications to submit a query and proceed while the database server process the query. The application is then notified (or it may need to poll the server) when the query has completed. For large computations, this could be very useful, but the DBI would need to specify how to interrupt the server (if necessary) plus other details. Also, some DBMS require applications to use threads to implement asynchronous communication, something that neither R nor S-Plus currently addresses.

SQL scripts:

the DBI only defines how to execute one SQL statement at a time, forcing users to split SQL scripts into individual statements. We need a mechanism by which users can submit SQL scripts that could possibly generate multiple result sets; in this case we may need to introduce new methods to loop over multiple results (similar to Python’s nextResultSet).

BLOBS/CLOBS:

large objects (both character and binary) present some challenges both to R and S-Plus. It is becoming more common to store images, sounds, and other data types as binary objects in DBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects.

Transactions:

transaction management is not fully described.

Additional methods:

Do we need any additional methods? (e.g., dbListDatabases(conn), dbListTableIndices(conn, name), how do we list all available drivers?)

Bind variables:

the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of R/S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement

  /* SQL */
  SELECT * from emp_table where emp_id = :sampleEmployee

would take the vector sampleEmployee and iterate over each of its elements to get the result. Perhaps the DBI could at some point in the future implement this feature.

Resources

The idea of a common interface to databases has been successfully implemented in various environments, for instance:

Java’s Database Connectivity (JDBC) (www.javasoft.com).

In C through the Open Database Connectivity (ODBC) (www.unixodbc.org).

Python’s Database Application Programming Interface (www.python.org).

Perl’s Database Interface (dbi.perl.org).

Chambers, John M. 1991. “Data Management in S.” Bell Labs, Lucent Technologies.
———. 1998. “Database Classes.” Bell Labs, Lucent Technologies.

  1. A virtual class allows us to group classes that share some common characteristics, even if their implementations are radically different.↩︎

  2. Duncan Temple Lang has volunteered to port the data conversion code found in R-Java, R-Perl, and R-Python packages to the DBI↩︎

DBI/inst/doc/DBI-proposal.Rmd0000644000176200001440000006643614064774575015333 0ustar liggesusers--- title: "A Common Interface to Relational Databases from R and S -- A Proposal" author: "David James" date: "March 16, 2000" output: rmarkdown::html_vignette bibliography: biblio.bib vignette: > %\VignetteIndexEntry{A Common Interface to Relational Databases from R and S -- A Proposal} %\VignetteEngine{knitr::rmarkdown} --- For too long S and similar data analysis environments have lacked good interfaces to relational database systems (RDBMS). For the last twenty years or so these RDBMS have evolved into highly optimized client-server systems for data storage and manipulation, and currently they serve as repositories for most of the business, industrial, and research “raw” data that analysts work with. Other analysis packages, such as SAS, have traditionally provided good data connectivity, but S and GNU R have relied on intermediate text files as means of importing data (but see @R.imp-exp and @R-dbms.) Although this simple approach works well for relatively modest amounts of mostly static data, it does not scale up to larger amounts of data distributed over machines and locations, nor does it scale up to data that is highly dynamic – situations that are becoming increasingly common. We want to propose a common interface between R/S and RDBMS that would allow users to access data stored on database servers in a uniform and predictable manner irrespective of the database engine. The interface defines a small set of classes and methods similar in spirit to Python’s DB-API, Java’s JDBC, Microsoft’s ODBC, Perl’s DBI, etc., but it conforms to the “whole-object” philosophy so natural in S and R. # Computing with Distributed Data {#sec:distr} As data analysts, we are increasingly faced with the challenge of larger data sources distributed over machines and locations; most of these data sources reside in relational database management systems (RDBMS). These relational databases represent a mature client-server distributed technology that we as analysts could be exploiting more that we’ve done in the past. The relational technology provides a well-defined standard, the ANSI SQL-92 @sql92, both for defining and manipulating data in a highly optimized fashion from virtually any application. In contrast, S and Splus have provided somewhat limited tools for coping with the challenges of larger and distributed data sets (Splus does provide an `import` function to import from databases, but it is quite limited in terms of SQL facilities). The R community has been more resourceful and has developed a number of good libraries for connecting to mSQL, MySQL, PostgreSQL, and ODBC; each library, however, has defined its own interface to each database engine a bit differently. We think it would be to everybody’s advantage to coordinate the definition of a common interface, an effort not unlike those taken in the Python and Perl communities. The goal of a common, seamless access to distributed data is a modest one in our evolution towards a fully distributed computing environment. We recognize the greater goal of distributed computing as the means to fully integrate diverse systems – not just databases – into a truly flexible analysis environment. Good connectivity to databases, however, is of immediate necessity both in practical terms and as a means to help us transition from monolithic, self-contained systems to those in which computations, not only the data, can be carried out in parallel over a wide number of computers and/or systems @duncan2000. Issues of reliability, security, location transparency, persistence, etc., will be new to most of us and working with distributed data may provide a more gradual change to ease in the ultimate goal of full distributed computing. # A Common Interface {#sec:rs-dbi} We believe that a common interface to databases can help users easily access data stored in RDBMS. A common interface would describe, in a uniform way, how to connect to RDBMS, extract meta-data (such as list of available databases, tables, etc.) as well as a uniform way to execute SQL statements and import their output into R and S. The current emphasis is on querying databases and not so much in a full low-level interface for database development as in JDBC or ODBC, but unlike these, we want to approach the interface from the “whole-object” perspective @S4 so natural to R/S and Python – for instance, by fetching all fields and records simultaneously into a single object. The basic idea is to split the interface into a front-end consisting of a few classes and generic functions that users invoke and a back-end set of database-specific classes and methods that implement the actual communication. (This is a very well-known pattern in software engineering, and another good verbatim is the device-independent graphics in R/S where graphics functions produce similar output on a variety of different devices, such X displays, Postscript, etc.) The following verbatim shows the front-end: ``` > mgr <- dbManager("Oracle") > con <- dbConnect(mgr, user = "user", passwd = "passwd") > rs <- dbExecStatement(con, "select fld1, fld2, fld3 from MY_TABLE") > tbls <- fetch(rs, n = 100) > hasCompleted(rs) [1] T > close(rs) > rs <- dbExecStatement(con, "select id_name, q25, q50 from liv2") > res <- fetch(rs) > getRowCount(rs) [1] 73 > close(con) ``` Such scripts should work with other RDBMS (say, MySQL) by replacing the first line with ``` > mgr <- dbManager("MySQL") ``` ## Interface Classes {#sec:rs-dbi-classes} The following are the main RS-DBI classes. They need to be extended by individual database back-ends (MySQL, Oracle, etc.) `dbManager` : Virtual class[^2] extended by actual database managers, e.g., Oracle, MySQL, Informix. `dbConnection` : Virtual class that captures a connection to a database instance[^3]. `dbResult` : Virtual class that describes the result of an SQL statement. `dbResultSet` : Virtual class, extends `dbResult` to fully describe the output of those statements that produce output records, i.e., `SELECT` (or `SELECT`-like) SQL statement. All these classes should implement the methods `show`, `describe`, and `getInfo`: `show` : (`print` in R) prints a one-line identification of the object. `describe` : prints a short summary of the meta-data of the specified object (like `summary` in R/S). `getInfo` : takes an object of one of the above classes and a string specifying a meta-data item, and it returns the corresponding information (`NULL` if unavailable). > mgr <- dbManager("MySQL") > getInfo(mgr, "version") > con <- dbConnect(mgr, ...) > getInfo(con, "type") The reason we implement the meta-data through `getInfo` in this way is to simplify the writing of database back-ends. We don’t want to overwhelm the developers of drivers (ourselves, most likely) with hundreds of methods as in the case of JDBC. In addition, the following methods should also be implemented: `getDatabases` : lists all available databases known to the `dbManager`. `getTables` : lists tables in a database. `getTableFields` : lists the fields in a table in a database. `getTableIndices` : lists the indices defined for a table in a database. These methods may be implemented using the appropriate `getInfo` method above. In the next few sections we describe in detail each of these classes and their methods. ### Class `dbManager` {#sec:dbManager} This class identifies the relational database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.) The `dbManager` class defines the following methods: `load` : initializes the driver code. We suggest having the generator, `dbManager(driver)`, automatically load the driver. `unload` : releases whatever resources the driver is using. `getVersion` : returns the version of the RS-DBI currently implemented, plus any other relevant information about the implementation itself and the RDBMS being used. ### Class `dbConnection` {#sec:dbConnection} This virtual class captures a connection to a RDBMS, and it provides access to dynamic SQL, result sets, RDBMS session management (transactions), etc. Note that the `dbManager` may or may not allow multiple simultaneous connections. The methods it defines include: `dbConnect` : opens a connection to the database `dbname`. Other likely arguments include `host`, `user`, and `password`. It returns an object that extends `dbConnection` in a driver-specific manner (e.g., the MySQL implementation creates a connection of class `MySQLConnection` that extends `dbConnection`). Note that we could separate the steps of connecting to a RDBMS and opening a database there (i.e., opening an *instance*). For simplicity we do the 2 steps in this method. If the user needs to open another instance in the same RDBMS, just open a new connection. `close` : closes the connection and discards all pending work. `dbExecStatement` : submits one SQL statement. It returns a `dbResult` object, and in the case of a `SELECT` statement, the object also inherits from `dbResultSet`. This `dbResultSet` object is needed for fetching the output rows of `SELECT` statements. The result of a non-`SELECT` statement (e.g., `UPDATE, DELETE, CREATE, ALTER`, ...) is defined as the number of rows affected (this seems to be common among RDBMS). `commit` : commits pending transaction (optional). `rollback` : undoes current transaction (optional). `callProc` : invokes a stored procedure in the RDBMS (tentative). Stored procedures are *not* part of the ANSI SQL-92 standard and possibly vary substantially from one RDBMS to another. For instance, Oracle seems to have a fairly decent implementation of stored procedures, but MySQL currently does not support them. `dbExec` : submit an SQL “script” (multiple statements). May be implemented by looping with `dbExecStatement`. `dbNextResultSet` : When running SQL scripts (multiple statements), it closes the current result set in the `dbConnection`, executes the next statement and returns its result set. ### Class `dbResult` {#sec:dbResult} This virtual class describes the result of an SQL statement (any statement) and the state of the operation. Non-query statements (e.g., `CREATE`, `UPDATE`, `DELETE`) set the “completed” state to 1, while `SELECT` statements to 0. Error conditions set this slot to a negative number. The `dbResult` class defines the following methods: `getStatement` : returns the SQL statement associated with the result set. `getDBConnection` : returns the `dbConnection` associated with the result set. `getRowsAffected` : returns the number of rows affected by the operation. `hasCompleted` : was the operation completed? `SELECT`’s, for instance, are not completed until their output rows are all fetched. `getException` : returns the status of the last SQL statement on a given connection as a list with two members, status code and status description. ### Class `dbResultSet` {#sec:dbResultSet} This virtual class extends `dbResult`, and it describes additional information from the result of a `SELECT` statement and the state of the operation. The `completed` state is set to 0 so long as there are pending rows to fetch. The `dbResultSet` class defines the following additional methods: `getRowCount` : returns the number of rows fetched so far. `getNullOk` : returns a logical vector with as many elements as there are fields in the result set, each element describing whether the corresponding field accepts `NULL` values. `getFields` : describes the `SELECT`ed fields. The description includes field names, RDBMS internal data types, internal length, internal precision and scale, null flag (i.e., column allows `NULL`’s), and corresponding S classes (which can be over-ridden with user-provided classes). The current MySQL and Oracle implementations define a `dbResultSet` as a named list with the following elements: `connection`: : the connection object associated with this result set; `statement`: : a string with the SQL statement being processed; `description`: : a field description `data.frame` with as many rows as there are fields in the `SELECT` output, and columns specifying the `name`, `type`, `length`, `precision`, `scale`, `Sclass` of the corresponding output field. `rowsAffected`: : the number of rows that were affected; `rowCount`: : the number of rows so far fetched; `completed`: : a logical value describing whether the operation has completed or not. `nullOk`: : a logical vector specifying whether the corresponding column may take NULL values. The methods above are implemented as accessor functions to this list in the obvious way. `setDataMappings` : defines a conversion between internal RDBMS data types and R/S classes. We expect the default mappings to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. (See Section [sec:mappings] for details.) `close` : closes the result set and frees resources both in R/S and the RDBMS. `fetch` : extracts the next `max.rec` records (-1 means all). ## Data Type Mappings {#sec:mappings} The data types supported by databases are slightly different than the data types in R and S, but the mapping between them is straightforward: Any of the many fixed and varying length character types are mapped to R/S `character`. Fixed-precision (non-IEEE) numbers are mapped into either doubles (`numeric`) or long (`integer`). Dates are mapped to character using the appropriate `TO_CHAR` function in the RDBMS (which should take care of any locale information). Some RDBMS support the type `CURRENCY` or `MONEY` which should be mapped to `numeric`. Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion as follows: 1. run the query (either with `dbExec` or `dbExecStatement`): > rs <- dbExecStatement(con, "select whatever-You-need") 2. extract the output field definitions > flds <- getFields(rs) 3. replace the class generator in the, say 3rd field, by the user own generator: > flds[3, "Sclass"] # default mapping [1] "character" by > flds[3, "Sclass"] <- "myOwnGeneratorFunction" 4. set the new data mapping prior to fetching > setDataMappings(resutlSet, flds) 5. fetch the rows and store in a `data.frame` > data <- fetch(resultSet) ## Open Issues {#sec:open-issues} We may need to provide some additional utilities, for instance to convert dates, to escape characters such as quotes and slashes in query strings, to strip excessive blanks from some character fields, etc. We need to decide whether we provide hooks so these conversions are done at the C level, or do all the post-processing in R or S. Another issue is what kind of data object is the output of an SQL query. Currently the MySQL and Oracle implementations return data as a `data.frame`; data frames have the slight inconvenience that they automatically re-label the fields according to R/S syntax, changing the actual RDBMS labels of the variables; the issue of non-numeric data being coerced into factors automatically “at the drop of a hat” (as someone in s-news wrote) is also annoying. The execution of SQL scripts is not fully described. The method that executes scripts could run individual statements without returning until it encounters a query (`SELECT`-like) statement. At that point it could return that one result set. The application is then responsible for fetching these rows, and then for invoking `dbNextResultSet` on the opened `dbConnection` object to repeat the `dbExec`/`fetch` loop until it encounters the next `dbResultSet`. And so on. Another (potentially very expensive) alternative would be to run all statements sequentially and return a list of `data.frame`s, each element of the list storing the result of each statement. Binary objects and large objects present some challenges both to R and S. It is becoming more common to store images, sounds, and other data types as binary objects in RDBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects – perhaps tentatively not in full generality. Large objects could be fetched by repeatedly invoking a specified R/S function that takes as argument chunks of a specified number of raw bytes. In the case of S4 (and Splus5.x) the RS-DBI implementation can write into an opened connection for which the user has defined a reader (but can we guarantee that we won’t overflow the connection?). In the case of R it is not clear what data type binary large objects (BLOB) should be mapped into. ## Limitations {#sec:limitations} These are some of the limitations of the current interface definition: - we only allow one SQL statement at a time, forcing users to split SQL scripts into individual statements; - transaction management is not fully described; - the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement /* SQL */ SELECT * from emp_table where emp_id = :sampleEmployee would take the vector `sampleEmployee` and iterate over each of its elements to get the result. Perhaps RS-DBI could at some point in the future implement this feature. # Other Approaches The high-level, front-end description of RS-DBI is the more critical aspect of the interface. Details on how to actually implement this interface may change over time. The approach described in this document based on one back-end driver per RDBMS is reasonable, but not the only approach – we simply felt that a simpler approach based on well-understood and self-contained tools (R, S, and C API’s) would be a better start. Nevertheless we want to briefly mention a few alternatives that we considered and tentatively decided against, but may quite possibly re-visit in the near future. ## Open Database Connectivity (ODBC) {#sec:odbc} The ODBC protocol was developed by Microsoft to allow connectivity among C/C++ applications and RDBMS. As you would expect, originally implementations of the ODBC were only available under Windows environments. There are various effort to create a Unix implementation (see [the Unix ODBC](http://www.unixodbc.org/) web-site and @odbc.lj). This approach looks promising because it allows us to write only one back-end, instead of one per RDBMS. Since most RDBMS already provide ODBC drivers, this could greatly simplify development. Unfortunately, the Unix implementation of ODBC was not mature enough at the time we looked at it, a situation we expect will change in the next year or so. At that point we will need to re-evaluate it to make sure that such an ODBC interface does not penalize the interface in terms of performance, ease of use, portability among the various Unix versions, etc. ## Java Database Connectivity (JDBC) {#sec:jdbc} Another protocol, the Java database connectivity, is very well-done and supported by just about every RDBMS. The issue with JDBC is that as of today neither S nor R (which are written in C) interfaces cleanly with Java. There are several efforts (some in a quite fairly advanced state) to allow S and R to invoke Java methods. Once this interface is widely available in Splus5x and R we will need to re-visit this issue again and study the performance, usability, etc., of JDBC as a common back-end to the RS-DBI. ## CORBA and a 3-tier Architecture {#sec:corba} Yet another approach is to move the interface to RDBMS out of R and S altogether into a separate system or server that would serve as a proxy between R/S and databases. The communication to this middle-layer proxy could be done through CORBA [@s-corba.98, @corba:siegel.96], Java’s RMI, or some other similar technology. Such a design could be very flexible, but the CORBA facilities both in R and S are not widely available yet, and we do not know whether this will be made available to Splus5 users from MathSoft. Also, my experience with this technology is rather limited. On the other hand, this 3-tier architecture seem to offer the most flexibility to cope with very large distributed databases, not necessarily relational. # Resources {#sec:resources} The latest documentation and software on the RS-DBI was available at www.omegahat.net (link dead now: `https://www.omegahat.net/contrib/RS-DBI/index.html`). The R community has developed interfaces to some databases: [RmSQL](https://cran.r-project.org/src/contrib/Archive/RmSQL/) is an interface to the [mSQL](https://www.Hughes.com.au) database written by Torsten Hothorn; [RPgSQL](https://sites.cns.utexas.edu/keittlab/software-0) is an interface to [PostgreSQL](https://www.postgreSQL.org) and was written by Timothy H. Keitt; [RODBC](https://www.stats.ox.ac.uk/pub/bdr/) is an interface to ODBC, and it was written by [Michael Lapsley](mailto:mlapsley@sthelier.sghms.ac.uk). (For more details on all these see @R.imp-exp.) The are R and S-Plus interfaces to [MySQL](https://dev.mysql.com/) that follow the propose RS-DBI API described here; also, there’s an S-Plus interface SOracle @RS-Oracle to [Oracle](https://www.oracle.com/) (we expect to have an R implementation soon.) The idea of a common interface to databases has been successfully implemented in Java’s Database Connectivity (JDBC) ([www.javasoft.com](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/)), in C through the Open Database Connectivity (ODBC) ([www.unixodbc.org](http://www.unixodbc.org/)), in Python’s Database Application Programming Interface ([www.python.org](https://www.python.org)), and in Perl’s Database Interface ([www.cpan.org](https://www.cpan.org)). # Acknowledgements The R/S database interface came about from suggestions, comments, and discussions with [John M. Chambers](mailto:jmc@research.bell-labs.com) and [Duncan Temple Lang](mailto:duncan@research.bell-labs.com) in the context of the Omega Project for Statistical Computing. [Doug Bates](mailto:bates@stat.wisc.edu) and [Saikat DebRoy](mailto:saikat@stat.wisc.edu) ported (and greatly improved) the first MySQL implementation to R. # The S Version 4 Definitions The following code is meant to serve as a detailed description of the R/S to database interface. We decided to use S4 (instead of R or S version 3) because its clean syntax help us to describe easily the classes and methods that form the RS-DBI, and also to convey the inter-class relationships. ```R ## Define all the classes and methods to be used by an ## implementation of the RS-DataBase Interface. Mostly, ## these classes are virtual and each driver should extend ## them to provide the actual implementation. ## Class: dbManager ## This class identifies the DataBase Management System ## (Oracle, MySQL, Informix, PostgreSQL, etc.) setClass("dbManager", VIRTUAL) setGeneric("load", def = function(dbMgr,...) standardGeneric("load") ) setGeneric("unload", def = function(dbMgr,...) standardGeneric("unload") ) setGeneric("getVersion", def = function(dbMgr,...) standardGeneric("getVersion") ) ## Class: dbConnections ## This class captures a connection to a database instance. setClass("dbConnection", VIRTUAL) setGeneric("dbConnection", def = function(dbMgr, ...) standardGeneric("dbConnection") ) setGeneric("dbConnect", def = function(dbMgr, ...) standardGeneric("dbConnect") ) setGeneric("dbExecStatement", def = function(con, statement, ...) standardGeneric("dbExecStatement") ) setGeneric("dbExec", def = function(con, statement, ...) standardGeneric("dbExec") ) setGeneric("getResultSet", def = function(con, ..) standardGeneric("getResultSet") ) setGeneric("commit", def = function(con, ...) standardGeneric("commit") ) setGeneric("rollback", def = function(con, ...) standardGeneric("rollback") ) setGeneric("callProc", def = function(con, ...) standardGeneric("callProc") ) setMethod("close", signature = list(con="dbConnection", type="missing"), def = function(con, type) NULL ) ## Class: dbResult ## This is a base class for arbitrary results from the RDBMS ## (INSERT, UPDATE, DELETE). SELECTs (and SELECT-like) ## statements produce "dbResultSet" objects, which extend ## dbResult. setClass("dbResult", VIRTUAL) setMethod("close", signature = list(con="dbResult", type="missing"), def = function(con, type) NULL ) ## Class: dbResultSet ## Note that we define a resultSet as the result of a ## SELECT SQL statement. setClass("dbResultSet", "dbResult") setGeneric("fetch", def = function(resultSet,n,...) standardGeneric("fetch") ) setGeneric("hasCompleted", def = function(object, ...) standardGeneric("hasCompleted") ) setGeneric("getException", def = function(object, ...) standardGeneric("getException") ) setGeneric("getDBconnection", def = function(object, ...) standardGeneric("getDBconnection") ) setGeneric("setDataMappings", def = function(resultSet, ...) standardGeneric("setDataMappings") ) setGeneric("getFields", def = function(object, table, dbname, ...) standardGeneric("getFields") ) setGeneric("getStatement", def = function(object, ...) standardGeneric("getStatement") ) setGeneric("getRowsAffected", def = function(object, ...) standardGeneric("getRowsAffected") ) setGeneric("getRowCount", def = function(object, ...) standardGeneric("getRowCount") ) setGeneric("getNullOk", def = function(object, ...) standardGeneric("getNullOk") ) ## Meta-data: setGeneric("getInfo", def = function(object, ...) standardGeneric("getInfo") ) setGeneric("describe", def = function(object, verbose=F, ...) standardGeneric("describe") ) setGeneric("getCurrentDatabase", def = function(object, ...) standardGeneric("getCurrentDatabase") ) setGeneric("getDatabases", def = function(object, ...) standardGeneric("getDatabases") ) setGeneric("getTables", def = function(object, dbname, ...) standardGeneric("getTables") ) setGeneric("getTableFields", def = function(object, table, dbname, ...) standardGeneric("getTableFields") ) setGeneric("getTableIndices", def = function(object, table, dbname, ...) standardGeneric("getTableIndices") ) ``` [^2]: A virtual class allows us to group classes that share some common functionality, e.g., the virtual class “`dbConnection`” groups all the connection implementations by Informix, Ingres, DB/2, Oracle, etc. Although the details will vary from one RDBMS to another, the defining characteristic of these objects is what a virtual class captures. R and S version 3 do not explicitly define virtual classes, but they can easily implement the idea through inheritance. [^3]: The term “database” is sometimes (confusingly) used both to denote the RDBMS, such as Oracle, MySQL, and also to denote a particular database instance under a RDBMS, such as “opto” or “sales” databases under the same RDBMS. DBI/inst/doc/backend.Rmd0000644000176200001440000002414014064774575014451 0ustar liggesusers --- title: "Implementing a new backend" author: "Hadley Wickham, Kirill Müller" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Implementing a new backend} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- ```{r, echo = FALSE} library(DBI) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ``` The goal of this document is to help you implement a new backend for DBI. If you are writing a package that connects a database to R, I highly recommend that you make it DBI compatible because it makes your life easier by spelling out exactly what you need to do. The consistent interface provided by DBI makes it easier for you to implement the package (because you have fewer arbitrary choices to make), and easier for your users (because it follows a familiar pattern). In addition, the `DBItest` package provides test cases which you can easily incorporate in your package. I'll illustrate the process using a fictional database called Kazam. ## Getting started Start by creating a package. It's up to you what to call the package, but following the existing pattern of `RSQLite`, `RMySQL`, `RPostgres` and `ROracle` will make it easier for people to find it. For this example, I'll call my package `RKazam`. A ready-to-use template package is available at https://github.com/r-dbi/RKazam/. You can start by creating a new GitHub repository from this template, or by copying the package code. Rename "Kazam" to your desired name everywhere. The template package already contains dummy implementations for all classes and methods. If you chose to create the package manually, make sure to include in your `DESCRIPTION`: ```yaml Imports: DBI (>= 0.3.0), methods Suggests: DBItest, testthat ``` Importing `DBI` is fine, because your users are not supposed to *attach* your package anyway; the preferred method is to attach `DBI` and use explicit qualification via `::` to access the driver in your package (which needs to be done only once). ## Testing Why testing at this early stage? Because testing should be an integral part of the software development cycle. Test right from the start, add automated tests as you go, finish faster (because tests are automated) while maintaining superb code quality (because tests also check corner cases that you might not be aware of). Don't worry: if some test cases are difficult or impossible to satisfy, or take too long to run, you can just turn them off. Take the time now to head over to the `DBItest` vignette at `vignette("test", package = "DBItest")`. You will find a vast amount of ready-to-use test cases that will help you in the process of implementing your new DBI backend. Add custom tests that are not covered by `DBItest` at your discretion, or enhance `DBItest` and file a pull request if the test is generic enough to be useful for many DBI backends. ## Driver Start by making a driver class which inherits from `DBIDriver`. This class doesn't need to do anything, it's just used to dispatch other generics to the right method. Users don't need to know about this, so you can remove it from the default help listing with `@keywords internal`: ```{r} #' Driver for Kazam database. #' #' @keywords internal #' @export #' @import DBI #' @import methods setClass("KazamDriver", contains = "DBIDriver") ``` The driver class was more important in older versions of DBI, so you should also provide a dummy `dbUnloadDriver()` method. ```{r} #' @export #' @rdname Kazam-class setMethod("dbUnloadDriver", "KazamDriver", function(drv, ...) { TRUE }) ``` If your package needs global setup or tear down, do this in the `.onLoad()` and `.onUnload()` functions. You might also want to add a show method so the object prints nicely: ```{r} setMethod("show", "KazamDriver", function(object) { cat("\n") }) ``` Next create `Kazam()` which instantiates this class. ```{r} #' @export Kazam <- function() { new("KazamDriver") } Kazam() ``` ## Connection Next create a connection class that inherits from `DBIConnection`. This should store all the information needed to connect to the database. If you're talking to a C api, this will include a slot that holds an external pointer. ```{r} #' Kazam connection class. #' #' @export #' @keywords internal setClass("KazamConnection", contains = "DBIConnection", slots = list( host = "character", username = "character", # and so on ptr = "externalptr" ) ) ``` Now you have some of the boilerplate out of the way, you can start work on the connection. The most important method here is `dbConnect()` which allows you to connect to a specified instance of the database. Note the use of `@rdname Kazam`. This ensures that `Kazam()` and the connect method are documented together. ```{r} #' @param drv An object created by \code{Kazam()} #' @rdname Kazam #' @export #' @examples #' \dontrun{ #' db <- dbConnect(RKazam::Kazam()) #' dbWriteTable(db, "mtcars", mtcars) #' dbGetQuery(db, "SELECT * FROM mtcars WHERE cyl == 4") #' } setMethod("dbConnect", "KazamDriver", function(drv, ...) { # ... new("KazamConnection", host = host, ...) }) ``` * Replace `...` with the arguments needed to connect to your database. You'll always need to include `...` in the arguments, even if you don't use it, for compatibility with the generic. * This is likely to be where people first come for help, so the examples should show how to connect to the database, and how to query it. (Obviously these examples won't work yet.) Ideally, include examples that can be run right away (perhaps relying on a publicly hosted database), but failing that surround in `\dontrun{}` so people can at least see the code. Next, implement `show()` and `dbDisconnect()` methods. ## Results Finally, you're ready to implement the meat of the system: fetching results of a query into a data frame. First define a results class: ```{r} #' Kazam results class. #' #' @keywords internal #' @export setClass("KazamResult", contains = "DBIResult", slots = list(ptr = "externalptr") ) ``` Then write a `dbSendQuery()` method. This takes a connection and SQL string as arguments, and returns a result object. Again `...` is needed for compatibility with the generic, but you can add other arguments if you need them. ```{r} #' Send a query to Kazam. #' #' @export #' @examples #' # This is another good place to put examples setMethod("dbSendQuery", "KazamConnection", function(conn, statement, ...) { # some code new("KazamResult", ...) }) ``` Next, implement `dbClearResult()`, which should close the result set and free all resources associated with it: ```{r} #' @export setMethod("dbClearResult", "KazamResult", function(res, ...) { # free resources TRUE }) ``` The hardest part of every DBI package is writing the `dbFetch()` method. This needs to take a result set and (optionally) number of records to return, and create a dataframe. Mapping R's data types to those of your database may require a custom implementation of the `dbDataType()` method for your connection class: ```{r} #' Retrieve records from Kazam query #' @export setMethod("dbFetch", "KazamResult", function(res, n = -1, ...) { ... }) # (optionally) #' Find the database data type associated with an R object #' @export setMethod("dbDataType", "KazamConnection", function(dbObj, obj, ...) { ... }) ``` Next, implement `dbHasCompleted()` which should return a `logical` indicating if there are any rows remaining to be fetched. ```{r} #' @export setMethod("dbHasCompleted", "KazamResult", function(res, ...) { }) ``` With these four methods in place, you can now use the default `dbGetQuery()` to send a query to the database, retrieve results if available and then clean up. Spend some time now making sure this works with an existing database, or relax and let the `DBItest` package do the work for you. ## SQL methods You're now on the home stretch, and can make your wrapper substantially more useful by implementing methods that wrap around variations in SQL across databases: * `dbQuoteString()` and `dbQuoteIdentifer()` are used to safely quote strings and identifiers to avoid SQL injection attacks. Note that the former must be vectorized, but not the latter. * `dbWriteTable()` creates a database table given an R dataframe. I'd recommend using the functions prefixed with `sql` in this package to generate the SQL. These functions are still a work in progress so please let me know if you have problems. * `dbReadTable()`: a simple wrapper around `SELECT * FROM table`. Use `dbQuoteIdentifer()` to safely quote the table name and prevent mismatches between the names allowed by R and the database. * `dbListTables()` and `dbExistsTable()` let you determine what tables are available. If not provided by your database's API, you may need to generate sql that inspects the system tables. * `dbListFields()` shows which fields are available in a given table. * `dbRemoveTable()` wraps around `DROP TABLE`. Start with `SQL::sqlTableDrop()`. * `dbBegin()`, `dbCommit()` and `dbRollback()`: implement these three functions to provide basic transaction support. This functionality is currently not tested in the `DBItest` package. ## Metadata methods There are a lot of extra metadata methods for result sets (and one for the connection) that you might want to implement. They are described in the following. * `dbIsValid()` returns if a connection or a result set is open (`TRUE`) or closed (`FALSE`). All further methods in this section are valid for result sets only. * `dbGetStatement()` returns the issued query as a character value. * `dbColumnInfo()` lists the names and types of the result set's columns. * `dbGetRowCount()` and `dbGetRowsAffected()` returns the number of rows returned or altered in a `SELECT` or `INSERT`/`UPDATE` query, respectively. * `dbBind()` allows using parametrised queries. Take a look at `sqlInterpolate()` and `sqlParseVariables()` if your SQL engine doesn't offer native parametrised queries. ## Full DBI compliance By now, your package should implement all methods defined in the DBI specification. If you want to walk the extra mile, offer a read-only mode that allows your users to be sure that their valuable data doesn't get destroyed inadvertently. DBI/inst/doc/DBI-advanced.html0000644000176200001440000014703314157714552015444 0ustar liggesusers Advanced DBI Usage

Advanced DBI Usage

James Wondrasek, Kirill Müller

17/03/2020

Who this tutorial is for

This tutorial is for you if you need to use a richer set of SQL features such as data manipulation queries, parameterized queries and queries performed using SQL’s transaction features. See vignette("DBI", package = "DBI") for a more basic tutorial covering connecting to DBMS and executing simple queries.

How to run more complex queries using DBI

dbGetQuery() works by calling a number of functions behind the scenes. If you need more control you can manually build your own query, retrieve results at your selected rate, and release the resources involved by calling the same functions.

These functions are:

  • dbSendQuery() sends the SQL query to the DBMS and returns a result object. The query is limited to SELECT statements. If you want to send other statements, such as INSERT, UPDATE, DELETE, etc, use dbSendStatement().
  • dbFetch() is called with the result object returned by dbSendQuery(). It also accepts an argument specifying the number of rows to be returned, e.g. n = 200. If you want to fetch all the rows, use n = -1.
  • dbClearResult() is called when you have finished retrieving data. It releases the resources associated with the result object.
library(DBI)

con <- dbConnect(
  RMariaDB::MariaDB(),
  host = "relational.fit.cvut.cz",
  port = 3306,
  username = "guest",
  password = "relational",
  dbname = "sakila"
)

res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = 'G'")
df <- dbFetch(res, n = 3)
dbClearResult(res)

head(df, 3)
##   film_id            title
## 1       2   ACE GOLDFINGER
## 2       4 AFFAIR PREJUDICE
## 3       5      AFRICAN EGG
##                                                                                                             description
## 1                  A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 2                          A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank
## 3 A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               3        4.99
## 2         2006           1                   NA               5        2.99
## 3         2006           1                   NA               6        2.99
##   length replacement_cost rating               special_features
## 1     48            12.99      G        Trailers,Deleted Scenes
## 2    117            26.99      G Commentaries,Behind the Scenes
## 3    130            22.99      G                 Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42

How to read part of a table from a database

If your dataset is large you may want to fetch a limited number of rows at a time. As demonstrated below, this can be accomplished by using a while loop where the function dbHasCompleted() is used to check for ongoing rows, and dbFetch() is used with the n = X argument, specifying how many rows to return on each iteration. Again, we call dbClearResult() at the end to release resources.

res <- dbSendQuery(con, "SELECT * FROM film")
while (!dbHasCompleted(res)) {
  chunk <- dbFetch(res, n = 300)
  print(nrow(chunk))
}
## [1] 300
## [1] 300
## [1] 300
## [1] 100
dbClearResult(res)

How to use parameters (safely) in SQL queries

dbSendQuery() can be used with parameterized SQL queries. DBI supports two ways to avoid SQL injection attacks from user-supplied parameters: quoting and parameterized queries.

Quoting

Quoting of parameter values is performed using the function dbQuoteLiteral(), which supports many R data types, including date and time.1

In cases where users may be supplying table or column names to use in the query for data retrieval, those names or identifiers must also be escaped. As there may be DBMS-specific rules for escaping these identifiers, DBI provides the function dbQuoteIdentifier() to generate a safe string representation.

safe_id <- dbQuoteIdentifier(con, "rating")
safe_param <- dbQuoteLiteral(con, "G")

query <- paste0("SELECT title, ", safe_id, " FROM film WHERE ", safe_id, " = ", safe_param )
query
## [1] "SELECT title, `rating` FROM film WHERE `rating` = 'G'"
res <- dbSendQuery(con, query)
dbFetch(res)
##              title rating
## 1   ACE GOLDFINGER      G
## 2 AFFAIR PREJUDICE      G
## 3      AFRICAN EGG      G
## Showing 3 out of 178 rows.
dbClearResult(res)

The same result can be had by using glue::glue_sql(). It performs the same safe quoting on any variable or R statement appearing between braces within the query string.

id <- "rating"
param <- "G"
query <- glue::glue_sql("SELECT title, {`id`} FROM film WHERE {`id`} = {param}", .con = con)

df <- dbGetQuery(con, query)
head(df, 3)
##              title rating
## 1   ACE GOLDFINGER      G
## 2 AFFAIR PREJUDICE      G
## 3      AFRICAN EGG      G

Parameterized queries

Rather than performing the parameter substitution ourselves, we can push it to the DBMS by including placeholders in the query. Different DBMS use different placeholder schemes, DBI passes through the SQL expression unchanged.

MariaDB uses a question mark (?) as placeholder and expects an unnamed list of parameter values. Other DBMS may use named parameters. We recommend consulting the documentation for the DBMS you are using. As an example, a web search for “mariadb parameterized queries” leads to the documentation for the PREPARE statement which mentions:

Within the statement, “?” characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it.

Currently there is no list of which placeholder scheme a particular DBMS supports.

Placeholders only work for literal values. Other parts of the query, e.g. table or column identifiers, still need to be quoted with dbQuoteIdentifier().

For a single set of parameters, the params argument to dbSendQuery() or dbGetQuery() can be used. It takes a list and its members are substituted in order for the placeholders within the query.

params <- list("G")
safe_id <- dbQuoteIdentifier(con, "rating")

query <- paste0("SELECT * FROM film WHERE ", safe_id, " = ?")
query
## [1] "SELECT * FROM film WHERE `rating` = ?"
res <- dbSendQuery(con, query, params = params)
dbFetch(res, n = 3)
##   film_id            title
## 1       2   ACE GOLDFINGER
## 2       4 AFFAIR PREJUDICE
## 3       5      AFRICAN EGG
##                                                                                                             description
## 1                  A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 2                          A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank
## 3 A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               3        4.99
## 2         2006           1                   NA               5        2.99
## 3         2006           1                   NA               6        2.99
##   length replacement_cost rating               special_features
## 1     48            12.99      G        Trailers,Deleted Scenes
## 2    117            26.99      G Commentaries,Behind the Scenes
## 3    130            22.99      G                 Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42
dbClearResult(res)

Below is an example query using multiple placeholders with the MariaDB driver. The placeholders are supplied as a list of values ordered to match the position of the placeholders in the query.

q_params <- list("G", 90)
query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?"

res <- dbSendQuery(con, query, params = q_params)
dbFetch(res, n = 3)
##              title rating length
## 1 AFFAIR PREJUDICE      G    117
## 2      AFRICAN EGG      G    130
## 3  ALAMO VIDEOTAPE      G    126
dbClearResult(res)

When you wish to perform the same query with different sets of parameter values, dbBind() is used. There are two ways to use dbBind(). Firstly, it can be used multiple times with same query.

res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?")
dbBind(res, list("G"))
dbFetch(res, n = 3)
##   film_id            title
## 1       2   ACE GOLDFINGER
## 2       4 AFFAIR PREJUDICE
## 3       5      AFRICAN EGG
##                                                                                                             description
## 1                  A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 2                          A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank
## 3 A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               3        4.99
## 2         2006           1                   NA               5        2.99
## 3         2006           1                   NA               6        2.99
##   length replacement_cost rating               special_features
## 1     48            12.99      G        Trailers,Deleted Scenes
## 2    117            26.99      G Commentaries,Behind the Scenes
## 3    130            22.99      G                 Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42
dbBind(res, list("PG"))
dbFetch(res, n = 3)
##   film_id            title
## 1       1 ACADEMY DINOSAUR
## 2       6     AGENT TRUMAN
## 3      12   ALASKA PHANTOM
##                                                                                        description
## 1 A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies
## 2        A Intrepid Panorama of a Robot And a Boy who must Escape a Sumo Wrestler in Ancient China
## 3               A Fanciful Saga of a Hunter And a Pastry Chef who must Vanquish a Boy in Australia
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               6        0.99
## 2         2006           1                   NA               3        2.99
## 3         2006           1                   NA               6        0.99
##   length replacement_cost rating                 special_features
## 1     86            20.99     PG Deleted Scenes,Behind the Scenes
## 2    169            17.99     PG                   Deleted Scenes
## 3    136            22.99     PG      Commentaries,Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42
dbClearResult(res)

Secondly, dbBind() can be used to execute the same statement with multiple values at once.

res <- dbSendQuery(con, "SELECT * FROM film WHERE rating = ?")
dbBind(res, list(c("G", "PG")))
dbFetch(res, n = 3)
##   film_id            title
## 1       2   ACE GOLDFINGER
## 2       4 AFFAIR PREJUDICE
## 3       5      AFRICAN EGG
##                                                                                                             description
## 1                  A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 2                          A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank
## 3 A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               3        4.99
## 2         2006           1                   NA               5        2.99
## 3         2006           1                   NA               6        2.99
##   length replacement_cost rating               special_features
## 1     48            12.99      G        Trailers,Deleted Scenes
## 2    117            26.99      G Commentaries,Behind the Scenes
## 3    130            22.99      G                 Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42
dbClearResult(res)

Use a list of vectors if your query has multiple parameters:

q_params <- list(c("G", "PG"), c(90, 120))
query <- "SELECT title, rating, length FROM film WHERE rating = ? AND length >= ?"

res <- dbSendQuery(con, query, params = q_params)
dbFetch(res, n = 3)
##              title rating length
## 1 AFFAIR PREJUDICE      G    117
## 2      AFRICAN EGG      G    130
## 3  ALAMO VIDEOTAPE      G    126
dbClearResult(res)

Always disconnect from the database when done.

dbDisconnect(con)

SQL data manipulation - UPDATE, DELETE and friends

For SQL queries that affect the underlying database, such as UPDATE, DELETE, INSERT INTO, and DROP TABLE, DBI provides two functions. dbExecute() passes the SQL statement to the DBMS for execution and returns the number of rows affected. dbSendStatement() performs in the same manner, but returns a result object. Call dbGetRowsAffected() with the result object to get the count of the affected rows. You then need to call dbClearResult() with the result object afterwards to release resources.

In actuality, dbExecute() is a convenience function that calls dbSendStatement(), dbGetRowsAffected(), and dbClearResult(). You can use these functions if you need more control over the query process.

The subsequent examples use an in-memory SQL database provided by RSQLite::SQLite(), because the remote database used in above examples does not allow writing.

library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cars", head(cars, 3))

dbExecute(
  con,
  "INSERT INTO cars (speed, dist) VALUES (1, 1), (2, 2), (3, 3)"
)
## [1] 3
rs <- dbSendStatement(
  con,
  "INSERT INTO cars (speed, dist) VALUES (4, 4), (5, 5), (6, 6)"
)
dbGetRowsAffected(rs)
## [1] 3
dbClearResult(rs)

dbReadTable(con, "cars")
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## Showing 3 out of 9 rows.
dbDisconnect(con)

SQL transactions with DBI

DBI allows you to group multiple queries into a single atomic transaction. Transactions are initiated with dbBegin() and either made persistent with dbCommit() or undone with dbRollback(). The example below updates two tables and ensures that either both tables are updated, or no changes are persisted to the database and an error is thrown.

con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "cash", data.frame(amount = 100))
dbWriteTable(con, "account", data.frame(amount = 2000))

withdraw <- function(amount) {
  # All operations must be carried out as logical unit:
  dbExecute(con, "UPDATE cash SET amount = amount + ?", list(amount))
  dbExecute(con, "UPDATE account SET amount = amount - ?", list(amount))
}

withdraw_transacted <- function(amount) {
  # Ensure atomicity
  dbBegin(con)

  # Perform operation
  withdraw(amount)

  # Persist results
  dbCommit(con)
}

withdraw_transacted(300)

After withdrawing 300 credits, the cash is increased and the account is decreased by this amount. The transaction ensures that either both operations succeed, or no change occurs.

dbReadTable(con, "cash")
##   amount
## 1    400
dbReadTable(con, "account")
##   amount
## 1   1700

We can roll back changes manually if necessary. Do not forget to call dbRollback() in case of error, otherwise the transaction remains open indefinitely.

withdraw_if_funds <- function(amount) {
  dbBegin(con)
  withdraw(amount)
  # Rolling back after detecting negative value on account:
  if (dbReadTable(con, "account")$amount >= 0) {
    dbCommit(con)
    TRUE
  } else {
    message("Insufficient funds")
    dbRollback(con)
    FALSE
  }
}

withdraw_if_funds(5000)
## Insufficient funds
## [1] FALSE
dbReadTable(con, "cash")
##   amount
## 1    400
dbReadTable(con, "account")
##   amount
## 1   1700

dbWithTransaction() simplifies using transactions. Pass it a connection and the code you want to run as a transaction. It will execute the code and call dbCommit() on success and call dbRollback() if an error is thrown.

withdraw_safely <- function(amount) {
  dbWithTransaction(con, {
    withdraw(amount)
    if (dbReadTable(con, "account")$amount < 0) {
      stop("Error: insufficient funds", call. = FALSE)
    }
  })
}

withdraw_safely(5000)
## Error: Error: insufficient funds
dbReadTable(con, "cash")
##   amount
## 1    400
dbReadTable(con, "account")
##   amount
## 1   1700

As usual, do not forget to disconnect from the database when done.

dbDisconnect(con)

Conclusion

That concludes the major features of DBI. For more details on the library functions covered in this tutorial and the vignette("DBI", package = "DBI") introductory tutorial see the DBI specification at vignette("spec", package = "DBI"). If you are after a data manipulation library that works at a higher level of abstraction, check out dplyr. It is a grammar of data manipulation that can work with local dataframes and remote databases and uses DBI under the hood.


  1. An older method, dbQuoteString(), was used to quote string values only. The dbQuoteLiteral() method forwards to dbQuoteString() for character vectors. Users do not need to distinguish between these two cases.↩︎

DBI/inst/doc/DBI.html0000644000176200001440000007143514157714556013707 0ustar liggesusers Introduction to DBI

Introduction to DBI

James Wondrasek, Katharina Brunner, Kirill Müller

27 February 2020

Who this tutorial is for

This tutorial is for you if you want to access or manipulate data in a database that may be on your machine or on a different computer on the internet, and you have found libraries that use a higher level of abstraction, such as dbplyr, are not suitable for your purpose. Depending on what you want to achieve, you may find it useful to have an understanding of SQL before using DBI.

The DBI (DataBase Interface) package provides a simple, consistent interface between R and database management systems (DBMS). Each supported DBMS is supported by its own R package that implements the DBI specification in vignette("spec", package = "DBI").

DBI currently supports about 30 DBMS, including:

For a more complete list of supported DBMS visit https://github.com/r-dbi/backends. You may need to install the package specific to your DBMS.

The functionality currently supported for each of these DBMS’s includes:

  • manage a connection to a database
  • list the tables in a database
  • list the column names in a table
  • read a table into a data frame

For more advanced features, such as parameterized queries, transactions, and more see vignette("DBI-advanced", package = "DBI").

How to connect to a database using DBI

The following code establishes a connection to the Sakila database hosted by the Relational Dataset Repository at https://relational.fit.cvut.cz/dataset/Sakila, lists all tables on the database, and closes the connection. The database represents a fictional movie rental business and includes tables describing films, actors, customers, stores, etc.:

library(DBI)

con <- dbConnect(
  RMariaDB::MariaDB(),
  host = "relational.fit.cvut.cz",
  port = 3306,
  username = "guest",
  password = "relational",
  dbname = "sakila"
)

dbListTables(con)
##  [1] "actor"         "address"       "category"      "city"         
##  [5] "country"       "customer"      "film"          "film_actor"   
##  [9] "film_category" "film_text"     "inventory"     "language"     
## [13] "payment"       "rental"        "staff"         "store"
dbDisconnect(con)

Connections to databases are created using the dbConnect() function. The first argument to the function is the driver for the DBMS you are connecting to. In the example above we are connecting to a MariaDB instance, so we use the RMariaDB::MariaDB() driver. The other arguments depend on the authentication required by the DBMS. In the example host, port, username, password, and dbname are required. See the documentation for the DBMS driver package that you are using for specifics.

The function dbListTables() takes a database connection as its only argument and returns a character vector with all table and view names in the database.

After completing a session with a DBMS, always release the connection with a call to dbDisconnect().

Secure password storage

The above example contains the password in the code, which should be avoided for databases with secured access. One way to use the credentials securely is to store it in your system’s credential store and then query it with the keyring package. The code to connect to the database could then look like this:

con <- dbConnect(
  RMariaDB::MariaDB(),
  host = "relational.fit.cvut.cz",
  port = 3306,
  username = "guest",
  password = keyring::key_get("relational.fit.cvut.cz", "guest"),
  dbname = "sakila"
)

How to retrieve column names for a table

We can list the column names for a table with the function dbListFields(). It takes as arguments a database connection and a table name and returns a character vector of the column names in order.

con <- dbConnect(RMariaDB::MariaDB(), username = "guest", password = "relational", host = "relational.fit.cvut.cz", port = 3306, dbname = "sakila")
dbListFields(con, "film")
##  [1] "film_id"              "title"                "description"         
##  [4] "release_year"         "language_id"          "original_language_id"
##  [7] "rental_duration"      "rental_rate"          "length"              
## [10] "replacement_cost"     "rating"               "special_features"    
## [13] "last_update"

Read a table into a data frame

The function dbReadTable() reads an entire table and returns it as a data frame. It is equivalent to the SQL query SELECT * FROM <name>. The columns of the returned data frame share the same names as the columns in the table. DBI and the database backends do their best to coerce data to equivalent R data types.

df <- dbReadTable(con, "film")
head(df, 3)
##   film_id            title
## 1       1 ACADEMY DINOSAUR
## 2       2   ACE GOLDFINGER
## 3       3 ADAPTATION HOLES
##                                                                                            description
## 1     A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies
## 2 A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 3     A Astounding Reflection of a Lumberjack And a Car who must Sink a Lumberjack in A Baloon Factory
##   release_year language_id original_language_id rental_duration rental_rate
## 1         2006           1                   NA               6        0.99
## 2         2006           1                   NA               3        4.99
## 3         2006           1                   NA               7        2.99
##   length replacement_cost rating                 special_features
## 1     86            20.99     PG Deleted Scenes,Behind the Scenes
## 2     48            12.99      G          Trailers,Deleted Scenes
## 3     50            18.99  NC-17          Trailers,Deleted Scenes
##           last_update
## 1 2006-02-15 04:03:42
## 2 2006-02-15 04:03:42
## 3 2006-02-15 04:03:42

Read only selected rows and columns into a data frame

To read a subset of the data in a table into a data frame, DBI provides functions to run custom SQL queries and manage the results. For small datasets where you do not need to manage the number of results being returned, the function dbGetQuery() takes a SQL SELECT query to execute and returns a data frame. Below is a basic query that specifies the columns we require (film_id, title and description) and which rows (records) we are interested in. Here we retrieve films released in the year 2006.

df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006")
head(df, 3)
##   film_id            title
## 1       1 ACADEMY DINOSAUR
## 2       2   ACE GOLDFINGER
## 3       3 ADAPTATION HOLES
##                                                                                            description
## 1     A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies
## 2 A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 3     A Astounding Reflection of a Lumberjack And a Car who must Sink a Lumberjack in A Baloon Factory

We could also retrieve movies released in 2006 that are rated “G”. Note that character strings must be quoted. As the query itself is contained within double quotes, we use single quotes around the rating. See dbQuoteLiteral() for programmatically converting arbitrary R values to SQL. This is covered in more detail in vignette("DBI-advanced", package = "DBI").

df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006 AND rating = 'G'")
head(df,3)
##   film_id            title
## 1       2   ACE GOLDFINGER
## 2       4 AFFAIR PREJUDICE
## 3       5      AFRICAN EGG
##                                                                                                             description
## 1                  A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China
## 2                          A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank
## 3 A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico

The equivalent operation using dplyr reconstructs the SQL query using three functions to specify the table (tbl()), the subset of the rows (filter()), and the columns we require (select()). Note that dplyr takes care of the quoting.

library(dplyr)

lazy_df <-
  tbl(con, "film") %>%
  filter(release_year == 2006 & rating == "G") %>%
  select(film_id, title, description)
head(lazy_df, 3)
## # Source:   lazy query [?? x 3]
## # Database: mysql [guest@relational.fit.cvut.cz:NA/sakila]
##   film_id title            description                                          
##     <int> <chr>            <chr>                                                
## 1       2 ACE GOLDFINGER   A Astounding Epistle of a Database Administrator And…
## 2       4 AFFAIR PREJUDICE A Fanciful Documentary of a Frisbee And a Lumberjack…
## 3       5 AFRICAN EGG      A Fast-Paced Documentary of a Pastry Chef And a Dent…

If you want to perform other data manipulation queries such as UPDATEs and DELETEs, see dbSendStatement() in vignette("DBI-advanced", package = "DBI").

How to end a DBMS session

When finished accessing the DBMS, always close the connection using dbDisconnect().

dbDisconnect(con)

Conclusion

This tutorial has given you the basic techniques for accessing data in any supported DBMS. If you need to work with databases that will not fit in memory, or want to run more complex queries, including parameterized queries, please see vignette("DBI-advanced", package = "DBI").

Further Reading

DBI/inst/doc/backend.R0000644000176200001440000000550214157714556014125 0ustar liggesusers## ---- echo = FALSE------------------------------------------------------------ library(DBI) knitr::opts_chunk$set(collapse = TRUE, comment = "#>") ## ----------------------------------------------------------------------------- #' Driver for Kazam database. #' #' @keywords internal #' @export #' @import DBI #' @import methods setClass("KazamDriver", contains = "DBIDriver") ## ----------------------------------------------------------------------------- #' @export #' @rdname Kazam-class setMethod("dbUnloadDriver", "KazamDriver", function(drv, ...) { TRUE }) ## ----------------------------------------------------------------------------- setMethod("show", "KazamDriver", function(object) { cat("\n") }) ## ----------------------------------------------------------------------------- #' @export Kazam <- function() { new("KazamDriver") } Kazam() ## ----------------------------------------------------------------------------- #' Kazam connection class. #' #' @export #' @keywords internal setClass("KazamConnection", contains = "DBIConnection", slots = list( host = "character", username = "character", # and so on ptr = "externalptr" ) ) ## ----------------------------------------------------------------------------- #' @param drv An object created by \code{Kazam()} #' @rdname Kazam #' @export #' @examples #' \dontrun{ #' db <- dbConnect(RKazam::Kazam()) #' dbWriteTable(db, "mtcars", mtcars) #' dbGetQuery(db, "SELECT * FROM mtcars WHERE cyl == 4") #' } setMethod("dbConnect", "KazamDriver", function(drv, ...) { # ... new("KazamConnection", host = host, ...) }) ## ----------------------------------------------------------------------------- #' Kazam results class. #' #' @keywords internal #' @export setClass("KazamResult", contains = "DBIResult", slots = list(ptr = "externalptr") ) ## ----------------------------------------------------------------------------- #' Send a query to Kazam. #' #' @export #' @examples #' # This is another good place to put examples setMethod("dbSendQuery", "KazamConnection", function(conn, statement, ...) { # some code new("KazamResult", ...) }) ## ----------------------------------------------------------------------------- #' @export setMethod("dbClearResult", "KazamResult", function(res, ...) { # free resources TRUE }) ## ----------------------------------------------------------------------------- #' Retrieve records from Kazam query #' @export setMethod("dbFetch", "KazamResult", function(res, n = -1, ...) { ... }) # (optionally) #' Find the database data type associated with an R object #' @export setMethod("dbDataType", "KazamConnection", function(dbObj, obj, ...) { ... }) ## ----------------------------------------------------------------------------- #' @export setMethod("dbHasCompleted", "KazamResult", function(res, ...) { }) DBI/inst/doc/spec.R0000644000176200001440000001026214157714557013470 0ustar liggesusers## ----echo = FALSE------------------------------------------------------------- library(magrittr) library(xml2) knitr::opts_chunk$set(echo = FALSE) r <- rprojroot::is_r_package$make_fix_file() ## ----error=TRUE--------------------------------------------------------------- rd_db <- tools::Rd_db(dir = r()) Links <- tools::findHTMLlinks() html_topic <- function(name) { rd <- rd_db[[paste0(name, ".Rd")]] conn <- textConnection(NULL, "w") on.exit(close(conn)) #tools::Rd2HTML(rd, conn, Links = Links) tools::Rd2HTML(rd, conn) textConnectionValue(conn) } xml_topic <- function(name, patcher) { html <- html_topic(name) x <- read_html(paste(html, collapse = "\n")) # No idea why this is necessary when embedding HTML in Markdown codes <- x %>% xml_find_all("//code[contains(., '$')]") xml_text(codes) <- gsub("[$]", "\\\\$", xml_text(codes)) xx <- x %>% xml_find_first("/html/body") xx %>% xml_find_first("//table") %>% xml_remove() xx %>% xml_find_all("//pre") %>% xml_set_attr("class", "r") patcher(xx) } out_topic <- function(name, patcher = identity) { xml <- lapply(name, xml_topic, patcher = patcher) sapply(xml, as.character) %>% paste(collapse = "\n") } patch_package_doc <- function(x) { x %>% xml_find_first("//h3") %>% xml_remove remove_see_also_section(x) remove_authors_section(x) x } move_contents_of_usage_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 usage_contents <- x %>% xml_find_all( "//h3[.='Usage']/following-sibling::node() [not(self::h3)] [count(preceding-sibling::h3)=2]") usage_text <- usage_contents %>% xml_find_first("//pre") %>% xml_text h3 <- x %>% xml_find_first("//h3") intro_text <- read_xml( paste0( "

This section describes the behavior of the following method", if (length(grep("[(]", strsplit(usage_text, "\n")[[1]])) > 1) "s" else "", ":

") ) xml_add_sibling( h3, intro_text, .where = "before") lapply(usage_contents, xml_add_sibling, .x = h3, .copy = FALSE, .where = "before") x %>% xml_find_first("//h3[.='Usage']") %>% xml_remove x } move_additional_arguments_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error additional_arguments <- x %>% xml_find_all( "//h3[.='Additional arguments'] | //h3[.='Additional arguments']/following-sibling::node()[following-sibling::h3]") after_arg <- x %>% xml_find_first("//h3[text()='Arguments']/following-sibling::h3") lapply(additional_arguments, xml_add_sibling, .x = after_arg, .copy = FALSE, .where = "before") x } remove_see_also_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='See Also'] | //h3[.='See Also']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } remove_authors_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='Author(s)'] | //h3[.='Author(s)']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } patch_method_doc <- function(x) { move_contents_of_usage_section(x) remove_see_also_section(x) move_additional_arguments_section(x) x } topics <- c( "dbDataType", "dbConnect", "dbDisconnect", "dbSendQuery", "dbFetch", "dbClearResult", "dbBind", "dbGetQuery", "dbSendStatement", "dbExecute", "dbQuoteString", "dbQuoteIdentifier", "dbReadTable", "dbWriteTable", "dbListTables", "dbExistsTable", "dbRemoveTable", "dbListFields", "dbIsValid", "dbHasCompleted", "dbGetStatement", "dbGetRowCount", "dbGetRowsAffected", "dbColumnInfo", "transactions", "dbWithTransaction" ) html <- c( out_topic("DBI-package", patch_package_doc), out_topic(topics, patch_method_doc) ) temp_html <- tempfile(fileext = ".html") temp_md <- tempfile(fileext = ".md") #temp_html <- "out.html" #temp_md <- "out.md" #html <- '
\na\nb\n
' writeLines(html, temp_html) rmarkdown::pandoc_convert(temp_html, "gfm", verbose = FALSE, output = temp_md) knitr::asis_output(paste(readLines(temp_md), collapse = "\n")) DBI/inst/doc/spec.Rmd0000644000176200001440000001173514064774575014022 0ustar liggesusers--- title: "DBI specification" author: "Kirill Müller" output: rmarkdown::html_vignette abstract: > The DBI package defines the generic DataBase Interface for R. The connection to individual DBMS is provided by other packages that import DBI (so-called *DBI backends*). This document formalizes the behavior expected by the methods declared in DBI and implemented by the individual backends. To ensure maximum portability and exchangeability, and to reduce the effort for implementing a new DBI backend, the DBItest package defines a comprehensive set of test cases that test conformance to the DBI specification. This document is derived from comments in the test definitions of the DBItest package. Any extensions or updates to the tests will be reflected in this document. vignette: > %\VignetteIndexEntry{DBI specification} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo = FALSE} library(magrittr) library(xml2) knitr::opts_chunk$set(echo = FALSE) r <- rprojroot::is_r_package$make_fix_file() ``` ```{r error=TRUE} rd_db <- tools::Rd_db(dir = r()) Links <- tools::findHTMLlinks() html_topic <- function(name) { rd <- rd_db[[paste0(name, ".Rd")]] conn <- textConnection(NULL, "w") on.exit(close(conn)) #tools::Rd2HTML(rd, conn, Links = Links) tools::Rd2HTML(rd, conn) textConnectionValue(conn) } xml_topic <- function(name, patcher) { html <- html_topic(name) x <- read_html(paste(html, collapse = "\n")) # No idea why this is necessary when embedding HTML in Markdown codes <- x %>% xml_find_all("//code[contains(., '$')]") xml_text(codes) <- gsub("[$]", "\\\\$", xml_text(codes)) xx <- x %>% xml_find_first("/html/body") xx %>% xml_find_first("//table") %>% xml_remove() xx %>% xml_find_all("//pre") %>% xml_set_attr("class", "r") patcher(xx) } out_topic <- function(name, patcher = identity) { xml <- lapply(name, xml_topic, patcher = patcher) sapply(xml, as.character) %>% paste(collapse = "\n") } patch_package_doc <- function(x) { x %>% xml_find_first("//h3") %>% xml_remove remove_see_also_section(x) remove_authors_section(x) x } move_contents_of_usage_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 usage_contents <- x %>% xml_find_all( "//h3[.='Usage']/following-sibling::node() [not(self::h3)] [count(preceding-sibling::h3)=2]") usage_text <- usage_contents %>% xml_find_first("//pre") %>% xml_text h3 <- x %>% xml_find_first("//h3") intro_text <- read_xml( paste0( "

This section describes the behavior of the following method", if (length(grep("[(]", strsplit(usage_text, "\n")[[1]])) > 1) "s" else "", ":

") ) xml_add_sibling( h3, intro_text, .where = "before") lapply(usage_contents, xml_add_sibling, .x = h3, .copy = FALSE, .where = "before") x %>% xml_find_first("//h3[.='Usage']") %>% xml_remove x } move_additional_arguments_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error additional_arguments <- x %>% xml_find_all( "//h3[.='Additional arguments'] | //h3[.='Additional arguments']/following-sibling::node()[following-sibling::h3]") after_arg <- x %>% xml_find_first("//h3[text()='Arguments']/following-sibling::h3") lapply(additional_arguments, xml_add_sibling, .x = after_arg, .copy = FALSE, .where = "before") x } remove_see_also_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='See Also'] | //h3[.='See Also']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } remove_authors_section <- function(x) { # https://stackoverflow.com/a/3839299/946850 and some trial and error x %>% xml_find_all( "//h3[.='Author(s)'] | //h3[.='Author(s)']/following-sibling::node()[following-sibling::h3]") %>% xml_remove() x } patch_method_doc <- function(x) { move_contents_of_usage_section(x) remove_see_also_section(x) move_additional_arguments_section(x) x } topics <- c( "dbDataType", "dbConnect", "dbDisconnect", "dbSendQuery", "dbFetch", "dbClearResult", "dbBind", "dbGetQuery", "dbSendStatement", "dbExecute", "dbQuoteString", "dbQuoteIdentifier", "dbReadTable", "dbWriteTable", "dbListTables", "dbExistsTable", "dbRemoveTable", "dbListFields", "dbIsValid", "dbHasCompleted", "dbGetStatement", "dbGetRowCount", "dbGetRowsAffected", "dbColumnInfo", "transactions", "dbWithTransaction" ) html <- c( out_topic("DBI-package", patch_package_doc), out_topic(topics, patch_method_doc) ) temp_html <- tempfile(fileext = ".html") temp_md <- tempfile(fileext = ".md") #temp_html <- "out.html" #temp_md <- "out.md" #html <- '
\na\nb\n
' writeLines(html, temp_html) rmarkdown::pandoc_convert(temp_html, "gfm", verbose = FALSE, output = temp_md) knitr::asis_output(paste(readLines(temp_md), collapse = "\n")) ``` DBI/inst/doc/DBI-proposal.html0000644000176200001440000017524314157714553015543 0ustar liggesusers A Common Interface to Relational Databases from R and S – A Proposal

A Common Interface to Relational Databases from R and S – A Proposal

David James

March 16, 2000

For too long S and similar data analysis environments have lacked good interfaces to relational database systems (RDBMS). For the last twenty years or so these RDBMS have evolved into highly optimized client-server systems for data storage and manipulation, and currently they serve as repositories for most of the business, industrial, and research “raw” data that analysts work with. Other analysis packages, such as SAS, have traditionally provided good data connectivity, but S and GNU R have relied on intermediate text files as means of importing data (but see R Data Import/Export (2001) and Using Relational Database Systems with R (2000).) Although this simple approach works well for relatively modest amounts of mostly static data, it does not scale up to larger amounts of data distributed over machines and locations, nor does it scale up to data that is highly dynamic – situations that are becoming increasingly common.

We want to propose a common interface between R/S and RDBMS that would allow users to access data stored on database servers in a uniform and predictable manner irrespective of the database engine. The interface defines a small set of classes and methods similar in spirit to Python’s DB-API, Java’s JDBC, Microsoft’s ODBC, Perl’s DBI, etc., but it conforms to the “whole-object” philosophy so natural in S and R.

Computing with Distributed Data

As data analysts, we are increasingly faced with the challenge of larger data sources distributed over machines and locations; most of these data sources reside in relational database management systems (RDBMS). These relational databases represent a mature client-server distributed technology that we as analysts could be exploiting more that we’ve done in the past. The relational technology provides a well-defined standard, the ANSI SQL-92 X/Open CAE Specification: SQL and RDA (1994), both for defining and manipulating data in a highly optimized fashion from virtually any application.

In contrast, S and Splus have provided somewhat limited tools for coping with the challenges of larger and distributed data sets (Splus does provide an import function to import from databases, but it is quite limited in terms of SQL facilities). The R community has been more resourceful and has developed a number of good libraries for connecting to mSQL, MySQL, PostgreSQL, and ODBC; each library, however, has defined its own interface to each database engine a bit differently. We think it would be to everybody’s advantage to coordinate the definition of a common interface, an effort not unlike those taken in the Python and Perl communities.

The goal of a common, seamless access to distributed data is a modest one in our evolution towards a fully distributed computing environment. We recognize the greater goal of distributed computing as the means to fully integrate diverse systems – not just databases – into a truly flexible analysis environment. Good connectivity to databases, however, is of immediate necessity both in practical terms and as a means to help us transition from monolithic, self-contained systems to those in which computations, not only the data, can be carried out in parallel over a wide number of computers and/or systems Temple Lang (2000). Issues of reliability, security, location transparency, persistence, etc., will be new to most of us and working with distributed data may provide a more gradual change to ease in the ultimate goal of full distributed computing.

A Common Interface

We believe that a common interface to databases can help users easily access data stored in RDBMS. A common interface would describe, in a uniform way, how to connect to RDBMS, extract meta-data (such as list of available databases, tables, etc.) as well as a uniform way to execute SQL statements and import their output into R and S. The current emphasis is on querying databases and not so much in a full low-level interface for database development as in JDBC or ODBC, but unlike these, we want to approach the interface from the “whole-object” perspective J. M. Chambers (1998) so natural to R/S and Python – for instance, by fetching all fields and records simultaneously into a single object.

The basic idea is to split the interface into a front-end consisting of a few classes and generic functions that users invoke and a back-end set of database-specific classes and methods that implement the actual communication. (This is a very well-known pattern in software engineering, and another good verbatim is the device-independent graphics in R/S where graphics functions produce similar output on a variety of different devices, such X displays, Postscript, etc.)

The following verbatim shows the front-end:

> mgr <- dbManager("Oracle")
> con <- dbConnect(mgr, user = "user", passwd = "passwd")
> rs <- dbExecStatement(con,
          "select fld1, fld2, fld3 from MY_TABLE")
> tbls <- fetch(rs, n = 100)
> hasCompleted(rs)
[1] T
> close(rs)
> rs <- dbExecStatement(con,
          "select id_name, q25, q50 from liv2")
> res <- fetch(rs)
> getRowCount(rs)
[1] 73
> close(con)

Such scripts should work with other RDBMS (say, MySQL) by replacing the first line with

> mgr <- dbManager("MySQL")

Interface Classes

The following are the main RS-DBI classes. They need to be extended by individual database back-ends (MySQL, Oracle, etc.)

dbManager

Virtual class1 extended by actual database managers, e.g., Oracle, MySQL, Informix.

dbConnection

Virtual class that captures a connection to a database instance2.

dbResult

Virtual class that describes the result of an SQL statement.

dbResultSet

Virtual class, extends dbResult to fully describe the output of those statements that produce output records, i.e., SELECT (or SELECT-like) SQL statement.

All these classes should implement the methods show, describe, and getInfo:

show

(print in R) prints a one-line identification of the object.

describe

prints a short summary of the meta-data of the specified object (like summary in R/S).

getInfo

takes an object of one of the above classes and a string specifying a meta-data item, and it returns the corresponding information (NULL if unavailable).

> mgr <- dbManager("MySQL")
> getInfo(mgr, "version")
> con <- dbConnect(mgr, ...)
> getInfo(con, "type")

The reason we implement the meta-data through getInfo in this way is to simplify the writing of database back-ends. We don’t want to overwhelm the developers of drivers (ourselves, most likely) with hundreds of methods as in the case of JDBC.

In addition, the following methods should also be implemented:

getDatabases

lists all available databases known to the dbManager.

getTables

lists tables in a database.

getTableFields

lists the fields in a table in a database.

getTableIndices

lists the indices defined for a table in a database.

These methods may be implemented using the appropriate getInfo method above.

In the next few sections we describe in detail each of these classes and their methods.

Class dbManager

This class identifies the relational database management system. It needs to be extended by individual back-ends (Oracle, PostgreSQL, etc.) The dbManager class defines the following methods:

load

initializes the driver code. We suggest having the generator, dbManager(driver), automatically load the driver.

unload

releases whatever resources the driver is using.

getVersion

returns the version of the RS-DBI currently implemented, plus any other relevant information about the implementation itself and the RDBMS being used.

Class dbConnection

This virtual class captures a connection to a RDBMS, and it provides access to dynamic SQL, result sets, RDBMS session management (transactions), etc. Note that the dbManager may or may not allow multiple simultaneous connections. The methods it defines include:

dbConnect

opens a connection to the database dbname. Other likely arguments include host, user, and password. It returns an object that extends dbConnection in a driver-specific manner (e.g., the MySQL implementation creates a connection of class MySQLConnection that extends dbConnection). Note that we could separate the steps of connecting to a RDBMS and opening a database there (i.e., opening an instance). For simplicity we do the 2 steps in this method. If the user needs to open another instance in the same RDBMS, just open a new connection.

close

closes the connection and discards all pending work.

dbExecStatement

submits one SQL statement. It returns a dbResult object, and in the case of a SELECT statement, the object also inherits from dbResultSet. This dbResultSet object is needed for fetching the output rows of SELECT statements. The result of a non-SELECT statement (e.g., UPDATE, DELETE, CREATE, ALTER, …) is defined as the number of rows affected (this seems to be common among RDBMS).

commit

commits pending transaction (optional).

rollback

undoes current transaction (optional).

callProc

invokes a stored procedure in the RDBMS (tentative). Stored procedures are not part of the ANSI SQL-92 standard and possibly vary substantially from one RDBMS to another. For instance, Oracle seems to have a fairly decent implementation of stored procedures, but MySQL currently does not support them.

dbExec

submit an SQL “script” (multiple statements). May be implemented by looping with dbExecStatement.

dbNextResultSet

When running SQL scripts (multiple statements), it closes the current result set in the dbConnection, executes the next statement and returns its result set.

Class dbResult

This virtual class describes the result of an SQL statement (any statement) and the state of the operation. Non-query statements (e.g., CREATE, UPDATE, DELETE) set the “completed” state to 1, while SELECT statements to 0. Error conditions set this slot to a negative number. The dbResult class defines the following methods:

getStatement

returns the SQL statement associated with the result set.

getDBConnection

returns the dbConnection associated with the result set.

getRowsAffected

returns the number of rows affected by the operation.

hasCompleted

was the operation completed? SELECT’s, for instance, are not completed until their output rows are all fetched.

getException

returns the status of the last SQL statement on a given connection as a list with two members, status code and status description.

Class dbResultSet

This virtual class extends dbResult, and it describes additional information from the result of a SELECT statement and the state of the operation. The completed state is set to 0 so long as there are pending rows to fetch. The dbResultSet class defines the following additional methods:

getRowCount

returns the number of rows fetched so far.

getNullOk

returns a logical vector with as many elements as there are fields in the result set, each element describing whether the corresponding field accepts NULL values.

getFields

describes the SELECTed fields. The description includes field names, RDBMS internal data types, internal length, internal precision and scale, null flag (i.e., column allows NULL’s), and corresponding S classes (which can be over-ridden with user-provided classes). The current MySQL and Oracle implementations define a dbResultSet as a named list with the following elements:

connection:

the connection object associated with this result set;

statement:

a string with the SQL statement being processed;

description:

a field description data.frame with as many rows as there are fields in the SELECT output, and columns specifying the name, type, length, precision, scale, Sclass of the corresponding output field.

rowsAffected:

the number of rows that were affected;

rowCount:

the number of rows so far fetched;

completed:

a logical value describing whether the operation has completed or not.

nullOk:

a logical vector specifying whether the corresponding column may take NULL values.

The methods above are implemented as accessor functions to this list in the obvious way.

setDataMappings

defines a conversion between internal RDBMS data types and R/S classes. We expect the default mappings to be by far the most common ones, but users that need more control may specify a class generator for individual fields in the result set. (See Section [sec:mappings] for details.)

close

closes the result set and frees resources both in R/S and the RDBMS.

fetch

extracts the next max.rec records (-1 means all).

Data Type Mappings

The data types supported by databases are slightly different than the data types in R and S, but the mapping between them is straightforward: Any of the many fixed and varying length character types are mapped to R/S character. Fixed-precision (non-IEEE) numbers are mapped into either doubles (numeric) or long (integer). Dates are mapped to character using the appropriate TO_CHAR function in the RDBMS (which should take care of any locale information). Some RDBMS support the type CURRENCY or MONEY which should be mapped to numeric. Large objects (character, binary, file, etc.) also need to be mapped. User-defined functions may be specified to do the actual conversion as follows:

  1. run the query (either with dbExec or dbExecStatement):

    > rs <- dbExecStatement(con, "select whatever-You-need")
  2. extract the output field definitions

    > flds <- getFields(rs)
  3. replace the class generator in the, say 3rd field, by the user own generator:

    > flds[3, "Sclass"]            # default mapping
    [1] "character"

    by

    > flds[3, "Sclass"] <- "myOwnGeneratorFunction"
  4. set the new data mapping prior to fetching

    > setDataMappings(resutlSet, flds)
  5. fetch the rows and store in a data.frame

    > data <- fetch(resultSet)

Open Issues

We may need to provide some additional utilities, for instance to convert dates, to escape characters such as quotes and slashes in query strings, to strip excessive blanks from some character fields, etc. We need to decide whether we provide hooks so these conversions are done at the C level, or do all the post-processing in R or S.

Another issue is what kind of data object is the output of an SQL query. Currently the MySQL and Oracle implementations return data as a data.frame; data frames have the slight inconvenience that they automatically re-label the fields according to R/S syntax, changing the actual RDBMS labels of the variables; the issue of non-numeric data being coerced into factors automatically “at the drop of a hat” (as someone in s-news wrote) is also annoying.

The execution of SQL scripts is not fully described. The method that executes scripts could run individual statements without returning until it encounters a query (SELECT-like) statement. At that point it could return that one result set. The application is then responsible for fetching these rows, and then for invoking dbNextResultSet on the opened dbConnection object to repeat the dbExec/fetch loop until it encounters the next dbResultSet. And so on. Another (potentially very expensive) alternative would be to run all statements sequentially and return a list of data.frames, each element of the list storing the result of each statement.

Binary objects and large objects present some challenges both to R and S. It is becoming more common to store images, sounds, and other data types as binary objects in RDBMS, some of which can be in principle quite large. The SQL-92 ANSI standard allows up to 2 gigabytes for some of these objects. We need to carefully plan how to deal with binary objects – perhaps tentatively not in full generality. Large objects could be fetched by repeatedly invoking a specified R/S function that takes as argument chunks of a specified number of raw bytes. In the case of S4 (and Splus5.x) the RS-DBI implementation can write into an opened connection for which the user has defined a reader (but can we guarantee that we won’t overflow the connection?). In the case of R it is not clear what data type binary large objects (BLOB) should be mapped into.

Limitations

These are some of the limitations of the current interface definition:

  • we only allow one SQL statement at a time, forcing users to split SQL scripts into individual statements;

  • transaction management is not fully described;

  • the interface is heavily biased towards queries, as opposed to general purpose database development. In particular we made no attempt to define “bind variables”; this is a mechanism by which the contents of S objects are implicitly moved to the database during SQL execution. For instance, the following embedded SQL statement

      /* SQL */
      SELECT * from emp_table where emp_id = :sampleEmployee

    would take the vector sampleEmployee and iterate over each of its elements to get the result. Perhaps RS-DBI could at some point in the future implement this feature.

Other Approaches

The high-level, front-end description of RS-DBI is the more critical aspect of the interface. Details on how to actually implement this interface may change over time. The approach described in this document based on one back-end driver per RDBMS is reasonable, but not the only approach – we simply felt that a simpler approach based on well-understood and self-contained tools (R, S, and C API’s) would be a better start. Nevertheless we want to briefly mention a few alternatives that we considered and tentatively decided against, but may quite possibly re-visit in the near future.

Open Database Connectivity (ODBC)

The ODBC protocol was developed by Microsoft to allow connectivity among C/C++ applications and RDBMS. As you would expect, originally implementations of the ODBC were only available under Windows environments. There are various effort to create a Unix implementation (see the Unix ODBC web-site and Harvey (1999)). This approach looks promising because it allows us to write only one back-end, instead of one per RDBMS. Since most RDBMS already provide ODBC drivers, this could greatly simplify development. Unfortunately, the Unix implementation of ODBC was not mature enough at the time we looked at it, a situation we expect will change in the next year or so. At that point we will need to re-evaluate it to make sure that such an ODBC interface does not penalize the interface in terms of performance, ease of use, portability among the various Unix versions, etc.

Java Database Connectivity (JDBC)

Another protocol, the Java database connectivity, is very well-done and supported by just about every RDBMS. The issue with JDBC is that as of today neither S nor R (which are written in C) interfaces cleanly with Java. There are several efforts (some in a quite fairly advanced state) to allow S and R to invoke Java methods. Once this interface is widely available in Splus5x and R we will need to re-visit this issue again and study the performance, usability, etc., of JDBC as a common back-end to the RS-DBI.

CORBA and a 3-tier Architecture

Yet another approach is to move the interface to RDBMS out of R and S altogether into a separate system or server that would serve as a proxy between R/S and databases. The communication to this middle-layer proxy could be done through CORBA Siegel (1996), Java’s RMI, or some other similar technology. Such a design could be very flexible, but the CORBA facilities both in R and S are not widely available yet, and we do not know whether this will be made available to Splus5 users from MathSoft. Also, my experience with this technology is rather limited.

On the other hand, this 3-tier architecture seem to offer the most flexibility to cope with very large distributed databases, not necessarily relational.

Resources

The latest documentation and software on the RS-DBI was available at www.omegahat.net (link dead now: https://www.omegahat.net/contrib/RS-DBI/index.html). The R community has developed interfaces to some databases: RmSQL is an interface to the mSQL database written by Torsten Hothorn; RPgSQL is an interface to PostgreSQL and was written by Timothy H. Keitt; RODBC is an interface to ODBC, and it was written by Michael Lapsley. (For more details on all these see R Data Import/Export (2001).)

The are R and S-Plus interfaces to MySQL that follow the propose RS-DBI API described here; also, there’s an S-Plus interface SOracle James (In preparation) to Oracle (we expect to have an R implementation soon.)

The idea of a common interface to databases has been successfully implemented in Java’s Database Connectivity (JDBC) (www.javasoft.com), in C through the Open Database Connectivity (ODBC) (www.unixodbc.org), in Python’s Database Application Programming Interface (www.python.org), and in Perl’s Database Interface (www.cpan.org).

Acknowledgements

The R/S database interface came about from suggestions, comments, and discussions with John M. Chambers and Duncan Temple Lang in the context of the Omega Project for Statistical Computing. Doug Bates and Saikat DebRoy ported (and greatly improved) the first MySQL implementation to R.

The S Version 4 Definitions

The following code is meant to serve as a detailed description of the R/S to database interface. We decided to use S4 (instead of R or S version 3) because its clean syntax help us to describe easily the classes and methods that form the RS-DBI, and also to convey the inter-class relationships.

## Define all the classes and methods to be used by an
## implementation of the RS-DataBase Interface.  Mostly,
## these classes are virtual and each driver should extend
## them to provide the actual implementation.

## Class: dbManager
## This class identifies the DataBase Management System
## (Oracle, MySQL, Informix, PostgreSQL, etc.)

setClass("dbManager", VIRTUAL)

setGeneric("load",
   def = function(dbMgr,...)
   standardGeneric("load")
   )
setGeneric("unload",
   def = function(dbMgr,...)
   standardGeneric("unload")
   )
setGeneric("getVersion",
   def = function(dbMgr,...)
   standardGeneric("getVersion")
   )

## Class: dbConnections
## This class captures a connection to a database instance.

setClass("dbConnection", VIRTUAL)

setGeneric("dbConnection",
   def = function(dbMgr, ...)
   standardGeneric("dbConnection")
   )
setGeneric("dbConnect",
   def = function(dbMgr, ...)
   standardGeneric("dbConnect")
   )
setGeneric("dbExecStatement",
   def = function(con, statement, ...)
   standardGeneric("dbExecStatement")
   )
setGeneric("dbExec",
   def = function(con, statement, ...)
   standardGeneric("dbExec")
   )
setGeneric("getResultSet",
   def = function(con, ..)
   standardGeneric("getResultSet")
   )
setGeneric("commit",
   def = function(con, ...)
   standardGeneric("commit")
   )
setGeneric("rollback",
   def = function(con, ...)
   standardGeneric("rollback")
   )
setGeneric("callProc",
   def = function(con, ...)
   standardGeneric("callProc")
   )
setMethod("close",
   signature = list(con="dbConnection", type="missing"),
   def = function(con, type) NULL
   )

## Class: dbResult
## This is a base class for arbitrary results from the RDBMS
## (INSERT, UPDATE, DELETE).  SELECTs (and SELECT-like)
## statements produce "dbResultSet" objects, which extend
## dbResult.

setClass("dbResult", VIRTUAL)

setMethod("close",
   signature = list(con="dbResult", type="missing"),
   def = function(con, type) NULL
   )

## Class: dbResultSet
## Note that we define a resultSet as the result of a
## SELECT  SQL statement.

setClass("dbResultSet", "dbResult")

setGeneric("fetch",
   def = function(resultSet,n,...)
   standardGeneric("fetch")
   )
setGeneric("hasCompleted",
   def = function(object, ...)
   standardGeneric("hasCompleted")
   )
setGeneric("getException",
   def = function(object, ...)
   standardGeneric("getException")
   )
setGeneric("getDBconnection",
   def = function(object, ...)
   standardGeneric("getDBconnection")
   )
setGeneric("setDataMappings",
   def = function(resultSet, ...)
   standardGeneric("setDataMappings")
   )
setGeneric("getFields",
   def = function(object, table, dbname,  ...)
   standardGeneric("getFields")
   )
setGeneric("getStatement",
   def = function(object, ...)
   standardGeneric("getStatement")
   )
setGeneric("getRowsAffected",
   def = function(object, ...)
   standardGeneric("getRowsAffected")
   )
setGeneric("getRowCount",
   def = function(object, ...)
   standardGeneric("getRowCount")
   )
setGeneric("getNullOk",
   def = function(object, ...)
   standardGeneric("getNullOk")
   )

## Meta-data:
setGeneric("getInfo",
   def = function(object, ...)
   standardGeneric("getInfo")
   )
setGeneric("describe",
   def = function(object, verbose=F, ...)
   standardGeneric("describe")
   )
setGeneric("getCurrentDatabase",
   def = function(object, ...)
   standardGeneric("getCurrentDatabase")
   )
setGeneric("getDatabases",
   def = function(object, ...)
   standardGeneric("getDatabases")
   )
setGeneric("getTables",
   def = function(object, dbname, ...)
   standardGeneric("getTables")
   )
setGeneric("getTableFields",
   def = function(object, table, dbname, ...)
   standardGeneric("getTableFields")
   )
setGeneric("getTableIndices",
   def = function(object, table, dbname, ...)
   standardGeneric("getTableIndices")
   )
Chambers, J. M. 1998. Programming with Data: A Guide to the s Language. New York: Springer.
Chambers, John M., Mark H. Hansen, David A. James, and Duncan Temple Lang. 1998. “Distributed Computing with Data: A CORBA-Based Approach.” In Computing Science and Statistics. Inteface Foundation of North America.
Harvey, Peter. 1999. Open Database Connectivity.” Linux Journal Nov. (67): 68–72.
James, David A. In preparation. “An R/S Interface to the Oracle Database.” www.omegahat.org: Bell Labs, Lucent Technologies.
R Data Import/Export. 2001. R-Development Core Team.
Siegel, Jon. 1996. CORBA Fundamentals and Programming. New York: Wiley.
Temple Lang, Duncan. 2000. The Omegahat Environment: New Possibilities for Statistical Computing.” Journal of Computational and Graphical Statistics to appear.
Using Relational Database Systems with R. 2000. R-Developemt Core Team.
X/Open CAE Specification: SQL and RDA. 1994. Reading, UK: X/Open Company Ltd.

  1. A virtual class allows us to group classes that share some common functionality, e.g., the virtual class “dbConnection” groups all the connection implementations by Informix, Ingres, DB/2, Oracle, etc. Although the details will vary from one RDBMS to another, the defining characteristic of these objects is what a virtual class captures. R and S version 3 do not explicitly define virtual classes, but they can easily implement the idea through inheritance.↩︎

  2. The term “database” is sometimes (confusingly) used both to denote the RDBMS, such as Oracle, MySQL, and also to denote a particular database instance under a RDBMS, such as “opto” or “sales” databases under the same RDBMS.↩︎

DBI/inst/doc/DBI-history.Rmd0000644000176200001440000001221614064774575015160 0ustar liggesusers--- title: "History of DBI" author: "David James" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"History of DBI"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- The following history of DBI was contributed by David James, the driving force behind the development of DBI, and many of the packages that implement it. The idea/work of interfacing S (originally S3 and S4) to RDBMS goes back to the mid- and late 1990's in Bell Labs. The first toy interface I did was to implement John Chamber's early concept of "Data Management in S" (1991). The implementation followed that interface pretty closely and immediately showed some of the limitations when dealing with very large databases; if my memory serves me, the issue was the instance-based of the language back then, e.g., if you attached an RDBMS to the `search()` path and then needed to resolve a symbol "foo", you effectively had to bring all the objects in the database to check their mode/class, i.e., the instance object had the metadata in itself as attributes. The experiment showed that the S3 implementation of "data management" was not really suitable to large external RDBMS (probably it was never intended to do that anyway). (Note however, that since then, John and Duncan Temple Lang generalized the data management in S4 a lot, including Duncan's implementation in his RObjectTables package where he considered a lot of synchronization/caching issues relevant to DBI and, more generally, to most external interfaces). Back then we were working very closely with Lucent's microelectronics manufacturing --- our colleagues there had huge Oracle (mostly) databases that we needed to constantly query via [SQL*Plus](https://en.wikipedia.org/wiki/SQL*Plus). My colleague Jake Luciani was developing advanced applications in C and SQL, and the two of us came up with the first implementation of S3 directly connecting with Oracle. What I remember is that the Linux [PRO*C](https://en.wikipedia.org/wiki/Pro*C) pre-compiler (that embedded SQL in C code) was very buggy --- we spent a lot of time looking for workarounds and tricks until we got the C interface running. At the time, other projects within Bell Labs began using MySQL, and we moved to MySQL (with the help of Doug Bates' student Saikat DebRoy, then a summer intern) with no intentions of looking back at the very difficult Oracle interface. It was at this time that I moved all the code from S3 methods to S4 classes and methods and begun reaching out to the S/R community for suggestions, ideas, etc. All (most) of this work was on Bell Labs versions of S3 and S4, but I made sure it worked with S-Plus. At some point around 2000 (I don't remember exactly when), I ported all the code to R regressing to S3 methods, and later on (once S4 classes and methods were available in R) I re-implemented everything back to S4 classes and methods in R (a painful back-and-forth). It was at this point that I decided to drop S-Plus altogether. Around that time, I came across a very early implementation of SQLite and I was quite interested and thought it was a very nice RDBMS that could be used for all kinds of experimentation, etc., so it was pretty easy to implement on top of the DBI. Within the R community, there were quite a number of people that showed interest on defining a common interface to databases, but only a few folks actually provided code/suggestions/etc. (Tim Keitt was most active with the dbi/PostgreSQL packages --- he also was considering what he called "proxy" objects, which was reminiscent of what Duncan had been doing). Kurt Hornick, Vincent Carey, Robert Gentleman, and others provided suggestions/comments/support for the DBI definition. By around 2003, the DBI was more or less implemented as it is today. I'm sure I'll forget some (most should be in the THANKS sections of the various packages), but the names that come to my mind at this moment are Jake Luciani (ROracle), Don MacQueen and other early ROracle users (super helpful), Doug Bates and his student Saikat DebRoy for RMySQL, Fei Chen (at the time a student of Prof. Ripley) also contributed to RMySQL, Tim Keitt (working on an early S3 interface to PostgrSQL), Torsten Hothorn (worked with mSQL and also MySQL), Prof. Ripley working/extending the RODBC package, in addition to John Chambers and Duncan Temple-Lang who provided very important comments and suggestions. Actually, the real impetus behind the DBI was always to do distributed statistical computing --- *not* to provide a yet-another import/export mechanism --- and this perspective was driven by John and Duncan's vision and work on inter-system computing, COM, CORBA, etc. I'm not sure many of us really appreciated (even now) the full extent of those ideas and concepts. Just like in other languages (C's ODBC, Java's JDBC, Perl's DBI/DBD, Python dbapi), R/S DBI was meant to unify the interfacing to RDBMS so that R/S applications could be developed on top of the DBI and not be hard coded to any one relation database. The interface I tried to follow the closest was the Python's DBAPI --- I haven't worked on this topic for a while, but I still feel Python's DBAPI is the cleanest and most relevant for the S language. DBI/inst/doc/DBI.Rmd0000644000176200001440000001627614157713767013472 0ustar liggesusers--- title: "Introduction to DBI" author: "James Wondrasek, Katharina Brunner, Kirill Müller" date: "27 February 2020" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{"Introduction to DBI"} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE,warning=FALSE, message=FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5")) ``` ## Who this tutorial is for This tutorial is for you if you want to access or manipulate data in a database that may be on your machine or on a different computer on the internet, and you have found libraries that use a higher level of abstraction, such as [dbplyr](https://dbplyr.tidyverse.org/), are not suitable for your purpose. Depending on what you want to achieve, you may find it useful to have an understanding of SQL before using DBI. The DBI (**D**ata**B**ase **I**nterface) package provides a simple, consistent interface between R and database management systems (DBMS). Each supported DBMS is supported by its own R package that implements the DBI specification in `vignette("spec", package = "DBI")`. DBI currently supports about 30 DBMS, including: * MySQL, using the R-package [RMySQL](https://github.com/r-dbi/RMySQL) * MariaDB, using the R-package [RMariaDB](https://github.com/r-dbi/RMariaDB) * Postgres, using the R-package [RPostgres](https://github.com/r-dbi/RPostgres) * SQLite, using the R-package [RSQLite](https://github.com/r-dbi/RSQLite) For a more complete list of supported DBMS visit [https://github.com/r-dbi/backends](https://github.com/r-dbi/backends#readme). You may need to install the package specific to your DBMS. The functionality currently supported for each of these DBMS's includes: - manage a connection to a database - list the tables in a database - list the column names in a table - read a table into a data frame For more advanced features, such as parameterized queries, transactions, and more see `vignette("DBI-advanced", package = "DBI")`. ## How to connect to a database using DBI The following code establishes a connection to the Sakila database hosted by the Relational Dataset Repository at `https://relational.fit.cvut.cz/dataset/Sakila`, lists all tables on the database, and closes the connection. The database represents a fictional movie rental business and includes tables describing films, actors, customers, stores, etc.: ```{r} library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = "relational", dbname = "sakila" ) dbListTables(con) dbDisconnect(con) ``` Connections to databases are created using the `dbConnect()` function. The first argument to the function is the driver for the DBMS you are connecting to. In the example above we are connecting to a MariaDB instance, so we use the `RMariaDB::MariaDB()` driver. The other arguments depend on the authentication required by the DBMS. In the example host, port, username, password, and dbname are required. See the documentation for the DBMS driver package that you are using for specifics. The function `dbListTables()` takes a database connection as its only argument and returns a character vector with all table and view names in the database. After completing a session with a DBMS, always release the connection with a call to `dbDisconnect()`. ### Secure password storage The above example contains the password in the code, which should be avoided for databases with secured access. One way to use the credentials securely is to store it in your system's credential store and then query it with the [keyring](https://github.com/r-lib/keyring#readme) package. The code to connect to the database could then look like this: ```{r eval = FALSE} con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fit.cvut.cz", port = 3306, username = "guest", password = keyring::key_get("relational.fit.cvut.cz", "guest"), dbname = "sakila" ) ``` ## How to retrieve column names for a table We can list the column names for a table with the function `dbListFields()`. It takes as arguments a database connection and a table name and returns a character vector of the column names in order. ```{r} con <- dbConnect(RMariaDB::MariaDB(), username = "guest", password = "relational", host = "relational.fit.cvut.cz", port = 3306, dbname = "sakila") dbListFields(con, "film") ``` ## Read a table into a data frame The function `dbReadTable()` reads an entire table and returns it as a data frame. It is equivalent to the SQL query `SELECT * FROM `. The columns of the returned data frame share the same names as the columns in the table. DBI and the database backends do their best to coerce data to equivalent R data types. ```{r} df <- dbReadTable(con, "film") head(df, 3) ``` ## Read only selected rows and columns into a data frame To read a subset of the data in a table into a data frame, DBI provides functions to run custom SQL queries and manage the results. For small datasets where you do not need to manage the number of results being returned, the function `dbGetQuery()` takes a SQL `SELECT` query to execute and returns a data frame. Below is a basic query that specifies the columns we require (`film_id`, `title` and `description`) and which rows (records) we are interested in. Here we retrieve films released in the year 2006. ```{r} df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006") head(df, 3) ``` We could also retrieve movies released in 2006 that are rated "G". Note that character strings must be quoted. As the query itself is contained within double quotes, we use single quotes around the rating. See `dbQuoteLiteral()` for programmatically converting arbitrary R values to SQL. This is covered in more detail in `vignette("DBI-advanced", package = "DBI")`. ```{r} df <- dbGetQuery(con, "SELECT film_id, title, description FROM film WHERE release_year = 2006 AND rating = 'G'") head(df,3) ``` The equivalent operation using `dplyr` reconstructs the SQL query using three functions to specify the table (`tbl()`), the subset of the rows (`filter()`), and the columns we require (`select()`). Note that dplyr takes care of the quoting. ```{r message=FALSE} library(dplyr) lazy_df <- tbl(con, "film") %>% filter(release_year == 2006 & rating == "G") %>% select(film_id, title, description) head(lazy_df, 3) ``` If you want to perform other data manipulation queries such as `UPDATE`s and `DELETE`s, see `dbSendStatement()` in `vignette("DBI-advanced", package = "DBI")`. ## How to end a DBMS session When finished accessing the DBMS, always close the connection using `dbDisconnect()`. ```{r} dbDisconnect(con) ``` ## Conclusion This tutorial has given you the basic techniques for accessing data in any supported DBMS. If you need to work with databases that will not fit in memory, or want to run more complex queries, including parameterized queries, please see `vignette("DBI-advanced", package = "DBI")`. ## Further Reading * An overview on [working with databases in R on Rstudio.com](https://db.rstudio.com/) * The DBI specification: `vignette("spec", package = "DBI")` * [List of supported DBMS](https://github.com/r-dbi/backends#readme) DBI/inst/doc/DBI-history.html0000644000176200001440000002766714157714552015412 0ustar liggesusers History of DBI

History of DBI

David James

The following history of DBI was contributed by David James, the driving force behind the development of DBI, and many of the packages that implement it.

The idea/work of interfacing S (originally S3 and S4) to RDBMS goes back to the mid- and late 1990’s in Bell Labs. The first toy interface I did was to implement John Chamber’s early concept of “Data Management in S” (1991). The implementation followed that interface pretty closely and immediately showed some of the limitations when dealing with very large databases; if my memory serves me, the issue was the instance-based of the language back then, e.g., if you attached an RDBMS to the search() path and then needed to resolve a symbol “foo”, you effectively had to bring all the objects in the database to check their mode/class, i.e., the instance object had the metadata in itself as attributes. The experiment showed that the S3 implementation of “data management” was not really suitable to large external RDBMS (probably it was never intended to do that anyway). (Note however, that since then, John and Duncan Temple Lang generalized the data management in S4 a lot, including Duncan’s implementation in his RObjectTables package where he considered a lot of synchronization/caching issues relevant to DBI and, more generally, to most external interfaces).

Back then we were working very closely with Lucent’s microelectronics manufacturing — our colleagues there had huge Oracle (mostly) databases that we needed to constantly query via SQL*Plus. My colleague Jake Luciani was developing advanced applications in C and SQL, and the two of us came up with the first implementation of S3 directly connecting with Oracle. What I remember is that the Linux PRO*C pre-compiler (that embedded SQL in C code) was very buggy — we spent a lot of time looking for workarounds and tricks until we got the C interface running. At the time, other projects within Bell Labs began using MySQL, and we moved to MySQL (with the help of Doug Bates’ student Saikat DebRoy, then a summer intern) with no intentions of looking back at the very difficult Oracle interface. It was at this time that I moved all the code from S3 methods to S4 classes and methods and begun reaching out to the S/R community for suggestions, ideas, etc. All (most) of this work was on Bell Labs versions of S3 and S4, but I made sure it worked with S-Plus. At some point around 2000 (I don’t remember exactly when), I ported all the code to R regressing to S3 methods, and later on (once S4 classes and methods were available in R) I re-implemented everything back to S4 classes and methods in R (a painful back-and-forth). It was at this point that I decided to drop S-Plus altogether. Around that time, I came across a very early implementation of SQLite and I was quite interested and thought it was a very nice RDBMS that could be used for all kinds of experimentation, etc., so it was pretty easy to implement on top of the DBI.

Within the R community, there were quite a number of people that showed interest on defining a common interface to databases, but only a few folks actually provided code/suggestions/etc. (Tim Keitt was most active with the dbi/PostgreSQL packages — he also was considering what he called “proxy” objects, which was reminiscent of what Duncan had been doing). Kurt Hornick, Vincent Carey, Robert Gentleman, and others provided suggestions/comments/support for the DBI definition. By around 2003, the DBI was more or less implemented as it is today.

I’m sure I’ll forget some (most should be in the THANKS sections of the various packages), but the names that come to my mind at this moment are Jake Luciani (ROracle), Don MacQueen and other early ROracle users (super helpful), Doug Bates and his student Saikat DebRoy for RMySQL, Fei Chen (at the time a student of Prof. Ripley) also contributed to RMySQL, Tim Keitt (working on an early S3 interface to PostgrSQL), Torsten Hothorn (worked with mSQL and also MySQL), Prof. Ripley working/extending the RODBC package, in addition to John Chambers and Duncan Temple-Lang who provided very important comments and suggestions.

Actually, the real impetus behind the DBI was always to do distributed statistical computing — not to provide a yet-another import/export mechanism — and this perspective was driven by John and Duncan’s vision and work on inter-system computing, COM, CORBA, etc. I’m not sure many of us really appreciated (even now) the full extent of those ideas and concepts. Just like in other languages (C’s ODBC, Java’s JDBC, Perl’s DBI/DBD, Python dbapi), R/S DBI was meant to unify the interfacing to RDBMS so that R/S applications could be developed on top of the DBI and not be hard coded to any one relation database. The interface I tried to follow the closest was the Python’s DBAPI — I haven’t worked on this topic for a while, but I still feel Python’s DBAPI is the cleanest and most relevant for the S language.