to find the current latest journal entries for each account_id (#273)

This commit is contained in:
Michael Quigley 2023-03-22 15:42:47 -04:00 committed by Kenneth Bingham
parent 5536a37372
commit a374ab421d
No known key found for this signature in database
GPG Key ID: 31709281860130B6
2 changed files with 48 additions and 0 deletions

View File

@ -40,3 +40,19 @@ func (str *Store) FindLatestAccountLimitJournal(acctId int, trx *sqlx.Tx) (*Acco
}
return j, nil
}
func (str *Store) FindAllLatestAccountLimitJournal(trx *sqlx.Tx) ([]*AccountLimitJournal, error) {
rows, err := trx.Queryx("select id, account_id, rx_bytes, tx_bytes, action, created_at, updated_at from account_limit_journal where id in (select max(id) as id from account_limit_journal group by account_id)")
if err != nil {
return nil, errors.Wrap(err, "error selecting distinct account_limit_jounal")
}
var is []*AccountLimitJournal
for rows.Next() {
i := &AccountLimitJournal{}
if err := rows.StructScan(i); err != nil {
return nil, errors.Wrap(err, "error scanning account_limit_journal")
}
is = append(is, i)
}
return is, nil
}

View File

@ -45,3 +45,35 @@ func TestAccountLimitJournal(t *testing.T) {
assert.Equal(t, int64(4096), latestAlj.TxBytes)
assert.Equal(t, LimitAction, latestAlj.Action)
}
func TestFindAllLatestAccountLimitJournal(t *testing.T) {
str, err := Open(&Config{Path: ":memory:", Type: "sqlite3"})
assert.Nil(t, err)
assert.NotNil(t, str)
trx, err := str.Begin()
assert.Nil(t, err)
assert.NotNil(t, trx)
acctId1, err := str.CreateAccount(&Account{Email: "nobody@nowehere.com", Salt: "salt1", Password: "password1", Token: "token1", Limitless: false, Deleted: false}, trx)
assert.Nil(t, err)
_, err = str.CreateAccountLimitJournal(&AccountLimitJournal{AccountId: acctId1, RxBytes: 2048, TxBytes: 4096, Action: WarningAction}, trx)
assert.Nil(t, err)
_, err = str.CreateAccountLimitJournal(&AccountLimitJournal{AccountId: acctId1, RxBytes: 2048, TxBytes: 4096, Action: ClearAction}, trx)
assert.Nil(t, err)
aljId13, err := str.CreateAccountLimitJournal(&AccountLimitJournal{AccountId: acctId1, RxBytes: 2048, TxBytes: 4096, Action: LimitAction}, trx)
assert.Nil(t, err)
acctId2, err := str.CreateAccount(&Account{Email: "someone@somewhere.com", Salt: "salt2", Password: "password2", Token: "token2", Limitless: false, Deleted: false}, trx)
assert.Nil(t, err)
aljId21, err := str.CreateAccountLimitJournal(&AccountLimitJournal{AccountId: acctId2, RxBytes: 2048, TxBytes: 4096, Action: WarningAction}, trx)
assert.Nil(t, err)
aljs, err := str.FindAllLatestAccountLimitJournal(trx)
assert.Nil(t, err)
assert.Equal(t, 2, len(aljs))
assert.Equal(t, aljId13, aljs[0].Id)
assert.Equal(t, aljId21, aljs[1].Id)
}