Software

PostgreSQL 使用外部連結

1. 使用 Dockerfile 安裝 TDS FDW 和 MySQL FDW

# 安裝必要的依賴
FROM postgres:16.2-alpine3.19
RUN apk add --no-cache \
    gcc \
    musl-dev \
    make \
    wget \
    freetds-dev \
    postgresql-dev \
    mariadb-dev

# 安裝 TDS FDW
RUN wget https://github.com/tds-fdw/tds_fdw/archive/v2.0.3.tar.gz \
    && tar -xvf v2.0.3.tar.gz \
    && cd tds_fdw-2.0.3 \
    && make USE_PGXS=1 \
    && make USE_PGXS=1 install

# 安裝 MySQL FDW
RUN wget https://github.com/EnterpriseDB/mysql_fdw/archive/REL-2_9_2.tar.gz \
    && tar -xvf REL-2_9_2.tar.gz \
    && cd mysql_fdw-REL-2_9_2 \
    && make USE_PGXS=1 \
    && make USE_PGXS=1 install

# 清理
RUN apk del gcc musl-dev make wget \
    && rm -rf /var/cache/apk/* /tmp/* /var/tmp/*

2. 建立外部連結

2.1 創建擴展

-- 用於 Sybase 或 SQL Server
CREATE EXTENSION tds_fdw;
-- 用於 MySQL
CREATE EXTENSION mysql_fdw;
-- 用於 PostgreSQL
CREATE EXTENSION postgres_fdw;

2.2 創建外部伺服器

-- 用於 Sybase 或 SQL Server
CREATE SERVER sybase_server
FOREIGN DATA WRAPPER tds_fdw
OPTIONS (servername '192.168.0.250', port '5000', database 'your_database');
-- 用於 MySQL
CREATE SERVER mysql_server
FOREIGN DATA WRAPPER mysql_fdw
OPTIONS (host '192.168.0.250', port '3306');
-- 用於 PostgreSQL
CREATE SERVER postgres_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '192.168.0.250', port '5432', dbname 'your_postgres_database');

2.3 創建用戶映射

CREATE USER MAPPING FOR CURRENT_USER
SERVER sybase_server
OPTIONS (username 'your_sybase_username', password 'your_sybase_password');
CREATE USER MAPPING FOR CURRENT_USER
SERVER mysql_server
OPTIONS (username 'your_mysql_username', password 'your_mysql_password');
CREATE USER MAPPING FOR CURRENT_USER
SERVER postgres_server
OPTIONS (user 'your_postgres_username', password 'your_postgres_password');

2.4 導入外部 Schema

-- 導入整個 Schema 中的所有表
IMPORT FOREIGN SCHEMA "remote_schema"
FROM SERVER foreign_server
INTO public;
-- 導入指定的表
IMPORT FOREIGN SCHEMA "remote_schema"
LIMIT TO (table1, table2, table3)
FROM SERVER foreign_server
INTO public;