DBにSSL接続する
RからDBに接続するには、例えば{RPostgreSQL}
パッケージを使って
library(RPostgreSQL)
con <- dbConnect(PostgreSQL(),
host = "your_host",
port = 5432,
dbname = "your_db_name",
user = "your_user_name",
password = "your_password")
のようにやる。ただし、{RPostgreSQL}
は現状ではSSL接続に対応していない。
SSLに対応しているパッケージとして{RPostgres}
がある。{RPostgres}
はCRANに登録されていないので、githubからインストールする。
install.packages("devtools")
devtools::install_github("rstats-db/RPostgres")
使い方はPostgreSQL()とほぼ一緒。
con <- dbConnect(RPostgres::Postgres(),
host = "your_host",
port = 5432,
dbname = "your_db_name",
user = "your_user_name",
password = "your_password")
dplyrからDBに接続する
{dplyr}
からDBに接続することができる。
con <- src_postgres(
host = "your_host",
port = 5432,
dbname = "your_db_name",
user = "your_user_name",
password = "your_password")
こうしておけば{dplyr}
っぽく操作できるようになるし、必要であればクエリも送れるので大変便利だ。ただしこれはSSLに対応していない。
中身を覗くと分かるが、src_postgres()
は内部でRPostgreSQL
によりコネクションを作成し、src_sql()
を呼び出している。
> src_postgres
function (dbname = NULL, host = NULL, port = NULL, user = NULL,
password = NULL, ...)
{
if (!requireNamespace("RPostgreSQL", quietly = TRUE)) {
stop("RPostgreSQL package required to connect to postgres db",
call. = FALSE)
}
user <- user %||% if (in_travis())
"postgres"
else ""
con <- dbConnect(RPostgreSQL::PostgreSQL(), host = host %||%
"", dbname = dbname %||% "", user = user, password = password %||%
"", port = port %||% "", ...)
info <- dbGetInfo(con)
src_sql("postgres", con, info = info, disco = db_disconnector(con,
"postgres"))
}
<environment: namespace:dplyr>
おそらく{RPostgreSQL}
はいずれ{RPostgres}
に置き換えられると思うが、まだそうはなっていない。
ともあれ、src_postgres()
のRPostgreSQL
を置き換えてやれば接続できるようになる。
con <- dbConnect(RPostgres::Postgres(),
host = "your_host",
port = 5432,
dbname = "your_db_name",
user = "your_user_name",
password = "your_password")
※dplyr 0.7.0
からsrc_*
系の関数が不要になった(cf.dplyr 0.7.0を使ってみる - Technically, technophobic.)。
dplyr 0.6.0
以前の場合は下記を実行してコネクションを変換する必要がある。
con <- src_sql("postgres", con, info = dbGetInfo(con))