89 lines
1.8 KiB
Go
89 lines
1.8 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
type Store interface {
|
|
Querier
|
|
PurchaseOrderTx(ctx context.Context, arg PurchasoOrderTxParams) (PurchaseOrderTxResult, error)
|
|
CreateUserMerchantTx(ctx context.Context, arg UserMerchantTxParams) (UserMerchantTxResult, error)
|
|
SaleOrderTx(ctx context.Context, arg SaleOrderTxParams) (SaleOrderTxResult, error)
|
|
}
|
|
|
|
type SQLStore struct {
|
|
*Queries
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewStore(db *sql.DB) Store {
|
|
return &SQLStore{
|
|
db: db,
|
|
Queries: New(db),
|
|
}
|
|
}
|
|
|
|
func (store *SQLStore) execTx(ctx context.Context, fn func(*Queries) error) error {
|
|
tx, err := store.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
q := New(tx)
|
|
err = fn(q)
|
|
if err != nil {
|
|
if rbErr := tx.Rollback(); rbErr != nil {
|
|
return fmt.Errorf("tx err: %v, rb err : %v", err, rbErr)
|
|
}
|
|
return err
|
|
}
|
|
|
|
return tx.Commit()
|
|
|
|
}
|
|
|
|
type UserMerchantTxParams struct {
|
|
Email string `json:"email"`
|
|
Fullname string `json:"fullname"`
|
|
Password string `json:"password"`
|
|
OutletName string `json:"outlet_name"`
|
|
}
|
|
|
|
type UserMerchantTxResult struct {
|
|
OwnerProfile User `json:"owner_profile"`
|
|
OutletProfile Merchant `json:"outlet_profile"`
|
|
}
|
|
|
|
func (store *SQLStore) CreateUserMerchantTx(ctx context.Context, arg UserMerchantTxParams) (UserMerchantTxResult, error) {
|
|
var result UserMerchantTxResult
|
|
err := store.execTx(ctx, func(q *Queries) error {
|
|
var err error
|
|
|
|
result.OwnerProfile, err = q.CreateUser(ctx, CreateUserParams{
|
|
Email: arg.Email,
|
|
Password: arg.Password,
|
|
Fullname: arg.Fullname,
|
|
})
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
result.OutletProfile, err = q.CreateMerchant(ctx, CreateMerchantParams{
|
|
Name: arg.OutletName,
|
|
OwnerID: result.OwnerProfile.ID,
|
|
})
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
return result, err
|
|
|
|
}
|