我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlalchemy.update()。
def upsert_message_localization(message_name, language_id, message_title, message_text): ''' Add or update a message localization. Returns new or updated localization with relation to message preloaded. ''' with session_scope() as session: message = session.query(model.Message).filter(model.Message.name == message_name).one() message_localization = session.query(model.MessageLocalization).\ filter(model.MessageLocalization.message == message).\ filter(model.MessageLocalization.language_id == language_id).\ one_or_none() if message_localization is not None: message_localization.message_title = message_title message_localization.message_text = message_text else: message_localization = model.MessageLocalization(message=message, language_id=language_id, message_title=message_title, message_text=message_text) session.add(message_localization) session.commit() session.refresh(message_localization) session.refresh(message_localization.message) return message_localization
def __call__(self, *c, **kwargs): o = self.opts.copy() o.update(kwargs) tokens = len(self.__names) if tokens == 2: package, fname = self.__names elif tokens == 1: package, fname = "_default", self.__names[0] else: package = None if package is not None and \ package in functions._registry and \ fname in functions._registry[package]: func = functions._registry[package][fname] return func(*c, **o) return Function(self.__names[-1], packagenames=self.__names[0:-1], *c, **o) # "func" global - i.e. func.count()
def update(self): """ Update followers and following :return: New follower count, Lost follower count, New following count, Lost following count """ # Update followers self._logger.info(u"Updating followers...") n_follower, d_follower = self._update_friends(self._twitter_con.get_followers_cursor(), follower=True) # Update following self._logger.info(u"Updating followings...") n_following, d_following = self._update_friends(self._twitter_con.get_following_cursor(), follower=False) # Insert a statistic self.update_statistics() return n_follower, d_follower, n_following, d_following # end update # Get followers cursor
def update_user(request): """ update the user level :param request: :return: """ user = request.db_session.query(LedUser).filter(LedUser.id == request.matchdict['user_id']).first() if user is not None: level = request.POST.get('access_level', None) if level is not None and int(level) in [0, 2]: user.access_level = int(level) log(request, 'Updated user {} to level {}'.format(user.email, level)) return {'message': 'success'} else: return {'message': "Nothing changed"}
def _after_flush_handler(session, flush_context): handlers = [ (_versioned_delete, session.deleted), (_versioned_insert, session.new), (_versioned_update, session.dirty), ] for handler, rows in handlers: for row in rows: if isinstance(row, VAModelMixin): if not hasattr(row, 'ArchiveTable'): raise LogTableCreationError('Need to register va tables!!') user_id = getattr(row, '_updated_by', None) va_id = handler(row, session, user_id) if va_id: Model = type(row) where_clause = utils.generate_and_clause( Model, row, row.va_version_columns ) session.execute(sa.update(Model, values={'va_id': va_id}).where(where_clause)) row.va_id = va_id
def upgrade(): bind = op.get_bind() ### commands auto generated by Alembic - please adjust! ### op.add_column('exercises', sa.Column('chapter_id', sa.Integer(), nullable=True)) op.add_column('exercises', sa.Column('section_id', sa.Integer(), nullable=True)) op.add_column('exercises', sa.Column('book_row_id', sa.Integer(), nullable=True)) op.add_column('subjects', sa.Column('book_url', sa.String(), nullable=True)) ### end Alembic commands ### data = [ {'id': 1, 'book_url': 'https://staging-tutor.cnx.org/contents/d52e93f4-8653-4273-86da-3850001c0786'}, {'id': 2, 'book_url': 'https://staging-tutor.cnx.org/contents/334f8b61-30eb-4475-8e05-5260a4866b4b'} ] for item in data: update = sa.update(subject_table)\ .where(subject_table.c.id == item['id'])\ .values(dict(book_url=item['book_url'])) bind.execute(update)
def where(self, whereclause): """return a new update() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. """ if self._whereclause is not None: self._whereclause = and_(self._whereclause, _literal_as_text(whereclause)) else: self._whereclause = _literal_as_text(whereclause)
def _extra_froms(self): # TODO: this could be made memoized # if the memoization is reset on each generative call. froms = [] seen = set([self.table]) if self._whereclause is not None: for item in _from_objects(self._whereclause): if not seen.intersection(item._cloned_set): froms.append(item) seen.update(item._cloned_set) return froms
def update_canonicals(canonicals): ''' Update canonical data for android devices. ''' global ENGINE binding = [{"p_{}".format(k): v for k, v in canonical.items()} for canonical in canonicals] device_table = model.metadata.tables['device'] stmt = update(device_table).\ values(device_token_new=bindparam('p_new_token')).\ where(and_(device_table.c.login_id == bindparam('p_login_id'), func.coalesce(device_table.c.device_token_new, device_table.c.device_token) == bindparam('p_old_token'))) ENGINE.execute(stmt, binding) with session_scope() as session: query = text('SELECT keep_max_users_per_device( \ (:platform_id)::int2, :device_token, (:max_users_per_device)::int2)') for canonical in canonicals: session.execute(query, {'platform_id': constants.PLATFORM_ANDROID, 'device_token': canonical['new_token'], 'max_users_per_device': config.max_users_per_device }) session.execute(query, {'platform_id': constants.PLATFORM_ANDROID_TABLET, 'device_token': canonical['new_token'], 'max_users_per_device': config.max_users_per_device }) session.commit()
def update_unregistered_devices(unregistered): ''' Update data for unregistered Android devices. Unregistered device will not receive notifications and will be deleted when number of devices exceeds maximum. ''' global ENGINE binding = [{"p_{}".format(k): v for k, v in u.items()} for u in unregistered] device_table = model.metadata.tables['device'] stmt = update(device_table).\ values(unregistered_ts=func.now()).\ where(and_(device_table.c.login_id == bindparam('p_login_id'), func.coalesce(device_table.c.device_token_new, device_table.c.device_token) == bindparam('p_device_token'))) ENGINE.execute(stmt, binding)
def process_user_login(login_id, language_id, platform_id, device_token, application_version): ''' Add or update device and login data. Also deletes oldest device if number of devices exceeds maximum. ''' with session_scope() as session: session.execute(text('SELECT process_user_login(:login_id, (:language_id)::int2, \ (:platform_id)::int2,:device_token, :application_version, \ (:max_devices_per_user)::int2, (:max_users_per_device)::int2)'), { 'login_id': login_id, 'language_id': language_id, 'platform_id': platform_id, 'device_token': device_token, 'application_version': application_version, 'max_devices_per_user': config.max_devices_per_user, 'max_users_per_device': config.max_users_per_device }) session.commit()
def upsert_login(login_id, language_id): ''' Add or update a login entity. Returns new or updated login. ''' with session_scope() as session: login = session.query(model.Login).filter(model.Login.id == login_id).one_or_none() if login is not None: login.language_id = language_id else: login = model.Login(id=login_id, language_id=language_id) session.add(login) session.commit() session.refresh(login) return login
def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None): ''' Add or update a device entity. Returns new or updated device with relation to login preloaded. ''' with session_scope() as session: login = session.query(model.Login).filter(model.Login.id == login_id).one() device = session.query(model.Device).\ filter(model.Device.login == login).\ filter(model.Device.platform_id == platform_id).\ filter(func.coalesce(model.Device.device_token_new, model.Device.device_token) == device_token).\ one_or_none() if device is not None: device.application_version = application_version device.unregistered_ts = unregistered_ts else: device = model.Device(login=login, platform_id=platform_id, device_token=device_token, application_version=application_version, unregistered_ts=unregistered_ts) session.add(device) session.commit() session.refresh(device) session.refresh(device.login) return device
def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority): ''' Add or update a message. Returns new or updated message. ''' with session_scope() as session: message = session.query(model.Message).filter(model.Message.name == message_name).one_or_none() if message is not None: message.cooldown_ts = cooldown_ts message.trigger_event_id = trigger_event_id message.screen = screen message.expiry_millis = expiry_millis message.priority = priority else: message = model.Message(name=message_name, cooldown_ts=cooldown_ts, trigger_event_id=trigger_event_id, screen=screen, expiry_millis=expiry_millis, priority=priority) session.add(message) session.commit() session.refresh(message) return message
def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None, screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL): ''' Add or update a message with localization for one language. ''' message = upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority) message_localization = upsert_message_localization(message_name, language_id, message_title, message_text) return message_localization
def get_and_update_messages_to_send(user_message_set): ''' Update last time a message id was send for a user. Expects a set of (login_id, message_id) tuples. ''' # collect user messages in a dictionary for easier processing user_dict = defaultdict(set) for login_id, message_id in user_message_set: user_dict[login_id].add(message_id) with session_scope() as session: joined_login_ids = ','.join([str(login_id) for login_id in user_dict.keys()]) array_login_ids = "'{{{}}}'".format(joined_login_ids) query = "select * from get_non_elligible_user_message_pairs({})".format(array_login_ids) non_eligible_messages = session.query(model.UserMessageLastTimeSent).\ from_statement(text(query)).all() for non_eligible_message in non_eligible_messages: user_dict[non_eligible_message.login_id].discard(non_eligible_message.message_id) # update user_message_last_time_sent return_tuple = [] for user, messages in user_dict.iteritems(): for message in messages: return_tuple.append({str(user): str(message)}) session.execute(text( 'SELECT upsert_user_message_last_time_sent((:login_id)::bigint, :message_id)'), { 'login_id': user, 'message_id': message }) session.commit() return return_tuple
def start(self): """Start the service.""" self._hub.start() with self.sessionCtx() as s: stmt = update(db.Microbot).values(is_connected=False) s.execute(stmt) self._evtHandle = self._hub.onMicrobot(self._onMbFound, self._onMbLost) self._daemon.start()
def _params(self, unique, optionaldict, kwargs): if len(optionaldict) == 1: kwargs.update(optionaldict[0]) elif len(optionaldict) > 1: raise exc.ArgumentError( "params() takes zero or one positional dictionary argument") def visit_bindparam(bind): if bind.key in kwargs: bind.value = kwargs[bind.key] bind.required = False if unique: bind._convert_to_unique() return cloned_traverse(self, {}, {'bindparam': visit_bindparam})
def proxy_set(self): s = util.column_set([self]) if hasattr(self, '_proxies'): for c in self._proxies: s.update(c.proxy_set) return s
def __init__(self, *cols): super(ColumnCollection, self).__init__() self._data.update((c.key, c) for c in cols) self.__dict__['_all_cols'] = util.column_set(self)
def update(self, value): self._data.update(value) self._all_cols.clear() self._all_cols.update(self._data.values())
def _populate_column_collection(self): columns = [c for c in self.left.columns] + \ [c for c in self.right.columns] self.primary_key.extend(sqlutil.reduce_columns( (c for c in columns if c.primary_key), self.onclause)) self._columns.update((col._label, col) for col in columns) self.foreign_keys.update(itertools.chain( *[col.foreign_keys for col in columns]))
def update(self, whereclause=None, values=None, inline=False, **kwargs): """Generate an :func:`.update` construct against this :class:`.TableClause`. E.g.:: table.update().where(table.c.id==7).values(name='foo') See :func:`.update` for argument and usage information. """ return update(self, whereclause=whereclause, values=values, inline=inline, **kwargs)
def _froms(self): # would love to cache this, # but there's just enough edge cases, particularly now that # declarative encourages construction of SQL expressions # without tables present, to just regen this each time. froms = [] seen = set() translate = self._from_cloned def add(items): for item in items: if item is self: raise exc.InvalidRequestError( "select() construct refers to itself as a FROM") if translate and item in translate: item = translate[item] if not seen.intersection(item._cloned_set): froms.append(item) seen.update(item._cloned_set) add(_from_objects(*self._raw_columns)) if self._whereclause is not None: add(_from_objects(self._whereclause)) add(self._from_obj) return froms