Changeset View
Changeset View
Standalone View
Standalone View
swh/storage/db.py
Show First 20 Lines • Show All 87 Lines • ▼ Show 20 Lines | def connect(cls, *args, **kwargs): | ||||
Args: | Args: | ||||
connstring: libpq2 connection string | connstring: libpq2 connection string | ||||
""" | """ | ||||
conn = psycopg2.connect(*args, **kwargs) | conn = psycopg2.connect(*args, **kwargs) | ||||
return cls(conn) | return cls(conn) | ||||
@classmethod | |||||
def from_pool(cls, pool): | |||||
return cls(pool.getconn(), pool=pool) | |||||
def _cursor(self, cur_arg): | def _cursor(self, cur_arg): | ||||
"""get a cursor: from cur_arg if given, or a fresh one otherwise | """get a cursor: from cur_arg if given, or a fresh one otherwise | ||||
meant to avoid boilerplate if/then/else in methods that proxy stored | meant to avoid boilerplate if/then/else in methods that proxy stored | ||||
procedures | procedures | ||||
""" | """ | ||||
if cur_arg is not None: | if cur_arg is not None: | ||||
return cur_arg | return cur_arg | ||||
# elif self.cur is not None: | # elif self.cur is not None: | ||||
# return self.cur | # return self.cur | ||||
else: | else: | ||||
return self.conn.cursor() | return self.conn.cursor() | ||||
def __init__(self, conn): | def __init__(self, conn, pool=None): | ||||
"""create a DB proxy | """create a DB proxy | ||||
Args: | Args: | ||||
conn: psycopg2 connection to the SWH DB | conn: psycopg2 connection to the SWH DB | ||||
pool: psycopg2 pool of connections | |||||
""" | """ | ||||
self.conn = conn | self.conn = conn | ||||
self.pool = pool | |||||
def __del__(self): | |||||
if self.pool: | |||||
self.pool.putconn(self.conn) | |||||
@contextmanager | @contextmanager | ||||
def transaction(self): | def transaction(self): | ||||
"""context manager to execute within a DB transaction | """context manager to execute within a DB transaction | ||||
Yields: | Yields: | ||||
a psycopg2 cursor | a psycopg2 cursor | ||||
▲ Show 20 Lines • Show All 913 Lines • Show Last 20 Lines |