// InitDB creates a new DB instance from a DBInfo containing the name of the
// file used to back the underlying sql database.
763585
func InitDB(dbInfo *DBInfo, shutdown func()) (*DB, error) {
	dbPath, err := filepath.Abs(dbInfo.FileName)
	if err != nil {
		return nil, err
	}

	// Ensures target DB-file has a parent folder
	parent := filepath.Dir(dbPath)
	err = os.MkdirAll(parent, 0755)
	if err != nil {
		return nil, err
	}

	// "shared-cache" mode has multiple connections share a single data and
	// schema cache. _busy_timeout helps prevent SQLITE_BUSY ("database is
	// locked") errors by sleeping for a certain amount of time when the
	// database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html.
	dbPath = dbPath + "?cache=shared&_busy_timeout=" + DBBusyTimeout
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil || db == nil {
		return nil, err
	}

	// Historically, SQLite did not handle concurrent writes internally,
	// necessitating a limitation of just 1 open connecton. With a busy_timeout
	// set, this is less important. With go-sqlite 1.10, this is not needed at
	// all since the library started compiling sqlite3 for
	// thread-safe/"serialized" operation (SQLITE_THREADSAFE=1). For details,
	// see https://sqlite.org/threadsafe.html and
	// https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized.
	// The change to go-sqlite3 is
	// github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e
	//
	// db.SetMaxOpenConns(1)

	// These are db-wide settings that persist for the entire session.
	_, err = db.Exec(SetCacheSizeSQL)
	if err != nil {
		log.Error("Error setting SQLite Cache size")
		return nil, err
	}
	_, err = db.Exec(SetSynchrounousOffSQL)
	if err != nil {
		log.Error("Error setting SQLite synchrounous off")
		return nil, err
	}

	rawCreateBlockSummaryStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	size INTEGER,
      	diff FLOAT,
      	sdiff FLOAT,
      	time INTEGER,
      	poolsize INTEGER,
      	poolval FLOAT,
      	poolavg FLOAT,
      	winners TEXT,
      	is_mainchain BOOL,
      	is_valid BOOL
    	);`

	createBlockSummaryStmt := fmt.Sprintf(rawCreateBlockSummaryStmt, TableNameSummaries)

	_, err = db.Exec(createBlockSummaryStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createBlockSummaryStmt)
		return nil, err
	}

	rawCreateStakeInfoExtendedStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	num_tickets INTEGER,
      	fee_min FLOAT, fee_max FLOAT, fee_mean FLOAT,
      	fee_med FLOAT, fee_std FLOAT,
      	sdiff FLOAT, window_num INTEGER, window_ind INTEGER,
      	pool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT,
      	winners TEXT
    	);`

	createStakeInfoExtendedStmt := fmt.Sprintf(rawCreateStakeInfoExtendedStmt, TableNameStakeInfo)

	_, err = db.Exec(createStakeInfoExtendedStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createStakeInfoExtendedStmt)
		return nil, err
	}

	if err = db.Ping(); err != nil {
		return nil, err
	}

	dataBase, err := NewDB(db, shutdown)
	if err != nil {
		return nil, err
	}

	// Table creation string are used in JustifyTableStructures
	// Eventually won't be needed.
	dataBase.rawCreateBlockSummaryStmt = rawCreateBlockSummaryStmt
	dataBase.rawCreateStakeInfoExtendedStmt = rawCreateStakeInfoExtendedStmt
	if err = dataBase.JustifyTableStructures(dbInfo); err != nil {
		return nil, err
	}

	return dataBase, err
}
600965
func (c *Client) AllDB(ctx context.Context) ([]chronograf.Database, error) {
	return c.showDatabases(ctx)
}
586817
func (b *stdBackend) init() {
	b.etmData = make(map[string]*stdMeasuringPoint)
	b.ssvData = make(map[string]*stdStaySetVariable)
	b.dsrData = make(map[string]DynamicStatusRetriever)
}
253354
func Init() {
	if *ldapAuthConfigFile == "" && *ldapAuthConfigString == "" {
		log.Infof("Not configuring AuthServerLdap because mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are empty")
		return
	}
	if *ldapAuthConfigFile != "" && *ldapAuthConfigString != "" {
		log.Infof("Both mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are non-empty, can only use one.")
		return
	}
	if *ldapAuthMethod != mysql.MysqlClearPassword && *ldapAuthMethod != mysql.MysqlDialog {
		log.Exitf("Invalid mysql_ldap_auth_method value: only support mysql_clear_password or dialog")
	}
	ldapAuthServer := &AuthServerLdap{
		Client:       &ClientImpl{},
		ServerConfig: ServerConfig{},
		Method:       *ldapAuthMethod,
	}

	data := []byte(*ldapAuthConfigString)
	if *ldapAuthConfigFile != "" {
		var err error
		data, err = ioutil.ReadFile(*ldapAuthConfigFile)
		if err != nil {
			log.Exitf("Failed to read mysql_ldap_auth_config_file: %v", err)
		}
	}
	if err := json.Unmarshal(data, ldapAuthServer); err != nil {
		log.Exitf("Error parsing AuthServerLdap config: %v", err)
	}
	mysql.RegisterAuthServerImpl("ldap", ldapAuthServer)
}
288174
func (s *SQLStore) Init(info *spb.ServerInfo) error {
	s.Lock()
	defer s.Unlock()
	count := 0
	r := s.db.QueryRow(sqlStmts[sqlHasServerInfoRow])
	if err := r.Scan(&count); err != nil && err != sql.ErrNoRows {
		return sqlStmtError(sqlHasServerInfoRow, err)
	}
	infoBytes, _ := info.Marshal()
	if count == 0 {
		if _, err := s.db.Exec(sqlStmts[sqlAddServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil {
			return sqlStmtError(sqlAddServerInfo, err)
		}
	} else {
		if _, err := s.db.Exec(sqlStmts[sqlUpdateServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil {
			return sqlStmtError(sqlUpdateServerInfo, err)
		}
	}
	return nil
}
1225926
func (s *Statement) Init(ctx context.Context, st storage.Store) error {
	for _, gn := range s.graphNames {
		g, err := st.Graph(ctx, gn)
		if err != nil {
			return err
		}
		s.graphs = append(s.graphs, g)
	}
	for _, ign := range s.inputGraphNames {
		ig, err := st.Graph(ctx, ign)
		if err != nil {
			return err
		}
		s.inputGraphs = append(s.inputGraphs, ig)
	}
	for _, ogn := range s.outputGraphNames {
		og, err := st.Graph(ctx, ogn)
		if err != nil {
			return err
		}
		s.outputGraphs = append(s.outputGraphs, og)
	}
	return nil
}
1179472
func (d *Databases) AllDB(ctx context.Context) ([]chronograf.Database, error) {
	return d.AllDBF(ctx)
}
882811
func InitWiredDB(dbInfo *DBInfo, stakeDB *stakedb.StakeDatabase, statusC chan uint32, cl *rpcclient.Client,
	p *chaincfg.Params, shutdown func()) (*WiredDB, error) {
	db, err := InitDB(dbInfo, shutdown)
	if err != nil {
		return nil, err
	}

	return newWiredDB(db, stakeDB, statusC, cl, p), nil
}
379544
func ConnectDB(name string) (*sqlx.DB, error) {
	if len(name) == 0 {
		dir, err := os.Getwd()
		if err != nil {
			return nil, err
		}
		name = filepath.Base(dir)
	}
	dbConnStr := DBConnectionString(name)
	log.Debug("connecting to db")
	return sqlx.Connect("postgres", dbConnStr)
}
21801
func (m *DB) Init(ctx context.Context) error {
	// errSkip is used when no migration or version needs to be written
	// to the database and the transaction can be immediately rolled
	// back rather than performing a much slower and unnecessary commit.
	var errSkip = errors.New("skip update")

	err := m.db.Update(func(tx *bolt.Tx) error {
		var (
			// current schema and version
			schema  = "v0"
			version = 0
		)

		// i represents the index of the first migration
		// which must be run to get the database up to date.
		// The migration's version will be checked in reverse
		// order, decrementing i for each migration which
		// represents a version newer than the current
		// database version
		i := len(migrations)

		for ; i > 0; i-- {
			migration := migrations[i-1]

			bkt := tx.Bucket([]byte(migration.schema))
			if bkt == nil {
				// Hasn't encountered another schema, go to next migration
				if schema == "v0" {
					continue
				}
				break
			}
			if schema == "v0" {
				schema = migration.schema
				vb := bkt.Get(bucketKeyDBVersion)
				if vb != nil {
					v, _ := binary.Varint(vb)
					version = int(v)
				}
			}

			if version >= migration.version {
				break
			}
		}

		// Previous version fo database found
		if schema != "v0" {
			updates := migrations[i:]

			// No migration updates, return immediately
			if len(updates) == 0 {
				return errSkip
			}

			for _, m := range updates {
				t0 := time.Now()
				if err := m.migrate(tx); err != nil {
					return errors.Wrapf(err, "failed to migrate to %s.%d", m.schema, m.version)
				}
				log.G(ctx).WithField("d", time.Since(t0)).Debugf("finished database migration to %s.%d", m.schema, m.version)
			}
		}

		bkt, err := tx.CreateBucketIfNotExists(bucketKeyVersion)
		if err != nil {
			return err
		}

		versionEncoded, err := encodeInt(dbVersion)
		if err != nil {
			return err
		}

		return bkt.Put(bucketKeyDBVersion, versionEncoded)
	})
	if err == errSkip {
		err = nil
	}
	return err
}
346412
func initDB(ldb *leveldb.DB) error {
	// The starting block file write cursor location is file num 0, offset
	// 0.
	batch := new(leveldb.Batch)
	batch.Put(bucketizedKey(metadataBucketID, writeLocKeyName),
		serializeWriteRow(0, 0))

	// Create block index bucket and set the current bucket id.
	//
	// NOTE: Since buckets are virtualized through the use of prefixes,
	// there is no need to store the bucket index data for the metadata
	// bucket in the database.  However, the first bucket ID to use does
	// need to account for it to ensure there are no key collisions.
	batch.Put(bucketIndexKey(metadataBucketID, blockIdxBucketName),
		blockIdxBucketID[:])
	batch.Put(curBucketIDKeyName, blockIdxBucketID[:])

	// Write everything as a single batch.
	if err := ldb.Write(batch, nil); err != nil {
		str := fmt.Sprintf("failed to initialize metadata database: %v",
			err)
		return convertErr(str, err)
	}

	return nil
}
1223566
func (m *MDBStore) initialize() error {
	// Allow up to 2 sub-dbs
	if err := m.env.SetMaxDBs(mdb.DBI(2)); err != nil {
		return err
	}

	// Increase the maximum map size
	if err := m.env.SetMapSize(m.maxSize); err != nil {
		return err
	}

	// Open the DB
	if err := m.env.Open(m.path, mdb.NOTLS, 0755); err != nil {
		return err
	}

	// Create all the tables
	tx, _, err := m.startTxn(false, dbLogs, dbConf)
	if err != nil {
		tx.Abort()
		return err
	}
	return tx.Commit()
}
1360121
func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
	c := s.clone()
	if result := c.First(out, where...); result.Error != nil {
		if !result.RecordNotFound() {
			return result
		}
		c.NewScope(out).inlineCondition(where...).initialize()
	} else {
		c.NewScope(out).updatedAttrsWithValues(c.search.assignAttrs)
	}
	return c
}
846662
func InitDB(path string) error {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		return err
	}
	defer db.Close()
	for _, tableSQL := range SQLCreateTables() {
		if _, err := db.Exec(tableSQL); err != nil {
			return err
		}
	}

	// Use Write Ahead Logging which improves SQLite concurrency.
	// Requires SQLite >= 3.7.0
	if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
		return err
	}

	// Check if the WAL mode was set correctly
	var journalMode string
	if err = db.QueryRow("PRAGMA journal_mode").Scan(&journalMode); err != nil {
		log.Fatalf("Unable to determine sqlite3 journal_mode: %v", err)
	}
	if journalMode != "wal" {
		log.Fatal("SQLite Write Ahead Logging (introducted in v3.7.0) is required. See http://perkeep.org/issue/114")
	}

	_, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))
	return err
}
1315911
func NewDb(db *sql.DB, driverName string) *DB {
	return &DB{DB: db, driverName: driverName, Mapper: mapper()}
}
98230
func (tsv *TabletServer) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error {
	tsv.mu.Lock()
	defer tsv.mu.Unlock()
	if tsv.state != StateNotConnected {
		return vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "InitDBConfig failed, current state: %s", stateName[tsv.state])
	}
	tsv.target = target
	tsv.dbconfigs = dbcfgs

	tsv.se.InitDBConfig(tsv.dbconfigs)
	tsv.qe.InitDBConfig(tsv.dbconfigs)
	tsv.teCtrl.InitDBConfig(tsv.dbconfigs)
	tsv.hw.InitDBConfig(tsv.dbconfigs)
	tsv.hr.InitDBConfig(tsv.dbconfigs)
	tsv.messager.InitDBConfig(tsv.dbconfigs)
	tsv.watcher.InitDBConfig(tsv.dbconfigs)
	tsv.vstreamer.InitDBConfig(tsv.dbconfigs)
	return nil
}
149006
func (mysqld *Mysqld) Init(ctx context.Context, cnf *Mycnf, initDBSQLFile string) error {
	log.Infof("mysqlctl.Init")
	err := mysqld.InitConfig(cnf)
	if err != nil {
		log.Errorf("%s", err.Error())
		return err
	}
	// Install data dir.
	if err = mysqld.installDataDir(cnf); err != nil {
		return err
	}

	// Start mysqld. We do not use Start, as we have to wait using
	// the root user.
	if err = mysqld.startNoWait(ctx, cnf); err != nil {
		log.Errorf("failed starting mysqld (check mysql error log %v for more info): %v", cnf.ErrorLogPath, err)
		return err
	}

	// Wait for mysqld to be ready, using root credentials, as no
	// user is created yet.
	params := &mysql.ConnParams{
		Uname:      "root",
		Charset:    "utf8",
		UnixSocket: cnf.SocketFile,
	}
	if err = mysqld.wait(ctx, cnf, params); err != nil {
		log.Errorf("failed starting mysqld in time (check mysyql error log %v for more info): %v", cnf.ErrorLogPath, err)
		return err
	}

	// Run initial SQL file.
	sqlFile, err := os.Open(initDBSQLFile)
	if err != nil {
		return fmt.Errorf("can't open init_db_sql_file (%v): %v", initDBSQLFile, err)
	}
	defer sqlFile.Close()
	if err := mysqld.executeMysqlScript(params, sqlFile); err != nil {
		return fmt.Errorf("can't run init_db_sql_file (%v): %v", initDBSQLFile, err)
	}

	return nil
}