code.vegaprotocol.io/vega@v0.79.0/datanode/sqlstore/risk_factor.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package sqlstore
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  
    22  	"code.vegaprotocol.io/vega/datanode/entities"
    23  	"code.vegaprotocol.io/vega/datanode/metrics"
    24  
    25  	"github.com/georgysavva/scany/pgxscan"
    26  )
    27  
    28  type RiskFactors struct {
    29  	*ConnectionSource
    30  }
    31  
    32  const (
    33  	sqlRiskFactorColumns = `market_id, short, long, tx_hash, vega_time`
    34  )
    35  
    36  func NewRiskFactors(connectionSource *ConnectionSource) *RiskFactors {
    37  	return &RiskFactors{
    38  		ConnectionSource: connectionSource,
    39  	}
    40  }
    41  
    42  func (rf *RiskFactors) Upsert(ctx context.Context, factor *entities.RiskFactor) error {
    43  	defer metrics.StartSQLQuery("RiskFactor", "Upsert")()
    44  	query := fmt.Sprintf(`insert into risk_factors (%s)
    45  values ($1, $2, $3, $4, $5)
    46  on conflict (market_id, vega_time) do update
    47  set
    48  	short=EXCLUDED.short,
    49  	long=EXCLUDED.long,
    50  	tx_hash=EXCLUDED.tx_hash`, sqlRiskFactorColumns)
    51  
    52  	if _, err := rf.Exec(ctx, query, factor.MarketID, factor.Short, factor.Long, factor.TxHash, factor.VegaTime); err != nil {
    53  		err = fmt.Errorf("could not insert risk factor into database: %w", err)
    54  		return err
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  func (rf *RiskFactors) GetMarketRiskFactors(ctx context.Context, marketID string) (entities.RiskFactor, error) {
    61  	defer metrics.StartSQLQuery("RiskFactors", "GetMarketRiskFactors")()
    62  	var riskFactor entities.RiskFactor
    63  	var bindVars []interface{}
    64  
    65  	query := fmt.Sprintf(`select %s
    66  		from risk_factors_current
    67  		where market_id = %s`, sqlRiskFactorColumns, nextBindVar(&bindVars, entities.MarketID(marketID)))
    68  
    69  	return riskFactor, rf.wrapE(pgxscan.Get(ctx, rf.ConnectionSource, &riskFactor, query, bindVars...))
    70  }