Connect to a local PostgreSQL database
pg_local_connect.Rdpg_local_connect creates a DBI connection to a
PostgreSQL database on localhost using the modern
RPostgres backend.
Arguments
- db
(character) Database name. If
NULL, missing, or empty, the function falls back togetOption("pg_local_db"), thenPG_LOCAL_DB, then"caplter".- user
(character) PostgreSQL username. If
NULL, missing, or empty, the function attempts to readDB_USERfrom the environment.- password
(character) PostgreSQL password. If
NULL, missing, or empty, the function attempts to readDB_PASSWORDfrom the environment.- host
(character) PostgreSQL host name. Defaults to
"localhost".- port
(integer) PostgreSQL port. Defaults to
5432.
Details
Database selection precedence is:
explicit
dbargument,R option
pg_local_db,environment variable
PG_LOCAL_DB,default
"caplter".
User credential selection precedence is:
explicit
userorpasswordargument,environment variables
DB_USERandDB_PASSWORD.
This function is intended as a convenience helper for local development and data exploration workflows that need a PostgreSQL connection while keeping credentials outside the codebase.
Note
Set credentials in ~/.Renviron to avoid hardcoding them in
scripts, for example:
DB_USER=your_username
DB_PASSWORD=your_password
PG_LOCAL_DB=caplterExamples
if (FALSE) { # \dontrun{
# use DB_USER / DB_PASSWORD from ~/.Renviron
pg <- pg_local_connect()
# change the default database for the current session
options(pg_local_db = "dev")
pg_dev <- pg_local_connect()
# override user and password explicitly
pg_override <- pg_local_connect(
db = "caplter",
user = "my_user",
password = "my_password"
)
} # }