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
230
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
160
Make yours and other people's life easier! Do support! - Mike Adolphs
kodio_linz
0
91
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
300
Docker; The Shipping - Andreas Tiefenthaler
kodio_linz
1
120
How to Get More Women in Tech in 5 Steps - Anika Lindtner
kodio_linz
0
530
RubyMotion’s Secret Sauce - Joshua Ballenco
kodio_linz
0
230
Fly, you tools - Piotr Szotkowski
kodio_linz
1
230
Other Decks in Programming
See All in Programming
私のEbitengineの第一歩
qt_luigi
0
430
デザインシステムとコンポーネント指向によるフロントエンド開発プロセスの革新 / Innovation in Frontend Development Processes through Design Systems and Component-Oriented Architecture
nrslib
7
5.1k
Why Prism?
kddnewton
4
1.4k
ECMAScript仕様を読むのに必要な知識 - ダイジェスト版
syumai
4
2.6k
What is Parser
yui_knk
8
3.5k
LangGraphでのHuman-in-the-Loopの実装
os1ma
3
860
エラーレスポンス設計から考える、0→1開発におけるGraphQLへの向き合い方
bicstone
5
950
Swiftで高速フーリエ変換してオーディオビジュアライザーを作る / iOSDC Japan 2024 Day1 Track D
kyome22
2
490
暴走のウホーレン 〜想いってのはvimrcにしないと伝わらないんだぜ〜 / iosdc_japan_2024
uhooi
1
240
Ebitengineの1vs1ゲーム WebRTCの活用
ponyo877
0
350
The Sequel to a Dream of Ruby Parser's Grammar
ydah
1
190
iOSの隠されたAPIを解明し、開発効率を向上させる方法/iOSDC24
noppefoxwolf
2
120
Featured
See All Featured
WebSockets: Embracing the real-time Web
robhawkes
59
7.3k
Large-scale JavaScript Application Architecture
addyosmani
508
110k
A better future with KSS
kneath
235
17k
Testing 201, or: Great Expectations
jmmastey
35
6.9k
Documentation Writing (for coders)
carmenintech
65
4.3k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
663
120k
We Have a Design System, Now What?
morganepeng
48
7.1k
Building a Scalable Design System with Sketch
lauravandoore
458
32k
Design by the Numbers
sachag
277
19k
Java REST API Framework Comparison - PWX 2021
mraible
PRO
27
7.4k
The Art of Programming - Codeland 2020
erikaheidi
48
13k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
26
1.9k
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