I rely on R DBI and odbc packages. Here is setup I used with help from @Floris
- First, create client SSL certificate and key, sign client certificate using postgres server root certificate, and also keep postgres server root certificate on client side at
~/.postgresql/
. A client ssl key is owned and read-only by owner only. Here is a guide from jealastic.com that I followed to create server and client SSL certificates.
ls -alh ~/.postgresql/
drwx------ 2 foo staff 122 Jul 23 10:45 ./
drwx------ 54 foo staff 2.1K Jul 23 10:45 ../
-rw-r--r-- 1 foo staff 875 Jul 21 17:42 postgresql.crt
-rw-r--r-- 1 foo staff 631 Jul 21 17:41 postgresql.csr
-r-------- 1 foo staff 891 Jul 21 17:41 postgresql.key
-rw-r--r-- 1 foo staff 1.1K Jul 21 17:40 root.crt
nano ~/.odbcinst.ini
and add following:
[PostgreSQL Driver]
Driver = /home/foo/anaconda3/envs/sql/lib/psqlodbcw.so
where odbc driver was installed in a conda env using conda create --name sql -c conda-forge psqlodbc
.
nano ~/.odbc.ini
and add one or more entry for database you like to connect with valid credentials:
[foodb]
Driver = PostgreSQL Driver
Database = foodb
Servername = db.example.com
UserName = foo
Password = mypassword
Port = 5432
sslmode = require
Note that PostgreSQL Driver matches corresponding entry in ~/.odbcinst.ini
For type of sslmode vs security and overhead, here is a good read: https://www.postgresql.org/docs/9.4/libpq-ssl.html
chmod 600 ~/.odbc.ini ~/.odbcinst.ini
- In RStudio GUI, either create a new connection and it should show an entry foodb from ~/.odbc.ini or type this into R console.
library(odbc)
foodb <- dbConnect(odbc::odbc(), "foodb", timeout = 10)
Done!