/*
This plugin uses 2 databases:
1. The default DB is used for APID table.
2. The versioned DB is used for APID_CLUSTER & DATA_SCOPE
(Currently, the snapshot never changes, but this is future-proof)
*/
431221
func creatDbManager() *dbManager {
	return &dbManager{
		DbMux:       &sync.RWMutex{},
		knownTables: make(map[string]bool),
	}
}
797992
func Version(url string, kvdbOptions map[string]string) (string, error) {
	// Currently we support only v1
	return kvdb.ConsulVersion1, nil
}
608365
func (t *TowerDB) Version() (uint32, error) {
	var version uint32
	err := t.db.View(func(tx *bbolt.Tx) error {
		var err error
		version, err = getDBVersion(tx)
		return err
	})
	if err != nil {
		return 0, err
	}

	return version, nil
}
740885
func NewSourceFromDatabase(
	dbMap dbSelector,
	caKeyHash []byte,
	reqSerialPrefixes []string,
	timeout time.Duration,
	log blog.Logger,
) (src *DBSource, err error) {
	src = &DBSource{
		dbMap:             dbMap,
		caKeyHash:         caKeyHash,
		reqSerialPrefixes: reqSerialPrefixes,
		timeout:           timeout,
		log:               log,
	}
	return
}
461520
func (s *Store) createDatabase() error {
	var db *sdb.DB
	var err error
	if !s.dbConf.Memory {
		// as it will be rebuilt from (possibly) a snapshot and committed log entries.
		if err := os.Remove(s.dbPath); err != nil && !os.IsNotExist(err) {
			return err
		}
		db, err = sdb.New(s.dbPath, s.dbConf.DSN, false)
		if err != nil {
			return err
		}
		s.logger.Println("SQLite database opened at", s.dbPath)
	} else {
		db, err = sdb.New(s.dbPath, s.dbConf.DSN, true)
		if err != nil {
			return err
		}
		s.logger.Println("SQLite in-memory database opened")
	}
	s.db = db
	return nil
}
80935
func (obj *Global) GetDatabasesFromConnectionString(ctx context.Context, connection *Connection) ([]*Database, error) {
	result := &struct {
		Databases []*Database	`json:"qDatabases"`
	} {}
	err := obj.rpc(ctx, "GetDatabasesFromConnectionString", result, connection)
	return result.Databases, err 
}
1191215
func NewSourceFromDB(DBConfigFile string) (Source, error) {
	// Load DB from cofiguration file
	db, err := dbconf.DBFromConfig(DBConfigFile)

	if err != nil {
		return nil, err
	}
	// Create accesor
	accessor := sql.NewAccessor(db)
	src := NewDBSource(accessor)

	return src, nil
}
882635
func (s *DB) DB() *sql.DB {
	db, _ := s.db.(*sql.DB)
	return db
}
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
}
1244251
func (m *Miniredis) swapDB(i, j int) bool {
	db1 := m.db(i)
	db2 := m.db(j)

	db1.id = j
	db2.id = i

	m.dbs[i] = db2
	m.dbs[j] = db1

	return true
}
805898
func (client *Client) CreateDatabase(args *CreateDatabaseArgs) (resp *CreateDatabaseResponse, err error) {
	response := CreateDatabaseResponse{}
	err = client.Invoke("CreateDatabase", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
411795
func NewSnapshotDB(authDB *protocol.AuthDB, authServiceURL string, rev int64) (*SnapshotDB, error) {
	db := &SnapshotDB{
		AuthServiceURL: authServiceURL,
		Rev:            rev,

		tokenServiceURL: authDB.TokenServerUrl,
	}

	// Set of all allowed clientIDs.
	db.clientIDs = make(map[string]struct{}, 2+len(authDB.OauthAdditionalClientIds))
	db.clientIDs[googleAPIExplorerClientID] = struct{}{}
	if authDB.OauthClientId != "" {
		db.clientIDs[authDB.OauthClientId] = struct{}{}
	}
	for _, cid := range authDB.OauthAdditionalClientIds {
		if cid != "" {
			db.clientIDs[cid] = struct{}{}
		}
	}

	// First pass: build all `group` nodes.
	db.groups = make(map[string]*group, len(authDB.Groups))
	for _, g := range authDB.Groups {
		if db.groups[g.Name] != nil {
			return nil, fmt.Errorf("auth: bad AuthDB, group %q is listed twice", g.Name)
		}
		gr := &group{}
		if len(g.Members) != 0 {
			gr.members = make(map[identity.Identity]struct{}, len(g.Members))
			for _, ident := range g.Members {
				gr.members[identity.Identity(ident)] = struct{}{}
			}
		}
		if len(g.Globs) != 0 {
			gr.globs = make([]identity.Glob, len(g.Globs))
			for i, glob := range g.Globs {
				gr.globs[i] = identity.Glob(glob)
			}
		}
		if len(g.Nested) != 0 {
			gr.nested = make([]*group, 0, len(g.Nested))
		}
		db.groups[g.Name] = gr
	}

	// Second pass: fill in `nested` with pointers, now that we have them.
	for _, g := range authDB.Groups {
		gr := db.groups[g.Name]
		for _, nestedName := range g.Nested {
			if nestedGroup := db.groups[nestedName]; nestedGroup != nil {
				gr.nested = append(gr.nested, nestedGroup)
			}
		}
	}

	// Build map of IP whitelist assignments.
	db.assignments = make(map[identity.Identity]string, len(authDB.IpWhitelistAssignments))
	for _, a := range authDB.IpWhitelistAssignments {
		db.assignments[identity.Identity(a.Identity)] = a.IpWhitelist
	}

	// Parse all subnets into IPNet objects.
	db.whitelists = make(map[string][]net.IPNet, len(authDB.IpWhitelists))
	for _, w := range authDB.IpWhitelists {
		if len(w.Subnets) == 0 {
			continue
		}
		nets := make([]net.IPNet, len(w.Subnets))
		for i, subnet := range w.Subnets {
			_, ipnet, err := net.ParseCIDR(subnet)
			if err != nil {
				return nil, fmt.Errorf("auth: bad subnet %q in IP list %q - %s", subnet, w.Name, err)
			}
			nets[i] = *ipnet
		}
		db.whitelists[w.Name] = nets
	}

	// SecurityConfig is stored in the serialized form.
	securityConf := protocol.SecurityConfig{}
	if len(authDB.SecurityConfig) != 0 {
		if err := proto.Unmarshal(authDB.SecurityConfig, &securityConf); err != nil {
			return nil, fmt.Errorf("auth: failed to deserialize SecurityConfig - %s", err)
		}
	}

	// Assemble a single regexp from a bunch of 'internal_service_regexp'.
	if len(securityConf.InternalServiceRegexp) > 0 {
		exp := ""
		for idx, re := range securityConf.InternalServiceRegexp {
			if idx != 0 {
				exp += "|"
			}
			exp += "(^" + re + "$)"
		}
		var err error
		if db.internalServices, err = regexp.Compile(exp); err != nil {
			return nil, fmt.Errorf("auth: failed to compile internal_service_regexp - %s", err)
		}
	}

	return db, nil
}
1320387
func (s *DeleteStatement) DefaultDatabase() string {
	if m, ok := s.Source.(*Measurement); ok {
		return m.Database
	}
	return ""
}
17274
func NewPluginClient(ctx context.Context, sys pluginutil.RunnerUtil, pluginRunner *pluginutil.PluginRunner, logger log.Logger, isMetadataMode bool) (Database, error) {

	// pluginSets is the map of plugins we can dispense.
	pluginSets := map[int]plugin.PluginSet{
		// Version 3 used to supports both protocols. We want to keep it around
		// since it's possible old plugins built against this version will still
		// work with gRPC. There is currently no difference between version 3
		// and version 4.
		3: plugin.PluginSet{
			"database": new(GRPCDatabasePlugin),
		},
		// Version 4 only supports gRPC
		4: plugin.PluginSet{
			"database": new(GRPCDatabasePlugin),
		},
	}

	var client *plugin.Client
	var err error
	if isMetadataMode {
		client, err = pluginRunner.RunMetadataMode(ctx, sys, pluginSets, handshakeConfig, []string{}, logger)
	} else {
		client, err = pluginRunner.Run(ctx, sys, pluginSets, handshakeConfig, []string{}, logger)
	}
	if err != nil {
		return nil, err
	}

	// Connect via RPC
	rpcClient, err := client.Client()
	if err != nil {
		return nil, err
	}

	// Request the plugin
	raw, err := rpcClient.Dispense("database")
	if err != nil {
		return nil, err
	}

	// We should have a database type now. This feels like a normal interface
	// implementation but is in fact over an RPC connection.
	var db Database
	switch raw.(type) {
	case *gRPCClient:
		db = raw.(*gRPCClient)
	default:
		return nil, errors.New("unsupported client type")
	}

	// Wrap RPC implementation in DatabasePluginClient
	return &DatabasePluginClient{
		client:   client,
		Database: db,
	}, nil
}
521905
func (c *client) CreateDatabase(ctx context.Context, name string, options *CreateDatabaseOptions) (Database, error) {
	input := struct {
		CreateDatabaseOptions
		Name string `json:"name"`
	}{
		Name: name,
	}
	if options != nil {
		input.CreateDatabaseOptions = *options
	}
	req, err := c.conn.NewRequest("POST", path.Join("_db/_system/_api/database"))
	if err != nil {
		return nil, WithStack(err)
	}
	if _, err := req.SetBody(input); err != nil {
		return nil, WithStack(err)
	}
	resp, err := c.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(201); err != nil {
		return nil, WithStack(err)
	}
	db, err := newDatabase(name, c.conn)
	if err != nil {
		return nil, WithStack(err)
	}
	return db, nil
}
99646
func (host *Host) useDatabase() error {
	if Verbose {
		log.Println("Using database " + host.dbname)
	}
	return nil
}
1104550
func (s *Store) Snapshot() *Snapshot {
	tx := s.db.Txn(false)

	var tables []string
	for table := range s.schema.Tables {
		tables = append(tables, table)
	}
	idx := maxIndexTxn(tx, tables...)

	return &Snapshot{s, tx, idx}
}