github.com/profzone/eden-framework@v1.0.10/pkg/client/postgre/postgres_endpoint.go (about)

     1  package confpostgres
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"github.com/profzone/eden-framework/pkg/sqlx"
     7  	"github.com/profzone/eden-framework/pkg/sqlx/postgresqlconnector"
     8  	"github.com/profzone/envconfig"
     9  	"time"
    10  )
    11  
    12  type PostgresEndpoint struct {
    13  	Endpoint envconfig.Endpoint `env:""`
    14  	Database *sqlx.Database     `env:"-"`
    15  
    16  	Extensions      []string
    17  	PoolSize        int
    18  	ConnMaxLifetime envconfig.Duration
    19  
    20  	*sqlx.DB `env:"-"`
    21  }
    22  
    23  func (m *PostgresEndpoint) LivenessCheck() map[string]string {
    24  	s := map[string]string{}
    25  
    26  	_, err := m.DB.ExecContext(context.Background(), "SELECT 1")
    27  	if err != nil {
    28  		s[m.Endpoint.Host()] = err.Error()
    29  	} else {
    30  		s[m.Endpoint.Host()] = "ok"
    31  	}
    32  
    33  	return s
    34  }
    35  
    36  func (m *PostgresEndpoint) SetDefaults() {
    37  	if m.PoolSize == 0 {
    38  		m.PoolSize = 10
    39  	}
    40  
    41  	if m.ConnMaxLifetime == 0 {
    42  		m.ConnMaxLifetime = envconfig.Duration(1 * time.Hour)
    43  	}
    44  
    45  	if m.Endpoint.IsZero() {
    46  		m.Endpoint.Hostname = "127.0.0.1"
    47  		m.Endpoint.Port = 5432
    48  	}
    49  
    50  	if m.Database.Name == "" {
    51  		if len(m.Endpoint.Base) > 0 {
    52  			m.Database.Name = m.Endpoint.Base
    53  		}
    54  	}
    55  }
    56  
    57  func (m *PostgresEndpoint) url(host string) string {
    58  	password := m.Endpoint.Password
    59  	if password != "" {
    60  		password = ":" + password
    61  	}
    62  	return fmt.Sprintf("postgres://%s%s@%s", m.Endpoint.Username, password, host)
    63  }
    64  
    65  func (m *PostgresEndpoint) conn(host string) (*sqlx.DB, error) {
    66  	db := m.Database.OpenDB(&postgresqlconnector.PostgreSQLConnector{
    67  		Host:       m.url(host),
    68  		Extra:      m.Endpoint.Extra.Encode(),
    69  		Extensions: m.Extensions,
    70  	})
    71  
    72  	db.SetMaxOpenConns(m.PoolSize)
    73  	db.SetMaxIdleConns(m.PoolSize / 2)
    74  	db.SetConnMaxLifetime(time.Duration(m.ConnMaxLifetime))
    75  
    76  	_, err := db.ExecContext(context.Background(), "SELECT 1")
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  	return db, nil
    81  }
    82  
    83  func (m *PostgresEndpoint) Init() {
    84  	r := Retry{Repeats: 5, Interval: envconfig.Duration(1 * time.Second)}
    85  
    86  	err := r.Do(func() error {
    87  		db, err := m.conn(m.Endpoint.Host())
    88  		if err != nil {
    89  			return err
    90  		}
    91  		m.DB = db
    92  		return nil
    93  	})
    94  
    95  	if err != nil {
    96  		panic(err)
    97  	}
    98  }