tempestas

A REST API for processing sensor.community data
git clone https://git.bracken.jp/tempestas.git
Log | Files | Refs | README | LICENSE

commit f15c48a2e40cc62921919f9d60b4e412840de4bb
parent 3f892c246b1f5257a2d9829c9ffa99f4d997e96c
Author: Chris Bracken <chris@bracken.jp>
Date:   Thu, 11 Nov 2021 14:16:36 -0800

Ensure DB connection is up at connect time

sql.Open doesn't guarantee that the database can be connected to; just
that it was able to create the sql.DB object. To ensure that we can
connect to the database, we now ping the database immediately after
sql.Open.

Diffstat:
Mstorage/storage.go | 11+++++++++++
1 file changed, 11 insertions(+), 0 deletions(-)

diff --git a/storage/storage.go b/storage/storage.go @@ -1,6 +1,7 @@ package storage import ( + "context" "database/sql" "fmt" "time" @@ -21,10 +22,20 @@ type DataStore struct { func Connect(dbname string, user string, password string) *DataStore { var s = new(DataStore) var err error + + // Create the database object. A nil error does not guarantee the DB is connected. dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, password, dbname) if s.db, err = sql.Open("postgres", dbinfo); err != nil { panic("Error connecting to database") } + + // Ping the DB to verify we can connect. + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + if err := s.db.PingContext(ctx); err != nil { + panic("Error connecting to database") + } + return s }