github.com/tommi2day/gomodules/dblib@v0.0.0-20230217211148-82cdbcf0a79d/db.go (about)

     1  // Package dblib collection of db func
     2  package dblib
     3  
     4  import (
     5  	"context"
     6  	"database/sql"
     7  	"time"
     8  
     9  	log "github.com/sirupsen/logrus"
    10  )
    11  
    12  // https://www.alexedwards.net/blog/how-to-manage-database-timeouts-and-cancellations-in-go
    13  // https://github.com/sijms/go-ora/#version-241-add-support-for-connection-time-out--context-read-and-write
    14  
    15  // DBConnect connect to a database using connect string
    16  func DBConnect(driver string, source string, timeout int) (db *sql.DB, err error) {
    17  	const defaultTimeout = 5
    18  	// Create a new child context with a 5-second timeout, using the
    19  	// provided ctx parameter as the parent.
    20  
    21  	if timeout < defaultTimeout {
    22  		timeout = defaultTimeout
    23  	}
    24  	log.Debugf("try to connect, timeout %d", timeout)
    25  	db, err = sql.Open(driver, source)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	// Create a context with timeout, using the empty
    31  	// context.Background() as the parent.
    32  	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
    33  	defer cancel()
    34  
    35  	// Use this when testing the connection pool.
    36  	if err = db.PingContext(ctx); err != nil {
    37  		log.Debugf("DB Connect returned error= %s", err)
    38  		return nil, err
    39  	}
    40  	log.Debugf("DB Connect success")
    41  	return db, err
    42  }
    43  
    44  // SelectOneStringValue Select a single string
    45  func SelectOneStringValue(db *sql.DB, sql string) (queryResult string, err error) {
    46  	row := db.QueryRow(sql)
    47  	err = row.Scan(&queryResult)
    48  	if err != nil {
    49  		if isOerr, _, msg := HaveOerr(err); isOerr {
    50  			log.Warnf("Oracle Error %s", msg)
    51  		} else {
    52  			log.Warnf("got error %s", err)
    53  		}
    54  	}
    55  	return
    56  }