order: extract query order sql generator

This commit is contained in:
ycdesu 2021-02-03 17:12:06 +08:00
parent 705edc38c0
commit 72b1877e4a
2 changed files with 42 additions and 13 deletions

View File

@ -58,6 +58,23 @@ type QueryOrdersOptions struct {
}
func (s *OrderService) Query(options QueryOrdersOptions) ([]AggOrder, error) {
sql := genOrderSQL(options)
rows, err := s.DB.NamedQuery(sql, map[string]interface{}{
"exchange": options.Exchange,
"symbol": options.Symbol,
"gid": options.LastGID,
})
if err != nil {
return nil, err
}
defer rows.Close()
return s.scanAggRows(rows)
}
func genOrderSQL(options QueryOrdersOptions) string {
// ascending
ordering := "ASC"
switch v := strings.ToUpper(options.Ordering); v {
@ -93,19 +110,7 @@ func (s *OrderService) Query(options QueryOrdersOptions) ([]AggOrder, error) {
sql += ` LIMIT ` + strconv.Itoa(500)
log.Info(sql)
rows, err := s.DB.NamedQuery(sql, map[string]interface{}{
"exchange": options.Exchange,
"symbol": options.Symbol,
"gid": options.LastGID,
})
if err != nil {
return nil, err
}
defer rows.Close()
return s.scanAggRows(rows)
return sql
}
func (s *OrderService) scanAggRows(rows *sqlx.Rows) (orders []AggOrder, err error) {

24
pkg/service/order_test.go Normal file
View File

@ -0,0 +1,24 @@
package service
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_genOrderSQL(t *testing.T) {
t.Run("accept empty options", func(t *testing.T) {
o := QueryOrdersOptions{}
assert.Equal(t, "SELECT orders.*, IFNULL(SUM(t.price * t.quantity)/SUM(t.quantity), orders.price) AS average_price FROM orders LEFT JOIN trades AS t ON (t.order_id = orders.order_id) GROUP BY orders.gid ORDER BY orders.gid ASC LIMIT 500", genOrderSQL(o))
})
t.Run("different ordering ", func(t *testing.T) {
o := QueryOrdersOptions{}
assert.Equal(t, "SELECT orders.*, IFNULL(SUM(t.price * t.quantity)/SUM(t.quantity), orders.price) AS average_price FROM orders LEFT JOIN trades AS t ON (t.order_id = orders.order_id) GROUP BY orders.gid ORDER BY orders.gid ASC LIMIT 500", genOrderSQL(o))
o.Ordering = "ASC"
assert.Equal(t, "SELECT orders.*, IFNULL(SUM(t.price * t.quantity)/SUM(t.quantity), orders.price) AS average_price FROM orders LEFT JOIN trades AS t ON (t.order_id = orders.order_id) GROUP BY orders.gid ORDER BY orders.gid ASC LIMIT 500", genOrderSQL(o))
o.Ordering = "DESC"
assert.Equal(t, "SELECT orders.*, IFNULL(SUM(t.price * t.quantity)/SUM(t.quantity), orders.price) AS average_price FROM orders LEFT JOIN trades AS t ON (t.order_id = orders.order_id) GROUP BY orders.gid ORDER BY orders.gid DESC LIMIT 500", genOrderSQL(o))
})
}