def _get_field_strs_and_params(self, fields): if not isinstance(fields, (list, tuple)): fields = [fields] # pragma: no cover strs = [] params = [] for field in fields: if isinstance(field, basestring): _field = getattr(self._model_class, field, None) if not _field: raise ExpressionError('Cannot find field: `{}`'.format( # noqa pragma: no cover pylint: disable=W field )) field = _field sql, _params = sql_and_params(field) if _params: params.extend(_params) alias_name = getattr(field, 'alias_name', None) if alias_name: strs.append(alias_name) else: strs.append(sql) return strs, params
def delete(self, **kwargs): if self.before_delete(**kwargs) is False: return expression, params = self.unique_expression_and_params if not params: raise ExpressionError( 'Cannot delete this instance because of ' # noqa pragma: no cover 'the model has no primary_key ' 'and unique_key') sql = ('DELETE FROM `{table_name}` ' 'WHERE {expression} ').format(table_name=self._get_table_name(), expression=expression) db = self._get_db() db.execute(sql, params) def func(): after_delete.send(self) self.after_delete(**kwargs) if db.autocommit: db.commit() func() else: db.add_lazy_func(func) return True
def delete(self, **kwargs): # before_delete will return None, so explicit compare with False if self.before_delete(**kwargs) is False: return False expression = self.unique_expression if expression is None: raise ExpressionError( 'Cannot delete this instance because of ' # noqa pragma: no cover 'the model has no primary_key ' 'and unique_key') sql_ast = [ 'DELETE', ['TABLE', self._get_table_name()], ['WHERE'] + [expression.get_sql_ast()] ] db = self._get_db() def func(): after_delete.send(self) self.after_delete(**kwargs) with db.transaction(): db.ast_execute(sql_ast) db.add_lazy_func(func) return True
def delete(self, **kwargs): if self.before_delete(**kwargs) is False: return expression = self.unique_expression if expression is None: raise ExpressionError( 'Cannot delete this instance because of ' # noqa pragma: no cover 'the model has no primary_key ' 'and unique_key') sql_ast = [ 'DELETE', ['TABLE', self._get_table_name()], ['WHERE'] + [expression.get_sql_ast()] ] db = self._get_db() db.ast_execute(sql_ast) def func(): after_delete.send(self) self.after_delete(**kwargs) if db.autocommit: db.commit() func() else: db.add_lazy_func(func) return True
def get_singleness_pk_attr_name(cls): pk = cls.__primary_key__ pkl = len(pk) if pkl != 1: raise ExpressionError( 'This method only support singleness primary key now. ' 'But your primary key has {} keys'.format(pkl)) return list(pk)[0]
def delete(self): expression = self._get_expression() if not expression: raise ExpressionError('Cannot execute delete because of ' 'without expression') sql_ast = ['DELETE', ['TABLE', self.table_name]] with self.db.transaction(): rows = self._get_rv(base_sql_ast=sql_ast) return rows
def delete(self): expression = self._get_expression() if not expression: raise ExpressionError('Cannot execute delete because of ' 'without expression') sql_ast = ['DELETE', ['TABLE', self.table_name]] rows = self._get_rv(base_sql_ast=sql_ast) if self.db.autocommit: self.db.commit() return rows
def delete(self): expression, _ = self._get_expression_and_params() if not expression: raise ExpressionError('Cannot execute delete because of ' 'without expression') sql = 'DELETE FROM `{table}` '.format( table=self.table_name, ) rows = self._get_rv(base_sql=sql) if self.db.autocommit: self.db.commit() return rows
def update(self, **values): expression = self._get_expression() if not expression: raise ExpressionError('Cannot execute update because of ' 'without expression') expressions, _, _ = self._model_class._split_attrs(values) sql_ast = [ 'UPDATE', ['TABLE', self.table_name], ['SET', ['SERIES'] + [exp.get_sql_ast() for exp in expressions]] ] with self.db.transaction(): rows = self._get_rv(base_sql_ast=sql_ast) return rows
def _get_fields(self, fields): if not isinstance(fields, (list, tuple)): fields = [fields] # pragma: no cover res = [] for field in fields: if isinstance(field, str_types): _field = getattr(self._model_class, field, None) if not _field: raise ExpressionError('Cannot find field: `{}`'.format( # noqa pragma: no cover pylint: disable=W field)) field = _field res.append(field) return res
def update(self, **values): expression, _ = self._get_expression_and_params() if not expression: raise ExpressionError('Cannot execute update because of ' 'without expression') expressions, _, _ = self._model_class._split_attrs(values) sql_pieces, params = get_sql_pieces_and_params(expressions) sql = 'UPDATE `{table}` SET {columns} '.format( table=self.table_name, columns=', '.join(sql_pieces), ) rows = self._get_rv(base_sql=sql, base_params=params) if self.db.autocommit: self.db.commit() return rows
def update(self, **values): from olo import PostgreSQLDataBase expression = self._get_expression() if not expression: raise ExpressionError('Cannot execute update because of ' 'without expression') assignments, _, _ = self._model_class._split_attrs(values) update_sql_ast = [ 'UPDATE', ['TABLE', self.table_name], ['SET', ['SERIES'] + [asg.get_sql_ast() for asg in assignments]], ] db = self._model_class._get_db() # FIXME(PG) if isinstance(db, PostgreSQLDataBase): pk = self._model_class.get_singleness_pk_field() if self._order_by: base_sql_ast = self.map(pk).for_update()._get_base_sql_ast() sql_ast = self.get_sql_ast( base_sql_ast=base_sql_ast, ) update_sql_ast.append( ['WHERE', ['BINARY_OPERATE', 'IN', ['QUOTE', pk.name], ['BRACKET', sql_ast]]] ) with self.db.transaction(): rows = self._get_rv_by_sql_ast(sql_ast=update_sql_ast) else: with self.db.transaction(): rows = self._get_rv(base_sql_ast=update_sql_ast) else: with self.db.transaction(): rows = self._get_rv(base_sql_ast=update_sql_ast) return rows
def update(self, **attrs): self._check_attrs(attrs) attrs = self._wash_attrs(attrs) if not attrs: return False if self._orig is None: self._set_orig() if self.before_update(**attrs) is False: self._rollback() return False db = self._get_db() need_updates = {} for k, v in self.__on_updates__.iteritems(): if k in attrs: continue try: res = v() except TypeError: res = v(self) need_updates[k] = res attrs = dict(need_updates, **attrs) expressions, sql_attrs, db_attrs = self._split_attrs(attrs) sql_attrs = self._validate_attrs(sql_attrs, decrypt=False) db_attrs = self._validate_attrs(db_attrs, decrypt=False) clean_attrs = dict(sql_attrs, **db_attrs) for k in db_attrs: # cache old db values getattr(self._orig, k, None) next_inst = self._clone() next_inst.__setstate__(dict(self._data, **clean_attrs)) can_update = self._orig._will_update( next_inst, fields=clean_attrs.keys(), ) if can_update is False: self._rollback() return False if expressions: expression, _params = self.unique_expression_and_params if not _params: raise ExpressionError( 'Cannot update this instance because of ' # noqa pragma: no cover 'the model has no primary_key ' 'and unique_key') sql_pieces, params = get_sql_pieces_and_params(expressions) if _params: params.extend(_params) sql = ('UPDATE `{table_name}` SET {columns} ' 'WHERE {expression} ').format( table_name=self._get_table_name(), columns=', '.join(sql_pieces), expression=expression) try: db.execute(sql, params) if db.autocommit: db.commit() except Exception: if db.autocommit: db.rollback() # pragma: no cover raise dynamic_exps = [ exp for exp in expressions if isinstance(exp.right, Expression) ] if dynamic_exps: keys = map(lambda x: x.left.attr_name, dynamic_exps) q = self.__class__.query(*keys).filter( **{ attr_name: getattr(self, attr_name) for attr_name in self.__primary_key__ }) values = q.first() if not isinstance(values, tuple): values = [values] _attrs = dict(izip(keys, values)) sql_attrs.update(self._parse_attrs(_attrs)) before_update.send(self) clean_attrs = dict(sql_attrs, **db_attrs) self._data.update(clean_attrs) for k in clean_attrs: self._parsed_data.pop(k, None) for k, v in db_attrs.iteritems(): field = getattr(self.__class__, k) field.db_set(self, v) _orig = self._orig def func(): db.commit_beansdb() after_update.send(self) self.after_update() if _orig is not None: self._orig = None self._did_update(_orig, fields=chain.from_iterable([ sql_attrs.iterkeys(), db_attrs.iterkeys(), ])) def rollback_handler(): self._rollback() if db.autocommit: func() else: db.add_lazy_func(func) db.add_rollback_handler(rollback_handler) return True
def update(self, **attrs): # pylint: disable=too-many-statements self._check_attrs(attrs) attrs = self._wash_attrs(attrs) if not attrs: return False if self._orig is None: self._set_orig() if self.before_update(**attrs) is False: self._rollback() return False for k in self.__setter_fields__: v = attrs.get(k, missing) if v is missing: continue f = getattr(self.__class__, k) v = f._setter(self, v) attrs[k] = v db = self._get_db() need_updates = {} for k, v in iteritems(self.__on_updates__): if k in attrs: continue try: res = v() except TypeError: res = v(self) need_updates[k] = res attrs = dict(need_updates, **attrs) assignments, sql_attrs, db_attrs = self._split_attrs(attrs) sql_attrs = self._validate_attrs(sql_attrs, decrypt=False) db_attrs = self._validate_attrs(db_attrs, decrypt=False) clean_attrs = dict(sql_attrs, **db_attrs) for k in db_attrs: # cache old db values getattr(self._orig, k, None) next_inst = self._clone() next_inst.__olo_setstate__(dict(self._data, **clean_attrs)) can_update = self._orig._will_update( next_inst, fields=clean_attrs.keys(), ) if can_update is False: self._rollback() return False if assignments: expression = self.unique_expression if expression is None: raise ExpressionError( 'Cannot update this instance because of ' # noqa pragma: no cover 'the model has no primary_key ' 'and unique_key') sql_ast = [ 'UPDATE', ['TABLE', self._get_table_name()], [ 'SET', ['SERIES'] + [asg.get_sql_ast() for asg in assignments] ], ['WHERE'] + [expression.get_sql_ast()] ] with db.transaction(): db.ast_execute(sql_ast) dynamic_exps = [ asg for asg in assignments if isinstance(asg.right, Expression) ] if dynamic_exps: keys = list(map(lambda x: x.left.attr_name, dynamic_exps)) q = self.__class__.query(*keys).filter( **{ attr_name: getattr(self, attr_name) for attr_name in self.__primary_key__ }) values = q.first() if not isinstance(values, tuple): values = [values] _attrs = dict(izip(keys, values)) sql_attrs.update(self._parse_attrs(_attrs)) before_update.send(self) clean_attrs = dict(sql_attrs, **db_attrs) self._data.update(clean_attrs) for k in clean_attrs: self._parsed_data.pop(k, None) for k, v in iteritems(db_attrs): field = getattr(self.__class__, k) field.db_set(self, v) _orig = self._orig def func(): db.commit_beansdb() after_update.send(self) self.after_update() if _orig is not None: self._orig = None self._did_update(_orig, fields=chain.from_iterable([ iterkeys(sql_attrs), iterkeys(db_attrs), ])) def rollback_handler(): self._rollback() if db.autocommit: func() else: db.add_lazy_func(func) db.add_rollback_handler(rollback_handler) return True