Write a Foreign Data Wrapper in
15 minutes

Error: Reference source not foundTable des matières
Write a Foreign Data Wrapper in 15 minutes.......................................................................................11 About me......................................................................................................................................42 Foreign Data Wrappers ?.............................................................................................................53 Goals............................................................................................................................................54 Agenda.........................................................................................................................................55 Part 1 - SQL/MED.......................................................................................................................66 MED ?..........................................................................................................................................67 DBLink and DBI-Link.................................................................................................................68 In other RDBMS..........................................................................................................................79 Overview......................................................................................................................................710 Part 2 - How To .........................................................................................................................811 Install..........................................................................................................................................812 Create server..............................................................................................................................813 Create Foreign Table..................................................................................................................814 Select..........................................................................................................................................915 Errors.........................................................................................................................................916 Beware.....................................................................................................................................1017 Uninstall...................................................................................................................................1018 Part 3 : Current List (feb. 2012)...............................................................................................1019 RDBMS fdw............................................................................................................................1120 NoSQL fdw..............................................................................................................................1121 Text fdw...................................................................................................................................1122 Web fdw...................................................................................................................................1222.1 ldap_fdw...........................................................................................................................1222.2 s3_fdw..............................................................................................................................1222.3 www_fdw.........................................................................................................................1323 Others.......................................................................................................................................1424 What about pgsql_fdw ?..........................................................................................................14
25 Full list.....................................................................................................................................1426 Ideas.........................................................................................................................................1527 Part 4 : Write a fdw..................................................................................................................1528 Write a FDW in C : the basics.................................................................................................15
29 Problems with that...................................................................................................................16
30 Multicorn.................................................................................................................................1631 Multicorn is your friend !.........................................................................................................16
32 Install multicorn.......................................................................................................................1733 ical_fdw.py...............................................................................................................................1734 make install..............................................................................................................................1835 Plug - 1.....................................................................................................................................1836 Plug - 2.....................................................................................................................................1837 Play - 1.....................................................................................................................................1838 Play - 2.....................................................................................................................................1939 There's more : Optimize...........................................................................................................1940 There's more : Log...................................................................................................................20
2 / 23

Error: Reference source not found41 Conclusions..............................................................................................................................2042 In a nutshell..............................................................................................................................2043 Limitations...............................................................................................................................2144 ETL No More...........................................................................................................................2145 Release on pgxn.......................................................................................................................2146 Links........................................................................................................................................2247 Contact.....................................................................................................................................2248 KTHXBYE..............................................................................................................................23

3 / 23

Error: Reference source not found1 About me• Damien Clochard• COO of DALIBO, French PostgreSQL Company• Admin of www.postgresql.fr

4 / 23

Error: Reference source not found

2 Foreign Data Wrappers ?

« One Database to Rule Them All »3 Goals• Know more about SQL/MED• Use the existing data wrappers• Write your own in 15 minutes

4 Agenda
1. SQL/MED ?
2. How to use a FDW
3. Current list
4. How to write a FDW

5 / 23

Error: Reference source not found5 Part 1 - SQL/MED• MED ?
• DBLink & DBI-LINK• In other RDBMS• Overview• Why SQL/MED is cool

6 MED ?
• Management of External Data
• Appeared in SQL:2003• implemented in PostgreSQL 9.1• Also present in IBM DB2

http://www.ibm.com/developerworks/data/library/techarticle/0203haas/0203haas.html

7 DBLink and DBI-Link• DBLink• Connect to other PostgreSQL databases• Contrib module since 8.3• Will be replaced by pgsql_fdw• DBI-Link• Partial implementation written in PL/PerlU• Started in 2004
• Now obsolete

6 / 23

Error: Reference source not foundMore information :• http://www.postgresql.org/docs/9.1/static/dblink.html• https://github.com/davidfetter/DBI-Link

8 In other RDBMS• Informix: External Tables (flat files)• Oracle: External Tables + DATABASE LINK (odbc)• MySQL: FEDERATED Storage Engine (mysql only)• MSSQL: Text File Driver (cvs only)• Firebird: External Table (cvs only)• DB2: Complete SQL/MED implementation

9 Overview

7 / 23

Error: Reference source not found10 Part 2 - How To ...
• Install• Create server• Create foreign table• Select• Uninstall

11 Install
CREATE EXTENSION file_fdw;

12 Create server
CREATE SERVER fileserver
FOREIGN DATA WRAPPER file_fdw;

13 Create Foreign Table
CREATE FOREIGN TABLE meminfo (stat text,value text) SERVER fileserver
OPTIONS ( filename '/proc/meminfo',
format 'csv',
delimiter ':');

8 / 23

Error: Reference source not found

14 Select
SELECT value
FROM meminfo
WHERE stat = 'MemFree';value­­­­­­­­­­­­­­­­­­­­­
55024 kB
(1 line)15 Errors• CREATE FOREIGN TABLE• won't check if the data storage exists/• won't check if the data can be read• won't check if the data format is ok• But SELECT will return an error

9 / 23

Error: Reference source not found

16 Beware• There's no cache• SELECT will scan the whole file every time
• To avoid this :CREATE TABLE localtable
AS SELECT * FROM foreigntable• Which is more or less equal to :COPY localtable FROM '/your/file';

17 Uninstall• DROP FOREIGN TABLE meminfo;• DROP SERVER fileserver CASCADE;• DROP EXTENSION file_fdw CASCADE;

18 Part 3 : Current List (feb. 2012)• SQL Databases Wrappers• NoSQL Databases Wrappers• File Wrappers• Web Wrappers• Others

10 / 23

Error: Reference source not foundIn a nutshell, you can now use various Foreign Data Wrappers (FDW) to connect a PostgreSQL
Server to remote data stores. This page is an incomplete list of the Wrappers available right now.
Another fdw list can be found at the PGXN website. Please keep in mind that most of thesewrappers are not officially supported by the PostgreSQL Global Development Group (PGDG) andthat some of these projects are still in Beta version. Use carefully!

19 RDBMS fdw• oracle_fdw• mysql_fdw• sql_lite• odbc_fdw

20 NoSQL fdw• couchdb_fdw• redis_fdw

21 Text fdw• file_fdw (delivered with PG 9.1)
• file_text_array_fdw

11 / 23Error: Reference source not found

22 Web fdw• www_fdw• twitter_fdw• google_fdw• rss_fdw• imap_fdw• s3_fdw

22.1 ldap_fdw
Allows PostgreSQL to query an LDAP server and retrieve data from some pre-configured
Organizational Unit.

CREATE EXTENSION ldap_fdw;
CREATE SERVER ldap_my_server_service
FOREIGN DATA WRAPPER ldap_fdw
OPTIONS ( address 'my_ldap_server', port '389');
CREATE USER MAPPING FOR current_user
SERVER ldap_my_server_service
OPTIONS (user_dn 'cn=the_ldap_user,dc=example,dc=com', password 'the_ldap_user_password');
CREATE FOREIGN TABLE ldap_people (uid text,displayname text,mail text)
SERVER ldap_my_server_service
OPTIONS (base_dn 'OU=people,DC=example,DC=com');
SELECT * FROM ldap_people WHERE mail = 'user@mail.com';

22.2 s3_fdw
s3_fdw reads files located in Amazon S3
db1=# CREATE EXTENSION s3_fdw;
CREATE EXTENSION
db1=# CREATE SERVER amazon_s3 FOREIGN DATA WRAPPER s3_fdw;
CREATE SERVER
db1=# CREATE USER MAPPING FOR CURRENT_USER SERVER amazon_s3OPTIONS (accesskey 'your­access­key­id',secretkey 'your­secret­access­key'

12 / 23

Error: Reference source not found);
CREATE USER MAPPING
db1=# CREATE FOREIGN TABLE log20110901(atime timestamp,
method text, elapse int,
session text) SERVER amazon_s3
OPTIONS (hostname 's3­ap­northeast­1.amazonaws.com',bucketname 'umitanuki­dbtest',
filename 'log20110901.txt',
delimiter E'\t');
CREATE FOREIGN TABLE

22.3 www_fdw
www_fdw allows to query different web services:Here is example for google search usage:
DROP EXTENSION IF EXISTS www_fdw CASCADE;CREATE EXTENSION www_fdw;
CREATE SERVER www_fdw_server_google_search FOREIGN DATA WRAPPER www_fdw
OPTIONS (uri 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0');
CREATE USER MAPPING FOR current_user SERVER www_fdw_server_google_search;
CREATE FOREIGN TABLE www_fdw_google_search (/* parameters used in request */q text,/* fields in response */GsearchResultClass text,
unescapedUrl text,
url text,
visibleUrl text,
cacheUrl text,
title text,
titleNoFormatting text,content text) SERVER www_fdw_server_google_search;
postgres=# SELECT url,substring(title,1,25)||'...',substring(content,1,25)||'...'FROM www_fdw_google_search WHERE q='postgres';url|?COLUMN?
|?COLUMN?
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­+­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­+­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
http://www.postgresql.org/| <b>PostgreSQL</b>: The wo... | Sophisticated open­
source...
http://www.postgresql.org/download/| <b>PostgreSQL</b>: Downlo... | The core of the<b>Postgr...
http://www.postgresql.org/docs/| <b>PostgreSQL</b>: Docume... | There IS a wealth of<b>P...
http://en.wikipedia.org/wiki/PostgreSQL | <b>PostgreSQL</b> ­ Wikip... | <b>PostgreSQL</b>, often...
(4 rows)

13 / 23

Error: Reference source not found

23 Others• git_fdw• ldap_fdw• process_fdw• pgStorm

24 What about pgsql_fdw ?
• Will be an “official” extension (like file_fdw)• Currently under development• Probably in 9.2• Until then keep using dblink

25 Full list
• http://wiki.postgresql.org/wiki/Foreign_data_wrappers• http://pgxn.org/tag/fdw/• 1 new wrapper every month

14 / 23Error: Reference source not found26 Ideas• XML• Excel / OpenDocument Spreadsheet• GIS file formats (KML,WKT,… )• Images• open data websites• RRD

27 Part 4 : Write a fdw• How to implement in C
• Multicorn
Let's write a wrapper for ICalendar files !

28 Write a FDW in C : the basics• 2 functions :• handler• validator (optionnal)• 6 callback routines (called by planner and executor)• PlanForeignScan / ExplainForeignScan• BeginForeignScan / EndForeignScan• IterateForeignScan / ReScanForeignScan15 / 23

Error: Reference source not found

29 Problems with that...
• This is complex• This is not well documented• The code is generic• What if i don't know C?

30 Multicorn

31 Multicorn is your friend !
• A simple python interface to write FDW• “A wrapper over a wrapper”• Handles all the dirty C code for you• You can focus on the extraction• … and use python's librairies

16 / 23

Error: Reference source not found

32 Install multicorn• You need postgresql-server-dev and python-dev• pgxn install multicorn --testing• Sources at github.com/Kozea/Multicorn.git

apt­get install python­software­properties
add­apt­repository ppa:pitti/postgresql
apt­get update
apt­get install postgresql­9.1 postgresql­server­dev­9.1 libpq­dev
setuptools
easy_install importlib
easy_install pgxnclient

python python­dev python­

thenpgxn install multicorn ­­testingor
git clone git://github.com/Kozea/Multicorn.git
cd Multicorn
make && make install

33 ical_fdw.py
from multicorn import ForeignDataWrapper
import urllib
from icalendar import Calendar, Eventclass ICalFdw(ForeignDataWrapper):def __init__(self, options, columns):
super(ICalFdw, self).__init__(options, columns)
self.url = options.get('url', None)self.columns = columns
def execute(self, quals, columns):
ical_file = urllib.urlopen(self.url).read()cal = Calendar.from_string(ical_file)for v in cal.walk('vevent'):
e = Event(v)line = {}for column_name in self.columns:

17 / 23

Error: Reference source not foundline[column_name] = e.decoded(column_name)yield line34 make install
cd Multicorn
cp icalfdw.py python/multicorn
make & make install

35 Plug - 1
CREATE EXTENSION multicorn;
CREATE SERVER multicorn_ical
FOREIGN DATA WRAPPER multicorn
options (wrapper 'multicorn.icalfdw.ICalFdw');

36 Plug - 2
CREATE FOREIGN TABLE fosdem_events (dtstart TIMESTAMP,dtend TIMESTAMP,summary TEXT) server multicorn_ical options (url
'http://fosdem.org/schedule/ical');37 Play - 1
SELECT count(*)

18 / 23

Error: Reference source not found
FROM fosdem_events;
count­­­­­­­437(1 line)

38 Play - 2
SELECT to_char(e.dtend,'HH24:MI') AS end_of_this_talk
FROM fosdem_events e
WHERE e.summary ILIKE '%foreign data wrapper%';
end_of_this_talk­­­­­­­­­­­­­­­­­­
12:50(1 line)39 There's more : Optimize
Reduce the amount of data fetched over the network :• handle the “quals” argument• a Qual object defines :• a field_name• an operator• a value

19 / 23

Error: Reference source not found

40 There's more : Log• multicorn.utils has a log_to_postgres function• 3 parameters• message• level• hint (optional)
log_to_postgres('You MUST set the url', ERROR)

41 Conclusions• In a Nutshell• Limitations• ETL No More
• Release on pgxn
• The future• Links / Contact

42 In a nutshell
Useful for :• Easier migrations• Data Warehouse• Reporting• Avoid useless data replication

20 / 23

Error: Reference source not found

43 Limitations• Read Only
• Most wrappers are beta or alpha• Most are not supported by PGDG
• Forget about performance• Forget about data integrity

44 ETL No More
• Instead of : EXTRACT - TRANSFORM - LOAD
• Just : CREATE FOREIGN TABLE - SELECT• Use SQL or PL/SQL to manipulate data
• Transformation code stays in the DB

45 Release on pgxn
If you write your own FDW:
• publish it on PGXN
• update the wiki page

21 / 23

Error: Reference source not found

46 Links• This talk : http://dalibo.org/conferences• Multicorn : http://multicorn.org• Ical FDW : http://moourl.com/icalfdw

47 Contact• me : damien@dalibo.info• Multicorn creator : Ronan Dunklau rdunklau@gmail.com

22 / 23

Error: Reference source not found

48 KTHXBYE

23 / 23