// NewDB creates a new DB instance with pre-generated sql statements from an
// existing sql.DB. Use InitDB to create a new DB without having a sql.DB.
764694
func NewDB(db *sql.DB, shutdown func()) (*DB, error) {
	d := DB{
		DB:                db,
		dbSummaryHeight:   -1,
		dbStakeInfoHeight: -1,
		shutdownDcrdata:   shutdown,
	}

	// Block summary insert
	d.insertBlockSQL = fmt.Sprintf(`
        INSERT OR REPLACE INTO %s(
			hash, height, size,
			diff, sdiff, time,
			poolsize, poolval, poolavg,
			winners, is_mainchain, is_valid
        ) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`, TableNameSummaries)

	// Stake info insert
	d.insertStakeInfoExtendedSQL = fmt.Sprintf(`
        INSERT OR REPLACE INTO %s(
            hash, height, num_tickets, fee_min, fee_max, fee_mean, fee_med, fee_std,
			sdiff, window_num, window_ind, pool_size, pool_val, pool_valavg, winners
        ) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`, TableNameStakeInfo)

	// Ticket pool queries (block summaries table)
	d.getPoolSQL = fmt.Sprintf(`SELECT hash, poolsize, poolval, poolavg, winners`+
		` FROM %s WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.getPoolByHashSQL = fmt.Sprintf(`SELECT height, poolsize, poolval, poolavg, winners`+
		` FROM %s WHERE hash = ?`, TableNameSummaries)
	d.getPoolRangeSQL = fmt.Sprintf(`SELECT height, hash, poolsize, poolval, poolavg, winners `+
		`FROM %s WHERE height BETWEEN ? AND ? AND is_mainchain = 1`, TableNameSummaries)
	d.getPoolValSizeRangeSQL = fmt.Sprintf(`SELECT poolsize, poolval `+
		`FROM %s WHERE height BETWEEN ? AND ? AND is_mainchain = 1`, TableNameSummaries)
	d.getAllPoolValSize = fmt.Sprintf(`SELECT poolsize, poolval, time `+
		`FROM %s WHERE is_mainchain = 1 AND height > $1`,
		TableNameSummaries)
	d.getWinnersSQL = fmt.Sprintf(`SELECT hash, winners FROM %s
		WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.getWinnersByHashSQL = fmt.Sprintf(`SELECT height, winners FROM %s WHERE hash = ?`,
		TableNameSummaries)

	d.getSDiffSQL = fmt.Sprintf(`SELECT sdiff FROM %s
		WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.getDifficulty = fmt.Sprintf(`SELECT diff FROM %s
		WHERE time >= ? ORDER BY time LIMIT 1`, TableNameSummaries)
	d.getSDiffRangeSQL = fmt.Sprintf(`SELECT sdiff FROM %s
		WHERE height BETWEEN ? AND ?`, TableNameSummaries)

	// General block summaries table queries
	d.getBlockSQL = fmt.Sprintf(`SELECT * FROM %s
		WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.getBlockByHashSQL = fmt.Sprintf(`SELECT * FROM %s
		WHERE hash = ?`, TableNameSummaries)
	d.getBestBlockSQL = fmt.Sprintf(`SELECT * FROM %s
		WHERE is_mainchain = 1
		ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)

	d.getBlockSizeSQL = fmt.Sprintf(`SELECT size FROM %s
		WHERE is_mainchain = 1 AND height = ?`,
		TableNameSummaries)
	d.getBlockSizeRangeSQL = fmt.Sprintf(`SELECT size FROM %s
		WHERE is_mainchain = 1 AND height BETWEEN ? AND ?`,
		TableNameSummaries)
	d.getBlockByTimeRangeSQL = fmt.Sprintf(`SELECT * FROM %s
		WHERE is_mainchain = 1 AND time BETWEEN ? AND ?
		ORDER BY time LIMIT ?`,
		TableNameSummaries)
	d.getBlockByTimeSQL = fmt.Sprintf(`SELECT * FROM %s WHERE time = ?`,
		TableNameSummaries)

	d.getBestBlockHashSQL = fmt.Sprintf(`SELECT hash FROM %s WHERE is_mainchain = 1
		ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
	d.getBestBlockHeightSQL = fmt.Sprintf(`SELECT height FROM %s WHERE is_mainchain = 1
		ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)

	d.getHighestBlockHashSQL = fmt.Sprintf(`SELECT hash FROM %s
		ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)
	d.getHighestBlockHeightSQL = fmt.Sprintf(`SELECT height FROM %s
		ORDER BY height DESC LIMIT 0, 1`, TableNameSummaries)

	d.getBlockHashSQL = fmt.Sprintf(`SELECT hash FROM %s
		WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.getBlockHeightSQL = fmt.Sprintf(`SELECT height FROM %s
		WHERE hash = ?`, TableNameSummaries)
	d.getMainchainStatusSQL = fmt.Sprintf(`SELECT is_mainchain FROM %s
		WHERE hash = ?`, TableNameSummaries)

	d.invalidateBlockSQL = fmt.Sprintf(`UPDATE %s SET is_valid = 0
		WHERE hash = ?`, TableNameSummaries)
	d.setHeightToSideChainSQL = fmt.Sprintf(`UPDATE %s SET is_mainchain = 0
		WHERE height = ?`, TableNameSummaries)

	d.deleteBlockByHashSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE hash = ?`, TableNameSummaries)
	d.deleteBlockByHeightMainChainSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE height = ? AND is_mainchain = 1`, TableNameSummaries)
	d.deleteBlocksAboveHeightSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE height > ?`, TableNameSummaries)

	// Stake info table queries
	d.getStakeInfoExtendedByHeightSQL = fmt.Sprintf(`SELECT %[1]s.* FROM %[1]s
		JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		WHERE %[2]s.is_mainchain = 1 AND %[1]s.height = ?`,
		TableNameStakeInfo, TableNameSummaries)
	d.getStakeInfoExtendedByHashSQL = fmt.Sprintf(`SELECT * FROM %s WHERE hash = ?`,
		TableNameStakeInfo)
	d.getStakeInfoWinnersSQL = fmt.Sprintf(`SELECT %[1]s.winners FROM %[1]s
		JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		WHERE %[1]s.height = ?`,
		TableNameStakeInfo, TableNameSummaries)
	d.getStakeInfoWinnersByHashSQL = fmt.Sprintf(`SELECT %[1]s.winners FROM %[1]s
		JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		WHERE %[1]s.hash = ?`,
		TableNameStakeInfo, TableNameSummaries)
	d.getLatestStakeInfoExtendedSQL = fmt.Sprintf(
		`SELECT %[1]s.* FROM %[1]s
		 JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		 WHERE %[2]s.is_mainchain = 1
		 ORDER BY %[1]s.height DESC LIMIT 0, 1`,
		TableNameStakeInfo, TableNameSummaries)
	d.getBestStakeHeightSQL = fmt.Sprintf(
		`SELECT %[1]s.height FROM %[1]s
		 JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		 WHERE %[2]s.is_mainchain = 1
		 ORDER BY %[1]s.height DESC LIMIT 0, 1`,
		TableNameStakeInfo, TableNameSummaries)
	d.getHighestStakeHeightSQL = fmt.Sprintf(
		`SELECT height FROM %s
		 ORDER BY height DESC LIMIT 0, 1`,
		TableNameStakeInfo)

	d.getAllFeeInfoPerBlock = fmt.Sprintf(
		`SELECT %[1]s.height, fee_med FROM %[1]s
		 JOIN %[2]s ON %[1]s.hash = %[2]s.hash
		 WHERE %[1]s.height > $1
		 AND %[2]s.is_mainchain=1
		 ORDER BY %[1]s.height;`,
		TableNameStakeInfo, TableNameSummaries)

	d.deleteStakeInfoByHashSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE hash = ?`, TableNameStakeInfo)
	d.deleteStakeInfoByHeightMainChainSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE hash IN (
			SELECT hash FROM %s
			WHERE height = ? AND is_mainchain = 1
		)`, TableNameStakeInfo, TableNameSummaries)
	d.deleteStakeInfoAboveHeightSQL = fmt.Sprintf(`DELETE FROM %s
		WHERE height > ?`, TableNameStakeInfo)

	// Table metadata
	d.getBlockSummaryTableInfo = fmt.Sprintf(`PRAGMA table_info(%s);`, TableNameSummaries)
	d.getStakeInfoExtendedTableInfo = fmt.Sprintf(`PRAGMA table_info(%s);`, TableNameStakeInfo)

	// Attempt to retrieve the best mainchain block heights from both tables,
	// but fallback to the highest block if the tables have yet to be upgraded
	// with the is_mainchain column. Log the latter case.
	var err error
	noSuchColPrefix := "no such column: "
	if d.dbSummaryHeight, err = d.getBlockSummaryHeight(); err != nil {
		// If the table scheme lacks the is_mainchain column, and upgrade is
		// required. Fall back to querying without the is_mainchain condition.
		errStr := err.Error()
		ind := strings.LastIndex(errStr, noSuchColPrefix)
		if ind == -1 {
			return nil, fmt.Errorf("NewDB: %v", err)
		}
		// Try again without the mainchain constraint.
		if ind+len(noSuchColPrefix) < len(errStr) {
			log.Infof(`Block summary table missing column "%s". Table upgrade required.`,
				errStr[ind+len(noSuchColPrefix):])
		}
		d.dbSummaryHeight, err = d.getBlockSummaryHeightAnyChain()
		if err != nil {
			return nil, fmt.Errorf("NewDB: %v", err)
		}
	}
	if d.dbStakeInfoHeight, err = d.getStakeInfoHeight(); err != nil {
		// If the table scheme lacks the is_mainchain column, and upgrade is
		// required. Fall back to querying without the is_mainchain condition.
		errStr := err.Error()
		ind := strings.LastIndex(err.Error(), noSuchColPrefix)
		if ind == -1 {
			return nil, fmt.Errorf("NewDB: %v", err)
		}
		// Try again without the mainchain constraint.
		if ind+len(noSuchColPrefix) < len(errStr) {
			log.Debugf(`Block summary table missing column "%s". Table upgrade required.`,
				err.Error()[ind+len(noSuchColPrefix):])
		}
		d.dbStakeInfoHeight, err = d.getStakeInfoHeightAnyChain()
		if err != nil {
			return nil, fmt.Errorf("NewDB: %v", err)
		}
	}

	return &d, nil
}
124504
func InitDB(db *bolt.DB) error {
	return db.Update(func(tx *bolt.Tx) error {
		_, err := createBucketIfNotExists(tx, bucketKeyStorageVersion, bucketKeyTasks)
		return err
	})
}
1082678
func New(path string, baseKey []byte, o *Options) (db *DB, err error) {
	if o == nil {
		o = new(Options)
	}
	db = &DB{
		capacity: o.Capacity,
		baseKey:  baseKey,
		// channel collectGarbageTrigger
		// needs to be buffered with the size of 1
		// to signal another event if it
		// is triggered during already running function
		collectGarbageTrigger:    make(chan struct{}, 1),
		close:                    make(chan struct{}),
		collectGarbageWorkerDone: make(chan struct{}),
	}
	if db.capacity <= 0 {
		db.capacity = defaultCapacity
	}
	if maxParallelUpdateGC > 0 {
		db.updateGCSem = make(chan struct{}, maxParallelUpdateGC)
	}

	db.shed, err = shed.NewDB(path, o.MetricsPrefix)
	if err != nil {
		return nil, err
	}
	// Identify current storage schema by arbitrary name.
	db.schemaName, err = db.shed.NewStringField("schema-name")
	if err != nil {
		return nil, err
	}
	// Persist gc size.
	db.gcSize, err = db.shed.NewUint64Field("gc-size")
	if err != nil {
		return nil, err
	}
	// Functions for retrieval data index.
	var (
		encodeValueFunc func(fields shed.Item) (value []byte, err error)
		decodeValueFunc func(keyItem shed.Item, value []byte) (e shed.Item, err error)
	)
	if o.MockStore != nil {
		encodeValueFunc = func(fields shed.Item) (value []byte, err error) {
			b := make([]byte, 8)
			binary.BigEndian.PutUint64(b, uint64(fields.StoreTimestamp))
			err = o.MockStore.Put(fields.Address, fields.Data)
			if err != nil {
				return nil, err
			}
			return b, nil
		}
		decodeValueFunc = func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			e.StoreTimestamp = int64(binary.BigEndian.Uint64(value[:8]))
			e.Data, err = o.MockStore.Get(keyItem.Address)
			return e, err
		}
	} else {
		encodeValueFunc = func(fields shed.Item) (value []byte, err error) {
			b := make([]byte, 8)
			binary.BigEndian.PutUint64(b, uint64(fields.StoreTimestamp))
			value = append(b, fields.Data...)
			return value, nil
		}
		decodeValueFunc = func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			e.StoreTimestamp = int64(binary.BigEndian.Uint64(value[:8]))
			e.Data = value[8:]
			return e, nil
		}
	}
	// Index storing actual chunk address, data and store timestamp.
	db.retrievalDataIndex, err = db.shed.NewIndex("Address->StoreTimestamp|Data", shed.IndexFuncs{
		EncodeKey: func(fields shed.Item) (key []byte, err error) {
			return fields.Address, nil
		},
		DecodeKey: func(key []byte) (e shed.Item, err error) {
			e.Address = key
			return e, nil
		},
		EncodeValue: encodeValueFunc,
		DecodeValue: decodeValueFunc,
	})
	if err != nil {
		return nil, err
	}
	// Index storing access timestamp for a particular address.
	// It is needed in order to update gc index keys for iteration order.
	db.retrievalAccessIndex, err = db.shed.NewIndex("Address->AccessTimestamp", shed.IndexFuncs{
		EncodeKey: func(fields shed.Item) (key []byte, err error) {
			return fields.Address, nil
		},
		DecodeKey: func(key []byte) (e shed.Item, err error) {
			e.Address = key
			return e, nil
		},
		EncodeValue: func(fields shed.Item) (value []byte, err error) {
			b := make([]byte, 8)
			binary.BigEndian.PutUint64(b, uint64(fields.AccessTimestamp))
			return b, nil
		},
		DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			e.AccessTimestamp = int64(binary.BigEndian.Uint64(value))
			return e, nil
		},
	})
	if err != nil {
		return nil, err
	}
	// pull index allows history and live syncing per po bin
	db.pullIndex, err = db.shed.NewIndex("PO|StoredTimestamp|Hash->nil", shed.IndexFuncs{
		EncodeKey: func(fields shed.Item) (key []byte, err error) {
			key = make([]byte, 41)
			key[0] = db.po(fields.Address)
			binary.BigEndian.PutUint64(key[1:9], uint64(fields.StoreTimestamp))
			copy(key[9:], fields.Address[:])
			return key, nil
		},
		DecodeKey: func(key []byte) (e shed.Item, err error) {
			e.Address = key[9:]
			e.StoreTimestamp = int64(binary.BigEndian.Uint64(key[1:9]))
			return e, nil
		},
		EncodeValue: func(fields shed.Item) (value []byte, err error) {
			return nil, nil
		},
		DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			return e, nil
		},
	})
	if err != nil {
		return nil, err
	}
	// create a pull syncing triggers used by SubscribePull function
	db.pullTriggers = make(map[uint8][]chan struct{})
	// push index contains as yet unsynced chunks
	db.pushIndex, err = db.shed.NewIndex("StoredTimestamp|Hash->nil", shed.IndexFuncs{
		EncodeKey: func(fields shed.Item) (key []byte, err error) {
			key = make([]byte, 40)
			binary.BigEndian.PutUint64(key[:8], uint64(fields.StoreTimestamp))
			copy(key[8:], fields.Address[:])
			return key, nil
		},
		DecodeKey: func(key []byte) (e shed.Item, err error) {
			e.Address = key[8:]
			e.StoreTimestamp = int64(binary.BigEndian.Uint64(key[:8]))
			return e, nil
		},
		EncodeValue: func(fields shed.Item) (value []byte, err error) {
			return nil, nil
		},
		DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			return e, nil
		},
	})
	if err != nil {
		return nil, err
	}
	// create a push syncing triggers used by SubscribePush function
	db.pushTriggers = make([]chan struct{}, 0)
	// gc index for removable chunk ordered by ascending last access time
	db.gcIndex, err = db.shed.NewIndex("AccessTimestamp|StoredTimestamp|Hash->nil", shed.IndexFuncs{
		EncodeKey: func(fields shed.Item) (key []byte, err error) {
			b := make([]byte, 16, 16+len(fields.Address))
			binary.BigEndian.PutUint64(b[:8], uint64(fields.AccessTimestamp))
			binary.BigEndian.PutUint64(b[8:16], uint64(fields.StoreTimestamp))
			key = append(b, fields.Address...)
			return key, nil
		},
		DecodeKey: func(key []byte) (e shed.Item, err error) {
			e.AccessTimestamp = int64(binary.BigEndian.Uint64(key[:8]))
			e.StoreTimestamp = int64(binary.BigEndian.Uint64(key[8:16]))
			e.Address = key[16:]
			return e, nil
		},
		EncodeValue: func(fields shed.Item) (value []byte, err error) {
			return nil, nil
		},
		DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
			return e, nil
		},
	})
	if err != nil {
		return nil, err
	}
	// start garbage collection worker
	go db.collectGarbageWorker()
	return db, nil
}
1291118
func (sqlite3 *Sqlite3DB) CreateDB() {
	var errDB error
	sqlite3.GolDB, errDB = sql.Open("sqlite3", sqlite3.DBPath)
	if errDB != nil {
		errMsg := fmt.Sprintf("DB %s Creation failed. %q", sqlite3.DBPath, errDB)
		golerror.Boohoo(errMsg, true)
	}
	sqlStmt := fmt.Sprintf("create table IF NOT EXISTS %s (FieldKey text not null primary key, FieldValue text); delete from %s;", sqlite3.TableName, sqlite3.TableName)
	_, errDB = sqlite3.GolDB.Exec(sqlStmt)
	if errDB != nil {
		golerror.Boohoo(errDB.Error(), true)
		return
	}
}
1356762
func NewDatabaseWithCache(diskdb ethdb.KeyValueStore, cache int) *Database {
	var cleans *bigcache.BigCache
	if cache > 0 {
		cleans, _ = bigcache.NewBigCache(bigcache.Config{
			Shards:             1024,
			LifeWindow:         time.Hour,
			MaxEntriesInWindow: cache * 1024,
			MaxEntrySize:       512,
			HardMaxCacheSize:   cache,
			Hasher:             trienodeHasher{},
		})
	}
	return &Database{
		diskdb: diskdb,
		cleans: cleans,
		dirties: map[common.Hash]*cachedNode{{}: {
			children: make(map[common.Hash]uint16),
		}},
		preimages: make(map[common.Hash][]byte),
	}
}
225011
func New(db *gorm.DB, keyPairs ...[]byte) *Store {
	return NewOptions(db, Options{}, keyPairs...)
}
161113
func CreateNewDatabase(values *CreateDatabaseValue) *Database {

	db := &Database{
		// Appliance
		Appliance: &Appliance{
			// Class
			Class: "database",
			// Name
			propName: propName{Name: values.Name},
			// Description
			propDescription: propDescription{Description: values.Description},
			// TagsType
			propTags: propTags{
				// Tags
				Tags: values.Tags,
			},
			// Icon
			propIcon: propIcon{
				&Icon{
					// Resource
					Resource: values.Icon,
				},
			},
			// Plan
			//propPlanID: propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
		},
		// Remark
		Remark: &DatabaseRemark{
			// ApplianceRemarkBase
			ApplianceRemarkBase: &ApplianceRemarkBase{
				// Servers
				Servers: []interface{}{""},
			},
			// DBConf
			DBConf: &DatabaseCommonRemarks{
				// Common
				Common: &DatabaseCommonRemark{
					// DatabaseName
					DatabaseName: values.DatabaseName,
					// DatabaseRevision
					DatabaseRevision: values.DatabaseRevision,
					// DatabaseTitle
					DatabaseTitle: values.DatabaseTitle,
					// DatabaseVersion
					DatabaseVersion: values.DatabaseVersion,
				},
			},
			// Plan
			propPlanID:      propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
			SourceAppliance: values.SourceAppliance,
		},
		// Settings
		Settings: &DatabaseSettings{
			// DBConf
			DBConf: &DatabaseSetting{
				// Backup
				Backup: &DatabaseBackupSetting{
					// Rotate
					// Rotate: values.BackupRotate,
					Rotate: 8,
					// Time
					Time: values.BackupTime,
					// DayOfWeek
					DayOfWeek: values.BackupDayOfWeek,
				},
				// Common
				Common: &DatabaseCommonSetting{
					// DefaultUser
					DefaultUser: values.DefaultUser,
					// UserPassword
					UserPassword: values.UserPassword,
					// SourceNetwork
					SourceNetwork: SourceNetwork(values.SourceNetwork),
				},
			},
		},
	}

	if values.ServicePort > 0 {
		db.Settings.DBConf.Common.ServicePort = json.Number(fmt.Sprintf("%d", values.ServicePort))
	}

	if !values.EnableBackup {
		db.Settings.DBConf.Backup = nil
	}

	db.Remark.Switch = &ApplianceRemarkSwitch{
		// ID
		ID: values.SwitchID,
	}
	db.Remark.Network = &DatabaseRemarkNetwork{
		// NetworkMaskLen
		NetworkMaskLen: values.MaskLen,
		// DefaultRoute
		DefaultRoute: values.DefaultRoute,
	}

	db.Remark.Servers = []interface{}{
		map[string]interface{}{"IPAddress": values.IPAddress1},
	}

	if values.WebUI {
		db.Settings.DBConf.Common.WebUI = values.WebUI
	}

	if values.ReplicaPassword != "" {
		db.Settings.DBConf.Common.ReplicaUser = "replica"
		db.Settings.DBConf.Common.ReplicaPassword = values.ReplicaPassword
		db.Settings.DBConf.Replication = &DatabaseReplicationSetting{
			Model: DatabaseReplicationModelMasterSlave,
		}
	}

	return db
}
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
}
726685
func NewDatabase() *Database {
	header := NewHeader()
	return &Database{
		Options:     NewOptions(),
		Credentials: new(DBCredentials),
		Header:      header,
		Hashes:      NewHashes(header),
		Content:     NewContent(),
	}
}
1201032
func New(dbName string, idAlloc autoid.Allocator) (KvEncoder, error) {
	kvEnc := &kvEncoder{}
	mu.Lock()
	defer mu.Unlock()
	if refCount == 0 {
		if err := initGlobal(); err != nil {
			return nil, err
		}
	}
	err := kvEnc.initial(dbName, idAlloc)
	if err != nil {
		return nil, err
	}
	refCount++
	return kvEnc, nil
}
1322645
func newDB(c *Context) (*empire.DB, error) {
	db, err := empire.OpenDB(c.String(FlagDB))
	if err != nil {
		return nil, err
	}

	db.Schema = &empire.Schema{
		InstancePortPool: &empire.InstancePortPool{
			Start: uint(c.Int(FlagInstancePortPoolStart)),
			End:   uint(c.Int(FlagInstancePortPoolEnd)),
		},
	}

	return db, nil
}
1332970
func (engine *Engine) NewDB() (*core.DB, error) {
	return core.OpenDialect(engine.dialect)
}
760212
func NewDebugDB(label string, db DB) debugDB {
	return debugDB{
		label: label,
		db:    db,
	}
}
365991
func New(cfg ...service.Config) *Database {
	db := &Database{redis: service.New(cfg...)}
	db.redis.Connect()
	_, err := db.redis.PingPong()
	if err != nil {
		golog.Debugf("error connecting to redis: %v", err)
		return nil
	}
	runtime.SetFinalizer(db, closeDB)
	return db
}
373711
func NewFromDB(service *badger.DB) *Database {
	db := &Database{Service: service}

	runtime.SetFinalizer(db, closeDB)
	return db
}
1313597
func (dbGorp *DbGorp) CloneDb(open bool) (newDb *DbGorp, err error) {
	dbInfo := *dbGorp.Info
	newDb = &DbGorp{Info: &dbInfo}
	newDb.dbInitFn = dbGorp.dbInitFn
	err = newDb.InitDb(open)

	return
}
587019
func NewDB(db *sql.DB, options ...DBOption) (*DB, error) {
	newDB := &DB{
		DB:                    db,
		AllowStringQueries:    true,
		IgnoreUnmappedCols:    true,
		IgnoreMissingCols:     false,
		Logger:                nil,
		OpentracingEnabled:    false,
		context:               context.Background(),
		deadlineQueryRewriter: noopDeadlineQueryRewriter,
		models:                map[reflect.Type]*Model{},
		mappings:              map[reflect.Type]fieldMap{},
		mu:                    &sync.RWMutex{},
	}
	for i, option := range options {
		if err := option(newDB); err != nil {
			return nil, fmt.Errorf("Error procesing DBOption with index %d: %v", i, err)
		}
	}
	return newDB, nil
}