diff --git a/internal/postgres/operation/storage.go b/internal/postgres/operation/storage.go index 8c1cb46d0..50f2a4294 100644 --- a/internal/postgres/operation/storage.go +++ b/internal/postgres/operation/storage.go @@ -122,32 +122,45 @@ 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") - - for key, value := range filters { - query.Where("? = ?", pg.Ident(key), value) - } + var ( + current = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.UTC) + ) + + for current.Year() < 2018 { + query := storage.DB.Model((*operation.Operation)(nil)). + Where("deffated_storage is not null"). + Where("timestamp >= ?", current). + Where("timestamp < ?", current.AddDate(1, 0, 0)). + OrderExpr("operation.id desc") + + for key, value := range filters { + query.Where("? = ?", pg.Ident(key), value) + } - if lastID > 0 { - query.Where("operation.id < ?", lastID) - } + if lastID > 0 { + query.Where("operation.id < ?", lastID) + } - query.Limit(2) // It's a hack to avoid postgres "optimization". Limit = 1 is extremely slow. + 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). + 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"). + Select(&ops); err != nil { + return operation.Operation{}, err + } + if len(ops) > 0 { + return ops[0], nil + } - var ops []operation.Operation - if err := storage.DB.Model().TableExpr("(?) as operation", query). - 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"). - Select(&ops); err != nil { - return operation.Operation{}, err - } - if len(ops) == 0 { - return operation.Operation{}, pg.ErrNoRows + current = current.AddDate(-1, 0, 0) } - return ops[0], nil + + return operation.Operation{}, pg.ErrNoRows } // Get -