|
| 1 | +package models |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +// TransactionsModel groups operations on Transactions. |
| 10 | +type TransactionsModel struct{} |
| 11 | + |
| 12 | +// Transaction is a transaction. |
| 13 | +type Transaction struct { |
| 14 | + BlockHeight int `db:"block_height" json:"block_height"` // pk1 |
| 15 | + TxIndex int `db:"tx_index" json:"index"` // pk2 |
| 16 | + Hash string `db:"hash" json:"hash"` |
| 17 | + BlockHash string `db:"block_hash" json:"block_hash"` |
| 18 | + Timestamp int64 `db:"timestamp" json:"-"` |
| 19 | + TimestampHuman time.Time `db:"-" json:"timestamp"` |
| 20 | + TxType int `db:"tx_type" json:"type"` |
| 21 | + Signee string `db:"signee" json:"signee"` |
| 22 | + Address string `db:"address" json:"address"` |
| 23 | + Signature string `db:"signature" json:"signature"` |
| 24 | + Raw string `db:"raw" json:"raw"` |
| 25 | + Tx interface{} `db:"-" json:"tx"` |
| 26 | +} |
| 27 | + |
| 28 | +// GetTransactionByHash get a transaction by its hash. |
| 29 | +func (m *TransactionsModel) GetTransactionByHash(hash string) (tx *Transaction, err error) { |
| 30 | + tx = &Transaction{} |
| 31 | + query := `SELECT block_height, tx_index, hash, block_hash, timestamp, tx_type, |
| 32 | + signee, address, signature, raw |
| 33 | + FROM indexed_transactions WHERE hash = ?` |
| 34 | + err = chaindb.SelectOne(tx, query, hash) |
| 35 | + if err == sql.ErrNoRows { |
| 36 | + return nil, nil |
| 37 | + } |
| 38 | + return tx, err |
| 39 | +} |
| 40 | + |
| 41 | +// GetTransactionList get a transaction list by hash marker. |
| 42 | +func (m *TransactionsModel) GetTransactionList(since, direction string, limit int) ( |
| 43 | + txs []*Transaction, err error, |
| 44 | +) { |
| 45 | + tx, err := m.GetTransactionByHash(since) |
| 46 | + if tx == nil { |
| 47 | + return txs, err |
| 48 | + } |
| 49 | + |
| 50 | + orderBy := "DESC" |
| 51 | + compare := "<" |
| 52 | + if direction == "forward" { |
| 53 | + orderBy = "ASC" |
| 54 | + compare = ">" |
| 55 | + } |
| 56 | + |
| 57 | + query := fmt.Sprintf(`SELECT block_height, tx_index, hash, block_hash, |
| 58 | + timestamp, tx_type, signee, address, signature, raw |
| 59 | + FROM indexed_transactions |
| 60 | + WHERE block_height %s ? and tx_index %s ? |
| 61 | + ORDER BY block_height %s, tx_index %s |
| 62 | + LIMIT ?`, compare, compare, orderBy, orderBy) |
| 63 | + |
| 64 | + _, err = chaindb.Select(&txs, query, tx.BlockHeight, tx.TxIndex, limit) |
| 65 | + return txs, err |
| 66 | +} |
0 commit comments