def cursor(self): global engine if self.connection is None: con = engine.connect() log.info('open connection <%s>...' % hex(id(connection))) self.connection = con return self.connection.cursor()
def __enter__(self): global _db_ctx self.should_close_conn = False if not _db_ctx.is_init(): # needs open a connection first: _db_ctx.init() self.should_close_conn = True _db_ctx.transactions += 1 log.info('begin transaction...' if _db_ctx.transactions == 1 else 'join current transaction...') return self
def commit(self): global _db_ctx log.info('commit transaction...') try: _db_ctx.connection.commit() log.info('commit ok.') except: log.warning('commit failed. try rollback...') _db_ctx.connection.rollback() log.warning('rollback ok.') raise
def __new__(cls, name, bases, attrs): if name == 'Model': return type.__new__(cls, name, bases, attrs) if not hasattr(cls, 'subclasses'): cls.subclasses = {} if name not in cls.subclasses: cls.subclasses[name] = name else: log.warning('Redefine class: %s' % name) log.info('Scan ORMapping %s...' % name) mappings = dict() primary_key = None for k, v in attrs.iteritems(): if isinstance(v, Field): if not v.name: v.name = k log.info('Found mapping: %s => %s' % (k, v)) if v.primary_key: if primary_key: raise TypeError( 'Cannot define more than 1 primary key in class: %s' % name) if v.writable: log.warning( 'NOTE: change primary key to non-writable.') v.writable = False if v.nullable: log.warning( 'NOTE: change primary key to non-nullable.') v.nullable = False primary_key = v mappings[k] = v # check exist of primary key: if not primary_key: raise TypeError('Primary key not defined in class: %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if '__table__' not in attrs: attrs['__table__'] = name.lower() attrs['__mappings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self: _gen_sql(attrs['__table__'], mappings) for trigger in _triggers: if trigger not in attrs: attrs[trigger] = None return type.__new__(cls, name, bases, attrs)
def _update(sql, *args): global _db_ctx cursor = None sql = sql.replace('?', '%s') log.info('SQL: %s, ARGS: %s' % (sql, args)) try: cursor = _db_ctx.connection.cursor() cursor.execute(sql, args) r = cursor.rowcount if _db_ctx.transactions == 0: # no transaction enviroment: log.info('auto commit') _db_ctx.connection.commit() return r finally: if cursor: cursor.close()
def __new__(cls, name, bases, attrs): if name == 'Model': return type.__new__(cls, name, bases, attrs) if not hasattr(cls, 'subclasses'): cls.subclasses = {} if name not in cls.subclasses: cls.subclasses[name] = name else: log.warning('Redefine class: %s' % name) log.info('Scan ORMapping %s...' % name) mappings = dict() primary_key = None for k, v in attrs.iteritems(): if isinstance(v, Field): if not v.name: v.name = k log.info('Found mapping: %s => %s' % (k, v)) if v.primary_key: if primary_key: raise TypeError('Cannot define more than 1 primary key in class: %s' % name) if v.writable: log.warning('NOTE: change primary key to non-writable.') v.writable = False if v.nullable: log.warning('NOTE: change primary key to non-nullable.') v.nullable = False primary_key = v mappings[k] = v # check exist of primary key: if not primary_key: raise TypeError('Primary key not defined in class: %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if '__table__' not in attrs: attrs['__table__'] = name.lower() attrs['__mappings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self: _gen_sql(attrs['__table__'], mappings) for trigger in _triggers: if trigger not in attrs: attrs[trigger] = None return type.__new__(cls, name, bases, attrs)
def _select(sql, first, *args): global _db_ctx cursor = None names = [] sql = sql.replace('?', '%s') log.info('SQL: %s, ARGS: %s', sql, args) try: cursor = _db_ctx.connection.cursor() cursor.execute(sql, args) if cursor.description: names = [x[0] for x in cursor.description] if first: values = cursor.fetchone() if not values: return None return Dict(names, values) return [Dict(names, x) for x in cursor.fetchall()] finally: if cursor: cursor.close()
def init(self): log.info('open lazy connection...') self.connection = _LasyConnection() self.transactions = 0
def cleanup(self): if self.connection: con = self.connection self.connection = None log.info('close connection <%s>...' % hex(id(con))) con.close()
def rollback(self): global _db_ctx log.warning('rollback transaction...') _db_ctx.connection.rollback() log.info('rollback ok.')
def profiling(start, sql=''): t = time.time() - start if t > 0.1: log.warning('[PROFILING] [DB] %s: %s', t, sql) else: log.info('[PROFILING] [DB] %s: %s', t, sql)