wahyu eko hadi saputro
wahyu eko hadi saputro

Reputation: 427

cockroarch DB "conn closed"

            var db *pgx.Conn //database

            func ConnectCockroachDB() {
                var dbUri string = "testurl"
                conn, err := pgx.Connect(context.Background(), dbUri)
                if err != nil {
                    fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
                    os.Exit(1)
                }
                db = conn
            }

            //returns a handle to the DB object
            func GetDB() *pgx.Conn {
                if db == nil {
                    ConnectCockroachDB()
                }
                return db
            }

but after i restart the DB, the application can not connect automatically. the error is "conn closed". i need to restart the application to make the app working

Upvotes: 1

Views: 144

Answers (2)

rafiss
rafiss

Reputation: 583

Since you're using pgx, you might want to try using pgxpool to connect: https://pkg.go.dev/github.com/jackc/pgx/v4/pgxpool

It will automatically take care of creating a new connection if the old one got closed. It also already supports concurrent usage.

Upvotes: 1

Kelsnare
Kelsnare

Reputation: 705

to just answer your question:

func GetDB() *pgx.Conn {
    if db == nil || db.IsClosed() {
        ConnectCockroachDB()
    }
    return db
}

However, this code is not safe for use from multiple goroutines. There should be a lock for accessing and updating the global db instance to avoid race conditions.

Upvotes: 1

Related Questions