You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package data
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"valuation/internal/biz"
"valuation/internal/conf"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/wire"
)
// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewPriceRuleInterface)
// Data .
type Data struct {
// TODO wrapped database client
Mdb *gorm.DB
}
// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
data := &Data{}
// 初始Mdb
// 连接mysql使用配置
dsn := c.Database.Source
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
data.Mdb = nil
log.Fatal(err)
}
data.Mdb = db
// 三开发阶段自动迁移表。发布阶段表结构稳定不需要migrate.
migrateTable(db)
cleanup := func() {
log.NewHelper(logger).Info("closing the data resources")
}
return data, cleanup, nil
}
func migrateTable(db *gorm.DB) {
if err := db.AutoMigrate(&biz.PriceRule{}); err != nil {
log.Info("price_rule table migrate error, err:", err)
}
rules := []biz.PriceRule{
{
Model: gorm.Model{ID: 1},
PriceRuleWork: biz.PriceRuleWork{
CityID: 1,
StartFee: 300,
DistanceFee: 35,
DurationFee: 10, // 5m
StartAt: 7,
EndAt: 23,
},
},
{
Model: gorm.Model{ID: 2},
PriceRuleWork: biz.PriceRuleWork{
CityID: 1,
StartFee: 350,
DistanceFee: 35,
DurationFee: 10, // 5m
StartAt: 23,
EndAt: 24,
},
},
{
Model: gorm.Model{ID: 3},
PriceRuleWork: biz.PriceRuleWork{
CityID: 1,
StartFee: 400,
DistanceFee: 35,
DurationFee: 10, // 5m
StartAt: 0,
EndAt: 7,
},
},
}
db.Clauses(clause.OnConflict{UpdateAll: true}).Create(rules) //一旦发生冲突 全部更新
//SELECT * FROM `price_rules` WHERE (city_id=1 AND start_at >= 9 AND end_at < 9) AND `price_rules`.`deleted_at` IS NULL ORDER BY `price_rules`.`id` LIMIT 1
//SELECT * FROM `price_rules` WHERE (city_id=1 AND start_at >= 4 AND end_at < 4) AND `price_rules`.`deleted_at` IS NULL ORDER BY `price_rules`.`id` LIMIT 1
}