// LockDB obtains db locks for all messages that need to
// be updated and returns the counterpart unlock function.
485708
func (me *Engine) LockDB(newMessages map[string][]*MessageRow, changedMessages map[string][]string) func() {
	// Short-circuit to avoid taking any locks if there's nothing to do.
	if len(newMessages) == 0 && len(changedMessages) == 0 {
		return func() {}
	}

	// Build the set of affected messages tables.
	combined := make(map[string]struct{})
	for name := range newMessages {
		combined[name] = struct{}{}
	}
	for name := range changedMessages {
		combined[name] = struct{}{}
	}

	// Build the list of manager objects (one per table).
	var mms []*messageManager
	// Don't do DBLock while holding lock on mu.
	// It causes deadlocks.
	func() {
		me.mu.Lock()
		defer me.mu.Unlock()
		for name := range combined {
			if mm := me.managers[name]; mm != nil {
				mms = append(mms, mm)
			}
		}
	}()
	if len(mms) > 1 {
		// Always use the same order in which manager objects are locked to avoid deadlocks.
		// The previous order in "mms" is not guaranteed for multiple reasons:
		// - We use a Go map above which does not guarantee an iteration order.
		// - Transactions may not always use the same order when writing to multiple
		//   messages tables.
		sort.Slice(mms, func(i, j int) bool { return mms[i].name.String() < mms[j].name.String() })
	}

	// Lock each manager/messages table.
	for _, mm := range mms {
		mm.DBLock.Lock()
	}
	return func() {
		for _, mm := range mms {
			mm.DBLock.Unlock()
		}
	}
}
1271349
func (db *StakeDatabase) DBPrevBlockHeader() (*wire.BlockHeader, error) {
	_, hash, err := db.DBState()
	if err != nil {
		return nil, err
	}

	parentHeader, err := db.NodeClient.GetBlockHeader(hash)
	if err != nil {
		return nil, err
	}

	return db.NodeClient.GetBlockHeader(&parentHeader.PrevBlock)
}
1140552
func (a *API) StopDB() error {
	if a.DB != nil {
		a.DB.Close()
	}

	a.Client.StopContainer(a.Config.DbID, 5)
	a.Client.WaitContainer(a.Config.DbID)
	a.Client.RemoveContainer(docker.RemoveContainerOptions{
		ID:    a.Config.DbID,
		Force: true,
	})

	return nil
}
866266
func (i *MySQLLock) Lock() error {
	defer metrics.MeasureSince([]string{"mysql", "get_lock"}, time.Now())

	// Lock timeout math.MaxInt32 instead of -1 solves compatibility issues with
	// different MySQL flavours i.e. MariaDB
	rows, err := i.in.Query("SELECT GET_LOCK(?, ?), IS_USED_LOCK(?)", i.key, math.MaxInt32, i.key)
	if err != nil {
		return err
	}

	defer rows.Close()
	rows.Next()
	var lock sql.NullInt64
	var connectionID sql.NullInt64
	rows.Scan(&lock, &connectionID)

	if rows.Err() != nil {
		return rows.Err()
	}

	// 1 is returned from GET_LOCK if it was able to get the lock
	// 0 if it failed and NULL if some strange error happened.
	// https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_get-lock
	if !lock.Valid || lock.Int64 != 1 {
		return ErrLockHeld
	}

	// Since we have the lock alert the rest of the cluster
	// that we are now the active leader.
	err = i.becomeLeader()
	if err != nil {
		return ErrLockHeld
	}

	// This will return the connection ID of NULL if an error happens
	// https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-used-lock
	if !connectionID.Valid {
		return ErrSettingGlobalID
	}

	GlobalLockID = connectionID.Int64

	return nil
}
914978
func GetDBlock(keymr string) (*DBlock, error) {
	params := keyMRRequest{KeyMR: keymr}
	req := NewJSON2Request("directory-block", APICounter(), params)
	resp, err := factomdRequest(req)
	if err != nil {
		return nil, err
	}
	if resp.Error != nil {
		return nil, resp.Error
	}

	db := new(DBlock)
	if err := json.Unmarshal(resp.JSONResult(), db); err != nil {
		return nil, err
	}

	return db, nil
}
43596
func (l *Lock) Lock() (err error) {
	return l.store(func(sem *Semaphore) error {
		return sem.Lock(l.id)
	})
}
205781
func OpenDB(uri string) (*DB, error) {
	_, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	conn, err := sql.Open(DBDriver, uri)
	if err != nil {
		return nil, err
	}

	return NewDB(conn)
}
828549
func OpenDb(opts *Options, name string) (*DB, error) {
	var (
		cErr  *C.char
		cName = C.CString(name)
	)
	defer C.free(unsafe.Pointer(cName))
	db := C.rocksdb_open(opts.c, cName, &cErr)
	if cErr != nil {
		defer C.free(unsafe.Pointer(cErr))
		return nil, errors.New(C.GoString(cErr))
	}
	return &DB{
		name: name,
		c:    db,
		opts: opts,
	}, nil
}
486594
func (client *lockRESTClient) Lock(args dsync.LockArgs) (reply bool, err error) {
	return client.restCall(lockRESTMethodLock, args)
}
400398
func (bi *blockIndex) flushToDB() error {
	bi.Lock()
	if len(bi.dirty) == 0 {
		bi.Unlock()
		return nil
	}

	err := bi.db.Update(func(dbTx database.Tx) error {
		for node := range bi.dirty {
			err := dbStoreBlockNode(dbTx, node)
			if err != nil {
				return err
			}
		}
		return nil
	})

	// If write was successful, clear the dirty set.
	if err == nil {
		bi.dirty = make(map[*blockNode]struct{})
	}

	bi.Unlock()
	return err
}
1275584
func (pgb *ChainDB) HashDB() (string, error) {
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	_, bestHash, _, err := RetrieveBestBlockHeight(ctx, pgb.db)
	return bestHash, pgb.replaceCancelError(err)
}
865385
func (post *UserPost) Locks() *[]Lock {
	ret := []UserPostLock{}
	Db().Model(UserPostLock{}).Where(&UserPostLock{Hpid: post.ID()}).Scan(&ret)
	var retLockers []Lock
	for _, l := range ret {
		locker := l
		retLockers = append(retLockers, Lock(&locker))
	}

	return &retLockers
}
1071308
func (db *WiredDB) SyncDB(ctx context.Context, blockGetter rpcutils.BlockGetter, fetchToHeight int64) (int64, error) {
	// Ensure the db is working.
	if err := db.CheckConnectivity(); err != nil {
		return -1, fmt.Errorf("CheckConnectivity failed: %v", err)
	}

	// Set the first height at which the smart client should wait for the block.
	if !(blockGetter == nil || blockGetter.(*rpcutils.BlockGate) == nil) {
		log.Debugf("Setting block gate height to %d", fetchToHeight)
		db.initWaitChan(blockGetter.WaitForHeight(fetchToHeight))
	}
	return db.resyncDB(ctx, blockGetter, fetchToHeight)
}
709219
func (db *StakeDatabase) dbPrevBlock() (*dcrutil.Block, error) {
	_, hash, err := db.dbState()
	if err != nil {
		return nil, err
	}

	parentHeader, err := db.NodeClient.GetBlockHeader(hash)
	if err != nil {
		return nil, err
	}

	return db.getBlock(&parentHeader.PrevBlock)
}
751143
func (s *AccountService) LockAccount(p *LockAccountParams) (*LockAccountResponse, error) {
	resp, err := s.cs.newRequest("lockAccount", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r LockAccountResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
1116258
func (l *DynamoDBLock) Unlock() error {
	l.lock.Lock()
	defer l.lock.Unlock()
	if !l.held {
		return nil
	}

	l.held = false

	// Conditionally delete after check that the key is actually this Vault's and
	// not been already claimed by another leader
	condition := "#identity = :identity"
	deleteMyLock := &dynamodb.DeleteItemInput{
		TableName:           &l.backend.table,
		ConditionExpression: &condition,
		Key: map[string]*dynamodb.AttributeValue{
			"Path": {S: aws.String(recordPathForVaultKey(l.key))},
			"Key":  {S: aws.String(recordKeyForVaultKey(l.key))},
		},
		ExpressionAttributeNames: map[string]*string{
			"#identity": aws.String("Identity"),
		},
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":identity": {B: []byte(l.identity)},
		},
	}

	_, err := l.backend.client.DeleteItem(deleteMyLock)
	if isConditionCheckFailed(err) {
		err = nil
	}

	return err
}
600965
func (c *Client) AllDB(ctx context.Context) ([]chronograf.Database, error) {
	return c.showDatabases(ctx)
}