SQLAlchemy

SQLAlchemy is an open-source SQL toolkit and object-relational mapper (ORM) for the Python programming language released under the MIT License.[5]

SQLAlchemy
Original author(s)Michael Bayer[1][2]
Initial releaseFebruary 14, 2006 (2006-02-14)[3]
Stable release
1.3.20 / October 12, 2020 (2020-10-12)[4]
Repository
Written inPython
Operating systemCross-platform
TypeObject-relational mapping
LicenseMIT License[5]
Websitewww.sqlalchemy.org 
Mike Bayer talking about SQLAlchemy at PyCon 2012

Description

SQLAlchemy's philosophy is that relational databases behave less like object collections as the scale gets larger and performance starts being a concern, while object collections behave less like tables and rows as more abstraction is designed into them. For this reason it has adopted the data mapper pattern (similar to Hibernate for Java) rather than the active record pattern used by a number of other object-relational mappers.[6] However, optional plugins allow users to develop using declarative syntax.[7]

History

SQLAlchemy was first released in February 2006[8][3] and has quickly become one of the most widely used object-relational mapping tools in the Python community, alongside Django's ORM.

Example

The following example represents an n-to-1 relationship between movies and their directors. It is shown how user-defined Python classes create corresponding database tables, how instances with relationships are created from either side of the relationship, and finally how the data can be queried—illustrating automatically generated SQL queries for both lazy and eager loading.

Schema definition

Creating two Python classes and according database tables in the DBMS:

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, sessionmaker

Base = declarative_base()

class Movie(Base):
    __tablename__ = "movies"

    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    year = Column(Integer)
    directed_by = Column(Integer, ForeignKey("directors.id"))

    director = relation("Director", backref="movies", lazy=False)

    def __init__(self, title=None, year=None):
        self.title = title
        self.year = year

    def __repr__(self):
        return "Movie(%r, %r, %r)" % (self.title, self.year, self.director)

class Director(Base):
    __tablename__ = "directors"

    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False, unique=True)

    def __init__(self, name=None):
        self.name = name

    def __repr__(self):
        return "Director(%r)" % (self.name)

engine = create_engine("dbms://user:pwd@host/dbname")
Base.metadata.create_all(engine)

Data insertion

One can insert a director-movie relationship via either entity:

Session = sessionmaker(bind=engine)
session = Session()

m1 = Movie("Robocop", 1987)
m1.director = Director("Paul Verhoeven")

d2 = Director("George Lucas")
d2.movies = [Movie("Star Wars", 1977), Movie("THX 1138", 1971)]

try:
    session.add(m1)
    session.add(d2)
    session.commit()
except:
    session.rollback()

Querying

alldata = session.query(Movie).all()
for somedata in alldata:
    print(somedata)

SQLAlchemy issues the following query to the DBMS (omitting aliases):

SELECT movies.id, movies.title, movies.year, movies.directed_by, directors.id, directors.name
FROM movies LEFT OUTER JOIN directors ON directors.id = movies.directed_by

The output:

Movie('Robocop', 1987L, Director('Paul Verhoeven'))
Movie('Star Wars', 1977L, Director('George Lucas'))
Movie('THX 1138', 1971L, Director('George Lucas'))

Setting lazy=True (default) instead, SQLAlchemy would first issue a query to get the list of movies and only when needed (lazy) for each director a query to get the name of the according director:

SELECT movies.id, movies.title, movies.year, movies.directed_by
FROM movies

SELECT directors.id, directors.name
FROM directors
WHERE directors.id = %s

See also

References

Notes
  • Gift, Noah (12 Aug 2008). "Using SQLAlchemy". Developerworks. IBM. Retrieved 8 Feb 2011.
  • Rick Copeland, Essential SQLAlchemy, O'Reilly, 2008, ISBN 0-596-51614-2
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.