2019-01-16 08:53:08 +00:00
package models
import (
"errors"
"time"
2019-01-22 09:42:18 +00:00
"github.com/jmoiron/sqlx"
2019-01-16 08:53:08 +00:00
)
// CardPrice -
type CardPrice struct {
2019-01-22 09:42:18 +00:00
ID string ` db:"id" cc:"id" `
2019-01-16 08:53:08 +00:00
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" `
}
2019-01-18 08:39:02 +00:00
// InsertCardPriceOpts -
2019-01-16 08:53:08 +00:00
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 := ""
2019-01-18 08:39:02 +00:00
vals := make ( [ ] interface { } , 0 , len ( tmp ) * 3 )
2019-01-16 08:53:08 +00:00
for i := 0 ; i < len ( tmp ) ; i ++ {
if len ( insStr ) > 0 {
insStr += ","
}
2019-01-18 08:39:02 +00:00
insStr += " (?, ?, ?, now()) "
vals = append ( vals , tmp [ i ] . Card , tmp [ i ] . PriceN , tmp [ i ] . PriceF )
2019-01-16 08:53:08 +00:00
}
2019-01-18 08:39:02 +00:00
query = x . Rebind ( query + insStr )
_ , err = x . Exec ( query , vals ... )
return
}
2019-01-22 09:42:18 +00:00
// GetCardsLastPrice -
func GetCardsLastPrice ( ids [ ] string ) ( price [ ] * CardPrice , err error ) {
if len ( ids ) == 0 {
return nil , errors . New ( "no card id" )
2019-01-18 08:39:02 +00:00
}
2019-01-22 09:42:18 +00:00
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 )
2019-01-18 08:39:02 +00:00
if err != nil {
return nil , err
}
2019-01-16 08:53:08 +00:00
2019-01-22 09:42:18 +00:00
query = x . Rebind ( query )
err = x . Select ( & price , query , args ... )
2019-01-16 08:53:08 +00:00
return
}