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" ) func (d *DB) CreateBenefactorAddress(ctx context.Context, address entity.Address) (entity.Address, error) { const op = "mysqlbenefactor.createBenefactorAddress" // Get Province ID by City ID var provinceID uint pErr := d.conn.Conn().QueryRowContext(ctx, `SELECT province_id FROM cities WHERE id = ?`, address.CityID).Scan(&provinceID) if pErr != nil && pErr != sql.ErrNoRows { return entity.Address{}, richerror.New(op).WithErr(pErr). WithMessage("error querying for existing main address").WithKind(richerror.KindUnexpected) } 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.ErrorMsgNotFound).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("error retrieving last insert id").WithKind(richerror.KindUnexpected) } address.ID = uint(id) return address, nil }