pgでSQLを実行するいくつかの方法
パターン1:PG::Connection#execを使う方法
code:exec.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
res = conn.exec('SELECT 1, 2, NULL')
PQexec https://www.postgresql.org/docs/current/libpq-exec.html#LIBPQ-PQEXEC
パターン2:PG::Connection#exec_paramsを使う方法
code:exec_params.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
res = conn.exec_params('SELECT $1, $2, $3', 1, 2, nil)
# 次のように評価される:
# res = conn.exec('SELECT 1, 2, NULL')
PQexecParams
https://www.postgresql.org/docs/current/libpq-exec.html#LIBPQ-PQEXECPARAMS
https://www.postgresql.jp/document/13/html/libpq-exec.html#LIBPQ-PQEXEC
パターン3:PG::Connection#prepareとPG::Connection#exec_preparedを使う方法
code:exec_prepared.rb
require 'pg'
conn = PG::Connection.open(:dbname => 'test')
# 例えば stmt という名前で、ステートメントを準備する
conn.prepare('stmt','SELECT $1, $2, $3')
# ステートメントにパラメータを渡して実行する
res = conn.exec_prepared('stmt', 1, 2, nil)
# 次のように評価される:
# res = conn.exec('SELECT 1, 2, NULL')
PQprepare
https://www.postgresql.org/docs/current/libpq-exec.html#LIBPQ-PQPREPARE
https://www.postgresql.jp/document/13/html/libpq-exec.html#LIBPQ-PQPREPARE
PQexecPrepared
https://www.postgresql.org/docs/current/libpq-exec.html#LIBPQ-PQEXECPREPARED
https://www.postgresql.jp/document/13/html/libpq-exec.html#LIBPQ-PQEXECPREPARED
This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.
同じSQL文を繰り返し利用する場合は、exec_paramsで都度SQL文を渡すのではなく、exec_preparedで準備したステートメントを使うと効率が良い
SQLインジェクションについて学ぶに関連して…
exec_paramやexec_preparedを使う(静的プレースホルダーを利用する)場合は、エスケープ処理は不要。
静的プレースホルダーを使わずexecで実行する(動的プレースホルダーを利用する?)場合は、エスケープ処理が必要。
libpqにおけるSQLエスケープについて
参考URL
PG: The Ruby PostgreSQL Driver
postgresql - Ruby PG Gem exec_params vs exec_prepared - Stack Overflow
#pg_gem