Created
February 8, 2016 20:19
-
-
Save binarymatt/5c327dd1428c32395c64 to your computer and use it in GitHub Desktop.
records.py in sqlalchemy
This file contains hidden or 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 tablib | |
from sqlalchemy import create_engine | |
from sqlalchemy.sql import text | |
class ResultSet(object): | |
def __init__(self, result_proxy): | |
self._rp = result_proxy | |
self.colum_names = self._rp.keys() | |
self._all_rows = [] | |
self._completed = False | |
def next(self): | |
result = self._rp.fetchone() | |
if result: | |
return result | |
raise StopIteration("ResultSet contains no more rows.") | |
def __iter__(self): | |
if self._completed: | |
for row in self._all_rows: | |
yield row | |
for row in self._rp: | |
self._all_rows.append(row) | |
yield row | |
self._completed = True | |
def all(self): | |
if not self._all_rows: | |
self._all_rows = list(self._rp) | |
return self._all_rows | |
@property | |
def dataset(self): | |
data = tablib.Dataset() | |
data.headers = self.colum_names | |
for row in self.all(): | |
row = _reduce_datetimes(row) | |
data.append(row) | |
return data | |
class Database(object): | |
def __init__(self, dsn): | |
self.engine = create_engine(dsn) | |
def query(self, query_string, params={}, fetchall=False): | |
query = text(query_string) | |
result_proxy = self.engine.execute(query, **params) | |
return ResultSet(result_proxy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment