@@ -41,21 +41,28 @@ func (d *Database) DBTypeMetric() prometheus.Metric {
4141 )
4242}
4343
44+ // ping the database. If the database is disconnected, try to reconnect.
45+ // If the database type is unknown, try to reload it.
4446func (d * Database ) ping (logger * slog.Logger ) error {
4547 ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
4648 defer cancel ()
4749 err := d .Session .PingContext (ctx )
4850 if err != nil {
4951 d .Up = 0
52+ // If database is closed, try to reconnect
5053 if strings .Contains (err .Error (), "sql: database is closed" ) {
5154 db , dbtype := connect (logger , d .Name , d .Config )
5255 d .Session = db
5356 d .Type = dbtype
5457 }
55- } else {
56- d .Up = 1
58+ return err
5759 }
58- return err
60+ // if connected but database type is unknown, try to reload it
61+ if d .Type == - 1 {
62+ d .Type = getDBtype (ctx , d .Session , logger , d .Name )
63+ }
64+ d .Up = 1
65+ return nil
5966}
6067
6168func (d * Database ) constLabels () map [string ]string {
@@ -188,16 +195,21 @@ func connect(logger *slog.Logger, dbname string, dbconfig DatabaseConfig) (*sql.
188195 logger .Info ("Could not set CLIENT_INFO." , "database" , dbname )
189196 }
190197
191- var result int
192- if err := db .QueryRowContext (ctx , "select sys_context('USERENV', 'CON_ID') from dual" ).Scan (& result ); err != nil {
193- logger .Info ("dbtype err" , "error" , err , "database" , dbname )
194- }
195-
196198 var sysdba string
197199 if err := db .QueryRowContext (ctx , "select sys_context('USERENV', 'ISDBA') from dual" ).Scan (& sysdba ); err != nil {
198200 logger .Error ("error checking my database role" , "error" , err , "database" , dbname )
199201 }
200202 logger .Info ("Connected as SYSDBA? " + sysdba , "database" , dbname )
201203
202- return db , float64 (result )
204+ dbtype := getDBtype (ctx , db , logger , dbname )
205+ return db , dbtype
206+ }
207+
208+ func getDBtype (ctx context.Context , db * sql.DB , logger * slog.Logger , dbname string ) float64 {
209+ var dbtype int
210+ if err := db .QueryRowContext (ctx , "select sys_context('USERENV', 'CON_ID') from dual" ).Scan (& dbtype ); err != nil {
211+ logger .Info ("dbtype err" , "error" , err , "database" , dbname )
212+ return - 1
213+ }
214+ return float64 (dbtype )
203215}
0 commit comments