SlideShare a Scribd company logo
1 of 38
One Database To Rule 'em All
European PostgreSQL Conference 2016
Tallinn
Stefanie Janine Stölting
@sjstoelting
mail@stefanie-stoelting.de
PostgreSQL SQL-MED
SQL/MED
Defined by ISO/IEC 9075-9:2008
Supported by
DB2
MariaDB
With CONNECT storage engine,
implementation differs to the standard
PostgreSQL
Implementation
Foreign Data Wrapper
Read only
Read and write
Installation as extensions
Available FDW
Examples:
Oracle (pgxn.org)
MS SQL Server / Sybase ASE
read-only (pgxn.org)
MongoDB
read-only (pgxn.org)
MariaDB / MySQL (pgxn.org)
SQLite
read-only (GithHub)
Hadoop (HDFS)
read-only (GitHub)
Special FDW
file_fdw
postgres_fdw
foreign_table_exposer
Write your own FDW
Multicorn
Use Python and Multicorn to write your own
and access lots of stuff like
IMAP
HTML
Data source
The example data used in the live data part is
available from Chinook Database:
PostgreSQL
MySQL
CSV
SQLite
Chinook Tables
CTE
Common Table Expressions will be used in examples
● Example:
WITH RECURSIVE t(n) AS (
VALUES (1)
UNION ALL
SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n), min(n), max(n) FROM t;
●
Result:
Live Data examples
Live Data examples
-- Create the SQLite foreign data wrapper extension in the current database
CREATE EXTENSION sqlite_fdw;
-- Create the mapping to the foreign SQLite file
CREATE SERVER sqlite_server
FOREIGN DATA WRAPPER sqlite_fdw
OPTIONS (database '/var/sqlite/Chinook_Sqlite.sqlite')
;
-- Create the SQLite foreign table, column definitions have to match
CREATE FOREIGN TABLE sqlite_artist(
"ArtistId" integer,
"Name" character varying(120)
)
SERVER sqlite_server
OPTIONS(
table 'Artist'
);
Live Data examples
-- Select some data
SELECT * FROM sqlite_artist;
Live Data examples
-- Create the foreign data wrapper extension in the current database
CREATE EXTENSION mysql_fdw;
-- Create the mapping to the foreign MariaDB server
CREATE SERVER mariadb_server
FOREIGN DATA WRAPPER mysql_fdw
OPTIONS (host '127.0.0.1', port '3306');
-- Create a user mapping with user and password of the foreign table
-- PostgreSQL gives you options to connect this user with its own users
CREATE USER MAPPING FOR PUBLIC SERVER mariadb_server
OPTIONS (username 'stefanie', password 'secret');
Live Data examples
-- Create the MariaDB foreign table, column definitions have to match
CREATE FOREIGN TABLE mysql_album(
"AlbumId" integer,
"Title" character varying(160),
"ArtistId" integer
)
SERVER mariadb_server
OPTIONS(
dbname 'Chinook',
table_name 'Album'
);
-- Select some data
SELECT * FROM mysql_album;
Live Data examples
-- Join SQLite and MariaDB tables
SELECT artist."Name"
, album."Title"
FROM sqlite_artist AS artist
INNER JOIN mysql_album AS album
ON artist."ArtistId" = album."ArtistId"
;
Live Data examples
CREATE EXTENSION postgres_fdw;
-- Create a connection to the other database on the same server
CREATE SERVER pg_localhost_chinook
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '127.0.0.1', port '5432', dbname 'chinook')
;
-- Create a user mapping
CREATE USER MAPPING FOR stefanie
SERVER pg_localhost_chinook
OPTIONS (user 'stefanie', password 'password')
;
Live Data examples
-- Link foreign tables into the current database and schema
IMPORT FOREIGN SCHEMA public LIMIT TO("Track")
FROM SERVER pg_localhost_chinook
INTO public
;
-- Try to select some data
SELECT * FROM "Track";
Live Data examples
-- Join SQLite, MariaDB, and PostgreSQL tables
SELECT artist."Name"
, album."Title"
, track."Name"
FROM sqlite_artist AS artist
INNER JOIN mysql_album AS album
ON artist."ArtistId" = album."ArtistId"
INNER JOIN "Track" AS track
ON album."AlbumId" = track."AlbumId"
;
Live Data examples
CREATE EXTENSION file_fdw;
-- One does need a server, but afterwards every csv file is avilable
CREATE SERVER chinook_csv
FOREIGN DATA WRAPPER file_fdw
;
-- Creating a foreign table based on a csv file
-- Options are the same as in COPY
CREATE FOREIGN TABLE csv_genre (
"GenreId" integer,
"Name" text
) SERVER chinook_csv
OPTIONS (
filename '/var/tmp/Genre.csv',
format 'csv',
HEADER 'true'
);
Live Data examples
-- Select some data
SELECT * FROM csv_genre;
Live Data examples
-- Join SQLite, MariaDB, PostgreSQL, and CSV tables
SELECT artist."Name"
, album."Title"
, track."Name"
, genre."Name"
FROM sqlite_artist AS artist
INNER JOIN mysql_album AS album
ON artist."ArtistId" = album."ArtistId"
INNER JOIN "Track" AS track
ON album."AlbumId" = track."AlbumId"
INNER JOIN csv_genre AS genre
ON track."GenreId" = genre."GenreId"
;
Live Data examples
-- Joining SQLite and MariaDB tables using PostgreSQL expressions
WITH album AS
(
SELECT "ArtistId"
, array_agg("Title") AS album_titles
FROM mysql_album
GROUP BY "ArtistId"
)
SELECT artist."Name" AS artist
, album.album_titles
FROM sqlite_artist AS artist
INNER JOIN album
ON artist."ArtistId" = album."ArtistId"
;
Live Data examples
-- Creates an materialized view on foreign tables
CREATE MATERIALIZED VIEW mv_album_artist AS
WITH album AS
(
SELECT "ArtistId"
, array_agg("Title") AS album_titles
FROM mysql_album
GROUP BY "ArtistId"
)
SELECT artist."Name" AS artist
, album.album_titles
, SUM(ARRAY_LENGTH(album_titles, 1))
FROM sqlite_artist AS artist
LEFT OUTER JOIN album
ON artist."ArtistId" = album."ArtistId"
GROUP BY artist."Name"
, album.album_titles
;
Live Data examples
-- Select the mv data
SELECT *
FROM mv_album_artist
WHERE upper(artist) LIKE 'A%'
ORDER BY artist
;
Live Data examples
-- SELECT the amount of albums from the MariaDB table from MariaDB, not with a foreign data
wrapper
SELECT count( * ) AS AlbumCount
FROM `Album`
;
Live Data examples
-- Insert data calculated from foreign tables using PostgreSQL features into another foreign table
INSERT INTO mysql_album("AlbumId", "ArtistId", "Title")
WITH album AS
(
-- Generate a new album id
SELECT MAX(album."AlbumId") + 1 AS new_album_id
FROM mysql_album AS album
)
SELECT album.new_album_id
, artist."ArtistId"
, 'Back in Black'
FROM sqlite_artist AS artist, album
WHERE artist."Name" = 'AC/DC'
GROUP BY album.new_album_id
, artist."ArtistId"
;
Live Data examples
-- SELECT the amount of albums from the MariaDB table from MariaDB, not with a foreign data
wrapper
SELECT count( * ) AS AlbumCount
FROM `Album`
;
Live Data examples
-- Select data from the materialized view
SELECT *
FROM mv_album_artist
WHERE artist = 'AC/DC'
ORDER BY artist
;
-- Refresh the mv to see the recently added data
REFRESH MATERIALIZED VIEW mv_album_artist;
-- We can even delete data from foreign tables
DELETE FROM mysql_album
WHERE "Title" = 'Back in Black'
AND "ArtistId" = 1
;
Live Data examples
-- Using PostgreSQL JSON with data from MariaDB and SQLite
-- Step 1: Albums with tracks as JSON
WITH albums AS
(
SELECT a."ArtistId" AS artist_id
, a."Title" AS album_title
, array_agg(t."Name") AS album_tracks
FROM mysql_album AS a
INNER JOIN "Track" AS t
ON a."AlbumId" = t."AlbumId"
GROUP BY a."ArtistId"
, a."Title"
)
SELECT row_to_json(albums) AS album_tracks
FROM albums
;
Live Data examples
-- Albums including tracks with aritsts with some JSON magic
WITH albums AS
(
SELECT a."ArtistId" AS artist_id
, a."Title" AS album_title
, array_agg(t."Name") AS album_tracks
FROM mysql_album AS a
INNER JOIN "Track" AS t
ON a."AlbumId" = t."AlbumId"
GROUP BY a."ArtistId"
, a."Title"
)
, js_albums AS
(
SELECT row_to_json(albums) AS album_tracks
FROM albums
)
SELECT a."Name" AS artist
, jsonb_pretty(al.album_tracks::jsonb) AS albums_tracks
FROM sqlite_artist AS a
INNER JOIN js_albums AS al
ON a."ArtistId" = (al.album_tracks→>'artist_id')::int
;
Live Data examples
Live Data examples
-- Create the multicorn extension
CREATE EXTENSION multicorn;
Live Data examples
CREATE SERVER rss_srv foreign data wrapper multicorn options (
wrapper 'multicorn.rssfdw.RssFdw'
)
;
Live Data examples
-- Create a foreign table based on an RSS feed
CREATE FOREIGN TABLE rss_postgresql_events (
title CHARACTER VARYING,
link CHARACTER VARYING,
description CHARACTER VARYING,
"pubDate" TIMESTAMPTZ,
guid CHARACTER VARYING
) server rss_srv OPTIONS (
url 'https://www.postgresql.org/events.rss'
)
;
Live Data examples
-- Query the RSS feed
SELECT *
FROM rss_postgresql_events
;
Live Data examples
-- Entend the query of the RSS feed
SELECT title
, "pubDate"::DATE AS "Conference Start Date"
, description
FROM rss_postgresql_events
WHERE "pubDate"::DATE > NOW()::DATE
ORDER BY "pubDate" ASC
;
Link List
PGXN Extensions:
- mysql_fdw, MySQL/MariaDB FDW
- sqlite_fdw, SQLite FDW
Slide and source on Github:
https://github.com/sjstoelting/talks/
One Database To Rule 'em All
This document by Stefanie Janine Stölting is covered by the
Creative Commons Attribution 4.0 International

More Related Content

What's hot

Logrotate sh
Logrotate shLogrotate sh
Logrotate shBen Pope
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Kai Chan
 
From Overnight to Always On @ Jfokus 2019
From Overnight to Always On @ Jfokus 2019From Overnight to Always On @ Jfokus 2019
From Overnight to Always On @ Jfokus 2019Enno Runne
 
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)Kai Chan
 
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)Kai Chan
 
Golang slidesaudrey
Golang slidesaudreyGolang slidesaudrey
Golang slidesaudreyAudrey Lim
 
Postgresql Database Administration- Day4
Postgresql Database Administration- Day4Postgresql Database Administration- Day4
Postgresql Database Administration- Day4PoguttuezhiniVP
 
7. Data Import – Data Export
7. Data Import – Data Export7. Data Import – Data Export
7. Data Import – Data ExportFAO
 
Video upload process_code
Video upload process_codeVideo upload process_code
Video upload process_codeR21docs
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collectorInfiniFlux
 
Ugif 10 2012 beauty ofifmxdiskstructs ugif
Ugif 10 2012 beauty ofifmxdiskstructs ugifUgif 10 2012 beauty ofifmxdiskstructs ugif
Ugif 10 2012 beauty ofifmxdiskstructs ugifUGIF
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptVCP Muthukrishna
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMailBash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMailVCP Muthukrishna
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHPMudasir Syed
 

What's hot (20)

No sql the-sql-way
No sql the-sql-wayNo sql the-sql-way
No sql the-sql-way
 
Logrotate sh
Logrotate shLogrotate sh
Logrotate sh
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)
 
From Overnight to Always On @ Jfokus 2019
From Overnight to Always On @ Jfokus 2019From Overnight to Always On @ Jfokus 2019
From Overnight to Always On @ Jfokus 2019
 
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
 
Basics of unix
Basics of unixBasics of unix
Basics of unix
 
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)
Search Engine-Building with Lucene and Solr, Part 1 (SoCal Code Camp LA 2013)
 
Cscope and ctags
Cscope and ctagsCscope and ctags
Cscope and ctags
 
Golang slidesaudrey
Golang slidesaudreyGolang slidesaudrey
Golang slidesaudrey
 
Hive commands
Hive commandsHive commands
Hive commands
 
Postgresql Database Administration- Day4
Postgresql Database Administration- Day4Postgresql Database Administration- Day4
Postgresql Database Administration- Day4
 
7. Data Import – Data Export
7. Data Import – Data Export7. Data Import – Data Export
7. Data Import – Data Export
 
Video upload process_code
Video upload process_codeVideo upload process_code
Video upload process_code
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collector
 
Ugif 10 2012 beauty ofifmxdiskstructs ugif
Ugif 10 2012 beauty ofifmxdiskstructs ugifUgif 10 2012 beauty ofifmxdiskstructs ugif
Ugif 10 2012 beauty ofifmxdiskstructs ugif
 
Pgbr 2013 fts
Pgbr 2013 ftsPgbr 2013 fts
Pgbr 2013 fts
 
Postgre sql unleashed
Postgre sql unleashedPostgre sql unleashed
Postgre sql unleashed
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMailBash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
 

Viewers also liked

PostgreSQL Conference: East 08
PostgreSQL Conference: East 08PostgreSQL Conference: East 08
PostgreSQL Conference: East 08Joshua Drake
 
Amazon RDS for PostgreSQL - PGConf 2016
Amazon RDS for PostgreSQL - PGConf 2016 Amazon RDS for PostgreSQL - PGConf 2016
Amazon RDS for PostgreSQL - PGConf 2016 Grant McAlister
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldJignesh Shah
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldJignesh Shah
 
презентация команды мбоу сш 15 5 класс
презентация команды мбоу сш 15 5 класспрезентация команды мбоу сш 15 5 класс
презентация команды мбоу сш 15 5 класслена резник
 
Effect of BA, IBA and cutting type on transplants production from cuttings
Effect of BA, IBA and cutting type on transplants production from cuttingsEffect of BA, IBA and cutting type on transplants production from cuttings
Effect of BA, IBA and cutting type on transplants production from cuttingsAhmedabd Eleslamboly Eleslamboly
 
Seminario 2 de investigación penal
Seminario 2 de investigación penalSeminario 2 de investigación penal
Seminario 2 de investigación penalmvillafranca
 
Isabella_Practicum_Assessment
Isabella_Practicum_AssessmentIsabella_Practicum_Assessment
Isabella_Practicum_AssessmentSarah Bunting
 
Presentación cartilla gallina
Presentación cartilla gallinaPresentación cartilla gallina
Presentación cartilla gallinaistej
 
교육평가 제5징 표준화검사화 컴퓨터화검사
교육평가 제5징 표준화검사화 컴퓨터화검사교육평가 제5징 표준화검사화 컴퓨터화검사
교육평가 제5징 표준화검사화 컴퓨터화검사은임 백
 
Unit dentar fona nou DenTam Creation
Unit dentar fona nou DenTam CreationUnit dentar fona nou DenTam Creation
Unit dentar fona nou DenTam CreationDenteam Creation
 
Evaluation 1
Evaluation 1 Evaluation 1
Evaluation 1 tubze_t
 
Education and poverty in florida
Education and poverty in floridaEducation and poverty in florida
Education and poverty in floridaGiang Trinh
 
Eνδοσχολική βία (Bullying)
Eνδοσχολική βία (Bullying)Eνδοσχολική βία (Bullying)
Eνδοσχολική βία (Bullying)JimVak1
 
Virtual Assistants: How to Avoid Premature Engagement
Virtual Assistants: How to Avoid Premature EngagementVirtual Assistants: How to Avoid Premature Engagement
Virtual Assistants: How to Avoid Premature EngagementUSource
 

Viewers also liked (19)

PostgreSQL Conference: East 08
PostgreSQL Conference: East 08PostgreSQL Conference: East 08
PostgreSQL Conference: East 08
 
Amazon RDS for PostgreSQL - PGConf 2016
Amazon RDS for PostgreSQL - PGConf 2016 Amazon RDS for PostgreSQL - PGConf 2016
Amazon RDS for PostgreSQL - PGConf 2016
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized World
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized World
 
презентация команды мбоу сш 15 5 класс
презентация команды мбоу сш 15 5 класспрезентация команды мбоу сш 15 5 класс
презентация команды мбоу сш 15 5 класс
 
Vipra march2015
Vipra march2015Vipra march2015
Vipra march2015
 
Effect of BA, IBA and cutting type on transplants production from cuttings
Effect of BA, IBA and cutting type on transplants production from cuttingsEffect of BA, IBA and cutting type on transplants production from cuttings
Effect of BA, IBA and cutting type on transplants production from cuttings
 
Seminario 2 de investigación penal
Seminario 2 de investigación penalSeminario 2 de investigación penal
Seminario 2 de investigación penal
 
Isabella_Practicum_Assessment
Isabella_Practicum_AssessmentIsabella_Practicum_Assessment
Isabella_Practicum_Assessment
 
Bistabilul
BistabilulBistabilul
Bistabilul
 
Presentación cartilla gallina
Presentación cartilla gallinaPresentación cartilla gallina
Presentación cartilla gallina
 
교육평가 제5징 표준화검사화 컴퓨터화검사
교육평가 제5징 표준화검사화 컴퓨터화검사교육평가 제5징 표준화검사화 컴퓨터화검사
교육평가 제5징 표준화검사화 컴퓨터화검사
 
Eutanasia
EutanasiaEutanasia
Eutanasia
 
Unit dentar fona nou DenTam Creation
Unit dentar fona nou DenTam CreationUnit dentar fona nou DenTam Creation
Unit dentar fona nou DenTam Creation
 
Evaluation 1
Evaluation 1 Evaluation 1
Evaluation 1
 
Education and poverty in florida
Education and poverty in floridaEducation and poverty in florida
Education and poverty in florida
 
Study on the effect of pollution on some vegetable crops
Study on the effect of pollution on some vegetable  cropsStudy on the effect of pollution on some vegetable  crops
Study on the effect of pollution on some vegetable crops
 
Eνδοσχολική βία (Bullying)
Eνδοσχολική βία (Bullying)Eνδοσχολική βία (Bullying)
Eνδοσχολική βία (Bullying)
 
Virtual Assistants: How to Avoid Premature Engagement
Virtual Assistants: How to Avoid Premature EngagementVirtual Assistants: How to Avoid Premature Engagement
Virtual Assistants: How to Avoid Premature Engagement
 

Similar to One Database To Rule 'em All

Overiew of Cassandra and Doradus
Overiew of Cassandra and DoradusOveriew of Cassandra and Doradus
Overiew of Cassandra and Doradusrandyguck
 
Graph Analysis over JSON, Larus
Graph Analysis over JSON, LarusGraph Analysis over JSON, Larus
Graph Analysis over JSON, LarusNeo4j
 
MYSQL
MYSQLMYSQL
MYSQLARJUN
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8宇 傅
 
My sql presentation
My sql presentationMy sql presentation
My sql presentationNikhil Jain
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationsupporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationMahabubur Rahaman
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objectshiren.joshi
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsStefan Urbanek
 
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Paul Leclercq
 
Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015StampedeCon
 
Visualizing a Database Structure with SchemaSpy
Visualizing a Database Structure with SchemaSpyVisualizing a Database Structure with SchemaSpy
Visualizing a Database Structure with SchemaSpyGuo Albert
 
My sql with querys
My sql with querysMy sql with querys
My sql with querysNIRMAL FELIX
 

Similar to One Database To Rule 'em All (20)

Sah
SahSah
Sah
 
Overiew of Cassandra and Doradus
Overiew of Cassandra and DoradusOveriew of Cassandra and Doradus
Overiew of Cassandra and Doradus
 
MySQL
MySQLMySQL
MySQL
 
Graph Analysis over JSON, Larus
Graph Analysis over JSON, LarusGraph Analysis over JSON, Larus
Graph Analysis over JSON, Larus
 
MYSQL
MYSQLMYSQL
MYSQL
 
MYSQL
MYSQLMYSQL
MYSQL
 
Neo4j (Part 1)
Neo4j (Part 1)Neo4j (Part 1)
Neo4j (Part 1)
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8
 
My sql presentation
My sql presentationMy sql presentation
My sql presentation
 
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentationsupporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
supporting t-sql scripts for IndexPage, Datapage and IndexDefragmentation
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
 
Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data Objects
 
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015Cassandra 3.0 - JSON at scale - StampedeCon 2015
Cassandra 3.0 - JSON at scale - StampedeCon 2015
 
JSON and the APInauts
JSON and the APInautsJSON and the APInauts
JSON and the APInauts
 
Visualizing a Database Structure with SchemaSpy
Visualizing a Database Structure with SchemaSpyVisualizing a Database Structure with SchemaSpy
Visualizing a Database Structure with SchemaSpy
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 

Recently uploaded

SMOTE and K-Fold Cross Validation-Presentation.pptx
SMOTE and K-Fold Cross Validation-Presentation.pptxSMOTE and K-Fold Cross Validation-Presentation.pptx
SMOTE and K-Fold Cross Validation-Presentation.pptxHaritikaChhatwal1
 
Principles and Practices of Data Visualization
Principles and Practices of Data VisualizationPrinciples and Practices of Data Visualization
Principles and Practices of Data VisualizationKianJazayeri1
 
Student Profile Sample report on improving academic performance by uniting gr...
Student Profile Sample report on improving academic performance by uniting gr...Student Profile Sample report on improving academic performance by uniting gr...
Student Profile Sample report on improving academic performance by uniting gr...Seán Kennedy
 
Easter Eggs From Star Wars and in cars 1 and 2
Easter Eggs From Star Wars and in cars 1 and 2Easter Eggs From Star Wars and in cars 1 and 2
Easter Eggs From Star Wars and in cars 1 and 217djon017
 
Real-Time AI Streaming - AI Max Princeton
Real-Time AI  Streaming - AI Max PrincetonReal-Time AI  Streaming - AI Max Princeton
Real-Time AI Streaming - AI Max PrincetonTimothy Spann
 
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...Amil Baba Dawood bangali
 
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024Susanna-Assunta Sansone
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfblazblazml
 
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptx
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptxThe Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptx
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptxTasha Penwell
 
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...Unveiling the Role of Social Media Suspect Investigators in Preventing Online...
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...Milind Agarwal
 
Defining Constituents, Data Vizzes and Telling a Data Story
Defining Constituents, Data Vizzes and Telling a Data StoryDefining Constituents, Data Vizzes and Telling a Data Story
Defining Constituents, Data Vizzes and Telling a Data StoryJeremy Anderson
 
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default  Presentation : Data Analysis Project PPTPredictive Analysis for Loan Default  Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPTBoston Institute of Analytics
 
What To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxWhat To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxSimranPal17
 
Conf42-LLM_Adding Generative AI to Real-Time Streaming Pipelines
Conf42-LLM_Adding Generative AI to Real-Time Streaming PipelinesConf42-LLM_Adding Generative AI to Real-Time Streaming Pipelines
Conf42-LLM_Adding Generative AI to Real-Time Streaming PipelinesTimothy Spann
 
convolutional neural network and its applications.pdf
convolutional neural network and its applications.pdfconvolutional neural network and its applications.pdf
convolutional neural network and its applications.pdfSubhamKumar3239
 
Semantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxSemantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxMike Bennett
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...Dr Arash Najmaei ( Phd., MBA, BSc)
 
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxmodul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxaleedritatuxx
 
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...Boston Institute of Analytics
 
INTRODUCTION TO Natural language processing
INTRODUCTION TO Natural language processingINTRODUCTION TO Natural language processing
INTRODUCTION TO Natural language processingsocarem879
 

Recently uploaded (20)

SMOTE and K-Fold Cross Validation-Presentation.pptx
SMOTE and K-Fold Cross Validation-Presentation.pptxSMOTE and K-Fold Cross Validation-Presentation.pptx
SMOTE and K-Fold Cross Validation-Presentation.pptx
 
Principles and Practices of Data Visualization
Principles and Practices of Data VisualizationPrinciples and Practices of Data Visualization
Principles and Practices of Data Visualization
 
Student Profile Sample report on improving academic performance by uniting gr...
Student Profile Sample report on improving academic performance by uniting gr...Student Profile Sample report on improving academic performance by uniting gr...
Student Profile Sample report on improving academic performance by uniting gr...
 
Easter Eggs From Star Wars and in cars 1 and 2
Easter Eggs From Star Wars and in cars 1 and 2Easter Eggs From Star Wars and in cars 1 and 2
Easter Eggs From Star Wars and in cars 1 and 2
 
Real-Time AI Streaming - AI Max Princeton
Real-Time AI  Streaming - AI Max PrincetonReal-Time AI  Streaming - AI Max Princeton
Real-Time AI Streaming - AI Max Princeton
 
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...
NO1 Certified Black Magic Specialist Expert Amil baba in Lahore Islamabad Raw...
 
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024
FAIR, FAIRsharing, FAIR Cookbook and ELIXIR - Sansone SA - Boston 2024
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
 
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptx
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptxThe Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptx
The Power of Data-Driven Storytelling_ Unveiling the Layers of Insight.pptx
 
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...Unveiling the Role of Social Media Suspect Investigators in Preventing Online...
Unveiling the Role of Social Media Suspect Investigators in Preventing Online...
 
Defining Constituents, Data Vizzes and Telling a Data Story
Defining Constituents, Data Vizzes and Telling a Data StoryDefining Constituents, Data Vizzes and Telling a Data Story
Defining Constituents, Data Vizzes and Telling a Data Story
 
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default  Presentation : Data Analysis Project PPTPredictive Analysis for Loan Default  Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
 
What To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptxWhat To Do For World Nature Conservation Day by Slidesgo.pptx
What To Do For World Nature Conservation Day by Slidesgo.pptx
 
Conf42-LLM_Adding Generative AI to Real-Time Streaming Pipelines
Conf42-LLM_Adding Generative AI to Real-Time Streaming PipelinesConf42-LLM_Adding Generative AI to Real-Time Streaming Pipelines
Conf42-LLM_Adding Generative AI to Real-Time Streaming Pipelines
 
convolutional neural network and its applications.pdf
convolutional neural network and its applications.pdfconvolutional neural network and its applications.pdf
convolutional neural network and its applications.pdf
 
Semantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxSemantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptx
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
 
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptxmodul pembelajaran robotic Workshop _ by Slidesgo.pptx
modul pembelajaran robotic Workshop _ by Slidesgo.pptx
 
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...
Data Analysis Project : Targeting the Right Customers, Presentation on Bank M...
 
INTRODUCTION TO Natural language processing
INTRODUCTION TO Natural language processingINTRODUCTION TO Natural language processing
INTRODUCTION TO Natural language processing
 

One Database To Rule 'em All

  • 1. One Database To Rule 'em All European PostgreSQL Conference 2016 Tallinn Stefanie Janine Stölting @sjstoelting mail@stefanie-stoelting.de PostgreSQL SQL-MED
  • 2. SQL/MED Defined by ISO/IEC 9075-9:2008 Supported by DB2 MariaDB With CONNECT storage engine, implementation differs to the standard PostgreSQL
  • 3. Implementation Foreign Data Wrapper Read only Read and write Installation as extensions
  • 4. Available FDW Examples: Oracle (pgxn.org) MS SQL Server / Sybase ASE read-only (pgxn.org) MongoDB read-only (pgxn.org) MariaDB / MySQL (pgxn.org) SQLite read-only (GithHub) Hadoop (HDFS) read-only (GitHub)
  • 6. Write your own FDW Multicorn Use Python and Multicorn to write your own and access lots of stuff like IMAP HTML
  • 7. Data source The example data used in the live data part is available from Chinook Database: PostgreSQL MySQL CSV SQLite
  • 9. CTE Common Table Expressions will be used in examples ● Example: WITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n < 100 ) SELECT sum(n), min(n), max(n) FROM t; ● Result:
  • 11. Live Data examples -- Create the SQLite foreign data wrapper extension in the current database CREATE EXTENSION sqlite_fdw; -- Create the mapping to the foreign SQLite file CREATE SERVER sqlite_server FOREIGN DATA WRAPPER sqlite_fdw OPTIONS (database '/var/sqlite/Chinook_Sqlite.sqlite') ; -- Create the SQLite foreign table, column definitions have to match CREATE FOREIGN TABLE sqlite_artist( "ArtistId" integer, "Name" character varying(120) ) SERVER sqlite_server OPTIONS( table 'Artist' );
  • 12. Live Data examples -- Select some data SELECT * FROM sqlite_artist;
  • 13. Live Data examples -- Create the foreign data wrapper extension in the current database CREATE EXTENSION mysql_fdw; -- Create the mapping to the foreign MariaDB server CREATE SERVER mariadb_server FOREIGN DATA WRAPPER mysql_fdw OPTIONS (host '127.0.0.1', port '3306'); -- Create a user mapping with user and password of the foreign table -- PostgreSQL gives you options to connect this user with its own users CREATE USER MAPPING FOR PUBLIC SERVER mariadb_server OPTIONS (username 'stefanie', password 'secret');
  • 14. Live Data examples -- Create the MariaDB foreign table, column definitions have to match CREATE FOREIGN TABLE mysql_album( "AlbumId" integer, "Title" character varying(160), "ArtistId" integer ) SERVER mariadb_server OPTIONS( dbname 'Chinook', table_name 'Album' ); -- Select some data SELECT * FROM mysql_album;
  • 15. Live Data examples -- Join SQLite and MariaDB tables SELECT artist."Name" , album."Title" FROM sqlite_artist AS artist INNER JOIN mysql_album AS album ON artist."ArtistId" = album."ArtistId" ;
  • 16. Live Data examples CREATE EXTENSION postgres_fdw; -- Create a connection to the other database on the same server CREATE SERVER pg_localhost_chinook FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'chinook') ; -- Create a user mapping CREATE USER MAPPING FOR stefanie SERVER pg_localhost_chinook OPTIONS (user 'stefanie', password 'password') ;
  • 17. Live Data examples -- Link foreign tables into the current database and schema IMPORT FOREIGN SCHEMA public LIMIT TO("Track") FROM SERVER pg_localhost_chinook INTO public ; -- Try to select some data SELECT * FROM "Track";
  • 18. Live Data examples -- Join SQLite, MariaDB, and PostgreSQL tables SELECT artist."Name" , album."Title" , track."Name" FROM sqlite_artist AS artist INNER JOIN mysql_album AS album ON artist."ArtistId" = album."ArtistId" INNER JOIN "Track" AS track ON album."AlbumId" = track."AlbumId" ;
  • 19. Live Data examples CREATE EXTENSION file_fdw; -- One does need a server, but afterwards every csv file is avilable CREATE SERVER chinook_csv FOREIGN DATA WRAPPER file_fdw ; -- Creating a foreign table based on a csv file -- Options are the same as in COPY CREATE FOREIGN TABLE csv_genre ( "GenreId" integer, "Name" text ) SERVER chinook_csv OPTIONS ( filename '/var/tmp/Genre.csv', format 'csv', HEADER 'true' );
  • 20. Live Data examples -- Select some data SELECT * FROM csv_genre;
  • 21. Live Data examples -- Join SQLite, MariaDB, PostgreSQL, and CSV tables SELECT artist."Name" , album."Title" , track."Name" , genre."Name" FROM sqlite_artist AS artist INNER JOIN mysql_album AS album ON artist."ArtistId" = album."ArtistId" INNER JOIN "Track" AS track ON album."AlbumId" = track."AlbumId" INNER JOIN csv_genre AS genre ON track."GenreId" = genre."GenreId" ;
  • 22. Live Data examples -- Joining SQLite and MariaDB tables using PostgreSQL expressions WITH album AS ( SELECT "ArtistId" , array_agg("Title") AS album_titles FROM mysql_album GROUP BY "ArtistId" ) SELECT artist."Name" AS artist , album.album_titles FROM sqlite_artist AS artist INNER JOIN album ON artist."ArtistId" = album."ArtistId" ;
  • 23. Live Data examples -- Creates an materialized view on foreign tables CREATE MATERIALIZED VIEW mv_album_artist AS WITH album AS ( SELECT "ArtistId" , array_agg("Title") AS album_titles FROM mysql_album GROUP BY "ArtistId" ) SELECT artist."Name" AS artist , album.album_titles , SUM(ARRAY_LENGTH(album_titles, 1)) FROM sqlite_artist AS artist LEFT OUTER JOIN album ON artist."ArtistId" = album."ArtistId" GROUP BY artist."Name" , album.album_titles ;
  • 24. Live Data examples -- Select the mv data SELECT * FROM mv_album_artist WHERE upper(artist) LIKE 'A%' ORDER BY artist ;
  • 25. Live Data examples -- SELECT the amount of albums from the MariaDB table from MariaDB, not with a foreign data wrapper SELECT count( * ) AS AlbumCount FROM `Album` ;
  • 26. Live Data examples -- Insert data calculated from foreign tables using PostgreSQL features into another foreign table INSERT INTO mysql_album("AlbumId", "ArtistId", "Title") WITH album AS ( -- Generate a new album id SELECT MAX(album."AlbumId") + 1 AS new_album_id FROM mysql_album AS album ) SELECT album.new_album_id , artist."ArtistId" , 'Back in Black' FROM sqlite_artist AS artist, album WHERE artist."Name" = 'AC/DC' GROUP BY album.new_album_id , artist."ArtistId" ;
  • 27. Live Data examples -- SELECT the amount of albums from the MariaDB table from MariaDB, not with a foreign data wrapper SELECT count( * ) AS AlbumCount FROM `Album` ;
  • 28. Live Data examples -- Select data from the materialized view SELECT * FROM mv_album_artist WHERE artist = 'AC/DC' ORDER BY artist ; -- Refresh the mv to see the recently added data REFRESH MATERIALIZED VIEW mv_album_artist; -- We can even delete data from foreign tables DELETE FROM mysql_album WHERE "Title" = 'Back in Black' AND "ArtistId" = 1 ;
  • 29. Live Data examples -- Using PostgreSQL JSON with data from MariaDB and SQLite -- Step 1: Albums with tracks as JSON WITH albums AS ( SELECT a."ArtistId" AS artist_id , a."Title" AS album_title , array_agg(t."Name") AS album_tracks FROM mysql_album AS a INNER JOIN "Track" AS t ON a."AlbumId" = t."AlbumId" GROUP BY a."ArtistId" , a."Title" ) SELECT row_to_json(albums) AS album_tracks FROM albums ;
  • 30. Live Data examples -- Albums including tracks with aritsts with some JSON magic WITH albums AS ( SELECT a."ArtistId" AS artist_id , a."Title" AS album_title , array_agg(t."Name") AS album_tracks FROM mysql_album AS a INNER JOIN "Track" AS t ON a."AlbumId" = t."AlbumId" GROUP BY a."ArtistId" , a."Title" ) , js_albums AS ( SELECT row_to_json(albums) AS album_tracks FROM albums ) SELECT a."Name" AS artist , jsonb_pretty(al.album_tracks::jsonb) AS albums_tracks FROM sqlite_artist AS a INNER JOIN js_albums AS al ON a."ArtistId" = (al.album_tracks→>'artist_id')::int ;
  • 32. Live Data examples -- Create the multicorn extension CREATE EXTENSION multicorn;
  • 33. Live Data examples CREATE SERVER rss_srv foreign data wrapper multicorn options ( wrapper 'multicorn.rssfdw.RssFdw' ) ;
  • 34. Live Data examples -- Create a foreign table based on an RSS feed CREATE FOREIGN TABLE rss_postgresql_events ( title CHARACTER VARYING, link CHARACTER VARYING, description CHARACTER VARYING, "pubDate" TIMESTAMPTZ, guid CHARACTER VARYING ) server rss_srv OPTIONS ( url 'https://www.postgresql.org/events.rss' ) ;
  • 35. Live Data examples -- Query the RSS feed SELECT * FROM rss_postgresql_events ;
  • 36. Live Data examples -- Entend the query of the RSS feed SELECT title , "pubDate"::DATE AS "Conference Start Date" , description FROM rss_postgresql_events WHERE "pubDate"::DATE > NOW()::DATE ORDER BY "pubDate" ASC ;
  • 37. Link List PGXN Extensions: - mysql_fdw, MySQL/MariaDB FDW - sqlite_fdw, SQLite FDW Slide and source on Github: https://github.com/sjstoelting/talks/
  • 38. One Database To Rule 'em All This document by Stefanie Janine Stölting is covered by the Creative Commons Attribution 4.0 International

Editor's Notes

  1. Some BI Tools don‘t detect foreign data tables. This extension solves the problem.