PostgreSQL额外提供模块file_fdw的简单使用

postgresql有很多额外的模块,file_fdw就是一个,它提供了外部数据封装器file_fdw,可以用来在服务器的文件系统中读取文件数据(必须为copy from可读的格式)。

因为默认是没安装额外的模块的,所以需要自行安装并手工创建【我的环境为centos+postgresql】

1、首先需要到源码下的contrib目录下,找到file_fdw进行make &makeinstall

[root@localhost file_fdw]# pwd
/opt/hgdb-core/contrib/file_fdw


2、psql,然后手工创建

highgo=# create extension file_fdw;

CREATE EXTENSION

想要查询创建的extension需要使用\dx命令

highgo=# \dx
                        List of installed extensions
   Name   | Version |   Schema   |                Description                
----------+---------+------------+-------------------------------------------
 file_fdw | 1.0     | public     | foreign-data wrapper for flat file access
 plpgsql  | 1.0     | pg_catalog | PL/pgSQL procedural language
(2 rows)


3、创建外部服务接口

highgo=# create server xu_server foreign data wrapper file_fdw ;
CREATE SERVER

查询用\dex

highgo=# \des
            List of foreign servers
      Name      | Owner  | Foreign-data wrapper 
----------------+--------+----------------------
 pg_file_server | highgo | file_fdw
 xu_server      | highgo | file_fdw
(2 rows)

4、创建外部表,要求与外部数据结构一致

highgo=# create foreign table xu(id int,name varchar(10),time date)server xu_server options(filename '/home/highgo/file_table/xu_table.csv',format 'csv',header 'true',delimiter ',',null '1');
CREATE FOREIGN TABLE


外部文件的位置、数据

[highgo@localhost file_table]$ pwd
/home/highgo/file_table
[highgo@localhost file_table]$ cat xu_table.csv 
id,name,time
1,Jim,2015-4-20
2,Tom,2015-4-21
3,,2015-4-22
4,Sam,2015-05-01


5、查询外部表

highgo=# select * from xu;
 id | name |    time    
----+------+------------
    | Jim  | 2015-04-20
  2 | Tom  | 2015-04-21
  3 |      | 2015-04-22
  4 | Sam  | 2015-05-01
(4 rows)


官方文档上提到这个功能可以为cvs的日志创建外部表,使得活动日志能够作为一个表进行查询

首先打开日志记录功能

[highgo@localhost ~]$ cd $PGDATA
[highgo@localhost data]$ vi postgresql.conf 

log_directory = '/home/highgo/pg_log'

logging_collector = on 

log_destination = 'stderr,csvlog'

改完后重启服务器

按照官方文档上所说的创建相应的外部服务器和外部数据表,然后就可以sql语句查询了



其中还有一些问题,需要再次确认?!

(1)外部文件中

id,name,time
1,Jim,2015-4-20
2,Tom,2015-4-21
3,,2015-4-22
4,Sam,2015-05-01

的时候,select 查询出的数据 第2行的id=1时没有

highgo=# select * from xu;
 id | name |    time    
----+------+------------
    | Jim  | 2015-04-20
  2 | Tom  | 2015-04-21
  3 |      | 2015-04-22
  4 | Sam  | 2015-05-01
(4 rows)


如果将外部文件中(也就是在第2行开头加一个空格就能查到第一个id的值1)

id,name,time
 1,Jim,2015-4-20
2,Tom,2015-4-21
3,,2015-4-22
4,Sam,2015-05-01

highgo=# select * from xu;
 id | name |    time    
----+------+------------
  1 | Jim  | 2015-04-20
  2 | Tom  | 2015-04-21
  3 |      | 2015-04-22
  4 | Sam  | 2015-05-01
(4 rows)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值