arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/historydb/historydb.go
db/historydb/historydb.goRaw
   1package historydb
   2
   3import (
   4	"database/sql"
   5	"errors"
   6	"fmt"
   7	"math"
   8	"math/big"
   9
  10	ethCommon "github.com/ethereum/go-ethereum/common"
  11	"github.com/hermeznetwork/hermez-node/common"
  12	"github.com/hermeznetwork/hermez-node/db"
  13	"github.com/hermeznetwork/hermez-node/log"
  14	"github.com/iden3/go-iden3-crypto/babyjub"
  15	"github.com/jmoiron/sqlx"
  16
  17	//nolint:errcheck // driver for postgres DB
  18	_ "github.com/lib/pq"
  19	"github.com/russross/meddler"
  20)
  21
  22const (
  23	// OrderAsc indicates ascending order when using pagination
  24	OrderAsc = "ASC"
  25	// OrderDesc indicates descending order when using pagination
  26	OrderDesc = "DESC"
  27)
  28
  29// TODO(Edu): Document here how HistoryDB is kept consistent
  30
  31// HistoryDB persist the historic of the rollup
  32type HistoryDB struct {
  33	db *sqlx.DB
  34}
  35
  36// NewHistoryDB initialize the DB
  37func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  38	return &HistoryDB{db: db}
  39}
  40
  41// AddBlock insert a block into the DB
  42func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  43func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  44	return meddler.Insert(d, "block", block)
  45}
  46
  47// AddBlocks inserts blocks into the DB
  48func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  49	return hdb.addBlocks(hdb.db, blocks)
  50}
  51
  52func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  53	return db.BulkInsert(
  54		d,
  55		`INSERT INTO block (
  56			eth_block_num,
  57			timestamp,
  58			hash
  59		) VALUES %s;`,
  60		blocks[:],
  61	)
  62}
  63
  64// GetBlock retrieve a block from the DB, given a block number
  65func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  66	block := &common.Block{}
  67	err := meddler.QueryRow(
  68		hdb.db, block,
  69		"SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  70	)
  71	return block, err
  72}
  73
  74// GetAllBlocks retrieve all blocks from the DB
  75func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  76	var blocks []*common.Block
  77	err := meddler.QueryAll(
  78		hdb.db, &blocks,
  79		"SELECT * FROM block;",
  80	)
  81	return db.SlicePtrsToSlice(blocks).([]common.Block), err
  82}
  83
  84// GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  85func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  86	var blocks []*common.Block
  87	err := meddler.QueryAll(
  88		hdb.db, &blocks,
  89		"SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;",
  90		from, to,
  91	)
  92	return db.SlicePtrsToSlice(blocks).([]common.Block), err
  93}
  94
  95// GetLastBlock retrieve the block with the highest block number from the DB
  96func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  97	block := &common.Block{}
  98	err := meddler.QueryRow(
  99		hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
 100	)
 101	return block, err
 102}
 103
 104// AddBatch insert a Batch into the DB
 105func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
 106func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
 107	// Calculate total collected fees in USD
 108	// Get IDs of collected tokens for fees
 109	tokenIDs := []common.TokenID{}
 110	for id := range batch.CollectedFees {
 111		tokenIDs = append(tokenIDs, id)
 112	}
 113	// Get USD value of the tokens
 114	type tokenPrice struct {
 115		ID       common.TokenID `meddler:"token_id"`
 116		USD      *float64       `meddler:"usd"`
 117		Decimals int            `meddler:"decimals"`
 118	}
 119	var tokenPrices []*tokenPrice
 120	if len(tokenIDs) > 0 {
 121		query, args, err := sqlx.In(
 122			"SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",
 123			tokenIDs,
 124		)
 125		if err != nil {
 126			return err
 127		}
 128		query = hdb.db.Rebind(query)
 129		if err := meddler.QueryAll(
 130			hdb.db, &tokenPrices, query, args...,
 131		); err != nil {
 132			return err
 133		}
 134	}
 135	// Calculate total collected
 136	var total float64
 137	for _, tokenPrice := range tokenPrices {
 138		if tokenPrice.USD == nil {
 139			continue
 140		}
 141		f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
 142		amount, _ := f.Float64()
 143		total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
 144	}
 145	batch.TotalFeesUSD = &total
 146	// Insert to DB
 147	return meddler.Insert(d, "batch", batch)
 148}
 149
 150// AddBatches insert Bids into the DB
 151func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
 152	return hdb.addBatches(hdb.db, batches)
 153}
 154func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
 155	for i := 0; i < len(batches); i++ {
 156		if err := hdb.addBatch(d, &batches[i]); err != nil {
 157			return err
 158		}
 159	}
 160	return nil
 161}
 162
 163// GetBatchAPI return the batch with the given batchNum
 164func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
 165	batch := &BatchAPI{}
 166	return batch, meddler.QueryRow(
 167		hdb.db, batch,
 168		`SELECT batch.*, block.timestamp, block.hash
 169	 	FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
 170	 	WHERE batch_num = $1;`, batchNum,
 171	)
 172}
 173
 174// GetBatchesAPI return the batches applying the given filters
 175func (hdb *HistoryDB) GetBatchesAPI(
 176	minBatchNum, maxBatchNum, slotNum *uint,
 177	forgerAddr *ethCommon.Address,
 178	fromItem, limit *uint, order string,
 179) ([]BatchAPI, *db.Pagination, error) {
 180	var query string
 181	var args []interface{}
 182	queryStr := `SELECT batch.*, block.timestamp, block.hash,
 183	count(*) OVER() AS total_items, MIN(batch.item_id) OVER() AS first_item,
 184	MAX(batch.item_id) OVER() AS last_item 
 185	FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
 186	// Apply filters
 187	nextIsAnd := false
 188	// minBatchNum filter
 189	if minBatchNum != nil {
 190		if nextIsAnd {
 191			queryStr += "AND "
 192		} else {
 193			queryStr += "WHERE "
 194		}
 195		queryStr += "batch.batch_num > ? "
 196		args = append(args, minBatchNum)
 197		nextIsAnd = true
 198	}
 199	// maxBatchNum filter
 200	if maxBatchNum != nil {
 201		if nextIsAnd {
 202			queryStr += "AND "
 203		} else {
 204			queryStr += "WHERE "
 205		}
 206		queryStr += "batch.batch_num < ? "
 207		args = append(args, maxBatchNum)
 208		nextIsAnd = true
 209	}
 210	// slotNum filter
 211	if slotNum != nil {
 212		if nextIsAnd {
 213			queryStr += "AND "
 214		} else {
 215			queryStr += "WHERE "
 216		}
 217		queryStr += "batch.slot_num = ? "
 218		args = append(args, slotNum)
 219		nextIsAnd = true
 220	}
 221	// forgerAddr filter
 222	if forgerAddr != nil {
 223		if nextIsAnd {
 224			queryStr += "AND "
 225		} else {
 226			queryStr += "WHERE "
 227		}
 228		queryStr += "batch.forger_addr = ? "
 229		args = append(args, forgerAddr)
 230		nextIsAnd = true
 231	}
 232	// pagination
 233	if fromItem != nil {
 234		if nextIsAnd {
 235			queryStr += "AND "
 236		} else {
 237			queryStr += "WHERE "
 238		}
 239		if order == OrderAsc {
 240			queryStr += "batch.item_id >= ? "
 241		} else {
 242			queryStr += "batch.item_id <= ? "
 243		}
 244		args = append(args, fromItem)
 245	}
 246	queryStr += "ORDER BY batch.item_id "
 247	if order == OrderAsc {
 248		queryStr += " ASC "
 249	} else {
 250		queryStr += " DESC "
 251	}
 252	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 253	query = hdb.db.Rebind(queryStr)
 254	log.Debug(query)
 255	batchPtrs := []*BatchAPI{}
 256	if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
 257		return nil, nil, err
 258	}
 259	batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
 260	if len(batches) == 0 {
 261		return nil, nil, sql.ErrNoRows
 262	}
 263	return batches, &db.Pagination{
 264		TotalItems: batches[0].TotalItems,
 265		FirstItem:  batches[0].FirstItem,
 266		LastItem:   batches[0].LastItem,
 267	}, nil
 268}
 269
 270// GetAllBatches retrieve all batches from the DB
 271func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
 272	var batches []*common.Batch
 273	err := meddler.QueryAll(
 274		hdb.db, &batches,
 275		`SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
 276		 batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
 277		 batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`,
 278	)
 279	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 280}
 281
 282// GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
 283func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
 284	var batches []*common.Batch
 285	err := meddler.QueryAll(
 286		hdb.db, &batches,
 287		"SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;",
 288		from, to,
 289	)
 290	return db.SlicePtrsToSlice(batches).([]common.Batch), err
 291}
 292
 293// GetLastBatchNum returns the BatchNum of the latest forged batch
 294func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
 295	row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
 296	var batchNum common.BatchNum
 297	return batchNum, row.Scan(&batchNum)
 298}
 299
 300// GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
 301// batches.  If there's no batch in the DB (nil, nil) is returned.
 302func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
 303	row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
 304	lastL1TxsNum := new(int64)
 305	return lastL1TxsNum, row.Scan(&lastL1TxsNum)
 306}
 307
 308// Reorg deletes all the information that was added into the DB after the
 309// lastValidBlock.  If lastValidBlock is negative, all block information is
 310// deleted.
 311func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
 312	var err error
 313	if lastValidBlock < 0 {
 314		_, err = hdb.db.Exec("DELETE FROM block;")
 315	} else {
 316		_, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
 317	}
 318	return err
 319}
 320
 321// SyncPoD stores all the data that can be changed / added on a block in the PoD SC
 322func (hdb *HistoryDB) SyncPoD(
 323	blockNum uint64,
 324	bids []common.Bid,
 325	coordinators []common.Coordinator,
 326	vars *common.AuctionVars,
 327) error {
 328	return nil
 329}
 330
 331// AddBids insert Bids into the DB
 332func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
 333func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
 334	// TODO: check the coordinator info
 335	return db.BulkInsert(
 336		d,
 337		"INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
 338		bids[:],
 339	)
 340}
 341
 342// GetAllBids retrieve all bids from the DB
 343func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
 344	var bids []*common.Bid
 345	err := meddler.QueryAll(
 346		hdb.db, &bids,
 347		`SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid;`,
 348	)
 349	return db.SlicePtrsToSlice(bids).([]common.Bid), err
 350}
 351
 352// GetBidsAPI return the bids applying the given filters
 353func (hdb *HistoryDB) GetBidsAPI(slotNum *uint, forgerAddr *ethCommon.Address, fromItem, limit *uint, order string) ([]BidAPI, *db.Pagination, error) {
 354	var query string
 355	var args []interface{}
 356	queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url, 
 357	COUNT(*) OVER() AS total_items, MIN(bid.item_id) OVER() AS first_item, 
 358	MAX(bid.item_id) OVER() AS last_item FROM bid
 359	INNER JOIN block ON bid.eth_block_num = block.eth_block_num 
 360	INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
 361	// Apply filters
 362	nextIsAnd := false
 363	// slotNum filter
 364	if slotNum != nil {
 365		if nextIsAnd {
 366			queryStr += "AND "
 367		} else {
 368			queryStr += "WHERE "
 369		}
 370		queryStr += "bid.slot_num = ? "
 371		args = append(args, slotNum)
 372		nextIsAnd = true
 373	}
 374	// slotNum filter
 375	if forgerAddr != nil {
 376		if nextIsAnd {
 377			queryStr += "AND "
 378		} else {
 379			queryStr += "WHERE "
 380		}
 381		queryStr += "bid.bidder_addr = ? "
 382		args = append(args, forgerAddr)
 383		nextIsAnd = true
 384	}
 385	if fromItem != nil {
 386		if nextIsAnd {
 387			queryStr += "AND "
 388		} else {
 389			queryStr += "WHERE "
 390		}
 391		if order == OrderAsc {
 392			queryStr += "bid.item_id >= ? "
 393		} else {
 394			queryStr += "bid.item_id <= ? "
 395		}
 396		args = append(args, fromItem)
 397	}
 398	// pagination
 399	queryStr += "ORDER BY bid.item_id "
 400	if order == OrderAsc {
 401		queryStr += "ASC "
 402	} else {
 403		queryStr += "DESC "
 404	}
 405	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 406	query, argsQ, err := sqlx.In(queryStr, args...)
 407	if err != nil {
 408		return nil, nil, err
 409	}
 410	query = hdb.db.Rebind(query)
 411	bids := []*BidAPI{}
 412	if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
 413		return nil, nil, err
 414	}
 415	if len(bids) == 0 {
 416		return nil, nil, sql.ErrNoRows
 417	}
 418	return db.SlicePtrsToSlice(bids).([]BidAPI), &db.Pagination{
 419		TotalItems: bids[0].TotalItems,
 420		FirstItem:  bids[0].FirstItem,
 421		LastItem:   bids[0].LastItem,
 422	}, nil
 423}
 424
 425// AddCoordinators insert Coordinators into the DB
 426func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
 427	return hdb.addCoordinators(hdb.db, coordinators)
 428}
 429func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
 430	return db.BulkInsert(
 431		d,
 432		"INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
 433		coordinators[:],
 434	)
 435}
 436
 437// AddExitTree insert Exit tree into the DB
 438func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
 439	return hdb.addExitTree(hdb.db, exitTree)
 440}
 441func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
 442	return db.BulkInsert(
 443		d,
 444		"INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
 445			"instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
 446		exitTree[:],
 447	)
 448}
 449
 450// AddToken insert a token into the DB
 451func (hdb *HistoryDB) AddToken(token *common.Token) error {
 452	return meddler.Insert(hdb.db, "token", token)
 453}
 454
 455// AddTokens insert tokens into the DB
 456func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
 457func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
 458	return db.BulkInsert(
 459		d,
 460		`INSERT INTO token (
 461			token_id,
 462			eth_block_num,
 463			eth_addr,
 464			name,
 465			symbol,
 466			decimals
 467		) VALUES %s;`,
 468		tokens[:],
 469	)
 470}
 471
 472// UpdateTokenValue updates the USD value of a token
 473func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
 474	_, err := hdb.db.Exec(
 475		"UPDATE token SET usd = $1 WHERE symbol = $2;",
 476		value, tokenSymbol,
 477	)
 478	return err
 479}
 480
 481// GetToken returns a token from the DB given a TokenID
 482func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
 483	token := &TokenWithUSD{}
 484	err := meddler.QueryRow(
 485		hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
 486	)
 487	return token, err
 488}
 489
 490// GetAllTokens returns all tokens from the DB
 491func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
 492	var tokens []*TokenWithUSD
 493	err := meddler.QueryAll(
 494		hdb.db, &tokens,
 495		"SELECT * FROM token ORDER BY token_id;",
 496	)
 497	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err
 498}
 499
 500// GetTokens returns a list of tokens from the DB
 501func (hdb *HistoryDB) GetTokens(ids []common.TokenID, symbols []string, name string, fromItem, limit *uint, order string) ([]TokenWithUSD, *db.Pagination, error) {
 502	var query string
 503	var args []interface{}
 504	queryStr := `SELECT * , COUNT(*) OVER() AS total_items, MIN(token.item_id) OVER() AS first_item, MAX(token.item_id) OVER() AS last_item FROM token `
 505	// Apply filters
 506	nextIsAnd := false
 507	if len(ids) > 0 {
 508		queryStr += "WHERE token_id IN (?) "
 509		nextIsAnd = true
 510		args = append(args, ids)
 511	}
 512	if len(symbols) > 0 {
 513		if nextIsAnd {
 514			queryStr += "AND "
 515		} else {
 516			queryStr += "WHERE "
 517		}
 518		queryStr += "symbol IN (?) "
 519		args = append(args, symbols)
 520		nextIsAnd = true
 521	}
 522	if name != "" {
 523		if nextIsAnd {
 524			queryStr += "AND "
 525		} else {
 526			queryStr += "WHERE "
 527		}
 528		queryStr += "name ~ ? "
 529		args = append(args, name)
 530		nextIsAnd = true
 531	}
 532	if fromItem != nil {
 533		if nextIsAnd {
 534			queryStr += "AND "
 535		} else {
 536			queryStr += "WHERE "
 537		}
 538		if order == OrderAsc {
 539			queryStr += "item_id >= ? "
 540		} else {
 541			queryStr += "item_id <= ? "
 542		}
 543		args = append(args, fromItem)
 544	}
 545	// pagination
 546	queryStr += "ORDER BY item_id "
 547	if order == OrderAsc {
 548		queryStr += "ASC "
 549	} else {
 550		queryStr += "DESC "
 551	}
 552	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 553	query, argsQ, err := sqlx.In(queryStr, args...)
 554	if err != nil {
 555		return nil, nil, err
 556	}
 557	query = hdb.db.Rebind(query)
 558	tokens := []*TokenWithUSD{}
 559	if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
 560		return nil, nil, err
 561	}
 562	if len(tokens) == 0 {
 563		return nil, nil, sql.ErrNoRows
 564	}
 565	return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), &db.Pagination{
 566		TotalItems: tokens[0].TotalItems,
 567		FirstItem:  tokens[0].FirstItem,
 568		LastItem:   tokens[0].LastItem,
 569	}, nil
 570}
 571
 572// GetTokenSymbols returns all the token symbols from the DB
 573func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
 574	var tokenSymbols []string
 575	rows, err := hdb.db.Query("SELECT symbol FROM token;")
 576	if err != nil {
 577		return nil, err
 578	}
 579	sym := new(string)
 580	for rows.Next() {
 581		err = rows.Scan(sym)
 582		if err != nil {
 583			return nil, err
 584		}
 585		tokenSymbols = append(tokenSymbols, *sym)
 586	}
 587	return tokenSymbols, nil
 588}
 589
 590// AddAccounts insert accounts into the DB
 591func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
 592	return hdb.addAccounts(hdb.db, accounts)
 593}
 594func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
 595	return db.BulkInsert(
 596		d,
 597		`INSERT INTO account (
 598			idx,
 599			token_id,
 600			batch_num,
 601			bjj,
 602			eth_addr
 603		) VALUES %s;`,
 604		accounts[:],
 605	)
 606}
 607
 608// GetAccounts returns a list of accounts from the DB
 609func (hdb *HistoryDB) GetAccounts() ([]common.Account, error) {
 610	var accs []*common.Account
 611	err := meddler.QueryAll(
 612		hdb.db, &accs,
 613		"SELECT * FROM account ORDER BY idx;",
 614	)
 615	return db.SlicePtrsToSlice(accs).([]common.Account), err
 616}
 617
 618// AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 619// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 620// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 621func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error { return hdb.addL1Txs(hdb.db, l1txs) }
 622
 623// addL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.
 624// If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
 625// BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
 626func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
 627	txs := []txWrite{}
 628	for i := 0; i < len(l1txs); i++ {
 629		af := new(big.Float).SetInt(l1txs[i].Amount)
 630		amountFloat, _ := af.Float64()
 631		laf := new(big.Float).SetInt(l1txs[i].LoadAmount)
 632		loadAmountFloat, _ := laf.Float64()
 633		txs = append(txs, txWrite{
 634			// Generic
 635			IsL1:        true,
 636			TxID:        l1txs[i].TxID,
 637			Type:        l1txs[i].Type,
 638			Position:    l1txs[i].Position,
 639			FromIdx:     &l1txs[i].FromIdx,
 640			ToIdx:       l1txs[i].ToIdx,
 641			Amount:      l1txs[i].Amount,
 642			AmountFloat: amountFloat,
 643			TokenID:     l1txs[i].TokenID,
 644			BatchNum:    l1txs[i].BatchNum,
 645			EthBlockNum: l1txs[i].EthBlockNum,
 646			// L1
 647			ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
 648			UserOrigin:      &l1txs[i].UserOrigin,
 649			FromEthAddr:     &l1txs[i].FromEthAddr,
 650			FromBJJ:         l1txs[i].FromBJJ,
 651			LoadAmount:      l1txs[i].LoadAmount,
 652			LoadAmountFloat: &loadAmountFloat,
 653		})
 654	}
 655	return hdb.addTxs(d, txs)
 656}
 657
 658// AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 659func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error { return hdb.addL2Txs(hdb.db, l2txs) }
 660
 661// addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
 662func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
 663	txs := []txWrite{}
 664	for i := 0; i < len(l2txs); i++ {
 665		f := new(big.Float).SetInt(l2txs[i].Amount)
 666		amountFloat, _ := f.Float64()
 667		txs = append(txs, txWrite{
 668			// Generic
 669			IsL1:        false,
 670			TxID:        l2txs[i].TxID,
 671			Type:        l2txs[i].Type,
 672			Position:    l2txs[i].Position,
 673			FromIdx:     &l2txs[i].FromIdx,
 674			ToIdx:       l2txs[i].ToIdx,
 675			Amount:      l2txs[i].Amount,
 676			AmountFloat: amountFloat,
 677			BatchNum:    &l2txs[i].BatchNum,
 678			EthBlockNum: l2txs[i].EthBlockNum,
 679			// L2
 680			Fee:   &l2txs[i].Fee,
 681			Nonce: &l2txs[i].Nonce,
 682		})
 683	}
 684	return hdb.addTxs(d, txs)
 685}
 686
 687func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
 688	return db.BulkInsert(
 689		d,
 690		`INSERT INTO tx (
 691			is_l1,
 692			id,
 693			type,
 694			position,
 695			from_idx,
 696			to_idx,
 697			amount,
 698			amount_f,
 699			token_id,
 700			batch_num,
 701			eth_block_num,
 702			to_forge_l1_txs_num,
 703			user_origin,
 704			from_eth_addr,
 705			from_bjj,
 706			load_amount,
 707			load_amount_f,
 708			fee,
 709			nonce
 710		) VALUES %s;`,
 711		txs[:],
 712	)
 713}
 714
 715// // GetTxs returns a list of txs from the DB
 716// func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
 717// 	var txs []*common.Tx
 718// 	err := meddler.QueryAll(
 719// 		hdb.db, &txs,
 720// 		`SELECT * FROM tx
 721// 		ORDER BY (batch_num, position) ASC`,
 722// 	)
 723// 	return db.SlicePtrsToSlice(txs).([]common.Tx), err
 724// }
 725
 726// GetHistoryTx returns a tx from the DB given a TxID
 727func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
 728	tx := &TxAPI{}
 729	err := meddler.QueryRow(
 730		hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 731		hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
 732		hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
 733		tx.amount, tx.token_id, tx.amount_usd, 
 734		tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 735		tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 736		token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
 737		token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 738		token.usd_update, block.timestamp
 739		FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 740		INNER JOIN block ON tx.eth_block_num = block.eth_block_num 
 741		WHERE tx.id = $1;`, txID,
 742	)
 743	return tx, err
 744}
 745
 746// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
 747// and pagination info
 748func (hdb *HistoryDB) GetHistoryTxs(
 749	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 750	tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
 751	fromItem, limit *uint, order string,
 752) ([]TxAPI, *db.Pagination, error) {
 753	if ethAddr != nil && bjj != nil {
 754		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 755	}
 756	var query string
 757	var args []interface{}
 758	queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position, 
 759	hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
 760	hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
 761	tx.amount, tx.token_id, tx.amount_usd, 
 762	tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin, 
 763	tx.load_amount, tx.load_amount_usd, tx.fee, tx.fee_usd, tx.nonce,
 764	token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
 765	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 766	token.usd_update, block.timestamp, count(*) OVER() AS total_items, 
 767	MIN(tx.item_id)  OVER() AS first_item, MAX(tx.item_id) OVER() AS last_item 
 768	FROM tx INNER JOIN token ON tx.token_id = token.token_id 
 769	INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
 770	// Apply filters
 771	nextIsAnd := false
 772	// ethAddr filter
 773	if ethAddr != nil {
 774		queryStr = `WITH acc AS 
 775		(select idx from account where eth_addr = ?) ` + queryStr
 776		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 777		nextIsAnd = true
 778		args = append(args, ethAddr)
 779	} else if bjj != nil { // bjj filter
 780		queryStr = `WITH acc AS 
 781		(select idx from account where bjj = ?) ` + queryStr
 782		queryStr += ", acc WHERE (tx.from_idx IN(acc.idx) OR tx.to_idx IN(acc.idx)) "
 783		nextIsAnd = true
 784		args = append(args, bjj)
 785	}
 786	// tokenID filter
 787	if tokenID != nil {
 788		if nextIsAnd {
 789			queryStr += "AND "
 790		} else {
 791			queryStr += "WHERE "
 792		}
 793		queryStr += "tx.token_id = ? "
 794		args = append(args, tokenID)
 795		nextIsAnd = true
 796	}
 797	// idx filter
 798	if idx != nil {
 799		if nextIsAnd {
 800			queryStr += "AND "
 801		} else {
 802			queryStr += "WHERE "
 803		}
 804		queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
 805		args = append(args, idx, idx)
 806		nextIsAnd = true
 807	}
 808	// batchNum filter
 809	if batchNum != nil {
 810		if nextIsAnd {
 811			queryStr += "AND "
 812		} else {
 813			queryStr += "WHERE "
 814		}
 815		queryStr += "tx.batch_num = ? "
 816		args = append(args, batchNum)
 817		nextIsAnd = true
 818	}
 819	// txType filter
 820	if txType != nil {
 821		if nextIsAnd {
 822			queryStr += "AND "
 823		} else {
 824			queryStr += "WHERE "
 825		}
 826		queryStr += "tx.type = ? "
 827		args = append(args, txType)
 828		nextIsAnd = true
 829	}
 830	if fromItem != nil {
 831		if nextIsAnd {
 832			queryStr += "AND "
 833		} else {
 834			queryStr += "WHERE "
 835		}
 836		if order == OrderAsc {
 837			queryStr += "tx.item_id >= ? "
 838		} else {
 839			queryStr += "tx.item_id <= ? "
 840		}
 841		args = append(args, fromItem)
 842		nextIsAnd = true
 843	}
 844	if nextIsAnd {
 845		queryStr += "AND "
 846	} else {
 847		queryStr += "WHERE "
 848	}
 849	queryStr += "tx.batch_num IS NOT NULL "
 850
 851	// pagination
 852	queryStr += "ORDER BY tx.item_id "
 853	if order == OrderAsc {
 854		queryStr += " ASC "
 855	} else {
 856		queryStr += " DESC "
 857	}
 858	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 859	query = hdb.db.Rebind(queryStr)
 860	log.Debug(query)
 861	txsPtrs := []*TxAPI{}
 862	if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
 863		return nil, nil, err
 864	}
 865	txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
 866	if len(txs) == 0 {
 867		return nil, nil, sql.ErrNoRows
 868	}
 869	return txs, &db.Pagination{
 870		TotalItems: txs[0].TotalItems,
 871		FirstItem:  txs[0].FirstItem,
 872		LastItem:   txs[0].LastItem,
 873	}, nil
 874}
 875
 876// GetAllExits returns all exit from the DB
 877func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
 878	var exits []*common.ExitInfo
 879	err := meddler.QueryAll(
 880		hdb.db, &exits,
 881		`SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
 882		exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
 883		exit_tree.delayed_withdrawn FROM exit_tree;`,
 884	)
 885	return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err
 886}
 887
 888// GetExit returns a exit from the DB
 889func (hdb *HistoryDB) GetExit(batchNum *uint, idx *common.Idx) (*HistoryExit, error) {
 890	exit := &HistoryExit{}
 891	err := meddler.QueryRow(
 892		hdb.db, exit, `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 893		token.eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
 894		FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 895		INNER JOIN token ON account.token_id = token.token_id 
 896		WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
 897	)
 898	return exit, err
 899}
 900
 901// GetExits returns a list of exits from the DB and pagination info
 902func (hdb *HistoryDB) GetExits(
 903	ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
 904	tokenID *common.TokenID, idx *common.Idx, batchNum *uint,
 905	fromItem, limit *uint, order string,
 906) ([]HistoryExit, *db.Pagination, error) {
 907	if ethAddr != nil && bjj != nil {
 908		return nil, nil, errors.New("ethAddr and bjj are incompatible")
 909	}
 910	var query string
 911	var args []interface{}
 912	queryStr := `SELECT exit_tree.*, token.token_id, token.eth_block_num AS token_block,
 913	token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
 914	token.usd_update, COUNT(*) OVER() AS total_items, MIN(exit_tree.item_id) OVER() AS first_item, MAX(exit_tree.item_id) OVER() AS last_item
 915	FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx 
 916	INNER JOIN token ON account.token_id = token.token_id `
 917	// Apply filters
 918	nextIsAnd := false
 919	// ethAddr filter
 920	if ethAddr != nil {
 921		queryStr += "WHERE account.eth_addr = ? "
 922		nextIsAnd = true
 923		args = append(args, ethAddr)
 924	} else if bjj != nil { // bjj filter
 925		queryStr += "WHERE account.bjj = ? "
 926		nextIsAnd = true
 927		args = append(args, bjj)
 928	}
 929	// tokenID filter
 930	if tokenID != nil {
 931		if nextIsAnd {
 932			queryStr += "AND "
 933		} else {
 934			queryStr += "WHERE "
 935		}
 936		queryStr += "account.token_id = ? "
 937		args = append(args, tokenID)
 938		nextIsAnd = true
 939	}
 940	// idx filter
 941	if idx != nil {
 942		if nextIsAnd {
 943			queryStr += "AND "
 944		} else {
 945			queryStr += "WHERE "
 946		}
 947		queryStr += "exit_tree.account_idx = ? "
 948		args = append(args, idx)
 949		nextIsAnd = true
 950	}
 951	// batchNum filter
 952	if batchNum != nil {
 953		if nextIsAnd {
 954			queryStr += "AND "
 955		} else {
 956			queryStr += "WHERE "
 957		}
 958		queryStr += "exit_tree.batch_num = ? "
 959		args = append(args, batchNum)
 960		nextIsAnd = true
 961	}
 962	if fromItem != nil {
 963		if nextIsAnd {
 964			queryStr += "AND "
 965		} else {
 966			queryStr += "WHERE "
 967		}
 968		if order == OrderAsc {
 969			queryStr += "exit_tree.item_id >= ? "
 970		} else {
 971			queryStr += "exit_tree.item_id <= ? "
 972		}
 973		args = append(args, fromItem)
 974		// nextIsAnd = true
 975	}
 976	// pagination
 977	queryStr += "ORDER BY exit_tree.item_id "
 978	if order == OrderAsc {
 979		queryStr += " ASC "
 980	} else {
 981		queryStr += " DESC "
 982	}
 983	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
 984	query = hdb.db.Rebind(queryStr)
 985	// log.Debug(query)
 986	exits := []*HistoryExit{}
 987	if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
 988		return nil, nil, err
 989	}
 990	if len(exits) == 0 {
 991		return nil, nil, sql.ErrNoRows
 992	}
 993	return db.SlicePtrsToSlice(exits).([]HistoryExit), &db.Pagination{
 994		TotalItems: exits[0].TotalItems,
 995		FirstItem:  exits[0].FirstItem,
 996		LastItem:   exits[0].LastItem,
 997	}, nil
 998}
 999
1000// // GetTx returns a tx from the DB
1001// func (hdb *HistoryDB) GetTx(txID common.TxID) (*common.Tx, error) {
1002// 	tx := new(common.Tx)
1003// 	return tx, meddler.QueryRow(
1004// 		hdb.db, tx,
1005// 		"SELECT * FROM tx WHERE id = $1;",
1006// 		txID,
1007// 	)
1008// }
1009
1010// GetAllL1UserTxs returns all L1UserTxs from the DB
1011func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
1012	var txs []*common.L1Tx
1013	err := meddler.QueryAll(
1014		hdb.db, &txs,
1015		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1016		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
1017		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
1018		FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`,
1019	)
1020	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
1021}
1022
1023// GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
1024func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
1025	var txs []*common.L1Tx
1026	err := meddler.QueryAll(
1027		hdb.db, &txs,
1028		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1029		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
1030		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
1031		FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`,
1032	)
1033	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
1034}
1035
1036// GetAllL2Txs returns all L2Txs from the DB
1037func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
1038	var txs []*common.L2Tx
1039	err := meddler.QueryAll(
1040		hdb.db, &txs,
1041		`SELECT tx.id, tx.batch_num, tx.position,
1042		tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
1043		tx.type, tx.eth_block_num
1044		FROM tx WHERE is_l1 = FALSE;`,
1045	)
1046	return db.SlicePtrsToSlice(txs).([]common.L2Tx), err
1047}
1048
1049// GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
1050func (hdb *HistoryDB) GetL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
1051	var txs []*common.L1Tx
1052	err := meddler.QueryAll(
1053		hdb.db, &txs,
1054		`SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
1055		tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id, tx.amount,
1056		tx.load_amount, tx.eth_block_num, tx.type, tx.batch_num
1057		FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`,
1058		toForgeL1TxsNum,
1059	)
1060	return db.SlicePtrsToSlice(txs).([]common.L1Tx), err
1061}
1062
1063// TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
1064
1065// GetLastTxsPosition for a given to_forge_l1_txs_num
1066func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
1067	row := hdb.db.QueryRow("SELECT MAX(position) FROM tx WHERE to_forge_l1_txs_num = $1;", toForgeL1TxsNum)
1068	var lastL1TxsPosition int
1069	return lastL1TxsPosition, row.Scan(&lastL1TxsPosition)
1070}
1071
1072// AddBlockSCData stores all the information of a block retrieved by the
1073// Synchronizer.  Blocks should be inserted in order, leaving no gaps because
1074// the pagination system of the API/DB depends on this.  Within blocks, all
1075// items should also be in the correct order (Accounts, Tokens, Txs, etc.)
1076func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
1077	txn, err := hdb.db.Begin()
1078	if err != nil {
1079		return err
1080	}
1081	defer func() {
1082		if err != nil {
1083			errRollback := txn.Rollback()
1084			if errRollback != nil {
1085				log.Errorw("Rollback", "err", errRollback)
1086			}
1087		}
1088	}()
1089
1090	// Add block
1091	err = hdb.addBlock(txn, &blockData.Block)
1092	if err != nil {
1093		return err
1094	}
1095
1096	// Add Coordinators
1097	if len(blockData.Coordinators) > 0 {
1098		err = hdb.addCoordinators(txn, blockData.Coordinators)
1099		if err != nil {
1100			return err
1101		}
1102	}
1103
1104	// Add Bids
1105	if len(blockData.Bids) > 0 {
1106		err = hdb.addBids(txn, blockData.Bids)
1107		if err != nil {
1108			return err
1109		}
1110	}
1111
1112	// Add Tokens
1113	if len(blockData.AddedTokens) > 0 {
1114		err = hdb.addTokens(txn, blockData.AddedTokens)
1115		if err != nil {
1116			return err
1117		}
1118	}
1119
1120	// Add l1 Txs
1121	if len(blockData.L1UserTxs) > 0 {
1122		err = hdb.addL1Txs(txn, blockData.L1UserTxs)
1123		if err != nil {
1124			return err
1125		}
1126	}
1127
1128	// Add Batches
1129	for i := range blockData.Batches {
1130		batch := &blockData.Batches[i]
1131		// Add Batch: this will trigger an update on the DB
1132		// that will set the batch num of forged L1 txs in this batch
1133		err = hdb.addBatch(txn, &batch.Batch)
1134		if err != nil {
1135			return err
1136		}
1137
1138		// Add unforged l1 Txs
1139		if batch.L1Batch {
1140			if len(batch.L1CoordinatorTxs) > 0 {
1141				err = hdb.addL1Txs(txn, batch.L1CoordinatorTxs)
1142				if err != nil {
1143					return err
1144				}
1145			}
1146		}
1147
1148		// Add l2 Txs
1149		if len(batch.L2Txs) > 0 {
1150			err = hdb.addL2Txs(txn, batch.L2Txs)
1151			if err != nil {
1152				return err
1153			}
1154		}
1155
1156		// Add accounts
1157		if len(batch.CreatedAccounts) > 0 {
1158			err = hdb.addAccounts(txn, batch.CreatedAccounts)
1159			if err != nil {
1160				return err
1161			}
1162		}
1163
1164		// Add exit tree
1165		if len(batch.ExitTree) > 0 {
1166			err = hdb.addExitTree(txn, batch.ExitTree)
1167			if err != nil {
1168				return err
1169			}
1170		}
1171
1172		// TODO: INSERT CONTRACTS VARS
1173	}
1174
1175	return txn.Commit()
1176}
1177
1178// GetCoordinatorAPI returns a coordinator by its bidderAddr
1179func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
1180	coordinator := &CoordinatorAPI{}
1181	err := meddler.QueryRow(
1182		hdb.db, coordinator, `SELECT * FROM coordinator WHERE bidder_addr = $1;`, bidderAddr,
1183	)
1184	return coordinator, err
1185}
1186
1187// GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
1188func (hdb *HistoryDB) GetCoordinatorsAPI(fromItem, limit *uint, order string) ([]CoordinatorAPI, *db.Pagination, error) {
1189	var query string
1190	var args []interface{}
1191	queryStr := `SELECT coordinator.*, 
1192	COUNT(*) OVER() AS total_items, MIN(coordinator.item_id) OVER() AS first_item, MAX(coordinator.item_id) OVER() AS last_item
1193	FROM coordinator `
1194	// Apply filters
1195	if fromItem != nil {
1196		queryStr += "WHERE "
1197		if order == OrderAsc {
1198			queryStr += "coordinator.item_id >= ? "
1199		} else {
1200			queryStr += "coordinator.item_id <= ? "
1201		}
1202		args = append(args, fromItem)
1203	}
1204	// pagination
1205	queryStr += "ORDER BY coordinator.item_id "
1206	if order == OrderAsc {
1207		queryStr += " ASC "
1208	} else {
1209		queryStr += " DESC "
1210	}
1211	queryStr += fmt.Sprintf("LIMIT %d;", *limit)
1212	query = hdb.db.Rebind(queryStr)
1213
1214	coordinators := []*CoordinatorAPI{}
1215	if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
1216		return nil, nil, err
1217	}
1218	if len(coordinators) == 0 {
1219		return nil, nil, sql.ErrNoRows
1220	}
1221	return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI), &db.Pagination{
1222		TotalItems: coordinators[0].TotalItems,
1223		FirstItem:  coordinators[0].FirstItem,
1224		LastItem:   coordinators[0].LastItem,
1225	}, nil
1226}