package order import ( "context" "github.com/jmoiron/sqlx" "sismedika.com/sas/westone/types" ) type Store struct { db *sqlx.DB } func NewStore(db *sqlx.DB) *Store { return &Store{db: db} } func (s *Store) CreateOrder(order types.Order) (int, error) { // Start a new transaction tx, err := s.db.BeginTxx(context.Background(), nil) if err != nil { return 0, err } // Defer rollback to ensure transaction is rolled back in case of an error defer func() { if err != nil { tx.Rollback() } }() query := `INSERT INTO orders (userId, total, status, address) VALUES (:userId, :total, :status, :address)` // Using tx.NamedExec to insert the order within the transaction res, err := tx.NamedExec(query, order) if err != nil { return 0, err } // Retrieving the last inserted ID id, err := res.LastInsertId() if err != nil { return 0, err } // Commit the transaction if everything succeeded if err = tx.Commit(); err != nil { return 0, err } return int(id), nil } func (s *Store) CreateOrderItem(orderItem types.OrderItem) error { // Start a new transaction tx, err := s.db.BeginTxx(context.Background(), nil) if err != nil { return err } // Defer rollback to ensure transaction is rolled back in case of an error defer func() { if err != nil { tx.Rollback() } }() query := `INSERT INTO order_items (orderId, productId, quantity, price) VALUES (:orderId, :productId, :quantity, :price)` // Using tx.NamedExec to insert the order item within the transaction _, err = tx.NamedExec(query, orderItem) if err != nil { return err } // Commit the transaction if everything succeeded if err = tx.Commit(); err != nil { return err } return nil }