Foreign Data Wrapper / PostgreSQL

外部データベースへのアクセスを拡張機能を使って試してみました。ここでは下記InfluxDBへのラッパーを使用しました。

https://github.com/pgspider/influxdb_fdw

環境)postgresql-12.2 / Ubuntu22.04
特に必要はありませんでしたが、下記ストリーミングレプリケーションで使った環境を使いました。(192.168.1.147)

PostgreSQL Replication


起動方法

pg_ctl –pgdata=/home/postgres/data –log=/home/postgres/db.log start
pg_ctl –pgdata=/home/postgres/data_rep –log=/home/postgres/db_rep.log start

ラッパーインストール
環境) Ubuntu22.04

git clone https://github.com/pgspider/influxdb_fdw.git
cd influxdb_fdw
make USE_PGXS=1 with_llvm=no
make install USE_PGXS=1 with_llvm=no

pg_configにはパスが通っていることを確認しておきます。
make installをsudoで実行すると環境変数で関連でうまくインストールできなかったため以下のようにインストール先の権限を変え、ローカルユーザでインストールできるようにしました。

sudo chmod 777 /opt/postgresql12/lib
sudo chmod 777 /opt/postgresql12/share/extension

外部DB(192.168.1.172)へのアクセス設定とデータ取得表示(外部DB設定は後述)

postgres=# CREATE EXTENSION influxdb_fdw;
postgres=# CREATE SERVER influxdb01 FOREIGN DATA WRAPPER influxdb_fdw OPTIONS (dbname ‘testdb01’, host ‘http://192.168.1.172’, port ‘8086’);
postgres=# CREATE USER MAPPING FOR CURRENT_USER SERVER influxdb01 OPTIONS(user ‘user’, password ‘pass’);
postgres=# CREATE FOREIGN TABLE tbl01(tag01 text, fld01 integer) SERVER influxdb01 OPTIONS (tags ‘tag01’);
postgres=# select * from tbl01;
tag01 | fld01
——-+——-
‘t01’ | 1
‘t02’ | 2
‘t03’ | 3

InfluxDB側(192.168.1.172)のインストール・設定
環境) Ubuntu 22.04

sudo apt install influxdb influxdb-client
sudo service influxdb status

$ influx
> create database testdb01
> use testdb01
> insert tbl01,tag01=’t01′ fld01=1
> insert tbl01,tag01=’t02′ fld01=2
> insert tbl01,tag01=’t03′ fld01=3
> select * from tbl01
name: tbl01
time fld01 tag01
—- —– —–
1678253859061435066 1 ‘t01’
1678254020282218700 2 ‘t02’
1678254024486185993 3 ‘t03’
> show measurements
name: measurements
name
—-
tbl01
> show tag keys
name: tbl01
tagKey
——
tag01
> show field keys
name: tbl01
fieldKey fieldType
——– ———
fld01 float

下記、テーブルのカラムを変更して再度SELECTしました。

外部のテーブルでも、自分のテーブルのように見ることができました。(レプリケーション先も同様)