Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created February 4, 2018 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kracekumar/e0748ea01994cef75b3c686191fb3836 to your computer and use it in GitHub Desktop.
Save kracekumar/e0748ea01994cef75b3c686191fb3836 to your computer and use it in GitHub Desktop.
SA ORM
annotation=> explain (analyze, timing off) select label, value from data limit 10000;
QUERY PLAN
------------------------------------------------------------------------------------------------
Limit (cost=0.00..322.22 rows=10000 width=8) (actual rows=10000 loops=1)
-> Seq Scan on data (cost=0.00..33860.40 rows=1050840 width=8) (actual rows=10000 loops=1)
Total runtime: 5.994 ms
(3 rows)
Time: 6.801 ms
import psycopg2
def pscopg2_select(limit=20):
conn = psycopg2.connect("dbname=db user=user password=password host=localhost")
cur = conn.cursor()
try:
# Note: In prod, escape SQL queries.
stmt = f"select value, label from data limit {limit}"
cur.execute(stmt)
return cur.fetchall()
finally:
cur.close()
conn.close()
def sa_orm(limit=20):
sess = create_session()
try:
return sess.query(Data.value, Data.label).limit(limit).all()
finally:
sess.close()
class Data(Base):
__tablename__ = 'data'
id = Column(Integer, primary_key=True)
value = Column(Integer)
# 0 => Training, 1 => test
label = Column(Integer, default=0, index=True)
x = Column(postgresql.ARRAY(Integer))
y = Column(postgresql.ARRAY(Integer))
def sa_select(limit=20):
tbl = Data.__table__
sess = create_session()
try:
stmt = select([tbl.c.value, tbl.c.label]).limit(limit)
return sess.execute(stmt).fetchall()
finally:
sess.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment