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 (20)

從頭打造 C#、.NET 與 ASP.NET Core 開發環境
從頭打造 C#、.NET 與 ASP.NET Core 開發環境從頭打造 C#、.NET 與 ASP.NET Core 開發環境
從頭打造 C#、.NET 與 ASP.NET Core 開發環境
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Java swing
Java swingJava swing
Java swing
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Json
JsonJson
Json
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switching
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 

Similar to An introduction to SQLAlchemy

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integrationwebhostingguy
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integrationPeter Gfader
 
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 IndicesKellyn Pot'Vin-Gorman
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guidelineSidney Chen
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfEric Xiao
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012Eduardo Castro
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancementsinfusiondev
 
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...Alex Zaballa
 
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, 2020Geir Høydalsvik
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 

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
 
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
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 

Recently uploaded

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 

Recently uploaded (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 

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.