1.安装tds_fdw依赖包
sudo apt-get install freetds-dev
2.下载并安装软件包
Sybase and Microsoft SQL Server
cd ~
unzip tds_fdw-master.zip
cd tds_fdw-master
make USE_PGXS=1 PG_CONFIG=/usr/local/pgsql/bin/pg_config
sudo make install USE_PGXS=1 PG_CONFIG=/usr/local/pgsql/bin/pg_config
#清理编译时生成的文件
make USE_PGXS=1 PG_CONFIG=/usr/local/pgsql/bin/pg_config clean
卸载
- 首先drop外部表相关的内容,在psql上以postgres用户运行
revoke select on t_classname from expe;
--revoke all privileges on t_classname from expe;
drop foreign table if exists t_classname;
drop user mapping if exists for expe server 外部服务器名称;
drop user mapping if exists for postgres server 外部服务器名称;
drop server if exists 外部服务器名称;
drop extension if exists tds_fdw;
- 如有可能停止Postgresql服务
sudo service postgresql stop
- 切换到tds_fdw源码目录,然后用make uninstall删除安装的插件相关文件
cd ~/tds_fdw-master
sudo make uninstall USE_PGXS=1 PG_CONFIG=/usr/local/pgsql/bin/pg_config
cd ..
rm -rf ~/tds_fdw-master
3.创建扩展
以下脚本只能在postgres用户下执行;
psql -h localhost -U postgres;
然后执行
drop extension if exists tds_fdw;
create extension tds_fdw;
4.访问SQL Server数据库
- 以下脚本只能在postgres用户下执行;
- 如果要使用其它用户访问,必须创建用户映射并为该用户授权;
- 大多数情况下外部表仅查询,因此不要直接用postgres用户访问,新建一个用户,授予查询权限
--创建server
revoke select on t_classname from expe;
--revoke all privileges on t_classname from expe;
drop foreign table if exists t_classname;
drop user mapping if exists for expe server 外部服务器名称;
drop user mapping if exists for postgres server 外部服务器名称;
drop server if exists 外部服务器名称;
-- 创建外部服务器
create server 外部服务器名称
foreign data wrapper tds_fdw
options (servername '服务器主机名或ip地址', port '1433', database '数据库名称', tds_version '7.1');
---- 定义一个用户到一个外部服务器的新映射
create user mapping for postgres
server 外部服务器名称
options (username 'sa', password '******'); --sql server对应的用户名和密码
--为保障安全性,我们使用用户expe访问外部表,该用户只有查询权限
create user mapping for expe
server 外部服务器名称
options (username 'sa', password '******'); --sql server对应的用户名和密码
--创建外部表,注意不支持主键\外键等,sql server varchar(x)替换为PostgreSQL的Text
create foreign table t_classname (
classnum integer NOT NULL,
classname text NOT NULL,
Resname text NOT NULL,
Hint text NULL,
position text NULL
) server 外部服务器名称
options (schema_name 'dbo',table_name 't_classname', row_estimate_method 'showplan_all');
--把表t_classname的查询权限授予用户expe:
grant select on t_classname to expe;
--把表t_classname的所有权限授予用户expe:
--grant all privileges on t_classname to expe;
已经把外部表t_classname的查询权限授予用户expe,现在用户expe可以查询外部表数据了