// NewPostgresMigrator returns a new Migrator instance that uses the underlying
// sql.DB connection to a postgres database to perform migrations. It will use
// Postgres's advisory locks to ensure that only 1 migration is run at a time.
174860
func NewPostgresMigrator(db *sql.DB) *Migrator {
	m := NewMigrator(db)
	m.Locker = newPostgresLocker(db)
	return m
}
1154736
func (mgr *SettingsManager) MigrateLegacyRepoSettings(settings *ArgoCDSettings) error {
	err := mgr.ensureSynced(false)
	if err != nil {
		return err
	}

	labelSelector := labels.NewSelector()
	req, err := labels.NewRequirement(common.LabelKeySecretType, selection.Equals, []string{"repository"})
	if err != nil {
		return err
	}
	labelSelector = labelSelector.Add(*req)
	repoSecrets, err := mgr.secrets.Secrets(mgr.namespace).List(labelSelector)
	if err != nil {
		return err
	}
	settings.Repositories = make([]RepoCredentials, len(repoSecrets))
	for i, s := range repoSecrets {
		_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Update(s)
		if err != nil {
			return err
		}
		cred := RepoCredentials{URL: string(s.Data["repository"])}
		if username, ok := s.Data["username"]; ok && string(username) != "" {
			cred.UsernameSecret = &apiv1.SecretKeySelector{
				LocalObjectReference: apiv1.LocalObjectReference{Name: s.Name},
				Key:                  "username",
			}
		}
		if password, ok := s.Data["password"]; ok && string(password) != "" {
			cred.PasswordSecret = &apiv1.SecretKeySelector{
				LocalObjectReference: apiv1.LocalObjectReference{Name: s.Name},
				Key:                  "password",
			}
		}
		if sshPrivateKey, ok := s.Data["sshPrivateKey"]; ok && string(sshPrivateKey) != "" {
			cred.SSHPrivateKeySecret = &apiv1.SecretKeySelector{
				LocalObjectReference: apiv1.LocalObjectReference{Name: s.Name},
				Key:                  "sshPrivateKey",
			}
		}
		settings.Repositories[i] = cred
	}
	return nil
}
242879
func NewPostLock() echo.HandlerFunc {

	// swagger:route POST /me/posts/{pid}/locks me post vote NewMePostLock
	//
	// Adds a new lock on the current post
	//
	// Consumes:
	// - application/json
	//
	//	Produces:
	//	- application/json
	//
	//	Security:
	//		oauth: profile_messages:write
	//
	//	Responses:
	//		default: MePostsPidLocks

	return func(c echo.Context) error {
		return user.NewPostLock()(c)
	}
}
944257
func NewIDGenerator(opts ...IDGeneratorOp) *IDGenerator {
	gen := &IDGenerator{}
	for _, f := range opts {
		f(gen)
	}
	if gen.Generator == nil {
		gen.Generator = snowflake.New(rand.Intn(1023))
	}
	return gen
}
287166
func NewIDGenerator() *IDGenerator {
	g := new(IDGenerator)
	_, err := rand.Read(g.seed[:])
	if err != nil {
		panic(err)
	}
	return g
}
1054493
func NewGRPCLogger(l *zap.Logger) *zapgrpc.Logger {
	l = l.WithOptions(
		zap.AddCaller(),
		zap.AddCallerSkip(3),
	)
	return zapgrpc.NewLogger(l, zapgrpc.WithDebug())
}
805082
func NewPostgresDataStore(routeType string, pgx *pgx.ConnPool) *pgDataStore {
	tableName := ""
	switch routeType {
	case routeTypeHTTP:
		tableName = tableNameHTTP
	case routeTypeTCP:
		tableName = tableNameTCP
	default:
		panic(fmt.Sprintf("unknown routeType: %q", routeType))
	}
	return &pgDataStore{
		pgx:       pgx,
		routeType: routeType,
		tableName: tableName,
	}
}
827992
func NewPostLurk() echo.HandlerFunc {

	// swagger:route POST /me/posts/{pid}/lurks me post vote NewMePostLurk
	//
	// Adds a new lurk on the current post
	//
	// Consumes:
	// - application/json
	//
	//	Produces:
	//	- application/json
	//
	//	Security:
	//		oauth: profile_messages:write
	//
	//	Responses:
	//		default: MePostsPidLurks

	return func(c echo.Context) error {
		return user.NewPostLurk()(c)
	}
}
964677
func NewDBFlagSet() *pflag.FlagSet {
	flags := &pflag.FlagSet{}

	// db subsection flags
	flags.BoolP("db.debug-mode", "", false, "Output database model SQL queries")
	flags.StringP("db.db", "", "", "The database software (postgres|mysql)")
	flags.StringP("db.dbname", "", "", "The database name to connect to")
	flags.StringP("db.host", "", "", "The database hostname, e.g localhost")
	flags.IntP("db.port", "", 0, "The database port")
	flags.StringP("db.user", "", "", "The database username")
	flags.StringP("db.pass", "", "", "The database password")
	flags.StringP("db.sslmode", "", "", "The database sslmode")
	flags.BoolP("db.enforce-migrations", "", true, "Throw error on app start if database is not using latest migration")

	return flags
}
675339
func (s *StreamMigrator) Migrate() {
	for _, st := range s.Streams {
		if s.isCreated(st) {
			Log.Printf("action=migrate at=create-stream stream=%s status=previously-created", LS(st.StreamName))
		} else {
			s.create(st)
			Log.Printf("action=migrate at=create-stream stream=%s status=created", LS(st.StreamName))
		}
		s.awaitActive(st.StreamName, s.Timeout)
	}
}
672432
func newMsgEventer(rw MsgReadWriter, feed *event.Feed, peerID enode.ID, proto string) *msgEventer {
	return &msgEventer{
		MsgReadWriter: rw,
		feed:          feed,
		peerID:        peerID,
		Protocol:      proto,
	}
}
1034101
func NewCmdMigrateAPIStorage(name, fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewMigrateAPIStorageOptions(streams)
	cmd := &cobra.Command{
		Use:     name, // TODO do something useful here
		Short:   "Update the stored version of API objects",
		Long:    internalMigrateStorageLong,
		Example: fmt.Sprintf(internalMigrateStorageExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			kcmdutil.CheckErr(o.Complete(f, cmd, args))
			kcmdutil.CheckErr(o.Validate())
			kcmdutil.CheckErr(o.Run())
		},
	}
	o.ResourceOptions.Bind(cmd)

	// opt-in to allow parallel execution since we know this command is goroutine safe
	// storage migration is IO bound so we make sure that we have enough workers to saturate the rate limiter
	o.Workers = 32 * runtime.NumCPU()
	// expose a flag to allow rate limiting the workers based on network bandwidth
	cmd.Flags().IntVar(&o.bandwidth, "bandwidth", o.bandwidth,
		"Average network bandwidth measured in megabits per second (Mbps) to use during storage migration.  Zero means no limit.  This flag is alpha and may change in the future.")

	// remove flags that do not make sense
	cmd.Flags().MarkDeprecated("confirm", "storage migration does not support dry run, this flag is ignored")
	cmd.Flags().MarkHidden("confirm")
	cmd.Flags().MarkDeprecated("output", "storage migration does not support dry run, this flag is ignored")
	cmd.Flags().MarkHidden("output")

	return cmd
}
321647
func (mg *Migration) CreateTableIfNotExists(structPtr interface{}) error {
	model := structPtrToModel(structPtr, true, nil)
	sql := mg.dialect.createTableSql(model, true)
	if mg.Log {
		fmt.Println(sql)
	}
	sqls := strings.Split(sql, ";")
	for _, v := range sqls {
		_, err := mg.db.Exec(v)
		if err != nil && !mg.dialect.catchMigrationError(err) {
			panic(err)
		}
	}
	columns := mg.dialect.columnsInTable(mg, model.table)
	if len(model.fields) > len(columns) {
		oldFields := []*modelField{}
		newFields := []*modelField{}
		for _, v := range model.fields {
			if _, ok := columns[v.name]; ok {
				oldFields = append(oldFields, v)
			} else {
				newFields = append(newFields, v)
			}
		}
		if len(oldFields) != len(columns) {
			panic("Column name has changed, rename column migration is not supported.")
		}
		for _, v := range newFields {
			mg.addColumn(model.table, v)
		}
	}
	var indexErr error
	for _, i := range model.indexes {
		indexErr = mg.CreateIndexIfNotExists(model.table, i.name, i.unique, i.columns...)
	}
	return indexErr
}
505933
func (t *TypesMigrator) Migrate() {
	if t.ActivityTypeMigrator == nil {
		t.ActivityTypeMigrator = new(ActivityTypeMigrator)
	}
	if t.DomainMigrator == nil {
		t.DomainMigrator = new(DomainMigrator)
	}
	if t.WorkflowTypeMigrator == nil {
		t.WorkflowTypeMigrator = new(WorkflowTypeMigrator)
	}
	if t.StreamMigrator == nil {
		t.StreamMigrator = new(StreamMigrator)
	}

	t.DomainMigrator.Migrate()
	ParallelMigrate(
		t.WorkflowTypeMigrator.Migrate,
		t.ActivityTypeMigrator.Migrate,
		t.StreamMigrator.Migrate,
	)
}
1067173
func (m *Migrator) MigrationTableExists() (bool, error) {
	row := m.DB.QueryRow(m.dbAdapter.SelectMigrationTableSql(), migrationTableName)
	var tableName string
	err := row.Scan(&tableName)
	if err == sql.ErrNoRows {
		m.logger.Print("Migrations table not found")
		return false, nil
	}
	if err != nil {
		m.logger.Printf("Error checking for migration table: %v", err)
		return false, err
	}
	m.logger.Print("Migrations table found")
	return true, nil
}
1133442
func postgresConnStr(cfg migrateConfig) string {
	connStrs := []string{
		fmt.Sprintf("user=%s", cfg.User),
	}

	if len(cfg.Pass) > 0 {
		connStrs = append(connStrs, fmt.Sprintf("password=%s", cfg.Pass))
	}

	connStrs = append(connStrs, []string{
		fmt.Sprintf("host=%s", cfg.Host),
		fmt.Sprintf("port=%d", cfg.Port),
		fmt.Sprintf("dbname=%s", cfg.DBName),
	}...)

	if len(cfg.SSLMode) > 0 {
		connStrs = append(connStrs, fmt.Sprintf("sslmode=%s", cfg.SSLMode))
	}

	return strings.Join(connStrs, " ")
}
743171
func (r *Registrar) ConsensusMigrationStart(context uint64) error {
	r.lock.Lock()
	defer r.lock.Unlock()

	for id, chain := range r.chains {
		if id != r.systemChannel.ChainID() && chain.MigrationStatus().IsPending() {
			return errors.Errorf("cannot start new consensus-type migration because standard channel %s, still pending", id)
		}
	}

	for _, chain := range r.chains {
		chain.MigrationStatus().SetStateContext(ab.ConsensusType_MIG_STATE_START, context)
	}
	logger.Debugf("Consensus-type migration: all standard channels marked as started, context=%d", context)

	return nil
}