SlideShare a Scribd company logo
1 of 18
Download to read offline
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
 
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 PecoraroChristopher Pecoraro
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4AtakanAral
 
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 frameworkflapiello
 
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 ManipulationC4Media
 
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 ChangedAyesh Karunaratne
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperNyros Technologies
 
NHibernate - SQLBits IV
NHibernate - SQLBits IVNHibernate - SQLBits IV
NHibernate - SQLBits IVBen 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 applicationsJeff 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 questionssekar 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 TechnologyValentine Gogichashvili
 
Model Inheritance
Model InheritanceModel Inheritance
Model InheritanceLoren 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

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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