Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
The Ultimate Python Database Toolkit: SQLAlchem...
Search
Kod.io Linz
March 01, 2014
Programming
1
250
The Ultimate Python Database Toolkit: SQLAlchemy - Muhammet Sena Aydın
Kod.io Linz
March 01, 2014
Tweet
Share
More Decks by Kod.io Linz
See All by Kod.io Linz
Kod.io Linz closing notes - Floor Drees
kodio_linz
0
170
Make yours and other people's life easier! Do support! - Mike Adolphs
kodio_linz
0
94
Objective-C for Rubyists - Mikael Konutgan
kodio_linz
0
140
How to become a better developer - Markus Prinz
kodio_linz
1
120
10 things I didn’t know about HTML, CSS, and JavaScript - Mathias Bynens
kodio_linz
5
320
Docker; The Shipping - Andreas Tiefenthaler
kodio_linz
1
120
How to Get More Women in Tech in 5 Steps - Anika Lindtner
kodio_linz
0
600
RubyMotion’s Secret Sauce - Joshua Ballenco
kodio_linz
0
250
Fly, you tools - Piotr Szotkowski
kodio_linz
1
240
Other Decks in Programming
See All in Programming
AWS Organizations で実現する、 マルチ AWS アカウントのルートユーザー管理からの脱却
atpons
0
150
color-scheme: light dark; を完全に理解する
uhyo
3
210
ペアーズでの、Langfuseを中心とした評価ドリブンなリリースサイクルのご紹介
fukubaka0825
2
320
SwiftUIで単方向アーキテクチャを導入して得られた成果
takuyaosawa
0
270
Grafana Cloudとソラカメ
devoc
0
170
『GO』アプリ バックエンドサーバのコスト削減
mot_techtalk
0
140
『品質』という言葉が嫌いな理由
korimu
0
160
CloudNativePGがCNCF Sandboxプロジェクトになったぞ! 〜CloudNativePGの仕組みの紹介〜
nnaka2992
0
230
Lottieアニメーションをカスタマイズしてみた
tahia910
0
130
GAEログのコスト削減
mot_techtalk
0
120
ASP. NET CoreにおけるWebAPIの最新情報
tomokusaba
0
370
一休.com のログイン体験を支える技術 〜Web Components x Vue.js 活用事例と最適化について〜
atsumim
0
420
Featured
See All Featured
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
4
320
Why Our Code Smells
bkeepers
PRO
336
57k
Into the Great Unknown - MozCon
thekraken
35
1.6k
Bash Introduction
62gerente
611
210k
What's in a price? How to price your products and services
michaelherold
244
12k
Agile that works and the tools we love
rasmusluckow
328
21k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
10
1.3k
Unsuck your backbone
ammeep
669
57k
The Pragmatic Product Professional
lauravandoore
32
6.4k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
27
1.6k
The World Runs on Bad Software
bkeepers
PRO
67
11k
It's Worth the Effort
3n
184
28k
Transcript
SQLAlchemy SQLAlchemy The Python SQL Toolkit and Object Relational Mapper
SQLAlchemy SQLAlchemy Muhammet S. AYDIN Python Developer @ Metglobal @mengukagan
SQLAlchemy SQLAlchemy • No ORM Required • Mature • High
Performing • Non-opinionated • Unit of Work • Function based query construction • Modular
SQLAlchemy SQLAlchemy • Seperation of mapping & classes • Eager
loading & caching related objects • Inheritance mapping • Raw SQL
SQLAlchemy SQLAlchemy Drivers: PostgreSQL MySQL MSSQL SQLite Sybase Drizzle Firebird
Oracle
SQLAlchemy SQLAlchemy Core Engine Connection Dialect MetaData Table Column
SQLAlchemy SQLAlchemy Core Engine Starting point for SQLAlchemy app. Home
base for the database and it's API.
SQLAlchemy SQLAlchemy Core Connection Provides functionality for a wrapped DB-API
connection. Executes SQL statements. Not thread-safe.
SQLAlchemy SQLAlchemy Core Dialect Defnes the behavior of a specifc
database and DB-API combination. Query generation, execution, result handling, anything that differs from other dbs is handled in Dialect.
SQLAlchemy SQLAlchemy Core MetaData Binds to an Engine or Connection.
Holds the Table and Column metadata in itself.
SQLAlchemy SQLAlchemy Core Table Represents a table in the database.
Stored in the MetaData.
SQLAlchemy SQLAlchemy Core Column Represents a column in a database
table.
SQLAlchemy SQLAlchemy Core Creating an engine:
SQLAlchemy SQLAlchemy Core Creating tables Register the Table with MetaData.
Defne your columns. Call metadata.create_all(engine) or table.create(engine)
SQLAlchemy SQLAlchemy Core Creating tables
SQLAlchemy 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 SQLAlchemy Core Column Types Integer, BigInteger, String, Unicode, UnicodeText,
Date, DateTime, Boolean, Text, Time and All of the SQL std types.
SQLAlchemy SQLAlchemy Core Insert insert = countries_table.insert().values( code='TR', name='Turkey') conn.execute(insert)
SQLAlchemy SQLAlchemy Core Select select([countries_table]) select([ct.c.code, ct.c.name]) select([ct.c.code.label('c')])
SQLAlchemy SQLAlchemy Core Select select([ct]).where(ct.c.region == 'Europe & Central Asia')
select([ct]).where(or_(ct.c.region.ilike('%euro pe%', ct.c.region.ilike('%asia%')))
SQLAlchemy SQLAlchemy Core Select A Little Bit Fancy select([func.count(ct.c.id).label('count'), ct.c.region]).group_by(ct.c.region).order_by('
count DESC') SELECT count(countries.id) AS count, countries.region FROM countries GROUP BY countries.region ORDER BY count DESC
SQLAlchemy SQLAlchemy Core Update ct.update().where(ct.c.id == 1).values(name='Turkey', code='TUR')
SQLAlchemy 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_list)) UPDATE photos SET photo_order=CASE WHEN (photos.id = :id_1) THEN :param_1 WHEN (photos.id = :id_2) THEN :param_2 END
SQLAlchemy SQLAlchemy Core Delete ct.delete().where(ct.c.id_in([60,71,80,97]))
SQLAlchemy SQLAlchemy Core Joins select([ct.c.name, dt.c.data]).select_from(ct.join(dt)).where(ct.c .code == 'TRY')
SQLAlchemy 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 SQLAlchemy Core Func A SQL function generator with attribute
access. simply put: func.count() becomes COUNT().
SQLAlchemy 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 SQLAlchemy ORM - Built on top of the core
- Applied usage of the Expression Language - Class declaration - Table defnition is nested in the class
SQLAlchemy SQLAlchemy ORM Defnition
SQLAlchemy 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 SQLAlchemy ORM Master / Slave Connection? master_session = sessionmaker(bind=engine1)
slave_session = sessionmaker(bind=engine2) Session = master_session() SlaveSession = slave_session()
SQLAlchemy SQLAlchemy ORM Querying Session.query(Country).flter(Country.name.s tartswith('Tur')).all() Session.query(func.count(Country.id)).one() Session.query(Country.name, Data.data).join(Data).all()
SQLAlchemy SQLAlchemy ORM Querying Session.query(Country).flter_by(id=1).updat e({“name”: “USA”}) Session.query(Country).flter(~Country.regio n.in_('Europe &
Central Asia')).delete()
SQLAlchemy SQLAlchemy ORM Relationships: One To Many
SQLAlchemy SQLAlchemy ORM Relationships: One To One
SQLAlchemy SQLAlchemy ORM Relationships: Many To Many
SQLAlchemy SQLAlchemy ORM Relationships: Many To Many
SQLAlchemy SQLAlchemy ORM Relationship Loading
SQLAlchemy SQLAlchemy ORM Relationship Loading
SQLAlchemy SQLAlchemy ORM More? http://sqlalchemy.org http://github.com/zzzeek/sqlalchemy irc.freenode.net #sqlalchemy