// Copy writes a copy of the database to the provided writer.  This call will
// start a read-only transaction to perform all operations.
//
// This function is part of the walletdb.Db interface implementation.
552152
func (db *db) Copy(w io.Writer) error {
	return convertErr((*bbolt.DB)(db).View(func(tx *bbolt.Tx) error {
		return tx.Copy(w)
	}))
}
602314
func (b *storageDBWrapper) Copy() *storageDBWrapper {
	session := b.session.Copy()

	coll := b.metaColl.With(session)
	db := coll.Database
	txnRunner := jujutxn.NewRunner(jujutxn.RunnerParams{
		Database:               db,
		ServerSideTransactions: false,
	})
	dbWrap := storageDBWrapper{
		session:   session,
		db:        db,
		metaColl:  coll,
		txnRunner: txnRunner,
		modelUUID: b.modelUUID,
	}
	return &dbWrap
}
778859
func (v *Vibranium) Copy(opts *pb.CopyOptions, stream pb.CoreRPC_CopyServer) error {
	v.taskAdd("Copy", true)
	defer v.taskDone("Copy", true)

	copyOpts := toCoreCopyOptions(opts)
	ch, err := v.cluster.Copy(stream.Context(), copyOpts)
	if err != nil {
		return err
	}

	//4K buffer
	bsize := 4 * 1024

	for m := range ch {
		var copyError string
		if m.Error != nil {
			copyError = fmt.Sprintf("%v", m.Error)
			if err := stream.Send(&pb.CopyMessage{
				Id:     m.ID,
				Status: m.Status,
				Name:   m.Name,
				Path:   m.Path,
				Error:  copyError,
				Data:   []byte{},
			}); err != nil {
				v.logUnsentMessages("Copy", m)
			}
			continue
		}

		r, w := io.Pipe()
		go func() {
			defer w.Close()
			defer m.Data.Close()
			buffer := bufio.NewWriterSize(w, bsize)
			defer buffer.Flush()
			gw := gzip.NewWriter(buffer)
			defer gw.Close()
			_, err = io.Copy(gw, m.Data)
			if err != nil {
				log.Errorf("[Copy] Error during copy resp: %v", err)
			}
		}()

		for {
			p := make([]byte, bsize)
			n, err := r.Read(p)
			if err != nil {
				if err != io.EOF {
					log.Errorf("[Copy] Error during buffer resp: %v", err)
				}
				break
			}
			if err = stream.Send(&pb.CopyMessage{
				Id:     m.ID,
				Status: m.Status,
				Name:   m.Name,
				Path:   m.Path,
				Error:  copyError,
				Data:   p[:n],
			}); err != nil {
				v.logUnsentMessages("Copy", m)
			}
		}
	}
	return nil
}
180935
func (db *DB) Clone() *DB {
	db2 := &DB{
		driverName:  db.driverName,
		sqlDB:       db.sqlDB,
		FieldMapper: db.FieldMapper,
		PerfFunc:    db.PerfFunc,
		LogFunc:     db.LogFunc,
	}
	db2.Builder = db2.newBuilder(db.sqlDB)
	return db2
}
265899
func (c *Carbon) Copy() *Carbon {
	return create(c.Year(), c.Month(), c.Day(), c.Hour(), c.Minute(), c.Second(), c.Nanosecond(), c.Location())
}
507994
func (m *MockDatabase) Copy() (state.Database, state.SessionCloser) {
	ret := m.ctrl.Call(m, "Copy")
	ret0, _ := ret[0].(state.Database)
	ret1, _ := ret[1].(state.SessionCloser)
	return ret0, ret1
}
1197237
func (entry *Entry) Copy() (*Entry, error) {
	var cdst C.acl_entry_t
	rv, _ := C.acl_copy_entry(cdst, entry.e)
	if rv < 0 {
		return nil, fmt.Errorf("unable to copy entry")
	}
	return &Entry{cdst}, nil
}
1267073
func (l Players) Copy() map[string]*player.Player {
	lc := make(map[string]*player.Player)
	l.RLock()
	for _, p := range l.list {
		lc[p.Name] = p
	}
	l.RUnlock()
	return lc
}
1103622
func (scw *LegacySplitCloneWorker) copy(ctx context.Context) error {
	scw.setState(WorkerStateCloneOffline)
	start := time.Now()
	defer func() {
		statsStateDurationsNs.Set(string(WorkerStateCloneOffline), time.Since(start).Nanoseconds())
	}()

	// get source schema from the first shard
	// TODO(alainjobart): for now, we assume the schema is compatible
	// on all source shards. Furthermore, we estimate the number of rows
	// in each source shard for each table to be about the same
	// (rowCount is used to estimate an ETA)
	shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
	sourceSchemaDefinition, err := scw.wr.GetSchema(shortCtx, scw.sourceAliases[0], nil, scw.excludeTables, false /* includeViews */)
	cancel()
	if err != nil {
		return vterrors.Wrapf(err, "cannot get schema from source %v", topoproto.TabletAliasString(scw.sourceAliases[0]))
	}
	if len(sourceSchemaDefinition.TableDefinitions) == 0 {
		return fmt.Errorf("no tables matching the table filter in tablet %v", topoproto.TabletAliasString(scw.sourceAliases[0]))
	}
	for _, td := range sourceSchemaDefinition.TableDefinitions {
		if len(td.Columns) == 0 {
			return fmt.Errorf("schema for table %v has no columns", td.Name)
		}
	}
	scw.wr.Logger().Infof("Source tablet 0 has %v tables to copy", len(sourceSchemaDefinition.TableDefinitions))
	scw.tableStatusList.initialize(sourceSchemaDefinition)

	// In parallel, setup the channels to send SQL data chunks to for each destination tablet:
	//
	// mu protects the context for cancelation, and firstError
	mu := sync.Mutex{}
	var firstError error

	ctx, cancelCopy := context.WithCancel(ctx)
	processError := func(format string, args ...interface{}) {
		scw.wr.Logger().Errorf(format, args...)
		mu.Lock()
		if firstError == nil {
			firstError = fmt.Errorf(format, args...)
			cancelCopy()
		}
		mu.Unlock()
	}

	insertChannels := make([]chan string, len(scw.destinationShards))
	destinationWaitGroup := sync.WaitGroup{}
	for shardIndex, si := range scw.destinationShards {
		// we create one channel per destination tablet.  It
		// is sized to have a buffer of a maximum of
		// destinationWriterCount * 2 items, to hopefully
		// always have data. We then have
		// destinationWriterCount go routines reading from it.
		insertChannels[shardIndex] = make(chan string, scw.destinationWriterCount*2)

		go func(keyspace, shard string, insertChannel chan string) {
			for j := 0; j < scw.destinationWriterCount; j++ {
				destinationWaitGroup.Add(1)
				go func(threadID int) {
					defer destinationWaitGroup.Done()

					keyspaceAndShard := topoproto.KeyspaceShardString(keyspace, shard)
					throttler := scw.destinationThrottlers[keyspaceAndShard]
					defer throttler.ThreadFinished(threadID)

					executor := newExecutor(scw.wr, scw.tsc, throttler, keyspace, shard, threadID)
					if err := executor.fetchLoop(ctx, insertChannel); err != nil {
						processError("executer.FetchLoop failed: %v", err)
					}
				}(j)
			}
		}(si.Keyspace(), si.ShardName(), insertChannels[shardIndex])
	}

	// read the vschema if needed
	var keyspaceSchema *vindexes.KeyspaceSchema
	if *useV3ReshardingMode {
		kschema, err := scw.wr.TopoServer().GetVSchema(ctx, scw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot load VSchema for keyspace %v", scw.keyspace)
		}
		if kschema == nil {
			return fmt.Errorf("no VSchema for keyspace %v", scw.keyspace)
		}

		keyspaceSchema, err = vindexes.BuildKeyspaceSchema(kschema, scw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot build vschema for keyspace %v", scw.keyspace)
		}
	}

	// Now for each table, read data chunks and send them to all
	// insertChannels
	sourceWaitGroup := sync.WaitGroup{}
	for shardIndex := range scw.sourceShards {
		sema := sync2.NewSemaphore(scw.sourceReaderCount, 0)
		for tableIndex, td := range sourceSchemaDefinition.TableDefinitions {
			var keyResolver keyspaceIDResolver
			if *useV3ReshardingMode {
				keyResolver, err = newV3ResolverFromTableDefinition(keyspaceSchema, td)
				if err != nil {
					return vterrors.Wrapf(err, "cannot resolve v3 sharding keys for keyspace %v", scw.keyspace)
				}
			} else {
				keyResolver, err = newV2Resolver(scw.keyspaceInfo, td)
				if err != nil {
					return vterrors.Wrapf(err, "cannot resolve sharding keys for keyspace %v", scw.keyspace)
				}
			}
			rowSplitter := NewRowSplitter(scw.destinationShards, keyResolver)

			chunks, err := generateChunks(ctx, scw.wr, scw.sourceTablets[shardIndex], td, scw.sourceReaderCount, defaultMinRowsPerChunk)
			if err != nil {
				return err
			}
			scw.tableStatusList.setThreadCount(tableIndex, len(chunks)-1)

			for _, c := range chunks {
				sourceWaitGroup.Add(1)
				go func(td *tabletmanagerdatapb.TableDefinition, shardIndex, tableIndex int, chunk chunk) {
					defer sourceWaitGroup.Done()

					sema.Acquire()
					defer sema.Release()

					scw.tableStatusList.threadStarted(tableIndex)
					defer scw.tableStatusList.threadDone(tableIndex)

					// Start streaming from the source tablets.
					tp := newSingleTabletProvider(ctx, scw.wr.TopoServer(), scw.sourceAliases[shardIndex])
					rr, err := NewRestartableResultReader(ctx, scw.wr.Logger(), tp, td, chunk, false /* allowMultipleRetries */)
					if err != nil {
						processError("NewRestartableResultReader failed: %v", err)
						return
					}
					defer rr.Close(ctx)

					// process the data
					dbNames := make([]string, len(scw.destinationShards))
					for i, si := range scw.destinationShards {
						keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName())
						dbNames[i] = scw.destinationDbNames[keyspaceAndShard]
					}
					if err := scw.processData(ctx, dbNames, td, tableIndex, rr, rowSplitter, insertChannels, scw.destinationPackCount); err != nil {
						processError("processData failed: %v", err)
					}
				}(td, shardIndex, tableIndex, c)
			}
		}
	}
	sourceWaitGroup.Wait()

	for shardIndex := range scw.destinationShards {
		close(insertChannels[shardIndex])
	}
	destinationWaitGroup.Wait()
	if firstError != nil {
		return firstError
	}

	sourcePositions := make([]string, len(scw.sourceShards))
	// get the current position from the sources
	for shardIndex := range scw.sourceShards {
		shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
		status, err := scw.wr.TabletManagerClient().SlaveStatus(shortCtx, scw.sourceTablets[shardIndex])
		cancel()
		if err != nil {
			return err
		}
		sourcePositions[shardIndex] = status.Position
	}

	for _, si := range scw.destinationShards {
		keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName())
		dbName := scw.destinationDbNames[keyspaceAndShard]

		destinationWaitGroup.Add(1)
		go func(keyspace, shard string, kr *topodatapb.KeyRange) {
			defer destinationWaitGroup.Done()
			scw.wr.Logger().Infof("Making and populating vreplication table for %v/%v", keyspace, shard)

			exc := newExecutor(scw.wr, scw.tsc, nil, keyspace, shard, 0)
			for shardIndex, src := range scw.sourceShards {
				bls := &binlogdatapb.BinlogSource{
					Keyspace: src.Keyspace(),
					Shard:    src.ShardName(),
					KeyRange: kr,
				}
				qr, err := exc.vreplicationExec(ctx, binlogplayer.CreateVReplication("LegacySplitClone", bls, sourcePositions[shardIndex], scw.maxTPS, throttler.ReplicationLagModuleDisabled, time.Now().Unix(), dbName))
				if err != nil {
					processError("vreplication queries failed: %v", err)
					break
				} else {
					scw.wr.Logger().Infof("Created replication for tablet %v/%v: %v, db: %v, pos: %v, uid: %v", keyspace, shard, bls, dbName, sourcePositions[shardIndex], uint32(qr.InsertID))
				}
				if err := scw.wr.SourceShardAdd(ctx, keyspace, shard, uint32(qr.InsertID), src.Keyspace(), src.ShardName(), src.Shard.KeyRange, nil); err != nil {
					processError("could not add source shard: %v", err)
					break
				}
			}
			// refreshState will cause the destination to become non-serving because
			// it's now participating in the resharding workflow.
			if err := exc.refreshState(ctx); err != nil {
				processError("RefreshState failed on tablet %v/%v: %v", keyspace, shard, err)
			}
		}(si.Keyspace(), si.ShardName(), si.KeyRange)
	}
	destinationWaitGroup.Wait()
	return firstError
}
223528
func (result *Result) Copy() *Result {
	out := &Result{
		InsertID:     result.InsertID,
		RowsAffected: result.RowsAffected,
	}
	if result.Fields != nil {
		fieldsp := make([]*querypb.Field, len(result.Fields))
		fields := make([]querypb.Field, len(result.Fields))
		for i, f := range result.Fields {
			fields[i] = *f
			fieldsp[i] = &fields[i]
		}
		out.Fields = fieldsp
	}
	if result.Rows != nil {
		out.Rows = make([][]Value, 0, len(result.Rows))
		for _, r := range result.Rows {
			out.Rows = append(out.Rows, CopyRow(r))
		}
	}
	if result.Extras != nil {
		out.Extras = &querypb.ResultExtras{
			Fresher: result.Extras.Fresher,
		}
		if result.Extras.EventToken != nil {
			out.Extras.EventToken = &querypb.EventToken{
				Timestamp: result.Extras.EventToken.Timestamp,
				Shard:     result.Extras.EventToken.Shard,
				Position:  result.Extras.EventToken.Position,
			}
		}
	}
	return out
}
984018
func (s *Node) Copy() *Node {
	localCopy := deepcopy.Copy(*s)
	nodeCopy := localCopy.(Node)
	return &nodeCopy
}
228132
func Copy(s *Snapshot) *Snapshot {
	cs := *(s.ChangeSet)

	return &Snapshot{
		ChangeSet: &cs,
		Version:   s.Version,
	}
}
1153637
func Copy(dst io.Writer, src io.Reader) (written int64, err error) {
	buf := BufioReader32KPool.Get(src)
	written, err = io.Copy(dst, buf)
	BufioReader32KPool.Put(buf)
	return
}
326521
func (d *EphemeralDisk) Copy() *EphemeralDisk {
	ld := new(EphemeralDisk)
	*ld = *d
	return ld
}
621185
func (s *DB) clone() *DB {
	db := &DB{
		db:                s.db,
		parent:            s.parent,
		logger:            s.logger,
		logMode:           s.logMode,
		Value:             s.Value,
		Error:             s.Error,
		blockGlobalUpdate: s.blockGlobalUpdate,
		dialect:           newDialect(s.dialect.GetName(), s.db),
	}

	s.values.Range(func(k, v interface{}) bool {
		db.values.Store(k, v)
		return true
	})

	if s.search == nil {
		db.search = &search{limit: -1, offset: -1}
	} else {
		db.search = s.search.clone()
	}

	db.search.db = db
	return db
}
727722
func (a *ActiveDevice) Copy(m MetaContext, src *ActiveDevice) error {

	// Take a consistent snapshot of the src device. Be careful not to hold
	// locks on both devices at once.
	src.Lock()
	uv := src.uv
	deviceID := src.deviceID
	sigKey := src.signingKey
	encKey := src.encryptionKey
	name := src.deviceName
	ctime := src.deviceCtime
	src.Unlock()

	return a.Set(m, uv, deviceID, sigKey, encKey, name, ctime)
}
349828
func (g *Generator) Copy(n interface{}) error {
	switch v := n.(type) {
	case *ast.TypeSpec:
		return g.CopyType(v)
	case *ast.ValueSpec:
		return g.CopyVal(v)
	}

	return fmt.Errorf("can't copy variable of type: %T", n)
}