在一个函数(Golang、Gocql、Cassandra)中基于过滤器输入(vendor_id、customer_id、order_status_id ... 或所有非空字段)编写查询的最佳方法是什么?我不想在每种情况下都编写新函数,例如以下仅按 customerID 过滤的函数:
func (repo *orderRepo) FindByCustomerId(req *pb.FindRequest) (*pb.OrdersResponse, error) {
offset := req.GetOffset()
limit := req.GetLimit()
customerID := req.GetCustomerId()
//vendorID := req.GetVendorId()
//orderStatusID := req.GetOrderStatusId()
var (
orders []*pb.Order
count int32
)
if err := repo.session.Query(`SELECT count(1) FROM orders WHERE customer_id = ?`, customerID).
Scan(&count); err != nil {
return nil, err
}
if offset < count {
query := repo.session.Query(`SELECT
id,
customer_id,
customer_name,
vendor_id,
toJSON(items),
paid_at,
created_at,
order_status_id
FROM orders WHERE customer_id = ?`, customerID)
defer query.Release()
var ps []byte
iter := query.PageState(ps).PageSize(int(offset % limit)).Iter()
ps = iter.PageState()
page := offset / limit
var i int32
for i = 0; i < page; i++ {
iter = query.PageState(ps).PageSize(int(limit)).Iter()
ps = iter.PageState()
}
iter = query.PageState(ps).PageSize(int(limit)).Iter()
rows := iter.Scanner()
for rows.Next() {
var (
order pb.Order
createdAt time.Time
paidAt time.Time
itemsJSON []byte
)
if err := rows.Scan(
&order.Id,
&order.CustomerId,
&order.CustomerName,
&order.VendorId,
&itemsJSON,
&paidAt,
&createdAt,
&order.OrderStatusId,
); err != nil {
return nil, err
}
if err := json.Unmarshal(itemsJSON, &order.Items); err != nil {
return nil, err
}
order.PaidAt = paidAt.String()
order.CreatedAt = createdAt.String()
orders = append(orders, &order)
}
if err := iter.Close(); err != nil {
return nil, err
}
}
return &pb.OrdersResponse{
Orders: orders,
Count: count,
}, nil
}
我需要为上述查询动态添加参数