SlideShare a Scribd company logo
Business logic with
PostgreSQL and Python
Using functions and triggers and PostgreSQL magic with plpy.
Knock knock, who's
there?
Hubert Piotrowski
Senior systems architect
How to build API
How to build API
Perfect API
My awesome
software
Where API
functionalities are
part of it
Welcome to the
Reality
My awesome
software
API
Another app
Oh this this
small tool
My awesome
software
API
Oh this this
small tool
Another
magic
Fancy twisted
stackless
HELP?
My awesome
software
API
Oh this this
small tool
Another
magic
Business
LOGIC
What is so great about
PostgreSQL
• Dynamic data typing
• Procedural functions (many languages)
• Horizontal scaling
• Plugins
• Triggers
• Granularity for access privileges
Data types
• Standard: Strings, float, inter, etc.
• JSON
• Dynamic (composite)
• Arrays
Arrays
Or, if no array size is to be specified:
pay_by_quarter integer ARRAY
pay_by_quarter integer ARRAY[4]
Arrays
And get it
INSERT INTO sal_emp
VALUES ('Bill',
'{10000, 10000, 10000, 10000}',
'{{"meeting", "lunch"}, {"training", "presentation"}}');
SELECT name FROM sal_emp WHERE pay_by_quarter[1] <> pay_by_quarter[2];
name
-------
Carol
(1 row)
Still arrays
SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill';
schedule
-------------------------------------------
{{meeting,lunch},{training,presentation}}
(1 row)
SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);
Composite
CREATE TYPE inventory_item AS (
name text,
supplier_id integer,
price numeric
);
CREATE TABLE on_hand (
item inventory_item,
count integer
);
INSERT INTO on_hand VALUES (ROW('fuzzy dice', 42, 1.99), 1000);
Procedures
plPythonu(?) one second
CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
DECLARE
t2_row table2%ROWTYPE;
BEGIN
SELECT * INTO t2_row FROM table2 WHERE ... ;
RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
END;
$$ LANGUAGE plpgsql;
SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
Better formatting
CREATE FUNCTION merge_fields(t_row table1)
RETURNS text AS
$$
DECLARE
t2_row table2%ROWTYPE;
BEGIN
SELECT * INTO t2_row FROM table2 WHERE ... ;
RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
END;
$$
LANGUAGE plpgsql;
SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
Let there be light...and there was light
Compile PostgreSQL 9.4 with Python 2.7.10
• PYTHONHOME
• PYTHONPATH
• PYTHONY2K
• PYTHONOPTIMIZE
• PYTHONDEBUG
• PYTHONVERBOSE
• PYTHONCASEOK
• PYTHONDONTWRITEBYTECODE
• PYTHONIOENCODING
• PYTHONUSERBASE
Python compiled with special flags
Compile python
Compilation takes some time…
Once it’s done… we need easy_install and other
python modules
[hubert@ThePit]~/stuff/Python-2.7.10% ./configure —PREFIX=/opt/py --enable-
shared
issues?
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/py/lib
py ➤ bin/python2.7
bin/python2.7: error while loading shared libraries: libpython2.7.so.1.0: cannot open
shared object file: No such file or directory
simple fix
Compile essential contrib data
contrib ➤ cd ~/stuff/postgresql-9.4.3/contrib
contrib ➤ make
contrib ➤ make install
Compile PostgreSQL
postgresql-9.4.3 ➤ ./configure --prefix=/opt/pgsql 
—with-python PYTHON=/opt/py/bin/python
postgresql-9.4.3 ➤ make
postgresql-9.4.3 ➤ make install
~ ➤ mkdir /opt/pg_data
~ ➤ /opt/pgsql/bin/initdb /opt/pg_data
~ ➤ /opt/pgsql/bin/postmaster -p 5432 -D /opt/pg_data/
~ ➤ /opt/pgsql/bin/createdb -h localhost -E utf8 pie
initialize database
Initialize postgresql data space
Create language plpython in database
~ ➤ /opt/pgsql/bin/createlang -h localhost -d pie plpythonu
~ ➤ /opt/pgsql/bin/postmaster -p 5432 -D /opt/pg_data/
LOG: database system was shut down at 2015-06-07 17:29:05 SGT
LOG: database system is ready to accept connections
LOG: autovacuum launcher started
pie=# select * from pg_extension ;
extname | extowner | extnamespace | extrelocatable | extversion | extconfig |
extcondition
-----------+----------+--------------+----------------+------------+-----------+--------------
plpgsql | 10 | 11 | f | 1.0 | |
plpythonu | 10 | 11 | f | 1.0 | |
(2 rows)
Let uncle Google help you
didn’t find the answer?
Probably the issue that you have means that
what you try to achieve is not possible or…
doesn’t make sense
First plPy function
Hello world
create or replace function logic.hello_world()
returns void as
$$
"""
Code code code code
"""
print "hello world"
$$
LANGUAGE plpythonu VOLATILE;
Hello world
create or replace function logic.hello_world()
returns void as
$$
"""
Code code code code
"""
plpy.info("hello world")
$$
LANGUAGE plpythonu VOLATILE;
Triggers
• can be fired before or after (instead of)
• upon action: insert, update or delete
• trigger fires function (also by using when condition)
• trigger function can but don’t have to manipulate data
• multiple triggers on the same table
Let’s see some action
Hungry for more?
@dj_techhub
darkman66
http://my-twisted-code.tumblr.com
https://github.com/darkman66/pyconsg2015

More Related Content

What's hot

Catmandu presentation at SWIB 2013
Catmandu presentation at SWIB 2013Catmandu presentation at SWIB 2013
Catmandu presentation at SWIB 2013
nicsteenlant
 
Luigi future
Luigi futureLuigi future
Luigi future
Erik Bernhardsson
 
First impressions of SparkR: our own machine learning algorithm
First impressions of SparkR: our own machine learning algorithmFirst impressions of SparkR: our own machine learning algorithm
First impressions of SparkR: our own machine learning algorithm
InfoFarm
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
Lin Yo-An
 
Introduction to SparkR
Introduction to SparkRIntroduction to SparkR
Introduction to SparkR
Kien Dang
 
Apache Flink - Hadoop MapReduce Compatibility
Apache Flink - Hadoop MapReduce CompatibilityApache Flink - Hadoop MapReduce Compatibility
Apache Flink - Hadoop MapReduce Compatibility
Fabian Hueske
 
IRIS-HEP Retreat: Boost-Histogram Roadmap
IRIS-HEP Retreat: Boost-Histogram RoadmapIRIS-HEP Retreat: Boost-Histogram Roadmap
IRIS-HEP Retreat: Boost-Histogram Roadmap
Henry Schreiner
 
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
Hakka Labs
 
Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...
jasonscheirer
 
RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)
Daniele Dell'Aglio
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
Florent Vilmart
 
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
InfluxData
 
Golang Arg / CABA Meetup #5 - go-carbon
Golang Arg / CABA Meetup #5 - go-carbonGolang Arg / CABA Meetup #5 - go-carbon
Golang Arg / CABA Meetup #5 - go-carbon
Ezequiel Maraschio
 
Introduction to R and R Studio
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R Studio
Rupak Roy
 
Libraries
LibrariesLibraries
SystemML - Datapalooza Denver - 05.17.16 MWD
SystemML - Datapalooza Denver - 05.17.16 MWDSystemML - Datapalooza Denver - 05.17.16 MWD
SystemML - Datapalooza Denver - 05.17.16 MWD
Mike Dusenberry
 
Distributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insightsDistributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insights
Huy Do
 
PyconUK-2015
PyconUK-2015PyconUK-2015
PyconUK-2015
Heeren Sharma
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
Steven Francia
 
Writing data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gemWriting data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gem
Sean S.G Wang
 

What's hot (20)

Catmandu presentation at SWIB 2013
Catmandu presentation at SWIB 2013Catmandu presentation at SWIB 2013
Catmandu presentation at SWIB 2013
 
Luigi future
Luigi futureLuigi future
Luigi future
 
First impressions of SparkR: our own machine learning algorithm
First impressions of SparkR: our own machine learning algorithmFirst impressions of SparkR: our own machine learning algorithm
First impressions of SparkR: our own machine learning algorithm
 
Happy Go Programming Part 1
Happy Go Programming Part 1Happy Go Programming Part 1
Happy Go Programming Part 1
 
Introduction to SparkR
Introduction to SparkRIntroduction to SparkR
Introduction to SparkR
 
Apache Flink - Hadoop MapReduce Compatibility
Apache Flink - Hadoop MapReduce CompatibilityApache Flink - Hadoop MapReduce Compatibility
Apache Flink - Hadoop MapReduce Compatibility
 
IRIS-HEP Retreat: Boost-Histogram Roadmap
IRIS-HEP Retreat: Boost-Histogram RoadmapIRIS-HEP Retreat: Boost-Histogram Roadmap
IRIS-HEP Retreat: Boost-Histogram Roadmap
 
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
Introduction to InfluxDB, an Open Source Distributed Time Series Database by ...
 
Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...
 
RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
 
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
Getting Ready to Move to InfluxDB 2.0 | Tim Hall | InfluxData
 
Golang Arg / CABA Meetup #5 - go-carbon
Golang Arg / CABA Meetup #5 - go-carbonGolang Arg / CABA Meetup #5 - go-carbon
Golang Arg / CABA Meetup #5 - go-carbon
 
Introduction to R and R Studio
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R Studio
 
Libraries
LibrariesLibraries
Libraries
 
SystemML - Datapalooza Denver - 05.17.16 MWD
SystemML - Datapalooza Denver - 05.17.16 MWDSystemML - Datapalooza Denver - 05.17.16 MWD
SystemML - Datapalooza Denver - 05.17.16 MWD
 
Distributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insightsDistributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insights
 
PyconUK-2015
PyconUK-2015PyconUK-2015
PyconUK-2015
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
Writing data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gemWriting data analysis pipeline as ruby gem
Writing data analysis pipeline as ruby gem
 

Similar to Business logic with PostgreSQL and Python

First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Dozie Agbo
 
Massively Parallel Processing with Procedural Python (PyData London 2014)
Massively Parallel Processing with Procedural Python (PyData London 2014)Massively Parallel Processing with Procedural Python (PyData London 2014)
Massively Parallel Processing with Procedural Python (PyData London 2014)
Ian Huston
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Prestogres internals
Prestogres internalsPrestogres internals
Prestogres internals
Sadayuki Furuhashi
 
PyWPS Development restart
PyWPS Development restartPyWPS Development restart
PyWPS Development restart
Jachym Cepicky
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
Mattupallipardhu
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 
Pl/Python
Pl/PythonPl/Python
Python on pi
Python on piPython on pi
Python on pi
swee meng ng
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
Chui-Wen Chiu
 
Massively Parallel Process with Prodedural Python by Ian Huston
Massively Parallel Process with Prodedural Python by Ian HustonMassively Parallel Process with Prodedural Python by Ian Huston
Massively Parallel Process with Prodedural Python by Ian Huston
PyData
 
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
PyData
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
it-people
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
Mark Rees
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Diego Freniche Brito
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Codemotion
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
Zabbix
 
Beyond the Loadable Module
Beyond the Loadable ModuleBeyond the Loadable Module
Beyond the Loadable Module
Vladimir Ulogov
 

Similar to Business logic with PostgreSQL and Python (20)

First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
Massively Parallel Processing with Procedural Python (PyData London 2014)
Massively Parallel Processing with Procedural Python (PyData London 2014)Massively Parallel Processing with Procedural Python (PyData London 2014)
Massively Parallel Processing with Procedural Python (PyData London 2014)
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Prestogres internals
Prestogres internalsPrestogres internals
Prestogres internals
 
PyWPS Development restart
PyWPS Development restartPyWPS Development restart
PyWPS Development restart
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
 
Python ppt
Python pptPython ppt
Python ppt
 
Pl/Python
Pl/PythonPl/Python
Pl/Python
 
Python on pi
Python on piPython on pi
Python on pi
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Massively Parallel Process with Prodedural Python by Ian Huston
Massively Parallel Process with Prodedural Python by Ian HustonMassively Parallel Process with Prodedural Python by Ian Huston
Massively Parallel Process with Prodedural Python by Ian Huston
 
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
Massively Parallel Processing with Procedural Python by Ronert Obst PyData Be...
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
 
Beyond the Loadable Module
Beyond the Loadable ModuleBeyond the Loadable Module
Beyond the Loadable Module
 

Recently uploaded

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 

Recently uploaded (20)

Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 

Business logic with PostgreSQL and Python

  • 1. Business logic with PostgreSQL and Python Using functions and triggers and PostgreSQL magic with plpy.
  • 2. Knock knock, who's there? Hubert Piotrowski Senior systems architect
  • 4. How to build API Perfect API
  • 8. My awesome software API Oh this this small tool Another magic Fancy twisted stackless
  • 10. My awesome software API Oh this this small tool Another magic Business LOGIC
  • 11. What is so great about PostgreSQL • Dynamic data typing • Procedural functions (many languages) • Horizontal scaling • Plugins • Triggers • Granularity for access privileges
  • 12. Data types • Standard: Strings, float, inter, etc. • JSON • Dynamic (composite) • Arrays
  • 13. Arrays Or, if no array size is to be specified: pay_by_quarter integer ARRAY pay_by_quarter integer ARRAY[4]
  • 14. Arrays And get it INSERT INTO sal_emp VALUES ('Bill', '{10000, 10000, 10000, 10000}', '{{"meeting", "lunch"}, {"training", "presentation"}}'); SELECT name FROM sal_emp WHERE pay_by_quarter[1] <> pay_by_quarter[2]; name ------- Carol (1 row)
  • 15. Still arrays SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill'; schedule ------------------------------------------- {{meeting,lunch},{training,presentation}} (1 row) SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);
  • 16. Composite CREATE TYPE inventory_item AS ( name text, supplier_id integer, price numeric ); CREATE TABLE on_hand ( item inventory_item, count integer ); INSERT INTO on_hand VALUES (ROW('fuzzy dice', 42, 1.99), 1000);
  • 17. Procedures plPythonu(?) one second CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$ DECLARE t2_row table2%ROWTYPE; BEGIN SELECT * INTO t2_row FROM table2 WHERE ... ; RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7; END; $$ LANGUAGE plpgsql; SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
  • 18. Better formatting CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$ DECLARE t2_row table2%ROWTYPE; BEGIN SELECT * INTO t2_row FROM table2 WHERE ... ; RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7; END; $$ LANGUAGE plpgsql; SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
  • 19. Let there be light...and there was light Compile PostgreSQL 9.4 with Python 2.7.10
  • 20. • PYTHONHOME • PYTHONPATH • PYTHONY2K • PYTHONOPTIMIZE • PYTHONDEBUG • PYTHONVERBOSE • PYTHONCASEOK • PYTHONDONTWRITEBYTECODE • PYTHONIOENCODING • PYTHONUSERBASE Python compiled with special flags
  • 21. Compile python Compilation takes some time… Once it’s done… we need easy_install and other python modules [hubert@ThePit]~/stuff/Python-2.7.10% ./configure —PREFIX=/opt/py --enable- shared
  • 22. issues? export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/py/lib py ➤ bin/python2.7 bin/python2.7: error while loading shared libraries: libpython2.7.so.1.0: cannot open shared object file: No such file or directory simple fix
  • 23. Compile essential contrib data contrib ➤ cd ~/stuff/postgresql-9.4.3/contrib contrib ➤ make contrib ➤ make install Compile PostgreSQL postgresql-9.4.3 ➤ ./configure --prefix=/opt/pgsql —with-python PYTHON=/opt/py/bin/python postgresql-9.4.3 ➤ make postgresql-9.4.3 ➤ make install
  • 24. ~ ➤ mkdir /opt/pg_data ~ ➤ /opt/pgsql/bin/initdb /opt/pg_data ~ ➤ /opt/pgsql/bin/postmaster -p 5432 -D /opt/pg_data/ ~ ➤ /opt/pgsql/bin/createdb -h localhost -E utf8 pie initialize database Initialize postgresql data space
  • 25. Create language plpython in database ~ ➤ /opt/pgsql/bin/createlang -h localhost -d pie plpythonu ~ ➤ /opt/pgsql/bin/postmaster -p 5432 -D /opt/pg_data/ LOG: database system was shut down at 2015-06-07 17:29:05 SGT LOG: database system is ready to accept connections LOG: autovacuum launcher started pie=# select * from pg_extension ; extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition -----------+----------+--------------+----------------+------------+-----------+-------------- plpgsql | 10 | 11 | f | 1.0 | | plpythonu | 10 | 11 | f | 1.0 | | (2 rows)
  • 26. Let uncle Google help you didn’t find the answer? Probably the issue that you have means that what you try to achieve is not possible or… doesn’t make sense
  • 28. Hello world create or replace function logic.hello_world() returns void as $$ """ Code code code code """ print "hello world" $$ LANGUAGE plpythonu VOLATILE;
  • 29. Hello world create or replace function logic.hello_world() returns void as $$ """ Code code code code """ plpy.info("hello world") $$ LANGUAGE plpythonu VOLATILE;
  • 30. Triggers • can be fired before or after (instead of) • upon action: insert, update or delete • trigger fires function (also by using when condition) • trigger function can but don’t have to manipulate data • multiple triggers on the same table