github.com/condensat/bank-core@v0.1.0/database/database.go (about)

     1  // Copyright 2020 Condensat Tech. All rights reserved.
     2  // Use of this source code is governed by a MIT
     3  // license that can be found in the LICENSE file.
     4  
     5  package database
     6  
     7  import (
     8  	"errors"
     9  	"log"
    10  	"os"
    11  
    12  	"github.com/jinzhu/gorm"
    13  )
    14  
    15  const (
    16  	DatabaseFloatingPrecision = 12
    17  )
    18  
    19  var (
    20  	ErrInvalidDatabase = errors.New("Invalid database")
    21  )
    22  
    23  type Database struct {
    24  	db *gorm.DB
    25  }
    26  
    27  // New create new mysql connection
    28  // pannic if failed to connect
    29  func New(options Options) Context {
    30  	db := connectMyql(
    31  		options.HostName, options.Port,
    32  		options.User, secretOrPassword(options.Password),
    33  		options.Database,
    34  	)
    35  
    36  	db.LogMode(options.EnableLogging)
    37  	db.SetLogger(log.New(os.Stderr, "", 0))
    38  
    39  	return &Database{
    40  		db: db,
    41  	}
    42  }
    43  
    44  // DB returns subsequent db connection
    45  // see Context interface
    46  func (d *Database) DB() DB {
    47  	return d.db
    48  }
    49  
    50  func (p *Database) Migrate(models []Model) error {
    51  	var interfaces []interface{}
    52  	for _, model := range models {
    53  		interfaces = append(interfaces, model)
    54  	}
    55  	return p.db.AutoMigrate(
    56  		interfaces...,
    57  	).Error
    58  }
    59  
    60  func (p *Database) Transaction(txFunc func(tx Context) error) error {
    61  	return p.db.Transaction(func(tx *gorm.DB) error {
    62  		return txFunc(&Database{db: tx})
    63  	})
    64  }