// Anko converts old anko-form migrations to new plush ones.
494527
func Anko(content string) (string, error) {
	bb := &bytes.Buffer{}

	lines := strings.Split(content, "\n")
	l := len(lines)
	fre := regexp.MustCompile(`,\s*func\(t\)\s*{`)

	for i := 0; i < l; i++ {
		line := lines[i]
		tl := strings.TrimSpace(line)
		if strings.HasPrefix(tl, "create_table") {
			// skip already converted create_table
			if fre.MatchString(line) {
				// fix create_table
				line = fre.ReplaceAllString(line, ") {")
				ll := i
				lines[i] = line
				waitParen := false
				for {
					if strings.HasPrefix(tl, "})") {
						line = "}" + tl[2:]
						break
					} else if strings.HasPrefix(tl, "}") {
						// Now, we have to make sure to match the missing ")"
						waitParen = true
					} else if waitParen && strings.HasPrefix(tl, ")") {
						line = tl[1:]
						break
					}
					i++
					if l == i {
						return "", fmt.Errorf("unclosed create_table statement line %d", ll+1)
					}
					line = lines[i]
					tl = strings.TrimSpace(line)
				}
			}
		} else if strings.HasPrefix(tl, "raw(") {
			// fix raw
			line = strings.Replace(line, "raw(", "sql(", -1)
		}
		lines[i] = line
	}

	body := strings.Join(lines, "\n")

	if _, err := plush.Parse(body); err != nil {
		return "", err
	}

	bb.WriteString(body)

	return bb.String(), nil
}
11835
func (_m *FacadeInterface) MigrateServices(ctx datastore.Context, request dao.ServiceMigrationRequest) error {
	ret := _m.Called(ctx, request)

	var r0 error
	if rf, ok := ret.Get(0).(func(datastore.Context, dao.ServiceMigrationRequest) error); ok {
		r0 = rf(ctx, request)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
663924
func (p *Paths) Migrate(newPaths Paths) {
	if newPaths.DataDir != "" {
		p.DataDir = newPaths.DataDir
	}
	if newPaths.LogDir != "" {
		p.LogDir = newPaths.LogDir
	}
	if newPaths.MetricsSpoolDir != "" {
		p.MetricsSpoolDir = newPaths.MetricsSpoolDir
	}
	if newPaths.ConfDir != "" {
		p.ConfDir = newPaths.ConfDir
	}
}
1204194
func (s *RedisMapStore) Migrate(selector string) error {
	if selector == "" {
		selector = "*"
	}
	if !strings.HasPrefix(selector, s.prefix) {
		selector = s.prefix + selector
	}

	var cursor uint64
	for {
		keys, next, err := s.client.Scan(cursor, selector, 0).Result()
		if err != nil {
			return err
		}

		for _, key := range keys {
			// Get migrates the item
			_, err := s.Get(key)

			// NotFound if item was deleted since Scan started
			if errors.GetErrType(err) == errors.NotFound {
				continue
			}

			// TxFailedError is returned if the item was changed by a concurrent process.
			// If it was a parallel migration, we don't have to do anything
			// Otherwise, this item will be migrated with the next Get
			if err == redis.TxFailedErr {
				continue
			}

			// Any other error should be returned
			if err != nil {
				return err
			}
		}

		cursor = next
		if cursor == 0 {
			break
		}
	}

	return nil
}
1275981
func (c *Client) MigrateVirtualMachine(p *MigrateVirtualMachineParameter) (*VirtualMachine, error) {
	obj, err := c.Request("migrateVirtualMachine", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
690816
func (wr *Wrangler) replicaMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, reverse bool) (err error) {
	ev := &events.MigrateServedTypes{
		KeyspaceName:      keyspace,
		SourceShards:      sourceShards,
		DestinationShards: destinationShards,
		ServedType:        servedType,
		Reverse:           reverse,
	}
	event.DispatchUpdate(ev, "start")
	defer func() {
		if err != nil {
			event.DispatchUpdate(ev, "failed: "+err.Error())
		}
	}()

	fromShards, toShards := sourceShards, destinationShards
	if reverse {
		fromShards, toShards = toShards, fromShards
	}

	// Check and update all source shard records.
	// Enable query service if needed
	event.DispatchUpdate(ev, "updating shards to migrate from")
	if err = wr.updateShardRecords(ctx, keyspace, fromShards, cells, servedType, true /* isFrom */, false /* clearSourceShards */); err != nil {
		return err
	}

	// Do the same for destination shards
	event.DispatchUpdate(ev, "updating shards to migrate to")
	if err = wr.updateShardRecords(ctx, keyspace, toShards, cells, servedType, false, false); err != nil {
		return err
	}

	// Now update serving keyspace

	if err = wr.ts.MigrateServedType(ctx, keyspace, toShards, fromShards, servedType, cells); err != nil {
		return err
	}

	event.DispatchUpdate(ev, "finished")
	return nil
}
630762
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
	logger.mu.Lock()
	oldHooks := logger.Hooks
	logger.Hooks = hooks
	logger.mu.Unlock()
	return oldHooks
}
574809
func (c *Client) migrate(ctx context.Context, build chronograf.BuildInfo) error {
	if c.db != nil {
		// Runtime migrations
		if err := c.OrganizationsStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.SourcesStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.ServersStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.LayoutsStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.DashboardsStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.ConfigStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.BuildStore.Migrate(ctx, build); err != nil {
			return err
		}
		if err := c.MappingsStore.Migrate(ctx); err != nil {
			return err
		}
		if err := c.OrganizationConfigStore.Migrate(ctx); err != nil {
			return err
		}

		MigrateAll(c)
	}
	return nil
}
1210904
func (c Context) AnErr(key string, err error) Context {
	marshaled := ErrorMarshalFunc(err)
	switch m := marshaled.(type) {
	case nil:
		return c
	case LogObjectMarshaler:
		return c.Object(key, m)
	case error:
		return c.Str(key, m.Error())
	case string:
		return c.Str(key, m)
	default:
		return c.Interface(key, m)
	}
}
666404
func (u *RelocationError) UnmarshalJSON(body []byte) error {
	type wrap struct {
		dropbox.Tagged
		// FromLookup : has no documentation (yet)
		FromLookup json.RawMessage `json:"from_lookup,omitempty"`
		// FromWrite : has no documentation (yet)
		FromWrite json.RawMessage `json:"from_write,omitempty"`
		// To : has no documentation (yet)
		To json.RawMessage `json:"to,omitempty"`
	}
	var w wrap
	var err error
	if err = json.Unmarshal(body, &w); err != nil {
		return err
	}
	u.Tag = w.Tag
	switch u.Tag {
	case "from_lookup":
		err = json.Unmarshal(w.FromLookup, &u.FromLookup)

		if err != nil {
			return err
		}
	case "from_write":
		err = json.Unmarshal(w.FromWrite, &u.FromWrite)

		if err != nil {
			return err
		}
	case "to":
		err = json.Unmarshal(w.To, &u.To)

		if err != nil {
			return err
		}
	}
	return nil
}
824805
func (o *ObjectToPack) BackToOriginal() {
	if o.IsDelta() && o.Original != nil {
		o.Object = o.Original
		o.Base = nil
		o.Depth = 0
	}
}
230813
func MigrateUpdate(currpath, driver, connStr, dir string) {
	migrate("upgrade", currpath, driver, connStr, dir)
}
257278
func (m *Migrator) migrateStableStore() error {
	op := "Migrating stable store"
	m.sendProgress(op, 0, 1)

	total := len(stableStoreKeys)
	for i, key := range stableStoreKeys {
		val, err := m.mdbStore.Get(key)
		if err != nil {
			if err.Error() != "not found" {
				return fmt.Errorf("Error getting key '%s': %s", string(key), err)
			}
			m.sendProgress(op, i+1, total)
			continue
		}
		if err := m.boltStore.Set(key, val); err != nil {
			return fmt.Errorf("Error storing key '%s': %s", string(key), err)
		}
		m.sendProgress(op, i+1, total)
	}
	return nil
}
439183
func (wr *Wrangler) MigrateServedTypes(ctx context.Context, keyspace, shard string, cells []string, servedType topodatapb.TabletType, reverse, skipReFreshState bool, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) {
	// check input parameters
	if servedType == topodatapb.TabletType_MASTER {
		// we cannot migrate a master back, since when master migration
		// is done, the source shards are dead
		if reverse {
			return fmt.Errorf("cannot migrate master back to %v/%v", keyspace, shard)
		}
		// we cannot skip refresh state for a master
		if skipReFreshState {
			return fmt.Errorf("cannot skip refresh state for master migration on %v/%v", keyspace, shard)
		}
		if cells != nil {
			return fmt.Errorf("cannot specify cells for master migration on %v/%v", keyspace, shard)
		}
	}

	// lock the keyspace
	ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedTypes(%v)", servedType))
	if lockErr != nil {
		return lockErr
	}
	defer unlock(&err)

	// find overlapping shards in this keyspace
	wr.Logger().Infof("Finding the overlapping shards in keyspace %v", keyspace)
	osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace)
	if err != nil {
		return fmt.Errorf("FindOverlappingShards failed: %v", err)
	}

	// find our shard in there
	os := topotools.OverlappingShardsForShard(osList, shard)
	if os == nil {
		return fmt.Errorf("shard %v is not involved in any overlapping shards", shard)
	}

	sourceShards, destinationShards, err := wr.findSourceDest(ctx, os)
	if err != nil {
		return err
	}

	// execute the migration
	if servedType == topodatapb.TabletType_MASTER {
		if err = wr.masterMigrateServedType(ctx, keyspace, sourceShards, destinationShards, filteredReplicationWaitTime, reverseReplication); err != nil {
			return err
		}
	} else {
		if err = wr.replicaMigrateServedType(ctx, keyspace, sourceShards, destinationShards, cells, servedType, reverse); err != nil {
			return err
		}
	}

	// Master migrate performs its own refresh.
	// Otherwise, honor skipRefreshState if requested.
	if servedType == topodatapb.TabletType_MASTER || skipReFreshState {
		return nil
	}

	// refresh
	// TODO(b/26388813): Integrate vtctl WaitForDrain here instead of just sleeping.
	// Anything that's not a replica will use the RDONLY sleep time.
	waitForDrainSleep := *waitForDrainSleepRdonly
	if servedType == topodatapb.TabletType_REPLICA {
		waitForDrainSleep = *waitForDrainSleepReplica
	}
	wr.Logger().Infof("WaitForDrain: Sleeping for %.0f seconds before shutting down query service on old tablets...", waitForDrainSleep.Seconds())
	time.Sleep(waitForDrainSleep)
	wr.Logger().Infof("WaitForDrain: Sleeping finished. Shutting down queryservice on old tablets now.")

	rec := concurrency.AllErrorRecorder{}
	refreshShards := sourceShards
	if reverse {
		// For a backwards migration, we should refresh (disable) destination shards instead.
		refreshShards = destinationShards
	}
	for _, si := range refreshShards {
		rec.RecordError(wr.RefreshTabletsByShard(ctx, si, []topodatapb.TabletType{servedType}, cells))
	}
	return rec.Error()
}
1108511
func migrateRecursively(src, dst walletdb.ReadWriteBucket,
	bucketKey []byte) error {
	// Within this bucket key, we'll migrate over, then delete each key.
	bucketToMigrate := src.NestedReadWriteBucket(bucketKey)
	newBucket, err := dst.CreateBucketIfNotExists(bucketKey)
	if err != nil {
		return err
	}
	err = bucketToMigrate.ForEach(func(k, v []byte) error {
		if nestedBucket := bucketToMigrate.
			NestedReadBucket(k); nestedBucket != nil {
			// We have a nested bucket, so recurse into it.
			return migrateRecursively(bucketToMigrate, newBucket, k)
		}

		if err := newBucket.Put(k, v); err != nil {
			return err
		}

		return bucketToMigrate.Delete(k)
	})
	if err != nil {
		return err
	}
	// Finally, we'll delete the bucket itself.
	if err := src.DeleteNestedBucket(bucketKey); err != nil {
		return err
	}
	return nil
}
236642
func (m *Migrate) Migrate() error {
	if err := m.createMigrationTableIfNotExists(); err != nil {
		return err
	}

	if m.initSchema != nil && m.isFirstRun() {
		return m.runInitSchema()
	}

	for _, migration := range m.migrations {
		if err := m.runMigration(migration); err != nil {
			return err
		}
	}
	return nil
}
813237
func Migrate(db *sql.DB, catalog string, configuration MigrationConfiguration) error {

	var err error
	if db == nil {
		return errs.Errorf("Database handle is nil\n")
	}

	m := GetMigrations(configuration)

	var tx *sql.Tx
	for nextVersion := int64(0); nextVersion < int64(len(m)) && err == nil; nextVersion++ {

		tx, err = db.Begin()
		if err != nil {
			return errs.Errorf("Failed to start transaction: %s\n", err)
		}

		err = MigrateToNextVersion(tx, &nextVersion, m, catalog)

		if err != nil {
			oldErr := err
			log.Info(nil, map[string]interface{}{
				"next_version": nextVersion,
				"migrations":   m,
				"err":          err,
			}, "Rolling back transaction due to: %v", err)

			if err = tx.Rollback(); err != nil {
				log.Error(nil, map[string]interface{}{
					"next_version": nextVersion,
					"migrations":   m,
					"err":          err,
				}, "error while rolling back transaction")
				return errs.Errorf("Error while rolling back transaction: %s\n", err)
			}
			return oldErr
		}

		if err = tx.Commit(); err != nil {
			log.Error(nil, map[string]interface{}{
				"migrations": m,
				"err":        err,
			}, "error during transaction commit: %v", err)
			return errs.Errorf("Error during transaction commit: %s\n", err)
		}

	}

	if err != nil {
		log.Error(nil, map[string]interface{}{
			"migrations": m,
			"err":        err,
		}, "migration failed with error: %v", err)
		return errs.Errorf("Migration failed with error: %s\n", err)
	}

	return nil
}