DBI/0000755000176200001440000000000015147513477010666 5ustar liggesusersDBI/tests/0000755000176200001440000000000015147357111012017 5ustar liggesusersDBI/tests/testthat/0000755000176200001440000000000015147513477013670 5ustar liggesusersDBI/tests/testthat/test-arrow.R0000644000176200001440000000266415071142015016110 0ustar liggesuserstest_that("write arrow to sqlite", { skip_if_not_installed("nanoarrow") skip_if_not_installed("RSQLite") con <- dbConnect(RSQLite::SQLite(), ":memory:") on.exit(dbDisconnect(con)) data <- data.frame( a = 1:3, b = 2.5, c = "three", stringsAsFactors = FALSE ) data$d <- blob::blob(as.raw(1:10)) tbl <- nanoarrow::as_nanoarrow_array_stream(data) dbCreateTableArrow(con, "data_tbl", tbl) dbAppendTableArrow(con, "data_tbl", tbl) tbl$release() expect_equal( dbReadTable(con, "data_tbl"), data ) tbl <- nanoarrow::as_nanoarrow_array_stream(data) res <- dbWriteTableArrow(con, "data_tbl", tbl, overwrite = TRUE) tbl$release() expect_equal( dbReadTable(con, "data_tbl"), data ) expect_equal( as.data.frame(dbReadTableArrow(con, "data_tbl")), data ) stream <- dbGetQueryArrow(con, "SELECT COUNT(*) FROM data_tbl") expect_equal( as.data.frame(stream)[[1]], nrow(data) ) stream$release() res <- dbSendQueryArrow(con, "SELECT COUNT(*) FROM data_tbl") expect_equal( as.data.frame(dbFetchArrow(res))[[1]], nrow(data) ) dbClearResult(res) # Implicit test for dbBind() tbl <- nanoarrow::as_nanoarrow_array_stream(data["a"]) stream <- dbGetQueryArrow( con, "SELECT * FROM data_tbl WHERE a < $a", params = tbl ) expect_equal( as.data.frame(stream), as.data.frame(data[c(1, 1:2), ], row.names = 1:3) ) tbl$release() }) DBI/tests/testthat/test-interpolate.R0000644000176200001440000000623015071142015017275 0ustar liggesuserstest_that("parameter names matched", { expect_equal( sqlInterpolate(ANSI(), "?a ?b", a = 1, b = 2), SQL("1 2") ) expect_equal( sqlInterpolate(ANSI(), "?a ?b", b = 2, a = 1), SQL("1 2") ) expect_equal( sqlInterpolate(ANSI(), "?a ?b", b = 2, .dots = list(a = 1)), SQL("1 2") ) expect_equal( sqlInterpolate(ANSI(), "?a ?b", .dots = list(a = 1, b = 2)), SQL("1 2") ) }) test_that("parameters in strings are ignored", { expect_equal( sqlInterpolate(ANSI(), "'? ?fuu'"), SQL("'? ?fuu'") ) }) test_that("named parameters check matches", { expect_error( sqlInterpolate(ANSI(), "?a ?b", a = 1, d = 2), "Supplied values don't match named vars to interpolate" ) }) test_that("positional parameters work", { expect_equal( sqlInterpolate(ANSI(), "a ? c ? d ", 1, 2), SQL("a 1 c 2 d ") ) }) test_that("positional parameters can't have names", { expect_error( sqlInterpolate(ANSI(), "? ?", a = 1, 2), "Positional variables don't take named arguments" ) }) test_that("parameters in comments are ignored", { expect_equal( sqlInterpolate(ANSI(), "-- ? ?fuu"), SQL("-- ? ?fuu") ) }) test_that("strings are quoted", { expect_equal( sqlInterpolate(ANSI(), "?a", a = "abc"), SQL("'abc'") ) }) test_that("unquoted strings", { expect_equal( sqlInterpolate(ANSI(), "?a ?b", a = SQL("abc"), b = SQL("('a','b')")), SQL("abc ('a','b')") ) }) test_that("some more complex case works as well", { expect_equal( sqlInterpolate( ANSI(), "asdf ?faa /*fdsa'zsc' */ qwer 'wer' \"bnmvbn\" -- Zc \n '234' ?fuu -- ? ?bar", faa = "abc", fuu = 42L ), SQL( "asdf 'abc' /*fdsa'zsc' */ qwer 'wer' \"bnmvbn\" -- Zc \n '234' 42 -- ? ?bar" ) ) }) test_that("escaping quotes with doubling works", { expect_equal( sqlInterpolate( ANSI(), "'this is a single '' one ?quoted string' ?bar ", bar = 42 ), SQL("'this is a single '' one ?quoted string' 42 ") ) }) test_that("corner cases work", { expect_equal( sqlInterpolate(ANSI(), ""), SQL("") ) expect_error( sqlInterpolate(ANSI(), "?"), "Supplied values don't match positional vars to interpolate" ) expect_equal( sqlInterpolate(ANSI(), "?a", a = 1), SQL("1") ) expect_equal( sqlInterpolate(ANSI(), "\"\""), SQL("\"\"") ) expect_error( sqlInterpolate(ANSI(), "\""), "Unterminated literal" ) expect_equal( sqlInterpolate(ANSI(), "?a\"\"?b", a = 1, b = 2), SQL("1\"\"2") ) expect_equal( sqlInterpolate(ANSI(), "--"), SQL("--") ) expect_equal( sqlInterpolate( ANSI(), "SELECT *\n--comment\n--consecutive comment with '\nFROM mytable" ), SQL("SELECT *\n--comment\n--consecutive comment with '\nFROM mytable") ) expect_error( sqlInterpolate(ANSI(), "/*"), "Unterminated comment" ) # Test escaping rules expect_identical( sqlParseVariablesImpl( "?a '?b\\'?c' ?d '''' ?e", list( sqlQuoteSpec("'", "'", escape = "\\", doubleEscape = FALSE) ), list() ), list( start = c(1L, 13L, 21L), end = c(2L, 14L, 22L) ) ) }) DBI/tests/testthat/test-quoting.R0000644000176200001440000000064714602466070016454 0ustar liggesuserstest_that("NA becomes NULL", { expect_equal(dbQuoteString(ANSI(), NA_character_), SQL("NULL")) }) test_that("strings surrounded by '", { expect_equal(dbQuoteString(ANSI(), "x"), SQL("'x'")) }) test_that("single quotes are doubled surrounded by '", { expect_equal(dbQuoteString(ANSI(), "It's"), SQL("'It''s'")) }) test_that("special chars are escaped", { expect_equal(dbQuoteString(ANSI(), "\n"), SQL("'\n'")) }) DBI/tests/testthat/test-table-insert.R0000644000176200001440000000161414602466070017352 0ustar liggesuserstest_that("appending with zero columns throws a dedicated error (#313)", { skip_if_not_installed("RSQLite") db <- dbConnect(RSQLite::SQLite(), ":memory:") on.exit(dbDisconnect(db)) dbExecute(db, "create table T(n integer primary key)") expect_error(dbAppendTable(db, "T", data.frame()), "column") }) test_that("appending with zero columns throws a dedicated error (#336)", { skip_if_not_installed("RSQLite") library(RSQLite) a <- data.frame(sep = c(1, 2, 3)) con <- dbConnect(SQLite()) on.exit(dbDisconnect(con)) dbWriteTable(con, "a", a) expect_equal(dbReadTable(con, "a"), a) }) test_that("appending with Id works (#380)", { skip_if_not_installed("RSQLite") db <- dbConnect(RSQLite::SQLite(), ":memory:") on.exit(dbDisconnect(db)) dbExecute(db, "create table T(n integer primary key)") expect_equal(dbAppendTable(db, Id(table = "T"), data.frame(n = 1:10)), 10) }) DBI/tests/testthat/test-quote.R0000644000176200001440000000273515071142015016112 0ustar liggesuserstest_that("identifier", { expect_equal(dbQuoteIdentifier(ANSI(), character()), SQL(character())) expect_equal(dbQuoteIdentifier(ANSI(), "a"), SQL('"a"')) expect_equal(dbQuoteIdentifier(ANSI(), "a b"), SQL('"a b"')) expect_equal(dbQuoteIdentifier(ANSI(), SQL('"a"')), SQL('"a"')) expect_equal(dbQuoteIdentifier(ANSI(), SQL('"a b"')), SQL('"a b"')) }) test_that("identifier names", { expect_equal( dbQuoteIdentifier(ANSI(), setNames(character(), character())), SQL(character(), names = character()) ) expect_equal(dbQuoteIdentifier(ANSI(), c(a = "a")), SQL('"a"', names = "a")) expect_equal( dbQuoteIdentifier(ANSI(), c(ab = "a b")), SQL('"a b"', names = "ab") ) expect_equal( dbQuoteIdentifier(ANSI(), SQL('"a"', names = "a")), SQL('"a"', names = "a") ) expect_equal( dbQuoteIdentifier(ANSI(), SQL('"a b"', names = "ab")), SQL('"a b"', names = "ab") ) }) test_that("SQL names", { expect_null(names(SQL(letters))) expect_equal(names(SQL(letters, names = LETTERS)), LETTERS) expect_null(names(SQL(setNames(letters, LETTERS)))) }) test_that("unquote Id", { expect_equal( dbUnquoteIdentifier(ANSI(), Id(table = "a")), list(Id(table = "a")) ) expect_equal( dbUnquoteIdentifier(ANSI(), Id(table = "a", schema = "b")), list(Id(table = "a", schema = "b")) ) expect_equal( dbUnquoteIdentifier(ANSI(), Id(table = "a", schema = "b", catalog = "c")), list(Id(table = "a", schema = "b", catalog = "c")) ) }) DBI/tests/testthat/test-otel.R0000644000176200001440000000372315143014221015713 0ustar liggesuserstest_that("OpenTelemetry tracing works", { skip_if_not_installed("RSQLite") skip_if_not_installed("otel") skip_if_not_installed("otelsdk") record <- with_otel_record({ con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbGetQuery(con, "SELECT * FROM `mtcars`") dbGetQuery( con, "SELECT COUNT(*) FROM \nmtcars WHERE cyl = ?", params = list(1:8) ) dbReadTable(con, "mtcars") dbRemoveTable(con, "mtcars") dbDisconnect(con) }) traces <- record$traces expect_length(traces, 10L) expect_equal(traces[[1L]]$name, "dbConnect RSQLite") expect_equal(traces[[1L]]$kind, "client") expect_equal(traces[[1L]]$attributes$db.system.name, "RSQLite") expect_equal(traces[[2L]]$name, "CREATE TABLE mtcars") expect_equal(traces[[2L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[2L]]$attributes$db.operation.name, "CREATE TABLE") expect_equal(traces[[3L]]$name, "INSERT INTO mtcars") expect_equal(traces[[3L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[3L]]$attributes$db.operation.name, "INSERT INTO") expect_equal(traces[[4L]]$name, "dbWriteTable mtcars") expect_equal(traces[[4L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[5L]]$name, "SELECT mtcars") expect_equal(traces[[5L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[5L]]$attributes$db.operation.name, "SELECT") expect_equal(traces[[6L]]$name, "SELECT mtcars") expect_equal(traces[[7L]]$name, "SELECT mtcars") expect_equal(traces[[8L]]$name, "dbReadTable mtcars") expect_equal(traces[[8L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[9L]]$name, "DROP TABLE mtcars") expect_equal(traces[[9L]]$attributes$db.collection.name, "mtcars") expect_equal(traces[[9L]]$attributes$db.operation.name, "DROP TABLE") expect_equal(traces[[10L]]$name, "dbDisconnect RSQLite") expect_equal(traces[[10L]]$attributes$db.system.name, "RSQLite") }) DBI/tests/testthat/test-methods.R0000644000176200001440000000107615071142015016415 0ustar liggesusersexpect_ellipsis <- function(name, method) { sym <- as.name(name) eval(bquote({ .(sym) <- method expect_true("..." %in% names(formals(.(sym)))) })) } test_that("all methods have ellipsis", { symbols <- ls(env = asNamespace("DBI")) objects <- mget( symbols, env = asNamespace("DBI"), mode = "function", ifnotfound = rep(list(NULL), length(symbols)) ) is_method <- vapply( objects, inherits, "standardGeneric", FUN.VALUE = logical(1L) ) methods <- objects[is_method] Map(expect_ellipsis, names(methods), methods) }) DBI/tests/testthat/test-DBItest.R0000644000176200001440000000203115144400576016252 0ustar liggesusers# Generated by helper-dev.R, do not edit by hand skip_if_not_installed("RSQLite") skip_if_not_installed("nanoarrow") # helper-DBItest.R # Also copied into DBI tryCatch(skip = function(e) message(conditionMessage(e)), { skip_on_cran() skip_if_not_installed("DBItest") DBItest::make_context( RSQLite::SQLite(), list(dbname = tempfile("DBItest", fileext = ".sqlite")), tweaks = DBItest::tweaks( dbitest_version = "1.8.1", constructor_relax_args = TRUE, placeholder_pattern = c("?", "$1", "$name", ":name"), date_cast = function(x) paste0("'", x, "'"), time_cast = function(x) paste0("'", x, "'"), timestamp_cast = function(x) paste0("'", x, "'"), logical_return = function(x) as.integer(x), date_typed = FALSE, time_typed = FALSE, timestamp_typed = FALSE ), name = "RSQLite" ) }) # test-DBItest.R # Also copied into DBI skip_on_cran() skip_if_not_installed("DBItest") DBItest::test_all( skip = c( if (getRversion() < "4.0") "stream_bind_too_many" ) ) DBI/tests/testthat/test-dbUnquoteIdentifier_DBIConnection.R0000644000176200001440000000207315071142015023417 0ustar liggesuserstest_that("can unquote any number of components", { expect_equal(dbUnquoteIdentifier(ANSI(), "a"), list(Id("a"))) expect_equal(dbUnquoteIdentifier(ANSI(), "a.b"), list(Id("a", "b"))) expect_equal(dbUnquoteIdentifier(ANSI(), "a.b.c"), list(Id("a", "b", "c"))) expect_equal( dbUnquoteIdentifier(ANSI(), "a.b.c.d"), list(Id("a", "b", "c", "d")) ) }) test_that("fail with NA input", { expect_error(dbUnquoteIdentifier(ANSI(), NA_character_)) expect_error(dbUnquoteIdentifier(ANSI(), c("a", NA_character_))) }) test_that("can unquote any quoted components", { expect_equal(dbUnquoteIdentifier(ANSI(), '"a.b"'), list(Id("a.b"))) expect_equal(dbUnquoteIdentifier(ANSI(), 'a."b"'), list(Id("a", "b"))) expect_equal(dbUnquoteIdentifier(ANSI(), '"a".b'), list(Id("a", "b"))) expect_equal(dbUnquoteIdentifier(ANSI(), '"a"."b"'), list(Id("a", "b"))) expect_equal(dbUnquoteIdentifier(ANSI(), '"a"""."b"""'), list(Id('a"', 'b"'))) }) test_that("Id is unchanged and wrapped in list", { expect_equal(dbUnquoteIdentifier(ANSI(), Id("foo")), list(Id("foo"))) }) DBI/tests/testthat/helper-dummy.R0000644000176200001440000000040014350241735016403 0ustar liggesusersMockObject <- setClass("MockObject", contains = "DBIObject") MockDriver <- setClass("MockDriver", contains = "DBIDriver") MockConnection <- setClass("MockConnection", contains = "DBIConnection") MockResult <- setClass("MockResult", contains = "DBIResult") DBI/tests/testthat/_snaps/0000755000176200001440000000000014602466070015142 5ustar liggesusersDBI/tests/testthat/_snaps/00-Id.md0000644000176200001440000000033415144400600016222 0ustar liggesusers# Id() requires a character vector Code Id(1) Condition Error: ! All elements of `...` must be strings. # has a decent print method Code Id("a", "b") Output "a"."b" DBI/tests/testthat/test-transactions_interrupt.R0000644000176200001440000000271215071142015021574 0ustar liggesuserstest_that("interrupting a transaction results in rollback, leaving DB in consistent state", { # hard to put in DBItest because need background R process to simulate interrupt skip_on_cran() skip_if_not_installed("RSQLite") skip_if_not_installed("callr") bg <- callr::r_bg( function() { con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) DBI::dbWriteTable(con, 'TEST', data.frame(a = 0L), overwrite = TRUE) # First transaction: long sleep, gets interrupted tryCatch( DBI::dbWithTransaction(con, { DBI::dbWriteTable(con, 'TEST', data.frame(a = 1L), overwrite = TRUE) Sys.sleep(10) }), interrupt = function(e) { message("Transaction interrupted") } ) # Check transaction is aborted with [dbRollback()] if ( !isTRUE(all.equal(DBI::dbReadTable(con, 'TEST'), data.frame(a = 0L))) ) { stop("did not rollback") } # Test no errors starting a second transaction after previous interrupted transaction DBI::dbWithTransaction(con, { Sys.sleep(0.5) }) invisible(TRUE) }, supervise = TRUE ) # Give the background process a moment to start, then interrupt it. Sys.sleep(2) expect_true(bg$is_alive()) expect_true(bg$interrupt()) # Wait for completion and assert no error bg$wait() expect_equal(bg$get_result(), TRUE) }) DBI/tests/testthat/test-data-type.R0000644000176200001440000000102314602466070016643 0ustar liggesuserstest_that("dbDataType works on a data frame", { df <- data.frame(x = 1:10, y = runif(10)) types <- dbDataType(MockDriver(), df) expect_equal(types, c(x = "INT", y = "DOUBLE")) }) test_that("dbDataType works on AsIs", { drv <- MockDriver() int_value <- 1L expect_equal(dbDataType(drv, int_value), "INT") expect_equal(dbDataType(drv, I(int_value)), "INT") date_value <- structure(17455, class = "Date") expect_equal(dbDataType(drv, date_value), "DATE") expect_equal(dbDataType(drv, I(date_value)), "DATE") }) DBI/tests/testthat/test-00-Id.R0000644000176200001440000000161115071142015015516 0ustar liggesuserstest_that("Id() requires a character vector", { expect_snapshot(Id(1), error = TRUE) }) test_that("has a decent print method", { expect_snapshot(Id("a", "b")) }) test_that("each element is quoted individually", { expect_equal( DBI::dbQuoteIdentifier(ANSI(), Id("a", "b.c")), SQL('"a"."b.c"') ) }) test_that("Id organizes the standard named elements", { expect_equal( dbQuoteIdentifier( ANSI(), Id( "unnamed", column = "ultimate", table = "last", schema = "3rd", cluster = '1st', catalog = "2nd" ) ), SQL('"1st"."2nd"."3rd"."unnamed"."last"."ultimate"') ) }) test_that("Id organizes mingled named and unnamed elements; ignores NULL", { expect_equal( dbQuoteIdentifier( ANSI(), Id(table = "4", some_ref = "2", "3", catalog = "1", cluster = NULL) ), SQL('"1"."2"."3"."4"') ) }) DBI/tests/testthat/test-rownames.R0000644000176200001440000000213714602466070016615 0ustar liggesuserstest_that("logical row names uses default name", { df <- data.frame(x = c(a = 1)) expect_equal(sqlRownamesToColumn(df, NA)$row_name, "a") expect_equal(sqlRownamesToColumn(df, T)$row_name, "a") expect_equal(sqlRownamesToColumn(df, F)$row_name, NULL) }) test_that("character row names uses supplied name", { df <- data.frame(x = c(a = 1)) expect_equal(sqlRownamesToColumn(df, "x")$x, "a") }) test_that("no rownames in input gives no rownames in output", { df <- data.frame(x = 1) expect_equal(sqlRownamesToColumn(df, NA)$row_name, NULL) }) test_that("guess identify of row_names columns", { df <- data.frame(row_names = "a", x = 1, stringsAsFactors = FALSE) expect_equal(row.names(sqlColumnToRownames(df, NA)), "a") expect_equal(row.names(sqlColumnToRownames(df, TRUE)), "a") expect_equal(row.names(sqlColumnToRownames(df, FALSE)), "1") }) test_that("override identify of row_names column", { df <- data.frame(x = 1, y = "a", stringsAsFactors = FALSE) expect_equal(row.names(sqlColumnToRownames(df, "y")), "a") expect_error(row.names(sqlColumnToRownames(df, "z")), "not present") }) DBI/tests/testthat/test-sql-df.R0000644000176200001440000000037614627152541016155 0ustar liggesuserstest_that("NAs turn in NULLs", { df <- data.frame( x = c(1, NA), y = c("a", NA), stringsAsFactors = FALSE ) sql_df <- sqlData(ANSI(), df) expect_equal(sql_df$x, SQL(c("1", "NULL"))) expect_equal(sql_df$y, SQL(c("'a'", "NULL"))) }) DBI/tests/testthat/setup.R0000644000176200001440000000007614350241735015144 0ustar liggesuserssuppressWarnings(requireNamespace("RSQLite", quietly = TRUE)) DBI/tests/testthat.R0000644000176200001440000000060214602466070014000 0ustar liggesusers# This file is part of the standard setup for testthat. # It is recommended that you do not modify it. # # Where should you do additional test configuration? # Learn more about the roles of various files in: # * https://r-pkgs.org/testing-design.html#sec-tests-files-overview # * https://testthat.r-lib.org/articles/special-files.html library(testthat) library(DBI) test_check("DBI") DBI/.Rinstignore0000644000176200001440000000002514350241735013155 0ustar liggesusersinst/doc/figure1.pdf DBI/MD50000644000176200001440000004072215147513477011203 0ustar liggesusersb879293a2e3d0e4a52c6d68fc93a3b79 *DESCRIPTION 261c3e3ddc96347b5a8e3f19c299cc5d *NAMESPACE 8303d148c8cffcd462b9fde549ef9226 *NEWS.md 7b86b096bbce97a78a708fe0e933d89e *R/00-Id.R df6668faefa1a555a8f9e95afeb70904 *R/01-DBIObject.R 5198c6eec4b353ff88882ba47c3841f4 *R/02-DBIDriver.R 12d9b4d8127b015ad982b471b9e08b27 *R/03-DBIConnection.R b56706702384fe74719397d7d086f585 *R/04-DBIResult.R 3ac82a661c763fbfae79e7333bd33d18 *R/06-ANSI.R 705f1e15a0eb7a0f8dadb7d2ade172a3 *R/07-DBIResultArrow.R 01d52ee22a1d7c1d561021f3b570f2a8 *R/11-dbAppendTable.R d12faa4cf662d1ef282ebf6fb3a3cc30 *R/12-dbCreateTable.R f01b451cfd09ca1ff7822c4b998adf0c *R/13-dbWriteTable.R b82cfb3593c47a90115b60b000b5f2d8 *R/14-dbSendQuery.R df52a3e5d4f419fd35b188fde7b4d193 *R/15-dbBind.R c934aa82e7a6efb7f6b7d9164540268e *R/21-dbAppendTableArrow.R dff3d4fef9375b422b56d45bf88833a9 *R/22-dbCreateTableArrow.R 96421e4a2ff1c354aa0a55f816fe2a6b *R/23-dbWriteTableArrow.R 0d940d65f06770ba3365027bba71bdb3 *R/24-dbSendQueryArrow.R 6dcf8c3a055a79c60acbb99ff8b12e0b *R/25-dbBindArrow.R 78c75925bbe18c89d22aef1ea84f90e1 *R/DBI-package.R aaa699e36799c933fab8a992c867531f *R/DBIConnector.R b2f768366db7da783ad65fca06d8012f *R/SQL.R 53b3b335788e1f9d6f7b245ca6a708d5 *R/SQLKeywords.R 571f189c8b41db56bcadff84373280a4 *R/SQLKeywords_DBIObject.R 0d52e8ec54b12d9fd1627eca0d452b1d *R/SQLKeywords_missing.R 4d9aa53c1ba51a9cdc12438530a86b64 *R/data-types.R 19cd20ad37a89a7fd9046bd159252be1 *R/data.R e20b93cf4c0e5eb5beefd3c6aaba7047 *R/dbAppendTableArrow_DBIConnection.R 5062cc5c8d67ff1f0a1143eb5a023553 *R/dbAppendTable_DBIConnection.R cf86083d25415494a3a878fb3c550ca4 *R/dbBegin.R 4ec90f1ff24745365a46f8182e9f5577 *R/dbBindArrow_DBIResult.R 3160c46f7a6b0e7ff7cc378a544a4f0b *R/dbBindArrow_DBIResultArrowDefault.R 9641bb6f1784fab5dfe4950f42f97098 *R/dbBind_DBIResultArrow.R ebcb0a06817b6ee3bd762ffffe181b3d *R/dbCallProc.R 0ad2db9ea727c8d2b5e7c79d8dff910e *R/dbCanConnect.R 8e74ceea09e2d78e7578dec900608289 *R/dbCanConnect_DBIDriver.R df1cadbc745c382b5f640c6aee532732 *R/dbClearResult.R 4ddbc1942db95185fca2d4f554e4a23f *R/dbClearResult_DBIResultArrow.R 3465ffe2f2db302fede48bcb032a100a *R/dbColumnInfo.R 89dc4c2e5a612799f8a7065d63943989 *R/dbCommit.R b91a0c52a2981813170fd29ed47b2a87 *R/dbConnect.R 2650c8652de8a83756fedc456a03d476 *R/dbConnect_DBIConnector.R cb151ccc09f8722c67e973e186e8e49c *R/dbCreateTableArrow_DBIConnection.R 88e69f630fb25777d77e44cca8960db0 *R/dbCreateTable_DBIConnection.R e0dedd9f8a87289fc2432db9c62faa29 *R/dbDataType.R e86feef168b8c012513dd50b015fcd9e *R/dbDataType_DBIConnector.R 0c75124e20e8fb03d107b30a27c19760 *R/dbDataType_DBIObject.R 6a7c8d3ff261ea39d7b9f7fd93d01ace *R/dbDisconnect.R abb403153d4031b6dd90ec01fe2d3494 *R/dbDriver.R 77006a92266de53743b1b27dc2166e52 *R/dbDriver_character.R 04d02f17ee09f632a4692ae1df9cc1e9 *R/dbExecute.R 01434fa11b9710cc4e95da8b289aa78a *R/dbExecute_DBIConnection_character.R bd9987ce6df3389beb5ff8bf17392ff3 *R/dbExistsTable.R 5a578efa6e766c709c791ff203e93a2f *R/dbExistsTable_DBIConnection_Id.R 8899dc1942285435bf864b86763db556 *R/dbFetch.R c57833f001a1ab4bb76b973e638673f9 *R/dbFetchArrow.R 4862b43e440cc7590023e01b8908fa7e *R/dbFetchArrowChunk.R f5f9bc7aca6956bc0b3972dbffa9aa9e *R/dbFetchArrowChunk_DBIResultArrow.R 0cef2c1d7339b074fb6582e2f8cb6875 *R/dbFetchArrow_DBIResultArrow.R e98adbf9e505b36bceaaea8f3c935573 *R/dbFetch_DBIResult.R d7963c7d33ac02f5dd9b02c2e7d1bb78 *R/dbFetch_DBIResultArrow.R 06de594a8c476aca186766435a5d086a *R/dbGetConnectArgs.R 3263611b86c9d89eb9fee37f467972f0 *R/dbGetConnectArgs_DBIConnector.R bd224cf8c2106c7df139421780dd1b1d *R/dbGetException.R 16f01fa0362bcb2b4936e563c7efdce0 *R/dbGetInfo.R 2fd40282c5a9b312901ecc629586f37f *R/dbGetInfo_DBIResult.R bb4fcd50d16319130582914d62557e6f *R/dbGetInfo_DBIResultArrow.R 4dbf2cbd9bb96946913c1e0e89962dd6 *R/dbGetQuery.R 1857d336ce79c6d21575a9e40d37803a *R/dbGetQueryArrow.R 7d93e6e9d6c7d92f5ba513d5d493f519 *R/dbGetQueryArrow_DBIConnection.R 19060c1bffde0b1e9774766cd8c93722 *R/dbGetQuery_DBIConnection_character.R 40e989df3d934468c31ba07c6faa3d1e *R/dbGetRowCount.R 3ab1358c6fd8921f3bc540d2649cac81 *R/dbGetRowCount_DBIResultArrow.R 3faa7358272afd3bb88880b5df31b8fa *R/dbGetRowsAffected.R c6f57edc7d11b705ccbf7c9cd5492629 *R/dbGetRowsAffected_DBIResultArrow.R d4b668cb76ad839f15510701539d974c *R/dbGetStatement.R 5a5aa73155db8f2c9bbe658214f3bedd *R/dbGetStatement_DBIResultArrow.R d7099a124b5ae1b500c2de129f706470 *R/dbHasCompleted.R 843f3693a5aa4858ca71441a3afa934c *R/dbHasCompleted_DBIResultArrow.R b2a949f66bae0bce9ccc9560c7727549 *R/dbIsReadOnly.R 20c1c442df9885b1dde2a79b4d5fdc52 *R/dbIsReadOnly_DBIConnector.R 083f467fd264c59ccafacef611d3429d *R/dbIsReadOnly_DBIObject.R e00076986a0a6b77d779277fbc0bb3ac *R/dbIsValid.R a0d3864e5374a4605db14c1e8b605f4f *R/dbIsValid_DBIResultArrowDefault.R 3c05561b26262d1794cf485e189d5009 *R/dbListConnections.R 6a28149cfc094260c66b2125c29216b8 *R/dbListFields.R 3075aec72adb0fe54fbb424c6a226ae8 *R/dbListFields_DBIConnection_Id.R a0edab14b79f7aa3b3c1a60d2a2cae1d *R/dbListFields_DBIConnection_character.R 76aa1ea73038fcef098a171538f08685 *R/dbListObjects.R f64006d2ea1aeb36ca21f70ece584243 *R/dbListObjects_DBIConnection_ANY.R fc8b76338e9f4c58ebfe90d0e4299dcf *R/dbListResults.R bef7540d1c27084ddfe5d1ada912fad2 *R/dbListTables.R 0220c44ca7a18ad4270ff5a7be5133d6 *R/dbQuoteIdentifier.R e75dc77fa63d2f5e7cd4863a7dc614c4 *R/dbQuoteIdentifier_DBIConnection.R a2d3b19846d4dfa0f9b24a3e92c19086 *R/dbQuoteLiteral.R 19887ef97ac639351c8ab00db8bdf31b *R/dbQuoteLiteral_DBIConnection.R a2eda269f83334b66dde7c9b307d4910 *R/dbQuoteString.R 1230e1970996acdf26d623e30eb3cd9b *R/dbQuoteString_DBIConnection.R ad2628b1148b954c30854fc61e2b8469 *R/dbReadTable.R d65b1a5732f7586348f4764e19075ede *R/dbReadTableArrow.R eace7a85d3cefc422ba77ef631a09011 *R/dbReadTableArrow_DBIConnection.R 97539df93f41e6175647a0e6debdc59f *R/dbReadTable_DBIConnection_Id.R b7515e5261f064f3f384c67d5200c4c9 *R/dbReadTable_DBIConnection_character.R d3415b36559536c0e5917c665af26882 *R/dbRemoveTable.R 824e55fb7887a8b6303b249bfa7efff6 *R/dbRemoveTable_DBIConnection_Id.R 83e080992ae4514aa3ad64e695e97ab0 *R/dbRollback.R 31638c52633c3bd9909324f6b5839679 *R/dbSendQueryArrow_DBIConnection.R 81655ef94683bfd48eb0148f8de53c57 *R/dbSendStatement.R f1e5d9d2f913249efb0d4a8895c3efcc *R/dbSendStatement_DBIConnection_character.R 355841fe0254b62110663ef6c829a1ef *R/dbSetDataMappings.R 7c54993d78562855f2495e00eef9a931 *R/dbUnloadDriver.R fcc7b02a191e75c5040d337291a3dc64 *R/dbUnquoteIdentifier.R d6e53e769a3f63f26982be03a0e27588 *R/dbUnquoteIdentifier_DBIConnection.R f21991213c3a4d507c761ceec8f0f1ea *R/dbWithTransaction.R 1b5a186e494c1d565e8254c954841e0c *R/dbWithTransaction_DBIConnection.R e64a116fa66f4b86e1c1f101c659b5c7 *R/dbWriteTableArrow_DBIConnection.R 91fb5ba86c064033893a4f2531fdaf86 *R/dbWriteTable_DBIConnection_Id_ANY.R c9390c8132ece818d66461227aa8d8a0 *R/dbiDataType.R b844e95f8a72cf21aba5b964041dcc32 *R/dbiDataType_ANY.R 65e5f21c95d37a35f6c8e9bf26af4924 *R/dbiDataType_AsIs.R e14fcdbe5bd13075c2193fa6ffaf5725 *R/dbiDataType_Date.R ac198cf63328dbe7fd1711cb184b8676 *R/dbiDataType_POSIXct.R 1ba179139ce12b0eca1e3e878f826778 *R/dbiDataType_character.R c83e452b5b55e1fa6a4db75c846ed422 *R/dbiDataType_data.frame.R 9d22ef1d422877d009aebf4ae1ab3301 *R/dbiDataType_default.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 fbd9e63f2e958996a47abb94143c673d *R/deprecated.R 2c817cb0bc6364b1c98ee71eaa0eae84 *R/fetch.R 2463950fd640ca47273a5315d957068d *R/hms.R 112f5b2745490908ff9d2fcabcf4395e *R/interpolate.R bd38754fd923627f39ecab1e15edcdd3 *R/isSQLKeyword.R 6e3f61ef10cbe316fc68551aa2bd8ef3 *R/isSQLKeyword_DBIObject_character.R 1f789e90375796a16ca3843dce72fcc1 *R/make.db.names.R 03642895829e912f2e9b95b1ecb866f6 *R/make.db.names_DBIObject_character.R 2ef7b7fff51bd71e08b3e27a20f6e435 *R/methods_as_rd.R 2830246bfd6e609f683f2e3d83379a43 *R/otel.R 947f83142489ed41e8b97aba4f6e2ef4 *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 35e1bb9553fd43b8b217a3b926d965c1 *R/sqlAppendTable.R 4308a11c8e72424905da6f9b46ef1f07 *R/sqlAppendTableTemplate.R 8a9871a268d6071ca55b557e9b191921 *R/sqlAppendTable_DBIConnection.R 4c4e9883f2837ba77b7b8618bc69fb20 *R/sqlCreateTable.R d15a131d185eb3d94ac63e34b7af6362 *R/sqlCreateTable_DBIConnection.R 2a2508e90deab5e2da1284cef1a57564 *R/sqlData.R 24f1bf8225b3cd27b652ecd726b0b7bf *R/sqlData_DBIConnection.R fefc9de94ce2ca4184a62cec19f432de *R/sqlInterpolate.R 5276afd3e4b3f99e4daff005ebba8877 *R/sqlInterpolate_DBIConnection.R e13594b8c77bc5846ef7a31ce23b094a *R/sqlParseVariables.R 32ffd70f624077dfd0094759550ebb51 *R/sqlParseVariables_DBIConnection.R 42f3ac8f9e3bf2c02205e18b7be385f3 *R/summary.R 0102589dc220e4a35f82466bc4fda1a4 *R/summary_DBIObject.R c2e81afb106abc23851775e46d795000 *R/transactions.R 1b7c83688dd5adabc765f44ab64e4b43 *README.md 1b2ab4c4bfdc3cb7c4190ca4f5119d00 *build/stage23.rdb 3ba0f34ae27c61be8e197b511819a738 *build/vignette.rds 9bfdd96f1790a32f2e6db3a3758ad785 *inst/doc/DBI-1.Rmd 9348a1289c4e9aae800bfa2d3097ab92 *inst/doc/DBI-1.html 4899c9a334116dc03394d258c964b4fd *inst/doc/DBI-advanced.R 10fd312adf3beb1f748604cefd38482b *inst/doc/DBI-advanced.Rmd 8a13397df3575f2f71e7bf9d435381bc *inst/doc/DBI-advanced.html 95fb12f4306c5310eb1f2031de5e8a4a *inst/doc/DBI-arrow.R 75540b51f9123b5f2d12716079a4900e *inst/doc/DBI-arrow.Rmd 6e0a17bbe1cd8ff7c6f7f599aeb15b82 *inst/doc/DBI-arrow.html 0cb90dc5f9e5b0a9b289f70dfe997079 *inst/doc/DBI-history.Rmd a08e730c0c2f3c4f7bb370540800f70f *inst/doc/DBI-history.html 363ab6fc48b043f76130050b4e90917a *inst/doc/DBI-proposal.Rmd 7aadd1993579016c23c41a65404b9e9b *inst/doc/DBI-proposal.html 90bde1beb6f89d0e9d5e4e21412753c3 *inst/doc/DBI.R 0047e328fa54d17e5df4b12b538ee4c3 *inst/doc/DBI.Rmd 7412cde17ac5b72ee2c6b9ea5526cfd6 *inst/doc/DBI.html 307b62fe7899567cd7a02c28f65ff726 *inst/doc/backend.R da87ef36460fcc8fc9d643bf8ade0ae3 *inst/doc/backend.Rmd 80eaea53b3a7313f8b80f6a2c6b19c54 *inst/doc/backend.html 79a10903a9332c71d8092d7859073f1f *inst/doc/spec.R 55510128b0e7e531f19c4229874cfd0e *inst/doc/spec.Rmd 023c0025ddf69d14388f0260c9e07adb *inst/doc/spec.html 3414b76d8057e97cfd58968b7a7ac837 *man/ANSI.Rd ca9721eaa444fd59023694caedf9bb9c *man/DBI-package.Rd ab064c3c46ffbbd8710b074f74268ee4 *man/DBIConnection-class.Rd 7e8db86abb813052c8a97fcdcbab891d *man/DBIConnector-class.Rd d6bab15f03567bc5047491d1b1de9ac2 *man/DBIDriver-class.Rd 8998a96e16bae8e43ec12f77c6ad71e7 *man/DBIObject-class.Rd 73f7e24e72271377afe15a0d32772fe5 *man/DBIResult-class.Rd 410ef6f7cebf63c23f1c529abfed78b2 *man/DBIResultArrow-class.Rd 3a90727203cd716586e82c69e8af3717 *man/Id.Rd 0abe5e81e5b910eb92f501e0d12102f5 *man/SQL.Rd 5372df9a8835d41dff856e1808202675 *man/dbAppendTable.Rd cd4d003fc55bc807f7f570669acb7812 *man/dbAppendTableArrow.Rd 4f57544e7e9fa18c351ac1dcaccb1083 *man/dbBind.Rd f88ce0ae82ce59297b13cd1a581c4105 *man/dbCallProc.Rd 9f220bc97495464c6d6c1405e9f07f4a *man/dbCanConnect.Rd 95c7101d6530b09579b2d0a0e5240be3 *man/dbClearResult.Rd cdec73d94cf23e09866332e9d9002314 *man/dbColumnInfo.Rd 61d1bf063cb2b4ba7b12a54051018f4c *man/dbConnect.Rd 746e27477737f0b4de0abd883a9c23d0 *man/dbCreateTable.Rd 20be63b3185fb4f8197318bccf60d972 *man/dbCreateTableArrow.Rd 2fd823be48d6eb28f3d659715538969c *man/dbDataType.Rd ab2b8bfe2a2c72da7279c8f07b55b4b0 *man/dbDisconnect.Rd 7e0a883d4537ad49edfc591b191b6585 *man/dbDriver.Rd a7e0ee2ff474987dca8181c99c04e44b *man/dbExecute.Rd 07e49a8e0e1702260becc1b3767dea76 *man/dbExistsTable.Rd 70905c7b8da990166708e5c8c57fe396 *man/dbFetch.Rd 544c779da5df7fe80e6cf0bcbeea02b0 *man/dbFetchArrow.Rd 6e5f3d65fca854b87bcb000cdca210d6 *man/dbFetchArrowChunk.Rd 306cf337e7ab579ed6a5ca717a752528 *man/dbGetConnectArgs.Rd 600709b1318e882e99b98e90fa8ba7e7 *man/dbGetDBIVersion.Rd 55b15e7885494ce72f5d9a76fdb710e6 *man/dbGetException.Rd 90f48fa63bdf17617fa622b39bbd4d33 *man/dbGetInfo.Rd 58597abe1f7a298bc9834da0d19e5919 *man/dbGetQuery.Rd 50f49b3a07896d421bfbf5ba3d09ab99 *man/dbGetQueryArrow.Rd 7db615e142840625192a51f7ea73b164 *man/dbGetRowCount.Rd 86d6d8d8ca955c724f347e535649b420 *man/dbGetRowsAffected.Rd deacad47d397e267882a7b04879be9f7 *man/dbGetStatement.Rd 4a86b3d9f5ca884073f5311dc0dfa372 *man/dbHasCompleted.Rd 12718205b9dd838dfcea973df6a99197 *man/dbIsReadOnly.Rd 54371b40af82a24b2d4b389b2c2f1b33 *man/dbIsValid.Rd 45195aabed941c5835837ef3944a48f6 *man/dbListConnections.Rd 7d4e0f8d4e889155c1d4074cc2b865cc *man/dbListFields.Rd 2c23d527cc980d986f7f0eceae8d746e *man/dbListObjects.Rd 06802bbda414892adddac28d81766c18 *man/dbListResults.Rd 795e5843b866a9b1fe9e2a11e8ef36a1 *man/dbListTables.Rd 1e0e3f509c1c9657f55fa7d7fa84076a *man/dbQuoteIdentifier.Rd 659f917f11fdd0ff89b943ffac33bb18 *man/dbQuoteLiteral.Rd 8b2544682727d9cd48a0cd468020f0e2 *man/dbQuoteString.Rd 04278d6c0473a8f3cd07ad95b8ea8c6a *man/dbReadTable.Rd d62a6d651ce7bba3c4d83fa342f6f4f0 *man/dbReadTableArrow.Rd 79de7bbee135e5998069aee676dcbfcd *man/dbRemoveTable.Rd a5d253d5a419fe20473fc2cd1648a62b *man/dbSendQuery.Rd 655e7bd9cb7cb765df41f9d4e453652e *man/dbSendQueryArrow.Rd 5919e141c041852c9c55d4cec5c262b9 *man/dbSendStatement.Rd aa5d0bf6981e5690cdfdde12a53ec958 *man/dbSetDataMappings.Rd f299d0f4bc23341f85974e9f41211313 *man/dbUnquoteIdentifier.Rd 26175817ee0a45a710e5c8e16668b9a2 *man/dbWithTransaction.Rd d0f444fab1671536c0078abfa0670f2b *man/dbWriteTable.Rd 4219c4f56462565e3007f1492d8f3819 *man/dbWriteTableArrow.Rd eeb064c9b0e28e5263755b8b2b8fbf13 *man/dot-SQL92Keywords.Rd a1cbaf3f328e8d74e747faacf640c7fc *man/figures/lifecycle-archived.svg 6f521fb1819410630e279d1abf88685a *man/figures/lifecycle-defunct.svg 391f696f961e28914508628a7af31b74 *man/figures/lifecycle-deprecated.svg 691b1eb2aec9e1bec96b79d11ba5e631 *man/figures/lifecycle-experimental.svg 405e252e54a79b33522e9699e4e9051c *man/figures/lifecycle-maturing.svg f41ed996be135fb35afe00641621da61 *man/figures/lifecycle-questioning.svg 306bef67d1c636f209024cf2403846fd *man/figures/lifecycle-soft-deprecated.svg ed42e3fbd7cc30bc6ca8fa9b658e24a8 *man/figures/lifecycle-stable.svg bf2f1ad432ecccee3400afe533404113 *man/figures/lifecycle-superseded.svg 3bbccfce9273099763a85541a3f653d5 *man/hidden_aliases.Rd ffba08bcb57becb6455b5165b6ef441d *man/make.db.names.Rd 4a7f8a265551b2f3dea24c3692721638 *man/rownames.Rd 5a453dec45fc5446ff0f2fe79c2c8e47 *man/sqlAppendTable.Rd 68107961a34d4649f3a65a98ffaed1da *man/sqlCreateTable.Rd 34eb62f416dcc41c0439e90e16c94cda *man/sqlData.Rd fcabc7b349489575b6c3dce063acf9a4 *man/sqlInterpolate.Rd f0d18acb231943d6f25691e6d1558492 *man/sqlParseVariables.Rd d5a103dc4bac8531aa6bb8438844e49c *man/transactions.Rd bf33e807cc16ea1b4376f48ebde12861 *tests/testthat.R 72e4e900b434270afacf30c871276669 *tests/testthat/_snaps/00-Id.md a607e1deab234336d12e88ad2b80fd80 *tests/testthat/helper-dummy.R 6d7152ea22dc498b844cb6d912b1c771 *tests/testthat/setup.R e7bbb07a40b744f3af703990deddb139 *tests/testthat/test-00-Id.R 7075698b944ff4fdaca9e5c006b83162 *tests/testthat/test-DBItest.R 3a63e97f63a8416d3e0b5e5a52a49009 *tests/testthat/test-arrow.R c85afd831e2fdf9e4cbb9a8ebb73671e *tests/testthat/test-data-type.R 60501aeaf684cac8a0798196e7beca5f *tests/testthat/test-dbUnquoteIdentifier_DBIConnection.R 653e0129ffc03de2ef408dae4555d417 *tests/testthat/test-interpolate.R 48946dc2c187cf11bb6eacc1da51656a *tests/testthat/test-methods.R 864ddc2b62c64c28156dc6f990fe8d7b *tests/testthat/test-otel.R feb04052b5a03e8d41a703f8ac52eff4 *tests/testthat/test-quote.R 0c6dc973642147f079d15e0477aa63d4 *tests/testthat/test-quoting.R 7895ec58f5c8d1e39634cbe839439283 *tests/testthat/test-rownames.R d6fd2ea45be6ac9ebf2643f2ea29dcdf *tests/testthat/test-sql-df.R bda1a87eaadd2fa466b451a36be1bf7a *tests/testthat/test-table-insert.R 86d9f186d7597edafd7c8f8ab02f6b7c *tests/testthat/test-transactions_interrupt.R 9bfdd96f1790a32f2e6db3a3758ad785 *vignettes/DBI-1.Rmd 10fd312adf3beb1f748604cefd38482b *vignettes/DBI-advanced.Rmd 75540b51f9123b5f2d12716079a4900e *vignettes/DBI-arrow.Rmd 0cb90dc5f9e5b0a9b289f70dfe997079 *vignettes/DBI-history.Rmd 363ab6fc48b043f76130050b4e90917a *vignettes/DBI-proposal.Rmd 0047e328fa54d17e5df4b12b538ee4c3 *vignettes/DBI.Rmd da87ef36460fcc8fc9d643bf8ade0ae3 *vignettes/backend.Rmd 67cca7009a40f5c6bab58418607deb57 *vignettes/biblio.bib 16facd043de5250ab88f5b3badef9ab0 *vignettes/hierarchy.png 55510128b0e7e531f19c4229874cfd0e *vignettes/spec.Rmd 0db42429d7746738cbd4621b2fbd56e0 *vignettes/spec.md DBI/R/0000755000176200001440000000000015147357111011056 5ustar liggesusersDBI/R/dbDisconnect.R0000644000176200001440000000125315143005033013566 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbDisconnect(con) setGeneric("dbDisconnect", def = function(conn, ...) { otel_local_active_span("dbDisconnect", conn) standardGeneric("dbDisconnect") }) DBI/R/dbCallProc.R0000644000176200001440000000074715071142015013205 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/dbQuoteIdentifier_DBIConnection.R0000644000176200001440000000261415071142015017277 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.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_Id ) DBI/R/dbListFields_DBIConnection_Id.R0000644000176200001440000000041215071142015016647 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/make.db.names_DBIObject_character.R0000644000176200001440000000062315071142015017415 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/dbClearResult_DBIResultArrow.R0000644000176200001440000000040415071142015016611 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbClearResult_DBIResultArrow <- function(res, ...) { dbClearResult(res@result, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbClearResult", signature("DBIResultArrow"), dbClearResult_DBIResultArrow ) DBI/R/dbGetConnectArgs_DBIConnector.R0000644000176200001440000000062415071142015016677 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/dbRollback.R0000644000176200001440000000017315071142015013230 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbRollback", def = function(conn, ...) { standardGeneric("dbRollback") }) DBI/R/13-dbWriteTable.R0000644000176200001440000000414715144400570013773 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 expects a data frame. #' Use [dbWriteTableArrow()] to write an Arrow object. #' #' This function is useful if you want to create and load a table at the same time. #' Use [dbAppendTable()] or [dbAppendTableArrow()] for appending data to an existing #' table, [dbCreateTable()] or [dbCreateTableArrow()] for creating a table, #' and [dbExistsTable()] and [dbRemoveTable()] for overwriting tables. #' #' DBI only standardizes writing data frames with `dbWriteTable()`. #' 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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") setGeneric("dbWriteTable", def = function(conn, name, value, ...) { otel_local_active_span( "dbWriteTable", conn, label = .dbi_get_collection_name(name, conn), attributes = list(db.collection.name = .dbi_get_collection_name(name, conn)) ) standardGeneric("dbWriteTable") }) DBI/R/show_AnsiConnection.R0000644000176200001440000000032014350241735015145 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL show_AnsiConnection <- function(object) { cat("\n") } #' @rdname hidden_aliases #' @export setMethod("show", "AnsiConnection", show_AnsiConnection) DBI/R/dbQuoteString_DBIConnection.R0000644000176200001440000000223115071142015016456 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/06-ANSI.R0000644000176200001440000000067214602466070012163 0ustar liggesuserssetClass("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/dbConnect.R0000644000176200001440000000361615143005033013073 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 [DBI::DBIDriver][DBIDriver-class], #' or an existing [DBI::DBIConnection][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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' # 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, ...) { otel_local_active_span("dbConnect", drv) standardGeneric("dbConnect") }, valueClass = "DBIConnection" ) DBI/R/dbiDataType_Date.R0000644000176200001440000000016514350241735014331 0ustar liggesusers#' @usage NULL dbiDataType_Date <- function(x) "DATE" setMethod("dbiDataType", signature("Date"), dbiDataType_Date) DBI/R/dbConnect_DBIConnector.R0000644000176200001440000000135514350241735015434 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/00-Id.R0000644000176200001440000000412115071142015011737 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 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. `cluster`, #' `catalog`, `schema`, or `table`, depending on the database backend. For more #' on these concepts, see #' @export #' @examples #' # Identifies a table in a specific schema: #' Id("dbo", "Customer") #' # You can name the components if you want, but it's not needed #' Id(table = "Customer", schema = "dbo") #' #' # Create a SQL expression for an identifier: #' dbQuoteIdentifier(ANSI(), Id("nycflights13", "flights")) #' #' # Write a table in a specific schema: #' \dontrun{ #' dbWriteTable(con, Id("myschema", "mytable"), data.frame(a = 1)) #' } Id <- function(...) { components <- orderIdParams(...) if (!is.character(components)) { stop("All elements of `...` must be strings.", call. = FALSE) } new("Id", name = components) } #' @export toString.Id <- function(x, ...) { paste0(" ", dbQuoteIdentifier(ANSI(), x)) } dbQuoteIdentifier_DBIConnection_Id <- function(conn, x, ...) { SQL(paste0(dbQuoteIdentifier(conn, x@name), collapse = ".")) } orderIdParams <- function( ..., database = NULL, db = NULL, catalog = NULL, cluster = NULL, schema = NULL, table = NULL, column = NULL ) { out <- c( database = database, db = db, cluster = cluster, catalog = catalog, schema = schema, ..., table = table, column = column ) if (all(names(out) == "")) { out <- unname(out) } out } DBI/R/dbWithTransaction.R0000644000176200001440000000465015071142015014624 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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 current 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/dbIsReadOnly_DBIObject.R0000644000176200001440000000027514350241735015330 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbIsReadOnly_DBIObject <- function(dbObj, ...) { FALSE } #' @rdname hidden_aliases setMethod("dbIsReadOnly", "DBIObject", dbIsReadOnly_DBIObject) DBI/R/dbiDataType_ANY.R0000644000176200001440000000036615071142015014076 0ustar liggesusersdbiDataType_ANY <- function(x) { if (inherits(x, "blob")) { return("BLOB") } stop( "Unknown SQL data type for object of class ", paste(class(x), collapse = "/") ) } setMethod("dbiDataType", signature("ANY"), dbiDataType_ANY) DBI/R/DBI-package.R0000644000176200001440000000213115143005033013152 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 #' #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' RSQLite::SQLite() #' @seealso #' Important generics: [dbConnect()], [dbGetQuery()], #' [dbReadTable()], [dbWriteTable()], [dbDisconnect()] #' #' Formal specification (currently work in progress and incomplete): #' `vignette("spec", package = "DBI")` "_PACKAGE" has_arrow <- function() { requireNamespace("nanoarrow", quietly = TRUE) } require_arrow <- function() { if (has_arrow()) { return(invisible(TRUE)) } stop("The nanoarrow package is required for this functionality.") } .onLoad <- function(libname, pkgname) { otel_cache_tracer() } DBI/R/14-dbSendQuery.R0000644000176200001440000000530315071142015013640 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()]. #' Use [dbSendQueryArrow()] or [dbGetQueryArrow()] instead to retrieve the results #' as an Arrow object. #' #' 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. #' #' @inheritSection dbBind The data retrieval flow #' #' @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 #' @family data retrieval generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbFetch.R0000644000176200001440000000364015071142015012532 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. #' #' @inheritSection dbBind The data retrieval flow #' #' @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 [DBI::DBIResult][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 #' @family data retrieval generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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) setGeneric( "dbFetch", def = function(res, n = -1, ...) standardGeneric("dbFetch"), valueClass = "data.frame" ) DBI/R/dbListConnections.R0000644000176200001440000000072715071142015014622 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_DBIConnection.R0000644000176200001440000000133314350241735015267 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/dbRemoveTable.R0000644000176200001440000000217715144400570013716 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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, ...) { otel_local_active_span( "DROP TABLE", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn), db.operation.name = "DROP TABLE" ) ) standardGeneric("dbRemoveTable") }) DBI/R/sqlCreateTable.R0000644000176200001440000000346215071142015014070 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. #' @inheritParams rownames #' @param ... Other arguments used by individual methods. #' #' @template methods #' @templateVar method_name sqlCreateTable #' #' @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/dbBind_DBIResultArrow.R0000644000176200001440000000041214602466070015250 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbBind_DBIResultArrow <- function(res, params, ...) { dbBind(res@result, params = params, ...) invisible(res) } #' @rdname hidden_aliases #' @export setMethod("dbBind", signature("DBIResultArrow"), dbBind_DBIResultArrow) DBI/R/sqlAppendTableTemplate.R0000644000176200001440000000300515071142015015561 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) if (length(table) != 1) { stop("Must pass one table name", call. = FALSE) } 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/dbGetException.R0000644000176200001440000000073615071142015014102 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/dbiDataType_character.R0000644000176200001440000000030115071142015015370 0ustar liggesusersdbiDataType_character <- function(x) { "TEXT" } setMethod("dbiDataType", signature("character"), dbiDataType_character) setMethod("dbiDataType", signature("factor"), dbiDataType_character) DBI/R/dbGetInfo_DBIResultArrow.R0000644000176200001440000000036014602466070015731 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetInfo_DBIResultArrow <- function(dbObj, ...) { dbGetInfo(dbObj@result, ...) } #' @rdname hidden_aliases #' @export setMethod("dbGetInfo", signature("DBIResultArrow"), dbGetInfo_DBIResultArrow) DBI/R/dbiDataType_logical.R0000644000176200001440000000020214350241735015056 0ustar liggesusers#' @usage NULL dbiDataType_logical <- function(x) "SMALLINT" setMethod("dbiDataType", signature("logical"), dbiDataType_logical) DBI/R/SQLKeywords_missing.R0000644000176200001440000000034615071142015015113 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_DBIDriver.R0000644000176200001440000000061114350241735014010 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/dbDataType_DBIObject.R0000644000176200001440000000033514350241735015027 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/SQL.R0000644000176200001440000000403614350241735011642 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/R/03-DBIConnection.R0000644000176200001440000000217615005150137014035 0ustar liggesusers#' 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' con #' dbDisconnect(con) #' \dontrun{ #' con <- dbConnect(RPostgreSQL::PostgreSQL(), "username", "password") #' 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/dbGetConnectArgs.R0000644000176200001440000000175715071142015014356 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbListObjects.R0000644000176200001440000000271515071142015013730 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbListFields.R0000644000176200001440000000147215071142015013544 0ustar liggesusers#' List field names of a remote table #' #' Returns the field names of a remote table as a character vector. #' #' @inheritParams dbReadTable #' #' @template methods #' @templateVar method_name dbListFields #' #' @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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbUnquoteIdentifier.R0000644000176200001440000000243515071142015015145 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 DBIConnection 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", "Schema", "Table")) #' #' # Quoting and unquoting are inverses #' dbQuoteIdentifier( #' ANSI(), #' dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]] #' ) #' #' dbQuoteIdentifier( #' ANSI(), #' dbUnquoteIdentifier(ANSI(), Id("Schema", "Table"))[[1]] #' ) setGeneric("dbUnquoteIdentifier", def = function(conn, x, ...) { standardGeneric("dbUnquoteIdentifier") }) DBI/R/dbColumnInfo.R0000644000176200001440000000202015071142015013541 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.) #' #' @inheritSection dbBind The data retrieval flow #' #' @inheritParams dbClearResult #' #' @template methods #' @templateVar method_name dbColumnInfo #' #' @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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/deprecated.R0000644000176200001440000001125715071142015013276 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 } #' Keywords according to the SQL-92 standard #' #' A character vector of SQL-92 keywords, uppercase. #' #' @export #' @examples #' "SELECT" %in% .SQL92Keywords .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/dbGetQuery.R0000644000176200001440000000514215143005033013243 0ustar liggesusers#' Retrieve results from a query #' #' 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 freed by [dbClearResult()]. #' For retrieving chunked/paged results or for passing query parameters, #' see [dbSendQuery()], in particular the "The data retrieval flow" section. #' For retrieving results as an Arrow object, see [dbGetQueryArrow()]. #' #' This method is for `SELECT` queries only #' (incl. other SQL statements that return a `SELECT`-alike result, #' e.g., execution of a stored procedure or data manipulation queries #' like `INSERT INTO ... RETURNING ...`). #' 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 [DBI::DBIConnection][DBIConnection-class] object, #' as returned by [dbConnect()]. #' @param statement a character string containing SQL. #' @param ... Other parameters passed on to methods. #' @family DBIConnection generics #' @family data retrieval generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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, ...) { otel_query_local_active_span(conn, statement) standardGeneric("dbGetQuery") }) DBI/R/dbRemoveTable_DBIConnection_Id.R0000644000176200001440000000045515071142015017021 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/dbReadTable_DBIConnection_character.R0000644000176200001440000000176515071142015020044 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbReadTable_DBIConnection_character <- function( conn, name, ..., row.names = FALSE, check.names = TRUE ) { sql_name <- dbReadTable_toSqlName(conn, name, ...) 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 } dbReadTable_toSqlName <- function(conn, name, ...) { sql_name <- dbQuoteIdentifier(conn, x = name, ...) if (length(sql_name) != 1L) { stop("Invalid name: ", format(name), call. = FALSE) } sql_name } #' @rdname hidden_aliases #' @export setMethod( "dbReadTable", signature("DBIConnection", "character"), dbReadTable_DBIConnection_character ) DBI/R/dbIsReadOnly_DBIConnector.R0000644000176200001440000000035114350241735016047 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/dbGetStatement_DBIResultArrow.R0000644000176200001440000000041015071142015016765 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetStatement_DBIResultArrow <- function(res, ...) { dbGetStatement(res@result, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbGetStatement", signature("DBIResultArrow"), dbGetStatement_DBIResultArrow ) DBI/R/show_SQL.R0000644000176200001440000000033114350241735012674 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/rownames.R0000644000176200001440000000527315071142015013032 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/dbIsValid_DBIResultArrowDefault.R0000644000176200001440000000041015071142015017221 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbIsValid_DBIResultArrowDefault <- function(dbObj, ...) { dbIsValid(dbObj@result) } #' @rdname hidden_aliases #' @export setMethod( "dbIsValid", signature("DBIResultArrowDefault"), dbIsValid_DBIResultArrowDefault ) DBI/R/dbiDataType_numeric.R0000644000176200001440000000020014350241735015104 0ustar liggesusers#' @usage NULL dbiDataType_numeric <- function(x) "DOUBLE" setMethod("dbiDataType", signature("numeric"), dbiDataType_numeric) DBI/R/sqlParseVariables_DBIConnection.R0000644000176200001440000000070415071142015017312 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/dbiDataType_default.R0000644000176200001440000000041515071142015015066 0ustar liggesusersdbiDataType_default <- function(x) { if (inherits(x, c("blob", "arrow_binary"))) { return("BLOB") } stop( "SQL type unknown for objects of class ", paste(class(x), collapse = "/") ) } setMethod("dbiDataType", signature("ANY"), dbiDataType_default) DBI/R/sqlAppendTable_DBIConnection.R0000644000176200001440000000163015071142015016565 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/dbFetchArrowChunk_DBIResultArrow.R0000644000176200001440000000047215071142015017426 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbFetchArrowChunk_DBIResultArrow <- function(res, ...) { nanoarrow::as_nanoarrow_array( dbFetch(res@result, n = 256, ...) ) } #' @rdname hidden_aliases #' @export setMethod( "dbFetchArrowChunk", signature("DBIResultArrow"), dbFetchArrowChunk_DBIResultArrow ) DBI/R/dbQuoteString.R0000644000176200001440000000225715071142015013770 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/hms.R0000644000176200001440000000406315071142015011762 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/dbDataType.R0000644000176200001440000000500015071142015013204 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 [DBI::DBIDriver][DBIDriver-class] #' or [DBI::DBIConnection][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) #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' #' 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/dbGetRowsAffected_DBIResultArrow.R0000644000176200001440000000042415071142015017402 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetRowsAffected_DBIResultArrow <- function(res, ...) { dbGetRowsAffected(res@result, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbGetRowsAffected", signature("DBIResultArrow"), dbGetRowsAffected_DBIResultArrow ) DBI/R/summary_DBIObject.R0000644000176200001440000000065015071142015014473 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/dbReadTableArrow_DBIConnection.R0000644000176200001440000000054115071142015017032 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbReadTableArrow_DBIConnection <- function(conn, name, ...) { sql_name <- dbReadTable_toSqlName(conn, name, ...) dbGetQueryArrow(conn, paste0("SELECT * FROM ", sql_name)) } #' @rdname hidden_aliases #' @export setMethod( "dbReadTableArrow", signature("DBIConnection"), dbReadTableArrow_DBIConnection ) DBI/R/dbIsValid.R0000644000176200001440000000152415071142015013033 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 #' @family DBIResultArrow generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/07-DBIResultArrow.R0000644000176200001440000000146215071142015014227 0ustar liggesusers#' DBIResultArrow class #' #' @description #' `r lifecycle::badge('experimental')` #' #' This virtual class describes the result and state of execution of #' a DBMS statement (any statement, query or non-query) #' for returning data as an Arrow object. #' #' @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 DBIResultArrow-class #' @docType class #' @family DBI classes #' @family DBIResultArrow generics #' @export setClass("DBIResultArrow", contains = c("DBIObject", "VIRTUAL")) #' @rdname DBIResultArrow-class #' @export setClass( "DBIResultArrowDefault", contains = "DBIResultArrow", slots = list( result = "DBIResult" ) ) DBI/R/sqlCreateTable_DBIConnection.R0000644000176200001440000000174515071142015016570 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/dbCreateTableArrow_DBIConnection.R0000644000176200001440000000110415071142015017356 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbCreateTableArrow_DBIConnection <- function( conn, name, value, ..., temporary = FALSE ) { require_arrow() # https://github.com/apache/arrow-nanoarrow/issues/347 if (!inherits(value, "nanoarrow_schema")) { value <- nanoarrow::infer_nanoarrow_schema(value) } ptype <- nanoarrow::infer_nanoarrow_ptype(value) dbCreateTable(conn, name, ptype, ..., temporary = temporary) } #' @rdname hidden_aliases #' @export setMethod( "dbCreateTableArrow", signature("DBIConnection"), dbCreateTableArrow_DBIConnection ) DBI/R/dbBindArrow_DBIResult.R0000644000176200001440000000065214602466070015256 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbBindArrow_DBIResult <- function(res, params, ...) { dbBind(res, params = param_stream_to_list(params), ...) } #' @rdname hidden_aliases #' @export setMethod("dbBindArrow", signature("DBIResult"), dbBindArrow_DBIResult) param_stream_to_list <- function(params) { params <- as.list(as.data.frame(params)) if (all(names(params) == "")) { names(params) <- NULL } params } DBI/R/dbCreateTable_DBIConnection.R0000644000176200001440000000107615071142015016353 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/dbiDataType_data.frame.R0000644000176200001440000000027214350241735015455 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/dbGetInfo.R0000644000176200001440000000127715071142015013040 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. #' #' @template methods #' @templateVar method_name dbGetInfo #' #' @family DBIDriver generics #' @family DBIConnection generics #' @family DBIResult generics #' @inherit DBItest::spec_get_info return #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' dbGetInfo(RSQLite::SQLite()) setGeneric("dbGetInfo", def = function(dbObj, ...) standardGeneric("dbGetInfo")) DBI/R/sqlInterpolate.R0000644000176200001440000000607315071142015014204 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. #' #' @template methods #' @templateVar method_name sqlInterpolate #' #' @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/show_DBIConnection.R0000644000176200001440000000061214350241735014655 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/dbClearResult.R0000644000176200001440000000220215071142015013717 0ustar liggesusers#' Clear a result set #' #' Frees all resources (local and remote) associated with a result set. #' This step is mandatory for all objects obtained by calling #' [dbSendQuery()] or [dbSendStatement()]. #' #' @inheritSection dbBind The data retrieval flow #' @inheritSection dbBind The command execution flow #' #' @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 [DBI::DBIResult][DBIResult-class]. #' @param ... Other arguments passed on to methods. #' @family DBIResult generics #' @family DBIResultArrow generics #' @family data retrieval generics #' @family command execution generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/sqlInterpolate_DBIConnection.R0000644000176200001440000000255715071142015016705 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/dbDriver.R0000644000176200001440000000332715071142015012736 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' # 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/dbSendStatement.R0000644000176200001440000000460115071142015014255 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. #' #' @inheritSection dbBind The command execution flow #' #' @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 #' @family command execution generics #' #' @seealso For queries: [dbSendQuery()] and [dbGetQuery()]. #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/methods_as_rd.R0000644000176200001440000000422215071142015014003 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/22-dbCreateTableArrow.R0000644000176200001440000000337215144400570015116 0ustar liggesusers#' Create a table in the database based on an Arrow object #' #' @description #' `r lifecycle::badge('experimental')` #' #' The default `dbCreateTableArrow()` method determines the R data types #' of the Arrow schema associated with the Arrow object, #' and calls [dbCreateTable()]. #' Backends that implement [dbAppendTableArrow()] should typically #' also implement this generic. #' Use [dbCreateTable()] to create a table from the column types #' as defined in a data frame. #' #' @param value An object for which a schema can be determined via #' [nanoarrow::infer_nanoarrow_schema()]. #' @inheritParams dbReadTable #' @inheritParams sqlCreateTable #' #' @inherit DBItest::spec_arrow_create_table_arrow return #' @inheritSection DBItest::spec_arrow_create_table_arrow Failure modes #' @inheritSection DBItest::spec_arrow_create_table_arrow Additional arguments #' @inheritSection DBItest::spec_arrow_create_table_arrow Specification #' #' @template methods #' @templateVar method_name dbCreateTableArrow #' #' @family DBIConnection generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' ptype <- data.frame(a = numeric()) #' dbCreateTableArrow(con, "df", nanoarrow::infer_nanoarrow_schema(ptype)) #' dbReadTable(con, "df") #' dbDisconnect(con) setGeneric( "dbCreateTableArrow", def = function(conn, name, value, ..., temporary = FALSE) { otel_local_active_span( "CREATE TABLE", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn), db.operation.name = "CREATE TABLE" ) ) standardGeneric("dbCreateTableArrow") } ) DBI/R/11-dbAppendTable.R0000644000176200001440000000365315144400570014107 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. #' Use [dbAppendTableArrow()] to append data from an Arrow stream. #' #' 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] (or coercible to data.frame). #' @param row.names Must be `NULL`. #' @inheritParams sqlAppendTableTemplate #' #' @template methods #' @templateVar method_name dbAppendTable #' #' @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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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) { otel_local_active_span( "INSERT INTO", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn), db.operation.name = "INSERT INTO" ) ) standardGeneric("dbAppendTable") } ) DBI/R/dbReadTable.R0000644000176200001440000000333215144403222013323 0ustar liggesusers#' Read database tables as data frames #' #' Reads a database table to a data frame, optionally converting #' a column to row names and converting the column names to valid #' R identifiers. #' Use [dbReadTableArrow()] instead to obtain an Arrow object. #' #' @details #' This function returns a data frame. #' Use [dbReadTableArrow()] to obtain an Arrow object. #' #' @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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars[1:10, ]) #' dbReadTable(con, "mtcars") #' #' dbDisconnect(con) setGeneric( "dbReadTable", def = function(conn, name, ...) { otel_local_active_span( "dbReadTable", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn) ) ) standardGeneric("dbReadTable") }, valueClass = "data.frame" ) DBI/R/24-dbSendQueryArrow.R0000644000176200001440000000422115071142015014652 0ustar liggesusers#' Execute a query on a given database connection for retrieval via Arrow #' #' @description #' `r lifecycle::badge('experimental')` #' #' The `dbSendQueryArrow()` 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 [dbFetchArrow()] method, and #' then you must call [dbClearResult()] when you finish fetching the #' records you need. #' For interactive use, you should almost always prefer [dbGetQueryArrow()]. #' Use [dbSendQuery()] or [dbGetQuery()] instead to retrieve the results #' as a data frame. #' #' @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. #' #' @inheritSection dbBindArrow The data retrieval flow for Arrow streams #' #' @template methods #' @templateVar method_name dbSendQueryArrow #' #' @inherit DBItest::spec_arrow_send_query_arrow return #' @inheritSection DBItest::spec_arrow_send_query_arrow Failure modes #' @inheritSection DBItest::spec_arrow_send_query_arrow Additional arguments #' @inheritSection DBItest::spec_arrow_send_query_arrow Specification #' @inheritSection DBItest::spec_arrow_send_query_arrow Specification for the `immediate` argument #' #' @inheritParams dbGetQueryArrow #' @param statement a character string containing SQL. #' #' @family DBIConnection generics #' @family data retrieval generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' # Retrieve data as arrow table #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") #' dbFetchArrow(rs) #' dbClearResult(rs) #' #' dbDisconnect(con) setGeneric( "dbSendQueryArrow", def = function(conn, statement, ...) { require_arrow() standardGeneric("dbSendQueryArrow") }, valueClass = "DBIResultArrow" ) DBI/R/04-DBIResult.R0000644000176200001440000000270714602466070013225 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/otel.R0000644000176200001440000000576215144400571012152 0ustar liggesusersotel_tracer_name <- "org.r-dbi.DBI" # Generic otel helpers: otel_cache_tracer <- NULL otel_local_active_span <- NULL otel_query_local_active_span <- NULL local({ otel_tracer <- NULL otel_is_tracing <- FALSE otel_cache_tracer <<- function() { requireNamespace("otel", quietly = TRUE) || return() otel_tracer <<- otel::get_tracer(otel_tracer_name) otel_is_tracing <<- tracer_enabled(otel_tracer) } otel_local_active_span <<- function( name, conn, label = NULL, attributes = NULL, activation_scope = parent.frame() ) { otel_is_tracing || return() dbname <- .dbi_get_db_name(conn) otel::start_local_active_span( name = sprintf("%s %s", name, if (length(label)) label else dbname), attributes = c(attributes, list(db.system.name = dbname)), options = list(kind = "client"), tracer = otel_tracer, activation_scope = activation_scope ) } otel_query_local_active_span <<- function( conn, statement, activation_scope = parent.frame() ) { otel_is_tracing || return() dbname <- .dbi_get_db_name(conn) collection <- character() op_name <- "SQL" if (length(statement) == 1) { op_name_matcher <- "^\\s*(\\w+)" op_name_matches <- regexec( op_name_matcher, statement, ignore.case = TRUE ) op_name_match <- regmatches(statement, op_name_matches)[[1L]] op_name <- toupper(op_name_match[2L]) collection_matcher <- "(FROM)\\s+([`\"']?)(\\w+)\\2" # collection_matcher <- "(FROM|INTO|UPDATE|TABLE)\\s+([`\"']?)(\\w+)\\2" collection_matches <- gregexec( collection_matcher, statement, ignore.case = TRUE, perl = TRUE ) collection_match <- regmatches(statement, collection_matches)[[1L]] # Returns an empty character vector if there is no match if (is.matrix(collection_match) && nrow(collection_match) >= 4L) { collection <- collection_match[4L, , drop = TRUE] } } otel::start_local_active_span( name = paste(op_name, if (length(collection)) collection else dbname), attributes = list( db.operation.name = op_name, db.collection.name = collection, db.system.name = dbname ), options = list(kind = "client"), tracer = otel_tracer, activation_scope = activation_scope ) } }) tracer_enabled <- function(tracer) { .subset2(tracer, "is_enabled")() } with_otel_record <- function(expr) { on.exit(otel_cache_tracer()) otelsdk::with_otel_record({ otel_cache_tracer() expr }) } # DBI-specific helpers: # When this was called `get_dbname()`, it collided with `dittodb::get_dbname()` # for some weakly understood reason. # The weird name makes collisions more unlikely. .dbi_get_db_name <- function(obj) { dbname <- attr(class(obj), "package") if (is.null(dbname)) "unknown" else dbname } .dbi_get_collection_name <- function(name, conn) { if (is.character(name)) name else dbQuoteIdentifier(conn, x = name) } DBI/R/transactions.R0000644000176200001440000000370014602466070013711 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()] #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/sqlAppendTable.R0000644000176200001440000000215215071142015014067 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()]. #' #' @template methods #' @templateVar method_name sqlAppendTable #' #' @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/dbUnquoteIdentifier_DBIConnection.R0000644000176200001440000000171015071142015017636 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbUnquoteIdentifier_DBIConnection <- function(conn, x, ...) { if (is(x, "SQL") || is.character(x)) { if (is.character(x)) { stopifnot(!anyNA(x)) } # Determine quoting character quote_char <- substr(dbQuoteIdentifier(conn, ""), 1L, 1L) x <- lapply(x, unquote, quote_char = quote_char) lapply(x, Id) } else if (is(x, "Id")) { list(x) } else { stop("x must be SQL, Id, or character", call. = FALSE) } } unquote <- function(x, quote_char) { # replace doubled quotes with escaped quote gsub <- gsub( pattern = paste0(quote_char, quote_char), replacement = paste0("\\", quote_char), x ) scan( text = x, what = character(), quote = quote_char, quiet = TRUE, na.strings = character(), sep = "." ) } #' @rdname hidden_aliases #' @export setMethod( "dbUnquoteIdentifier", signature("DBIConnection"), dbUnquoteIdentifier_DBIConnection ) DBI/R/dbExistsTable.R0000644000176200001440000000140115071142015013721 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbWriteTable_DBIConnection_Id_ANY.R0000644000176200001440000000050615071142015017362 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/dbGetQueryArrow.R0000644000176200001440000000460515143005033014261 0ustar liggesusers#' Retrieve results from a query as an Arrow object #' #' @description #' `r lifecycle::badge('experimental')` #' #' Returns the result of a query as an Arrow object. #' `dbGetQueryArrow()` comes with a default implementation #' (which should work with most backends) that calls #' [dbSendQueryArrow()], then [dbFetchArrow()], ensuring that #' the result is always freed by [dbClearResult()]. #' For passing query parameters, #' see [dbSendQueryArrow()], in particular #' the "The data retrieval flow for Arrow streams" section. #' For retrieving results as a data frame, see [dbGetQuery()]. #' #' @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 or data manipulation queries #' like `INSERT INTO ... RETURNING ...`). #' To execute a stored procedure that does not return a result set, #' use [dbExecute()]. #' #' Some backends may #' support data manipulation statements through this method. #' However, callers are strongly advised to use #' [dbExecute()] for data manipulation statements. #' #' @template methods #' @templateVar method_name dbGetQueryArrow #' #' @inherit DBItest::spec_arrow_get_query_arrow return #' @inheritSection DBItest::spec_arrow_get_query_arrow Failure modes #' @inheritSection DBItest::spec_arrow_get_query_arrow Additional arguments #' @inheritSection DBItest::spec_arrow_get_query_arrow 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 [DBI::DBIConnection][DBIConnection-class] object, #' as returned by [dbConnect()]. #' @param statement a character string containing SQL. #' @param ... Other parameters passed on to methods. #' @family DBIConnection generics #' @family data retrieval generics #' @seealso For updates: [dbSendStatement()] and [dbExecute()]. #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' # Retrieve data as arrow table #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' dbGetQueryArrow(con, "SELECT * FROM mtcars") #' #' dbDisconnect(con) setGeneric("dbGetQueryArrow", def = function(conn, statement, ...) { otel_query_local_active_span(conn, statement) standardGeneric("dbGetQueryArrow") }) DBI/R/dbExistsTable_DBIConnection_Id.R0000644000176200001440000000045515071142015017043 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/isSQLKeyword.R0000644000176200001440000000044615071142015013534 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/dbCommit.R0000644000176200001440000000016115071142015012724 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbCommit", def = function(conn, ...) standardGeneric("dbCommit")) DBI/R/23-dbWriteTableArrow.R0000644000176200001440000000350215144400570015001 0ustar liggesusers#' Copy Arrow objects to database tables #' #' @description #' `r lifecycle::badge('experimental')` #' #' Writes, overwrites or appends an Arrow object to a database table. #' #' @details #' This function expects an Arrow object. #' Convert a data frame to an Arrow object with [nanoarrow::as_nanoarrow_array_stream()] or #' use [dbWriteTable()] to write a data frame. #' #' This function is useful if you want to create and load a table at the same time. #' Use [dbAppendTableArrow()] for appending data to an existing #' table, [dbCreateTableArrow()] for creating a table and specifying field types, #' and [dbRemoveTable()] for overwriting tables. #' #' @template methods #' @templateVar method_name dbWriteTableArrow #' #' @inherit DBItest::spec_arrow_write_table_arrow return #' @inheritSection DBItest::spec_arrow_write_table_arrow Failure modes #' @inheritSection DBItest::spec_arrow_write_table_arrow Additional arguments #' @inheritSection DBItest::spec_arrow_write_table_arrow Specification #' #' @inheritParams dbGetQuery #' @inheritParams dbReadTable #' @param value An nanoarray stream, or an object coercible to a nanoarray stream with #' [nanoarrow::as_nanoarrow_array_stream()]. #' @family DBIConnection generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTableArrow(con, "mtcars", nanoarrow::as_nanoarrow_array_stream(mtcars[1:5, ])) #' dbReadTable(con, "mtcars") #' #' dbDisconnect(con) setGeneric("dbWriteTableArrow", def = function(conn, name, value, ...) { otel_local_active_span( "dbWriteTableArrow", conn, label = .dbi_get_collection_name(name, conn), attributes = list(db.collection.name = .dbi_get_collection_name(name, conn)) ) standardGeneric("dbWriteTableArrow") }) DBI/R/dbListResults.R0000644000176200001440000000101115071142015013764 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/dbWithTransaction_DBIConnection.R0000644000176200001440000000255515071142015017324 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, interrupt = 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/dbWriteTableArrow_DBIConnection.R0000644000176200001440000000210515071142015017247 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbWriteTableArrow_DBIConnection <- function( conn, name, value, append = FALSE, overwrite = FALSE, ..., temporary = FALSE ) { require_arrow() stopifnot(is.logical(append)) stopifnot(length(append) == 1) stopifnot(!is.na(append)) stopifnot(is.logical(overwrite)) stopifnot(length(overwrite) == 1) stopifnot(!is.na(overwrite)) stopifnot(is.logical(temporary)) stopifnot(length(temporary) == 1) stopifnot(!is.na(temporary)) name <- dbQuoteIdentifier(conn, name) value <- nanoarrow::as_nanoarrow_array_stream(value) if (overwrite && append) { stop("overwrite and append cannot both be TRUE") } exists <- dbExistsTable(conn, name) if (overwrite && exists) { dbRemoveTable(conn, name) } if (overwrite || !append || !exists) { dbCreateTableArrow(conn, name, value, temporary = temporary) } dbAppendTableArrow(conn, name, value) invisible(TRUE) } #' @rdname hidden_aliases #' @export setMethod( "dbWriteTableArrow", signature("DBIConnection"), dbWriteTableArrow_DBIConnection ) DBI/R/dbHasCompleted_DBIResultArrow.R0000644000176200001440000000041015071142015016731 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbHasCompleted_DBIResultArrow <- function(res, ...) { dbHasCompleted(res@result, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbHasCompleted", signature("DBIResultArrow"), dbHasCompleted_DBIResultArrow ) DBI/R/dbGetQueryArrow_DBIConnection.R0000644000176200001440000000055315071142015016757 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetQueryArrow_DBIConnection_character <- function(conn, statement, ...) { rs <- dbSendQueryArrow(conn, statement, ...) on.exit(dbClearResult(rs)) dbFetchArrow(rs, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbGetQueryArrow", signature("DBIConnection"), dbGetQueryArrow_DBIConnection_character ) DBI/R/dbDataType_DBIConnector.R0000644000176200001440000000036614350241735015557 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/dbiDataType_POSIXct.R0000644000176200001440000000020314350241735014676 0ustar liggesusers#' @usage NULL dbiDataType_POSIXct <- function(x) "TIMESTAMP" setMethod("dbiDataType", signature("POSIXct"), dbiDataType_POSIXct) DBI/R/dbQuoteLiteral_DBIConnection.R0000644000176200001440000000251315071142015016607 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%z") )) } 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/dbAppendTableArrow_DBIConnection.R0000644000176200001440000000331115071142015017364 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbAppendTableArrow_DBIConnection <- function(conn, name, value, ...) { require_arrow() name <- dbQuoteIdentifier(conn, name) value <- nanoarrow::as_nanoarrow_array_stream(value) rows <- 0L while (TRUE) { # Append next batch (starting with the first or second, doesn't matter) tmp <- value$get_next() if (is.null(tmp)) { break } tmp_df <- as.data.frame(tmp) dbAppendTable(conn, name, stream_append_data(tmp_df), ...) rows <- rows + nrow(tmp_df) } value$release() rows } #' @rdname hidden_aliases #' @export setMethod( "dbAppendTableArrow", signature("DBIConnection"), dbAppendTableArrow_DBIConnection ) stream_append_data <- function(value) { value <- factor_to_string(value) value <- string_to_utf8(value) value } factor_to_string <- function(value, warn = FALSE) { is_factor <- vapply(value, is.factor, logical(1)) if (warn && any(is_factor)) { warning("Factors converted to character", call. = FALSE) } value[is_factor] <- lapply(value[is_factor], as.character) value } raw_to_string <- function(value) { is_raw <- vapply(value, is.raw, logical(1)) if (any(is_raw)) { warning( "Creating a TEXT column from raw, use lists of raw to create BLOB columns", call. = FALSE ) value[is_raw] <- lapply(value[is_raw], as.character) } value } quote_string <- function(value, conn) { is_character <- vapply(value, is.character, logical(1)) value[is_character] <- lapply(value[is_character], dbQuoteString, conn = conn) value } string_to_utf8 <- function(value) { is_char <- vapply(value, is.character, logical(1)) value[is_char] <- lapply(value[is_char], enc2utf8) value } DBI/R/dbGetRowCount.R0000644000176200001440000000162315071142015013720 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbFetch_DBIResult.R0000644000176200001440000000033314350241735014413 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/dbCanConnect.R0000644000176200001440000000173315071142015013515 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' # 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/dbListObjects_DBIConnection_ANY.R0000644000176200001440000000073215071142015017132 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/interpolate.R0000644000176200001440000000770215071142015013524 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/make.db.names.R0000644000176200001440000000576715071142015013612 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/dbSendQueryArrow_DBIConnection.R0000644000176200001440000000057615071142015017136 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbSendQueryArrow_DBIConnection <- function( conn, statement, params = NULL, ... ) { result <- dbSendQuery(conn, statement, params = params, ...) new("DBIResultArrowDefault", result = result) } #' @rdname hidden_aliases #' @export setMethod( "dbSendQueryArrow", signature("DBIConnection"), dbSendQueryArrow_DBIConnection ) DBI/R/21-dbAppendTableArrow.R0000644000176200001440000000276615144400570015127 0ustar liggesusers#' Insert rows into a table from an Arrow stream #' #' @description #' `r lifecycle::badge('experimental')` #' #' The `dbAppendTableArrow()` method assumes that the table has been created #' beforehand, e.g. with [dbCreateTableArrow()]. #' The default implementation calls [dbAppendTable()] for each chunk #' of the stream. #' Use [dbAppendTable()] to append data from a data.frame. #' #' @inheritParams dbReadTable #' @param value An object coercible with [nanoarrow::as_nanoarrow_array_stream()]. #' @inheritParams sqlAppendTableTemplate #' #' @template methods #' @templateVar method_name dbAppendTableArrow #' #' @inherit DBItest::spec_arrow_append_table_arrow return #' @inheritSection DBItest::spec_arrow_append_table_arrow Failure modes #' @inheritSection DBItest::spec_arrow_append_table_arrow Specification #' #' @family DBIConnection generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' dbCreateTableArrow(con, "iris", iris[0, ]) #' dbAppendTableArrow(con, "iris", iris[1:5, ]) #' dbReadTable(con, "iris") #' dbDisconnect(con) setGeneric("dbAppendTableArrow", def = function(conn, name, value, ...) { otel_local_active_span( "INSERT INTO", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn), db.operation.name = "INSERT INTO" ) ) standardGeneric("dbAppendTableArrow") }) DBI/R/dbDriver_character.R0000644000176200001440000000032114350241735014751 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbDriver_character <- function(drvName, ...) { findDriver(drvName)(...) } #' @rdname hidden_aliases setMethod("dbDriver", signature("character"), dbDriver_character) DBI/R/dbiDataType_integer.R0000644000176200001440000000017514350241735015112 0ustar liggesusers#' @usage NULL dbiDataType_integer <- function(x) "INT" setMethod("dbiDataType", signature("integer"), dbiDataType_integer) DBI/R/02-DBIDriver.R0000644000176200001440000000300415071142015013156 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 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/summary.R0000644000176200001440000000002614350241735012673 0ustar liggesuserssetGeneric("summary") DBI/R/dbBegin.R0000644000176200001440000000015715071142015012525 0ustar liggesusers#' @export #' @rdname transactions setGeneric("dbBegin", def = function(conn, ...) standardGeneric("dbBegin")) DBI/R/dbUnloadDriver.R0000644000176200001440000000035215071142015014074 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/dbExecute.R0000644000176200001440000000426315071142015013105 0ustar liggesusers#' Change database state #' #' 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 freed by [dbClearResult()]. #' For passing query parameters, see [dbBind()], in particular #' the "The command execution flow" section. #' #' 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, #' or a data manipulation query that also returns a result set #' such as `INSERT INTO ... RETURNING ...`, 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 #' @family command execution generics #' @seealso For queries: [dbSendQuery()] and [dbGetQuery()]. #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbAppendTable_DBIConnection.R0000644000176200001440000000116515071142015016356 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.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/SQLKeywords.R0000644000176200001440000000040315071142015013354 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/dbQuoteLiteral.R0000644000176200001440000000254215071142015014113 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/show_DBIResult.R0000644000176200001440000000060514350241735014036 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/show_DBIConnector.R0000644000176200001440000000051114350241735014506 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/dbFetchArrow_DBIResultArrow.R0000644000176200001440000000146315071142015016436 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbFetchArrow_DBIResultArrow <- function(res, ...) { chunk <- dbFetchArrowChunk_DBIResultArrow(res) # Corner case: add empty chunk only for zero rows, for schema if (chunk$length == 0) { return(nanoarrow::basic_array_stream( list(), schema = nanoarrow::infer_nanoarrow_schema(chunk), validate = FALSE )) } out <- list(chunk) repeat { chunk <- dbFetchArrowChunk_DBIResultArrow(res) if (chunk$length == 0) { return(nanoarrow::basic_array_stream( out, schema = nanoarrow::infer_nanoarrow_schema(out[[1]]), validate = FALSE )) } out <- c(out, list(chunk)) } } #' @rdname hidden_aliases #' @export setMethod( "dbFetchArrow", signature("DBIResultArrow"), dbFetchArrow_DBIResultArrow ) DBI/R/dbCanConnect_DBIDriver.R0000644000176200001440000000062714350241735015360 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/dbiDataType_list.R0000644000176200001440000000037514350241735014432 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/DBIConnector.R0000644000176200001440000000303115071142015013436 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' # 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/dbIsReadOnly.R0000644000176200001440000000075415071142015013515 0ustar liggesusers#' Is this DBMS object read only? #' #' This generic tests whether a database object is read only. #' #' @inheritParams dbGetInfo #' #' @template methods #' @templateVar method_name dbIsReadOnly #' #' @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/dbGetRowsAffected.R0000644000176200001440000000165015071142015014514 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. #' #' @inheritSection dbBind The command execution flow #' #' @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 #' @family command execution generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/SQLKeywords_DBIObject.R0000644000176200001440000000035415071142015015166 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/15-dbBind.R0000644000176200001440000002167415071142015012607 0ustar liggesusers#' Bind values to a parameterized/prepared statement #' #' @description #' For parametrized or prepared statements, #' the [dbSendQuery()], [dbSendQueryArrow()], and [dbSendStatement()] functions #' can be called with statements that contain placeholders for values. #' The `dbBind()` and `dbBindArrow()` functions bind these placeholders #' to actual values, #' and are intended to be called on the result set #' before calling [dbFetch()] or [dbFetchArrow()]. #' The values are passed to `dbBind()` as lists or data frames, #' and to `dbBindArrow()` as a stream #' created by [nanoarrow::as_nanoarrow_array_stream()]. #' #' `r lifecycle::badge('experimental')` #' #' `dbBindArrow()` is experimental, as are the other `*Arrow` functions. #' `dbSendQuery()` is compatible with `dbBindArrow()`, and `dbSendQueryArrow()` #' is compatible with `dbBind()`. #' #' @details #' \pkg{DBI} supports parametrized (or prepared) queries and statements #' via the `dbBind()` and `dbBindArrow()` generics. #' 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{RMariaDB} and \pkg{RSQLite} #' - `$1` (positional matching by index) in \pkg{RPostgres} and \pkg{RSQLite} #' - `:name` and `$name` (named matching) in \pkg{RSQLite} #' #' @section The data retrieval flow: #' #' This section gives a complete overview over the flow #' for the execution of queries that return tabular data as data frames. #' #' Most of this flow, except repeated calling of [dbBind()] or [dbBindArrow()], #' is implemented by [dbGetQuery()], which should be sufficient #' unless you want to access the results in a paged way #' or you have a parameterized query that you want to reuse. #' This flow requires an active connection established by [dbConnect()]. #' See also `vignette("dbi-advanced")` for a walkthrough. #' #' 1. Use [dbSendQuery()] to create a result set object of class #' [DBIResult-class]. #' 1. Optionally, bind query parameters with [dbBind()] or [dbBindArrow()]. #' This is required only if the query contains placeholders #' such as `?` or `$1`, depending on the database backend. #' 1. Optionally, use [dbColumnInfo()] to retrieve the structure of the result set #' without retrieving actual data. #' 1. Use [dbFetch()] to get the entire result set, a page of results, #' or the remaining rows. #' Fetching zero rows is also possible to retrieve the structure of the result set #' as a data frame. #' This step can be called multiple times. #' Only forward paging is supported, you need to cache previous pages #' if you need to navigate backwards. #' 1. Use [dbHasCompleted()] to tell when you're done. #' This method returns `TRUE` if no more rows are available for fetching. #' 1. Repeat the last four steps as necessary. #' 1. Use [dbClearResult()] to clean up the result set object. #' This step is mandatory even if no rows have been fetched #' or if an error has occurred during the processing. #' It is good practice to use [on.exit()] or [withr::defer()] #' to ensure that this step is always executed. #' #' @section The data retrieval flow for Arrow streams: #' #' This section gives a complete overview over the flow #' for the execution of queries that return tabular data as an Arrow stream. #' #' Most of this flow, except repeated calling of [dbBindArrow()] or [dbBind()], #' is implemented by [dbGetQueryArrow()], #' which should be sufficient #' unless you have a parameterized query that you want to reuse. #' This flow requires an active connection established by [dbConnect()]. #' See also `vignette("dbi-advanced")` for a walkthrough. #' #' 1. Use [dbSendQueryArrow()] to create a result set object of class #' [DBIResultArrow-class]. #' 1. Optionally, bind query parameters with [dbBindArrow()] or [dbBind()]. #' This is required only if the query contains placeholders #' such as `?` or `$1`, depending on the database backend. #' 1. Use [dbFetchArrow()] to get a data stream. #' 1. Repeat the last two steps as necessary. #' 1. Use [dbClearResult()] to clean up the result set object. #' This step is mandatory even if no rows have been fetched #' or if an error has occurred during the processing. #' It is good practice to use [on.exit()] or [withr::defer()] #' to ensure that this step is always executed. #' #' @section The command execution flow: #' #' This section gives a complete overview over the flow #' for the execution of SQL statements that have side effects #' such as stored procedures, inserting or deleting data, #' or setting database or connection options. #' Most of this flow, except repeated calling of [dbBindArrow()], #' is implemented by [dbExecute()], which should be sufficient #' for non-parameterized queries. #' This flow requires an active connection established by [dbConnect()]. #' See also `vignette("dbi-advanced")` for a walkthrough. #' #' 1. Use [dbSendStatement()] to create a result set object of class #' [DBIResult-class]. #' For some queries you need to pass `immediate = TRUE`. #' 1. Optionally, bind query parameters with[dbBind()] or [dbBindArrow()]. #' This is required only if the query contains placeholders #' such as `?` or `$1`, depending on the database backend. #' 1. Optionally, use [dbGetRowsAffected()] to retrieve the number #' of rows affected by the query. #' 1. Repeat the last two steps as necessary. #' 1. Use [dbClearResult()] to clean up the result set object. #' This step is mandatory even if no rows have been fetched #' or if an error has occurred during the processing. #' It is good practice to use [on.exit()] or [withr::defer()] #' to ensure that this step is always executed. #' #' @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 For `dbBind()`, a list of values, named or unnamed, #' or a data frame, with one element/column per query parameter. #' For `dbBindArrow()`, values as a nanoarrow stream, #' with one column per query parameter. #' @family DBIResult generics #' @family DBIResultArrow generics #' @family data retrieval generics #' @family command execution generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' # Data frame flow: #' 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) #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' #' # Arrow flow: #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "iris", iris) #' #' # Using the same query for different values #' iris_result <- dbSendQueryArrow(con, "SELECT * FROM iris WHERE [Petal.Width] > ?") #' dbBindArrow( #' iris_result, #' nanoarrow::as_nanoarrow_array_stream(data.frame(2.3, fix.empty.names = FALSE)) #' ) #' as.data.frame(dbFetchArrow(iris_result)) #' dbBindArrow( #' iris_result, #' nanoarrow::as_nanoarrow_array_stream(data.frame(3, fix.empty.names = FALSE)) #' ) #' as.data.frame(dbFetchArrow(iris_result)) #' dbClearResult(iris_result) #' #' # Executing the same statement with different values at once #' iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = $species") #' dbBindArrow(iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame( #' 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/dbFetch_DBIResultArrow.R0000644000176200001440000000057315071142015015424 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbFetch_DBIResultArrow <- function(res, n = -1, ...) { if (is.infinite(n)) { n <- -1 } if (n != -1) { stop("Cannot dbFetch() an Arrow result unless n = -1") } as.data.frame( dbFetchArrow(res, ...) ) } #' @rdname hidden_aliases #' @export setMethod("dbFetch", signature("DBIResultArrow"), dbFetch_DBIResultArrow) DBI/R/data-types.R0000644000176200001440000000005514350241735013253 0ustar liggesuserssetOldClass("difftime") setOldClass("AsIs") DBI/R/data.R0000644000176200001440000000162214350241735012112 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/dbSetDataMappings.R0000644000176200001440000000141115071142015014517 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/dbFetchArrowChunk.R0000644000176200001440000000310115071142015014526 0ustar liggesusers#' Fetch the next batch of records from a previously executed query as an Arrow object #' #' @description #' `r lifecycle::badge('experimental')` #' #' Fetch the next chunk of the result set and return it as an Arrow object. #' The chunk size is implementation-specific. #' Use [dbFetchArrow()] to fetch all results. #' #' @inheritSection dbBind The data retrieval flow for Arrow streams #' #' @template methods #' @templateVar method_name dbFetchArrowChunk #' #' @inherit DBItest::spec_arrow_fetch_arrow_chunk return #' @inheritSection DBItest::spec_arrow_fetch_arrow_chunk Failure modes #' @inheritSection DBItest::spec_arrow_fetch_arrow_chunk Specification #' #' @param res An object inheriting from [DBI::DBIResultArrow][DBIResultArrow-class], #' created by [dbSendQueryArrow()]. #' @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 DBIResultArrow generics #' @family data retrieval generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' #' # Fetch all results #' rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") #' dbHasCompleted(rs) #' as.data.frame(dbFetchArrowChunk(rs)) #' dbHasCompleted(rs) #' as.data.frame(dbFetchArrowChunk(rs)) #' dbClearResult(rs) #' #' dbDisconnect(con) setGeneric("dbFetchArrowChunk", def = function(res, ...) { standardGeneric("dbFetchArrowChunk") }) DBI/R/dbListTables.R0000644000176200001440000000152515071142015013547 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbSendStatement_DBIConnection_character.R0000644000176200001440000000046715071142015020775 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/dbGetRowCount_DBIResultArrow.R0000644000176200001440000000040415071142015016604 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbGetRowCount_DBIResultArrow <- function(res, ...) { dbGetRowCount(res@result, ...) } #' @rdname hidden_aliases #' @export setMethod( "dbGetRowCount", signature("DBIResultArrow"), dbGetRowCount_DBIResultArrow ) DBI/R/dbQuoteIdentifier.R0000644000176200001440000000263715071142015014606 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 DBIConnection 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/01-DBIObject.R0000644000176200001440000000273214602466070013150 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/dbListFields_DBIConnection_character.R0000644000176200001440000000043715071142015020256 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/dbGetStatement.R0000644000176200001440000000143415071142015014104 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 #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/12-dbCreateTable.R0000644000176200001440000000336415144400570014103 0ustar liggesusers#' Create a table in the database #' #' The default `dbCreateTable()` method calls [sqlCreateTable()] and #' [dbExecute()]. #' Use [dbCreateTableArrow()] to create a table from an Arrow schema. #' #' 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 #' #' @template methods #' @templateVar method_name dbCreateTable #' #' @family DBIConnection generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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) { otel_local_active_span( "CREATE TABLE", conn, label = .dbi_get_collection_name(name, conn), attributes = list( db.collection.name = .dbi_get_collection_name(name, conn), db.operation.name = "CREATE TABLE" ) ) standardGeneric("dbCreateTable") } ) DBI/R/show_Id.R0000644000176200001440000000035114537352607012603 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/fetch.R0000644000176200001440000000022015071142015012253 0ustar liggesusers#' @rdname dbFetch #' @export setGeneric( "fetch", def = function(res, n = -1, ...) standardGeneric("fetch"), valueClass = "data.frame" ) DBI/R/dbGetInfo_DBIResult.R0000644000176200001440000000055014350241735014716 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/dbiDataType.R0000644000176200001440000000012115071142015013354 0ustar liggesuserssetGeneric("dbiDataType", def = function(x, ...) standardGeneric("dbiDataType")) DBI/R/dbExecute_DBIConnection_character.R0000644000176200001440000000054415071142015017615 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/dbiDataType_difftime.R0000644000176200001440000000020114350241735015232 0ustar liggesusers#' @usage NULL dbiDataType_difftime <- function(x) "TIME" setMethod("dbiDataType", signature("difftime"), dbiDataType_difftime) DBI/R/dbReadTableArrow.R0000644000176200001440000000251415144400570014342 0ustar liggesusers#' Read database tables as Arrow objects #' #' @description #' `r lifecycle::badge('experimental')` #' #' Reads a database table as an Arrow object. #' Use [dbReadTable()] instead to obtain a data frame. #' #' @details #' This function returns an Arrow object. #' Convert it to a data frame with [as.data.frame()] or #' use [dbReadTable()] to obtain a data frame. #' #' @template methods #' @templateVar method_name dbReadTableArrow #' #' @inherit DBItest::spec_arrow_read_table_arrow return #' @inheritSection DBItest::spec_arrow_read_table_arrow Failure modes #' @inheritSection DBItest::spec_arrow_read_table_arrow Specification #' #' @inheritParams dbGetQuery #' @inheritParams dbReadTable #' @family DBIConnection generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' # Read data as Arrow table #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars[1:10, ]) #' dbReadTableArrow(con, "mtcars") #' #' dbDisconnect(con) setGeneric("dbReadTableArrow", def = function(conn, name, ...) { require_arrow() otel_local_active_span( "dbReadTableArrow", conn, label = .dbi_get_collection_name(name, conn), attributes = list(db.collection.name = .dbi_get_collection_name(name, conn)) ) standardGeneric("dbReadTableArrow") }) DBI/R/dbiDataType_AsIs.R0000644000176200001440000000022514350241735014310 0ustar liggesusersdbiDataType_AsIs <- function(x) { oldClass(x) <- oldClass(x)[-1] dbiDataType(x) } setMethod("dbiDataType", signature("AsIs"), dbiDataType_AsIs) DBI/R/dbReadTable_DBIConnection_Id.R0000644000176200001440000000044515071142015016436 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/sqlParseVariables.R0000644000176200001440000000214315071142015014613 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/isSQLKeyword_DBIObject_character.R0000644000176200001440000000052515071142015017353 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/dbFetchArrow.R0000644000176200001440000000260115071142015013541 0ustar liggesusers#' Fetch records from a previously executed query as an Arrow object #' #' @description #' `r lifecycle::badge('experimental')` #' #' Fetch the result set and return it as an Arrow object. #' Use [dbFetchArrowChunk()] to fetch results in chunks. #' #' @inheritSection dbBind The data retrieval flow for Arrow streams #' #' @template methods #' @templateVar method_name dbFetchArrow #' #' @inherit DBItest::spec_arrow_fetch_arrow return #' @inheritSection DBItest::spec_arrow_fetch_arrow Failure modes #' @inheritSection DBItest::spec_arrow_fetch_arrow Specification #' #' @param res An object inheriting from [DBI::DBIResultArrow][DBIResultArrow-class], #' created by [dbSendQueryArrow()]. #' @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 DBIResultArrow generics #' @family data retrieval generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE) #' con <- dbConnect(RSQLite::SQLite(), ":memory:") #' #' dbWriteTable(con, "mtcars", mtcars) #' #' # Fetch all results #' rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") #' as.data.frame(dbFetchArrow(rs)) #' dbClearResult(rs) #' #' dbDisconnect(con) setGeneric("dbFetchArrow", def = function(res, ...) { standardGeneric("dbFetchArrow") }) DBI/R/dbHasCompleted.R0000644000176200001440000000216115071142015014046 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. #' #' @inheritSection dbBind The data retrieval flow #' #' @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 #' @family DBIResultArrow generics #' @family data retrieval generics #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/25-dbBindArrow.R0000644000176200001440000000017615071142015013615 0ustar liggesusers#' @rdname dbBind #' @export setGeneric("dbBindArrow", def = function(res, params, ...) { standardGeneric("dbBindArrow") }) DBI/R/dbGetQuery_DBIConnection_character.R0000644000176200001440000000063715071142015017763 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/dbBindArrow_DBIResultArrowDefault.R0000644000176200001440000000051415071142015017562 0ustar liggesusers#' @rdname hidden_aliases #' @usage NULL dbBindArrow_DBIResultArrowDefault <- function(res, params, ...) { dbBind(res@result, params = param_stream_to_list(params), ...) invisible(res) } #' @rdname hidden_aliases #' @export setMethod( "dbBindArrow", signature("DBIResultArrowDefault"), dbBindArrow_DBIResultArrowDefault ) DBI/R/sqlData.R0000644000176200001440000000206315071142015012562 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: #' #' - Converts factors to characters #' - Quotes all strings with [dbQuoteIdentifier()] #' - Converts all columns to strings with [dbQuoteLiteral()] #' - Replaces NA with NULL #' #' @inheritParams sqlCreateTable #' @inheritParams rownames #' @param value A data frame #' #' @template methods #' @templateVar method_name sqlData #' #' @export #' @examplesIf requireNamespace("RSQLite", quietly = TRUE) #' 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/vignettes/0000755000176200001440000000000015147357131012667 5ustar liggesusersDBI/vignettes/DBI-arrow.Rmd0000644000176200001440000001517214602466070015065 0ustar liggesusers--- title: "Using DBI with Arrow" author: "Kirill Müller" date: "25/12/2023" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using DBI with Arrow} %\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, 6)) if (nrow(x) > 6) { cat("Showing 6 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 want to leverage [Apache Arrow](https://arrow.apache.org/) for accessing and manipulating data on databases. See `vignette("DBI", package = "DBI")` and `vignette("DBI-advanced", package = "DBI")` for tutorials on accessing data using R's data frames instead of Arrow's structures. ## Rationale Apache Arrow is > a cross-language development platform for in-memory analytics, suitable for large and huge data, with support for out-of-memory operation. Arrow is also a data exchange format, the data types covered by Arrow align well with the data types supported by SQL databases. DBI 1.2.0 introduced support for Arrow as a format for exchanging data between R and databases. The aim is to: - accelerate data retrieval and loading, by using fewer costly data conversions; - better support reading and summarizing data from a database that is larger than memory; - provide better type fidelity with workflows centered around Arrow. This allows existing code to be used with Arrow, and it allows new code to be written that is more efficient and more flexible than code that uses R's data frames. The interface is built around the {nanoarrow} R package, with `nanoarrow::as_nanoarrow_array` and `nanoarrow::as_nanoarrow_array_stream` as fundamental data structures. ## New classes and generics DBI 1.2.0 introduces new classes and generics for working with Arrow data: - `dbReadTableArrow()` - `dbWriteTableArrow()` - `dbCreateTableArrow()` - `dbAppendTableArrow()` - `dbGetQueryArrow()` - `dbSendQueryArrow()` - `dbBindArrow()` - `dbFetchArrow()` - `dbFetchArrowChunk()` - `DBIResultArrow-class` - `DBIResultArrowDefault-class` Compatibility is important for DBI, and implementing new generics and classes greatly reduces the risk of breaking existing code. The DBI package comes with a fully functional fallback implementation for all existing DBI backends. The fallback is not improving performance, but it allows existing code to be used with Arrow before switching to a backend with native Arrow support. Backends with native support, like the [adbi](https://adbi.r-dbi.org/) package, implement the new generics and classes for direct support and improved performance. In the remainder of this tutorial, we will demonstrate the new generics and classes using the RSQLite package. SQLite is an in-memory database, this code does not need a database server to be installed and running. ## Prepare We start by setting up a database connection and creating a table with some data, using the original `dbWriteTable()` method. ```{r} library(DBI) con <- dbConnect(RSQLite::SQLite()) data <- data.frame( a = 1:3, b = 4.5, c = "five" ) dbWriteTable(con, "tbl", data) ``` ## Read all rows from a table The `dbReadTableArrow()` method reads all rows from a table into an Arrow stream, similarly to `dbReadTable()`. Arrow objects implement the `as.data.frame()` method, so we can convert the stream to a data frame. ```{r} stream <- dbReadTableArrow(con, "tbl") stream as.data.frame(stream) ``` ## Run queries The `dbGetQueryArrow()` method runs a query and returns the result as an Arrow stream. This stream can be turned into an `arrow::RecordBatchReader` object and processed further, without bringing it into R. ```{r} stream <- dbGetQueryArrow(con, "SELECT COUNT(*) AS n FROM tbl WHERE a < 3") stream path <- tempfile(fileext = ".parquet") arrow::write_parquet(arrow::as_record_batch_reader(stream), path) arrow::read_parquet(path) ``` ## Prepared queries The `dbGetQueryArrow()` method supports prepared queries, using the `params` argument which accepts a data frame or a list. ```{r} params <- data.frame(a = 3L) stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) params <- data.frame(a = c(2L, 4L)) # Equivalent to dbBind() stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) ``` ## Manual flow For the manual flow, use `dbSendQueryArrow()` to send a query to the database, and `dbFetchArrow()` to fetch the result. This also allows using the new `dbBindArrow()` method to bind data in Arrow format to a prepared query. Result objects must be cleared with `dbClearResult()`. ```{r} rs <- dbSendQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a") in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 2L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 3L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1:4L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) dbClearResult(rs) ``` ## Writing data Streams returned by `dbGetQueryArrow()` and `dbReadTableArrow()` can be written to a table using `dbWriteTableArrow()`. ```{r} stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbWriteTableArrow(con, "tbl_new", stream) dbReadTable(con, "tbl_new") ``` ## Appending data For more control over the writing process, use `dbCreateTableArrow()` and `dbAppendTableArrow()`. ```{r} stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbCreateTableArrow(con, "tbl_split", stream) dbAppendTableArrow(con, "tbl_split", stream) stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a >= 3") dbAppendTableArrow(con, "tbl_split", stream) dbReadTable(con, "tbl_split") ``` ## Conclusion Do not forget to disconnect from the database when done. ```{r} dbDisconnect(con) ``` That concludes the major features of DBI's new Arrow interface. For more details on the library functions covered in this tutorial see the DBI specification at `vignette("spec", package = "DBI")`. See the [adbi](https://adbi.r-dbi.org/) package for a backend with native Arrow support, and [nanoarrow](https://github.com/apache/arrow-nanoarrow) and [arrow](https://arrow.apache.org/docs/r/) for packages to work with the Arrow format. DBI/vignettes/DBI-1.Rmd0000644000176200001440000006004715144403222014064 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](https://www.unixodbc.org/)). Python’s Database Application Programming Interface ([www.python.org](https://wiki.python.org/python/DatabaseProgramming.html)). 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/spec.md0000644000176200001440000045675615144400600014155 0ustar liggesusers## 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 ``` r RSQLite::SQLite() ``` ## Determine the SQL data type of an object This section describes the behavior of the following method: ``` r 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. ### 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 ``` r 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: ``` r 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. ### 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 ``` r # 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: ``` r dbDisconnect(conn, ...) ``` ### Description This closes the connection, discards all pending work, and frees resources (e.g., memory, sockets). ### 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. At least one warning is issued immediately when calling `dbDisconnect()` on an already disconnected or invalid connection. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbDisconnect(con) ``` ## Execute a query on a given database connection This section describes the behavior of the following method: ``` r 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()`. Use `dbSendQueryArrow()` or `dbGetQueryArrow()` instead to retrieve the results as an Arrow object. ### 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()`. ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r 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: ``` r 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. ### 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. Passing `n = NA` is supported and returns an arbitrary number of rows (at least one) as specified by the driver, but at most the remaining rows in the result set. ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r 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: ``` r dbClearResult(res, ...) ``` ### Description Frees all resources (local and remote) associated with a result set. This step is mandatory for all objects obtained by calling `dbSendQuery()` or `dbSendStatement()`. ### Arguments | | | |-------|---------------------------------------| | `res` | An object inheriting from DBIResult. | | `...` | Other arguments passed on to methods. | ### Value `dbClearResult()` returns `TRUE`, invisibly, for result sets obtained from `dbSendQuery()`, `dbSendStatement()`, or `dbSendQueryArrow()`, ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### The command execution flow This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of `dbBindArrow()`, is implemented by `dbExecute()`, which should be sufficient for non-parameterized queries. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendStatement()` to create a result set object of class DBIResult. For some queries you need to pass `immediate = TRUE`. 2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows affected by the query. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### Failure modes An attempt to close an already closed result set issues a warning for `dbSendQuery()`, `dbSendStatement()`, and `dbSendQueryArrow()`, ### 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 ``` r 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 methods: ``` r dbBind(res, params, ...) dbBindArrow(res, params, ...) ``` ### Description For parametrized or prepared statements, the `dbSendQuery()`, `dbSendQueryArrow()`, and `dbSendStatement()` functions can be called with statements that contain placeholders for values. The `dbBind()` and `dbBindArrow()` functions bind these placeholders to actual values, and are intended to be called on the result set before calling `dbFetch()` or `dbFetchArrow()`. The values are passed to `dbBind()` as lists or data frames, and to `dbBindArrow()` as a stream created by `nanoarrow::as_nanoarrow_array_stream()`. [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) `dbBindArrow()` is experimental, as are the other `⁠*Arrow⁠` functions. `dbSendQuery()` is compatible with `dbBindArrow()`, and `dbSendQueryArrow()` is compatible with `dbBind()`. ### Arguments | | | |----|----| | `res` | An object inheriting from DBIResult. | | `params` | For `dbBind()`, a list of values, named or unnamed, or a data frame, with one element/column per query parameter. For `dbBindArrow()`, values as a nanoarrow stream, with one column per query parameter. | | `...` | Other arguments passed on to methods. | ### Details DBI supports parametrized (or prepared) queries and statements via the `dbBind()` and `dbBindArrow()` generics. 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 RMariaDB 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()` or `dbSendQueryArrow()` and also for data manipulation statements issued by `dbSendStatement()`. ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### The data retrieval flow for Arrow streams This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of `dbBindArrow()` or `dbBind()`, is implemented by `dbGetQueryArrow()`, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQueryArrow()` to create a result set object of class DBIResultArrow. 2. Optionally, bind query parameters with `dbBindArrow()` or `dbBind()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Use `dbFetchArrow()` to get a data stream. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### The command execution flow This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of `dbBindArrow()`, is implemented by `dbExecute()`, which should be sufficient for non-parameterized queries. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendStatement()` to create a result set object of class DBIResult. For some queries you need to pass `immediate = TRUE`. 2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows affected by the query. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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()`, `dbSendQueryArrow()` 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()` or `dbBindArrow()` have been called, the returned result set object has the following behavior: - `dbFetch()` raises an error (for `dbSendQuery()` and `dbSendQueryArrow()`) - `dbGetRowCount()` returns zero (for `dbSendQuery()` and `dbSendQueryArrow()`) - `dbGetRowsAffected()` returns an integer `NA` (for `dbSendStatement()`) - `dbIsValid()` returns `TRUE` - `dbHasCompleted()` returns `FALSE` 2. Call `dbBind()` or `dbBindArrow()`: - For `dbBind()`, the `params` argument must be a list where all elements have the same lengths and contain values supported by the backend. A data.frame is internally stored as such a list. - For `dbBindArrow()`, the `params` argument must be a nanoarrow array stream, with one column per query parameter. 3. Retrieve the data or the number of affected rows from the `DBIResult` object. - For queries issued by `dbSendQuery()` or `dbSendQueryArrow()`, 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 ``` r # Data frame flow: 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) # Arrow flow: con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "iris", iris) # Using the same query for different values iris_result <- dbSendQueryArrow(con, "SELECT * FROM iris WHERE [Petal.Width] > ?") dbBindArrow( iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(2.3, fix.empty.names = FALSE)) ) as.data.frame(dbFetchArrow(iris_result)) dbBindArrow( iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(3, fix.empty.names = FALSE)) ) as.data.frame(dbFetchArrow(iris_result)) dbClearResult(iris_result) # Executing the same statement with different values at once iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = \$species") dbBindArrow(iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame( species = c("setosa", "versicolor", "unknown") ))) dbGetRowsAffected(iris_result) dbClearResult(iris_result) nrow(dbReadTable(con, "iris")) dbDisconnect(con) ``` ## Retrieve results from a query This section describes the behavior of the following method: ``` r 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 freed by `dbClearResult()`. For retrieving chunked/paged results or for passing query parameters, see `dbSendQuery()`, in particular the "The data retrieval flow" section. For retrieving results as an Arrow object, see `dbGetQueryArrow()`. ### 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 or data manipulation queries like `⁠INSERT INTO ... RETURNING ...⁠`). 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 ``` r 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: ``` r 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()`. ### 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()`. ### The command execution flow This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of `dbBindArrow()`, is implemented by `dbExecute()`, which should be sufficient for non-parameterized queries. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendStatement()` to create a result set object of class DBIResult. For some queries you need to pass `immediate = TRUE`. 2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows affected by the query. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r 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) ``` ## Change database state This section describes the behavior of the following method: ``` r 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 freed by `dbClearResult()`. For passing query parameters, see `dbBind()`, in particular the "The command execution flow" section. ### 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, or a data manipulation query that also returns a result set such as `⁠INSERT INTO ... RETURNING ...⁠`, 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 ``` r 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: ``` r 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. ### 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 ``` r # 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 literal values This section describes the behavior of the following method: ``` r dbQuoteLiteral(conn, x, ...) ``` ### 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. ### Arguments | | | |--------|-------------------------------------------------------| | `conn` | A DBIConnection object, as returned by `dbConnect()`. | | `x` | A vector to quote as string. | | `...` | Other arguments passed on to methods. | ### Value `dbQuoteLiteral()` returns an object that can be coerced to 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 `dbQuoteLiteral()` 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 list for the `x` argument raises an error. ### Specification The returned expression can be used in a `⁠SELECT ...⁠` query, and the value of `dbGetQuery(paste0("SELECT ", dbQuoteLiteral(x)))[[1]]` must be equal to `x` for any scalar integer, numeric, string, and logical. If `x` is `NA`, the result must merely satisfy `is.na()`. The literals `"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 ``` r # 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)) ``` ## Quote identifiers This section describes the behavior of the following method: ``` r 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()`. ### 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 ``` r # 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)) ``` ## Unquote identifiers This section describes the behavior of the following method: ``` r dbUnquoteIdentifier(conn, x, ...) ``` ### Description Call this method to convert a SQL object created by `dbQuoteIdentifier()` back to a list of Id objects. ### Arguments | | | |--------|-------------------------------------------------------| | `conn` | A DBIConnection object, as returned by `dbConnect()`. | | `x` | An SQL or Id object. | | `...` | Other arguments passed on to methods. | ### Value `dbUnquoteIdentifier()` returns a list of objects of the same length as the input. For an empty vector, this function returns a length-0 object. The names of the input argument are preserved in the output. If `x` is a value returned by `dbUnquoteIdentifier()`, calling `dbUnquoteIdentifier(..., dbQuoteIdentifier(..., x))` returns `list(x)`. If `x` is an object of class Id, calling `dbUnquoteIdentifier(..., x)` returns `list(x)`. (For backends it may be most convenient to return Id objects to achieve this behavior, but this is not required.) Plain character vectors can also be passed to `dbUnquoteIdentifier()`. ### Failure modes An error is raised if a character vectors with a missing value is passed as the `x` argument. ### Specification For any character vector of length one, quoting (with `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 `SQL()` and then quoting via `dbQuoteIdentifier()` gives the same result as just quoting the string. Similarly, unquoting expressions of the form `SQL("schema.table")` and then quoting gives the same result as quoting the identifier constructed by `Id("schema", "table")`. ### Examples ``` r # 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", "Schema", "Table")) # Quoting and unquoting are inverses dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]] ) dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), Id("Schema", "Table"))[[1]] ) ``` ## Read database tables as data frames This section describes the behavior of the following method: ``` r 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. Use `dbReadTableArrow()` instead to obtain an Arrow object. ### 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 ### Details This function returns a data frame. Use `dbReadTableArrow()` to obtain an Arrow object. ### Value `dbReadTable()` returns a data frame that contains the complete data from the remote table, effectively the result of calling `dbGetQuery()` with `⁠SELECT * FROM ⁠`. 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 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 ``` r 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: ``` r 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. ### 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 expects a data frame. Use `dbWriteTableArrow()` to write an Arrow object. This function is useful if you want to create and load a table at the same time. Use `dbAppendTable()` or `dbAppendTableArrow()` for appending data to an existing table, `dbCreateTable()` or `dbCreateTableArrow()` for creating a table, and `dbExistsTable()` and `dbRemoveTable()` for overwriting tables. DBI only standardizes writing data frames with `dbWriteTable()`. 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 ``` r 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") ``` ## Create a table in the database This section describes the behavior of the following method: ``` r dbCreateTable(conn, name, fields, ..., row.names = NULL, temporary = FALSE) ``` ### Description The default `dbCreateTable()` method calls `sqlCreateTable()` and `dbExecute()`. Use `dbCreateTableArrow()` to create a table from an Arrow schema. ### 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"')

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().

...

Other parameters passed on to methods.

row.names

Must be NULL.

temporary

If TRUE, will generate a temporary table.

### Additional arguments The following arguments are not part of the `dbCreateTable()` generic (to improve compatibility across backends) but are part of the DBI specification: - `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: `dbCreateTable()` 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 can be: - a data frame, - a named list of SQL types 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, and spaces can also be used for table names and column names, if the database supports non-syntactic identifiers. The `row.names` argument must be missing or `NULL`, the default value. All other values for the `row.names` argument (in particular `TRUE`, `NA`, and a string) raise an error. ### Details 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. ### Value `dbCreateTable()` returns `TRUE`, invisibly. ### 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 `name` cannot be processed with `dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values for the `row.names` and `temporary` arguments (non-scalars, unsupported data types, `NA`, incompatible values, duplicate names) also raise an error. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) ``` ## Insert rows into a table This section describes the behavior of the following method: ``` r dbAppendTable(conn, name, value, ..., row.names = NULL) ``` ### Description 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. Use `dbAppendTableArrow()` to append data from an Arrow stream. ### 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.

row.names

Must be NULL.

### Details 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. ### Value `dbAppendTable()` returns a scalar numeric. ### Failure modes If the table does not exist, or the new data in `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 `name` cannot be processed with `dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values for the `row.names` argument (non-scalars, unsupported data types, `NA`) also raise an error. Passing a `value` argument different to `NULL` to the `row.names` argument (in particular `TRUE`, `NA`, and a string) raises an error. ### 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 `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 non-empty strings) - factor (returned as character, with a warning) - 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 `name` argument is processed as follows, to support databases that allow non-syntactic names for their objects: - If an unquoted table name as string: `dbAppendTable()` will do the quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)` - If the result of a call to `dbQuoteIdentifier()`: no more quoting is done to support databases that allow non-syntactic names for their objects: The `row.names` argument must be `NULL`, the default value. Row names are ignored. The `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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbAppendTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) ``` ## Remove a table from the database This section describes the behavior of the following method: ``` r dbRemoveTable(conn, name, ...) ``` ### Description Remove a remote table (e.g., created by `dbWriteTable()`) from the database. ### 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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbRemoveTable(con, "iris") dbExistsTable(con, "iris") dbDisconnect(con) ``` ## List remote tables This section describes the behavior of the following method: ``` r 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. ### 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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListTables(con) dbWriteTable(con, "mtcars", mtcars) dbListTables(con) dbDisconnect(con) ``` ## List field names of a remote table This section describes the behavior of the following method: ``` r dbListFields(conn, name, ...) ``` ### Description Returns the field names of a remote table as a character vector. ### 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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbListFields(con, "mtcars") dbDisconnect(con) ``` ## Does a table exist? This section describes the behavior of the following method: ``` r dbExistsTable(conn, name, ...) ``` ### Description Returns if a table given by name exists in the database. ### 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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbDisconnect(con) ``` ## List remote objects This section describes the behavior of the following method: ``` r dbListObjects(conn, prefix = NULL, ...) ``` ### 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 RMariaDB and 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. ### Arguments | | | |----|----| | `conn` | A DBIConnection object, as returned by `dbConnect()`. | | `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. | | `...` | Other parameters passed on to methods. | ### Value `dbListObjects()` returns a data frame with columns `table` and `is_prefix` (in that order), optionally with other columns with a dot (`.`) prefix. The `table` column is of type list. Each object in this list is suitable for use as argument in `dbQuoteIdentifier()`. The `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 `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 `dbQuoteIdentifier()`. ### Failure modes An error is raised when calling this method for a closed or invalid connection. ### Specification The `prefix` column indicates if the `table` value refers to a table or a prefix. For a call with the default `prefix = NULL`, the `table` values that have `is_prefix == FALSE` correspond to the tables returned from `dbListTables()`, The `table` object can be quoted with `dbQuoteIdentifier()`. The result of quoting can be passed to `dbUnquoteIdentifier()`. (For backends it may be convenient to use the Id class, but this is not required.) Values in `table` column that have `is_prefix == TRUE` can be passed as the `prefix` argument to another call to `dbListObjects()`. For the data frame returned from a `dbListObject()` call with the `prefix` argument set, all `table` values where `is_prefix` is `FALSE` can be used in a call to `dbExistsTable()` which returns `TRUE`. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListObjects(con) dbWriteTable(con, "mtcars", mtcars) dbListObjects(con) dbDisconnect(con) ``` ## Is this DBMS object still valid? This section describes the behavior of the following method: ``` r dbIsValid(dbObj, ...) ``` ### Description This generic tests whether a database object is still valid (i.e. it hasn't been disconnected or cleared). ### 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 ``` r 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: ``` r 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. ### 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`. ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r 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: ``` r dbGetStatement(res, ...) ``` ### Description Returns the statement that was passed to `dbSendQuery()` or `dbSendStatement()`. ### 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 ``` r 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: ``` r dbGetRowCount(res, ...) ``` ### Description Returns the total number of rows actually fetched with calls to `dbFetch()` for this result set. ### 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 ``` r 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: ``` r dbGetRowsAffected(res, ...) ``` ### Description This method returns the number of rows that were added, deleted, or updated by a data manipulation statement. ### 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()`. `NA_integer_` or `NA_numeric_` are allowed if the number of rows affected is not known. For queries issued with `dbSendQuery()`, zero is returned before and after the call to `dbFetch()`. `NA` values are not allowed. ### The command execution flow This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of `dbBindArrow()`, is implemented by `dbExecute()`, which should be sufficient for non-parameterized queries. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendStatement()` to create a result set object of class DBIResult. For some queries you need to pass `immediate = TRUE`. 2. Optionally, bind query parameters with`dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbGetRowsAffected()` to retrieve the number of rows affected by the query. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### Failure modes Attempting to get the rows affected for a result set cleared with `dbClearResult()` gives an error. ### Examples ``` r 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: ``` r 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. ### The data retrieval flow This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of `dbBind()` or `dbBindArrow()`, is implemented by `dbGetQuery()`, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQuery()` to create a result set object of class DBIResult. 2. Optionally, bind query parameters with `dbBind()` or `dbBindArrow()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Optionally, use `dbColumnInfo()` to retrieve the structure of the result set without retrieving actual data. 4. Use `dbFetch()` to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. 5. Use `dbHasCompleted()` to tell when you're done. This method returns `TRUE` if no more rows are available for fetching. 6. Repeat the last four steps as necessary. 7. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r 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: ``` r 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. ### 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 ``` r 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: ``` r 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 or 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 ``` r 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 current 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) ``` ## Get DBMS metadata This section describes the behavior of the following method: ``` r dbGetInfo(dbObj, ...) ``` ### Description Retrieves information on objects of class DBIDriver, DBIConnection or DBIResult. ### Arguments | | | |----|----| | `dbObj` | An object inheriting from DBIObject, i.e. DBIDriver, DBIConnection, or a DBIResult | | `...` | Other arguments to methods. | ### Value For objects of class DBIDriver, `dbGetInfo()` returns a named list that contains at least the following components: - `driver.version`: the package version of the DBI backend, - `client.version`: the version of the DBMS client library. For objects of class DBIConnection, `dbGetInfo()` returns a named list that contains at least the following components: - `db.version`: version of the database server, - `dbname`: database name, - `username`: username to connect to the database, - `host`: hostname of the database server, - `port`: port on the database server. It must not contain a `password` component. Components that are not applicable should be set to `NA`. For objects of class DBIResult, `dbGetInfo()` returns a named list that contains at least the following components: - `statatment`: the statement used with `dbSendQuery()` or `dbExecute()`, as returned by `dbGetStatement()`, - `row.count`: the number of rows fetched so far (for queries), as returned by `dbGetRowCount()`, - `rows.affected`: the number of rows affected (for statements), as returned by `dbGetRowsAffected()` - `has.completed`: a logical that indicates if the query or statement has completed, as returned by `dbHasCompleted()`. ### 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()`. ### Examples ``` r dbGetInfo(RSQLite::SQLite()) ``` ## Execute a query on a given database connection for retrieval via Arrow This section describes the behavior of the following method: ``` r dbSendQueryArrow(conn, statement, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) The `dbSendQueryArrow()` 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 `dbFetchArrow()` method, and then you must call `dbClearResult()` when you finish fetching the records you need. For interactive use, you should almost always prefer `dbGetQueryArrow()`. Use `dbSendQuery()` or `dbGetQuery()` instead to retrieve the results as a data frame. ### 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 `dbSendQueryArrow()` 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. ### Value `dbSendQueryArrow()` returns an S4 object that inherits from DBIResultArrow. The result set can be used with `dbFetchArrow()` to extract records. Once you have finished using a result, make sure to clear it with `dbClearResult()`. ### The data retrieval flow for Arrow streams This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of `dbBindArrow()` or `dbBind()`, is implemented by `dbGetQueryArrow()`, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQueryArrow()` to create a result set object of class DBIResultArrow. 2. Optionally, bind query parameters with `dbBindArrow()` or `dbBind()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Use `dbFetchArrow()` to get a data stream. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### 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 ``` r # Retrieve data as arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") dbFetchArrow(rs) dbClearResult(rs) dbDisconnect(con) ``` ## Fetch records from a previously executed query as an Arrow object This section describes the behavior of the following method: ``` r dbFetchArrow(res, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) Fetch the result set and return it as an Arrow object. Use `dbFetchArrowChunk()` to fetch results in chunks. ### Arguments | | | |----|----| | `res` | An object inheriting from DBIResultArrow, created by `dbSendQueryArrow()`. | | `...` | Other arguments passed on to methods. | ### Value `dbFetchArrow()` always returns an object coercible to 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. ### The data retrieval flow for Arrow streams This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of `dbBindArrow()` or `dbBind()`, is implemented by `dbGetQueryArrow()`, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQueryArrow()` to create a result set object of class DBIResultArrow. 2. Optionally, bind query parameters with `dbBindArrow()` or `dbBind()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Use `dbFetchArrow()` to get a data stream. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### Failure modes An attempt to fetch from a closed result set raises an error. ### Specification Fetching multi-row queries with one or more columns by default returns the entire result. The object returned by `dbFetchArrow()` can also be passed to `nanoarrow::as_nanoarrow_array_stream()` to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) # Fetch all results rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") as.data.frame(dbFetchArrow(rs)) dbClearResult(rs) dbDisconnect(con) ``` ## Fetch the next batch of records from a previously executed query as an Arrow object This section describes the behavior of the following method: ``` r dbFetchArrowChunk(res, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) Fetch the next chunk of the result set and return it as an Arrow object. The chunk size is implementation-specific. Use `dbFetchArrow()` to fetch all results. ### Arguments | | | |----|----| | `res` | An object inheriting from DBIResultArrow, created by `dbSendQueryArrow()`. | | `...` | Other arguments passed on to methods. | ### Value `dbFetchArrowChunk()` always returns an object coercible to 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. ### The data retrieval flow for Arrow streams This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of `dbBindArrow()` or `dbBind()`, is implemented by `dbGetQueryArrow()`, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by `dbConnect()`. See also `vignette("dbi-advanced")` for a walkthrough. 1. Use `dbSendQueryArrow()` to create a result set object of class DBIResultArrow. 2. Optionally, bind query parameters with `dbBindArrow()` or `dbBind()`. This is required only if the query contains placeholders such as `⁠?⁠` or `⁠\$1⁠`, depending on the database backend. 3. Use `dbFetchArrow()` to get a data stream. 4. Repeat the last two steps as necessary. 5. Use `dbClearResult()` to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use `on.exit()` or `withr::defer()` to ensure that this step is always executed. ### Failure modes An attempt to fetch from a closed result set raises an error. ### Specification Fetching multi-row queries with one or more columns returns the next chunk. The size of the chunk is implementation-specific. The object returned by `dbFetchArrowChunk()` can also be passed to `nanoarrow::as_nanoarrow_array()` to create a nanoarrow array object. The chunk size is implementation-specific. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) # Fetch all results rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") dbHasCompleted(rs) as.data.frame(dbFetchArrowChunk(rs)) dbHasCompleted(rs) as.data.frame(dbFetchArrowChunk(rs)) dbClearResult(rs) dbDisconnect(con) ``` ## Retrieve results from a query as an Arrow object This section describes the behavior of the following method: ``` r dbGetQueryArrow(conn, statement, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) Returns the result of a query as an Arrow object. `dbGetQueryArrow()` comes with a default implementation (which should work with most backends) that calls `dbSendQueryArrow()`, then `dbFetchArrow()`, ensuring that the result is always freed by `dbClearResult()`. For passing query parameters, see `dbSendQueryArrow()`, in particular the "The data retrieval flow for Arrow streams" section. For retrieving results as a data frame, see `dbGetQuery()`. ### 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 `dbGetQueryArrow()` 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" and "Value" sections for details on their usage. 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 or data manipulation queries like `⁠INSERT INTO ... RETURNING ...⁠`). To execute a stored procedure that does not return a result set, use `dbExecute()`. Some backends may support data manipulation statements through this method. However, callers are strongly advised to use `dbExecute()` for data manipulation statements. ### Value `dbGetQueryArrow()` always returns an object coercible to 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. The object returned by `dbGetQueryArrow()` can also be passed to `nanoarrow::as_nanoarrow_array_stream()` to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific. ### Examples ``` r # Retrieve data as arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbGetQueryArrow(con, "SELECT * FROM mtcars") dbDisconnect(con) ``` ## Read database tables as Arrow objects This section describes the behavior of the following method: ``` r dbReadTableArrow(conn, name, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) Reads a database table as an Arrow object. Use `dbReadTable()` instead to obtain a 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"')

...

Other parameters passed on to methods.

### Details This function returns an Arrow object. Convert it to a data frame with `as.data.frame()` or use `dbReadTable()` to obtain a data frame. ### Value `dbReadTableArrow()` returns an Arrow object that contains the complete data from the remote table, effectively the result of calling `dbGetQueryArrow()` with `⁠SELECT * FROM ⁠`. An empty table is returned as an Arrow object with zero rows. ### Failure modes An error is raised if the table does not exist. 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. ### 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: `dbReadTableArrow()` will do the quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)` - If the result of a call to `dbQuoteIdentifier()`: no more quoting is done ### Examples ``` r # Read data as Arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars[1:10, ]) dbReadTableArrow(con, "mtcars") dbDisconnect(con) ``` ## Copy Arrow objects to database tables This section describes the behavior of the following method: ``` r dbWriteTableArrow(conn, name, value, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) Writes, overwrites or appends an Arrow object to a database 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"')

value

An nanoarray stream, or an object coercible to a nanoarray stream with nanoarrow::as_nanoarrow_array_stream().

...

Other parameters passed on to methods.

### Additional arguments The following arguments are not part of the `dbWriteTableArrow()` generic (to improve compatibility across backends) but are part of the DBI specification: - `overwrite` (default: `FALSE`) - `append` (default: `FALSE`) - `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: `dbWriteTableArrow()` 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 (possibly returned as character) - 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. ### Details This function expects an Arrow object. Convert a data frame to an Arrow object with `nanoarrow::as_nanoarrow_array_stream()` or use `dbWriteTable()` to write a data frame. This function is useful if you want to create and load a table at the same time. Use `dbAppendTableArrow()` for appending data to an existing table, `dbCreateTableArrow()` for creating a table and specifying field types, and `dbRemoveTable()` for overwriting tables. ### Value `dbWriteTableArrow()` 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 `overwrite`, `append`, and `temporary` (non-scalars, unsupported data types, `NA`, incompatible values, incompatible columns) also raise an error. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTableArrow(con, "mtcars", nanoarrow::as_nanoarrow_array_stream(mtcars[1:5, ])) dbReadTable(con, "mtcars") dbDisconnect(con) ``` ## Create a table in the database based on an Arrow object This section describes the behavior of the following method: ``` r dbCreateTableArrow(conn, name, value, ..., temporary = FALSE) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) The default `dbCreateTableArrow()` method determines the R data types of the Arrow schema associated with the Arrow object, and calls `dbCreateTable()`. Backends that implement `dbAppendTableArrow()` should typically also implement this generic. Use `dbCreateTable()` to create a table from the column types as defined in a 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

An object for which a schema can be determined via nanoarrow::infer_nanoarrow_schema().

...

Other parameters passed on to methods.

temporary

If TRUE, will generate a temporary table.

### Additional arguments The following arguments are not part of the `dbCreateTableArrow()` generic (to improve compatibility across backends) but are part of the DBI specification: - `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: `dbCreateTableArrow()` 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 can be: - a data frame, - a nanoarrow array - a nanoarrow array stream (which will still contain the data after the call) - a nanoarrow schema 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, and spaces can also be used for table names and column names, if the database supports non-syntactic identifiers. ### Value `dbCreateTableArrow()` returns `TRUE`, invisibly. ### 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 `name` cannot be processed with `dbQuoteIdentifier()` or if this results in a non-scalar. Invalid values for the `temporary` argument (non-scalars, unsupported data types, `NA`, incompatible values, duplicate names) also raise an error. ### Examples ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") ptype <- data.frame(a = numeric()) dbCreateTableArrow(con, "df", nanoarrow::infer_nanoarrow_schema(ptype)) dbReadTable(con, "df") dbDisconnect(con) ``` ## Insert rows into a table from an Arrow stream This section describes the behavior of the following method: ``` r dbAppendTableArrow(conn, name, value, ...) ``` ### Description [![\[Experimental\]](https://dbi.r-dbi.org/reference/figures/lifecycle-experimental.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) The `dbAppendTableArrow()` method assumes that the table has been created beforehand, e.g. with `dbCreateTableArrow()`. The default implementation calls `dbAppendTable()` for each chunk of the stream. Use `dbAppendTable()` to append data from a 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

An object coercible with nanoarrow::as_nanoarrow_array_stream().

...

Other parameters passed on to methods.

### Value `dbAppendTableArrow()` returns a scalar numeric. ### Failure modes If the table does not exist, or the new data in `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 `name` cannot be processed with `dbQuoteIdentifier()` or if this results in a non-scalar. ### 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 `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 non-empty strings) - factor (possibly returned as character) - 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 `name` argument is processed as follows, to support databases that allow non-syntactic names for their objects: - If an unquoted table name as string: `dbAppendTableArrow()` will do the quoting, perhaps by calling `dbQuoteIdentifier(conn, x = name)` - If the result of a call to `dbQuoteIdentifier()`: no more quoting is done to support databases that allow non-syntactic names for their objects: The `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 ``` r con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTableArrow(con, "iris", iris[0, ]) dbAppendTableArrow(con, "iris", iris[1:5, ]) dbReadTable(con, "iris") dbDisconnect(con) ``` DBI/vignettes/spec.Rmd0000644000176200001440000000177114607456777014313 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} knitr::asis_output(paste(readLines("spec.md"), collapse = "\n")) ``` DBI/vignettes/hierarchy.png0000644000176200001440000022345514350241735015363 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 @@@@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-U6 ጼMj>Ra^iZ-kSCGYOO<裏/Ѫs|,δ!(37LkYk}!yԬ31C0p >\O~?~ 8: w歵SL'uŜ9HwFqlљsy+e֬9uWDžV9Ϸi4sv+[,<3r(wwu|1kߴ{rll[,9|+_1giÆ "U HcǼQoΝ4\|yw˪{iWQVL慈(ɚ9Yq͌޽/|4͜1C1[ c2*v:D539+3 jB@`HYZh~hFfգ}UIxNz+#s4v #/01EٹfEsq#`&w mPGbc'`h#    P:E@@@@@@`h( ~@@@@uJGH     ]ď    .@C @@@@@H7l oүJ-_s8    !@Cn~\x1 q@@@@tep     @ 0Gi B@@@@ P0j"B@@@@d4YKt!    @h(M5!    @ P%C@@@@@ a4&@@@@@ Yh(M֒!]     0JFMD     4&kɐ.@@@@H &"@@@@HVJdH    $L҄Q    $ Z2 @@@@&@Ci¨@@@@Ud-҅     4aD    *b%K.??&kI Ξ=/|WrH L:UUUU صk`yveL@` ؟'b|{ŋ'9FƱ@AAF9xgeU, &O{׽$9I d (xv6c    )(SEb@@@@@`$h( UD@@@@1%@C*.    #!@CH&    )JTqX@@@@ JGB0@@@@@`L P:"    H$uC}ݧΑ ^۷o3 j,iDXݫg}6ӓo|Jp&'? g @Dq"D܉UD;q. VOO8/[o8:( <_JgΜ|p}8rB@]gK+b̉( @3    $^ě#    $ IV $@@@@/@Ci͉@@@@L$+    4Ĉ    I&@CiA@@@@ PxsbD@@@@$4     @h(M91"    @ PdBr@@@@@ 4&ޜ@@@@@ h(M!9     xJoN     d4&Y@@@@H 7'F@@@@H2J@H    $^ě#    $ IV $@@@@/@Ci͉@@@@L$+    4Ĉ    I&@CiA@@@@ PxsbD@@@@$4     @h(M91"    @ PdBr@@@@@ 4&ޜ@@@@@ h(M!9     xJoN     d4&Y@@@@H 7'F@@@@H2J@H    $^ě#    $ IV $@@@@/@Ci͉@@@@L$+    4Ę`GyDiii6m7Pff}n@ƣsE} ?&MǬ'@<;B$ q  vttS__}uV@Y4e;o_z I@@@ p³sI5z='J //'R|V/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$]/;Iw' f: -0{4meq oFd,TՎ9(em!$# PguVj"@.4xn<Z//AkFiDwtIkM/o,&`D蕃lSa>[  PXOt@KbjSvO;tmm䷟ʀ ݰn={lvPϧ"  E VMņ @ZAÅ-H_Γ^ߚt %.g++vd @ ؃BDߒ$M3K~IH\%ۯd^ֿ=Zmc @ V}S@4HE |/1 ;|4,sJרAR  P@ R&5HV[*e/ 6y  @muGpTm$8_,E@ eV&?l.g  _:  @~IE@@@@#@;uMI@@@@@ @C2    xG@wꚒ"    A@d@@@@R5%E@@@@R      ީkJ    @@@@@;JSה@@@@ J 0$#    wz))    `HF@@@@(N]SR@@@@0(5     Pꝺ     ` Pj!@@@@#@;uMI@@@@@ @C2    xG@wꚒ"    AJonn'O6!-011!> G ܺuK=*---.9E XW+W2k2vbSf' 0vvRmg^V$a255UT@GVZ傜E\vV< @U숀;k= 0vZuNҁRd     (CvzIENDB`DBI/vignettes/biblio.bib0000644000176200001440000001772214350241735014613 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/DBI-advanced.Rmd0000644000176200001440000002655715143057347015515 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, 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.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-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/docs/server/reference/sql-statements/prepared-statements/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") ``` Do not forget to disconnect from the database at the end. ```{r} 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-history.Rmd0000644000176200001440000001221414602466070015426 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.Rmd0000644000176200001440000001624315005325062013726 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} knitr::opts_chunk$set( echo = TRUE, 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-data.org/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.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-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.fel.cvut.cz", port = 3306, username = "guest", password = keyring::key_get("relational.fel.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(), host = "relational.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-relational", 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/vignettes/DBI-proposal.Rmd0000644000176200001440000006635215143057347015604 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](https://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://keittlab.org) 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 (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](https://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/backend.Rmd0000644000176200001440000002413615005150137014716 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/NAMESPACE0000644000176200001440000000632014602466070012075 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(dbAppendTableArrow) export(dbBegin) export(dbBind) export(dbBindArrow) export(dbBreak) export(dbCallProc) export(dbCanConnect) export(dbClearResult) export(dbColumnInfo) export(dbCommit) export(dbConnect) export(dbCreateTable) export(dbCreateTableArrow) export(dbDataType) export(dbDisconnect) export(dbDriver) export(dbExecute) export(dbExistsTable) export(dbFetch) export(dbFetchArrow) export(dbFetchArrowChunk) export(dbGetConnectArgs) export(dbGetDBIVersion) export(dbGetException) export(dbGetInfo) export(dbGetQuery) export(dbGetQueryArrow) 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(dbReadTableArrow) export(dbRemoveTable) export(dbRollback) export(dbSendQuery) export(dbSendQueryArrow) export(dbSendStatement) export(dbSetDataMappings) export(dbUnloadDriver) export(dbUnquoteIdentifier) export(dbWithTransaction) export(dbWriteTable) export(dbWriteTableArrow) 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(DBIResultArrow) exportClasses(DBIResultArrowDefault) exportClasses(SQL) exportMethods(dbAppendTable) exportMethods(dbAppendTableArrow) exportMethods(dbBind) exportMethods(dbBindArrow) exportMethods(dbCanConnect) exportMethods(dbClearResult) exportMethods(dbConnect) exportMethods(dbCreateTable) exportMethods(dbCreateTableArrow) exportMethods(dbDataType) exportMethods(dbExecute) exportMethods(dbExistsTable) exportMethods(dbFetch) exportMethods(dbFetchArrow) exportMethods(dbFetchArrowChunk) exportMethods(dbGetConnectArgs) exportMethods(dbGetInfo) exportMethods(dbGetQuery) exportMethods(dbGetQueryArrow) exportMethods(dbGetRowCount) exportMethods(dbGetRowsAffected) exportMethods(dbGetStatement) exportMethods(dbHasCompleted) exportMethods(dbIsValid) exportMethods(dbListFields) exportMethods(dbListObjects) exportMethods(dbQuoteIdentifier) exportMethods(dbQuoteLiteral) exportMethods(dbQuoteString) exportMethods(dbReadTable) exportMethods(dbReadTableArrow) exportMethods(dbRemoveTable) exportMethods(dbSendQueryArrow) exportMethods(dbSendStatement) exportMethods(dbUnquoteIdentifier) exportMethods(dbWithTransaction) exportMethods(dbWriteTable) exportMethods(dbWriteTableArrow) exportMethods(show) exportMethods(sqlAppendTable) exportMethods(sqlCreateTable) exportMethods(sqlData) exportMethods(sqlInterpolate) exportMethods(sqlParseVariables) import(methods) DBI/NEWS.md0000644000176200001440000005322415146014721011755 0ustar liggesusers # DBI 1.3.0 (2026-02-11) ## Features - Add support for OpenTelemetry via the otel and otelsdk packages (@shikokuchuo, #551). ## Bug fixes - `dbWithTransaction()` calls `dbRollback()` also on interrupt (@klin333, #528). - `dbQuoteLiteral()` uses the format `"%Y-%m-%d %H:%M:%S%z"` which is understood by more databases (#486). ## Documentation - Add "Supported By Posit" badge to website (@krlmlr). - Render specification with newest pandoc (#568). - Add new generics to specification. ## Performance - Avoid unnecessary computation in default `dbUnquoteIdentifier()` method (@MichaelChirico, #515). ## Breaking changes - Many generics in the package are now a `"nonstandardGeneric"` instead of a `"standardGeneric"`: The `def` argument to `methods::setClass()` changed from a direct call to `methods::standardGeneric()` to a function that wraps `methods::standardGeneric()`. This should not affect most users, but became apparent with the tests in the dittodb package failing and is listed here for completeness. See for detail. # DBI 1.2.3 (2024-06-02) ## Bug fixes - `dbQuoteLiteral()` uses the format `"%Y-%m-%d %H-%M-%S%z"` which is understood by more databases (#467, #474). ## Documentation - Use relational-data.org as a replacement for relational.fit.cvut.cz. - Set BS version explicitly for now (@maelle, #478). - Include `dbGetInfo()` in the spec (#477). - Fix typos (@salim-b, #469, @MichaelChirico, #482). # DBI 1.2.2 (2024-02-09) ## Bug fixes - `Id()` does not assign empty names to the components if all arguments are unnamed (#464). - Add spec to version control to avoid weird pandoc errors on CRAN (#465). # DBI 1.2.1 (2024-01-12) ## Bug fixes - Fix `dbWriteTableArrow()` according to spec (#457). - Fix type inference in default method for `dbCreateTableArrow()` (#450). ## Features - `dbAppendTableArrow()` returns number of rows (#454). - Add `temporary` argument to `dbCreateTableArrow()` (#453). - Avoid coercing `params` in default implementation for `dbSendQueryArrow()` (#447). - Use `nanoarrow::infer_nanoarrow_schema()` in the default method for `dbCreateTable()` (#445). ## Chore - Add badge to `DBIResultArrow` class (#452). - Change maintainer e-mail. ## Documentation - Finalize Arrow vignette (#451, #455). - Document new Arrow generics (#444, #449). - Use dbitemplate (@maelle, #442). # DBI 1.2.0 (2023-12-20) ## Breaking changes - `dbUnquoteIdentifier()` creates `Id()` objects without component names and allows non-`NA` character input (#421, #422). ## Features - New generics `dbSendQueryArrow()`, `dbFetchArrow()`, `dbGetQueryArrow()`, `dbReadTableArrow()`, `dbWriteTableArrow()` (@nbenn, #390), `dbCreateTableArrow()`, `dbAppendTableArrow()` (#396), `dbBindArrow()` (#415) and `dbFetchArrowChunk()` (#424), with default implementations via nanoarrow (#414). - `Id()` now accepts unnamed components (#417). If names are provided, the components are arranged in SQL order (@eauleaf, #427). - New `dbIsValid()` method for `"DBIResultArrowDefault"` objects implemented by DBI (#425). - Implement `dbiDataType()` for objects of class `"blob"`. ## Documentation - Update pkgdown template (@maelle, #428, #438, #437). - Clarify repeated parameter binding (#430). - Deal with sundown of `https://relational.fit.cvut.cz` (#423). - Correct vignette titles (#419). - Harmonize table documentation (#400). - Tweak typo, add families for data retrieval and command execution. ## Testing - Enable BLOB tests for arrow \>= 10.0.0 (#395). - Run DBItest for SQLite as part of the checks here (#431). - Fix checks without suggested packages (#420). - Fix Windows tests on GHA (#406). - `testthat::use_testthat(3)` (#416). # DBI 1.1.3 (2022-06-18) ## Features - `dbAppendTable()` accepts `Id` (#381, @renkun-ken). ## Documentation - `?dbSendQuery` and related methods gain a section "The data retrieval flow" (#386). - `?dbSendStatement` and related methods gain a section "The command execution flow" (#386). # 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 - The pkgdown documentation for DBI generics (e.g. `?dbConnect`) contains clickable links to all known backends (except ROracle), and an explanatory sentence (#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). - `?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/inst/0000755000176200001440000000000015147357131011634 5ustar liggesusersDBI/inst/doc/0000755000176200001440000000000015147357131012401 5ustar liggesusersDBI/inst/doc/backend.R0000644000176200001440000000550015147357127014120 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/backend.html0000644000176200001440000007305415147357127014674 0ustar liggesusers Implementing 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-arrow.Rmd0000644000176200001440000001517214602466070014577 0ustar liggesusers--- title: "Using DBI with Arrow" author: "Kirill Müller" date: "25/12/2023" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using DBI with Arrow} %\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, 6)) if (nrow(x) > 6) { cat("Showing 6 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 want to leverage [Apache Arrow](https://arrow.apache.org/) for accessing and manipulating data on databases. See `vignette("DBI", package = "DBI")` and `vignette("DBI-advanced", package = "DBI")` for tutorials on accessing data using R's data frames instead of Arrow's structures. ## Rationale Apache Arrow is > a cross-language development platform for in-memory analytics, suitable for large and huge data, with support for out-of-memory operation. Arrow is also a data exchange format, the data types covered by Arrow align well with the data types supported by SQL databases. DBI 1.2.0 introduced support for Arrow as a format for exchanging data between R and databases. The aim is to: - accelerate data retrieval and loading, by using fewer costly data conversions; - better support reading and summarizing data from a database that is larger than memory; - provide better type fidelity with workflows centered around Arrow. This allows existing code to be used with Arrow, and it allows new code to be written that is more efficient and more flexible than code that uses R's data frames. The interface is built around the {nanoarrow} R package, with `nanoarrow::as_nanoarrow_array` and `nanoarrow::as_nanoarrow_array_stream` as fundamental data structures. ## New classes and generics DBI 1.2.0 introduces new classes and generics for working with Arrow data: - `dbReadTableArrow()` - `dbWriteTableArrow()` - `dbCreateTableArrow()` - `dbAppendTableArrow()` - `dbGetQueryArrow()` - `dbSendQueryArrow()` - `dbBindArrow()` - `dbFetchArrow()` - `dbFetchArrowChunk()` - `DBIResultArrow-class` - `DBIResultArrowDefault-class` Compatibility is important for DBI, and implementing new generics and classes greatly reduces the risk of breaking existing code. The DBI package comes with a fully functional fallback implementation for all existing DBI backends. The fallback is not improving performance, but it allows existing code to be used with Arrow before switching to a backend with native Arrow support. Backends with native support, like the [adbi](https://adbi.r-dbi.org/) package, implement the new generics and classes for direct support and improved performance. In the remainder of this tutorial, we will demonstrate the new generics and classes using the RSQLite package. SQLite is an in-memory database, this code does not need a database server to be installed and running. ## Prepare We start by setting up a database connection and creating a table with some data, using the original `dbWriteTable()` method. ```{r} library(DBI) con <- dbConnect(RSQLite::SQLite()) data <- data.frame( a = 1:3, b = 4.5, c = "five" ) dbWriteTable(con, "tbl", data) ``` ## Read all rows from a table The `dbReadTableArrow()` method reads all rows from a table into an Arrow stream, similarly to `dbReadTable()`. Arrow objects implement the `as.data.frame()` method, so we can convert the stream to a data frame. ```{r} stream <- dbReadTableArrow(con, "tbl") stream as.data.frame(stream) ``` ## Run queries The `dbGetQueryArrow()` method runs a query and returns the result as an Arrow stream. This stream can be turned into an `arrow::RecordBatchReader` object and processed further, without bringing it into R. ```{r} stream <- dbGetQueryArrow(con, "SELECT COUNT(*) AS n FROM tbl WHERE a < 3") stream path <- tempfile(fileext = ".parquet") arrow::write_parquet(arrow::as_record_batch_reader(stream), path) arrow::read_parquet(path) ``` ## Prepared queries The `dbGetQueryArrow()` method supports prepared queries, using the `params` argument which accepts a data frame or a list. ```{r} params <- data.frame(a = 3L) stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) params <- data.frame(a = c(2L, 4L)) # Equivalent to dbBind() stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) ``` ## Manual flow For the manual flow, use `dbSendQueryArrow()` to send a query to the database, and `dbFetchArrow()` to fetch the result. This also allows using the new `dbBindArrow()` method to bind data in Arrow format to a prepared query. Result objects must be cleared with `dbClearResult()`. ```{r} rs <- dbSendQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a") in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 2L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 3L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1:4L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) dbClearResult(rs) ``` ## Writing data Streams returned by `dbGetQueryArrow()` and `dbReadTableArrow()` can be written to a table using `dbWriteTableArrow()`. ```{r} stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbWriteTableArrow(con, "tbl_new", stream) dbReadTable(con, "tbl_new") ``` ## Appending data For more control over the writing process, use `dbCreateTableArrow()` and `dbAppendTableArrow()`. ```{r} stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbCreateTableArrow(con, "tbl_split", stream) dbAppendTableArrow(con, "tbl_split", stream) stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a >= 3") dbAppendTableArrow(con, "tbl_split", stream) dbReadTable(con, "tbl_split") ``` ## Conclusion Do not forget to disconnect from the database when done. ```{r} dbDisconnect(con) ``` That concludes the major features of DBI's new Arrow interface. For more details on the library functions covered in this tutorial see the DBI specification at `vignette("spec", package = "DBI")`. See the [adbi](https://adbi.r-dbi.org/) package for a backend with native Arrow support, and [nanoarrow](https://github.com/apache/arrow-nanoarrow) and [arrow](https://arrow.apache.org/docs/r/) for packages to work with the Arrow format. DBI/inst/doc/DBI-proposal.html0000644000176200001440000016214615147357123015535 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 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. Springer.
Chambers, John M., Mark H. Hansen, David A. James, and Duncan Temple Lang. 1998. “Distributed Computing with Data: A CORBA-Based Approach.” Computing Science and Statistics.
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. Bell Labs, Lucent Technologies.
R Data Import/Export. 2001. R-Development Core Team.
Siegel, Jon. 1996. CORBA Fundamentals and Programming. 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. 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-1.Rmd0000644000176200001440000006004715144403222013576 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](https://www.unixodbc.org/)). Python’s Database Application Programming Interface ([www.python.org](https://wiki.python.org/python/DatabaseProgramming.html)). 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/DBI.R0000644000176200001440000000360615147357126013133 0ustar liggesusers## ----setup, include=FALSE----------------------------------------------------- knitr::opts_chunk$set( echo = TRUE, error = Sys.getenv("IN_PKGDOWN") != "true" || (getRversion() < "3.5") ) ## ----------------------------------------------------------------------------- library(DBI) con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-relational", dbname = "sakila" ) dbListTables(con) dbDisconnect(con) ## ----eval = FALSE------------------------------------------------------------- # con <- dbConnect( # RMariaDB::MariaDB(), # host = "relational.fel.cvut.cz", # port = 3306, # username = "guest", # password = keyring::key_get("relational.fel.cvut.cz", "guest"), # dbname = "sakila" # ) ## ----------------------------------------------------------------------------- con <- dbConnect( RMariaDB::MariaDB(), host = "relational.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-relational", 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/spec.html0000644000176200001440000110262215147357131014225 0ustar liggesusers DBI 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.

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.

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).

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. At least one 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(). Use dbSendQueryArrow() or dbGetQueryArrow() instead to retrieve the results as an Arrow object.

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().

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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.

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. Passing n = NA is supported and returns an arbitrary number of rows (at least one) as specified by the driver, but at most the remaining rows in the result set.

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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. This step is mandatory for all objects obtained by calling dbSendQuery() or dbSendStatement().

Arguments

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

Value

dbClearResult() returns TRUE, invisibly, for result sets obtained from dbSendQuery(), dbSendStatement(), or dbSendQueryArrow(),

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

The command execution flow

This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of dbBindArrow(), is implemented by dbExecute(), which should be sufficient for non-parameterized queries. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendStatement() to create a result set object of class DBIResult. For some queries you need to pass immediate = TRUE.

  2. Optionally, bind query parameters withdbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbGetRowsAffected() to retrieve the number of rows affected by the query.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

Failure modes

An attempt to close an already closed result set issues a warning for dbSendQuery(), dbSendStatement(), and dbSendQueryArrow(),

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 methods:

dbBind(res, params, ...)

dbBindArrow(res, params, ...)

Description

For parametrized or prepared statements, the dbSendQuery(), dbSendQueryArrow(), and dbSendStatement() functions can be called with statements that contain placeholders for values. The dbBind() and dbBindArrow() functions bind these placeholders to actual values, and are intended to be called on the result set before calling dbFetch() or dbFetchArrow(). The values are passed to dbBind() as lists or data frames, and to dbBindArrow() as a stream created by nanoarrow::as_nanoarrow_array_stream().

Experimental

dbBindArrow() is experimental, as are the other ⁠*Arrow⁠ functions. dbSendQuery() is compatible with dbBindArrow(), and dbSendQueryArrow() is compatible with dbBind().

Arguments

res An object inheriting from DBIResult.
params For dbBind(), a list of values, named or unnamed, or a data frame, with one element/column per query parameter. For dbBindArrow(), values as a nanoarrow stream, with one column per query parameter.
... Other arguments passed on to methods.

Details

DBI supports parametrized (or prepared) queries and statements via the dbBind() and dbBindArrow() generics. 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 RMariaDB 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() or dbSendQueryArrow() and also for data manipulation statements issued by dbSendStatement().

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

The data retrieval flow for Arrow streams

This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream.

Most of this flow, except repeated calling of dbBindArrow() or dbBind(), is implemented by dbGetQueryArrow(), which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQueryArrow() to create a result set object of class DBIResultArrow.

  2. Optionally, bind query parameters with dbBindArrow() or dbBind(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Use dbFetchArrow() to get a data stream.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

The command execution flow

This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of dbBindArrow(), is implemented by dbExecute(), which should be sufficient for non-parameterized queries. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendStatement() to create a result set object of class DBIResult. For some queries you need to pass immediate = TRUE.

  2. Optionally, bind query parameters withdbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbGetRowsAffected() to retrieve the number of rows affected by the query.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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(), dbSendQueryArrow() 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() or dbBindArrow() have been called, the returned result set object has the following behavior:

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

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

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

    • dbIsValid() returns TRUE

    • dbHasCompleted() returns FALSE

  2. Call dbBind() or dbBindArrow():

    • For dbBind(), the params argument must be a list where all elements have the same lengths and contain values supported by the backend. A data.frame is internally stored as such a list.

    • For dbBindArrow(), the params argument must be a nanoarrow array stream, with one column per query parameter.

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

    • For queries issued by dbSendQuery() or dbSendQueryArrow(), 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

# Data frame flow:
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)



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

dbWriteTable(con, "iris", iris)

# Using the same query for different values
iris_result <- dbSendQueryArrow(con, "SELECT * FROM iris WHERE [Petal.Width] > ?")
dbBindArrow(
  iris_result,
  nanoarrow::as_nanoarrow_array_stream(data.frame(2.3, fix.empty.names = FALSE))
)
as.data.frame(dbFetchArrow(iris_result))
dbBindArrow(
  iris_result,
  nanoarrow::as_nanoarrow_array_stream(data.frame(3, fix.empty.names = FALSE))
)
as.data.frame(dbFetchArrow(iris_result))
dbClearResult(iris_result)

# Executing the same statement with different values at once
iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = \$species")
dbBindArrow(iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(
  species = c("setosa", "versicolor", "unknown")
)))
dbGetRowsAffected(iris_result)
dbClearResult(iris_result)

nrow(dbReadTable(con, "iris"))

dbDisconnect(con)

Retrieve results from a query

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 freed by dbClearResult(). For retrieving chunked/paged results or for passing query parameters, see dbSendQuery(), in particular the “The data retrieval flow” section. For retrieving results as an Arrow object, see dbGetQueryArrow().

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 or data manipulation queries like ⁠INSERT INTO ... RETURNING ...⁠). 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().

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().

The command execution flow

This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of dbBindArrow(), is implemented by dbExecute(), which should be sufficient for non-parameterized queries. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendStatement() to create a result set object of class DBIResult. For some queries you need to pass immediate = TRUE.

  2. Optionally, bind query parameters withdbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbGetRowsAffected() to retrieve the number of rows affected by the query.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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)

Change database state

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 freed by dbClearResult(). For passing query parameters, see dbBind(), in particular the “The command execution flow” section.

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, or a data manipulation query that also returns a result set such as ⁠INSERT INTO ... RETURNING ...⁠, 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.

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 literal values

This section describes the behavior of the following method:

dbQuoteLiteral(conn, x, ...)

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.

Arguments

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

Value

dbQuoteLiteral() returns an object that can be coerced to 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 dbQuoteLiteral() 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 list for the x argument raises an error.

Specification

The returned expression can be used in a ⁠SELECT ...⁠ query, and the value of dbGetQuery(paste0("SELECT ", dbQuoteLiteral(x)))[[1]] must be equal to x for any scalar integer, numeric, string, and logical. If x is NA, the result must merely satisfy is.na(). The literals "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;--"
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))

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().

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))

Unquote identifiers

This section describes the behavior of the following method:

dbUnquoteIdentifier(conn, x, ...)

Description

Call this method to convert a SQL object created by dbQuoteIdentifier() back to a list of Id objects.

Arguments

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

Value

dbUnquoteIdentifier() returns a list of objects of the same length as the input. For an empty vector, this function returns a length-0 object. The names of the input argument are preserved in the output. If x is a value returned by dbUnquoteIdentifier(), calling dbUnquoteIdentifier(..., dbQuoteIdentifier(..., x)) returns list(x). If x is an object of class Id, calling dbUnquoteIdentifier(..., x) returns list(x). (For backends it may be most convenient to return Id objects to achieve this behavior, but this is not required.)

Plain character vectors can also be passed to dbUnquoteIdentifier().

Failure modes

An error is raised if a character vectors with a missing value is passed as the x argument.

Specification

For any character vector of length one, quoting (with 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 SQL() and then quoting via dbQuoteIdentifier() gives the same result as just quoting the string. Similarly, unquoting expressions of the form SQL("schema.table") and then quoting gives the same result as quoting the identifier constructed by Id("schema", "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", "Schema", "Table"))

# Quoting and unquoting are inverses
dbQuoteIdentifier(
  ANSI(),
  dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]]
)

dbQuoteIdentifier(
  ANSI(),
  dbUnquoteIdentifier(ANSI(), Id("Schema", "Table"))[[1]]
)

Read database tables as data frames

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. Use dbReadTableArrow() instead to obtain an Arrow object.

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

Details

This function returns a data frame. Use dbReadTableArrow() to obtain an Arrow object.

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 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.

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 expects a data frame. Use dbWriteTableArrow() to write an Arrow object.

This function is useful if you want to create and load a table at the same time. Use dbAppendTable() or dbAppendTableArrow() for appending data to an existing table, dbCreateTable() or dbCreateTableArrow() for creating a table, and dbExistsTable() and dbRemoveTable() for overwriting tables.

DBI only standardizes writing data frames with dbWriteTable(). 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")

Create a table in the database

This section describes the behavior of the following method:

dbCreateTable(conn, name, fields, ..., row.names = NULL, temporary = FALSE)

Description

The default dbCreateTable() method calls sqlCreateTable() and dbExecute(). Use dbCreateTableArrow() to create a table from an Arrow schema.

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”’)

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().

Other parameters passed on to methods.

row.names

Must be NULL.

temporary

If TRUE, will generate a temporary table.

Additional arguments

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

  • 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: dbCreateTable() 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 can be:

  • a data frame,

  • a named list of SQL types

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, and spaces can also be used for table names and column names, if the database supports non-syntactic identifiers.

The row.names argument must be missing or NULL, the default value. All other values for the row.names argument (in particular TRUE, NA, and a string) raise an error.

Details

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.

Value

dbCreateTable() returns TRUE, invisibly.

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 name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar. Invalid values for the row.names and temporary arguments (non-scalars, unsupported data types, NA, incompatible values, duplicate names) also raise an error.

Examples

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

Insert rows into a table

This section describes the behavior of the following method:

dbAppendTable(conn, name, value, ..., row.names = NULL)

Description

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. Use dbAppendTableArrow() to append data from an Arrow stream.

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.

row.names

Must be NULL.

Details

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.

Value

dbAppendTable() returns a scalar numeric.

Failure modes

If the table does not exist, or the new data in 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 name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar. Invalid values for the row.names argument (non-scalars, unsupported data types, NA) also raise an error.

Passing a value argument different to NULL to the row.names argument (in particular TRUE, NA, and a string) raises an error.

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 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 non-empty strings)

  • factor (returned as character, with a warning)

  • 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 name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

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

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done to support databases that allow non-syntactic names for their objects:

The row.names argument must be NULL, the default value. Row names are ignored.

The 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)

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.

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 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.

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)

List field names of a remote table

This section describes the behavior of the following method:

dbListFields(conn, name, ...)

Description

Returns the field names of a remote table as a character vector.

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)

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.

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)

List remote objects

This section describes the behavior of the following method:

dbListObjects(conn, prefix = NULL, ...)

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 RMariaDB and 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.

Arguments

conn A DBIConnection object, as returned by dbConnect().
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.
... Other parameters passed on to methods.

Value

dbListObjects() returns a data frame with columns table and is_prefix (in that order), optionally with other columns with a dot (.) prefix. The table column is of type list. Each object in this list is suitable for use as argument in dbQuoteIdentifier(). The 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 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 dbQuoteIdentifier().

Failure modes

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

Specification

The prefix column indicates if the table value refers to a table or a prefix. For a call with the default prefix = NULL, the table values that have is_prefix == FALSE correspond to the tables returned from dbListTables(),

The table object can be quoted with dbQuoteIdentifier(). The result of quoting can be passed to dbUnquoteIdentifier(). (For backends it may be convenient to use the Id class, but this is not required.)

Values in table column that have is_prefix == TRUE can be passed as the prefix argument to another call to dbListObjects(). For the data frame returned from a dbListObject() call with the prefix argument set, all table values where is_prefix is FALSE can be used in a call to dbExistsTable() which returns TRUE.

Examples

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

dbListObjects(con)
dbWriteTable(con, "mtcars", mtcars)
dbListObjects(con)

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).

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.

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.

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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().

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.

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.

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(). NA_integer_ or NA_numeric_ are allowed if the number of rows affected is not known.

For queries issued with dbSendQuery(), zero is returned before and after the call to dbFetch(). NA values are not allowed.

The command execution flow

This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of dbBindArrow(), is implemented by dbExecute(), which should be sufficient for non-parameterized queries. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendStatement() to create a result set object of class DBIResult. For some queries you need to pass immediate = TRUE.

  2. Optionally, bind query parameters withdbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbGetRowsAffected() to retrieve the number of rows affected by the query.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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.

The data retrieval flow

This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames.

Most of this flow, except repeated calling of dbBind() or dbBindArrow(), is implemented by dbGetQuery(), which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQuery() to create a result set object of class DBIResult.

  2. Optionally, bind query parameters with dbBind() or dbBindArrow(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Optionally, use dbColumnInfo() to retrieve the structure of the result set without retrieving actual data.

  4. Use dbFetch() to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards.

  5. Use dbHasCompleted() to tell when you’re done. This method returns TRUE if no more rows are available for fetching.

  6. Repeat the last four steps as necessary.

  7. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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.

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 or 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 current 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)

Get DBMS metadata

This section describes the behavior of the following method:

dbGetInfo(dbObj, ...)

Description

Retrieves information on objects of class DBIDriver, DBIConnection or DBIResult.

Arguments

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

Value

For objects of class DBIDriver, dbGetInfo() returns a named list that contains at least the following components:

  • driver.version: the package version of the DBI backend,

  • client.version: the version of the DBMS client library.

For objects of class DBIConnection, dbGetInfo() returns a named list that contains at least the following components:

  • db.version: version of the database server,

  • dbname: database name,

  • username: username to connect to the database,

  • host: hostname of the database server,

  • port: port on the database server. It must not contain a password component. Components that are not applicable should be set to NA.

For objects of class DBIResult, dbGetInfo() returns a named list that contains at least the following components:

  • statatment: the statement used with dbSendQuery() or dbExecute(), as returned by dbGetStatement(),

  • row.count: the number of rows fetched so far (for queries), as returned by dbGetRowCount(),

  • rows.affected: the number of rows affected (for statements), as returned by dbGetRowsAffected()

  • has.completed: a logical that indicates if the query or statement has completed, as returned by dbHasCompleted().

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().

Examples

dbGetInfo(RSQLite::SQLite())

Execute a query on a given database connection for retrieval via Arrow

This section describes the behavior of the following method:

dbSendQueryArrow(conn, statement, ...)

Description

Experimental

The dbSendQueryArrow() 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 dbFetchArrow() method, and then you must call dbClearResult() when you finish fetching the records you need. For interactive use, you should almost always prefer dbGetQueryArrow(). Use dbSendQuery() or dbGetQuery() instead to retrieve the results as a data frame.

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 dbSendQueryArrow() 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.

Value

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

The data retrieval flow for Arrow streams

This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream.

Most of this flow, except repeated calling of dbBindArrow() or dbBind(), is implemented by dbGetQueryArrow(), which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQueryArrow() to create a result set object of class DBIResultArrow.

  2. Optionally, bind query parameters with dbBindArrow() or dbBind(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Use dbFetchArrow() to get a data stream.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

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

# Retrieve data as arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")

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

dbDisconnect(con)

Fetch records from a previously executed query as an Arrow object

This section describes the behavior of the following method:

dbFetchArrow(res, ...)

Description

Experimental

Fetch the result set and return it as an Arrow object. Use dbFetchArrowChunk() to fetch results in chunks.

Arguments

res An object inheriting from DBIResultArrow, created by dbSendQueryArrow().
... Other arguments passed on to methods.

Value

dbFetchArrow() always returns an object coercible to 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.

The data retrieval flow for Arrow streams

This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream.

Most of this flow, except repeated calling of dbBindArrow() or dbBind(), is implemented by dbGetQueryArrow(), which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQueryArrow() to create a result set object of class DBIResultArrow.

  2. Optionally, bind query parameters with dbBindArrow() or dbBind(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Use dbFetchArrow() to get a data stream.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

Failure modes

An attempt to fetch from a closed result set raises an error.

Specification

Fetching multi-row queries with one or more columns by default returns the entire result. The object returned by dbFetchArrow() can also be passed to nanoarrow::as_nanoarrow_array_stream() to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific.

Examples

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

dbWriteTable(con, "mtcars", mtcars)

# Fetch all results
rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4")
as.data.frame(dbFetchArrow(rs))
dbClearResult(rs)

dbDisconnect(con)

Fetch the next batch of records from a previously executed query as an Arrow object

This section describes the behavior of the following method:

dbFetchArrowChunk(res, ...)

Description

Experimental

Fetch the next chunk of the result set and return it as an Arrow object. The chunk size is implementation-specific. Use dbFetchArrow() to fetch all results.

Arguments

res An object inheriting from DBIResultArrow, created by dbSendQueryArrow().
... Other arguments passed on to methods.

Value

dbFetchArrowChunk() always returns an object coercible to 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.

The data retrieval flow for Arrow streams

This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream.

Most of this flow, except repeated calling of dbBindArrow() or dbBind(), is implemented by dbGetQueryArrow(), which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by dbConnect(). See also vignette("dbi-advanced") for a walkthrough.

  1. Use dbSendQueryArrow() to create a result set object of class DBIResultArrow.

  2. Optionally, bind query parameters with dbBindArrow() or dbBind(). This is required only if the query contains placeholders such as ⁠?⁠ or ⁠\$1⁠, depending on the database backend.

  3. Use dbFetchArrow() to get a data stream.

  4. Repeat the last two steps as necessary.

  5. Use dbClearResult() to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use on.exit() or withr::defer() to ensure that this step is always executed.

Failure modes

An attempt to fetch from a closed result set raises an error.

Specification

Fetching multi-row queries with one or more columns returns the next chunk. The size of the chunk is implementation-specific. The object returned by dbFetchArrowChunk() can also be passed to nanoarrow::as_nanoarrow_array() to create a nanoarrow array object. The chunk size is implementation-specific.

Examples

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

dbWriteTable(con, "mtcars", mtcars)

# Fetch all results
rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbHasCompleted(rs)
as.data.frame(dbFetchArrowChunk(rs))
dbHasCompleted(rs)
as.data.frame(dbFetchArrowChunk(rs))
dbClearResult(rs)

dbDisconnect(con)

Retrieve results from a query as an Arrow object

This section describes the behavior of the following method:

dbGetQueryArrow(conn, statement, ...)

Description

Experimental

Returns the result of a query as an Arrow object. dbGetQueryArrow() comes with a default implementation (which should work with most backends) that calls dbSendQueryArrow(), then dbFetchArrow(), ensuring that the result is always freed by dbClearResult(). For passing query parameters, see dbSendQueryArrow(), in particular the “The data retrieval flow for Arrow streams” section. For retrieving results as a data frame, see dbGetQuery().

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 dbGetQueryArrow() 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” and “Value” sections for details on their usage.

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 or data manipulation queries like ⁠INSERT INTO ... RETURNING ...⁠). To execute a stored procedure that does not return a result set, use dbExecute().

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

Value

dbGetQueryArrow() always returns an object coercible to 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. The object returned by dbGetQueryArrow() can also be passed to nanoarrow::as_nanoarrow_array_stream() to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific.

Examples

# Retrieve data as arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")

dbWriteTable(con, "mtcars", mtcars)
dbGetQueryArrow(con, "SELECT * FROM mtcars")

dbDisconnect(con)

Read database tables as Arrow objects

This section describes the behavior of the following method:

dbReadTableArrow(conn, name, ...)

Description

Experimental

Reads a database table as an Arrow object. Use dbReadTable() instead to obtain a 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”’)

Other parameters passed on to methods.

Details

This function returns an Arrow object. Convert it to a data frame with as.data.frame() or use dbReadTable() to obtain a data frame.

Value

dbReadTableArrow() returns an Arrow object that contains the complete data from the remote table, effectively the result of calling dbGetQueryArrow() with ⁠SELECT * FROM <name>⁠.

An empty table is returned as an Arrow object with zero rows.

Failure modes

An error is raised if the table does not exist.

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.

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: dbReadTableArrow() will do the quoting, perhaps by calling dbQuoteIdentifier(conn, x = name)

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

Examples

# Read data as Arrow table
con <- dbConnect(RSQLite::SQLite(), ":memory:")

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

dbDisconnect(con)

Copy Arrow objects to database tables

This section describes the behavior of the following method:

dbWriteTableArrow(conn, name, value, ...)

Description

Experimental

Writes, overwrites or appends an Arrow object to a database 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”’)

value

An nanoarray stream, or an object coercible to a nanoarray stream with nanoarrow::as_nanoarrow_array_stream().

Other parameters passed on to methods.

Additional arguments

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

  • overwrite (default: FALSE)

  • append (default: FALSE)

  • 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: dbWriteTableArrow() 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 (possibly returned as character)

  • 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.

Details

This function expects an Arrow object. Convert a data frame to an Arrow object with nanoarrow::as_nanoarrow_array_stream() or use dbWriteTable() to write a data frame.

This function is useful if you want to create and load a table at the same time. Use dbAppendTableArrow() for appending data to an existing table, dbCreateTableArrow() for creating a table and specifying field types, and dbRemoveTable() for overwriting tables.

Value

dbWriteTableArrow() 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 overwrite, append, and temporary (non-scalars, unsupported data types, NA, incompatible values, incompatible columns) also raise an error.

Examples

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

dbWriteTableArrow(con, "mtcars", nanoarrow::as_nanoarrow_array_stream(mtcars[1:5, ]))
dbReadTable(con, "mtcars")

dbDisconnect(con)

Create a table in the database based on an Arrow object

This section describes the behavior of the following method:

dbCreateTableArrow(conn, name, value, ..., temporary = FALSE)

Description

Experimental

The default dbCreateTableArrow() method determines the R data types of the Arrow schema associated with the Arrow object, and calls dbCreateTable(). Backends that implement dbAppendTableArrow() should typically also implement this generic. Use dbCreateTable() to create a table from the column types as defined in a 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

An object for which a schema can be determined via nanoarrow::infer_nanoarrow_schema().

Other parameters passed on to methods.

temporary

If TRUE, will generate a temporary table.

Additional arguments

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

  • 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: dbCreateTableArrow() 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 can be:

  • a data frame,

  • a nanoarrow array

  • a nanoarrow array stream (which will still contain the data after the call)

  • a nanoarrow schema

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, and spaces can also be used for table names and column names, if the database supports non-syntactic identifiers.

Value

dbCreateTableArrow() returns TRUE, invisibly.

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 name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar. Invalid values for the temporary argument (non-scalars, unsupported data types, NA, incompatible values, duplicate names) also raise an error.

Examples

con <- dbConnect(RSQLite::SQLite(), ":memory:")
ptype <- data.frame(a = numeric())
dbCreateTableArrow(con, "df", nanoarrow::infer_nanoarrow_schema(ptype))
dbReadTable(con, "df")
dbDisconnect(con)

Insert rows into a table from an Arrow stream

This section describes the behavior of the following method:

dbAppendTableArrow(conn, name, value, ...)

Description

Experimental

The dbAppendTableArrow() method assumes that the table has been created beforehand, e.g. with dbCreateTableArrow(). The default implementation calls dbAppendTable() for each chunk of the stream. Use dbAppendTable() to append data from a 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

An object coercible with nanoarrow::as_nanoarrow_array_stream().

Other parameters passed on to methods.

Value

dbAppendTableArrow() returns a scalar numeric.

Failure modes

If the table does not exist, or the new data in 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 name cannot be processed with dbQuoteIdentifier() or if this results in a non-scalar.

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 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 non-empty strings)

  • factor (possibly returned as character)

  • 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 name argument is processed as follows, to support databases that allow non-syntactic names for their objects:

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

  • If the result of a call to dbQuoteIdentifier(): no more quoting is done to support databases that allow non-syntactic names for their objects:

The 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:")
dbCreateTableArrow(con, "iris", iris[0, ])
dbAppendTableArrow(con, "iris", iris[1:5, ])
dbReadTable(con, "iris")
dbDisconnect(con)
DBI/inst/doc/spec.R0000644000176200001440000000022315147357127013460 0ustar liggesusers## ----echo = FALSE------------------------------------------------------------- knitr::asis_output(paste(readLines("spec.md"), collapse = "\n")) DBI/inst/doc/spec.Rmd0000644000176200001440000000177114607456777014025 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} knitr::asis_output(paste(readLines("spec.md"), collapse = "\n")) ``` DBI/inst/doc/DBI-history.html0000644000176200001440000002332515147357123015372 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.

DBI/inst/doc/DBI-advanced.R0000644000176200001440000001231115147357120014661 0ustar liggesusers## ----setup, include=FALSE----------------------------------------------------- library(knitr) opts_chunk$set( echo = TRUE, 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.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-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------------------------------------------------------------- try({ 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/DBI-arrow.R0000644000176200001440000000547115147357122014261 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, 6)) if (nrow(x) > 6) { cat("Showing 6 out of", nrow(x), "rows.\n") } invisible(x) } registerS3method("knit_print", "data.frame", "knit_print.data.frame") ## ----------------------------------------------------------------------------- library(DBI) con <- dbConnect(RSQLite::SQLite()) data <- data.frame( a = 1:3, b = 4.5, c = "five" ) dbWriteTable(con, "tbl", data) ## ----------------------------------------------------------------------------- stream <- dbReadTableArrow(con, "tbl") stream as.data.frame(stream) ## ----------------------------------------------------------------------------- stream <- dbGetQueryArrow(con, "SELECT COUNT(*) AS n FROM tbl WHERE a < 3") stream path <- tempfile(fileext = ".parquet") arrow::write_parquet(arrow::as_record_batch_reader(stream), path) arrow::read_parquet(path) ## ----------------------------------------------------------------------------- params <- data.frame(a = 3L) stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) params <- data.frame(a = c(2L, 4L)) # Equivalent to dbBind() stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params) as.data.frame(stream) ## ----------------------------------------------------------------------------- rs <- dbSendQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a") in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 2L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 3L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1:4L)) dbBindArrow(rs, in_arrow) as.data.frame(dbFetchArrow(rs)) dbClearResult(rs) ## ----------------------------------------------------------------------------- stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbWriteTableArrow(con, "tbl_new", stream) dbReadTable(con, "tbl_new") ## ----------------------------------------------------------------------------- stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3") dbCreateTableArrow(con, "tbl_split", stream) dbAppendTableArrow(con, "tbl_split", stream) stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a >= 3") dbAppendTableArrow(con, "tbl_split", stream) dbReadTable(con, "tbl_split") ## ----------------------------------------------------------------------------- dbDisconnect(con) DBI/inst/doc/DBI-advanced.Rmd0000644000176200001440000002655715143057347015227 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, 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.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-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/docs/server/reference/sql-statements/prepared-statements/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") ``` Do not forget to disconnect from the database at the end. ```{r} 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-history.Rmd0000644000176200001440000001221414602466070015140 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-1.html0000644000176200001440000042621315147357114014034 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.
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.
Chambers, John M. 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-advanced.html0000644000176200001440000013505715147357121015442 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.fel.cvut.cz",
  port = 3306,
  username = "guest",
  password = "ctu-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.

Do not forget to disconnect from the database at the end.

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.Rmd0000644000176200001440000001624315005325062013440 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} knitr::opts_chunk$set( echo = TRUE, 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-data.org/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.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-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.fel.cvut.cz", port = 3306, username = "guest", password = keyring::key_get("relational.fel.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(), host = "relational.fel.cvut.cz", port = 3306, username = "guest", password = "ctu-relational", 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.html0000644000176200001440000006375615147357127013713 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-data.org/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.fel.cvut.cz",
  port = 3306,
  username = "guest",
  password = "ctu-relational",
  dbname = "sakila"
)

dbListTables(con)
##  [1] "country"       "city"          "customer"      "address"      
##  [5] "film_actor"    "store"         "film_category" "inventory"    
##  [9] "actor"         "film_text"     "payment"       "category"     
## [13] "film"          "rental"        "language"      "staff"
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.fel.cvut.cz",
  port = 3306,
  username = "guest",
  password = keyring::key_get("relational.fel.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(),
  host = "relational.fel.cvut.cz",
  port = 3306,
  username = "guest",
  password = "ctu-relational",
  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:   SQL [?? x 3]
## # Database: mysql  [guest@relational.fel.cvut.cz:3306/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/DBI-proposal.Rmd0000644000176200001440000006635215143057347015316 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](https://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://keittlab.org) 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 (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](https://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.Rmd0000644000176200001440000002413615005150137014430 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-arrow.html0000644000176200001440000006203115147357122015017 0ustar liggesusers Using DBI with Arrow

Using DBI with Arrow

Kirill Müller

25/12/2023

Who this tutorial is for

This tutorial is for you if you want to leverage Apache Arrow for accessing and manipulating data on databases. See vignette("DBI", package = "DBI") and vignette("DBI-advanced", package = "DBI") for tutorials on accessing data using R’s data frames instead of Arrow’s structures.

Rationale

Apache Arrow is

a cross-language development platform for in-memory analytics,

suitable for large and huge data, with support for out-of-memory operation. Arrow is also a data exchange format, the data types covered by Arrow align well with the data types supported by SQL databases.

DBI 1.2.0 introduced support for Arrow as a format for exchanging data between R and databases. The aim is to:

  • accelerate data retrieval and loading, by using fewer costly data conversions;
  • better support reading and summarizing data from a database that is larger than memory;
  • provide better type fidelity with workflows centered around Arrow.

This allows existing code to be used with Arrow, and it allows new code to be written that is more efficient and more flexible than code that uses R’s data frames.

The interface is built around the {nanoarrow} R package, with nanoarrow::as_nanoarrow_array and nanoarrow::as_nanoarrow_array_stream as fundamental data structures.

New classes and generics

DBI 1.2.0 introduces new classes and generics for working with Arrow data:

  • dbReadTableArrow()
  • dbWriteTableArrow()
  • dbCreateTableArrow()
  • dbAppendTableArrow()
  • dbGetQueryArrow()
  • dbSendQueryArrow()
  • dbBindArrow()
  • dbFetchArrow()
  • dbFetchArrowChunk()
  • DBIResultArrow-class
  • DBIResultArrowDefault-class

Compatibility is important for DBI, and implementing new generics and classes greatly reduces the risk of breaking existing code. The DBI package comes with a fully functional fallback implementation for all existing DBI backends. The fallback is not improving performance, but it allows existing code to be used with Arrow before switching to a backend with native Arrow support. Backends with native support, like the adbi package, implement the new generics and classes for direct support and improved performance.

In the remainder of this tutorial, we will demonstrate the new generics and classes using the RSQLite package. SQLite is an in-memory database, this code does not need a database server to be installed and running.

Prepare

We start by setting up a database connection and creating a table with some data, using the original dbWriteTable() method.

library(DBI)

con <- dbConnect(RSQLite::SQLite())

data <- data.frame(
  a = 1:3,
  b = 4.5,
  c = "five"
)

dbWriteTable(con, "tbl", data)

Read all rows from a table

The dbReadTableArrow() method reads all rows from a table into an Arrow stream, similarly to dbReadTable(). Arrow objects implement the as.data.frame() method, so we can convert the stream to a data frame.

stream <- dbReadTableArrow(con, "tbl")
stream
## <nanoarrow_array_stream struct<a: int32, b: double, c: string>>
##  $ get_schema:function ()  
##  $ get_next  :function (schema = x$get_schema(), validate = TRUE)  
##  $ release   :function ()
as.data.frame(stream)
##   a   b    c
## 1 1 4.5 five
## 2 2 4.5 five
## 3 3 4.5 five

Run queries

The dbGetQueryArrow() method runs a query and returns the result as an Arrow stream. This stream can be turned into an arrow::RecordBatchReader object and processed further, without bringing it into R.

stream <- dbGetQueryArrow(con, "SELECT COUNT(*) AS n FROM tbl WHERE a < 3")
stream
## <nanoarrow_array_stream struct<n: int32>>
##  $ get_schema:function ()  
##  $ get_next  :function (schema = x$get_schema(), validate = TRUE)  
##  $ release   :function ()
path <- tempfile(fileext = ".parquet")
arrow::write_parquet(arrow::as_record_batch_reader(stream), path)
arrow::read_parquet(path)
## # A data frame: 1 × 1
##       n
## * <int>
## 1     2

Prepared queries

The dbGetQueryArrow() method supports prepared queries, using the params argument which accepts a data frame or a list.

params <- data.frame(a = 3L)
stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params)
as.data.frame(stream)
##   batch a   b    c
## 1     3 1 4.5 five
## 2     3 2 4.5 five
params <- data.frame(a = c(2L, 4L))
# Equivalent to dbBind()
stream <- dbGetQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a", params = params)
as.data.frame(stream)
##   batch a   b    c
## 1     2 1 4.5 five
## 2     4 1 4.5 five
## 3     4 2 4.5 five
## 4     4 3 4.5 five

Manual flow

For the manual flow, use dbSendQueryArrow() to send a query to the database, and dbFetchArrow() to fetch the result. This also allows using the new dbBindArrow() method to bind data in Arrow format to a prepared query. Result objects must be cleared with dbClearResult().

rs <- dbSendQueryArrow(con, "SELECT $a AS batch, * FROM tbl WHERE a < $a")

in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1L))
dbBindArrow(rs, in_arrow)
as.data.frame(dbFetchArrow(rs))
## [1] batch a     b     c    
## <0 rows> (or 0-length row.names)
in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 2L))
dbBindArrow(rs, in_arrow)
as.data.frame(dbFetchArrow(rs))
##   batch a   b    c
## 1     2 1 4.5 five
in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 3L))
dbBindArrow(rs, in_arrow)
as.data.frame(dbFetchArrow(rs))
##   batch a   b    c
## 1     3 1 4.5 five
## 2     3 2 4.5 five
in_arrow <- nanoarrow::as_nanoarrow_array(data.frame(a = 1:4L))
dbBindArrow(rs, in_arrow)
as.data.frame(dbFetchArrow(rs))
##   batch a   b    c
## 1     2 1 4.5 five
## 2     3 1 4.5 five
## 3     3 2 4.5 five
## 4     4 1 4.5 five
## 5     4 2 4.5 five
## 6     4 3 4.5 five
dbClearResult(rs)

Writing data

Streams returned by dbGetQueryArrow() and dbReadTableArrow() can be written to a table using dbWriteTableArrow().

stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3")
dbWriteTableArrow(con, "tbl_new", stream)
dbReadTable(con, "tbl_new")
##   a   b    c
## 1 1 4.5 five
## 2 2 4.5 five

Appending data

For more control over the writing process, use dbCreateTableArrow() and dbAppendTableArrow().

stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a < 3")
dbCreateTableArrow(con, "tbl_split", stream)
dbAppendTableArrow(con, "tbl_split", stream)
## [1] 2
stream <- dbGetQueryArrow(con, "SELECT * FROM tbl WHERE a >= 3")
dbAppendTableArrow(con, "tbl_split", stream)
## [1] 1
dbReadTable(con, "tbl_split")
##   a   b    c
## 1 1 4.5 five
## 2 2 4.5 five
## 3 3 4.5 five

Conclusion

Do not forget to disconnect from the database when done.

dbDisconnect(con)

That concludes the major features of DBI’s new Arrow interface. For more details on the library functions covered in this tutorial see the DBI specification at vignette("spec", package = "DBI"). See the adbi package for a backend with native Arrow support, and nanoarrow and arrow for packages to work with the Arrow format.

DBI/README.md0000644000176200001440000001371415005150137012132 0ustar liggesusers # DBI [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) [![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://app.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, 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://r-dbi.org/) hosts a blog where recent developments are presented. - [A history of DBI](https://dbi.r-dbi.org/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.html). By contributing to this project, you agree to abide by its terms. DBI/build/0000755000176200001440000000000015147357131011756 5ustar liggesusersDBI/build/vignette.rds0000644000176200001440000000067715147357131014327 0ustar liggesusersSMS0 C@Q8yZozukhS&$pg{7%)W=$M۾v !i4~[ WW4Hf:β}E+p) HrUK ESC34|gginE c*Si^ً'#: /19{Q +e02X`ѻt˥XJu"8MdRd0#xFhN1Gh0[i,c\)p{dmZIXWȸY=9BzhWs}NfKvr)ͅ7jlh9@k3E醜8ӌ)lY1IR7DFq}0oiMPMG1X/_ywW~sS h4џO`KU}2V Z߮vj^:{M;-{nE FX0?rlB.`>8{SYË.~[7LOqZ˸LAVPsFrdȢdlt#OO,ُ?GN>]L#wGܘql ȥ S# ==˙v15W*n)#%K4[~RETJAb]C֭g^YdC[|oOh=ʚgFE0 غe#G ȗ Kd :&< 4w$$#@cG%tJW/O_(Cz;Dq&*eݮ3!1:l=L"#IuJgś. Y#d9YRSmT F6 ii8W{׮ pӯGN}R1WNMq+Y+&͑ GPMͲt賭 V&@rd4BFV0; inMY]t'&aVZ`"%osM0^~]~ꗛ'k-3v𾃼Eh^}EN];$i4fRj/,T? @8{*r& H}@ۀGa +$GIkTEc|E({{7*ܸ}<.? ilE (Z+Qk?33z|u%6`uwތU/.t[\Tgy7Ҧ[t_—3g['W xU%0(կ ~(߇o;O7\sB |\ 坲u#HGm,^;!E'tCOMW|ײ%˟VOKa(޴kf4lE鲍9<7sRَ.jƭa*=Tꭔŕ6K[۫_3n̩ } 31(-`TlV-oa#m4wMz` CSi]=JZkvA_`[P%z,SBαGV f'y#K}L;@Lo~6@kTBT K͛ >.,?; i(*- =^}28{B:{bxj(!> kj(6޹}-TU&t:l]ISA-<%ܵ` vzva.zלh04> ɕre!fC -TaܵOO rA<~s>XKmEeeLM:uɧ;Yh}IFR L(o 7pRڿQZHit;4K YY֐6|c8ϼ#{`Tv[ptSAG0kVm 3կbQ>|&ē4HSŬU͝"\$t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323731011422 5ustar liggesusersDBI/man/dbGetQueryArrow.Rd0000644000176200001440000001502515005323731015002 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetQueryArrow.R \name{dbGetQueryArrow} \alias{dbGetQueryArrow} \title{Retrieve results from a query as an Arrow object} \usage{ dbGetQueryArrow(conn, statement, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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{dbGetQueryArrow()} always returns an object coercible to 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{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} Returns the result of a query as an Arrow object. \code{dbGetQueryArrow()} comes with a default implementation (which should work with most backends) that calls \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}}, then \code{\link[=dbFetchArrow]{dbFetchArrow()}}, ensuring that the result is always freed by \code{\link[=dbClearResult]{dbClearResult()}}. For passing query parameters, see \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}}, in particular the "The data retrieval flow for Arrow streams" section. For retrieving results as a data frame, see \code{\link[=dbGetQuery]{dbGetQuery()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetQueryArrow")} } \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 or data manipulation queries like \verb{INSERT INTO ... RETURNING ...}). 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. 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. The object returned by \code{dbGetQueryArrow()} can also be passed to \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}} to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific. } \section{Additional arguments}{ The following arguments are not part of the \code{dbGetQueryArrow()} 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" and "Value" sections for details on their usage. The \code{param} argument allows passing query parameters, see \code{\link[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Retrieve data as arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbGetQueryArrow(con, "SELECT * FROM mtcars") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \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{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIConnection generics} \concept{data retrieval generics} DBI/man/dbConnect.Rd0000644000176200001440000000754115005323731013617 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 \link[=DBIDriver-class]{DBI::DBIDriver}, or an existing \link[=DBIConnection-class]{DBI::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 \link[DBI:DBIConnection-class]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} # 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:")) \dontshow{\}) # examplesIf} } \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/DBI-package.Rd0000644000176200001440000000513115005323731013700 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 \link[DBI:DBIDriver-class]{DBI::DBIDriver}, \link[DBI:DBIConnection-class]{DBI::DBIConnection}, and \link[DBI:DBIResult-class]{DBI::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 \link[DBI:DBIDriver-class]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} RSQLite::SQLite() \dontshow{\}) # examplesIf} } \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{kirill@cynkra.com} (\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/dbAppendTableArrow.Rd0000644000176200001440000001326315005323731015416 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/21-dbAppendTableArrow.R \name{dbAppendTableArrow} \alias{dbAppendTableArrow} \title{Insert rows into a table from an Arrow stream} \usage{ dbAppendTableArrow(conn, name, value, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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}{An object coercible with \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}}.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbAppendTableArrow()} returns a scalar numeric. } \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} The \code{dbAppendTableArrow()} method assumes that the table has been created beforehand, e.g. with \code{\link[=dbCreateTableArrow]{dbCreateTableArrow()}}. The default implementation calls \code{\link[=dbAppendTable]{dbAppendTable()}} for each chunk of the stream. Use \code{\link[=dbAppendTable]{dbAppendTable()}} to append data from a data.frame. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbAppendTableArrow")} } \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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}} or if this results in a non-scalar. } \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[DBI:dbReadTable]{DBI::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 (possibly returned as character) \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{dbAppendTableArrow()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done to support databases that allow non-syntactic names for their objects: } 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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTableArrow(con, "iris", iris[0, ]) dbAppendTableArrow(con, "iris", iris[1:5, ]) dbReadTable(con, "iris") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbGetQuery.Rd0000644000176200001440000001610515005323731013767 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbGetQuery.R \name{dbGetQuery} \alias{dbGetQuery} \title{Retrieve results from a query} \usage{ dbGetQuery(conn, statement, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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 freed by \code{\link[=dbClearResult]{dbClearResult()}}. For retrieving chunked/paged results or for passing query parameters, see \code{\link[=dbSendQuery]{dbSendQuery()}}, in particular the "The data retrieval flow" section. For retrieving results as an Arrow object, see \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}}. \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 or data manipulation queries like \verb{INSERT INTO ... RETURNING ...}). 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[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIConnection generics} \concept{data retrieval generics} DBI/man/dbListObjects.Rd0000644000176200001440000001077015005323731014451 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 \link[=DBIConnection-class]{DBI::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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbWriteTable]{DBI::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{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[DBI:dbListTables]{DBI::dbListTables()}}, The \code{table} object can be quoted with \code{\link[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}. The result of quoting can be passed to \code{\link[DBI:dbUnquoteIdentifier]{DBI::dbUnquoteIdentifier()}}. (For backends it may be convenient to use the \link[DBI:Id]{DBI::Id} class, but this is not required.) 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[DBI:dbExistsTable]{DBI::dbExistsTable()}} which returns \code{TRUE}. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListObjects(con) dbWriteTable(con, "mtcars", mtcars) dbListObjects(con) dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbQuoteIdentifier.Rd0000644000176200001440000000761515005323731015330 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 \link[=DBIConnection-class]{DBI::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[DBI:SQL]{DBI::SQL} should also return them unchanged. (For backends it may be most convenient to return \link[DBI:SQL]{DBI::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[DBI:dbGetQuery]{DBI::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 DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbWriteTableArrow.Rd0000644000176200001440000001660715005323731015306 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/23-dbWriteTableArrow.R \name{dbWriteTableArrow} \alias{dbWriteTableArrow} \title{Copy Arrow objects to database tables} \usage{ dbWriteTableArrow(conn, name, value, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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}{An nanoarray stream, or an object coercible to a nanoarray stream with \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}}.} \item{...}{Other parameters passed on to methods.} } \value{ \code{dbWriteTableArrow()} returns \code{TRUE}, invisibly. } \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} Writes, overwrites or appends an Arrow object to a database table. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbWriteTableArrow")} } \details{ This function expects an Arrow object. Convert a data frame to an Arrow object with \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}} or use \code{\link[=dbWriteTable]{dbWriteTable()}} to write a data frame. This function is useful if you want to create and load a table at the same time. Use \code{\link[=dbAppendTableArrow]{dbAppendTableArrow()}} for appending data to an existing table, \code{\link[=dbCreateTableArrow]{dbCreateTableArrow()}} for creating a table and specifying field types, and \code{\link[=dbRemoveTable]{dbRemoveTable()}} for overwriting tables. } \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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}} or if this results in a non-scalar. Invalid values for the additional arguments \code{overwrite}, \code{append}, and \code{temporary} (non-scalars, unsupported data types, \code{NA}, incompatible values, incompatible columns) also raise an error. } \section{Additional arguments}{ The following arguments are not part of the \code{dbWriteTableArrow()} generic (to improve compatibility across backends) but are part of the DBI specification: \itemize{ \item \code{overwrite} (default: \code{FALSE}) \item \code{append} (default: \code{FALSE}) \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{dbWriteTableArrow()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbReadTable]{DBI::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 (possibly returned as character) \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. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTableArrow(con, "mtcars", nanoarrow::as_nanoarrow_array_stream(mtcars[1:5, ])) dbReadTable(con, "mtcars") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()} } \concept{DBIConnection generics} DBI/man/dbDataType.Rd0000644000176200001440000001200515005323731013730 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 \link[=DBIDriver-class]{DBI::DBIDriver} or \link[=DBIConnection-class]{DBI::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[DBI:dbDataType]{DBI::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) \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} 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/dot-SQL92Keywords.Rd0000644000176200001440000000064114602466070015046 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/deprecated.R \docType{data} \name{.SQL92Keywords} \alias{.SQL92Keywords} \title{Keywords according to the SQL-92 standard} \format{ An object of class \code{character} of length 220. } \usage{ .SQL92Keywords } \description{ A character vector of SQL-92 keywords, uppercase. } \examples{ "SELECT" \%in\% .SQL92Keywords } \keyword{datasets} DBI/man/transactions.Rd0000644000176200001440000000763315005323731014432 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 \link[=DBIConnection-class]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ Self-contained transactions: \code{\link[=dbWithTransaction]{dbWithTransaction()}} } DBI/man/dbListConnections.Rd0000644000176200001440000000147714542245565015363 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/dbExistsTable.Rd0000644000176200001440000000641415005323731014453 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 \link[=DBIConnection-class]{DBI::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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } For all tables listed by \code{\link[DBI:dbListTables]{DBI::dbListTables()}}, \code{dbExistsTable()} returns \code{TRUE}. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbExecute.Rd0000644000176200001440000001337115005323731013626 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbExecute.R \name{dbExecute} \alias{dbExecute} \title{Change database state} \usage{ dbExecute(conn, statement, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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 freed by \code{\link[=dbClearResult]{dbClearResult()}}. For passing query parameters, see \code{\link[=dbBind]{dbBind()}}, in particular the "The command execution flow" section. \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, or a data manipulation query that also returns a result set such as \verb{INSERT INTO ... RETURNING ...}, 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[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ For queries: \code{\link[=dbSendQuery]{dbSendQuery()}} and \code{\link[=dbGetQuery]{dbGetQuery()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other command execution generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbSendStatement}()} } \concept{DBIConnection generics} \concept{command execution generics} DBI/man/DBIConnector-class.Rd0000644000176200001440000000316715005150137015272 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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} # 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) \dontshow{\}) # examplesIf} } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIObject-class}}, \code{\link{DBIResult-class}}, \code{\link{DBIResultArrow-class}} Other DBIConnector generics: \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbGetConnectArgs}()}, \code{\link{dbIsReadOnly}()} } \concept{DBI classes} \concept{DBIConnector generics} DBI/man/sqlData.Rd0000644000176200001440000000330715005150137013303 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. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("sqlData")} } \details{ The default method: \itemize{ \item Converts factors to characters \item Quotes all strings with \code{\link[=dbQuoteIdentifier]{dbQuoteIdentifier()}} \item Converts all columns to strings with \code{\link[=dbQuoteLiteral]{dbQuoteLiteral()}} \item Replaces NA with NULL } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") sqlData(con, head(iris)) sqlData(con, head(mtcars)) dbDisconnect(con) \dontshow{\}) # examplesIf} } DBI/man/dbReadTable.Rd0000644000176200001440000001214415005323731014044 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbReadTable.R \name{dbReadTable} \alias{dbReadTable} \title{Read database tables as data frames} \usage{ dbReadTable(conn, name, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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[DBI:dbGetQuery]{DBI::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[DBI:rownames]{DBI::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. Use \code{\link[=dbReadTableArrow]{dbReadTableArrow()}} instead to obtain an Arrow object. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbReadTable")} } \details{ This function returns a data frame. Use \code{\link[=dbReadTableArrow]{dbReadTableArrow()}} to obtain an Arrow object. } \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 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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars[1:10, ]) dbReadTable(con, "mtcars") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/sqlInterpolate.Rd0000644000176200001440000000643615005150137014726 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 \link[=DBIConnection-class]{DBI::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. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("sqlInterpolate")} } \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/dbIsReadOnly.Rd0000644000176200001440000000464314602466070014245 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. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbIsReadOnly")} } \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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} 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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} 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/man/dbBind.Rd0000644000176200001440000004007415005323731013100 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/15-dbBind.R, R/25-dbBindArrow.R \name{dbBind} \alias{dbBind} \alias{dbBindArrow} \title{Bind values to a parameterized/prepared statement} \usage{ dbBind(res, params, ...) dbBindArrow(res, params, ...) } \arguments{ \item{res}{An object inheriting from \link[=DBIResult-class]{DBI::DBIResult}.} \item{params}{For \code{dbBind()}, a list of values, named or unnamed, or a data frame, with one element/column per query parameter. For \code{dbBindArrow()}, values as a nanoarrow stream, with one column per query parameter.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbBind()} returns the result set, invisibly, for queries issued by \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}} or \code{\link[DBI:dbSendQueryArrow]{DBI::dbSendQueryArrow()}} and also for data manipulation statements issued by \code{\link[DBI:dbSendStatement]{DBI::dbSendStatement()}}. } \description{ For parametrized or prepared statements, the \code{\link[=dbSendQuery]{dbSendQuery()}}, \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}}, and \code{\link[=dbSendStatement]{dbSendStatement()}} functions can be called with statements that contain placeholders for values. The \code{dbBind()} and \code{dbBindArrow()} functions bind these placeholders to actual values, and are intended to be called on the result set before calling \code{\link[=dbFetch]{dbFetch()}} or \code{\link[=dbFetchArrow]{dbFetchArrow()}}. The values are passed to \code{dbBind()} as lists or data frames, and to \code{dbBindArrow()} as a stream created by \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}}. \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} \code{dbBindArrow()} is experimental, as are the other \verb{*Arrow} functions. \code{dbSendQuery()} is compatible with \code{dbBindArrow()}, and \code{dbSendQueryArrow()} is compatible with \code{dbBind()}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbBind")} } \details{ \pkg{DBI} supports parametrized (or prepared) queries and statements via the \code{dbBind()} and \code{dbBindArrow()} generics. 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{RMariaDB} 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{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{The data retrieval flow for Arrow streams}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}, is implemented by \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}}, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}} to create a result set object of class \linkS4class{DBIResultArrow}. \item Optionally, bind query parameters with \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Use \code{\link[=dbFetchArrow]{dbFetchArrow()}} to get a data stream. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{The command execution flow}{ This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbExecute]{dbExecute()}}, which should be sufficient for non-parameterized queries. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendStatement]{dbSendStatement()}} to create a result set object of class \linkS4class{DBIResult}. For some queries you need to pass \code{immediate = TRUE}. \item Optionally, bind query parameters with\code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} to retrieve the number of rows affected by the query. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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[DBI:dbClearResult]{DBI::dbClearResult()}} also raises an error. } \section{Specification}{ \pkg{DBI} clients execute parametrized statements as follows: \enumerate{ \item Call \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}}, \code{\link[DBI:dbSendQueryArrow]{DBI::dbSendQueryArrow()}} or \code{\link[DBI:dbSendStatement]{DBI::dbSendStatement()}} with a query or statement that contains placeholders, store the returned \link[DBI:DBIResult-class]{DBI::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[DBI:dbClearResult]{DBI::dbClearResult()}} via \code{\link[=on.exit]{on.exit()}} right after calling \code{dbSendQuery()} or \code{dbSendStatement()} (see the last enumeration item). Until \code{\link[DBI:dbBind]{DBI::dbBind()}} or \code{\link[DBI:dbBind]{DBI::dbBindArrow()}} have been called, the returned result set object has the following behavior: \itemize{ \item \code{\link[DBI:dbFetch]{DBI::dbFetch()}} raises an error (for \code{dbSendQuery()} and \code{dbSendQueryArrow()}) \item \code{\link[DBI:dbGetRowCount]{DBI::dbGetRowCount()}} returns zero (for \code{dbSendQuery()} and \code{dbSendQueryArrow()}) \item \code{\link[DBI:dbGetRowsAffected]{DBI::dbGetRowsAffected()}} returns an integer \code{NA} (for \code{dbSendStatement()}) \item \code{\link[DBI:dbIsValid]{DBI::dbIsValid()}} returns \code{TRUE} \item \code{\link[DBI:dbHasCompleted]{DBI::dbHasCompleted()}} returns \code{FALSE} } \item Call \code{\link[DBI:dbBind]{DBI::dbBind()}} or \code{\link[DBI:dbBind]{DBI::dbBindArrow()}}: \itemize{ \item For \code{\link[DBI:dbBind]{DBI::dbBind()}}, the \code{params} argument must be a list where all elements have the same lengths and contain values supported by the backend. A \link{data.frame} is internally stored as such a list. \item For \code{\link[DBI:dbBind]{DBI::dbBindArrow()}}, the \code{params} argument must be a nanoarrow array stream, with one column per query parameter. } \item Retrieve the data or the number of affected rows from the \code{DBIResult} object. \itemize{ \item For queries issued by \code{dbSendQuery()} or \code{dbSendQueryArrow()}, call \code{\link[DBI:dbFetch]{DBI::dbFetch()}}. \item For statements issued by \code{dbSendStatements()}, call \code{\link[DBI:dbGetRowsAffected]{DBI::dbGetRowsAffected()}}. (Execution begins immediately after the \code{\link[DBI:dbBind]{DBI::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[DBI:dbClearResult]{DBI::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[=Dates]{Date} (also when stored internally as integer) \item \link[=DateTimeClasses]{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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Data frame flow: 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) \dontshow{\}) # examplesIf} \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Arrow flow: con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "iris", iris) # Using the same query for different values iris_result <- dbSendQueryArrow(con, "SELECT * FROM iris WHERE [Petal.Width] > ?") dbBindArrow( iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(2.3, fix.empty.names = FALSE)) ) as.data.frame(dbFetchArrow(iris_result)) dbBindArrow( iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame(3, fix.empty.names = FALSE)) ) as.data.frame(dbFetchArrow(iris_result)) dbClearResult(iris_result) # Executing the same statement with different values at once iris_result <- dbSendStatement(con, "DELETE FROM iris WHERE [Species] = $species") dbBindArrow(iris_result, nanoarrow::as_nanoarrow_array_stream(data.frame( species = c("setosa", "versicolor", "unknown") ))) dbGetRowsAffected(iris_result) dbClearResult(iris_result) nrow(dbReadTable(con, "iris")) dbDisconnect(con) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()} Other data retrieval generics: \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} Other command execution generics: \code{\link{dbClearResult}()}, \code{\link{dbExecute}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbSendStatement}()} } \concept{DBIResult generics} \concept{DBIResultArrow generics} \concept{command execution generics} \concept{data retrieval generics} DBI/man/dbFetchArrowChunk.Rd0000644000176200001440000001043415005323731015256 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbFetchArrowChunk.R \name{dbFetchArrowChunk} \alias{dbFetchArrowChunk} \title{Fetch the next batch of records from a previously executed query as an Arrow object} \usage{ dbFetchArrowChunk(res, ...) } \arguments{ \item{res}{An object inheriting from \link[=DBIResultArrow-class]{DBI::DBIResultArrow}, created by \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbFetchArrowChunk()} always returns an object coercible to 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{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} Fetch the next chunk of the result set and return it as an Arrow object. The chunk size is implementation-specific. Use \code{\link[=dbFetchArrow]{dbFetchArrow()}} to fetch all results. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbFetchArrowChunk")} } \section{The data retrieval flow for Arrow streams}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}, is implemented by \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}}, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}} to create a result set object of class \linkS4class{DBIResultArrow}. \item Optionally, bind query parameters with \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Use \code{\link[=dbFetchArrow]{dbFetchArrow()}} to get a data stream. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{Failure modes}{ An attempt to fetch from a closed result set raises an error. } \section{Specification}{ Fetching multi-row queries with one or more columns returns the next chunk. The size of the chunk is implementation-specific. The object returned by \code{dbFetchArrowChunk()} can also be passed to \code{\link[nanoarrow:as_nanoarrow_array]{nanoarrow::as_nanoarrow_array()}} to create a nanoarrow array object. The chunk size is implementation-specific. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) # Fetch all results rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") dbHasCompleted(rs) as.data.frame(dbFetchArrowChunk(rs)) dbHasCompleted(rs) as.data.frame(dbFetchArrowChunk(rs)) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Close the result set with \code{\link[=dbClearResult]{dbClearResult()}} as soon as you finish retrieving the records you want. Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIResultArrow generics} \concept{data retrieval generics} DBI/man/dbRemoveTable.Rd0000644000176200001440000001037715005323731014434 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 \link[=DBIConnection-class]{DBI::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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbListTables]{DBI::dbListTables()}}, and \code{\link[DBI:dbExistsTable]{DBI::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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExistsTable(con, "iris") dbWriteTable(con, "iris", iris) dbExistsTable(con, "iris") dbRemoveTable(con, "iris") dbExistsTable(con, "iris") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbListResults.Rd0000644000176200001440000000320415005150137014511 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 \link[=DBIConnection-class]{DBI::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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} \keyword{internal} DBI/man/make.db.names.Rd0000644000176200001440000000671014350241735014325 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/DBIObject-class.Rd0000644000176200001440000000342615005150137014544 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/01-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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ Other DBI classes: \code{\link{DBIConnection-class}}, \code{\link{DBIConnector-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIResult-class}}, \code{\link{DBIResultArrow-class}} } \concept{DBI classes} DBI/man/dbSendQuery.Rd0000644000176200001440000002221315005323731014136 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/14-dbSendQuery.R \name{dbSendQuery} \alias{dbSendQuery} \title{Execute a query on a given database connection} \usage{ dbSendQuery(conn, statement, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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 \link[DBI:DBIResult-class]{DBI::DBIResult}. The result set can be used with \code{\link[DBI:dbFetch]{DBI::dbFetch()}} to extract records. Once you have finished using a result, make sure to clear it with \code{\link[DBI:dbClearResult]{DBI::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()}}. Use \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}} or \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}} instead to retrieve the results as an Arrow object. \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{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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[DBI:dbClearResult]{DBI::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[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIConnection generics} \concept{data retrieval generics} DBI/man/DBIResult-class.Rd0000644000176200001440000000257214602466070014625 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/04-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}}, \code{\link{DBIResultArrow-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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBI classes} \concept{DBIResult generics} DBI/man/dbUnquoteIdentifier.Rd0000644000176200001440000000744115005323731015670 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 \link[=DBIConnection-class]{DBI::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 vector, this function returns a length-0 object. The names of the input argument are preserved in the output. If \code{x} is a value returned by \code{dbUnquoteIdentifier()}, calling \code{dbUnquoteIdentifier(..., dbQuoteIdentifier(..., x))} returns \code{list(x)}. If \code{x} is an object of class \link[DBI:Id]{DBI::Id}, calling \code{dbUnquoteIdentifier(..., x)} returns \code{list(x)}. (For backends it may be most convenient to return \link[DBI:Id]{DBI::Id} objects to achieve this behavior, but this is not required.) Plain character vectors can also be passed to \code{dbUnquoteIdentifier()}. } \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 a character vectors with a missing value is passed as the \code{x} argument. } \section{Specification}{ For any character vector of length one, quoting (with \code{\link[DBI:dbQuoteIdentifier]{DBI::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[DBI:SQL]{DBI::SQL()}} and then quoting via \code{\link[DBI:dbQuoteIdentifier]{DBI::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", "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", "Schema", "Table")) # Quoting and unquoting are inverses dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), SQL("UnqualifiedTable"))[[1]] ) dbQuoteIdentifier( ANSI(), dbUnquoteIdentifier(ANSI(), Id("Schema", "Table"))[[1]] ) } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbCreateTableArrow.Rd0000644000176200001440000001232315005323731015406 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/22-dbCreateTableArrow.R \name{dbCreateTableArrow} \alias{dbCreateTableArrow} \title{Create a table in the database based on an Arrow object} \usage{ dbCreateTableArrow(conn, name, value, ..., temporary = FALSE) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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}{An object for which a schema can be determined via \code{\link[nanoarrow:as_nanoarrow_schema]{nanoarrow::infer_nanoarrow_schema()}}.} \item{...}{Other parameters passed on to methods.} \item{temporary}{If \code{TRUE}, will generate a temporary table.} } \value{ \code{dbCreateTableArrow()} returns \code{TRUE}, invisibly. } \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} The default \code{dbCreateTableArrow()} method determines the R data types of the Arrow schema associated with the Arrow object, and calls \code{\link[=dbCreateTable]{dbCreateTable()}}. Backends that implement \code{\link[=dbAppendTableArrow]{dbAppendTableArrow()}} should typically also implement this generic. Use \code{\link[=dbCreateTable]{dbCreateTable()}} to create a table from the column types as defined in a data frame. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbCreateTableArrow")} } \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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}} or if this results in a non-scalar. Invalid values for the \code{temporary} argument (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{dbCreateTableArrow()} 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{dbCreateTableArrow()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } The \code{value} argument can be: \itemize{ \item a data frame, \item a nanoarrow array \item a nanoarrow array stream (which will still contain the data after the call) \item a nanoarrow schema } 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. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") ptype <- data.frame(a = numeric()) dbCreateTableArrow(con, "df", nanoarrow::infer_nanoarrow_schema(ptype)) dbReadTable(con, "df") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \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{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbListTables.Rd0000644000176200001440000000466115005323731014274 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 \link[=DBIConnection-class]{DBI::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[DBI:dbWriteTable]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbListTables(con) dbWriteTable(con, "mtcars", mtcars) dbListTables(con) dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/Id.Rd0000644000176200001440000000315014602466070012252 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/00-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{cluster}, \code{catalog}, \code{schema}, or \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 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("dbo", "Customer") # You can name the components if you want, but it's not needed Id(table = "Customer", schema = "dbo") # Create a SQL expression for an identifier: dbQuoteIdentifier(ANSI(), Id("nycflights13", "flights")) # Write a table in a specific schema: \dontrun{ dbWriteTable(con, Id("myschema", "mytable"), data.frame(a = 1)) } } DBI/man/dbCreateTable.Rd0000644000176200001440000001305115005323731014372 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/12-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 \link[=DBIConnection-class]{DBI::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.} } \value{ \code{dbCreateTable()} returns \code{TRUE}, invisibly. } \description{ The default \code{dbCreateTable()} method calls \code{\link[=sqlCreateTable]{sqlCreateTable()}} and \code{\link[=dbExecute]{dbExecute()}}. Use \code{\link[=dbCreateTableArrow]{dbCreateTableArrow()}} to create a table from an Arrow schema. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbCreateTable")} } \details{ 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. 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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } The \code{value} argument can be: \itemize{ \item a data frame, \item a named list of SQL types } 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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbHasCompleted.Rd0000644000176200001440000001217015005323731014570 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 \link[=DBIResult-class]{DBI::DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbHasCompleted()} returns a logical scalar. For a query initiated by \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}} with non-empty result set, \code{dbHasCompleted()} returns \code{FALSE} initially and \code{TRUE} after calling \code{\link[DBI:dbFetch]{DBI::dbFetch()}} without limit. For a query initiated by \code{\link[DBI:dbSendStatement]{DBI::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{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{Failure modes}{ Attempting to query completion status for a result set cleared with \code{\link[DBI:dbClearResult]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbIsValid}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIResult generics} \concept{DBIResultArrow generics} \concept{data retrieval generics} DBI/man/dbDriver.Rd0000644000176200001440000000464215005150137013456 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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Create a RSQLite driver with a string d <- dbDriver("SQLite") d # But better, access the object directly RSQLite::SQLite() \dontshow{\}) # examplesIf} } \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/SQL.Rd0000644000176200001440000000360414350241735012360 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/dbGetRowCount.Rd0000644000176200001440000000443115005323731014441 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 \link[=DBIResult-class]{DBI::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[DBI:dbSendQuery]{DBI::dbSendQuery()}}, the row count is initially zero. After a call to \code{\link[DBI:dbFetch]{DBI::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[DBI:dbSendStatement]{DBI::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[DBI:dbClearResult]{DBI::dbClearResult()}} gives an error. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBIResult generics} DBI/man/dbListFields.Rd0000644000176200001440000000637415005323731014273 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 \link[=DBIConnection-class]{DBI::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{ Returns the field names of a remote table as a character vector. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbListFields")} } \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[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}} \item a value from the \code{table} column from the return value of \code{\link[DBI:dbListObjects]{DBI::dbListObjects()}} where \code{is_prefix} is \code{FALSE} } A column named \code{row_names} is treated like any other column. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) dbListFields(con, "mtcars") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ \code{\link[=dbColumnInfo]{dbColumnInfo()}} to get the type of the fields. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/DBIConnection-class.Rd0000644000176200001440000000363715005150137015441 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/03-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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") con dbDisconnect(con) \dontrun{ con <- dbConnect(RPostgreSQL::PostgreSQL(), "username", "password") con dbDisconnect(con) } \dontshow{\}) # examplesIf} } \seealso{ Other DBI classes: \code{\link{DBIConnector-class}}, \code{\link{DBIDriver-class}}, \code{\link{DBIObject-class}}, \code{\link{DBIResult-class}}, \code{\link{DBIResultArrow-class}} Other DBIConnection generics: \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBI classes} \concept{DBIConnection generics} DBI/man/dbGetDBIVersion.Rd0000644000176200001440000000045514350241735014634 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/DBIResultArrow-class.Rd0000644000176200001440000000234614602466070015637 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/07-DBIResultArrow.R \docType{class} \name{DBIResultArrow-class} \alias{DBIResultArrow-class} \alias{DBIResultArrowDefault-class} \title{DBIResultArrow class} \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} This virtual class describes the result and state of execution of a DBMS statement (any statement, query or non-query) for returning data as an Arrow object. } \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}}, \code{\link{DBIResult-class}} Other DBIResultArrow generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()} } \concept{DBI classes} \concept{DBIResultArrow generics} DBI/man/hidden_aliases.Rd0000644000176200001440000002737714602466070014673 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/06-ANSI.R, R/SQLKeywords_DBIObject.R, % R/SQLKeywords_missing.R, R/dbAppendTableArrow_DBIConnection.R, % R/dbAppendTable_DBIConnection.R, R/dbBindArrow_DBIResult.R, % R/dbBindArrow_DBIResultArrowDefault.R, R/dbBind_DBIResultArrow.R, % R/dbCanConnect_DBIDriver.R, R/dbClearResult_DBIResultArrow.R, % R/dbConnect_DBIConnector.R, R/dbCreateTableArrow_DBIConnection.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/dbFetchArrowChunk_DBIResultArrow.R, R/dbFetchArrow_DBIResultArrow.R, % R/dbFetch_DBIResult.R, R/dbFetch_DBIResultArrow.R, % R/dbGetConnectArgs_DBIConnector.R, R/dbGetInfo_DBIResult.R, % R/dbGetInfo_DBIResultArrow.R, R/dbGetQueryArrow_DBIConnection.R, % R/dbGetQuery_DBIConnection_character.R, R/dbGetRowCount_DBIResultArrow.R, % R/dbGetRowsAffected_DBIResultArrow.R, R/dbGetStatement_DBIResultArrow.R, % R/dbHasCompleted_DBIResultArrow.R, R/dbIsReadOnly_DBIConnector.R, % R/dbIsReadOnly_DBIObject.R, R/dbIsValid_DBIResultArrowDefault.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/dbReadTableArrow_DBIConnection.R, R/dbReadTable_DBIConnection_Id.R, % R/dbReadTable_DBIConnection_character.R, % R/dbRemoveTable_DBIConnection_Id.R, R/dbSendQueryArrow_DBIConnection.R, % R/dbSendStatement_DBIConnection_character.R, % R/dbUnquoteIdentifier_DBIConnection.R, R/dbWithTransaction_DBIConnection.R, % R/dbWriteTableArrow_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{dbAppendTableArrow_DBIConnection} \alias{dbAppendTableArrow,DBIConnection-method} \alias{dbAppendTable_DBIConnection} \alias{dbAppendTable,DBIConnection-method} \alias{dbBindArrow_DBIResult} \alias{dbBindArrow,DBIResult-method} \alias{dbBindArrow_DBIResultArrowDefault} \alias{dbBindArrow,DBIResultArrowDefault-method} \alias{dbBind_DBIResultArrow} \alias{dbBind,DBIResultArrow-method} \alias{dbCanConnect_DBIDriver} \alias{dbCanConnect,DBIDriver-method} \alias{dbClearResult_DBIResultArrow} \alias{dbClearResult,DBIResultArrow-method} \alias{dbConnect_DBIConnector} \alias{dbConnect,DBIConnector-method} \alias{dbCreateTableArrow_DBIConnection} \alias{dbCreateTableArrow,DBIConnection-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{dbFetchArrowChunk_DBIResultArrow} \alias{dbFetchArrowChunk,DBIResultArrow-method} \alias{dbFetchArrow_DBIResultArrow} \alias{dbFetchArrow,DBIResultArrow-method} \alias{dbFetch_DBIResult} \alias{dbFetch,DBIResult-method} \alias{dbFetch_DBIResultArrow} \alias{dbFetch,DBIResultArrow-method} \alias{dbGetConnectArgs_DBIConnector} \alias{dbGetConnectArgs,DBIConnector-method} \alias{dbGetInfo_DBIResult} \alias{dbGetInfo,DBIResult-method} \alias{dbGetInfo_DBIResultArrow} \alias{dbGetInfo,DBIResultArrow-method} \alias{dbGetQueryArrow_DBIConnection_character} \alias{dbGetQueryArrow,DBIConnection-method} \alias{dbGetQuery_DBIConnection_character} \alias{dbGetQuery,DBIConnection,character-method} \alias{dbGetRowCount_DBIResultArrow} \alias{dbGetRowCount,DBIResultArrow-method} \alias{dbGetRowsAffected_DBIResultArrow} \alias{dbGetRowsAffected,DBIResultArrow-method} \alias{dbGetStatement_DBIResultArrow} \alias{dbGetStatement,DBIResultArrow-method} \alias{dbHasCompleted_DBIResultArrow} \alias{dbHasCompleted,DBIResultArrow-method} \alias{dbIsReadOnly_DBIConnector} \alias{dbIsReadOnly,DBIConnector-method} \alias{dbIsReadOnly_DBIObject} \alias{dbIsReadOnly,DBIObject-method} \alias{dbIsValid_DBIResultArrowDefault} \alias{dbIsValid,DBIResultArrowDefault-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{dbReadTableArrow_DBIConnection} \alias{dbReadTableArrow,DBIConnection-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{dbSendQueryArrow_DBIConnection} \alias{dbSendQueryArrow,DBIConnection-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{dbWriteTableArrow_DBIConnection} \alias{dbWriteTableArrow,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{dbAppendTableArrow}{DBIConnection}(conn, name, value, ...) \S4method{dbAppendTable}{DBIConnection}(conn, name, value, ..., row.names = NULL) \S4method{dbBindArrow}{DBIResult}(res, params, ...) \S4method{dbBindArrow}{DBIResultArrowDefault}(res, params, ...) \S4method{dbBind}{DBIResultArrow}(res, params, ...) \S4method{dbCanConnect}{DBIDriver}(drv, ...) \S4method{dbClearResult}{DBIResultArrow}(res, ...) \S4method{dbConnect}{DBIConnector}(drv, ...) \S4method{dbCreateTableArrow}{DBIConnection}(conn, name, value, ..., temporary = FALSE) \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{dbFetchArrowChunk}{DBIResultArrow}(res, ...) \S4method{dbFetchArrow}{DBIResultArrow}(res, ...) \S4method{dbFetch}{DBIResult}(res, n = -1, ...) \S4method{dbFetch}{DBIResultArrow}(res, n = -1, ...) \S4method{dbGetConnectArgs}{DBIConnector}(drv, eval = TRUE, ...) \S4method{dbGetInfo}{DBIResult}(dbObj, ...) \S4method{dbGetInfo}{DBIResultArrow}(dbObj, ...) \S4method{dbGetQueryArrow}{DBIConnection}(conn, statement, ...) \S4method{dbGetQuery}{DBIConnection,character}(conn, statement, ..., n = -1L) \S4method{dbGetRowCount}{DBIResultArrow}(res, ...) \S4method{dbGetRowsAffected}{DBIResultArrow}(res, ...) \S4method{dbGetStatement}{DBIResultArrow}(res, ...) \S4method{dbHasCompleted}{DBIResultArrow}(res, ...) \S4method{dbIsReadOnly}{DBIConnector}(dbObj, ...) \S4method{dbIsReadOnly}{DBIObject}(dbObj, ...) \S4method{dbIsValid}{DBIResultArrowDefault}(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{dbReadTableArrow}{DBIConnection}(conn, name, ...) \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{dbSendQueryArrow}{DBIConnection}(conn, statement, params = NULL, ...) \S4method{dbSendStatement}{DBIConnection,character}(conn, statement, ...) \S4method{dbUnquoteIdentifier}{DBIConnection}(conn, x, ...) \S4method{dbWithTransaction}{DBIConnection}(conn, code) \S4method{dbWriteTableArrow}{DBIConnection}( conn, name, value, append = FALSE, overwrite = FALSE, ..., temporary = FALSE ) \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/dbWriteTable.Rd0000644000176200001440000002141615005323731014265 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/13-dbWriteTable.R \name{dbWriteTable} \alias{dbWriteTable} \title{Copy data frames to database tables} \usage{ dbWriteTable(conn, name, value, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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 expects a data frame. Use \code{\link[=dbWriteTableArrow]{dbWriteTableArrow()}} to write an Arrow object. This function is useful if you want to create and load a table at the same time. Use \code{\link[=dbAppendTable]{dbAppendTable()}} or \code{\link[=dbAppendTableArrow]{dbAppendTableArrow()}} for appending data to an existing table, \code{\link[=dbCreateTable]{dbCreateTable()}} or \code{\link[=dbCreateTableArrow]{dbCreateTableArrow()}} for creating a table, and \code{\link[=dbExistsTable]{dbExistsTable()}} and \code{\link[=dbRemoveTable]{dbRemoveTable()}} for overwriting tables. DBI only standardizes writing data frames with \code{dbWriteTable()}. 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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbReadTable]{DBI::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[DBI:dbDataType]{DBI::dbDataType()}}. The interpretation of \link{rownames} depends on the \code{row.names} argument, see \code{\link[DBI:rownames]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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") \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/figures/0000755000176200001440000000000014602466070013074 5ustar liggesusersDBI/man/figures/lifecycle-questioning.svg0000644000176200001440000000244414602466070020123 0ustar liggesusers lifecycle: questioning lifecycle questioning DBI/man/figures/lifecycle-stable.svg0000644000176200001440000000247214602466070017031 0ustar liggesusers lifecycle: stable lifecycle stable DBI/man/figures/lifecycle-experimental.svg0000644000176200001440000000245014602466070020250 0ustar liggesusers lifecycle: experimental lifecycle experimental DBI/man/figures/lifecycle-deprecated.svg0000644000176200001440000000244014602466070017652 0ustar liggesusers lifecycle: deprecated lifecycle deprecated DBI/man/figures/lifecycle-superseded.svg0000644000176200001440000000244014602466070017715 0ustar liggesusers lifecycle: superseded lifecycle superseded DBI/man/figures/lifecycle-archived.svg0000644000176200001440000000243014602466070017336 0ustar liggesusers lifecycle: archived lifecycle archived DBI/man/figures/lifecycle-defunct.svg0000644000176200001440000000242414602466070017204 0ustar liggesusers lifecycle: defunct lifecycle defunct DBI/man/figures/lifecycle-soft-deprecated.svg0000644000176200001440000000246614602466070020633 0ustar liggesusers lifecycle: soft-deprecated lifecycle soft-deprecated DBI/man/figures/lifecycle-maturing.svg0000644000176200001440000000243014602466070017377 0ustar liggesusers lifecycle: maturing lifecycle maturing DBI/man/rownames.Rd0000644000176200001440000000267714350241735013565 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/dbQuoteLiteral.Rd0000644000176200001440000000570715005323731014642 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 \link[=DBIConnection-class]{DBI::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[DBI:SQL]{DBI::SQL} should also return them unchanged. (For backends it may be most convenient to return \link[DBI:SQL]{DBI::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{dbQuoteString}()} } \concept{DBIResult generics} DBI/man/dbSendQueryArrow.Rd0000644000176200001440000002020715005323731015152 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/24-dbSendQueryArrow.R \name{dbSendQueryArrow} \alias{dbSendQueryArrow} \title{Execute a query on a given database connection for retrieval via Arrow} \usage{ dbSendQueryArrow(conn, statement, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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{dbSendQueryArrow()} returns an S4 object that inherits from \link[DBI:DBIResultArrow-class]{DBI::DBIResultArrow}. The result set can be used with \code{\link[DBI:dbFetchArrow]{DBI::dbFetchArrow()}} to extract records. Once you have finished using a result, make sure to clear it with \code{\link[DBI:dbClearResult]{DBI::dbClearResult()}}. } \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} The \code{dbSendQueryArrow()} 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[=dbFetchArrow]{dbFetchArrow()}} 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[=dbGetQueryArrow]{dbGetQueryArrow()}}. Use \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbGetQuery]{dbGetQuery()}} instead to retrieve the results as a data frame. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbSendQueryArrow")} } \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. } \section{The data retrieval flow for Arrow streams}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}, is implemented by \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}}, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}} to create a result set object of class \linkS4class{DBIResultArrow}. \item Optionally, bind query parameters with \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Use \code{\link[=dbFetchArrow]{dbFetchArrow()}} to get a data stream. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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{dbSendQueryArrow()} 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[DBI:dbClearResult]{DBI::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[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Retrieve data as arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") dbFetchArrow(rs) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ For updates: \code{\link[=dbSendStatement]{dbSendStatement()}} and \code{\link[=dbExecute]{dbExecute()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()} } \concept{DBIConnection generics} \concept{data retrieval generics} DBI/man/dbGetStatement.Rd0000644000176200001440000000327515005323731014632 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 \link[=DBIResult-class]{DBI::DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbGetStatement()} returns a string, the query used in either \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}} or \code{\link[DBI:dbSendStatement]{DBI::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[DBI:dbClearResult]{DBI::dbClearResult()}} gives an error. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendQuery(con, "SELECT * FROM mtcars") dbGetStatement(rs) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBIResult generics} DBI/man/dbSendStatement.Rd0000644000176200001440000002036415005323731015002 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 \link[=DBIConnection-class]{DBI::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 \link[DBI:DBIResult-class]{DBI::DBIResult}. The result set can be used with \code{\link[DBI:dbGetRowsAffected]{DBI::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[DBI:dbClearResult]{DBI::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{The command execution flow}{ This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbExecute]{dbExecute()}}, which should be sufficient for non-parameterized queries. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendStatement]{dbSendStatement()}} to create a result set object of class \linkS4class{DBIResult}. For some queries you need to pass \code{immediate = TRUE}. \item Optionally, bind query parameters with\code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} to retrieve the number of rows affected by the query. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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[DBI:dbClearResult]{DBI::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[DBI:dbBind]{DBI::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[DBI:dbBind]{DBI::dbBind()}} \item \code{params} given: query is executed } } } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \seealso{ For queries: \code{\link[=dbSendQuery]{dbSendQuery()}} and \code{\link[=dbGetQuery]{dbGetQuery()}}. Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} Other command execution generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbExecute}()}, \code{\link{dbGetRowsAffected}()} } \concept{DBIConnection generics} \concept{command execution generics} DBI/man/dbGetConnectArgs.Rd0000644000176200001440000000245415005150137015070 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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} cnr <- new("DBIConnector", .drv = RSQLite::SQLite(), .conn_args = list(dbname = ":memory:", password = function() "supersecret") ) dbGetConnectArgs(cnr) dbGetConnectArgs(cnr, eval = FALSE) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnector generics: \code{\link{DBIConnector-class}}, \code{\link{dbConnect}()}, \code{\link{dbDataType}()}, \code{\link{dbIsReadOnly}()} } \concept{DBIConnector generics} DBI/man/dbGetException.Rd0000644000176200001440000000314715005150137014620 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 \link[=DBIConnection-class]{DBI::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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} \keyword{internal} DBI/man/dbCanConnect.Rd0000644000176200001440000000337215005150137014235 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 \link[=DBIDriver-class]{DBI::DBIDriver}, or an existing \link[=DBIConnection-class]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} # 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:") \dontshow{\}) # examplesIf} } \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/dbFetch.Rd0000644000176200001440000002030715005323731013252 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 \link[=DBIResult-class]{DBI::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. Passing \code{n = NA} is supported and returns an arbitrary number of rows (at least one) as specified by the driver, but at most the remaining rows in the result set. } \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{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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[DBI:dbSendStatement]{DBI::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[=Dates]{Date} for dates (also applies to the return value of the SQL function \code{current_date}) \item \link[=DateTimeClasses]{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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIResult generics} \concept{data retrieval generics} DBI/man/dbReadTableArrow.Rd0000644000176200001440000000745515005323731015070 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbReadTableArrow.R \name{dbReadTableArrow} \alias{dbReadTableArrow} \title{Read database tables as Arrow objects} \usage{ dbReadTableArrow(conn, name, ...) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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{dbReadTableArrow()} returns an Arrow object that contains the complete data from the remote table, effectively the result of calling \code{\link[DBI:dbGetQueryArrow]{DBI::dbGetQueryArrow()}} with \verb{SELECT * FROM }. An empty table is returned as an Arrow object with zero rows. } \description{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} Reads a database table as an Arrow object. Use \code{\link[=dbReadTable]{dbReadTable()}} instead to obtain a data frame. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbReadTableArrow")} } \details{ This function returns an Arrow object. Convert it to a data frame with \code{\link[=as.data.frame]{as.data.frame()}} or use \code{\link[=dbReadTable]{dbReadTable()}} to obtain a data frame. } \section{Failure modes}{ An error is raised if the table does not exist. 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[DBI:dbQuoteIdentifier]{DBI::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{dbReadTableArrow()} will do the quoting, perhaps by calling \code{dbQuoteIdentifier(conn, x = name)} \item If the result of a call to \code{\link[DBI:dbQuoteIdentifier]{DBI::dbQuoteIdentifier()}}: no more quoting is done } } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} # Read data as Arrow table con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars[1:10, ]) dbReadTableArrow(con, "mtcars") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/dbClearResult.Rd0000644000176200001440000001452615005323731014454 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 \link[=DBIResult-class]{DBI::DBIResult}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbClearResult()} returns \code{TRUE}, invisibly, for result sets obtained from \code{dbSendQuery()}, \code{dbSendStatement()}, or \code{dbSendQueryArrow()}, } \description{ Frees all resources (local and remote) associated with a result set. This step is mandatory for all objects obtained by calling \code{\link[=dbSendQuery]{dbSendQuery()}} or \code{\link[=dbSendStatement]{dbSendStatement()}}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbClearResult")} } \section{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{The command execution flow}{ This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbExecute]{dbExecute()}}, which should be sufficient for non-parameterized queries. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendStatement]{dbSendStatement()}} to create a result set object of class \linkS4class{DBIResult}. For some queries you need to pass \code{immediate = TRUE}. \item Optionally, bind query parameters with\code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} to retrieve the number of rows affected by the query. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{Failure modes}{ An attempt to close an already closed result set issues a warning for \code{dbSendQuery()}, \code{dbSendStatement()}, and \code{dbSendQueryArrow()}, } \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[DBI:dbSendQuery]{DBI::dbSendQuery()}} or \code{\link[DBI:dbSendStatement]{DBI::dbSendStatement()}} call. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") rs <- dbSendQuery(con, "SELECT 1") print(dbFetch(rs)) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbBind}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} Other command execution generics: \code{\link{dbBind}()}, \code{\link{dbExecute}()}, \code{\link{dbGetRowsAffected}()}, \code{\link{dbSendStatement}()} } \concept{DBIResult generics} \concept{DBIResultArrow generics} \concept{command execution generics} \concept{data retrieval generics} DBI/man/dbDisconnect.Rd0000644000176200001440000000410715005323731014312 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 \link[=DBIConnection-class]{DBI::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. At least one warning is issued immediately when calling \code{dbDisconnect()} on an already disconnected or invalid connection. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTable}()}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/ANSI.Rd0000644000176200001440000000046314602466070012454 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/06-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/dbFetchArrow.Rd0000644000176200001440000001023015005323731014257 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/dbFetchArrow.R \name{dbFetchArrow} \alias{dbFetchArrow} \title{Fetch records from a previously executed query as an Arrow object} \usage{ dbFetchArrow(res, ...) } \arguments{ \item{res}{An object inheriting from \link[=DBIResultArrow-class]{DBI::DBIResultArrow}, created by \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}}.} \item{...}{Other arguments passed on to methods.} } \value{ \code{dbFetchArrow()} always returns an object coercible to 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{ \ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#experimental}{\figure{lifecycle-experimental.svg}{options: alt='[Experimental]'}}}{\strong{[Experimental]}} Fetch the result set and return it as an Arrow object. Use \code{\link[=dbFetchArrowChunk]{dbFetchArrowChunk()}} to fetch results in chunks. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbFetchArrow")} } \section{The data retrieval flow for Arrow streams}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as an Arrow stream. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}, is implemented by \code{\link[=dbGetQueryArrow]{dbGetQueryArrow()}}, which should be sufficient unless you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQueryArrow]{dbSendQueryArrow()}} to create a result set object of class \linkS4class{DBIResultArrow}. \item Optionally, bind query parameters with \code{\link[=dbBindArrow]{dbBindArrow()}} or \code{\link[=dbBind]{dbBind()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Use \code{\link[=dbFetchArrow]{dbFetchArrow()}} to get a data stream. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{Failure modes}{ An attempt to fetch from a closed result set raises an error. } \section{Specification}{ Fetching multi-row queries with one or more columns by default returns the entire result. The object returned by \code{dbFetchArrow()} can also be passed to \code{\link[nanoarrow:as_nanoarrow_array_stream]{nanoarrow::as_nanoarrow_array_stream()}} to create a nanoarrow array stream object that can be used to read the result set in batches. The chunk size is implementation-specific. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE) && requireNamespace("nanoarrow", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) # Fetch all results rs <- dbSendQueryArrow(con, "SELECT * FROM mtcars WHERE cyl = 4") as.data.frame(dbFetchArrow(rs)) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Close the result set with \code{\link[=dbClearResult]{dbClearResult()}} as soon as you finish retrieving the records you want. Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbIsValid}()} Other data retrieval generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetch}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbHasCompleted}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()} } \concept{DBIResultArrow generics} \concept{data retrieval generics} DBI/man/sqlAppendTable.Rd0000644000176200001440000000531514350241735014621 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. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("sqlAppendTable")} } \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/dbCallProc.Rd0000644000176200001440000000127415005150137013720 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 \link[=DBIConnection-class]{DBI::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/dbSetDataMappings.Rd0000644000176200001440000000167115005150137015246 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 \link[=DBIResult-class]{DBI::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/dbWithTransaction.Rd0000644000176200001440000000665615005323731015355 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 \link[=DBIConnection-class]{DBI::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 or if \code{\link[DBI:transactions]{DBI::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[DBI:transactions]{DBI::dbCommit()}}. If the code raises an error, the transaction is instead aborted with \code{\link[DBI:transactions]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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 current 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) \dontshow{\}) # examplesIf} } DBI/man/dbGetRowsAffected.Rd0000644000176200001440000000747315005323731015246 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 \link[=DBIResult-class]{DBI::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[DBI:dbSendStatement]{DBI::dbSendStatement()}}. The value is available directly after the call and does not change after calling \code{\link[DBI:dbFetch]{DBI::dbFetch()}}. \code{NA_integer_} or \code{NA_numeric_} are allowed if the number of rows affected is not known. For queries issued with \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}}, zero is returned before and after the call to \code{dbFetch()}. \code{NA} values are not allowed. } \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{The command execution flow}{ This section gives a complete overview over the flow for the execution of SQL statements that have side effects such as stored procedures, inserting or deleting data, or setting database or connection options. Most of this flow, except repeated calling of \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbExecute]{dbExecute()}}, which should be sufficient for non-parameterized queries. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendStatement]{dbSendStatement()}} to create a result set object of class \linkS4class{DBIResult}. For some queries you need to pass \code{immediate = TRUE}. \item Optionally, bind query parameters with\code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbGetRowsAffected]{dbGetRowsAffected()}} to retrieve the number of rows affected by the query. \item Repeat the last two steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \section{Failure modes}{ Attempting to get the rows affected for a result set cleared with \code{\link[DBI:dbClearResult]{DBI::dbClearResult()}} gives an error. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) rs <- dbSendStatement(con, "DELETE FROM mtcars") dbGetRowsAffected(rs) nrow(mtcars) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other command execution generics: \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbExecute}()}, \code{\link{dbSendStatement}()} } \concept{DBIResult generics} \concept{command execution generics} DBI/man/dbQuoteString.Rd0000644000176200001440000000570515005323731014512 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 \link[=DBIConnection-class]{DBI::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[DBI:SQL]{DBI::SQL} should also return them unchanged. (For backends it may be most convenient to return \link[DBI:SQL]{DBI::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{dbQuoteLiteral}()} } \concept{DBIResult generics} DBI/man/dbGetInfo.Rd0000644000176200001440000001070115005323731013551 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/04-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 \link[DBI:DBIDriver-class]{DBI::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 \link[DBI:DBIConnection-class]{DBI::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 \link[DBI:DBIResult-class]{DBI::DBIResult}, \code{dbGetInfo()} returns a named list that contains at least the following components: \itemize{ \item \code{statatment}: the statement used with \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}} or \code{\link[DBI:dbExecute]{DBI::dbExecute()}}, as returned by \code{\link[DBI:dbGetStatement]{DBI::dbGetStatement()}}, \item \code{row.count}: the number of rows fetched so far (for queries), as returned by \code{\link[DBI:dbGetRowCount]{DBI::dbGetRowCount()}}, \item \code{rows.affected}: the number of rows affected (for statements), as returned by \code{\link[DBI:dbGetRowsAffected]{DBI::dbGetRowsAffected()}} \item \code{has.completed}: a logical that indicates if the query or statement has completed, as returned by \code{\link[DBI:dbHasCompleted]{DBI::dbHasCompleted()}}. } } \description{ Retrieves information on objects of class \linkS4class{DBIDriver}, \linkS4class{DBIConnection} or \linkS4class{DBIResult}. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbGetInfo")} } \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()}}. } \examples{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} dbGetInfo(RSQLite::SQLite()) \dontshow{\}) # examplesIf} } \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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} 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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBIConnection generics} \concept{DBIDriver generics} \concept{DBIResult generics} DBI/man/sqlParseVariables.Rd0000644000176200001440000000315414350241735015344 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/DBIDriver-class.Rd0000644000176200001440000000177114602466070014602 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/02-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}}, \code{\link{DBIResultArrow-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/dbAppendTable.Rd0000644000176200001440000001471515005323731014406 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/11-dbAppendTable.R \name{dbAppendTable} \alias{dbAppendTable} \title{Insert rows into a table} \usage{ dbAppendTable(conn, name, value, ..., row.names = NULL) } \arguments{ \item{conn}{A \link[=DBIConnection-class]{DBI::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.} \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. Use \code{\link[=dbAppendTableArrow]{dbAppendTableArrow()}} to append data from an Arrow stream. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbAppendTable")} } \details{ 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. 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[DBI:dbQuoteIdentifier]{DBI::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[DBI:dbReadTable]{DBI::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[DBI:dbQuoteIdentifier]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") dbCreateTable(con, "iris", iris) dbAppendTable(con, "iris", iris) dbReadTable(con, "iris") dbDisconnect(con) \dontshow{\}) # examplesIf} } \seealso{ Other DBIConnection generics: \code{\link{DBIConnection-class}}, \code{\link{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbIsValid}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} } \concept{DBIConnection generics} DBI/man/sqlCreateTable.Rd0000644000176200001440000000455314602466070014621 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.} \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. \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("sqlCreateTable")} } \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/dbColumnInfo.Rd0000644000176200001440000001065315005323731014275 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 \link[=DBIResult-class]{DBI::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[DBI:dbFetch]{DBI::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.) \Sexpr[results=rd,stage=render]{DBI:::methods_as_rd("dbColumnInfo")} } \section{The data retrieval flow}{ This section gives a complete overview over the flow for the execution of queries that return tabular data as data frames. Most of this flow, except repeated calling of \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}, is implemented by \code{\link[=dbGetQuery]{dbGetQuery()}}, which should be sufficient unless you want to access the results in a paged way or you have a parameterized query that you want to reuse. This flow requires an active connection established by \code{\link[=dbConnect]{dbConnect()}}. See also \code{vignette("dbi-advanced")} for a walkthrough. \enumerate{ \item Use \code{\link[=dbSendQuery]{dbSendQuery()}} to create a result set object of class \linkS4class{DBIResult}. \item Optionally, bind query parameters with \code{\link[=dbBind]{dbBind()}} or \code{\link[=dbBindArrow]{dbBindArrow()}}. This is required only if the query contains placeholders such as \verb{?} or \verb{$1}, depending on the database backend. \item Optionally, use \code{\link[=dbColumnInfo]{dbColumnInfo()}} to retrieve the structure of the result set without retrieving actual data. \item Use \code{\link[=dbFetch]{dbFetch()}} to get the entire result set, a page of results, or the remaining rows. Fetching zero rows is also possible to retrieve the structure of the result set as a data frame. This step can be called multiple times. Only forward paging is supported, you need to cache previous pages if you need to navigate backwards. \item Use \code{\link[=dbHasCompleted]{dbHasCompleted()}} to tell when you're done. This method returns \code{TRUE} if no more rows are available for fetching. \item Repeat the last four steps as necessary. \item Use \code{\link[=dbClearResult]{dbClearResult()}} to clean up the result set object. This step is mandatory even if no rows have been fetched or if an error has occurred during the processing. It is good practice to use \code{\link[=on.exit]{on.exit()}} or \code{\link[withr:defer]{withr::defer()}} to ensure that this step is always executed. } } \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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} con <- dbConnect(RSQLite::SQLite(), ":memory:") rs <- dbSendQuery(con, "SELECT 1 AS a, 2 AS b") dbColumnInfo(rs) dbFetch(rs) dbClearResult(rs) dbDisconnect(con) \dontshow{\}) # examplesIf} } \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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} } \concept{DBIResult generics} DBI/man/dbIsValid.Rd0000644000176200001440000001002315005323731013546 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 \link[DBI:DBIConnection-class]{DBI::DBIConnection} object is initially valid, and becomes invalid after disconnecting with \code{\link[DBI:dbDisconnect]{DBI::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 \link[DBI:DBIResult-class]{DBI::DBIResult} object is valid after a call to \code{\link[DBI:dbSendQuery]{DBI::dbSendQuery()}}, and stays valid even after all rows have been fetched; only clearing it with \code{\link[DBI:dbClearResult]{DBI::dbClearResult()}} invalidates it. A \link[DBI:DBIResult-class]{DBI::DBIResult} object is also valid after a call to \code{\link[DBI:dbSendStatement]{DBI::dbSendStatement()}}, and stays valid after querying the number of rows affected; only clearing it with \code{\link[DBI:dbClearResult]{DBI::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{ \dontshow{if (requireNamespace("RSQLite", quietly = TRUE)) withAutoprint(\{ # examplesIf} 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) \dontshow{\}) # examplesIf} } \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{dbAppendTableArrow}()}, \code{\link{dbCreateTable}()}, \code{\link{dbCreateTableArrow}()}, \code{\link{dbDataType}()}, \code{\link{dbDisconnect}()}, \code{\link{dbExecute}()}, \code{\link{dbExistsTable}()}, \code{\link{dbGetException}()}, \code{\link{dbGetInfo}()}, \code{\link{dbGetQuery}()}, \code{\link{dbGetQueryArrow}()}, \code{\link{dbIsReadOnly}()}, \code{\link{dbListFields}()}, \code{\link{dbListObjects}()}, \code{\link{dbListResults}()}, \code{\link{dbListTables}()}, \code{\link{dbQuoteIdentifier}()}, \code{\link{dbReadTable}()}, \code{\link{dbReadTableArrow}()}, \code{\link{dbRemoveTable}()}, \code{\link{dbSendQuery}()}, \code{\link{dbSendQueryArrow}()}, \code{\link{dbSendStatement}()}, \code{\link{dbUnquoteIdentifier}()}, \code{\link{dbWriteTable}()}, \code{\link{dbWriteTableArrow}()} 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{dbQuoteLiteral}()}, \code{\link{dbQuoteString}()} Other DBIResultArrow generics: \code{\link{DBIResultArrow-class}}, \code{\link{dbBind}()}, \code{\link{dbClearResult}()}, \code{\link{dbFetchArrow}()}, \code{\link{dbFetchArrowChunk}()}, \code{\link{dbHasCompleted}()} } \concept{DBIConnection generics} \concept{DBIDriver generics} \concept{DBIResult generics} \concept{DBIResultArrow generics} DBI/DESCRIPTION0000644000176200001440000000355315147513477012402 0ustar liggesusersPackage: DBI Title: R Database Interface Version: 1.3.0 Date: 2026-02-11 Authors@R: c( person("R Special Interest Group on Databases (R-SIG-DB)", role = "aut"), person("Hadley", "Wickham", role = "aut"), person("Kirill", "Müller", , "kirill@cynkra.com", 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: arrow, blob, callr, covr, DBItest (>= 1.8.2), dbplyr, downlit, dplyr, glue, hms, knitr, magrittr, nanoarrow (>= 0.3.0.1), otel, otelsdk, RMariaDB, rmarkdown, rprojroot, RSQLite (>= 1.1-2), testthat (>= 3.0.0), vctrs, xml2 VignetteBuilder: knitr Config/autostyle/scope: line_breaks Config/autostyle/strict: false Config/Needs/check: r-dbi/DBItest Config/Needs/website: r-dbi/DBItest, r-dbi/dbitemplate, adbi, AzureKusto, bigrquery, DatabaseConnector, dittodb, duckdb, implyr, lazysf, odbc, pool, RAthena, IMSMWU/RClickhouse, RH2, RJDBC, RMariaDB, RMySQL, RPostgres, RPostgreSQL, RPresto, RSQLite, sergeant, sparklyr, withr Config/testthat/edition: 3 Encoding: UTF-8 RoxygenNote: 7.3.3.9000 NeedsCompilation: no Packaged: 2026-02-24 17:22:33 UTC; kirill Author: R Special Interest Group on Databases (R-SIG-DB) [aut], Hadley Wickham [aut], Kirill Müller [aut, cre] (ORCID: ), R Consortium [fnd] Maintainer: Kirill Müller Repository: CRAN Date/Publication: 2026-02-25 06:31:27 UTC