Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with reconnection to postgres #1011

Open
mrkaspa opened this issue Jul 29, 2024 · 1 comment
Open

Problem with reconnection to postgres #1011

mrkaspa opened this issue Jul 29, 2024 · 1 comment
Labels

Comments

@mrkaspa
Copy link

mrkaspa commented Jul 29, 2024

I am using a global connection like this:

var dbConn *bun.DB

// GetDB gets the pointer to the database.
func GetDB() *bun.DB {
	return dbConn
}

// Close the DB connection
func Close() {
	if dbConn != nil {
		dbConn.Close()
	}
}

// Connect to the database
func Connect() error {
	if dbConn != nil {
		return nil
	}

	cfg := config.GetConfig()
	sslMode := "disable"
	if cfg.DatabaseSSLMode {
		sslMode = "require"
	}
	dsn := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s",
		cfg.DatabaseUser, cfg.DatabasePassword, cfg.DatabaseHost, cfg.DatabasePort, cfg.DatabaseName, sslMode)
	sqlDB := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))

	dbConn = bun.NewDB(sqlDB, pgdialect.New())
	maxOpenConns := 2 * runtime.GOMAXPROCS(0)
	dbConn.SetMaxIdleConns(maxOpenConns)
	dbConn.SetMaxOpenConns(maxOpenConns)

	_, err := dbConn.ExecContext(context.Background(), "SELECT 1")
	if err != nil {
		sentry.CaptureException(err)
		return err
	}

	return nil
}

and when I use this connection I am getting this error:

sql: database is closed

My question is if the pgdriver handles someway the reconnection to the Database Server, perhaps there is a parameter to pass to the connection, because the Database is not down and if I restart the container it works

Copy link

This issue has been automatically marked as stale because it has not had activity in the last 30 days. If there is no update within the next 7 days, this issue will be closed.

@github-actions github-actions bot added the stale label Nov 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant