// Take apart and rebuild the connection string. Also return the dbname.
2346
func rebuildConnectionString(connectionString string) (string, string) {
	username, password, hasPassword, hostname, port, dbname := splitConnectionString(connectionString)
	return buildConnectionString(username, password, hasPassword, hostname, port, dbname), dbname
}
1027277
func (db *RedisDB) Get(k string) (string, error) {
	db.master.Lock()
	defer db.master.Unlock()
	if !db.exists(k) {
		return "", ErrKeyNotFound
	}
	if db.t(k) != "string" {
		return "", ErrWrongType
	}
	return db.stringGet(k), nil
}
1047097
func ConstructMetadataDBName(dbName string) string {
	if len(dbName) > maxLength {
		untruncatedDBName := dbName
		// Truncate the name if the length violates the allowed limit
		// As the passed dbName is same as chain/channel name, truncate using chainNameAllowedLength
		dbName = dbName[:chainNameAllowedLength]
		// For metadataDB (i.e., chain/channel DB), the dbName contains <first 50 chars
		// (i.e., chainNameAllowedLength) of chainName> + (SHA256 hash of actual chainName)
		dbName = dbName + "(" + hex.EncodeToString(util.ComputeSHA256([]byte(untruncatedDBName))) + ")"
		// 50 chars for dbName + 1 char for ( + 64 chars for sha256 + 1 char for ) = 116 chars
	}
	return dbName + "_"
}
1176938
func getPoolReconnect(ctx context.Context, pool *dbconnpool.ConnectionPool) (*dbconnpool.PooledDBConnection, error) {
	conn, err := pool.Get(ctx)
	if err != nil {
		return conn, err
	}
	// Run a test query to see if this connection is still good.
	if _, err := conn.ExecuteFetch("SELECT 1", 1, false); err != nil {
		// If we get a connection error, try to reconnect.
		if sqlErr, ok := err.(*mysql.SQLError); ok && (sqlErr.Number() == mysql.CRServerGone || sqlErr.Number() == mysql.CRServerLost) {
			if err := conn.Reconnect(); err != nil {
				conn.Recycle()
				return nil, err
			}
			return conn, nil
		}
		conn.Recycle()
		return nil, err
	}
	return conn, nil
}
494773
func (db *DB) ConnectionClosed(c *mysql.Conn) {
	db.mu.Lock()
	defer db.mu.Unlock()

	if db.t != nil {
		db.t.Logf("ConnectionClosed(%v): client %v", db.name, c.ConnectionID)
	}

	if _, ok := db.connections[c.ConnectionID]; !ok {
		db.t.Fatalf("BUG: Cannot delete connection from list of open connections because it is not registered. ID: %v Conn: %v", c.ConnectionID, c)
	}
	delete(db.connections, c.ConnectionID)
}
1188152
func (cp *Pool) Get(ctx context.Context) (*DBConn, error) {
	span, ctx := trace.NewSpan(ctx, "Pool.Get")
	defer span.Finish()

	if cp.isCallerIDAppDebug(ctx) {
		return NewDBConnNoPool(cp.appDebugParams, cp.dbaPool)
	}
	p := cp.pool()
	if p == nil {
		return nil, ErrConnPoolClosed
	}
	span.Annotate("capacity", p.Capacity())
	span.Annotate("in_use", p.InUse())
	span.Annotate("available", p.Available())
	span.Annotate("active", p.Active())

	r, err := p.Get(ctx)
	if err != nil {
		return nil, err
	}
	return r.(*DBConn), nil
}
279688
func (dbMan *dbManager) buildDeleteSql(tableName string, row common.Row, pkeys []string) string {

	var wherePlaceholders []string
	i := 1
	if row == nil {
		return ""
	}
	normalizedTableName := normalizeTableName(tableName)

	for _, pk := range pkeys {
		wherePlaceholders = append(wherePlaceholders, fmt.Sprintf("%s=$%v", pk, i))
		i++
	}

	sql := "DELETE FROM " + normalizedTableName
	sql += " WHERE "
	sql += strings.Join(wherePlaceholders, " AND ")

	return sql

}
615947
func (db *DB) conn() (*driverConn, error) {
	db.mu.Lock()
	if db.closed {
		db.mu.Unlock()
		return nil, errDBClosed
	}

	// If db.maxOpen > 0 and the number of open connections is over the limit
	// and there are no free connection, make a request and wait.
	if db.maxOpen > 0 && db.numOpen >= db.maxOpen && len(db.freeConn) == 0 {
		// Make the connRequest channel. It's buffered so that the
		// connectionOpener doesn't block while waiting for the req to be read.
		req := make(chan connRequest, 1)
		db.connRequests = append(db.connRequests, req)
		db.maybeOpenNewConnections()
		db.mu.Unlock()
		ret := <-req
		return ret.conn, ret.err
	}

	if c := len(db.freeConn); c > 0 {
		conn := db.freeConn[0]
		copy(db.freeConn, db.freeConn[1:])
		db.freeConn = db.freeConn[:c-1]
		conn.inUse = true
		db.mu.Unlock()
		return conn, nil
	}

	dsn := db.dsn
	db.numOpen++ // optimistically
	db.mu.Unlock()
	ci, err := db.driver.Open(dsn)
	if err != nil {
		db.mu.Lock()
		db.numOpen-- // correct for earlier optimism
		db.mu.Unlock()
		return nil, err
	}
	db.mu.Lock()
	dc := &driverConn{
		db:  db,
		ci:  ci,
		dsn: dsn,
	}
	db.addDepLocked(dc, dc)
	dc.inUse = true
	db.mu.Unlock()
	return dc, nil
}
1029614
func (session *Session) DB() *core.DB {
	if session.db == nil {
		session.db = session.engine.db
		session.stmtCache = make(map[uint32]*core.Stmt, 0)
	}
	return session.db
}
984076
func (s *EventStore) dbName(ctx context.Context) string {
	ns := eh.NamespaceFromContext(ctx)
	return s.dbPrefix + "_" + ns
}
1153664
func (provider *VersionedDBProvider) GetDBHandle(dbName string) (statedb.VersionedDB, error) {
	return newVersionedDB(provider.dbProvider.GetDBHandle(dbName), dbName), nil
}
534894
func (r *RedigoStore) getConn() (redis.Conn, error) {
	conn := r.pool.Get()

	// Select the specified database
	if r.db > 0 {
		if _, err := redis.String(conn.Do("SELECT", r.db)); err != nil {
			conn.Close()
			return nil, err
		}
	}

	return conn, nil
}
1096188
func ConnectMysqlDBConnStr(connStr string, name string) DBWrapper {
	dbWrapper := DBWrapper{}
	dbWrapper.Name = name
	db, err := sql.Open("mysql", connStr)
	if err != nil {
		dbWrapper.logError(err, connStr)
	} else {
		dbWrapper.DB = db
	}
	return dbWrapper
}
1003477
func (m *mysqlBackend) connectWithoutDB() (string, *sql.DB, error) {
	re := regexp.MustCompile("(.*)/([^?]+)")
	matches := re.FindStringSubmatch(m.Datasource.DSN)
	if len(matches) != 3 {
		return "", nil, fmt.Errorf("migrate: error parsing mysql dsn")
	}
	dsn := matches[1] + "/"
	database := matches[2]

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return "", nil, err
	}
	return database, db, err
}
783136
func (p *NodbProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
	if p.Exist(sid) {
		return nil, fmt.Errorf("new sid '%s' already exists", sid)
	}

	kvs := make([]byte, 0)
	if p.Exist(oldsid) {
		if kvs, err = p.c.Get([]byte(oldsid)); err != nil {
			return nil, err
		} else if _, err = p.c.Del([]byte(oldsid)); err != nil {
			return nil, err
		}
	}

	if err = p.c.Set([]byte(sid), kvs); err != nil {
		return nil, err
	} else if _, err = p.c.Expire([]byte(sid), p.expire); err != nil {
		return nil, err
	}

	var kv map[interface{}]interface{}
	if len(kvs) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = session.DecodeGob([]byte(kvs))
		if err != nil {
			return nil, err
		}
	}

	return NewNodbStore(p.c, sid, p.expire, kv), nil
}
1322485
func (pc *PooledDBConnection) Reconnect() error {
	pc.DBConnection.Close()
	newConn, err := NewDBConnection(pc.pool.info, pc.mysqlStats)
	if err != nil {
		return err
	}
	pc.DBConnection = newConn
	return nil
}
911931
func (s *RestoreDBInstanceToPointInTimeInput) SetDBName(v string) *RestoreDBInstanceToPointInTimeInput {
	s.DBName = &v
	return s
}