-
Notifications
You must be signed in to change notification settings - Fork 19
/
markets.go
170 lines (140 loc) · 5.12 KB
/
markets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.DATANODE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package sqlstore
import (
"context"
"fmt"
"sync"
"code.vegaprotocol.io/vega/datanode/entities"
"code.vegaprotocol.io/vega/datanode/metrics"
v2 "code.vegaprotocol.io/vega/protos/data-node/api/v2"
"github.com/georgysavva/scany/pgxscan"
)
type Markets struct {
*ConnectionSource
cache map[string]entities.Market
cacheLock sync.Mutex
}
var marketOrdering = TableOrdering{
ColumnOrdering{Name: "vega_time", Sorting: ASC},
}
const (
sqlMarketsColumns = `id, tx_hash, vega_time, instrument_id, tradable_instrument, decimal_places,
fees, opening_auction, price_monitoring_settings, liquidity_monitoring_parameters,
trading_mode, state, market_timestamps, position_decimal_places, lp_price_range`
)
func NewMarkets(connectionSource *ConnectionSource) *Markets {
return &Markets{
ConnectionSource: connectionSource,
cache: make(map[string]entities.Market),
}
}
func (m *Markets) Upsert(ctx context.Context, market *entities.Market) error {
query := fmt.Sprintf(`insert into markets(%s)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
on conflict (id, vega_time) do update
set
instrument_id=EXCLUDED.instrument_id,
tradable_instrument=EXCLUDED.tradable_instrument,
decimal_places=EXCLUDED.decimal_places,
fees=EXCLUDED.fees,
opening_auction=EXCLUDED.opening_auction,
price_monitoring_settings=EXCLUDED.price_monitoring_settings,
liquidity_monitoring_parameters=EXCLUDED.liquidity_monitoring_parameters,
trading_mode=EXCLUDED.trading_mode,
state=EXCLUDED.state,
market_timestamps=EXCLUDED.market_timestamps,
position_decimal_places=EXCLUDED.position_decimal_places,
lp_price_range=EXCLUDED.lp_price_range,
tx_hash=EXCLUDED.tx_hash;`, sqlMarketsColumns)
defer metrics.StartSQLQuery("Markets", "Upsert")()
if _, err := m.Connection.Exec(ctx, query, market.ID, market.TxHash, market.VegaTime, market.InstrumentID, market.TradableInstrument, market.DecimalPlaces,
market.Fees, market.OpeningAuction, market.PriceMonitoringSettings, market.LiquidityMonitoringParameters,
market.TradingMode, market.State, market.MarketTimestamps, market.PositionDecimalPlaces, market.LpPriceRange); err != nil {
err = fmt.Errorf("could not insert market into database: %w", err)
return err
}
m.AfterCommit(ctx, func() {
// delete cache
m.cacheLock.Lock()
defer m.cacheLock.Unlock()
delete(m.cache, market.ID.String())
})
return nil
}
func (m *Markets) GetByID(ctx context.Context, marketID string) (entities.Market, error) {
m.cacheLock.Lock()
defer m.cacheLock.Unlock()
var market entities.Market
if market, ok := m.cache[marketID]; ok {
return market, nil
}
query := fmt.Sprintf(`select %s
from markets_current
where id = $1
order by id, vega_time desc
`, sqlMarketsColumns)
defer metrics.StartSQLQuery("Markets", "GetByID")()
err := pgxscan.Get(ctx, m.Connection, &market, query, entities.MarketID(marketID))
if err == nil {
m.cache[marketID] = market
}
return market, m.wrapE(err)
}
func (m *Markets) GetAll(ctx context.Context, pagination entities.OffsetPagination) ([]entities.Market, error) {
var markets []entities.Market
query := fmt.Sprintf(`select %s
from markets_current
where state != 'STATE_REJECTED'
order by id, vega_time desc
`, sqlMarketsColumns)
query, _ = orderAndPaginateQuery(query, nil, pagination)
defer metrics.StartSQLQuery("Markets", "GetAll")()
err := pgxscan.Select(ctx, m.Connection, &markets, query)
return markets, err
}
func (m *Markets) GetAllPaged(ctx context.Context, marketID string, pagination entities.CursorPagination, includeSettled bool) ([]entities.Market, entities.PageInfo, error) {
if marketID != "" {
market, err := m.GetByID(ctx, marketID)
if err != nil {
return nil, entities.PageInfo{}, err
}
return []entities.Market{market}, entities.PageInfo{
HasNextPage: false,
HasPreviousPage: false,
StartCursor: market.Cursor().Encode(),
EndCursor: market.Cursor().Encode(),
}, nil
}
markets := make([]entities.Market, 0)
args := make([]interface{}, 0)
settledClause := ""
if !includeSettled {
settledClause = " AND state != 'STATE_SETTLED'"
}
query := fmt.Sprintf(`select %s
from markets_current
where state != 'STATE_REJECTED' %s`, sqlMarketsColumns, settledClause)
var (
pageInfo entities.PageInfo
err error
)
query, args, err = PaginateQuery[entities.MarketCursor](query, args, marketOrdering, pagination)
if err != nil {
return markets, pageInfo, err
}
if err = pgxscan.Select(ctx, m.Connection, &markets, query, args...); err != nil {
return markets, pageInfo, err
}
markets, pageInfo = entities.PageEntities[*v2.MarketEdge](markets, pagination)
return markets, pageInfo, nil
}