Created
February 4, 2018 11:28
-
-
Save kracekumar/e0748ea01994cef75b3c686191fb3836 to your computer and use it in GitHub Desktop.
SA ORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sa_orm(limit=20): | |
sess = create_session() | |
try: | |
return sess.query(Data.value, Data.label).limit(limit).all() | |
finally: | |
sess.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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