github.com/tuingking/flamingo@v0.0.0-20220403134817-2796ae0e84ca/internal/product/repository.go (about)

     1  package product
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/pkg/errors"
     7  	"github.com/tuingking/flamingo/infra/mysql"
     8  )
     9  
    10  type Repository interface {
    11  	FindAll(ctx context.Context) ([]Product, error)
    12  	Create(ctx context.Context, v Product) (Product, error)
    13  }
    14  
    15  type repository struct {
    16  	mysql mysql.MySQL
    17  }
    18  
    19  func NewRepository(mysql mysql.MySQL) Repository {
    20  	return &repository{
    21  		mysql: mysql,
    22  	}
    23  }
    24  
    25  func (r *repository) FindAll(ctx context.Context) ([]Product, error) {
    26  	var res []Product
    27  
    28  	query := `SELECT id, name FROM product LIMIT 100`
    29  
    30  	rows, err := r.mysql.QueryContext(ctx, query)
    31  	if err != nil {
    32  		return res, errors.Wrap(err, "exec query")
    33  	}
    34  	defer rows.Close()
    35  
    36  	for rows.Next() {
    37  		var v Product
    38  		if err := rows.Scan(
    39  			&v.ID,
    40  			&v.Name,
    41  		); err != nil {
    42  			return res, errors.Wrap(err, "row scan")
    43  		}
    44  
    45  		res = append(res, v)
    46  	}
    47  
    48  	return res, nil
    49  }
    50  
    51  func (r *repository) Create(ctx context.Context, v Product) (Product, error) {
    52  	// dbStat := r.mysql.Stats()
    53  	// now := time.Now()
    54  	// defer func() {
    55  	// 	logrus.WithFields(logrus.Fields{
    56  	// 		"MaxOpenConnections": dbStat.MaxOpenConnections,
    57  	// 		"OpenConnections":    dbStat.OpenConnections,
    58  	// 		"InUse":              dbStat.InUse,
    59  	// 		"Idle":               dbStat.Idle,
    60  	// 		"Elapsed":            time.Since(now),
    61  	// 	}).Info(v.Name)
    62  	// }()
    63  
    64  	query := `INSERT INTO product(name, price) VALUES(?,?)`
    65  
    66  	res, err := r.mysql.ExecContext(ctx, query, v.Name, v.Price)
    67  	if err != nil {
    68  		return v, errors.Wrap(err, "exec query")
    69  	}
    70  
    71  	id, err := res.LastInsertId()
    72  	if err != nil {
    73  		return v, errors.Wrap(err, "get last insert ID")
    74  	}
    75  	v.ID = id
    76  
    77  	return v, nil
    78  }