github.com/condensat/bank-core@v0.1.0/database/query/currencyrate.go (about) 1 // Copyright 2020 Condensat Tech. All rights reserved. 2 // Use of this source code is governed by a MIT 3 // license that can be found in the LICENSE file. 4 5 package query 6 7 import ( 8 "errors" 9 10 "github.com/condensat/bank-core/database" 11 "github.com/condensat/bank-core/database/model" 12 13 "github.com/jinzhu/gorm" 14 ) 15 16 func GetLastCurencyRates(db database.Context) ([]model.CurrencyRate, error) { 17 if db == nil { 18 return nil, database.ErrInvalidDatabase 19 } 20 21 gdb := db.DB().(*gorm.DB) 22 23 subQuery := gdb.Model(&model.CurrencyRate{}). 24 Select("MAX(id) as id, MAX(timestamp) AS last"). 25 Group("name"). 26 SubQuery() 27 28 var list []*model.CurrencyRate 29 err := gdb.Joins("RIGHT JOIN (?) AS t1 ON currency_rate.id = t1.id AND timestamp = t1.last", subQuery). 30 Order("name ASC"). 31 Find(&list).Error 32 33 if err != nil && err != gorm.ErrRecordNotFound { 34 return nil, err 35 } 36 37 var result []model.CurrencyRate 38 for _, entry := range list { 39 result = append(result, *entry) 40 } 41 42 return result, nil 43 } 44 45 func AppendCurencyRates(db database.Context, currencyRates []model.CurrencyRate) error { 46 return db.Transaction(func(tx database.Context) error { 47 txdb := tx.DB().(*gorm.DB) 48 if txdb == nil { 49 return errors.New("Invalid tx Database") 50 } 51 52 for _, rate := range currencyRates { 53 err := txdb.Create(&rate).Error 54 if err != nil { 55 return err // Rollback all previous writes 56 } 57 } 58 59 return nil 60 }) 61 }