Performs the actual mutation and then updates the recorded schema version
160476
@Override
	public final void mutate(Context context)
			throws MutagenException {

		// Perform the mutation
		performMutation(context);

		int version=getResultingState().getID();

		String change=getChangeSummary();
		if (change==null) {
			change="";
		}

		String changeHash=md5String(change);

		// The straightforward way, without locking
		try {
			MutationBatch batch=getKeyspace().prepareMutationBatch();
			batch
				.withRow(CassandraSubject.VERSION_CF,
					CassandraSubject.ROW_KEY)
				.putColumn(CassandraSubject.VERSION_COLUMN,version);

			batch
				.withRow(CassandraSubject.VERSION_CF,
					String.format("%08d",version))
				.putColumn("change",change)
				.putColumn("hash",changeHash);

			batch.execute();
		}
		catch (ConnectionException e) {
			throw new MutagenException("Could not update \"schema_version\" "+
				"column family to state "+version+
				"; schema is now out of sync with recorded version",e);
		}

// TAF: Why does this fail with a StaleLockException? Do we need to use a
// separate lock table?

//		// Attempt to acquire a lock to update the version
//		ColumnPrefixDistributedRowLock<String> lock =
//			new ColumnPrefixDistributedRowLock<String>(getKeyspace(),
//					CassandraSubject.VERSION_CF,CassandraSubject.VERSION_COLUMN)
//				.withBackoff(new BoundedExponentialBackoff(250, 10000, 10))
//				.expireLockAfter(1, TimeUnit.SECONDS)
////				.failOnStaleLock(false);
//				.failOnStaleLock(true);
//
//		try {
//			lock.acquire();
//		}
//		catch (StaleLockException e) {
//			// Won't happen
//			throw new MutagenException("Could not update "+
//				"\"schema_version\" column family to state "+version+
//				" because lock expired",e);
//		}
//		catch (BusyLockException e) {
//			throw new MutagenException("Could not update "+
//				"\"schema_version\" column family to state "+version+
//				" because another client is updating the recorded version",e);
//		}
//		catch (Exception e) {
//			if (e instanceof RuntimeException) {
//				throw (RuntimeException)e;
//			}
//			else {
//				throw new MutagenException("Could not update "+
//					"\"schema_version\" column family to state "+version+
//					" because a write lock could not be obtained",e);
//			}
//		}
//		finally {
//			try {
//				MutationBatch batch=getKeyspace().prepareMutationBatch();
//				batch.withRow(CassandraSubject.VERSION_CF,
//						CassandraSubject.ROW_KEY)
//					.putColumn(CassandraSubject.VERSION_COLUMN,version);
//
//				// Release and update
//				lock.releaseWithMutation(batch);
//			}
//			catch (Exception e) {
//				if (e instanceof RuntimeException) {
//					throw (RuntimeException)e;
//				}
//				else {
//					throw new MutagenException("Could not update "+
//						"\"schema_version\" column family to state "+version+
//						"; schema is now out of sync with recorded version",e);
//				}
//			}
//		}
	}
1313486
@Override
    public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException {
        Preconditions.checkNotNull(mutations);

        final MaskedTimestamp commitTime = new MaskedTimestamp(txh);

        int size = 0;
        for (Map<StaticBuffer, KCVMutation> mutation : mutations.values()) size += mutation.size();
        Map<StaticBuffer, org.apache.cassandra.db.Mutation> rowMutations = new HashMap<>(size);

        for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> mutEntry : mutations.entrySet()) {
            String columnFamily = mutEntry.getKey();
            for (Map.Entry<StaticBuffer, KCVMutation> titanMutation : mutEntry.getValue().entrySet()) {
                StaticBuffer key = titanMutation.getKey();
                KCVMutation mut = titanMutation.getValue();

                org.apache.cassandra.db.Mutation rm = rowMutations.get(key);
                if (rm == null) {
                    rm = new org.apache.cassandra.db.Mutation(keySpaceName, key.asByteBuffer());
                    rowMutations.put(key, rm);
                }

                if (mut.hasAdditions()) {
                    for (Entry e : mut.getAdditions()) {
                        Integer ttl = (Integer) e.getMetaData().get(EntryMetaData.TTL);

                        if (null != ttl && ttl > 0) {
                            rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
                                    e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times), ttl);
                        } else {
                            rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
                                    e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times));
                        }
                    }
                }

                if (mut.hasDeletions()) {
                    for (StaticBuffer col : mut.getDeletions()) {
                        rm.delete(columnFamily, CellNames.simpleDense(col.as(StaticBuffer.BB_FACTORY)),
                                commitTime.getDeletionTime(times));
                    }
                }

            }
        }

        mutate(new ArrayList<org.apache.cassandra.db.Mutation>(rowMutations.values()), getTx(txh).getWriteConsistencyLevel().getDB());

        sleepAfterWrite(txh, commitTime);
    }
437524
def update(instance, full_clean=True, post_save=False, **kwargs):
    ""

    # apply the updated args to the instance to mimic the change
    # note that these might slightly differ from the true database values
    # as the DB could have been updated by another thread. callers should
    # retrieve a new copy of the object if up-to-date values are required
    for k, v in kwargs.iteritems():
        if isinstance(v, ExpressionNode):
            v = resolve_expression_node(instance, v)
        setattr(instance, k, v)

    # clean instance before update
    if full_clean:
        instance.full_clean()

    # fields that use auto_now=True should be updated corrected, too!
    for field in instance._meta.fields:
        if hasattr(field, 'auto_now') and field.auto_now and field.name not in kwargs:
            kwargs[field.name] = field.pre_save(instance, False)

    rows_affected = instance.__class__._default_manager.filter(
        pk=instance.pk).update(**kwargs)

    if post_save:
        signals.post_save.send(sender=instance.__class__, instance=instance)

    return rows_affected
193871
@Override
  public void mutate(Mutation mutation) throws IOException {
    handleExceptions();
    addCallback(helper.mutate(mutation), mutation);
  }
1078219
public void updateSchema(String migrationPath) {
        try {
            logger.info("Updating schema... ");
            int current_version = 0;

            // first check the current schema version
            HashMap<String, Object> configuration = getFirstResult("SELECT * FROM " + Constants.DB_TABLE_CONFIGURATION +
                                                                       " WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + " = \'" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\'");

            if (configuration == null) {
                logger.info("Creating configuration table..");
                // create configuration table
                executeUpdate("CREATE TABLE "
                                  + Constants.DB_TABLE_CONFIGURATION
                                  + " (" + Constants.GENERIC_ID + " INTEGER IDENTITY,"
                                  + Constants.DB_TABLE_CONFIGURATION_NAME + " VARCHAR(256),"
                                  + Constants.DB_TABLE_CONFIGURATION_VALUE + " VARCHAR(1024));");

                executeUpdate("INSERT INTO " + Constants.DB_TABLE_CONFIGURATION
                                  + "(" + Constants.DB_TABLE_CONFIGURATION_NAME + "," + Constants.DB_TABLE_CONFIGURATION_VALUE + ")"
                                  + " VALUES (\'"
                                  + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION
                                  + "\', '0');");
            } else {
                logger.info("Getting current schema version..");
                // get current version
                current_version = new Integer(configuration.get("VALUE").toString());
                logger.info("Current schema version is {}", current_version);
            }

            // loop through until we get up to the right schema version
            while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {
                current_version++;

                // look for a schema file for this version
                logger.info("Updating to schema version {}", current_version);
                String currentFile = migrationPath + "/schema."
                    + current_version;
                Resource migFile = new ClassPathResource(currentFile);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                    migFile.getInputStream()));

                String str;
                while ((str = in.readLine()) != null) {
                    // execute each line
                    if (str.length() > 0) {
                        executeUpdate(str);
                    }
                }
                in.close();
            }

            // update the configuration table with the correct version
            executeUpdate("UPDATE " + Constants.DB_TABLE_CONFIGURATION
                              + " SET " + Constants.DB_TABLE_CONFIGURATION_VALUE + "='" + current_version
                              + "' WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + "='"
                              + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "';");
        } catch (Exception e) {
            logger.info("Error in executeUpdate");
            e.printStackTrace();
        }
    }
1329288
function processVersioned (entity, version, versions) {
  quantum.select(entity)
    .selectAll('versioned', {recursive: true})
    .forEach(versioned => {
      const candidateVersionSelections = versioned.selectAll('version')
      const currentVersion = mostRecentVersion(version, candidateVersionSelections, versions)
      if (currentVersion) {
        versioned.addAfter(currentVersion.content())
      }
      versioned.remove()
    })
}
716573
protected function updateSchemaVersionFile() {
    // Write BLT version to blt/.schema-version.
    $latest_update_method_version = $this->updater->getLatestUpdateMethodVersion();
    $schema_file_name = $this->getConfigValue('blt.config-files.schema-version');

    $fs = new Filesystem();
    $fs->dumpFile($schema_file_name, $latest_update_method_version);
  }
139640
def _modify(self, **patch):
        """"""

        requests_params, patch_uri, session, read_only = \
            self._prepare_put_or_patch(patch)
        self._check_for_boolean_pair_reduction(patch)
        read_only_mutations = []
        for attr in read_only:
            if attr in patch:
                read_only_mutations.append(attr)
        if read_only_mutations:
            msg = 'Attempted to mutate read-only attribute(s): %s' \
                % read_only_mutations
            raise AttemptedMutationOfReadOnly(msg)

        patch = self._prepare_request_json(patch)
        response = session.patch(patch_uri, json=patch, **requests_params)
        self._local_update(response.json())
1080782
def upgrade():
    """"""
    op.create_table(
        'records_buckets',
        sa.Column(
            'record_id',
            sqlalchemy_utils.types.uuid.UUIDType(),
            nullable=False),
        sa.Column(
            'bucket_id',
            sqlalchemy_utils.types.uuid.UUIDType(),
            nullable=False),
        sa.ForeignKeyConstraint(['bucket_id'], [u'files_bucket.id'], ),
        sa.ForeignKeyConstraint(['record_id'], [u'records_metadata.id'], ),
        sa.PrimaryKeyConstraint('record_id', 'bucket_id')
    )
678943
@Override
  public CompletableFuture<Void> mutate(final Mutation mutation) {
    return toCompletableFuture(helper.mutate(mutation))
        .thenApply(r -> null);
  }
1213550
def _add_variants(self, key, value, schema):
        ''' 
        '''
        variants = schema.get('variants')
        obj = {}
        if variants:
            for _key, func in variants.iteritems():
                _value = func(value, self.store)
                obj.update({_key: _value})
        return obj
1270396
def modify_record(durable_model, current_revision, arn, event_time, diff_func):
    """"""
    # We want the newest items first.
    # See: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html
    items = list(durable_model.query(
        arn,
        (durable_model.eventTime <= event_time),
        scan_index_forward=False,
        limit=1,
        consistent_read=True))

    if items:
        latest_revision = items[0]

        latest_config = latest_revision._get_json()[1]['attributes']    # pylint: disable=W0212
        current_config = current_revision._get_json()[1]['attributes']  # pylint: disable=W0212

        # Determine if there is truly a difference, disregarding Ephemeral Paths
        diff = diff_func(latest_config, current_config)
        if diff:
            LOG.debug(
                f'[~] Difference found saving new revision to durable table. Arn: {arn} LatestConfig: {latest_config} '
                f'CurrentConfig: {json.dumps(current_config)}')
            current_revision.save()
    else:
        current_revision.save()
        LOG.info(f'[?] Got modify event but no current revision found. Arn: {arn}')
701847
private function throwIfPiwikVersionIsOlderThanDBSchema()
    {
        // When developing this situation happens often when switching branches
        if (Development::isEnabled()) {
            return;
        }

        if (!StaticContainer::get('EnableDbVersionCheck')) {
            return;
        }

        $updater = new Updater();

        $dbSchemaVersion = $updater->getCurrentComponentVersion('core');
        $current = Version::VERSION;
        if (-1 === version_compare($current, $dbSchemaVersion)) {
            $messages = array(
                Piwik::translate('General_ExceptionDatabaseVersionNewerThanCodebase', array($current, $dbSchemaVersion)),
                Piwik::translate('General_ExceptionDatabaseVersionNewerThanCodebaseWait'),
                // we cannot fill in the Super User emails as we are failing before Authentication was ready
                Piwik::translate('General_ExceptionContactSupportGeneric', array('', ''))
            );
            throw new DatabaseSchemaIsNewerThanCodebaseException(implode(" ", $messages));
        }
    }
874840
public boolean updateVersion(final Migration migration) {
        final Statement insert = QueryBuilder.insertInto(SCHEMA_VERSION_CF).value(TYPE, migration.getType().name())
                .value(VERSION, migration.getVersion()).value(TIMESTAMP, System.currentTimeMillis())
                .value(DESCRIPTION, migration.getDescription()).setConsistencyLevel(ConsistencyLevel.ALL);

        try {
            session.execute(insert);
            return true;
        } catch (final Exception e) {
            LOGGER.error("Failed to execute update version statement", e);
            return false;
        }
    }
1262377
public function upgradeSchema(Schema $schema)
    {
        $table = $schema->getTable('FileImageThumbnailPaths');
        if ($table->hasIndex('thumbnailPathID')) {
            $table->dropIndex('thumbnailPathID');
        }
        if (!$table->hasColumn('thumbnailFormat')) {
            $table->addColumn(
                'thumbnailFormat',
                'string',
                [
                    'notnull' => true,
                    'default' => '',
                    'length' => 5,
                ]
            );
            $table->setPrimaryKey([
                'fileID',
                'fileVersionID',
                'thumbnailTypeHandle',
                'storageLocationID',
                'thumbnailFormat',
            ]);
        }
    }
716123
def mutate(self, mutation=None, set_obj=None, del_obj=None, set_nquads=None,
               del_nquads=None, commit_now=None, ignore_index_conflict=None,
               timeout=None, metadata=None, credentials=None):
        """"""
        mutation = self._common_mutate(
            mutation=mutation, set_obj=set_obj, del_obj=del_obj,
            set_nquads=set_nquads, del_nquads=del_nquads,
            commit_now=commit_now, ignore_index_conflict=ignore_index_conflict)

        new_metadata = self._dg.add_login_metadata(metadata)
        mutate_error = None

        try:
            assigned = self._dc.mutate(mutation, timeout=timeout,
                                       metadata=new_metadata,
                                       credentials=credentials)
        except Exception as error:
            if util.is_jwt_expired(error):
                self._dg.retry_login()
                new_metadata = self._dg.add_login_metadata(metadata)
                try:
                    assigned = self._dc.mutate(mutation, timeout=timeout,
                                               metadata=new_metadata,
                                               credentials=credentials)
                except Exception as error:
                    mutate_error = error
            else:
                mutate_error = error

        if mutate_error is not None:
            try:
                self.discard(timeout=timeout, metadata=metadata,
                             credentials=credentials)
            except:
                # Ignore error - user should see the original error.
                pass

            self._common_except_mutate(mutate_error)

        if mutation.commit_now:
            self._finished = True

        self.merge_context(assigned.context)
        return assigned
535033
public function upgradeSchema(Schema $schema)
    {
        try {
            $table = $schema->getTable('SystemDatabaseQueryLog');
            $table->addColumn('ID', 'integer', ['unsigned' => true, 'autoincrement' => true]);
            $table->setPrimaryKey(['ID']);
        } catch (\Exception $e) {
        }
    }