github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/db/sql_adapter.go (about)

     1  package db
     2  
     3  import (
     4  	"database/sql"
     5  	"time"
     6  
     7  	"github.com/safedep/dry/log"
     8  	"golang.org/x/net/context"
     9  	"gorm.io/gorm"
    10  )
    11  
    12  // SqlDataAdapter represents a contract for implementing RDBMS data adapters
    13  type SqlDataAdapter interface {
    14  	GetDB() (*gorm.DB, error)
    15  	GetConn() (*sql.DB, error)
    16  	Migrate(...interface{}) error
    17  	Ping() error
    18  }
    19  
    20  type SqlAdapterConfig struct {
    21  	MaxIdleConnections int
    22  	MaxOpenConnections int
    23  }
    24  
    25  var defaultSqlAdapterConfig SqlAdapterConfig = SqlAdapterConfig{
    26  	MaxIdleConnections: 5,
    27  	MaxOpenConnections: 50,
    28  }
    29  
    30  func DefaultSqlAdapterConfig() SqlAdapterConfig {
    31  	return defaultSqlAdapterConfig
    32  }
    33  
    34  type baseSqlAdapter struct {
    35  	db     *gorm.DB
    36  	config *SqlAdapterConfig
    37  }
    38  
    39  func (m *baseSqlAdapter) Config() *SqlAdapterConfig {
    40  	if m.config != nil {
    41  		return m.config
    42  	}
    43  
    44  	return &defaultSqlAdapterConfig
    45  }
    46  
    47  func (m *baseSqlAdapter) SetupConnectionPool() error {
    48  	conn, err := m.GetConn()
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	log.Debugf("Setting up connection pool with max idle connections: %d, max open connections: %d",
    54  		m.Config().MaxIdleConnections, m.Config().MaxOpenConnections)
    55  
    56  	conn.SetMaxIdleConns(m.Config().MaxIdleConnections)
    57  	conn.SetMaxOpenConns(m.Config().MaxOpenConnections)
    58  
    59  	return nil
    60  }
    61  
    62  func (m *baseSqlAdapter) GetDB() (*gorm.DB, error) {
    63  	return m.db, nil
    64  }
    65  
    66  func (m *baseSqlAdapter) GetConn() (*sql.DB, error) {
    67  	db, err := m.GetDB()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	return db.DB()
    73  }
    74  
    75  func (m *baseSqlAdapter) Migrate(tables ...interface{}) error {
    76  	return m.db.AutoMigrate(tables...)
    77  }
    78  
    79  func (m *baseSqlAdapter) Ping() error {
    80  	sqlDB, err := m.GetConn()
    81  	if err != nil {
    82  		return err
    83  	}
    84  
    85  	ctx, cFunc := context.WithTimeout(context.Background(), 2*time.Second)
    86  	defer cFunc()
    87  
    88  	log.Debugf("Pinging database server")
    89  	return sqlDB.PingContext(ctx)
    90  }