Skip to contents

RPostgres is an DBI-compliant interface to the postgres database. It’s a ground-up rewrite using C++ and cpp11. Compared to RPostgreSQL, it:

  • Has full support for parameterised queries via dbSendQuery(), and dbBind().

  • Automatically cleans up open connections and result sets, ensuring that you don’t need to worry about leaking connections or memory.

  • Is a little faster, saving ~5 ms per query. (For reference, it takes around 5ms to retrieve a 1000 x 25 result set from a local database, so this is decent speed up for smaller queries.)

  • A simplified build process that relies on system libpq.

Goals and non-goals

RPostgres aims to:

  • implement the DBI specification for PostgreSQL, and to keep proving it by running the DBItest suite as part of its own tests
  • support parameterised queries through dbSendQuery() and dbBind(), so that values never have to be pasted into the SQL string
  • map PostgreSQL types to the R types that fit them best: 64-bit integers as bit64::integer64 by default, bytea via blob, and date-time columns with an explicit time zone
  • reach the PostgreSQL features that DBI has no generic for, such as LISTEN/NOTIFY through postgresWaitForNotify() and large objects through postgresImportLargeObject()
  • serve AWS Redshift clusters through Redshift(), with the behavior of individual methods adjusted where that cluster differs

It is explicitly not trying to:

  • define what the database interface looks like: the generics, their semantics and the specification belong to DBI; this package supplies the PostgreSQL implementation
  • translate R code into SQL: queries are handed to dbSendQuery() and friends as SQL strings
  • bundle a client library: no libpq source ships with the package; the build links the one the platform provides and downloads a prebuilt binary where that one is missing or unsuitable

Installation

# Install the latest RPostgres release from CRAN:
install.packages("RPostgres")

# Or the development version from GitHub:
# install.packages("pak")
pak::pak("r-dbi/RPostgres")

Discussions associated with DBI and related database packages take place on R-SIG-DB. The website Databases using R describes the tools and best practices in this ecosystem.

Basic usage

library(DBI)
# Connect to the default postgres database
con <- dbConnect(RPostgres::Postgres())

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

dbListFields(con, "mtcars")
dbReadTable(con, "mtcars")

# You can fetch all results:
res <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(res)
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))
}
# Clear the result
dbClearResult(res)

# Disconnect from the database
dbDisconnect(con)

Connecting to a specific Postgres instance

library(DBI)
# Connect to a specific postgres database i.e. Heroku
con <- dbConnect(RPostgres::Postgres(),dbname = 'DATABASE_NAME', 
                 host = 'HOST', # i.e. 'ec2-54-83-201-96.compute-1.amazonaws.com'
                 port = 5432, # or any other port specified by your DBA
                 user = 'USERNAME',
                 password = 'PASSWORD')

Design notes

On the C++ side, a connection owns the libpq connection and remembers at most one current result set. The result object holds the state of its own query. An R result object holds its own external pointer to the C++ result, separate from the connection’s. Sending a new query while a result set is still open warns, cancels the old query if it has not completed, and invalidates the old result.