75 lines
1.5 KiB
Go
75 lines
1.5 KiB
Go
package models
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// CardPrice -
|
|
type CardPrice struct {
|
|
ID string `db:"id" cc:"id"`
|
|
Card string `db:"card" cc:"card"`
|
|
PriceN float32 `db:"price_n" cc:"price_n"`
|
|
PriceF float32 `db:"price_f" cc:"price_f"`
|
|
Ctime time.Time `db:"ctime" cc:"ctime"`
|
|
}
|
|
|
|
// InsertCardPriceOpts -
|
|
type InsertCardPriceOpts struct {
|
|
Data []CardPrice
|
|
}
|
|
|
|
// InsertCardPrice -
|
|
func InsertCardPrice(arg InsertCardPriceOpts) (err error) {
|
|
if len(arg.Data) == 0 {
|
|
return errors.New("data list is empty")
|
|
}
|
|
|
|
tmp := make([]CardPrice, 0, len(arg.Data))
|
|
|
|
for _, v := range arg.Data {
|
|
if len(v.Card) > 0 {
|
|
tmp = append(tmp, v)
|
|
}
|
|
}
|
|
|
|
query := `insert into "public"."card_price" ("card", "price_n", "price_f", "ctime") values `
|
|
insStr := ""
|
|
|
|
vals := make([]interface{}, 0, len(tmp)*3)
|
|
for i := 0; i < len(tmp); i++ {
|
|
if len(insStr) > 0 {
|
|
insStr += ","
|
|
}
|
|
|
|
insStr += " (?, ?, ?, now()) "
|
|
vals = append(vals, tmp[i].Card, tmp[i].PriceN, tmp[i].PriceF)
|
|
}
|
|
|
|
query = x.Rebind(query + insStr)
|
|
_, err = x.Exec(query, vals...)
|
|
|
|
return
|
|
}
|
|
|
|
// GetCardsLastPrice -
|
|
func GetCardsLastPrice(ids []string) (price []*CardPrice, err error) {
|
|
if len(ids) == 0 {
|
|
return nil, errors.New("no card id")
|
|
}
|
|
|
|
query := `select distinct on (cp.id) cp.id, cp.card, cp.price_n, cp.price_f, cp.ctime from card_price cp where cp.card in (?) order by cp.id, cp.ctime desc`
|
|
|
|
query, args, err := sqlx.In(query, ids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
query = x.Rebind(query)
|
|
err = x.Select(&price, query, args...)
|
|
|
|
return
|
|
}
|