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...
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-saf...
SQLAlchemy
Core
Dialect
Defines the behavior of a specific
database and DB-API combination.
Query generation, execution, r...
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...
SQLAlchemy
Core
Creating tables
SQLAlchemy
Core

More on Columns
Columns have some important
parameters.
index=bool, nullable=bool,
unique=bool, primary_k...
SQLAlchemy
Core
Column Types
Integer, BigInteger, String, Unicode,
UnicodeText, Date, DateTime, Boolean,
Text, Time
and
Al...
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
ik...
SQLAlchemy
Core
Select A Little Bit Fancy
select([func.count(ct.c.id).label('co
unt'),
ct.c.region]).group_by(ct.c.region)...
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...
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...
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.na...
SQLAlchemy
ORM
- Built on top of the core
- Applied usage of the Expression
Language
- Class declaration
- Table definitio...
SQLAlchemy
ORM
Definition
SQLAlchemy
ORM
Session
Basically it establishes all
connections to the db.
All objects are kept on it through
their lifesp...
SQLAlchemy
ORM
Master / Slave Connection?
master_session =
sessionmaker(bind=engine1)
slave_session =
sessionmaker(bind=en...
SQLAlchemy
ORM
Querying
Session.query(Country).filter(Country
.name.startswith('Tur')).all()
Session.query(func.count(Coun...
SQLAlchemy
ORM
Querying
Session.query(Country).filter_by(id=1
).update({“name”: “USA”})
Session.query(Country).filter(~Cou...
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
Upcoming SlideShare
Loading in...5
×

An introduction to SQLAlchemy

1,403

Published on

An introduction to SQLAlchemy for Python Istanbul user group.

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,403
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
32
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide
  • 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()
  • SQLAlchemy core consists of 6 classes
  • We define columns as arguments to Table object
  • Conn is retrieved from engine.connect()
  • Case – when statement is a way of saying
    When the condition is met, use this value to update the column.
  • An introduction to SQLAlchemy

    1. 1. SQLAlchemy The Python SQL Toolkit and Object Relational Mapper
    2. 2. SQLAlchemy Muhammet S. AYDIN Python Developer @ Metglobal @mengukagan
    3. 3. SQLAlchemy No ORM Required ● Mature ● High Performing ● Non-opinionated ● Unit of Work ● Function based query construction ● Modular ●
    4. 4. SQLAlchemy Seperation of mapping & classes ● Eager loading & caching related objects ● Inheritance mapping ● Raw SQL ●
    5. 5. SQLAlchemy Drivers: PostgreSQL MySQL MSSQL SQLite Sybase Drizzle Firebird Oracle
    6. 6. SQLAlchemy Core Engine Connection Dialect MetaData Table Column
    7. 7. SQLAlchemy Core Engine Starting point for SQLAlchemy app. Home base for the database and it's API.
    8. 8. SQLAlchemy Core Connection Provides functionality for a wrapped DB-API connection. Executes SQL statements. Not thread-safe.
    9. 9. 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.
    10. 10. SQLAlchemy Core MetaData Binds to an Engine or Connection. Holds the Table and Column metadata in itself.
    11. 11. SQLAlchemy Core Table Represents a table in the database. Stored in the MetaData.
    12. 12. SQLAlchemy Core Column Represents a column in a database table.
    13. 13. SQLAlchemy Core Creating an engine:
    14. 14. SQLAlchemy Core Creating tables Register the Table with MetaData. Define your columns. Call metadata.create_all(engine) or table.create(engine)
    15. 15. SQLAlchemy Core Creating tables
    16. 16. 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
    17. 17. SQLAlchemy Core Column Types Integer, BigInteger, String, Unicode, UnicodeText, Date, DateTime, Boolean, Text, Time and All of the SQL std types.
    18. 18. SQLAlchemy Core Insert insert = countries_table.insert().values( code='TR', name='Turkey') conn.execute(insert)
    19. 19. SQLAlchemy Core Select select([countries_table]) select([ct.c.code, ct.c.name]) select([ct.c.code.label('c')])
    20. 20. 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%')))
    21. 21. 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
    22. 22. SQLAlchemy Core Update ct.update().where(ct.c.id == 1).values(name='Turkey', code='TUR')
    23. 23. 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
    24. 24. SQLAlchemy Core Delete ct.delete().where(ct.c.id_in([60,71,8 0,97]))
    25. 25. SQLAlchemy Core Joins select([ct.c.name, dt.c.data]).select_from(ct.join(dt)). where(ct.c.code == 'TRY')
    26. 26. 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')
    27. 27. SQLAlchemy Core Func A SQL function generator with attribute access. simply put: func.count() becomes COUNT().
    28. 28. 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
    29. 29. SQLAlchemy ORM - Built on top of the core - Applied usage of the Expression Language - Class declaration - Table definition is nested in the class
    30. 30. SQLAlchemy ORM Definition
    31. 31. SQLAlchemy ORM Session Basically it establishes all connections to the db. All objects are kept on it through their lifespan. Entry point for Query.
    32. 32. SQLAlchemy ORM Master / Slave Connection? master_session = sessionmaker(bind=engine1) slave_session = sessionmaker(bind=engine2) Session = master_session() SlaveSession = slave_session()
    33. 33. 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()
    34. 34. 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()
    35. 35. SQLAlchemy ORM Relationships: One To Many
    36. 36. SQLAlchemy ORM Relationships: One To One
    37. 37. SQLAlchemy ORM Relationships: Many To Many
    38. 38. SQLAlchemy ORM Relationships: Many To Many
    39. 39. SQLAlchemy ORM Relationship Loading
    40. 40. SQLAlchemy ORM Relationship Loading
    41. 41. SQLAlchemy ORM More? http://sqlalchemy.org http://github.com/zzzeek/sqlalchemy irc.freenode.net #sqlalchemy
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×