LoginSignup
6
4

More than 5 years have passed since last update.

dplyrでPostgreSQLにSSL接続

Last updated at Posted at 2017-05-18

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))
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4