SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
[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
 
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
 
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
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...itnewsafrica
 
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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 

Kürzlich hochgeladen (20)

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
[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
 
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
 
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...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
 
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
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 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