Title: | Connect to ODBC Compatible Databases (using the DBI Interface) |
Version: | 1.6.1 |
Description: | A DBI-compatible interface to ODBC databases. |
License: | MIT + file LICENSE |
URL: | https://odbc.r-dbi.org, https://github.com/r-dbi/odbc, https://solutions.posit.co/connections/db/ |
BugReports: | https://github.com/r-dbi/odbc/issues |
Depends: | R (≥ 4.0.0) |
Imports: | bit64, blob (≥ 1.2.0), cli, DBI (≥ 1.0.0), hms, lifecycle, methods, Rcpp (≥ 0.12.11), rlang (≥ 1.1.0) |
Suggests: | connectcreds, covr, DBItest, httr2, knitr, magrittr, paws.common, rmarkdown, RSQLite, testthat (≥ 3.0.0), tibble, withr |
LinkingTo: | Rcpp |
ByteCompile: | true |
Config/Needs/check: | pkgbuild |
Config/Needs/website: | tidyverse/tidytemplate |
Config/testthat/edition: | 3 |
Encoding: | UTF-8 |
RoxygenNote: | 7.3.2 |
SystemRequirements: | GNU make, An ODBC3 driver manager and drivers. |
Collate: | 'RcppExports.R' 'aaa-odbc-data-type.R' 'connection-pane.R' 'dbi-connection.R' 'odbc-connection.R' 'db.R' 'dbi-driver.R' 'dbi-result.R' 'dbi-table.R' 'dbi.R' 'driver-access.R' 'driver-bigquery.R' 'driver-databricks.R' 'driver-db2.R' 'driver-hana.R' 'driver-hive.R' 'driver-impala.R' 'driver-mysql.R' 'driver-netezza.R' 'driver-oracle.R' 'driver-postgres.R' 'driver-redshift.R' 'driver-snowflake.R' 'driver-spark.R' 'driver-sql-server.R' 'driver-sqlite.R' 'driver-teradata.R' 'driver-vertica.R' 'import-standalone-obj-type.R' 'import-standalone-types-check.R' 'odbc-config.R' 'odbc-data-sources.R' 'odbc-drivers.R' 'odbc-package.R' 'odbc.R' 'utils.R' 'zzz.R' |
VignetteBuilder: | knitr |
NeedsCompilation: | yes |
Packaged: | 2025-03-26 20:22:27 UTC; hadleywickham |
Author: | Jim Hester [aut], Hadley Wickham [aut, cre], Oliver Gjoneski [aut], lexicalunit [cph] (nanodbc library), Google Inc. [cph] (cctz library), Posit Software, PBC [cph, fnd] |
Maintainer: | Hadley Wickham <hadley@posit.co> |
Repository: | CRAN |
Date/Publication: | 2025-03-27 12:10:02 UTC |
odbc: Connect to ODBC Compatible Databases (using the DBI Interface)
Description
A DBI-compatible interface to ODBC databases.
Author(s)
Maintainer: Hadley Wickham simon.couch@posit.co
Authors:
Jim Hester
Oliver Gjoneski
Other contributors:
lexicalunit (nanodbc library) [copyright holder]
Google Inc. (cctz library) [copyright holder]
Posit Software, PBC [copyright holder, funder]
See Also
Useful links:
Report bugs at https://github.com/r-dbi/odbc/issues
DBI classes
Description
DBI classes
Convenience functions for reading/writing DBMS tables
Description
Convenience functions for reading/writing DBMS tables
Usage
## S4 method for signature 'OdbcConnection,character,data.frame'
dbWriteTable(
conn,
name,
value,
overwrite = FALSE,
append = FALSE,
temporary = FALSE,
row.names = NULL,
field.types = NULL,
batch_rows = getOption("odbc.batch_rows", NA),
...
)
## S4 method for signature 'OdbcConnection,Id,data.frame'
dbWriteTable(
conn,
name,
value,
overwrite = FALSE,
append = FALSE,
temporary = FALSE,
row.names = NULL,
field.types = NULL,
batch_rows = getOption("odbc.batch_rows", NA),
...
)
## S4 method for signature 'OdbcConnection,SQL,data.frame'
dbWriteTable(
conn,
name,
value,
overwrite = FALSE,
append = FALSE,
temporary = FALSE,
row.names = NULL,
field.types = NULL,
batch_rows = getOption("odbc.batch_rows", NA),
...
)
## S4 method for signature 'OdbcConnection'
dbAppendTable(
conn,
name,
value,
batch_rows = getOption("odbc.batch_rows", NA),
...,
row.names = NULL
)
## S4 method for signature 'OdbcConnection'
sqlCreateTable(
con,
table,
fields,
row.names = NA,
temporary = FALSE,
...,
field.types = NULL
)
Arguments
conn |
An OdbcConnection object, produced by |
name |
a character string specifying a table name. Names will be automatically quoted so you can use any sequence of characters, not just any valid bare table name. |
value |
A data.frame to write to the database. |
overwrite |
Allow overwriting the destination table. Cannot be
|
append |
Allow appending to the destination table. Cannot be
|
temporary |
If |
row.names |
Either If A string is equivalent to For backward compatibility, |
field.types |
Additional field types used to override derived types. |
batch_rows |
The number of rows to retrieve. Defaults to |
... |
Other arguments used by individual methods. |
con |
A database connection. |
table |
The table name, passed on to
|
fields |
Either a character vector or a data frame. A named character vector: Names are column names, values are types.
Names are escaped with A data frame: field types are generated using
|
Examples
## Not run:
library(DBI)
con <- dbConnect(odbc::odbc())
dbListTables(con)
dbWriteTable(con, "mtcars", mtcars, temporary = TRUE)
dbReadTable(con, "mtcars")
dbListTables(con)
dbExistsTable(con, "mtcars")
# A zero row data frame just creates a table definition.
dbWriteTable(con, "mtcars2", mtcars[0, ], temporary = TRUE)
dbReadTable(con, "mtcars2")
dbDisconnect(con)
## End(Not run)
SQL Server
Description
Details of SQL Server methods for odbc and DBI generics.
dbUnquoteIdentifier()
conn@quote
returns the quotation mark, but quotation marks and square
brackets can be used interchangeably for delimited identifiers.
(https://learn.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers).
This function strips the brackets first and then calls the DBI method to
strip the quotation marks.
isTempTable()
Local temp tables are stored as
[tempdb].[dbo].[#name]_____[numeric identifier]
, so isTempTable()
returns TRUE
if catalog_name
is "tempdb"
or "%"
, or the
name starts with "#"
.
dbExistsTable()
The default implementation reports temporary tables as non-existent
since they live in a different catalog. This method provides a special
case for temporary tables, as identified by isTempTable()
.
dbListTables()
The default implementation reports temporary tables as non-existent
when a catalog_name
isn't supplied since they live in a different catalog.
This method provides a special case for temporary tables.
odbcConnectionSchemas
Method for an internal function. Calls catalog-specific sp_tables
to make
sure we list the schemas in the appropriate database/catalog.
sqlCreateTable()
Warns if temporary = TRUE
but the name
does not conform to temp table
naming conventions (i.e. it doesn't start with #
).
odbcConnectionColumns_()
If temp table, query the database for the actual table name.
odbcConnectionColumns_()
Copied over from odbc-connection to avoid S4 dispatch NOTEs.
Odbc Connection Methods
Description
Implementations of pure virtual functions defined in the DBI
package
for OdbcConnection objects.
Usage
## S4 method for signature 'OdbcConnection'
show(object)
## S4 method for signature 'OdbcConnection'
dbIsValid(dbObj, ...)
## S4 method for signature 'OdbcConnection'
dbDisconnect(conn, ...)
## S4 method for signature 'OdbcConnection,character'
dbSendQuery(conn, statement, params = NULL, ..., immediate = FALSE)
## S4 method for signature 'OdbcConnection,character'
dbExecute(conn, statement, params = NULL, ..., immediate = is.null(params))
## S4 method for signature 'OdbcConnection,character'
dbSendStatement(conn, statement, params = NULL, ..., immediate = FALSE)
## S4 method for signature 'OdbcConnection,ANY'
dbDataType(dbObj, obj, ...)
## S4 method for signature 'OdbcConnection,data.frame'
dbDataType(dbObj, obj, ...)
## S4 method for signature 'OdbcConnection,character'
dbQuoteIdentifier(conn, x, ...)
## S4 method for signature 'OdbcConnection,SQL'
dbQuoteIdentifier(conn, x, ...)
## S4 method for signature 'OdbcConnection'
dbGetInfo(dbObj, ...)
## S4 method for signature 'OdbcConnection,character'
dbGetQuery(
conn,
statement,
n = -1,
params = NULL,
immediate = is.null(params),
...
)
## S4 method for signature 'OdbcConnection'
dbBegin(conn, ...)
## S4 method for signature 'OdbcConnection'
dbCommit(conn, ...)
## S4 method for signature 'OdbcConnection'
dbRollback(conn, ...)
## S4 method for signature 'OdbcConnection,Id'
dbListFields(conn, name, ...)
## S4 method for signature 'OdbcConnection,SQL'
dbListFields(conn, name, ...)
## S4 method for signature 'OdbcConnection,character'
dbListFields(
conn,
name,
catalog_name = NULL,
schema_name = NULL,
column_name = NULL,
...
)
## S4 method for signature 'OdbcConnection,Id'
dbExistsTable(conn, name, ...)
## S4 method for signature 'OdbcConnection,SQL'
dbExistsTable(conn, name, ...)
## S4 method for signature 'OdbcConnection,character'
dbExistsTable(conn, name, ...)
## S4 method for signature 'OdbcConnection,character'
dbRemoveTable(conn, name, ...)
Arguments
object |
Any R object |
dbObj |
An object inheriting from |
... |
Other arguments to methods. |
conn |
A DBI::DBIConnection object,
as returned by |
statement |
a character string containing SQL. |
params |
Query parameters to pass to |
immediate |
If |
obj |
An R object whose SQL type we want to determine. |
x |
A character vector, SQL or Id object to quote as identifier. |
n |
maximum number of records to retrieve per fetch. Use |
name |
The table name, passed on to
|
catalog_name |
Catalog where table is located. |
schema_name |
Schema where table is located. |
column_name |
The name of the column to return, the default returns all columns. |
Odbc Driver Methods
Description
Implementations of pure virtual functions defined in the DBI
package
for OdbcDriver objects.
Usage
## S4 method for signature 'OdbcDriver'
show(object)
## S4 method for signature 'OdbcDriver,ANY'
dbDataType(dbObj, obj, ...)
## S4 method for signature 'OdbcDriver,list'
dbDataType(dbObj, obj, ...)
## S4 method for signature 'OdbcDriver,data.frame'
dbDataType(dbObj, obj, ...)
## S4 method for signature 'OdbcDriver'
dbIsValid(dbObj, ...)
## S4 method for signature 'OdbcDriver'
dbGetInfo(dbObj, ...)
Arguments
object |
Any R object |
dbObj |
A object inheriting from DBI::DBIDriver or DBI::DBIConnection |
obj |
An R object whose SQL type we want to determine. |
... |
Other arguments passed on to methods. |
Odbc Result Methods
Description
Implementations of pure virtual functions defined in the DBI
package
for OdbcResult objects.
Usage
## S4 method for signature 'OdbcResult'
dbClearResult(res, ...)
## S4 method for signature 'OdbcResult'
dbFetch(res, n = -1, ...)
## S4 method for signature 'OdbcResult'
dbHasCompleted(res, ...)
## S4 method for signature 'OdbcResult'
dbIsValid(dbObj, ...)
## S4 method for signature 'OdbcResult'
dbGetStatement(res, ...)
## S4 method for signature 'OdbcResult'
dbColumnInfo(res, ...)
## S4 method for signature 'OdbcResult'
dbGetRowCount(res, ...)
## S4 method for signature 'OdbcResult'
dbGetRowsAffected(res, ...)
## S4 method for signature 'OdbcResult'
dbBind(res, params, ..., batch_rows = getOption("odbc.batch_rows", NA))
Arguments
res |
An object inheriting from DBI::DBIResult. |
... |
Other arguments passed on to methods. |
n |
maximum number of records to retrieve per fetch. Use |
dbObj |
An object inheriting from |
params |
For |
batch_rows |
The number of rows to retrieve. Defaults to |
Oracle
Description
Details of Oracle methods for odbc and DBI generics.
odbcConnectionTables()
Method for an internal function that otherwise relies on the SQLTables
ODBC API. While this method is much faster than the OEM implementation, it
does not look through synonyms.
odbcConnectionColumns()
Query, rather than use SQLColumns
ODBC API, since we bind a BIGINT
to
one of the column results and Oracle's OEM driver can't handle it.
Usage
## S4 method for signature 'Oracle'
sqlCreateTable(
con,
table,
fields,
row.names = NA,
temporary = FALSE,
...,
field.types = NULL
)
## S4 method for signature 'Oracle,character'
odbcConnectionTables(
conn,
name,
catalog_name = NULL,
schema_name = NULL,
table_type = NULL,
exact = FALSE
)
Supported Connection Attributes
Description
These (pre) connection attributes are supported and can be passed as
part of the dbConnect
call in the named list attributes
parameter:
Details
-
azure_token
: This should be a string scalar; in particular Azure Active Directory authentication token. Only for use with Microsoft SQL Server and with limited support away from the OEM Microsoft driver.
Examples
## Not run:
conn <- dbConnect(
odbc::odbc(),
dsn = "my_azure_mssql_db",
Encrypt = "yes",
attributes = list("azure_token" = .token)
)
## End(Not run)
Helper for Connecting to Databricks via ODBC
Description
Connect to Databricks clusters and SQL warehouses via the Databricks ODBC driver.
In particular, the custom dbConnect()
method for the Databricks ODBC driver
implements a subset of the Databricks client unified authentication
model, with support for personal access tokens, OAuth machine-to-machine
credentials, and OAuth user-to-machine credentials supplied via Posit
Workbench or the Databricks CLI on desktop. It can also detect viewer-based
credentials on Posit Connect if the connectcreds package is
installed. All of these credentials are detected automatically if present
using standard environment variables.
In addition, on macOS platforms, the dbConnect()
method will check
for irregularities with how the driver is configured,
and attempt to fix in-situ, unless the odbc.no_config_override
environment variable is set.
Usage
databricks()
## S4 method for signature 'DatabricksOdbcDriver'
dbConnect(
drv,
httpPath,
workspace = Sys.getenv("DATABRICKS_HOST"),
useNativeQuery = TRUE,
driver = NULL,
HTTPPath,
uid = NULL,
pwd = NULL,
...
)
Arguments
drv |
An object that inherits from DBI::DBIDriver, or an existing DBI::DBIConnection object (in order to clone an existing connection). |
httpPath , HTTPPath |
To query a cluster, use the HTTP Path value found
under |
workspace |
The URL of a Databricks workspace, e.g.
|
useNativeQuery |
Suppress the driver's conversion from ANSI SQL 92 to
HiveSQL? The default ( |
driver |
The name of the Databricks ODBC driver, or |
uid , pwd |
Manually specify a username and password for authentication. Specifying these options will disable automated credential discovery. |
... |
Further arguments passed on to |
Value
An OdbcConnection
object with an active connection to a Databricks
cluster or SQL warehouse.
Examples
## Not run:
DBI::dbConnect(
odbc::databricks(),
httpPath = "sql/protocolv1/o/4425955464597947/1026-023828-vn51jugj"
)
# Use credentials from the viewer (when possible) in a Shiny app
# deployed to Posit Connect.
library(connectcreds)
server <- function(input, output, session) {
conn <- DBI::dbConnect(
odbc::databricks(),
httpPath = "sql/protocolv1/o/4425955464597947/1026-023828-vn51jugj"
)
}
## End(Not run)
List remote tables and fields for an ODBC connection
Description
dbListTables()
provides names of remote tables accessible through this
connection; dbListFields()
provides names of columns within a table.
Usage
## S4 method for signature 'OdbcConnection'
dbListTables(
conn,
catalog_name = NULL,
schema_name = NULL,
table_name = NULL,
table_type = NULL,
...
)
Arguments
conn |
A DBI::DBIConnection object,
as returned by |
catalog_name , schema_name , table_name |
Catalog, schema, and table names. By default, |
table_type |
The type of the table to return, the default returns all table types. |
... |
Other parameters passed on to methods. |
Value
A character vector of table or field names respectively.
Helper method used to determine if a table identifier is that of a temporary table.
Description
Currently implemented only for select back-ends where we have a use for it (SQL Server, for example). Generic, in case we develop a broader use case.
Usage
isTempTable(conn, name, ...)
## S4 method for signature 'OdbcConnection,Id'
isTempTable(conn, name, ...)
## S4 method for signature 'OdbcConnection,SQL'
isTempTable(conn, name, ...)
Arguments
conn |
OdbcConnection |
name |
Table name |
... |
additional parameters to methods |
Connect to a database via an ODBC driver
Description
The dbConnect()
method documented here is invoked when DBI::dbConnect()
is called with the first argument odbc()
. Connecting to a database via
an ODBC driver is likely the first step in analyzing data using the odbc
package; for an overview of package concepts, see the Overview section
below.
Usage
odbc()
## S4 method for signature 'OdbcDriver'
dbConnect(
drv,
dsn = NULL,
...,
timezone = "UTC",
timezone_out = "UTC",
encoding = "",
name_encoding = "",
bigint = c("integer64", "integer", "numeric", "character"),
timeout = 10,
driver = NULL,
server = NULL,
database = NULL,
uid = NULL,
pwd = NULL,
dbms.name = NULL,
attributes = NULL,
interruptible = getOption("odbc.interruptible", interactive()),
.connection_string = NULL
)
Arguments
drv |
An |
dsn |
The data source name. For currently available options, see the
|
... |
Additional ODBC keywords. These will be joined with the other arguments to form the final connection string. Note that ODBC parameter names are case-insensitive so that (e.g.) Any values containing a leading or trailing space, a |
timezone |
The server time zone. Useful if the database has an internal
timezone that is not 'UTC'. If the database is in your local timezone,
set this argument to |
timezone_out |
The time zone returned to R. If you want to display
datetime values in the local timezone, set to |
encoding |
The text encoding used on the Database. If the database is
not using UTF-8 you will need to set the encoding to get accurate
re-encoding. See |
name_encoding |
The text encoding for column names used on the
Database. May be different than the |
bigint |
The R type that |
timeout |
Time in seconds to timeout the connection attempt. Setting a
timeout of |
driver |
The ODBC driver name or a path to a driver. For currently
available options, see the |
server |
The server hostname. Some drivers use |
database |
The database on the server. Not required when configured for
the supplied |
uid |
The user identifier. Some drivers use |
pwd |
The password. Some drivers use |
dbms.name |
The database management system name. This should normally
be queried automatically by the ODBC driver. This name is used as the class
name for the OdbcConnection object returned from |
attributes |
A list of connection attributes that are passed prior to the connection being established. See ConnectionAttributes. |
interruptible |
Logical. If |
.connection_string |
A complete connection string, useful if you are copy pasting it from another source. If this argument is used, any additional arguments will be appended to this string. |
Connection strings
Internally, dbConnect()
creates a connection string using the supplied
arguments. Connection string keywords are driver-dependent; the arguments
documented here are common, but some drivers may not accept them.
Alternatively to configuring DSNs and driver names with the driver manager,
you can pass a complete connection string directly as the
.connection_string
argument.
The Connection Strings Reference is a
useful resource that has example connection strings for a large variety of
databases.
Overview
The odbc package is one piece of the R interface to databases with support for ODBC:
The package supports any Database Management System (DBMS) with ODBC support. Support for a given DBMS is provided by an ODBC driver, which defines how to interact with that DBMS using the standardized syntax of ODBC and SQL. Drivers can be downloaded from the DBMS vendor or, if you're a Posit customer, using the professional drivers. To manage information about each driver and the data sources they provide access to, our computers use a driver manager. Windows is bundled with a driver manager, while MacOS and Linux require installation of one; this package supports the unixODBC driver manager.
In the R interface, the DBI package provides a front-end while odbc implements a back-end to communicate with the driver manager. The odbc package is built on top of the nanodbc C++ library.
Interfacing with DBMSs using R and odbc involves three high-level steps:
-
Configure drivers and data sources: the functions
odbcListDrivers()
,odbcListDataSources()
, andodbcListConfig()
help to interface with the driver manager. -
Connect to a database: The
dbConnect()
function, called with the first argument odbc(), connects to a database using the specified ODBC driver to create a connection object. -
Interface with connections: The resulting connection object can be passed to various functions to retrieve information on database structure ([DBI::dbListTables()][]), iteratively develop queries (
DBI::dbSendQuery()
,DBI::dbColumnInfo()
), and query data objects (DBI::dbFetch()
).
Learn more
To learn more about databases:
-
"Best Practices in Working with Databases" documents how to use the odbc package with various popular databases.
-
The pyodbc "Drivers and Driver Managers" Wiki provides further context on drivers and driver managers.
-
Microsoft's "Introduction to ODBC" is a thorough resource on the ODBC interface.
List the actions supported for the connection
Description
Return a list of actions that can be performed on the connection.
Usage
odbcConnectionActions(connection)
Arguments
connection |
A connection object, as returned by |
Details
The list returned is a named list of actions, where each action has the following properties:
- callback
A function to be invoked to perform the action
- icon
An optional path to an icon representing the action
Value
A named list of actions that can be performed on the connection.
odbcConnectionColumns
Description
This function has been deprecated in favor of DBI::dbListFields()
.
For a given table this function returns detailed information on
all fields / columns. The expectation is that this is a relatively thin
wrapper around the ODBC SQLColumns
function call, with some of the field
names renamed / re-ordered according to the return specifications below.
Usage
odbcConnectionColumns(conn, name, ..., exact = FALSE)
Arguments
conn |
OdbcConnection |
name |
Table identifiers.
By default, are interpreted as a ODBC search pattern where |
... |
additional parameters to methods |
exact |
Set to |
Details
In DBI::dbWriteTable()
we make a call to this method
to get details on the fields of the table we are writing to. In particular
the columns data_type
, column_size
, and decimal_digits
are used. An
implementation is not necessary for DBI::dbWriteTable()
to work.
odbcConnectionColumns
is routed through the SQLColumns
ODBC
method. This function, together with remaining catalog functions
(SQLTables
, etc), by default ( SQL_ATTR_METADATA_ID == false
) expect
either ordinary arguments (OA) in the case of the catalog, or pattern value
arguments (PV) in the case of schema/table name. For these, quoted
identifiers do not make sense, so we unquote identifiers prior to the call.
Value
data.frame with columns
name
field.type - equivalent to type_name in SQLColumns output
table_name
schema_name
catalog_name
data_type
column_size
buffer_length
decimal_digits
numeric_precision_radix
remarks
column_default
sql_data_type
sql_datetime_subtype
char_octet_length
ordinal_position
nullable
See Also
The ODBC documentation on SQLColumns for further details.
Connecting to Snowflake via ODBC
Description
odbcConnectionColumns()
If the catalog, or the schema arguments are NULL, attempt to infer by querying for CURRENT_DATABASE() and CURRENT_SCHEMA(). We do this to aid with performance, as the SQLColumns method is more performant when restricted to a particular DB/schema.
Usage
## S4 method for signature 'Snowflake,character'
dbExistsTableForWrite(conn, name, ..., catalog_name = NULL, schema_name = NULL)
Arguments
conn |
A DBI::DBIConnection object,
as returned by |
name |
The table name, passed on to
|
... |
Other parameters passed on to methods. |
catalog_name , schema_name |
Catalog and schema names. |
Get an icon representing a connection.
Description
Return the path on disk to an icon representing a connection.
Usage
odbcConnectionIcon(connection)
Arguments
connection |
A connection object, as returned by |
Details
The icon returned should be a 32x32 square image file.
Value
The path to an icon file on disk.
Return the corresponding ODBC data type for an R object
Description
This is used when creating a new table with dbWriteTable()
.
Databases with default methods defined are:
MySQL
PostgreSQL
SQL Server
Oracle
SQLite
Spark
Hive
Impala
Redshift
Vertica
BigQuery
Teradata
Access
Snowflake
Usage
odbcDataType(con, obj, ...)
Arguments
con |
A driver connection object, as returned by |
obj |
An R object. |
... |
Additional arguments passed to methods. |
Details
If you are using a different database and dbWriteTable()
fails with a SQL
parsing error the default method is not appropriate, you will need to write
a new method. The object type for your method will be the database name
retrieved by dbGetInfo(con)$dbms.name
. Use the documentation provided with
your database to determine appropriate values for each R data type.
Value
Corresponding SQL type for the obj
.
List columns in an object.
Description
Lists the names and types of each column (field) of a specified object.
Usage
odbcListColumns(connection, ...)
Arguments
connection |
A connection object, as returned by |
... |
Parameters specifying the object. |
Details
The object to inspect must be specified as one of the arguments
(e.g. table = "employees"
); depending on the driver and underlying
data store, additional specification arguments may be required.
Value
A data frame with name
and type
columns, listing the
object's fields.
List locations of ODBC configuration files
Description
On MacOS and Linux, odbc uses the unixODBC driver manager to manage information about driver and data sources. This helper returns the filepaths where the driver manager will look for that information.
odbcListConfig()
is a wrapper around the command line call odbcinst -j
.
The odbcEditDrivers()
, odbcEditSystemDSN()
, and
odbcEditUserDSN()
helpers provide a shorthand for
file.edit(odbcListConfig()[[i]])
.
Windows does not use .ini
configuration files; on Windows,
odbcListConfig()
will return a 0-length vector and odbcEdit*()
will raise an error.
Usage
odbcListConfig()
odbcEditDrivers()
odbcEditSystemDSN()
odbcEditUserDSN()
See Also
The odbcListDrivers()
and odbcListDataSources()
helpers return
information on the contents of odbcinst.ini
and odbc.ini
files,
respectively. odbcListDataSources()
collates entries from both the
System and User odbc.ini
files.
Learn more about unixODBC and the odbcinst
utility
here.
Examples
configs <- odbcListConfig()
configs
# shorthand for file.edit(configs[[1]])
odbcEditDrivers()
List Configured Data Source Names
Description
Collect information about the available data source names (DSNs). A DSN must
be both installed and configured with the driver manager to be included in
this list. Configuring a DSN just sets up a lookup table (e.g. in
odbc.ini
) to allow users to pass only the DSN to dbConnect()
.
DSNs that are not configured with the driver manager can still be
connected to with dbConnect()
by providing DSN metadata directly.
Usage
odbcListDataSources()
Value
A data frame with two columns:
- name
Name of the data source. The entries in this column can be passed to the
dsn
argument ofdbConnect()
.- description
Data source description.
Configuration
This function interfaces with the driver manager to collect information about the available data source names.
For MacOS and Linux, the odbc package supports the unixODBC driver
manager. unixODBC looks to the odbc.ini
configuration file for information
on DSNs. Find the location(s) of your odbc.ini
file(s) with odbcinst -j
.
In this example odbc.ini
file:
[MySQL] Driver = MySQL Driver Database = test Server = 127.0.0.1 User = root password = root Port = 3306
...the data source name is MySQL
, which will appear in the name
column of this function's output. To pass the DSN as the dsn
argument to
dbConnect()
, pass it as a string, like "MySQL"
.
Driver = MySQL Driver
references the driver name
in odbcListDrivers()
output.
Windows is bundled with an ODBC driver manager.
When a DSN is configured with a driver manager, information on the DSN will
be automatically passed on to dbConnect()
when its dsn
argument is set.
For example, with the MySQL
data source name configured, and the driver
name MySQL Driver
appearing in odbcListDrivers()
output, the code:
con <- dbConnect( odbc::odbc(), Driver = "MySQL Driver", Database = "test", Server = "127.0.0.1", User = "root", password = "root", Port = 3306 )
...can be written:
con <- dbConnect(odbc::odbc(), dsn = "MySQL")
In this case, dbConnect()
will look up the information defined for MySQL
in the driver manager (in our example, odbc.ini
) and automatically
pass the needed arguments.
See Also
List Configured ODBC Drivers
Description
Collect information about the configured driver names. A driver must be both
installed and configured with the driver manager to be included in this list.
Configuring a driver name just sets up a lookup table (e.g. in
odbcinst.ini
) to allow users to pass only the driver name to dbConnect()
.
Driver names that are not configured with the driver manager (and thus
do not appear in this function's output) can still be
used in dbConnect()
by providing a path to a driver directly.
Usage
odbcListDrivers(
keep = getOption("odbc.drivers_keep"),
filter = getOption("odbc.drivers_filter")
)
Arguments
keep , filter |
A character vector of driver names to keep in or remove
from the results, respectively. If Driver names are first processed with |
Value
A data frame with three columns.
- name
Name of the driver. The entries in this column can be passed to the
driver
argument ofdbConnect()
(as long as the driver accepts the argument).- attribute
Driver attribute name.
- value
Driver attribute value.
If a driver has multiple attributes, there will be one row per attribute,
each with the same driver name
. If a given driver name does not have any
attributes, the function will return one row with the driver name
, but
the last two columns will be NA
.
Configuration
This function interfaces with the driver manager to collect information about the available driver names.
For MacOS and Linux, the odbc package supports the unixODBC driver
manager. unixODBC looks to the odbcinst.ini
configuration file for
information on driver names. Find the location(s) of your odbcinst.ini
file(s) with odbcinst -j
.
In this example odbcinst.ini
file:
[MySQL Driver] Driver=/opt/homebrew/Cellar/mysql/8.2.0_1/lib/libmysqlclient.dylib
Then the driver name is MySQL Driver
, which will appear in the name
column of this function's output. To pass the driver name as the driver
argument to dbConnect()
, pass it as a string, like "MySQL Driver"
.
Windows is bundled with an ODBC driver manager.
In this example, function output would include 1 row: the name
column
would read "MySQL Driver"
, attribute
would be "Driver"
, and value
would give the file path to the driver. Additional key-value pairs
under the driver name would add additional rows with the same name
entry.
When a driver is configured with a driver manager, information on the driver
will be automatically passed on to dbConnect()
when its driver
argument
is set. For an example, see the same section in the odbcListDataSources()
help-file. Instead of configuring driver information with a driver manager,
it is also possible to provide a path to a driver directly to dbConnect()
.
See Also
Examples
odbcListDrivers()
Return the object hierarchy supported by a connection.
Description
Lists the object types and metadata known by the connection, and how those object types relate to each other.
Usage
odbcListObjectTypes(connection)
Arguments
connection |
A connection object, as returned by |
Details
The returned hierarchy takes the form of a nested list, in which each object type supported by the connection is a named list with the following attributes:
- contains
A list of other object types contained by the object, or "data" if the object contains data
- icon
An optional path to an icon representing the type
For instance, a connection in which the top-level object is a schema that contains tables and views, the function will return a list like the following:
list(schema = list(contains = list( list(name = "table", contains = "data") list(name = "view", contains = "data"))))
Value
The hierarchy of object types supported by the connection.
List objects in a connection.
Description
Lists all of the objects in the connection, or all the objects which have specific attributes.
Usage
odbcListObjects(connection, ...)
Arguments
connection |
A connection object, as returned by |
... |
Attributes to filter by. |
Details
When used without parameters, this function returns all of the objects known
by the connection. Any parameters passed will filter the list to only objects
which have the given attributes; for instance, passing schema = "foo"
will return only objects matching the schema foo
.
Value
A data frame with name
and type
columns, listing the
objects.
Preview the data in an object.
Description
Return the data inside an object as a data frame.
Usage
odbcPreviewObject(connection, rowLimit, ...)
Arguments
connection |
A connection object, as returned by |
rowLimit |
The maximum number of rows to display. |
... |
Parameters specifying the object. |
Details
The object to previewed must be specified as one of the arguments
(e.g. table = "employees"
); depending on the driver and underlying
data store, additional specification arguments may be required.
Value
A data frame containing the data in the object.
Create a preview query.
Description
Optimize against the rowLimit argument. S3 since some back-ends do not parse the LIMIT syntax. Internal, not expected that users would interact with this method.
Usage
odbcPreviewQuery(connection, rowLimit, name)
## S3 method for class 'OdbcConnection'
odbcPreviewQuery(connection, rowLimit, name)
## S3 method for class ''Microsoft SQL Server''
odbcPreviewQuery(connection, rowLimit, name)
## S3 method for class 'Teradata'
odbcPreviewQuery(connection, rowLimit, name)
## S3 method for class 'Oracle'
odbcPreviewQuery(connection, rowLimit, name)
Arguments
connection |
A connection object, as returned by |
rowLimit |
The maximum number of rows to display. |
name |
Name of the object to be previewed |
Set the Transaction Isolation Level for a Connection
Description
Set the Transaction Isolation Level for a Connection
Usage
odbcSetTransactionIsolationLevel(conn, levels)
Arguments
conn |
A DBI::DBIConnection object,
as returned by |
levels |
One or more of 'read_uncommitted', 'read_committed', 'repeatable_read', 'serializable'. |
See Also
Examples
## Not run:
# Can use spaces or underscores in between words.
odbcSetTransactionIsolationLevel(con, "read uncommitted")
# Can also use the full constant name.
odbcSetTransactionIsolationLevel(con, "SQL_TXN_READ_UNCOMMITTED")
## End(Not run)
Quote special character when connecting
Description
When connecting to a database using odbc, all the arguments are concatenated
into a single connection string that looks like name1=value1;name2=value2
.
That means if your value contains =
or ;
then it needs to be quoted.
Other rules mean that you need to quote any values that starts or ends with
white space, or contains {
or }
.
This function quotes a string in a way that should work for most drivers, but unfortunately there doesn't seem to be an approach that works everywhere. If this function doesn't work for you, you'll need to carefully read the docs for your driver.
Usage
quote_value(x)
Arguments
x |
A string to quote. |
Value
A quoted string, wrapped in I()
.
Examples
quote_value("abc")
quote_value("ab'c")
# Real usage is more likely to look like:
## Not run:
library(DBI)
con <- dbConnect(
odbc::odbc(),
dsn = "reallycooldatabase"
password = odbc::quote_value(Sys.getenv("MY_PASSWORD"))
)
## End(Not run)
Helper for Connecting to Redshift via ODBC
Description
Connect to Redshift clusters via ODBC.
In particular, the custom dbConnect()
method for Redshift ODBC drivers
automatically determines whether IAM-based credentials are available, much
like other AWS SDKs and tools. This requires the paws.common package.
Usage
redshift()
## S4 method for signature 'RedshiftOdbcDriver'
dbConnect(
drv,
clusterId,
server,
database,
region = NULL,
driver = NULL,
uid = NULL,
pwd = NULL,
dbUser = uid,
...
)
Arguments
drv |
An object that inherits from DBI::DBIDriver, or an existing DBI::DBIConnection object (in order to clone an existing connection). |
clusterId |
The Redshift cluster identifier. Only one of |
server |
The full hostname of the Redshift cluster. |
database |
The name of the Redshift database to connect to. |
region |
The AWS region the Redshift cluster runs in. Ignored when
|
driver |
The name of or path to a Redshift ODBC driver, or |
uid , pwd |
Disable IAM credentials and manually specify a username and password for authentication. |
dbUser |
The Redshift database account. |
... |
Further arguments passed on to |
Value
An OdbcConnection
object with an active connection to a Redshift
cluster or SQL warehouse.
Examples
## Not run:
# Connect to Redshift using IAM credentials.
DBI::dbConnect(
odbc::redshift(),
clusterId = "my-testing-cluster",
database = "dev",
dbUser = "me"
)
## End(Not run)
Helper for connecting to Snowflake via ODBC
Description
Connect to a Snowflake account via the Snowflake ODBC driver.
In particular, the custom dbConnect()
method for the Snowflake ODBC driver
detects ambient OAuth credentials on platforms like Snowpark Container
Services or Posit Workbench. It can also detect viewer-based
credentials on Posit Connect if the connectcreds package is
installed.
In addition, on macOS platforms, the dbConnect
method will check and warn
if it detects irregularities with how the driver is configured, unless the
odbc.no_config_override
environment variable is set.
Usage
snowflake()
## S4 method for signature 'SnowflakeOdbcDriver'
dbConnect(
drv,
account = Sys.getenv("SNOWFLAKE_ACCOUNT"),
driver = NULL,
warehouse = NULL,
database = NULL,
schema = NULL,
uid = NULL,
pwd = NULL,
...
)
Arguments
drv |
An object that inherits from DBI::DBIDriver, or an existing DBI::DBIConnection object (in order to clone an existing connection). |
account |
A Snowflake account identifier,
e.g. |
driver |
The name of the Snowflake ODBC driver, or |
warehouse |
The name of a Snowflake compute warehouse, or |
database |
The name of a Snowflake database, or |
schema |
The name of a Snowflake database schema, or |
uid , pwd |
Manually specify a username and password for authentication. Specifying these options will disable ambient credential discovery. |
... |
Further arguments passed on to |
Value
An OdbcConnection
object with an active connection to a Snowflake
account.
Examples
## Not run:
# Use ambient credentials.
DBI::dbConnect(odbc::snowflake())
# Use browser-based SSO (if configured). Only works on desktop.
DBI::dbConnect(
odbc::snowflake(),
account = "testorg-test_account",
authenticator = "externalbrowser"
)
# Use a traditional username & password.
DBI::dbConnect(
odbc::snowflake(),
account = "testorg-test_account",
uid = "me",
pwd = rstudioapi::askForPassword()
)
# Use credentials from the viewer (when possible) in a Shiny app
# deployed to Posit Connect.
library(connectcreds)
server <- function(input, output, session) {
conn <- DBI::dbConnect(odbc::snowflake())
}
## End(Not run)
Unimportant DBI methods
Description
Unimportant DBI methods
Usage
## S4 method for signature 'OdbcConnection'
sqlData(con, value, row.names = NA, ...)
## S4 method for signature 'HDB'
sqlCreateTable(
con,
table,
fields,
row.names = NA,
temporary = FALSE,
...,
field.types = NULL
)
## S4 method for signature 'Hive,character'
dbQuoteString(conn, x, ...)
## S4 method for signature 'Teradata'
sqlCreateTable(
con,
table,
fields,
row.names = NA,
temporary = FALSE,
...,
field.types = NULL
)