SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Python in the database 
Writing PostgreSQL triggers and functions 
with Python
Who Am I 
Brian Sutherland 
Partner at Vanguardistas LLC 
Worked with PostgreSQL and Python for years 
Used them to build Metro Publisher (SaaS)
What is PostgreSQL? 
A non-NoSQL database… 
Actually an SQL database 
Extremely extensible 
Performant 
First released 1995 
Very good general purpose Database
But we’re here to talk about Triggers 
Code which executes inside the database 
process in response to events 
e.g. INSERT/UPDATE/DELETE a new row
Triggers 
Used for 
● auditing/logging 
● sending email 
● validation 
● denormalization/cache 
● cache invalidation 
● replication
Triggers 
PostgreSQL allows writing triggers in a number 
of languages: 
● C 
● Java 
● Javascript 
● Python 
● ...
Triggers 
Use with caution 
● Principle of least astonishment 
○ INSERT can send email 
● Transactions 
○ Serialization Errors 
○ Idempotency 
○ Transaction Rollback
PL/Python 
● Python 2 and 3 
● Basic Postgres types are converted to 
Python 
● An “untrusted” language 
● One interpreter per database session
Calendaring Example 
Web application for calendaring 
● Recurring events 
● Read queries must be fast 
High number of database reads compared to 
writes
Calendaring Example 
Every Weekday at 3PM until 1 January 2020 
>>> from dateutil.rrule import * 
>>> list(rrule(DAILY, 
byweekday=[MO, TU, WE, TH, FR], 
dtstart=datetime(2014, 11, 10, 15), 
until=datetime(2020, 1, 1))) 
[datetime.datetime(2014, 11, 10, 15, 0), 
datetime.datetime(2014, 11, 11, 15, 0), 
datetime.datetime(2014, 11, 12, 15, 0), 
…]
Calendaring Example 
Naïve Implementation 
● Store only the rule in the database 
● On display, expand the rule using dateutil 
● Render calendar in HTML
Calendaring Example 
FAIL 
There are 100 000 events in the database, find 
all events which occur between 3 and 4 PM 
today 
Calculating………………………...
Calendaring Example 
Find another way, use triggers to 
● Pre-calculate occurrences 
● Store them in another “cache” table 
● Use PostgreSQL indexes to make queries 
fast
Calendaring Example 
Trigger on the “event” generates occurrences 
Store the occurrences in an “occ” table 
Thanks to indexing, this query is FAST: 
SELECT * FROM occ 
WHERE dtstart > X AND dtend < Y
Calendaring Example 
PostgreSQL has a range type which makes 
things even faster: 
SELECT * FROM occ 
WHERE occuring && tsrange(X, Y)
Calendaring Example 
Creating the trigger 
CREATE LANGUAGE "plpython2u"; 
CREATE FUNCTION event_occs () RETURNS trigger AS $$ 
from my.plpy.generate_event_occs import generate_event_occs 
generate_event_occs(TD["new"]) 
return "OK" 
$$ LANGUAGE plpython2u; 
CREATE TRIGGER event_gen_occs BEFORE UPDATE OR INSERT ON 
event FOR EACH ROW EXECUTE PROCEDURE event_occs();
Calendaring Example 
Much simplified function: 
import plpy 
def generate_event_occs(new): 
d = plpy.prepare("DELETE FROM occ WHERE event_id=$1" , ["int"]) 
plpy.execute(d, [new[‘event_id’]]) 
i = plpy.prepare("INSERT INTO occ VALUES ($1,$2)", ["int", “tsrange”]) 
for period in rrule(new): 
plpy.execute(i, [new[‘event_id’], period])
JSON Validation example 
Store JSON in a column 
We want to make sure there is a “type” key
JSON Validation example 
Much simplified function: 
CREATE FUNCTION check_foo() RETURNS trigger AS $$ 
from json import loads 
foo = loads(TD["new"]["foo"]) 
if "type" not in foo or foo["type"] not in ["a", "b"]: 
raise Exception("Invalid Type") 
return "OK" 
$$ LANGUAGE plpython2u;
Best Practices 
Immediately import and call a python function 
CREATE FUNCTION event_occs () RETURNS trigger AS $$ 
from my.plpy.generate_event_occs import generate_event_occs 
generate_event_occs(TD["new"]) 
return "OK" 
$$ LANGUAGE plpython2u;
Best Practices 
Import time can kill performance as modules 
are re-imported every database connection
The ugly 
● Except for some very basic types, Python 2 
gets fed byte strings in the “database 
encoding” 
● A little better in Python 3 which gets unicode 
● Debugging is interesting... (try running PDB 
inside the PostgreSQL process)
The REALLY ugly (Fixed?) 
ERROR: Exception: oops 
CONTEXT: Traceback (most recent call last): 
PL/Python function "generate_event_occs", line 3, in <module> 
return generate_event_occs(event, rrule, SD) 
PL/Python function "generate_event_occs", line 256, in generate_event_occs 
PL/Python function "generate_event_occs", line 73, in generate_occurrences 
PL/Python function "generate_event_occs", line 97, in generate 
PL/Python function "generate_event_occs", line 424, in _handle_byday 
PL/Python function "generate_event_occs", line 206, in resolve 
PL/Python function "generate_event_occs" 
PL/pgSQL function content.generate_event_occs() line 7 at assignment 
SQL statement "UPDATE content.event SET dtstart_occs=NULL WHERE uuid=ev_uuid" 
PL/pgSQL function content.event_rrule_set_occ_bounds() line 12 at SQL statement
Conclusions 
VERY useful for complex code in the database 
if you already program in python 
Python has a lot of libraries which can be used 
It has warts, but is a lifesaver
Questions? 
Documentation: 
http://www.postgresql.org/docs/devel/static/plpython.html

Contenu connexe

Tendances

Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsFlink Forward
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxvishal choudhary
 
Cassandra for Python Developers
Cassandra for Python DevelopersCassandra for Python Developers
Cassandra for Python DevelopersTyler Hobbs
 
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...Ruby Meditation
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB Puppet
 
More Data, More Problems: Evolving big data machine learning pipelines with S...
More Data, More Problems: Evolving big data machine learning pipelines with S...More Data, More Problems: Evolving big data machine learning pipelines with S...
More Data, More Problems: Evolving big data machine learning pipelines with S...Alex Sadovsky
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...Modern Data Stack France
 
Create & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptxCreate & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptxvishal choudhary
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
Node collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDBNode collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDBm_richardson
 

Tendances (20)

How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
Sbt for mere mortals
Sbt for mere mortalsSbt for mere mortals
Sbt for mere mortals
 
Apache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API BasicsApache Flink Training: DataSet API Basics
Apache Flink Training: DataSet API Basics
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
 
Cassandra for Python Developers
Cassandra for Python DevelopersCassandra for Python Developers
Cassandra for Python Developers
 
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB
Puppet Camp Melbourne 2014: Node Collaboration with PuppetDB
 
Query planner
Query plannerQuery planner
Query planner
 
More Data, More Problems: Evolving big data machine learning pipelines with S...
More Data, More Problems: Evolving big data machine learning pipelines with S...More Data, More Problems: Evolving big data machine learning pipelines with S...
More Data, More Problems: Evolving big data machine learning pipelines with S...
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
Hadoop meetup : HUGFR Construire le cluster le plus rapide pour l'analyse des...
 
Full Text Search In PostgreSQL
Full Text Search In PostgreSQLFull Text Search In PostgreSQL
Full Text Search In PostgreSQL
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
 
Create & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptxCreate & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptx
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Node collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDBNode collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDB
 
Bootstrap
BootstrapBootstrap
Bootstrap
 

En vedette

No sql database and python -- Presentation done at Python Developer's meetup ...
No sql database and python -- Presentation done at Python Developer's meetup ...No sql database and python -- Presentation done at Python Developer's meetup ...
No sql database and python -- Presentation done at Python Developer's meetup ...Roshan Bhandari
 
Business logic with PostgreSQL and Python
Business logic with PostgreSQL and PythonBusiness logic with PostgreSQL and Python
Business logic with PostgreSQL and PythonHubert Piotrowski
 
Embarrassingly parallel database calls with Python (PyData Paris 2015 )
Embarrassingly parallel database calls with Python (PyData Paris 2015 )Embarrassingly parallel database calls with Python (PyData Paris 2015 )
Embarrassingly parallel database calls with Python (PyData Paris 2015 )GoDataDriven
 
Python and EM CLI: The Enterprise Management Super Tools
Python and EM CLI: The Enterprise Management Super ToolsPython and EM CLI: The Enterprise Management Super Tools
Python and EM CLI: The Enterprise Management Super ToolsSeth Miller
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with PythonMark Rees
 
Profile and CV Martin C. Michel
Profile and CV Martin C. MichelProfile and CV Martin C. Michel
Profile and CV Martin C. MichelMartin C. Michel
 
Google plus pp
Google plus  ppGoogle plus  pp
Google plus ppmalimido
 
Bbl company presentation
Bbl company presentationBbl company presentation
Bbl company presentation水琴 余
 
TCEH Competitive Analysis July 2015
TCEH Competitive Analysis July 2015TCEH Competitive Analysis July 2015
TCEH Competitive Analysis July 2015Farhan Baig
 
Catalogo Vasos Exportação JPR
Catalogo Vasos Exportação JPRCatalogo Vasos Exportação JPR
Catalogo Vasos Exportação JPRthaishe
 

En vedette (20)

No sql database and python -- Presentation done at Python Developer's meetup ...
No sql database and python -- Presentation done at Python Developer's meetup ...No sql database and python -- Presentation done at Python Developer's meetup ...
No sql database and python -- Presentation done at Python Developer's meetup ...
 
Business logic with PostgreSQL and Python
Business logic with PostgreSQL and PythonBusiness logic with PostgreSQL and Python
Business logic with PostgreSQL and Python
 
Embarrassingly parallel database calls with Python (PyData Paris 2015 )
Embarrassingly parallel database calls with Python (PyData Paris 2015 )Embarrassingly parallel database calls with Python (PyData Paris 2015 )
Embarrassingly parallel database calls with Python (PyData Paris 2015 )
 
Python and EM CLI: The Enterprise Management Super Tools
Python and EM CLI: The Enterprise Management Super ToolsPython and EM CLI: The Enterprise Management Super Tools
Python and EM CLI: The Enterprise Management Super Tools
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
 
MEMS 200704
MEMS 200704MEMS 200704
MEMS 200704
 
Profile and CV Martin C. Michel
Profile and CV Martin C. MichelProfile and CV Martin C. Michel
Profile and CV Martin C. Michel
 
Linked in talent solution for indonesia
Linked in talent solution for indonesiaLinked in talent solution for indonesia
Linked in talent solution for indonesia
 
Trabajo
TrabajoTrabajo
Trabajo
 
Google plus pp
Google plus  ppGoogle plus  pp
Google plus pp
 
Office 365
Office 365Office 365
Office 365
 
Advertisement
AdvertisementAdvertisement
Advertisement
 
Aqua Jet 2017
Aqua Jet 2017Aqua Jet 2017
Aqua Jet 2017
 
Bbl company presentation
Bbl company presentationBbl company presentation
Bbl company presentation
 
TCEH Competitive Analysis July 2015
TCEH Competitive Analysis July 2015TCEH Competitive Analysis July 2015
TCEH Competitive Analysis July 2015
 
Catalogo Vasos Exportação JPR
Catalogo Vasos Exportação JPRCatalogo Vasos Exportação JPR
Catalogo Vasos Exportação JPR
 
Diktat autocad
Diktat autocadDiktat autocad
Diktat autocad
 
Tuanda powerpoint
Tuanda powerpointTuanda powerpoint
Tuanda powerpoint
 
Upeps 2016
Upeps 2016Upeps 2016
Upeps 2016
 
Dalton
DaltonDalton
Dalton
 

Similaire à Python in the database

How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowLaura Lorenz
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowPyData
 
Etl confessions pg conf us 2017
Etl confessions   pg conf us 2017Etl confessions   pg conf us 2017
Etl confessions pg conf us 2017Corey Huinker
 
Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek PROIDEA
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackJakub Hajek
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Ontico
 
Learn backend java script
Learn backend java scriptLearn backend java script
Learn backend java scriptTsuyoshi Maeda
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Alessandro Molina
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...it-people
 
Distributed real time stream processing- why and how
Distributed real time stream processing- why and howDistributed real time stream processing- why and how
Distributed real time stream processing- why and howPetr Zapletal
 
Elk with Openstack
Elk with OpenstackElk with Openstack
Elk with OpenstackArun prasath
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
Logstash: Get to know your logs
Logstash: Get to know your logsLogstash: Get to know your logs
Logstash: Get to know your logsSmartLogic
 
Digdagによる大規模データ処理の自動化とエラー処理
Digdagによる大規模データ処理の自動化とエラー処理Digdagによる大規模データ処理の自動化とエラー処理
Digdagによる大規模データ処理の自動化とエラー処理Sadayuki Furuhashi
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupDavid Barreto
 
Oracle Wait Events That Everyone Should Know.ppt
Oracle Wait Events That Everyone Should Know.pptOracle Wait Events That Everyone Should Know.ppt
Oracle Wait Events That Everyone Should Know.pptTricantinoLopezPerez
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 

Similaire à Python in the database (20)

How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with Airflow
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with Airflow
 
Etl confessions pg conf us 2017
Etl confessions   pg conf us 2017Etl confessions   pg conf us 2017
Etl confessions pg conf us 2017
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek Docker Logging and analysing with Elastic Stack - Jakub Hajek
Docker Logging and analysing with Elastic Stack - Jakub Hajek
 
Docker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic StackDocker Logging and analysing with Elastic Stack
Docker Logging and analysing with Elastic Stack
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
 
Learn backend java script
Learn backend java scriptLearn backend java script
Learn backend java script
 
Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2Reactive & Realtime Web Applications with TurboGears2
Reactive & Realtime Web Applications with TurboGears2
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
 
Distributed real time stream processing- why and how
Distributed real time stream processing- why and howDistributed real time stream processing- why and how
Distributed real time stream processing- why and how
 
Elk with Openstack
Elk with OpenstackElk with Openstack
Elk with Openstack
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
Logstash: Get to know your logs
Logstash: Get to know your logsLogstash: Get to know your logs
Logstash: Get to know your logs
 
Digdagによる大規模データ処理の自動化とエラー処理
Digdagによる大規模データ処理の自動化とエラー処理Digdagによる大規模データ処理の自動化とエラー処理
Digdagによる大規模データ処理の自動化とエラー処理
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Oracle Wait Events That Everyone Should Know.ppt
Oracle Wait Events That Everyone Should Know.pptOracle Wait Events That Everyone Should Know.ppt
Oracle Wait Events That Everyone Should Know.ppt
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Google cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache FlinkGoogle cloud Dataflow & Apache Flink
Google cloud Dataflow & Apache Flink
 

Dernier

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 

Dernier (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 

Python in the database

  • 1. Python in the database Writing PostgreSQL triggers and functions with Python
  • 2. Who Am I Brian Sutherland Partner at Vanguardistas LLC Worked with PostgreSQL and Python for years Used them to build Metro Publisher (SaaS)
  • 3. What is PostgreSQL? A non-NoSQL database… Actually an SQL database Extremely extensible Performant First released 1995 Very good general purpose Database
  • 4. But we’re here to talk about Triggers Code which executes inside the database process in response to events e.g. INSERT/UPDATE/DELETE a new row
  • 5. Triggers Used for ● auditing/logging ● sending email ● validation ● denormalization/cache ● cache invalidation ● replication
  • 6. Triggers PostgreSQL allows writing triggers in a number of languages: ● C ● Java ● Javascript ● Python ● ...
  • 7. Triggers Use with caution ● Principle of least astonishment ○ INSERT can send email ● Transactions ○ Serialization Errors ○ Idempotency ○ Transaction Rollback
  • 8. PL/Python ● Python 2 and 3 ● Basic Postgres types are converted to Python ● An “untrusted” language ● One interpreter per database session
  • 9. Calendaring Example Web application for calendaring ● Recurring events ● Read queries must be fast High number of database reads compared to writes
  • 10. Calendaring Example Every Weekday at 3PM until 1 January 2020 >>> from dateutil.rrule import * >>> list(rrule(DAILY, byweekday=[MO, TU, WE, TH, FR], dtstart=datetime(2014, 11, 10, 15), until=datetime(2020, 1, 1))) [datetime.datetime(2014, 11, 10, 15, 0), datetime.datetime(2014, 11, 11, 15, 0), datetime.datetime(2014, 11, 12, 15, 0), …]
  • 11. Calendaring Example Naïve Implementation ● Store only the rule in the database ● On display, expand the rule using dateutil ● Render calendar in HTML
  • 12. Calendaring Example FAIL There are 100 000 events in the database, find all events which occur between 3 and 4 PM today Calculating………………………...
  • 13. Calendaring Example Find another way, use triggers to ● Pre-calculate occurrences ● Store them in another “cache” table ● Use PostgreSQL indexes to make queries fast
  • 14. Calendaring Example Trigger on the “event” generates occurrences Store the occurrences in an “occ” table Thanks to indexing, this query is FAST: SELECT * FROM occ WHERE dtstart > X AND dtend < Y
  • 15. Calendaring Example PostgreSQL has a range type which makes things even faster: SELECT * FROM occ WHERE occuring && tsrange(X, Y)
  • 16. Calendaring Example Creating the trigger CREATE LANGUAGE "plpython2u"; CREATE FUNCTION event_occs () RETURNS trigger AS $$ from my.plpy.generate_event_occs import generate_event_occs generate_event_occs(TD["new"]) return "OK" $$ LANGUAGE plpython2u; CREATE TRIGGER event_gen_occs BEFORE UPDATE OR INSERT ON event FOR EACH ROW EXECUTE PROCEDURE event_occs();
  • 17. Calendaring Example Much simplified function: import plpy def generate_event_occs(new): d = plpy.prepare("DELETE FROM occ WHERE event_id=$1" , ["int"]) plpy.execute(d, [new[‘event_id’]]) i = plpy.prepare("INSERT INTO occ VALUES ($1,$2)", ["int", “tsrange”]) for period in rrule(new): plpy.execute(i, [new[‘event_id’], period])
  • 18. JSON Validation example Store JSON in a column We want to make sure there is a “type” key
  • 19. JSON Validation example Much simplified function: CREATE FUNCTION check_foo() RETURNS trigger AS $$ from json import loads foo = loads(TD["new"]["foo"]) if "type" not in foo or foo["type"] not in ["a", "b"]: raise Exception("Invalid Type") return "OK" $$ LANGUAGE plpython2u;
  • 20. Best Practices Immediately import and call a python function CREATE FUNCTION event_occs () RETURNS trigger AS $$ from my.plpy.generate_event_occs import generate_event_occs generate_event_occs(TD["new"]) return "OK" $$ LANGUAGE plpython2u;
  • 21. Best Practices Import time can kill performance as modules are re-imported every database connection
  • 22. The ugly ● Except for some very basic types, Python 2 gets fed byte strings in the “database encoding” ● A little better in Python 3 which gets unicode ● Debugging is interesting... (try running PDB inside the PostgreSQL process)
  • 23. The REALLY ugly (Fixed?) ERROR: Exception: oops CONTEXT: Traceback (most recent call last): PL/Python function "generate_event_occs", line 3, in <module> return generate_event_occs(event, rrule, SD) PL/Python function "generate_event_occs", line 256, in generate_event_occs PL/Python function "generate_event_occs", line 73, in generate_occurrences PL/Python function "generate_event_occs", line 97, in generate PL/Python function "generate_event_occs", line 424, in _handle_byday PL/Python function "generate_event_occs", line 206, in resolve PL/Python function "generate_event_occs" PL/pgSQL function content.generate_event_occs() line 7 at assignment SQL statement "UPDATE content.event SET dtstart_occs=NULL WHERE uuid=ev_uuid" PL/pgSQL function content.event_rrule_set_occ_bounds() line 12 at SQL statement
  • 24. Conclusions VERY useful for complex code in the database if you already program in python Python has a lot of libraries which can be used It has warts, but is a lifesaver