db

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2016 License: Apache-2.0, BSD-2-Clause-Views, MIT Imports: 25 Imported by: 0

Documentation

Overview

Package db provides machinery for the database subsystem of horizon.

The crux of this package is `db.Query`. Various structs implement this interface, where the struct usually represent the arguments to the query. For example the following would represent a query to find a single account by address:

type AccountByAddress struct {
  SqlQuery
  Address string
}

You would then implement the query's execution like so:

func (q CoreAccountByAddressQuery) Select(ctx context.Context, dest interface{}) error {
	sql := CoreAccountRecordSelect.Where("accountid = ?", q.Address).Limit(1)
	return q.SqlQuery.Select(ctx, sql, dest)
}

Executing queries happens through `db.Select()` and `db.Get()`.

Index

Examples

Constants

View Source
const (
	// DefaultPageSize is the default page size for db queries
	DefaultPageSize = 10
	// MaxPageSize is the max page size for db queries
	MaxPageSize = 200

	// OrderAscending is used to indicate an ascending order in request params
	OrderAscending = "asc"

	// OrderDescending is used to indicate an descending order in request params
	OrderDescending = "desc"

	// DefaultPairSep is the default separator used to separate two numbers for CursorInt64Pair
	DefaultPairSep = "-"
)
View Source
const (
	FlagAuthRequired  = 1 << iota
	FlagAuthRevocable = 1 << iota
)
View Source
const (
	// account effects
	EffectAccountCreated           = 0 // from create_account
	EffectAccountRemoved           = 1 // from merge_account
	EffectAccountCredited          = 2 // from create_account, payment, path_payment, merge_account
	EffectAccountDebited           = 3 // from create_account, payment, path_payment, create_account
	EffectAccountThresholdsUpdated = 4 // from set_options
	EffectAccountHomeDomainUpdated = 5 // from set_options
	EffectAccountFlagsUpdated      = 6 // from set_options

	// signer effects
	EffectSignerCreated = 10 // from set_options
	EffectSignerRemoved = 11 // from set_options
	EffectSignerUpdated = 12 // from set_options

	// trustline effects
	EffectTrustlineCreated      = 20 // from change_trust
	EffectTrustlineRemoved      = 21 // from change_trust
	EffectTrustlineUpdated      = 22 // from change_trust, allow_trust
	EffectTrustlineAuthorized   = 23 // from allow_trust
	EffectTrustlineDeauthorized = 24 // from allow_trust

	// trading effects
	EffectOfferCreated = 30 // from manage_offer, creat_passive_offer
	EffectOfferRemoved = 31 // from manage_offer, creat_passive_offer, path_payment
	EffectOfferUpdated = 32 // from manage_offer, creat_passive_offer, path_payment
	EffectTrade        = 33 // from manage_offer, creat_passive_offer, path_payment
)
View Source
const (
	// TotalOrderLedgerMask is the bitmask to mask out ledger sequences in a
	// TotalOrderID
	TotalOrderLedgerMask = (1 << 32) - 1
	// TotalOrderTransactionMask is the bitmask to mask out transaction indexes
	TotalOrderTransactionMask = (1 << 20) - 1
	// TotalOrderOperationMask is the bitmask to mask out operation indexes
	TotalOrderOperationMask = (1 << 12) - 1

	// TotalOrderLedgerShift is the number of bits to shift an int64 to target the
	// ledger component
	TotalOrderLedgerShift = 32
	// TotalOrderTransactionShift is the number of bits to shift an int64 to
	// target the transaction component
	TotalOrderTransactionShift = 12
	// TotalOrderOperationShift is the number of bits to shift an int64 to target
	// the operation component
	TotalOrderOperationShift = 0
)
View Source
const (
	MaxHistoryLedger = "SELECT MAX(sequence) FROM history_ledgers"
)
View Source
const OrderBookSummaryPageSize = 20

OrderBookSummaryPageSize is the default limit of price levels returned per "side" of an order book

View Source
const OrderBookSummarySQL = `` /* 1470-byte string literal not displayed */

OrderBookSummarySQL is the raw sql query (postgresql style placeholders) to query for a summary of price levels for a given order book.

View Source
const (
	// PaymentTypeFilter restricts an OperationPageQuery to return only
	// Payment and PathPayment operations
	PaymentTypeFilter = "payment"
)

Variables

View Source
var (
	// ErrInvalidOrder is an error that occurs when a user-provided order string
	// is invalid
	ErrInvalidOrder = errors.New("Invalid order")
	// ErrInvalidLimit is an error that occurs when a user-provided limit num
	// is invalid
	ErrInvalidLimit = errors.New("Invalid limit")
	// ErrInvalidCursor is an error that occurs when a user-provided cursor string
	// is invalid
	ErrInvalidCursor = errors.New("Invalid cursor")
	// ErrNotPageable is an error that occurs when the records provided to
	// PageQuery.GetContinuations cannot be cast to Pageable
	ErrNotPageable = errors.New("Records provided are not Pageable")
)
View Source
var CoreAccountRecordSelect sq.SelectBuilder = sq.Select(
	"a.accountid",
	"a.balance",
	"a.seqnum",
	"a.numsubentries",
	"a.inflationdest",
	"a.homedomain",
	"a.thresholds",
	"a.flags",
).From("accounts a")
View Source
var CoreOfferRecordSelect = sq.Select("co.*").From("offers co")

CoreOfferRecordSelect is a sql fragment to help select form queries that select into a CoreOfferRecord

View Source
var CoreSignerRecordSelect sq.SelectBuilder = sq.Select(
	"si.accountid",
	"si.publickey",
	"si.weight",
).From("signers si")
View Source
var CoreTransactionRecordSelect = sq.Select("ctxh.*").From("txhistory ctxh")

CoreTransactionRecordSelect is a sql fragment to help select form queries that select into a CoreTransactionRecord

View Source
var CoreTrustlineRecordSelect sq.SelectBuilder = sq.Select(
	"tl.accountid",
	"tl.assettype",
	"tl.issuer",
	"tl.assetcode",
	"tl.tlimit",
	"tl.balance",
	"tl.flags",
).From("trustlines tl")
View Source
var EffectRecordSelect sq.SelectBuilder = sq.
	Select("heff.*, hacc.address").
	From("history_effects heff").
	LeftJoin("history_accounts hacc ON hacc.id = heff.history_account_id")
View Source
var ErrDestinationIncompatible = errors.New("Retrieved results' type is not compatible with dest")

ErrDestinationIncompatible is returned when one of the retrieved results is not capable of being assigned to the destination

View Source
var ErrDestinationNil = errors.New("dest is nil")

ErrDestinationNotSlice is returned when the destination is nil

View Source
var ErrDestinationNotPointer = errors.New("dest is not a pointer")

ErrDestinationNotPointer is returned when the result destination for a query is not a pointer

View Source
var ErrDestinationNotSlice = errors.New("dest is not a slice")

ErrDestinationNotSlice is returned when the derefed destination is not a slice

View Source
var ErrNoResults = stderr.New("No record found")

ErrNoResults is returned when no results are found during a `Get` call NOTE: this is not a go-errors based error, as stack traces are unnecessary

View Source
var HistoryAccountRecordSelect = sq.
	Select("ha.*").
	From("history_accounts ha")

HistoryAccountRecordSelect is a reusable select builder to make it easier to query upon the history_accounts table

View Source
var LedgerRecordSelect sq.SelectBuilder = sq.Select(
	"hl.id",
	"hl.sequence",
	"hl.importer_version",
	"hl.ledger_hash",
	"hl.previous_ledger_hash",
	"hl.transaction_count",
	"hl.operation_count",
	"hl.closed_at",
	"hl.created_at",
	"hl.updated_at",
	"hl.total_coins",
	"hl.fee_pool",
	"hl.base_fee",
	"hl.base_reserve",
	"hl.max_tx_set_size",
).From("history_ledgers hl")
View Source
var OperationRecordSelect sq.SelectBuilder = sq.
	Select(
		"hop.id, " +
			"hop.transaction_id, " +
			"hop.application_order, " +
			"hop.type, " +
			"hop.details, " +
			"hop.source_account, " +
			"ht.transaction_hash").
	From("history_operations hop").
	LeftJoin("history_transactions ht ON ht.id = hop.transaction_id")
View Source
var OrderBookSummaryTemplate *template.Template
View Source
var TransactionRecordSelect sq.SelectBuilder = sq.
	Select(
		"ht.id, " +
			"ht.transaction_hash, " +
			"ht.ledger_sequence, " +
			"ht.application_order, " +
			"ht.account, " +
			"ht.account_sequence, " +
			"ht.fee_paid, " +
			"ht.operation_count, " +
			"ht.tx_envelope, " +
			"ht.tx_result, " +
			"ht.tx_meta, " +
			"ht.tx_fee_meta, " +
			"ht.created_at, " +
			"ht.updated_at, " +
			"array_to_string(ht.signatures, ',') AS signatures, " +
			"ht.memo_type, " +
			"ht.memo, " +
			"lower(ht.time_bounds) AS valid_after, " +
			"upper(ht.time_bounds) AS valid_before, " +
			"hl.closed_at AS ledger_close_time").
	From("history_transactions ht").
	LeftJoin("history_ledgers hl ON ht.ledger_sequence = hl.sequence")

Provides a squirrel.SelectBuilder upon which you may build actual queries.

Functions

func Get

func Get(ctx context.Context, query Query, dest interface{}) error

Get runs the provided query, returning the first result found, if any.

Example
db := OpenStellarCoreTestDatabase()
defer db.Close()

q := CoreAccountByAddressQuery{
	SqlQuery{db},
	"GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H",
}

var account CoreAccountRecord
err := Get(context.Background(), q, &account)

if err != nil {
	panic(err)
}

fmt.Printf("%s", account.Accountid)
Output:

GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H

func MustGet

func MustGet(ctx context.Context, query Query, dest interface{})

MustGet is like Get, but panics on error

func MustSelect

func MustSelect(ctx context.Context, query Query, dest interface{})

MustSelect is like Select, but panics on error

func NewLedgerClosePump

func NewLedgerClosePump(ctx context.Context, db *sqlx.DB) <-chan struct{}

NewLedgerClosePump starts a background proc that continually watches the history database provided. The watch is stopped after the provided context is cancelled.

Every second, the proc spawned by calling this func will check to see if a new ledger has been imported (by ruby-horizon as of 2015-04-30, but should eventually end up being in this project). If a new ledger is seen the the channel returned by this function emits

func Open

func Open(url string) (*sqlx.DB, error)

Open the postgres database at the provided url and performing an initial ping to ensure we can connect to it.

func Select

func Select(ctx context.Context, query Query, dest interface{}) error

Select runs the provided query, setting all found results on dest.

Example
db := OpenStellarCoreTestDatabase()
defer db.Close()

q := CoreAccountByAddressQuery{
	SqlQuery{db},
	"GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H",
}

var records []CoreAccountRecord
err := Select(context.Background(), q, &records)

if err != nil {
	panic(err)
}

fmt.Printf("%d", len(records))
Output:

1

Types

type AccountByAddressQuery

type AccountByAddressQuery struct {
	History SqlQuery
	Core    SqlQuery
	Address string
}

AccountByAddressQuery represents a query that retrieves a composite of the CoreAccount and the HistoryAccount associated with an address.

func (AccountByAddressQuery) Select

func (q AccountByAddressQuery) Select(ctx context.Context, dest interface{}) error

type AccountRecord

type AccountRecord struct {
	HistoryAccountRecord
	CoreAccountRecord
	Trustlines []CoreTrustlineRecord
	Signers    []CoreSignerRecord
}

type AssetsForAddressQuery

type AssetsForAddressQuery struct {
	SqlQuery
	Address string
}

AssetsForAddress retrieves a slice of xdr.Asset structs which the provided address can hold a balance. Used by the path finding system to load potential source assets, for example.

func (AssetsForAddressQuery) Select

func (q AssetsForAddressQuery) Select(ctx context.Context, dest interface{}) error

type CompositeSQLFilter

type CompositeSQLFilter struct {
	Filters []SQLFilter
}

CompositeSQLFilter represents a group of SQLFilters. It implements SQLFilter itself

func FilterAll

func FilterAll(filters ...SQLFilter) *CompositeSQLFilter

func (*CompositeSQLFilter) Apply

func (cf *CompositeSQLFilter) Apply(ctx context.Context, sql sq.SelectBuilder) (res sq.SelectBuilder, err error)

Apply applies each constituent filter of this composite to the SelectBuilder in order.

type ConnectedAssetsQuery

type ConnectedAssetsQuery struct {
	SqlQuery
	SellingAsset xdr.Asset
}

ConnectedAssetsQuery returns xdr.Asset records for the purposes of path finding. Given the input asset type, a list of xdr.Assets is returned that each have some available trades for the input asset.

func (ConnectedAssetsQuery) Select

func (q ConnectedAssetsQuery) Select(ctx context.Context, dest interface{}) error

type CoreAccountByAddressQuery

type CoreAccountByAddressQuery struct {
	SqlQuery
	Address string
}

func (CoreAccountByAddressQuery) Select

func (q CoreAccountByAddressQuery) Select(ctx context.Context, dest interface{}) error

type CoreAccountRecord

type CoreAccountRecord struct {
	Accountid     string
	Balance       xdr.Int64
	Seqnum        string
	Numsubentries int32
	Inflationdest null.String
	HomeDomain    null.String
	Thresholds    xdr.Thresholds
	Flags         xdr.AccountFlags
}

A row of data from the `accounts` table from stellar-core

func (CoreAccountRecord) IsAuthRequired

func (ac CoreAccountRecord) IsAuthRequired() bool

func (CoreAccountRecord) IsAuthRevocable

func (ac CoreAccountRecord) IsAuthRevocable() bool

type CoreOfferPageByAddressQuery

type CoreOfferPageByAddressQuery struct {
	SqlQuery
	PageQuery
	Address string
}

CoreOfferPageByAddressQuery loads a page of active offers for the given address.

func (CoreOfferPageByAddressQuery) Select

func (q CoreOfferPageByAddressQuery) Select(ctx context.Context, dest interface{}) error

type CoreOfferPageByCurrencyQuery

type CoreOfferPageByCurrencyQuery struct {
	SqlQuery
	PageQuery
	BuyingAssetType  xdr.AssetType
	BuyingAssetCode  string
	BuyingIssuer     string
	SellingAssetType xdr.AssetType
	SellingAssetCode string
	SellingIssuer    string
}

CoreOfferPageByAddressQuery loads a page of active offers for the given address.

func (CoreOfferPageByCurrencyQuery) Select

func (q CoreOfferPageByCurrencyQuery) Select(ctx context.Context, dest interface{}) error

type CoreOfferRecord

type CoreOfferRecord struct {
	SellerID string `db:"sellerid"`
	OfferID  int64  `db:"offerid"`

	SellingAssetType xdr.AssetType  `db:"sellingassettype"`
	SellingAssetCode sql.NullString `db:"sellingassetcode"`
	SellingIssuer    sql.NullString `db:"sellingissuer"`

	BuyingAssetType xdr.AssetType  `db:"buyingassettype"`
	BuyingAssetCode sql.NullString `db:"buyingassetcode"`
	BuyingIssuer    sql.NullString `db:"buyingissuer"`

	Amount       xdr.Int64 `db:"amount"`
	Pricen       int32     `db:"pricen"`
	Priced       int32     `db:"priced"`
	Price        float64   `db:"price"`
	Flags        int32     `db:"flags"`
	Lastmodified int32     `db:"lastmodified"`
}

CoreOfferRecord is row of data from the `offers` table from stellar-core

func (CoreOfferRecord) PagingToken

func (r CoreOfferRecord) PagingToken() string

PagingToken returns a suitable paging token for the CoreOfferRecord

func (CoreOfferRecord) PriceAsString

func (r CoreOfferRecord) PriceAsString() string

PriceAsFloat return the price fraction as a floating point approximate.

type CoreSignerRecord

type CoreSignerRecord struct {
	Accountid string
	Publickey string
	Weight    int32
}

A row of data from the `signers` table from stellar-core

type CoreSignersByAddressQuery

type CoreSignersByAddressQuery struct {
	SqlQuery
	Address string
}

func (CoreSignersByAddressQuery) Select

func (q CoreSignersByAddressQuery) Select(ctx context.Context, dest interface{}) error

type CoreTransactionByHashQuery

type CoreTransactionByHashQuery struct {
	SqlQuery
	Hash string
}

func (CoreTransactionByHashQuery) Select

func (q CoreTransactionByHashQuery) Select(ctx context.Context, dest interface{}) error

type CoreTransactionRecord

type CoreTransactionRecord struct {
	TransactionHash string `db:"txid"`
	LedgerSequence  int32  `db:"ledgerseq"`
	Index           int32  `db:"txindex"`
	EnvelopeXDR     string `db:"txbody"`
	ResultXDR       string `db:"txresult"`
	ResultMetaXDR   string `db:"txmeta"`
}

CoreTransactionRecord is row of data from the `txhistory` table from stellar-core

type CoreTrustlineRecord

type CoreTrustlineRecord struct {
	Accountid string
	Assettype xdr.AssetType
	Issuer    string
	Assetcode string
	Tlimit    xdr.Int64
	Balance   xdr.Int64
	Flags     int32
}

A row of data from the `trustlines` table from stellar-core

type CoreTrustlinesByAddressQuery

type CoreTrustlinesByAddressQuery struct {
	SqlQuery
	Address string
}

func (CoreTrustlinesByAddressQuery) Select

func (q CoreTrustlinesByAddressQuery) Select(ctx context.Context, dest interface{}) error

type EffectAccountFilter

type EffectAccountFilter struct {
	SqlQuery
	AccountAddress string
}

EffectAccountFilter represents a filter that excludes all rows that do not apply to the account specified

func (*EffectAccountFilter) Apply

type EffectLedgerFilter

type EffectLedgerFilter struct {
	LedgerSequence int32
}

EffectLedgerFilter represents a filter that excludes all rows that did not occur in the specified ledger

func (*EffectLedgerFilter) Apply

type EffectOperationFilter

type EffectOperationFilter struct {
	OperationID int64
}

EffectOperationFilter represents a filter that excludes all rows that did not occur in the specified operation

func (*EffectOperationFilter) Apply

type EffectOrderBookFilter

type EffectOrderBookFilter struct {
	SellingType   xdr.AssetType
	SellingCode   string
	SellingIssuer string
	BuyingType    xdr.AssetType
	BuyingCode    string
	BuyingIssuer  string
}

EffectOrderBookFilter represents a filter that excludes all rows that did not occur in the specified order book

func (*EffectOrderBookFilter) Apply

type EffectPageQuery

type EffectPageQuery struct {
	SqlQuery
	PageQuery
	Filter SQLFilter
}

EffectPageQuery is the main query for paging through a collection of operations in the history database.

func (EffectPageQuery) Select

func (q EffectPageQuery) Select(ctx context.Context, dest interface{}) (err error)

Select executes the query and returns the results

type EffectRecord

type EffectRecord struct {
	HistoryAccountID   int64          `db:"history_account_id"`
	Account            string         `db:"address"`
	HistoryOperationID int64          `db:"history_operation_id"`
	Order              int32          `db:"order"`
	Type               int32          `db:"type"`
	DetailsString      sql.NullString `db:"details"`
}

func (EffectRecord) ID

func (r EffectRecord) ID() string

ID returns a lexically ordered id for this effect record

func (EffectRecord) PagingToken

func (r EffectRecord) PagingToken() string

func (EffectRecord) UnmarshalDetails

func (r EffectRecord) UnmarshalDetails(dest interface{}) error

type EffectTransactionFilter

type EffectTransactionFilter struct {
	SqlQuery
	TransactionHash string
}

EffectTransactionFilter represents a filter that excludes all rows that did not occur in the specified transaction

func (*EffectTransactionFilter) Apply

type EffectTypeFilter

type EffectTypeFilter struct {
	Type int32
}

EffectTypeFilter represents a filter that excludes all rows that do not match the type specified by the filter

func (*EffectTypeFilter) Apply

type HistoryAccountByAddressQuery

type HistoryAccountByAddressQuery struct {
	SqlQuery
	Address string
}

func (HistoryAccountByAddressQuery) Select

func (q HistoryAccountByAddressQuery) Select(ctx context.Context, dest interface{}) error

type HistoryAccountPageQuery

type HistoryAccountPageQuery struct {
	SqlQuery
	PageQuery
}

HistoryAccountPageQuery queries for a single page of HitoryAccount objects, in the normal collection paging style

func (HistoryAccountPageQuery) Select

func (q HistoryAccountPageQuery) Select(ctx context.Context, dest interface{}) error

Get executes the query, returning any results

type HistoryAccountRecord

type HistoryAccountRecord struct {
	HistoryRecord
	Address string `db:"address"`
}

HistoryAccountRecord represents a single row from the history database's `history_accounts` table

type HistoryRecord

type HistoryRecord struct {
	Id int64 `db:"id"`
}

func (HistoryRecord) PagingToken

func (r HistoryRecord) PagingToken() string

type LedgerBySequenceQuery

type LedgerBySequenceQuery struct {
	SqlQuery
	Sequence int32
}

func (LedgerBySequenceQuery) Select

func (q LedgerBySequenceQuery) Select(ctx context.Context, dest interface{}) error

type LedgerPageQuery

type LedgerPageQuery struct {
	SqlQuery
	PageQuery
}

func (LedgerPageQuery) Select

func (q LedgerPageQuery) Select(ctx context.Context, dest interface{}) error

type LedgerRecord

type LedgerRecord struct {
	HistoryRecord
	Sequence           int32          `db:"sequence"`
	ImporterVersion    int32          `db:"importer_version"`
	LedgerHash         string         `db:"ledger_hash"`
	PreviousLedgerHash sql.NullString `db:"previous_ledger_hash"`
	TransactionCount   int32          `db:"transaction_count"`
	OperationCount     int32          `db:"operation_count"`
	ClosedAt           time.Time      `db:"closed_at"`
	CreatedAt          time.Time      `db:"created_at"`
	UpdatedAt          time.Time      `db:"updated_at"`
	TotalCoins         int64          `db:"total_coins"`
	FeePool            int64          `db:"fee_pool"`
	BaseFee            int32          `db:"base_fee"`
	BaseReserve        int32          `db:"base_reserve"`
	MaxTxSetSize       int32          `db:"max_tx_set_size"`
}

type LedgerState

type LedgerState struct {
	HorizonSequence     int32
	StellarCoreSequence int32
}

LedgerState represents the latest known ledgers for both horizon and stellar-core.

type LedgerStateQuery

type LedgerStateQuery struct {
	Horizon SqlQuery
	Core    SqlQuery
}

LedgerStateQuery retrieves the latest ledgers for stellar-core and horizon.

func (LedgerStateQuery) Select

func (q LedgerStateQuery) Select(ctx context.Context, dest interface{}) error

Get executes the query, returning any found results

type OperationByIdQuery

type OperationByIdQuery struct {
	SqlQuery
	Id int64
}

func (OperationByIdQuery) Select

func (q OperationByIdQuery) Select(ctx context.Context, dest interface{}) error

type OperationPageQuery

type OperationPageQuery struct {
	SqlQuery
	PageQuery
	AccountAddress  string
	LedgerSequence  int32
	TransactionHash string
	TypeFilter      string
}

OperationPageQuery is the main query for paging through a collection of operations in the history database.

func (OperationPageQuery) Select

func (q OperationPageQuery) Select(ctx context.Context, dest interface{}) error

Select executes the query and returns the results

type OperationRecord

type OperationRecord struct {
	HistoryRecord
	TransactionId    int64             `db:"transaction_id"`
	TransactionHash  string            `db:"transaction_hash"`
	ApplicationOrder int32             `db:"application_order"`
	Type             xdr.OperationType `db:"type"`
	DetailsString    sql.NullString    `db:"details"`
	SourceAccount    string            `db:"source_account"`
}

func (OperationRecord) UnmarshalDetails

func (r OperationRecord) UnmarshalDetails(dest interface{}) error

type OrderBookSummaryPriceLevelRecord

type OrderBookSummaryPriceLevelRecord struct {
	Type string `db:"type"`
	PriceLevelRecord
}

OrderBookSummaryPriceLevelRecord is a collapsed view of multiple offers at the same price that contains the summed amount from all the member offers. Used by OrderBookSummaryRecord

type OrderBookSummaryQuery

type OrderBookSummaryQuery struct {
	SqlQuery
	SellingType   xdr.AssetType
	SellingCode   string
	SellingIssuer string
	BuyingType    xdr.AssetType
	BuyingCode    string
	BuyingIssuer  string
	// contains filtered or unexported fields
}

OrderBookSummaryQuery is a query from which you should be able to drive a order book summary client interface (bid/ask spread, prices and volume, etc).

func (*OrderBookSummaryQuery) Filter

func (q *OrderBookSummaryQuery) Filter(col string, v interface{}) string

Filter helps manage positional parameters and "IS NULL" checks for this query. An empty string will be converted into a null comparison.

func (*OrderBookSummaryQuery) Invert

Invert returns a new query in which the bids/asks have swapped places.

func (*OrderBookSummaryQuery) Select

func (q *OrderBookSummaryQuery) Select(ctx context.Context, dest interface{}) error

Select executes the query, populating the provided OrderBookSummaryRecord with data.

type OrderBookSummaryRecord

type OrderBookSummaryRecord []OrderBookSummaryPriceLevelRecord

OrderBookSummaryRecord is a summary of a set of offers for a given base and counter currency

func (OrderBookSummaryRecord) Asks

Asks filters the summary into a slice of PriceLevelRecords where the type is 'ask'

func (OrderBookSummaryRecord) Bids

Bids filters the summary into a slice of PriceLevelRecords where the type is 'bid'

type PageQuery

type PageQuery struct {
	Cursor string
	Order  string
	Limit  int32
}

PageQuery represents a portion of a Query struct concerned with paging through a large dataset.

func MustPageQuery

func MustPageQuery(cursor string, order string, limit int32) PageQuery

MustPageQuery behaves as NewPageQuery, but panics upon error

func NewPageQuery

func NewPageQuery(
	cursor string,
	order string,
	limit int32,
) (result PageQuery, err error)

NewPageQuery creates a new PageQuery struct, ensuring the order, limit, and cursor are set to the appropriate defaults and are valid.

func (PageQuery) CursorInt64

func (p PageQuery) CursorInt64() (int64, error)

CursorInt64 parses this query's Cursor string as an int64

func (PageQuery) CursorInt64Pair

func (p PageQuery) CursorInt64Pair(sep string) (l int64, r int64, err error)

CursorInt64Pair parses this query's Cursor string as two int64s, separated by the provided separator

func (PageQuery) GetContinuations

func (p PageQuery) GetContinuations(records interface{}) (next PageQuery, prev PageQuery, err error)

GetContinuations returns two new PageQuery structs, a next and previous query.

func (PageQuery) Invert

func (p PageQuery) Invert() PageQuery

Invert returns a new PageQuery whose order is reversed

type Pageable

type Pageable interface {
	PagingToken() string
}

Pageable records have a defined order, and the place withing that order is determined by the paging token

type PriceLevelRecord

type PriceLevelRecord struct {
	Pricen int32   `db:"pricen"`
	Priced int32   `db:"priced"`
	Pricef float64 `db:"pricef"`
	Amount int64   `db:"amount"`
}

PriceLevelRecord represents an aggregation of offers to trade at a certain price.

func (*PriceLevelRecord) AmountAsString

func (p *PriceLevelRecord) AmountAsString() string

AmountAsString returns the amount as a string, formatted using the amount.String() utility from go-stellar-base.

func (*PriceLevelRecord) InvertPricef

func (p *PriceLevelRecord) InvertPricef() float64

InvertPricef returns the inverted price of the price-level, i.e. what the price would be if you were viewing the price level from the other side of the bid/ask dichotomy.

func (*PriceLevelRecord) PriceAsString

func (p *PriceLevelRecord) PriceAsString() string

PriceAsString returns the price as a string

type Query

type Query interface {
	Select(context.Context, interface{}) error
}

Query is the interface to implement to plug a struct into the query system. see doc.go for an example.

type Record

type Record interface{}

type ResultProvider

type ResultProvider struct {
	Core    *sqlx.DB
	History *sqlx.DB
}

func (*ResultProvider) ResultByHash

func (rp *ResultProvider) ResultByHash(ctx context.Context, hash string) txsub.Result

type SQLFilter

type SQLFilter interface {
	Apply(context.Context, sq.SelectBuilder) (sq.SelectBuilder, error)
}

SQLFilter represents an extension mechanism for queries. A query that wants to provide a mechanism to arbitrarily add additional conditions to the sql it uses can accept an instance of this interface and call to it to augment the sql it is building.

type SequenceByAddressQuery

type SequenceByAddressQuery struct {
	SqlQuery
	Addresses []string
}

func (SequenceByAddressQuery) Get

func (q SequenceByAddressQuery) Get(ctx context.Context, addresses []string) (map[string]uint64, error)

Get implements the txsub.SequenceProvider interface, allowing this query to be used directly for providing account sequence numbers for

func (SequenceByAddressQuery) Select

func (q SequenceByAddressQuery) Select(ctx context.Context, dest interface{}) error

type SqlQuery

type SqlQuery struct {
	DB *sqlx.DB
}

SqlQuery helps facilitate queries against a postgresql database. See Select and Get for the main methods used by collaborators.

func (SqlQuery) Get

func (q SqlQuery) Get(ctx context.Context, sql sq.SelectBuilder, dest interface{}) error

Get gets a single row returned by the provided sql builder into the provided dest. dest must be a non-slice value of the correct record type.

func (SqlQuery) GetRaw

func (q SqlQuery) GetRaw(ctx context.Context, query string, args []interface{}, dest interface{}) error

GetRaw runs the provided postgres query and args against this sqlquery's db.

func (SqlQuery) Query

func (q SqlQuery) Query(ctx context.Context, sql sq.SelectBuilder) (*sqlx.Rows, error)

func (SqlQuery) QueryRaw

func (q SqlQuery) QueryRaw(ctx context.Context, query string, args []interface{}) (*sqlx.Rows, error)

QueryRaw runs the provided query and returns a *sqlx.Rows value to iterate through the response

func (SqlQuery) Select

func (q SqlQuery) Select(ctx context.Context, sql sq.SelectBuilder, dest interface{}) error

Select selects multiple rows returned by the provided sql builder into the provided dest. dest must be a slice of the correct record type.

func (SqlQuery) SelectRaw

func (q SqlQuery) SelectRaw(ctx context.Context, query string, args []interface{}, dest interface{}) error

SelectRaw runs the provided postgres query and args against this sqlquery's db.

type TotalOrderID

type TotalOrderID struct {
	LedgerSequence   int32
	TransactionOrder int32
	OperationOrder   int32
}

A TotalOrderID expressed the total order of Ledgers, Transactions and Operations.

Operations within the stellar network have a total order, expressed by three pieces of information: the ledger sequence the operation was validated in, the order which the operation's containing transaction was applied in that ledger, and the index of the operation within that parent transaction.

We express this order by packing those three pieces of information into a single signed 64-bit number (we used a signed number for SQL compatibility).

The follow diagram shows this format:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Ledger Sequence Number                     |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Transaction Application Order     |       Op Index        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

By component:

Ledger Sequence: 32-bits

A complete ledger sequence number in which the operation was validated.

Expressed in network byte order.

Transaction Application Order: 20-bits

The order that the transaction was applied within the ledger it was
validated.  Accommodates up to 1,048,575 transactions in a single ledger.

Expressed in network byte order.

Operation Index: 12-bits

The index of the operation within its parent transaction. Accommodates up
to 4095 operations per transaction.

Expressed in network byte order.

Note: API Clients should not be interpreting this value. We will use it as an opaque paging token that clients can parrot back to us after having read it within a resource to page from the represented position in time.

Note: This does not uniquely identify an object. Given a ledger, it will share its id with its first transaction and the first operation of that transaction as well. Given that this ID is only meant for ordering within a single type of object, the sharing of ids across object types seems acceptable.

func ParseTotalOrderID

func ParseTotalOrderID(id int64) (result TotalOrderID)

ParseTotalOrderID parses an int64 into a TotalOrderID struct

Example
toid := ParseTotalOrderID(12884910080)
fmt.Printf("ledger:%d, tx:%d, op:%d", toid.LedgerSequence, toid.TransactionOrder, toid.OperationOrder)
Output:

ledger:3, tx:2, op:0

func (*TotalOrderID) IncOperationOrder

func (id *TotalOrderID) IncOperationOrder()

IncOperationOrder increments the operation order, rolling over to the next ledger if overflow occurs. This allows queries to easily advance a cursor to the next operation.

func (*TotalOrderID) String

func (id *TotalOrderID) String() string

String returns a string representation of this id

func (*TotalOrderID) ToInt64

func (id *TotalOrderID) ToInt64() (result int64)

ToInt64 converts this struct back into an int64

type TransactionByAddressAndSequence

type TransactionByAddressAndSequence struct {
	SqlQuery
	Address  string
	Sequence uint64
}

func (TransactionByAddressAndSequence) Select

func (q TransactionByAddressAndSequence) Select(ctx context.Context, dest interface{}) error

type TransactionByHashQuery

type TransactionByHashQuery struct {
	SqlQuery
	Hash string
}

func (TransactionByHashQuery) Select

func (q TransactionByHashQuery) Select(ctx context.Context, dest interface{}) error

type TransactionPageQuery

type TransactionPageQuery struct {
	SqlQuery
	PageQuery
	AccountAddress string
	LedgerSequence int32
}

func (TransactionPageQuery) Select

func (q TransactionPageQuery) Select(ctx context.Context, dest interface{}) error

type TransactionRecord

type TransactionRecord struct {
	HistoryRecord
	TransactionHash  string         `db:"transaction_hash"`
	LedgerSequence   int32          `db:"ledger_sequence"`
	LedgerCloseTime  time.Time      `db:"ledger_close_time"`
	ApplicationOrder int32          `db:"application_order"`
	Account          string         `db:"account"`
	AccountSequence  int64          `db:"account_sequence"`
	FeePaid          int32          `db:"fee_paid"`
	OperationCount   int32          `db:"operation_count"`
	TxEnvelope       string         `db:"tx_envelope"`
	TxResult         string         `db:"tx_result"`
	TxMeta           string         `db:"tx_meta"`
	TxFeeMeta        string         `db:"tx_fee_meta"`
	SignatureString  string         `db:"signatures"`
	MemoType         string         `db:"memo_type"`
	Memo             sql.NullString `db:"memo"`
	ValidAfter       sql.NullInt64  `db:"valid_after"`
	ValidBefore      sql.NullInt64  `db:"valid_before"`
	CreatedAt        time.Time      `db:"created_at"`
	UpdatedAt        time.Time      `db:"updated_at"`
}

func (TransactionRecord) TableName

func (r TransactionRecord) TableName() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL