SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
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

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

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