An introduction to SQLAlchemy


Published on

An introduction to SQLAlchemy for Python Istanbul user group.

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
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,]) select([ct.c.code.label('c')])
    20. 20. SQLAlchemy Core Select select([ct]).where(ct.c.region == 'Europe & Central Asia') select([ct]).where(or_( ike('%europe%', ct.c.region.ilike('%asia%')))
    21. 21. SQLAlchemy Core Select A Little Bit Fancy select([func.count('co unt'), ct.c.region]).group_by(ct.c.region).o rder_by('count DESC') SELECT count( AS count, countries.region FROM countries GROUP BY countries.region ORDER BY count DESC
    22. 22. SQLAlchemy Core Update ct.update().where( == 1).values(name='Turkey', code='TUR')
    23. 23. SQLAlchemy Core Cooler Update case_list = [( == 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 ( = :id_1) THEN :param_1 WHEN ( = :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([,]).select_from(ct.join(dt)). where(ct.c.code == 'TRY')
    26. 26. SQLAlchemy Core Joins select([,]).select_from(join(ct, dt, == 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.code)]) SELECT concat_ws(%(concat_ws_2)s,, 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( .one() Session.query(,
    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? #sqlalchemy
    1. A particular slide catching your eye?

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