SlideShare a Scribd company logo
1 of 41
SQLAlchemy

The Python SQL Toolkit and Object
Relational Mapper
SQLAlchemy

Muhammet S. AYDIN
Python Developer @ Metglobal
@mengukagan
SQLAlchemy
No ORM Required
● Mature
● High Performing
● Non-opinionated
● Unit of Work
● Function based query construction
● Modular
●
SQLAlchemy

Seperation of mapping & classes
● Eager loading & caching related
objects
● Inheritance mapping
● Raw SQL
●
SQLAlchemy
Drivers:
PostgreSQL
MySQL
MSSQL
SQLite
Sybase
Drizzle
Firebird
Oracle
SQLAlchemy
Core
Engine
Connection
Dialect
MetaData
Table
Column
SQLAlchemy
Core
Engine
Starting point for SQLAlchemy app.
Home base for the database and it's
API.
SQLAlchemy
Core
Connection
Provides functionality for a wrapped
DB-API connection.
Executes SQL statements.
Not thread-safe.
SQLAlchemy
Core
Dialect
Defines the behavior of a specific
database and DB-API combination.
Query generation, execution, result
handling, anything that differs from
other dbs is handled in Dialect.
SQLAlchemy
Core
MetaData
Binds to an Engine or Connection.
Holds the Table and Column metadata
in itself.
SQLAlchemy
Core
Table
Represents a table in the database.
Stored in the MetaData.
SQLAlchemy
Core
Column
Represents a column in a database
table.
SQLAlchemy
Core
Creating an engine:
SQLAlchemy
Core
Creating tables
Register the Table with MetaData.
Define your columns.
Call metadata.create_all(engine)
or
table.create(engine)
SQLAlchemy
Core
Creating tables
SQLAlchemy
Core

More on Columns
Columns have some important
parameters.
index=bool, nullable=bool,
unique=bool, primary_key=bool,
default=callable/scalar,
onupdate=callable/scalar,
autoincrement=bool
SQLAlchemy
Core
Column Types
Integer, BigInteger, String, Unicode,
UnicodeText, Date, DateTime, Boolean,
Text, Time
and
All of the SQL std types.
SQLAlchemy
Core
Insert
insert =
countries_table.insert().values(
code='TR', name='Turkey')
conn.execute(insert)
SQLAlchemy
Core
Select
select([countries_table])
select([ct.c.code, ct.c.name])
select([ct.c.code.label('c')])
SQLAlchemy
Core
Select
select([ct]).where(ct.c.region ==
'Europe & Central Asia')
select([ct]).where(or_(ct.c.region.il
ike('%europe%',
ct.c.region.ilike('%asia%')))
SQLAlchemy
Core
Select A Little Bit Fancy
select([func.count(ct.c.id).label('co
unt'),
ct.c.region]).group_by(ct.c.region).o
rder_by('count DESC')
SELECT count(countries.id) AS count,
countries.region
FROM countries GROUP BY
countries.region ORDER BY count DESC
SQLAlchemy
Core
Update
ct.update().where(ct.c.id ==
1).values(name='Turkey', code='TUR')
SQLAlchemy
Core
Cooler Update
case_list = [(pt.c.id == photo_id,
index+1) for index, photo_id in
enumerate(order_list)]
pt.update().values(photo_order=case(case_l
ist))
UPDATE photos SET photo_order=CASE WHEN
(photos.id = :id_1) THEN :param_1 WHEN
(photos.id = :id_2) THEN :param_2 END
SQLAlchemy
Core
Delete
ct.delete().where(ct.c.id_in([60,71,8
0,97]))
SQLAlchemy

Core
Joins
select([ct.c.name,
dt.c.data]).select_from(ct.join(dt)).
where(ct.c.code == 'TRY')
SQLAlchemy
Core
Joins
select([ct.c.name,
dt.c.data]).select_from(join(ct, dt,
ct.c.id ==
dt.c.country_id)).where(ct.c.code ==
'TRY')
SQLAlchemy
Core
Func
A SQL function generator with
attribute access.
simply put:
func.count() becomes COUNT().
SQLAlchemy
Core
Func
select([func.concat_ws(“ -> “,
ct.c.name, ct.c.code)])
SELECT concat_ws(%(concat_ws_2)s,
countries.name, countries.code) AS
concat_ws_1
FROM countries
SQLAlchemy
ORM
- Built on top of the core
- Applied usage of the Expression
Language
- Class declaration
- Table definition is nested in the
class
SQLAlchemy
ORM
Definition
SQLAlchemy
ORM
Session
Basically it establishes all
connections to the db.
All objects are kept on it through
their lifespan.
Entry point for Query.
SQLAlchemy
ORM
Master / Slave Connection?
master_session =
sessionmaker(bind=engine1)
slave_session =
sessionmaker(bind=engine2)
Session = master_session()
SlaveSession = slave_session()
SQLAlchemy
ORM
Querying
Session.query(Country).filter(Country
.name.startswith('Tur')).all()
Session.query(func.count(Country.id))
.one()
Session.query(Country.name,
Data.data).join(Data).all()
SQLAlchemy
ORM
Querying
Session.query(Country).filter_by(id=1
).update({“name”: “USA”})
Session.query(Country).filter(~Countr
y.region.in_('Europe & Central
Asia')).delete()
SQLAlchemy
ORM
Relationships: One To Many
SQLAlchemy
ORM
Relationships: One To One
SQLAlchemy
ORM
Relationships: Many To Many
SQLAlchemy
ORM
Relationships: Many To Many
SQLAlchemy
ORM
Relationship Loading
SQLAlchemy
ORM
Relationship Loading
SQLAlchemy
ORM
More?
http://sqlalchemy.org
http://github.com/zzzeek/sqlalchemy
irc.freenode.net #sqlalchemy

More Related Content

What's hot

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 

What's hot (20)

JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Lombok
LombokLombok
Lombok
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Clean code
Clean codeClean code
Clean code
 
Spring boot
Spring bootSpring boot
Spring boot
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 

Similar to An introduction to SQLAlchemy

SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
webhostingguy
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
webhostingguy
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
Sidney Chen
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
Geir Høydalsvik
 

Similar to An introduction to SQLAlchemy (20)

Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integration
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancements
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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 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...
 

An introduction to SQLAlchemy

Editor's Notes

  1. If you use ORM you just use classes But if you use the core, you can also map the tables to Python classess with mapper()
  2. SQLAlchemy core consists of 6 classes
  3. We define columns as arguments to Table object
  4. Conn is retrieved from engine.connect()
  5. Case – when statement is a way of saying When the condition is met, use this value to update the column.