niki/repository/mysql/address/create.go

52 lines
1.7 KiB
Go
Raw Permalink Normal View History

package mysqladdress
import (
"context"
"database/sql"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
2024-01-19 16:37:15 +00:00
func (d *DB) CreateBenefactorAddress(ctx context.Context, address entity.Address) (entity.Address, error) {
const op = "mysqladdress.createBenefactorAddress"
provinceID, err := d.getProvinceIDByCityID(ctx, address.CityID)
if err != nil {
return entity.Address{}, err
2024-05-26 16:26:18 +00:00
}
address.ProvinceID = provinceID
// Insert the new address
res, err := d.conn.Conn().ExecContext(ctx, `INSERT INTO addresses (postal_code, address, lat, lon, name, city_id, province_id, benefactor_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
address.PostalCode, address.Address, address.Lat, address.Lon, address.Name, address.CityID, provinceID, address.BenefactorID)
if err != nil {
return entity.Address{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantInsertRecord).WithKind(richerror.KindUnexpected)
}
// Get the ID of the newly inserted record
id, err := res.LastInsertId()
if err != nil {
return entity.Address{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantRetrieveLastInsertID).WithKind(richerror.KindUnexpected)
}
address.ID = uint(id)
return address, nil
}
func (d *DB) getProvinceIDByCityID(ctx context.Context, cityID uint) (uint, error) {
const op = "mysqladdress.getProvinceIDByCityID"
var provinceID uint
pErr := d.conn.Conn().QueryRowContext(ctx, `SELECT province_id FROM cities WHERE id = ?`, cityID).Scan(&provinceID)
if pErr != nil && pErr != sql.ErrNoRows {
return 0, richerror.New(op).WithErr(pErr).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return provinceID, nil
}