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

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Recently uploaded (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

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