github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/dal/database.go (about)

     1  package dal
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"time"
     8  
     9  	"github.com/octohelm/storage/internal/sql/adapter"
    10  	"github.com/octohelm/storage/pkg/migrator"
    11  	"github.com/octohelm/storage/pkg/sqlbuilder"
    12  
    13  	_ "github.com/octohelm/storage/internal/sql/adapter/postgres"
    14  	_ "github.com/octohelm/storage/internal/sql/adapter/sqlite"
    15  )
    16  
    17  func ConfigureAdapter(a adapter.Adapter, poolSize int, maxConnDur time.Duration) {
    18  	if setting, ok := a.(adapter.DBSetting); ok {
    19  		setting.SetMaxOpenConns(poolSize)
    20  		setting.SetMaxIdleConns(poolSize / 2)
    21  		setting.SetConnMaxLifetime(maxConnDur)
    22  	}
    23  }
    24  
    25  type Database struct {
    26  	// Endpoint of database
    27  	Endpoint string `flag:""`
    28  	// auto migrate before run
    29  	EnableMigrate bool `flag:",omitempty"`
    30  
    31  	name   string
    32  	tables *sqlbuilder.Tables
    33  	db     adapter.Adapter
    34  }
    35  
    36  func (d *Database) SetDefaults() {
    37  	if d.Endpoint == "" {
    38  		cwd, _ := os.Getwd()
    39  		d.Endpoint = fmt.Sprintf("sqlite://%s/%s.sqlite", cwd, d.name)
    40  	}
    41  }
    42  
    43  func (d *Database) ApplyCatalog(name string, tables ...*sqlbuilder.Tables) {
    44  	d.name = name
    45  	d.tables = &sqlbuilder.Tables{}
    46  
    47  	for i := range tables {
    48  		tables[i].Range(func(tab sqlbuilder.Table, idx int) bool {
    49  			d.tables.Add(tab)
    50  			return true
    51  		})
    52  	}
    53  }
    54  
    55  func (d *Database) Init(ctx context.Context) error {
    56  	if d.db != nil {
    57  		return nil
    58  	}
    59  
    60  	db, err := adapter.Open(ctx, d.Endpoint)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	d.db = db
    65  
    66  	ConfigureAdapter(d.db, 10, 1*time.Hour)
    67  
    68  	registerSessionCatalog(d.name, d.tables)
    69  
    70  	return nil
    71  }
    72  
    73  func (d *Database) InjectContext(ctx context.Context) context.Context {
    74  	return InjectContext(ctx, New(d.db, d.name))
    75  }
    76  
    77  func (d *Database) Run(ctx context.Context) error {
    78  	if d.EnableMigrate == false {
    79  		return nil
    80  	}
    81  	return migrator.Migrate(ctx, d.db, d.tables)
    82  }