SlideShare a Scribd company logo
Introduction to python ORM SQLAlchemy
Jorge A. Medina Oliva - Barcelona
http://pybcn.org
May. 22 , 2014
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 1 / 18
What is an ORM?
An ORM is the software artefact who maps from relational data base
tables to object/class
This means: maps the tables and columns in a relational database directly
to the object instance and wraps all SQL/DDL functionality in his
methods.
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 2 / 18
SQLAlchemy it’s equivalent to...
Hiberante in java (main ideas become from here)
Doctrine in PHP
DataMapper in ruby (this is more close to Active Record pattern)
NHibernate in .Net C#
django ORM in python Web framework
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 3 / 18
differences with django orm
There are two very important differences between SQLAlchemy and
Django. SQLAlchemy is a deeply layered system, whereas Django’s ORM
is basically just one layer which is the ORM you see.
1 In SQLAlchemy you have at the very bottom the engine:
Connection pools and basic API differences between different databases
On top of that: the SQL abstraction language,
On top of SQL abstraction: the table definitions with the basic ORM
And on top of ORM you have the declarative ORM which looks very
close to the Django ORM.
2 The other more striking difference however is that SQLAlchemy
follows the “Unit of Work” pattern whereas Django’s ORM follows
something that is very close to the “Active Record” pattern.
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 4 / 18
SQLAlchemy Advantages
Great documentation at http://www.sqlalchemy.org
Independent framework
active and stable development
Strong design since beginning
Layered components like Connection pool, ORM, API, SQL,
Aggregates, etc.
We can use any independent component
Implement advanced Hibernate’s ideas.
SQLAlchemy doesn’t override all your columns when you just changed
one on update.
differed column load
Connection pooling
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 5 / 18
SQLAlchemy Disadvantages
Documentation overwhelming
Confuses at the beginning because exist different programming
options.
only integrates in Flask-SQLAlchemy web framework
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 6 / 18
Supported Platforms
SQLAlchemy has been tested against the following platforms:
cPython since version 2.6, through the 2.xx series
cPython version 3, throughout all 3.xx series
Pypy 2.1 or greater
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 7 / 18
Installation
With pip
pip install SQLAlchemy
Or with easy install
easy install SQLAlchemy
All other methods are supported too...
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 8 / 18
Arquitecture of SQLAlchemy
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 9 / 18
The basics to starts
""" SQLAlchemy engine factory """
from sqlalchemy import create_engine
""" ORM Datatypes """
from sqlalchemy import Column, ForeignKey, Integer, String
""" ORM Session factory """
from sqlalchemy.orm import sessionmaker
""" ORM relationship mapper """
from sqlalchemy.orm relationship
""" Declarative Base Object """
from sqlalchemy.ext.declarative import declarative_base
""" SQL expresions functions wrappers """
from sqlalchemy.sql import func
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 10 / 18
Basic Use case
engine = create_engine(’sqlite:///demo.db’, echo=False)
session = sessionmaker(bind=engine)()
Base.metadata.create_all(engine, checkfirst=True)
p = Parent(’prueba’)
session.add(p)
session.commit()
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 11 / 18
Basic Use case
q = session.query(Parent).all()
for x in q:
c = Child("child", x.id)
session.add(c)
session.commit()
session.refresh(p)
for x in q:
print("{}+n |".format(x.name))
for i in x.children:
print(" +-->{}".format(i.name))
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 12 / 18
Object mapper and relational pattern
One to Many
Base = declarative_base()
class Parent(Base):
__tablename__ = ’parent’
id = Column(Integer, primary_key=True)
children = relationship("Child", backref="parent")
class Child(Base):
__tablename__ = ’child’
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey(’parent.id’))
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 13 / 18
Object mapper and relational pattern
Many to One
class Parent(Base):
__tablename__ = ’parent’
id = Column(Integer, primary_key=True)
child_id = Column(Integer, ForeignKey(’child.id’))
child = relationship("Child")
class Child(Base):
__tablename__ = ’child’
id = Column(Integer, primary_key=True)
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 14 / 18
Object mapper and relational pattern
One to One
class Parent(Base):
__tablename__ = ’parent’
id = Column(Integer, primary_key=True)
child = relationship("Child", uselist=False,
backref="parent")
class Child(Base):
__tablename__ = ’child’
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey(’parent.id’))
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 15 / 18
Object mapper and relational pattern
Many to Many
association_table = Table(’association’, Base.metadata,
Column(’left_id’, Integer, ForeignKey(’left.id’)),
Column(’right_id’, Integer, ForeignKey(’right.id’))
)
class Parent(Base):
__tablename__ = ’left’
id = Column(Integer, primary_key=True)
children = relationship("Child",
secondary=association_table,
backref="parents")
class Child(Base):
__tablename__ = ’right’
id = Column(Integer, primary_key=True)
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 16 / 18
Bibliography
1 SQLAlchemy - Official documentation, March 28, 2014
http://docs.sqlalchemy.org
2 Armin Ronacher - SQLAlchemy and You, July 19, 2011
http://lucumr.pocoo.org/2011/7/19/sqlachemy-and-you/
3 Alexander Solovyov, April 23, 2011
http://solovyov.net/en/2011/basic-sqlalchemy/
4 Alexander Solovyov, May 14, 2012
https://github.com/piranha/slides/blob/gh-pages/sqla-talk/sqla.md
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 17 / 18
Thanks & Contact info
Questions?
More information or social links about me:
http://bsdchile.cl
Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 18 / 18

More Related Content

Similar to Python BCN Introduction to SQLAlchemy

070517 Jena
070517 Jena070517 Jena
070517 Jenayuhana
 
Oop in-php
Oop in-phpOop in-php
Oop in-phpRajesh S
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
umesh patil
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4
AtakanAral
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)Oleg Zinchenko
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
flapiello
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Living in the Matrix with Bytecode Manipulation
Living in the Matrix with Bytecode ManipulationLiving in the Matrix with Bytecode Manipulation
Living in the Matrix with Bytecode Manipulation
C4Media
 
PHP 8: What's New and Changed
PHP 8: What's New and ChangedPHP 8: What's New and Changed
PHP 8: What's New and Changed
Ayesh Karunaratne
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
Nyros Technologies
 
NHibernate - SQLBits IV
NHibernate - SQLBits IVNHibernate - SQLBits IV
NHibernate - SQLBits IV
Ben Hall
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
Let ColdFusion ORM do the work for you!
Let ColdFusion ORM do the work for you!Let ColdFusion ORM do the work for you!
Let ColdFusion ORM do the work for you!
Masha Edelen
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
Jena University Talk 2016.03.09 -- SQL at Zalando Technology
Jena University Talk 2016.03.09 -- SQL at Zalando TechnologyJena University Talk 2016.03.09 -- SQL at Zalando Technology
Jena University Talk 2016.03.09 -- SQL at Zalando Technology
Valentine Gogichashvili
 
Model Inheritance
Model InheritanceModel Inheritance
Model Inheritance
Loren Davie
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Tony Frame
 

Similar to Python BCN Introduction to SQLAlchemy (20)

070517 Jena
070517 Jena070517 Jena
070517 Jena
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
 
php
phpphp
php
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Living in the Matrix with Bytecode Manipulation
Living in the Matrix with Bytecode ManipulationLiving in the Matrix with Bytecode Manipulation
Living in the Matrix with Bytecode Manipulation
 
PHP 8: What's New and Changed
PHP 8: What's New and ChangedPHP 8: What's New and Changed
PHP 8: What's New and Changed
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
NHibernate - SQLBits IV
NHibernate - SQLBits IVNHibernate - SQLBits IV
NHibernate - SQLBits IV
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Let ColdFusion ORM do the work for you!
Let ColdFusion ORM do the work for you!Let ColdFusion ORM do the work for you!
Let ColdFusion ORM do the work for you!
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Jena University Talk 2016.03.09 -- SQL at Zalando Technology
Jena University Talk 2016.03.09 -- SQL at Zalando TechnologyJena University Talk 2016.03.09 -- SQL at Zalando Technology
Jena University Talk 2016.03.09 -- SQL at Zalando Technology
 
Model Inheritance
Model InheritanceModel Inheritance
Model Inheritance
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
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
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
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
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
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
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
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
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 

Python BCN Introduction to SQLAlchemy

  • 1. Introduction to python ORM SQLAlchemy Jorge A. Medina Oliva - Barcelona http://pybcn.org May. 22 , 2014 Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 1 / 18
  • 2. What is an ORM? An ORM is the software artefact who maps from relational data base tables to object/class This means: maps the tables and columns in a relational database directly to the object instance and wraps all SQL/DDL functionality in his methods. Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 2 / 18
  • 3. SQLAlchemy it’s equivalent to... Hiberante in java (main ideas become from here) Doctrine in PHP DataMapper in ruby (this is more close to Active Record pattern) NHibernate in .Net C# django ORM in python Web framework Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 3 / 18
  • 4. differences with django orm There are two very important differences between SQLAlchemy and Django. SQLAlchemy is a deeply layered system, whereas Django’s ORM is basically just one layer which is the ORM you see. 1 In SQLAlchemy you have at the very bottom the engine: Connection pools and basic API differences between different databases On top of that: the SQL abstraction language, On top of SQL abstraction: the table definitions with the basic ORM And on top of ORM you have the declarative ORM which looks very close to the Django ORM. 2 The other more striking difference however is that SQLAlchemy follows the “Unit of Work” pattern whereas Django’s ORM follows something that is very close to the “Active Record” pattern. Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 4 / 18
  • 5. SQLAlchemy Advantages Great documentation at http://www.sqlalchemy.org Independent framework active and stable development Strong design since beginning Layered components like Connection pool, ORM, API, SQL, Aggregates, etc. We can use any independent component Implement advanced Hibernate’s ideas. SQLAlchemy doesn’t override all your columns when you just changed one on update. differed column load Connection pooling Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 5 / 18
  • 6. SQLAlchemy Disadvantages Documentation overwhelming Confuses at the beginning because exist different programming options. only integrates in Flask-SQLAlchemy web framework Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 6 / 18
  • 7. Supported Platforms SQLAlchemy has been tested against the following platforms: cPython since version 2.6, through the 2.xx series cPython version 3, throughout all 3.xx series Pypy 2.1 or greater Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 7 / 18
  • 8. Installation With pip pip install SQLAlchemy Or with easy install easy install SQLAlchemy All other methods are supported too... Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 8 / 18
  • 9. Arquitecture of SQLAlchemy Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 9 / 18
  • 10. The basics to starts """ SQLAlchemy engine factory """ from sqlalchemy import create_engine """ ORM Datatypes """ from sqlalchemy import Column, ForeignKey, Integer, String """ ORM Session factory """ from sqlalchemy.orm import sessionmaker """ ORM relationship mapper """ from sqlalchemy.orm relationship """ Declarative Base Object """ from sqlalchemy.ext.declarative import declarative_base """ SQL expresions functions wrappers """ from sqlalchemy.sql import func Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 10 / 18
  • 11. Basic Use case engine = create_engine(’sqlite:///demo.db’, echo=False) session = sessionmaker(bind=engine)() Base.metadata.create_all(engine, checkfirst=True) p = Parent(’prueba’) session.add(p) session.commit() Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 11 / 18
  • 12. Basic Use case q = session.query(Parent).all() for x in q: c = Child("child", x.id) session.add(c) session.commit() session.refresh(p) for x in q: print("{}+n |".format(x.name)) for i in x.children: print(" +-->{}".format(i.name)) Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 12 / 18
  • 13. Object mapper and relational pattern One to Many Base = declarative_base() class Parent(Base): __tablename__ = ’parent’ id = Column(Integer, primary_key=True) children = relationship("Child", backref="parent") class Child(Base): __tablename__ = ’child’ id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey(’parent.id’)) Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 13 / 18
  • 14. Object mapper and relational pattern Many to One class Parent(Base): __tablename__ = ’parent’ id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey(’child.id’)) child = relationship("Child") class Child(Base): __tablename__ = ’child’ id = Column(Integer, primary_key=True) Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 14 / 18
  • 15. Object mapper and relational pattern One to One class Parent(Base): __tablename__ = ’parent’ id = Column(Integer, primary_key=True) child = relationship("Child", uselist=False, backref="parent") class Child(Base): __tablename__ = ’child’ id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey(’parent.id’)) Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 15 / 18
  • 16. Object mapper and relational pattern Many to Many association_table = Table(’association’, Base.metadata, Column(’left_id’, Integer, ForeignKey(’left.id’)), Column(’right_id’, Integer, ForeignKey(’right.id’)) ) class Parent(Base): __tablename__ = ’left’ id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table, backref="parents") class Child(Base): __tablename__ = ’right’ id = Column(Integer, primary_key=True) Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 16 / 18
  • 17. Bibliography 1 SQLAlchemy - Official documentation, March 28, 2014 http://docs.sqlalchemy.org 2 Armin Ronacher - SQLAlchemy and You, July 19, 2011 http://lucumr.pocoo.org/2011/7/19/sqlachemy-and-you/ 3 Alexander Solovyov, April 23, 2011 http://solovyov.net/en/2011/basic-sqlalchemy/ 4 Alexander Solovyov, May 14, 2012 https://github.com/piranha/slides/blob/gh-pages/sqla-talk/sqla.md Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 17 / 18
  • 18. Thanks & Contact info Questions? More information or social links about me: http://bsdchile.cl Jorge A. Medina Oliva - Barcelona (http://pybcn.org)Introduction to python ORM SQLAlchemy May. 22 , 2014 18 / 18