def count(cls, **kwargs): cur = connection.cursor() values = ['='.join((k, '"%s"' % v)) for k, v in kwargs.iteritems()] condition = 'WHERE '+' and '.join(values) if kwargs else '' sql = 'SELECT count(1) FROM %s '+ condition cur.execute(sql % cls.__table__) data = cur.fetchone() print cur._last_executed return data[0] if data else 0
def __new__(cls, name, bases, attrs): base0 = bases[0] if base0 is object: return super(_Model, cls).__new__(cls, name, bases, attrs) new_class = type.__new__(cls, name, bases, attrs) new_class.__table__ = table = name cur = connection.cursor() cur.execute('SELECT * FROM %s LIMIT 1' % name) print cur._last_executed new_class.__column__ = column = map(itemgetter(0), cur.description) new_class.MC_KEY = name + '_%s' return new_class
def where(cls, limit=1, offset=0, order_by='id', **kwargs): cur = connection.cursor() values = ['='.join((k, '"%s"' % v)) for k, v in kwargs.iteritems()] condition = 'WHERE '+' and '.join(values) if kwargs else '' sql = 'SELECT * FROM %s '+ condition +'ORDER BY %s LIMIT %s OFFSET %s' cur.execute(sql % (cls.__table__, order_by, limit, offset)) data = cur.fetchall() print cur._last_executed result = [] for i in data: result.append(cls._data_to_obj(i)) return result
def get(cls, id=None, **kwargs): if id is None: if not kwargs: return data = None if id: id = str(id) kwargs['id'] = id mc_key = cls.MC_KEY % id data = mc.get(mc_key) if data: data = unpackb(data) return cls._data_to_obj(data) cur = connection.cursor() values = ['='.join((k, '"%s"' % v)) for k, v in kwargs.iteritems()] sql = 'SELECT * FROM %s WHERE '+' and '.join(values)+' LIMIT 1' cur.execute(sql % cls.__table__) data = cur.fetchone() print cur._last_executed if id or data: _id = data[0] if data else id mc_key = cls.MC_KEY % _id mc.set(mc_key, packb(data)) return cls._data_to_obj(data)
def _query(self, query, values): cur = connection.cursor() cur.execute(query, values) print cur._last_executed return cur.lastrowid
def delete(self): mc.delete(self.MC_KEY % self.id) cur = connection.cursor() cur.execute('DELETE FROM %s WHERE id=%s', (self.__table__, self.id)) print cur._last_executed
def __init__(self, table, NULL=""): self.table = table self.cursor = connection.cursor() self.prefix = table + "_%s" self.prefix_v = table + "_v_%s" self.NULL = NULL