53
INTRODUCTION TO SQLALCHEMY ORM Created by / Jason A Myers @jasonamyers

Introduction to SQLAlchemy ORM

Embed Size (px)

Citation preview

INTRODUCTION TOSQLALCHEMY ORM

Created by / Jason A Myers @jasonamyers

WARNING!

SQLALCHEMY

Core - Schema centric

ORM - User Model

INSTALLINGpip install sqlalchemy

CONNECTING AND ESTABLISHING ASESSION

CONNECTING

from sqlalchemy import create_engine

engine = create_engine('sqlite:///:memory:')

ESTABLISHING A SESSIONfrom sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine)

session = Session()

DEFINING MODELS

MODEL BASE

Declarative Base

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

COOKIE MODEL

from sqlalchemy import Column, Integer, Numeric, String

class Cookie(Base): __tablename__ = 'cookies'

cookie_id = Column(Integer, primary_key=True) cookie_name = Column(String(50), index=True) cookie_recipe_url = Column(String(255)) cookie_sku = Column(String(55)) quantity = Column(Integer()) unit_cost = Column(Numeric(12, 2))

PERSISTING OUR TABLE

Base.metadata.create_all(engine)

INSERTING DATA

ADDING A COOKIE

cc_cookie = Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50)

ADDING TO SESSION

session.add(cc_cookie)session.commit()

ACCESSING ATTRIBUTESprint(cc_cookie.cookie_id)

1

BULK INSERTSc1 = Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25)c2 = Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00)session.bulk_save_objects([c1,c2])session.commit()

BULK INSERT DIFFERENCESc1.cookie_id

QUERIES

ALL THE COOKIES!cookies = session.query(Cookie).all()print(cookies)

[Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50), Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25), Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00)]

ALL THE COOKIES! - ITERATORfor cookie in session.query(Cookie): print(cookie)

Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50)Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25)Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00)

PARTICULAR ATTRIBUTESprint(session.query(Cookie.cookie_name, Cookie.quantity).first())

('chocolate chip', 12)

ORDER BY

for cookie in session.query(Cookie).order_by(Cookie.quantity): print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))

12 - chocolate chip 24 - peanut butter 100 - oatmeal raisin

DECENDINGfrom sqlalchemy import descfor cookie in session.query(Cookie).order_by(desc(Cookie.quantity)): print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))

LIMITINGquery = session.query(Cookie).order_by(Cookie.quantity).limit(2)print([result.cookie_name for result in query])

['chocolate chip', 'peanut butter']

DATABASE FUNCTIONS

from sqlalchemy import func

inv_count = session.query(func.sum(Cookie.quantity)).scalar()print(inv_count)

136

DATABASE FUNCTIONS COUNT

rec_count = session.query(func.count(Cookie.cookie_name)).first()print(rec_count)

(3, 0)

LABELINGrec_count = session.query(func.count(Cookie.cookie_name) \ .label('inventory_count')).first()print(rec_count.keys())print(rec_count.inventory_count)

['inventory_count']5

FILTER_BYrecord = session.query(Cookie). \ filter_by(cookie_name='chocolate chip').first()print(record)

Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50)

FILTERrecord = session.query(Cookie). \ filter(Cookie.cookie_name == 'chocolate chip').first()print(record)

CLAUSEELEMENTSquery = session.query(Cookie).filter( Cookie.cookie_name.like('%chocolate%'))for record in query: print(record.cookie_name)

chocolate chip

CLAUSEELEMENT METHODS

between(cleft, cright) - Find where the column is between

cleft and cright

distinct() - Find only unique values for column

in_([list]) - Find where the column is in the list

is_(None) - Find where the column is None (commonly

used for Null checks with None)

contains('string') - Find where the column has 'string' in it

(Case-sensitive)

endswith('string') - Find where the column ends with

'string' (Case-sensitive)

startswith('string') - Find where the column begins with

'string' (Case-sensitive)

ilike('string') - Find where the column is like 'string' (NOT

Case-sensitive)

OPERATORS

from sqlalchemy import castquery = session.query(Cookie.cookie_name, cast((Cookie.quantity * Cookie.unit_cost), Numeric(12,2)).label('inv_cost'))for result in query: print('{} - {}'.format(result.cookie_name, result.inv_cost))

chocolate chip - 6.00peanut butter - 6.00oatmeal raisin - 100.00

CONJUNCTIONS

from sqlalchemy import and_, or_, not_query = session.query(Cookie).filter( or_( Cookie.quantity.between(10, 50), Cookie.cookie_name.contains('chip') ))for result in query: print(result.cookie_name)

chocolate chippeanut butter

UPDATING COOKIES

UPDATING COOKIES

query = session.query(Cookie)cc_cookie = query.filter(Cookie.cookie_name == "chocolate chip").first()

cc_cookie.quantity = cc_cookie.quantity + 120

session.commit()print(cc_cookie.quantity)

132

DELETING COOKIES

DELETING COOKIES

query = session.query(Cookie)query = query.filter(Cookie.cookie_name == "peanut butter")

dcc_cookie = query.one()session.delete(dcc_cookie)session.commit()

dcc_cookie = query.first()print(dcc_cookie)

None

OKAY TIME FOR A BREATHER

RELATIONSHIPS

IMPORTS

from datetime import datetimefrom sqlalchemy import DateTime, ForeignKey, Booleanfrom sqlalchemy.orm import relationship, backref

USER MODEL

class User(Base): __tablename__ = 'users'

user_id = Column(Integer(), primary_key=True) username = Column(String(15), nullable=False, unique=True) email_address = Column(String(255), nullable=False) phone = Column(String(20), nullable=False) password = Column(String(25), nullable=False) created_on = Column(DateTime(), default=datetime.now) updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)

ORDER MODEL

class Order(Base):

__tablename__ = 'orders'

order_id = Column(Integer(), primary_key=True)

user_id = Column(Integer(), ForeignKey('users.user_id'))

shipped = Column(Boolean(), default=False)

user = relationship("User", backref=backref('orders', order_by=order_id))

LINEITEM MODEL

class LineItem(Base):

__tablename__ = 'line_items'

line_item_id = Column(Integer(), primary_key=True)

order_id = Column(Integer(), ForeignKey('orders.order_id'))

cookie_id = Column(Integer(), ForeignKey('cookies.cookie_id'))

quantity = Column(Integer())

extended_cost = Column(Numeric(12, 2))

order = relationship("Order", backref=backref('line_items', order_by=line_item_id))

cookie = relationship("Cookie", uselist=False)

PERSIST THEM

Base.metadata.create_all(engine)

DEFINING A USERcookiemon = User(username='cookiemon', email_address='[email protected]', phone='111-111-1111', password='password')

session.add(cookiemon)

session.commit()

SETTING UP AN ORDER

o1 = Order()

o1.user = cookiemon

session.add(o1)

PREPARING LINE ITEMScc = session.query(Cookie).filter(Cookie.cookie_name == "chocolate chip").one()line1 = LineItem(cookie=cc, quantity=2, extended_cost=1.00)

pb = session.query(Cookie).filter(Cookie.cookie_name == "oatmeal raisin").one()line2 = LineItem(quantity=12, extended_cost=3.00)line2.cookie = pb

ASSOCIATE ORDER AND LINE ITEMS

o1.line_items.append(line1)o1.line_items.append(line2)

session.commit()

USING RELATIONSHIPS IN QUERIESquery = session.query(Order.order_id, User.username, User.phone,

Cookie.cookie_name, LineItem.quantity,

LineItem.extended_cost)

query = query.join(User).join(LineItem).join(Cookie)

results = query.filter(User.username == 'cookiemon').all()

print(results)

[(1, 'cookiemon', '111-111-1111', 'chocolate chip', 2, Decimal('1.00')),

(1, 'cookiemon', '111-111-1111', 'oatmeal raisin', 12, Decimal('3.00'

ANOTHER EXAMPLEquery = session.query(User.username, func.count(Order.order_id))

query = query.outerjoin(Order).group_by(User.username)

for row in query:

print(row)

('cookiemon', 1)

WHAT OTHER THINGS ARE OUTTHERE?

AutomapGeospatial Queries

QUESTIONS

Jason Myers / @jasonamyers / Essential SQLAlchemy