From 01d2454d984472e219869b8818cecdd87c43da7c Mon Sep 17 00:00:00 2001 From: Artem Poltorzhitskiy Date: Tue, 31 Jan 2023 17:12:01 +0400 Subject: [PATCH] Fix: last operation query (#962) --- internal/postgres/operation/storage.go | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/internal/postgres/operation/storage.go b/internal/postgres/operation/storage.go index 1088a1a23..7a35f7c5b 100644 --- a/internal/postgres/operation/storage.go +++ b/internal/postgres/operation/storage.go @@ -122,7 +122,7 @@ func (storage *Storage) GetByAccount(acc account.Account, size uint64, filters m // Last - get last operation by `filters` with not empty deffated_storage func (storage *Storage) Last(filters map[string]interface{}, lastID int64) (operation.Operation, error) { - query := storage.DB.Model((*operation.Operation)(nil)).Where("deffated_storage is not null").OrderExpr("operation.id desc") + query := storage.DB.Model((*operation.Operation)(nil)).Where("deffated_storage is not null") for key, value := range filters { query.Where("? = ?", pg.Ident(key), value) @@ -132,22 +132,19 @@ func (storage *Storage) Last(filters map[string]interface{}, lastID int64) (oper query.Where("operation.id < ?", lastID) } - query.Limit(2) // It's a hack to avoid postgres "optimization". Limit = 1 is extremely slow. - - var ops []operation.Operation - if err := storage.DB.Model().TableExpr("(?) as operation", query). + var ops operation.Operation + if err := storage.DB.Model().With("operation", query).Table("operation"). ColumnExpr("operation.*"). ColumnExpr("source.address as source__address"). ColumnExpr("destination.address as destination__address"). Join("LEFT JOIN accounts as source ON source.id = operation.source_id"). Join("LEFT JOIN accounts as destination ON destination.id = operation.destination_id"). + OrderExpr("operation.id desc"). + Limit(1). Select(&ops); err != nil { return operation.Operation{}, err } - if len(ops) == 0 { - return operation.Operation{}, pg.ErrNoRows - } - return ops[0], nil + return ops, nil } // Get -