// Creates a DB at the desired path or drops an existing one and recreates a
// new empty one at the path. The bitcoin network is needed because the genesis
// block must be inserted first for the DB to initialized properly.
164582
func InitDB(path string, params *chaincfg.Params) (*PublicRecord, error) {
	path = filepath.Clean(path)
	// Check if the file exists and remove it if it does.
	if _, err := os.Stat(path); err == nil {
		if err := os.Remove(path); err != nil {
			return nil, err
		}
	}

	conn, err := sql.Open("sqlite3", path)
	if err != nil {
		return nil, err
	}

	// Execute the Create Table sql
	_, err = conn.Exec(createSql())
	if err != nil {
		return nil, err
	}
	conn.Close()

	db, err := createPubRec(path)
	if err != nil {
		return nil, err
	}

	// Prepare the DB to do one insert (for the pegBlk)
	if err := prepareInserts(db); err != nil {
		return nil, err
	}

	err = db.InsertGenesisBlk(params.Net)
	if err != nil {
		return nil, err
	}
	return prepareDB(db)
}
850857
func (idx *AddrIndex) Create(dbTx database.Tx) error {
	_, err := dbTx.Metadata().CreateBucket(addrIndexKey)
	return err
}
677231
func (_class NetworkClass) Create(sessionID SessionRef, args NetworkRecord) (_retval NetworkRef, _err error) {
	_method := "network.create"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_argsArg, _err := convertNetworkRecordToXen(fmt.Sprintf("%s(%s)", _method, "args"), args)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _argsArg)
	if _err != nil {
		return
	}
	_retval, _err = convertNetworkRefToGo(_method + " -> ", _result.Value)
	return
}
213043
func newPersistentDB(path string) (*DB, error) {
	opts := &opt.Options{OpenFilesCacheCapacity: 5}
	db, err := leveldb.OpenFile(path, opts)
	if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted {
		db, err = leveldb.RecoverFile(path, nil)
	}
	if err != nil {
		return nil, err
	}
	// The nodes contained in the cache correspond to a certain protocol version.
	// Flush all nodes if the version doesn't match.
	currentVer := make([]byte, binary.MaxVarintLen64)
	currentVer = currentVer[:binary.PutVarint(currentVer, int64(dbVersion))]

	blob, err := db.Get([]byte(dbVersionKey), nil)
	switch err {
	case leveldb.ErrNotFound:
		// Version not found (i.e. empty cache), insert it
		if err := db.Put([]byte(dbVersionKey), currentVer, nil); err != nil {
			db.Close()
			return nil, err
		}

	case nil:
		// Version present, flush if different
		if !bytes.Equal(blob, currentVer) {
			db.Close()
			if err = os.RemoveAll(path); err != nil {
				return nil, err
			}
			return newPersistentDB(path)
		}
	}
	return &DB{lvl: db, quit: make(chan struct{})}, nil
}
40475
func (c *FakeNodes) Create(node *corev1.Node) (result *corev1.Node, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(nodesResource, node), &corev1.Node{})
	if obj == nil {
		return nil, err
	}
	return obj.(*corev1.Node), err
}
1097230
func LoadOrNewBlockchain(db dbm.DB, genesisDoc *genesis.GenesisDoc, logger *logging.Logger) (bool, *Blockchain, error) {
	logger = logger.WithScope("LoadOrNewBlockchain")
	logger.InfoMsg("Trying to load blockchain state from database",
		"database_key", stateKey)
	bc, err := loadBlockchain(db)
	if err != nil {
		return false, nil, fmt.Errorf("error loading blockchain state from database: %v", err)
	}
	if bc != nil {
		dbHash := bc.genesisDoc.Hash()
		argHash := genesisDoc.Hash()
		if !bytes.Equal(dbHash, argHash) {
			return false, nil, fmt.Errorf("GenesisDoc passed to LoadOrNewBlockchain has hash: 0x%X, which does not "+
				"match the one found in database: 0x%X, database genesis:\n%v\npassed genesis:\n%v\n",
				argHash, dbHash, bc.genesisDoc.JSONString(), genesisDoc.JSONString())
		}
		return true, bc, nil
	}

	logger.InfoMsg("No existing blockchain state found in database, making new blockchain")
	return false, NewBlockchain(db, genesisDoc), nil
}
702681
func (db *DB) Create(name string) error {
	db.schemaLock.Lock()
	defer db.schemaLock.Unlock()
	return db.create(name)
}
843005
func (db *Database) Create(value DBModel) error {
	defer func() {
		if db.rawRows != nil {
			db.rawRows.Close()
		}
	}()
	db = db.clone()
	return db.commonCreateUpdate(value, db.buildCreate)
}
307890
func CreateCouchDatabase(couchInstance *CouchInstance, dbName string) (*CouchDatabase, error) {

	databaseName, err := mapAndValidateDatabaseName(dbName)
	if err != nil {
		logger.Errorf("Error calling CouchDB CreateDatabaseIfNotExist() for dbName: %s, error: %s", dbName, err)
		return nil, err
	}

	couchDBDatabase := CouchDatabase{CouchInstance: couchInstance, DBName: databaseName, IndexWarmCounter: 1}

	// Create CouchDB database upon ledger startup, if it doesn't already exist
	err = couchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error calling CouchDB CreateDatabaseIfNotExist() for dbName: %s, error: %s", dbName, err)
		return nil, err
	}

	return &couchDBDatabase, nil
}
945948
func (d *Database) Add(path string, n *Node) {
	d.mtx.Lock()
	defer d.mtx.Unlock()

	if path == "" {
		d.root = n
		return
	}

	rabbitHole := strings.Split(path, "/")
	current := d.root
	for i := 0; i < len(rabbitHole)-1; i++ {
		step := rabbitHole[i]
		next, ok := current.Children[step]
		if !ok {
			next = &Node{
				Parent:   current,
				Key:      step,
				Children: map[string]*Node{},
			}
			current.Children[step] = next
		}
		next.Value = nil // no long has a value since it now has a child
		current, next = next, nil
	}

	lastPath := rabbitHole[len(rabbitHole)-1]
	current.Children[lastPath] = n
	n.Parent = current
}
1295926
func loadBlockDB() (database.DB, error) {
	// The database name is based on the database type.
	dbName := blockDbNamePrefix + "_" + cfg.DbType
	dbPath := filepath.Join(cfg.DataDir, dbName)
	fmt.Printf("Loading block database from '%s'\n", dbPath)
	db, err := database.Open(cfg.DbType, dbPath, activeNetParams.Net)
	if err != nil {
		return nil, err
	}
	return db, nil
}
100006
func (s *persistentSequencer) initDB() error {
	return s.db.Update(func(tx *bbolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists(nextPaymentIDKey)
		return err
	})
}
976217
func (d *database) CreateGraph(ctx context.Context, name string, options *CreateGraphOptions) (Graph, error) {
	input := createGraphOptions{
		Name: name,
	}
	if options != nil {
		input.OrphanVertexCollections = options.OrphanVertexCollections
		input.EdgeDefinitions = options.EdgeDefinitions
		input.IsSmart = options.IsSmart
		if options.SmartGraphAttribute != "" || options.NumberOfShards != 0 {
			input.Options = &createGraphAdditionalOptions{
				SmartGraphAttribute: options.SmartGraphAttribute,
				NumberOfShards:      options.NumberOfShards,
			}
		}
	}
	req, err := d.conn.NewRequest("POST", path.Join(d.relPath(), "_api/gharial"))
	if err != nil {
		return nil, WithStack(err)
	}
	if _, err := req.SetBody(input); err != nil {
		return nil, WithStack(err)
	}
	resp, err := d.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(201, 202); err != nil {
		return nil, WithStack(err)
	}
	g, err := newGraph(name, d)
	if err != nil {
		return nil, WithStack(err)
	}
	return g, nil
}
800168
func NewFromDB(sqlDB *sql.DB, driverName string) *DB {
	db := &DB{
		driverName:  driverName,
		sqlDB:       sqlDB,
		FieldMapper: DefaultFieldMapFunc,
	}
	db.Builder = db.newBuilder(db.sqlDB)
	return db
}
536584
func (d *Databases) CreateDB(ctx context.Context, db *chronograf.Database) (*chronograf.Database, error) {
	return d.CreateDBF(ctx, db)
}
1271086
func blockDbPath(dbType string) string {
	// The database name is based on the database type.
	dbName := blockDbNamePrefix + "_" + dbType
	if dbType == "sqlite" {
		dbName = dbName + ".db"
	}
	dbPath := filepath.Join(cfg.DataDir, dbName)
	return dbPath
}
822022
func Create(inputPath string, zipPath string) error {
	ctx := context{
		createBaseDir: true,
		zipPath:       zipPath,
	}
	return createZip(inputPath, zipPath, ctx)
}