zitadel/internal/eventstore/handler/crdb/handler_stmt_test.go
Silvan 37ee5b4bab
feat: jobs for projection tables (#1730)
* job queue

* wg improvements

* start handler

* statement

* statements

* imporve handler

* improve statement

* statement in seperate file

* move handlers

* move query/old to query

* handler

* read models

* bulk works

* cleanup

* contrib

* rename readmodel to projection

* rename read_models schema to projections

* rename read_models schema to projections

* search query as func,
bulk iterates as long as new events

* add event sequence less query

* update checks for events between current sequence and sequence of first statement if it has previous sequence 0

* cleanup crdb projection

* refactor projection handler

* start with testing

* tests for handler

* remove todo

* refactor statement: remove table name,
add tests

* improve projection handler shutdown,
no savepoint if noop stmt,
tests for stmt handler

* tests

* start failed events

* seperate branch for contrib

* move statement constructors to crdb pkg

* correct import

* Subscribe for eventtypes (#1800)

* fix: is default (#1737)

* fix: use email as username on global org (#1738)

* fix: use email as username on global org

* Update user_human.go

* Update register_handler.go

* chore(deps): update docusaurus (#1739)

* chore: remove PAT and use GH Token (#1716)

* chore: remove PAT and use GH Token

* fix env

* fix env

* fix env

* md lint

* trigger ci

* change user

* fix GH bug

* replace login part

* chore: add GH Token to sem rel (#1746)

* chore: add GH Token to sem rel

* try branch

* add GH Token

* remove test branch again

* docs: changes acme to acme-caos (#1744)

* changes acme to acme-caos

* Apply suggestions from code review

Co-authored-by: Florian Forster <florian@caos.ch>

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>

* feat: add additional origins on applications (#1691)

* feat: add additional origins on applications

* app additional redirects

* chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console (#1706)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @angular/cli from 11.2.8 to 11.2.11 in /console

Bumps [@angular/cli](https://github.com/angular/angular-cli) from 11.2.8 to 11.2.11.
- [Release notes](https://github.com/angular/angular-cli/releases)
- [Commits](https://github.com/angular/angular-cli/compare/v11.2.8...v11.2.11)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console (#1703)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump stylelint from 13.10.0 to 13.13.1 in /console

Bumps [stylelint](https://github.com/stylelint/stylelint) from 13.10.0 to 13.13.1.
- [Release notes](https://github.com/stylelint/stylelint/releases)
- [Changelog](https://github.com/stylelint/stylelint/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stylelint/stylelint/compare/13.10.0...13.13.1)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console (#1702)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @types/node from 14.14.37 to 15.0.1 in /console

Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 14.14.37 to 15.0.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console (#1701)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps): bump ts-protoc-gen from 0.14.0 to 0.15.0 in /console

Bumps [ts-protoc-gen](https://github.com/improbable-eng/ts-protoc-gen) from 0.14.0 to 0.15.0.
- [Release notes](https://github.com/improbable-eng/ts-protoc-gen/releases)
- [Changelog](https://github.com/improbable-eng/ts-protoc-gen/blob/master/CHANGELOG.md)
- [Commits](https://github.com/improbable-eng/ts-protoc-gen/compare/0.14.0...0.15.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump @types/jasmine from 3.6.9 to 3.6.10 in /console (#1682)

Bumps [@types/jasmine](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jasmine) from 3.6.9 to 3.6.10.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jasmine)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump @types/google-protobuf in /console (#1681)

Bumps [@types/google-protobuf](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/google-protobuf) from 3.7.4 to 3.15.2.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/google-protobuf)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump grpc from 1.24.5 to 1.24.7 in /console (#1666)

Bumps [grpc](https://github.com/grpc/grpc-node) from 1.24.5 to 1.24.7.
- [Release notes](https://github.com/grpc/grpc-node/releases)
- [Commits](https://github.com/grpc/grpc-node/compare/grpc@1.24.5...grpc@1.24.7)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* lock

* chore(deps-dev): bump @angular/language-service from 11.2.9 to 11.2.12 in /console (#1704)

* fix: show org with regex (#1688)

* fix: flag mapping (#1699)

* chore(deps-dev): bump @angular/language-service in /console

Bumps [@angular/language-service](https://github.com/angular/angular/tree/HEAD/packages/language-service) from 11.2.9 to 11.2.12.
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/master/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/11.2.12/packages/language-service)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Silvan <silvan.reusser@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* package lock

* downgrade grpc

* downgrade protobuf types

* revert npm packs 🥸

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Silvan <silvan.reusser@gmail.com>

* docs: update run and start section texts (#1745)

* update run and start section texts

* adds showcase

Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>

* fix: additional origin list (#1753)

* fix: handle api configs in authz handler (#1755)

* fix(console): add model for api keys, fix toast, binding (#1757)

* fix: add model for api keys, fix toast, binding

* show api clientid

* fix: missing patchvalue (#1758)

* feat: refresh token (#1728)

* begin refresh tokens

* refresh tokens

* list and revoke refresh tokens

* handle remove

* tests for refresh tokens

* uniqueness and default expiration

* rename oidc token methods

* cleanup

* migration version

* Update internal/static/i18n/en.yaml

Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* fixes

* feat: update oidc pkg for refresh tokens

Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* fix: correct json name of clientId in key.json (#1760)

* fix: migration version (#1767)

* start subscription

* eventtypes

* fix(login): links (#1778)

* fix(login): href for help

* fix(login): correct link to tos

* fix: access tokens for service users and refresh token infos (#1779)

* fix: access token for service user

* handle info from refresh request

* uniqueness

* postpone access token uniqueness change

* chore(coc): recommend code of conduct (#1782)

* subscribe for events

* feat(console): refresh toggle out of granttype context (#1785)

* refresh toggle

* disable if not code flow, lint

* lint

* fix: change oidc config order

* accept refresh option within flow

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* fix: refresh token activation (#1795)

* fix: oidc grant type check

* docs: add offline_access scope

* docs: update refresh token status in supported grant types

* fix: update oidc pkg

* fix: check refresh token grant type (#1796)

* configuration structs

* org admins

* failed events

* fixes

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>

* remove comment

* aggregate reducer

* remove eventtypes

* add protoc-get-validate to mod

* fix transaltion

* upsert

* add gender on org admins,
allow to retry failed stmts after configurable time

* remove if

* sub queries

* fix: tests

* add builder to tests

* new search query

* rename searchquerybuilder to builder

* remove comment from code

* test with multiple queries

* add filters test

* current sequences

* make org and org_admins work again

* add aggregate type to current sequence

* fix(contibute): listing

* add validate module

* fix: search queries

* feat(eventstore): previous aggregate root sequence (#1810)

* feat(eventstore): previous aggregate root sequence

* fix tests

* fix: eventstore v1 test

* add col to all mocked rows

* next try

* fix mig

* rename aggregate root to aggregate type

* update comment

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* small refactorings

* allow update multiple current sequences

* unique log id

* fix migrations

* rename org admin to org owner

* improve error handling and logging

* fix(migration): optimize prev agg root seq

* fix: projection handler test

* fix: sub queries

* small fixes

* additional event types

* correct org owner projection

* fix primary key

* feat(eventstore): jobs for projections (#2026)

* fix: template names in login (#1974)

* fix: template names in login

* fix: error.html

* fix: check for features on mgmt only (#1976)

* fix: add sentry in ui, http and projection handlers (#1977)

* fix: add sentry in ui, http and projection handlers

* fix test

* fix(eventstore): sub queries (#1805)

* sub queries

* fix: tests

* add builder to tests

* new search query

* rename searchquerybuilder to builder

* remove comment from code

* test with multiple queries

* add filters test

* fix(contibute): listing

* add validate module

* fix: search queries

* remove unused event type in query

* ignore query if error in marshal

* go mod tidy

* update privacy policy query

* update queries

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* feat: Extend oidc idp with oauth endpoints (#1980)

* feat: add oauth attributes to oidc idp configuration

* feat: return idpconfig id on create idp

* feat: tests

* feat: descriptions

* feat: docs

* feat: tests

* docs: update to beta 3 (#1984)

* fix: role assertion (#1986)

* fix: enum to display access token role assertion

* improve assertion descriptions

* fix nil pointer

* docs: eventstore (#1982)

* docs: eventstore

* Apply suggestions from code review

Co-authored-by: Florian Forster <florian@caos.ch>

Co-authored-by: Florian Forster <florian@caos.ch>

* fix(sentry): trigger sentry release (#1989)

* feat(send sentry release): send sentry release

* fix(moved step and added releasetag): moved step and added releasetag

* fix: set version for sentry release (#1990)

* feat(send sentry release): send sentry release

* fix(moved step and added releasetag): moved step and added releasetag

* fix(corrected var name): corrected var name

Co-authored-by: Livio Amstutz <livio.a@gmail.com>

* fix: log error reason on terminate session (#1973)

* fix: return default language file, if requested lang does not exist for default login texts (#1988)

* fix: return default language file, if requested lang doesnt exists

* feat: read default translation file

* feat: docs

* fix: race condition in auth request unmarshalling (#1993)

* feat: handle ui_locales in login (#1994)

* fix: handle ui_locales in login

* move supportedlanguage func into i18n package

* update oidc pkg

* fix: handle closed channels on unsubscribe (#1995)

* fix: give restore more time (#1997)

* fix: translation file read (#2009)

* feat: translation file read

* feat: readme

* fix: enable idp add button for iam users (#2010)

* fix: filter event_data (#2011)

* feat: Custom message files (#1992)

* feat: add get custom message text to admin api

* feat: read custom message texts from files

* feat: get languages in apis

* feat: get languages in apis

* feat: get languages in apis

* feat: pr feedback

* feat: docs

* feat: merge main

* fix: sms notification (#2013)

* fix: phone verifications

* feat: fix password reset as sms

* fix: phone verification

* fix: grpc status in sentry and validation interceptors (#2012)

* fix: remove oauth endpoints from oidc config proto (#2014)

* try with view

* fix(console): disable sw (#2021)

* fix: disable sw

* angular.json disable sw

* project projections

* fix typos

* customize projections

* customizable projections,
add change date to projects

Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com>
Co-authored-by: Elio Bischof <eliobischof@gmail.com>

* env file

* typo

* correct users

* correct migration

* fix: merge fail

* fix test

* fix(tests): unordered matcher

* improve currentSequenceMatcher

* correct certs

* correct certs

* add zitadel database on database list

* refctor switch in match

* enable all handlers

* Delete io.env

* cleanup

* add handlers

* rename view to projection

* rename view to projection

* fix type typo

* remove unnecessary logs

* refactor stmts

* simplify interval calculation

* fix tests

* fix unlock test

* fix migration

* migs

* fix(operator): update cockroach and flyway versions (#2138)

* chore(deps): bump k8s.io/apiextensions-apiserver from 0.19.2 to 0.21.3

Bumps [k8s.io/apiextensions-apiserver](https://github.com/kubernetes/apiextensions-apiserver) from 0.19.2 to 0.21.3.
- [Release notes](https://github.com/kubernetes/apiextensions-apiserver/releases)
- [Commits](https://github.com/kubernetes/apiextensions-apiserver/compare/v0.19.2...v0.21.3)

---
updated-dependencies:
- dependency-name: k8s.io/apiextensions-apiserver
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(deps): bump google.golang.org/api from 0.34.0 to 0.52.0

Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.34.0 to 0.52.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/master/CHANGES.md)
- [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.34.0...v0.52.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* start update dependencies

* update mods and otlp

* fix(build): update to go 1.16

* old version for k8s mods

* update k8s versions

* update orbos

* fix(operator): update cockroach and flyway version

* Update images.go

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Stefan Benz <stefan@caos.ch>

* fix import

* fix typo

* fix(migration): add org projection

* fix(projection): correct table for org events in org owners

* better insert stmt

* fix typo

* fix typo

* set max connection lifetime

* set max conns and conn lifetime in eventstore v1

* configure sql connection settings

* add mig for agg type index

* fix replace tab in yaml

* check requeue at least 500ms

* split column in column and condition

* remove useless comment

* mig versions

* fix migs

Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: Florian Forster <florian@caos.ch>
Co-authored-by: mffap <mpa@caos.ch>
Co-authored-by: Maximilian Panne <maximilian.panne@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Fabi <38692350+fgerschwiler@users.noreply.github.com>
Co-authored-by: Christian Jakob <47860090+thesephirot@users.noreply.github.com>
Co-authored-by: Elio Bischof <eliobischof@gmail.com>
Co-authored-by: Stefan Benz <stefan@caos.ch>
2021-08-19 08:31:56 +02:00

1548 lines
35 KiB
Go

package crdb
import (
"context"
"database/sql"
"errors"
"reflect"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/handler"
"github.com/caos/zitadel/internal/eventstore/repository"
es_repo_mock "github.com/caos/zitadel/internal/eventstore/repository/mock"
)
var (
errFilter = errors.New("filter err")
errReduce = errors.New("reduce err")
)
var _ eventstore.EventReader = &testEvent{}
type testEvent struct {
eventstore.BaseEvent
sequence uint64
previousSequence uint64
aggregateType eventstore.AggregateType
}
func (e *testEvent) Sequence() uint64 {
return e.sequence
}
func (e *testEvent) Aggregate() eventstore.Aggregate {
return eventstore.Aggregate{
Type: e.aggregateType,
}
}
func (e *testEvent) PreviousAggregateTypeSequence() uint64 {
return e.previousSequence
}
func TestProjectionHandler_SearchQuery(t *testing.T) {
type want struct {
SearchQueryBuilder *eventstore.SearchQueryBuilder
limit uint64
isErr func(error) bool
expectations []mockExpectation
}
type fields struct {
sequenceTable string
projectionName string
aggregates []eventstore.AggregateType
bulkLimit uint64
}
tests := []struct {
name string
fields fields
want want
}{
{
name: "error in current sequence",
fields: fields{
sequenceTable: "my_sequences",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"testAgg"},
bulkLimit: 5,
},
want: want{
limit: 0,
isErr: func(err error) bool {
return errors.Is(err, sql.ErrTxDone)
},
expectations: []mockExpectation{
expectCurrentSequenceErr("my_sequences", "my_projection", sql.ErrTxDone),
},
SearchQueryBuilder: nil,
},
},
{
name: "only aggregates",
fields: fields{
sequenceTable: "my_sequences",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"testAgg"},
bulkLimit: 5,
},
want: want{
limit: 5,
isErr: func(err error) bool {
return err == nil
},
expectations: []mockExpectation{
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
},
SearchQueryBuilder: eventstore.
NewSearchQueryBuilder(eventstore.ColumnsEvent).
AddQuery().
AggregateTypes("testAgg").
SequenceGreater(5).
Builder().
Limit(5),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
h := NewStatementHandler(context.Background(), StatementHandlerConfig{
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
ProjectionName: tt.fields.projectionName,
},
SequenceTable: tt.fields.sequenceTable,
BulkLimit: tt.fields.bulkLimit,
Client: client,
})
h.aggregates = tt.fields.aggregates
for _, expectation := range tt.want.expectations {
expectation(mock)
}
query, limit, err := h.SearchQuery()
if !tt.want.isErr(err) {
t.Errorf("ProjectionHandler.prepareBulkStmts() error = %v", err)
return
}
if !reflect.DeepEqual(query, tt.want.SearchQueryBuilder) {
t.Errorf("unexpected query: expected %v, got %v", tt.want.SearchQueryBuilder, query)
}
if tt.want.limit != limit {
t.Errorf("unexpected limit: got: %d want %d", limit, tt.want.limit)
}
mock.MatchExpectationsInOrder(true)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
})
}
}
func TestStatementHandler_Update(t *testing.T) {
type fields struct {
eventstore *eventstore.Eventstore
aggregates []eventstore.AggregateType
}
type want struct {
expectations []mockExpectation
isErr func(error) bool
stmtsLen int
}
type args struct {
ctx context.Context
stmts []handler.Statement
reduce handler.Reduce
}
tests := []struct {
name string
fields fields
want want
args args
}{
{
name: "begin fails",
args: args{
ctx: context.Background(),
},
want: want{
expectations: []mockExpectation{
expectBeginErr(sql.ErrConnDone),
},
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
},
},
{
name: "current sequence fails",
args: args{
ctx: context.Background(),
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequenceErr("my_sequences", "my_projection", sql.ErrTxDone),
expectRollback(),
},
isErr: func(err error) bool {
return errors.Is(err, sql.ErrTxDone)
},
},
},
{
name: "fetch previous fails",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).
ExpectFilterEventsError(errFilter),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewNoOpStatement(&testEvent{
aggregateType: "agg",
sequence: 6,
previousSequence: 0,
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
expectRollback(),
},
isErr: func(err error) bool {
return errors.Is(err, errFilter)
},
stmtsLen: 1,
},
},
{
name: "no successful stmts",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "testAgg",
sequence: 7,
previousSequence: 6,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
expectCommit(),
},
isErr: func(err error) bool {
return errors.Is(err, handler.ErrSomeStmtsFailed)
},
stmtsLen: 1,
},
},
{
name: "update current sequence fails",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t),
),
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 7,
previousSequence: 5,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "agg"),
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
expectUpdateCurrentSequenceNoRows("my_sequences", "my_projection", 7, "agg"),
expectRollback(),
},
isErr: func(err error) bool {
return errors.Is(err, errSeqNotUpdated)
},
stmtsLen: 1,
},
},
{
name: "commit fails",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t),
),
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 7,
previousSequence: 5,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "agg"),
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
expectUpdateCurrentSequence("my_sequences", "my_projection", 7, "agg"),
expectCommitErr(sql.ErrConnDone),
},
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
stmtsLen: 1,
},
},
{
name: "correct",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewNoOpStatement(&testEvent{
aggregateType: "testAgg",
sequence: 7,
previousSequence: 5,
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
expectUpdateCurrentSequence("my_sequences", "my_projection", 7, "testAgg"),
expectCommit(),
},
isErr: func(err error) bool {
return errors.Is(err, nil)
},
stmtsLen: 0,
},
},
{
name: "fetch previous stmts no additional stmts",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEvents(),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewNoOpStatement(&testEvent{
aggregateType: "testAgg",
sequence: 7,
previousSequence: 0,
}),
},
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
expectUpdateCurrentSequence("my_sequences", "my_projection", 7, "testAgg"),
expectCommit(),
},
isErr: func(err error) bool {
return errors.Is(err, nil)
},
},
},
{
name: "fetch previous stmts additional events",
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEvents(
&repository.Event{
AggregateType: "testAgg",
Sequence: 6,
PreviousAggregateSequence: 5,
},
),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
args: args{
ctx: context.Background(),
stmts: []handler.Statement{
NewNoOpStatement(&testEvent{
aggregateType: "testAgg",
sequence: 7,
previousSequence: 0,
}),
},
reduce: testReduce(),
},
want: want{
expectations: []mockExpectation{
expectBegin(),
expectCurrentSequence("my_sequences", "my_projection", 5, "testAgg"),
expectUpdateCurrentSequence("my_sequences", "my_projection", 7, "testAgg"),
expectCommit(),
},
isErr: func(err error) bool {
return errors.Is(err, nil)
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
h := NewStatementHandler(context.Background(), StatementHandlerConfig{
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
ProjectionName: "my_projection",
HandlerConfig: handler.HandlerConfig{
Eventstore: tt.fields.eventstore,
},
RequeueEvery: 0,
},
SequenceTable: "my_sequences",
Client: client,
})
h.aggregates = tt.fields.aggregates
for _, expectation := range tt.want.expectations {
expectation(mock)
}
stmts, err := h.Update(tt.args.ctx, tt.args.stmts, tt.args.reduce)
if !tt.want.isErr(err) {
t.Errorf("StatementHandler.Update() error = %v", err)
}
if tt.want.stmtsLen != len(stmts) {
t.Errorf("wrong stmts length: want: %d got %d", tt.want.stmtsLen, len(stmts))
}
mock.MatchExpectationsInOrder(true)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
})
}
}
func TestProjectionHandler_fetchPreviousStmts(t *testing.T) {
type args struct {
ctx context.Context
stmtSeq uint64
sequences currentSequences
reduce handler.Reduce
}
type want struct {
stmtCount int
isErr func(error) bool
}
type fields struct {
eventstore *eventstore.Eventstore
aggregates []eventstore.AggregateType
}
tests := []struct {
name string
args args
fields fields
want want
}{
{
name: "no queries",
args: args{
ctx: context.Background(),
reduce: testReduce(),
},
fields: fields{
aggregates: []eventstore.AggregateType{"testAgg"},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, nil)
},
stmtCount: 0,
},
},
{
name: "eventstore returns err",
args: args{
ctx: context.Background(),
reduce: testReduce(),
sequences: currentSequences{
"testAgg": 5,
},
stmtSeq: 6,
},
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEventsError(errFilter),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, errFilter)
},
stmtCount: 0,
},
},
{
name: "no events found",
args: args{
ctx: context.Background(),
reduce: testReduce(),
sequences: currentSequences{
"testAgg": 5,
},
stmtSeq: 6,
},
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEvents(),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
want: want{
isErr: func(err error) bool {
return err == nil
},
},
},
{
name: "found events",
args: args{
ctx: context.Background(),
reduce: testReduce(),
sequences: currentSequences{
"testAgg": 5,
},
stmtSeq: 10,
},
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEvents(
&repository.Event{
ID: "id",
Sequence: 7,
PreviousAggregateSequence: 0,
CreationDate: time.Now(),
Type: "test.added",
Version: "v1",
AggregateID: "testid",
AggregateType: "testAgg",
},
&repository.Event{
ID: "id",
Sequence: 9,
PreviousAggregateSequence: 7,
CreationDate: time.Now(),
Type: "test.changed",
Version: "v1",
AggregateID: "testid",
AggregateType: "testAgg",
},
),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
want: want{
stmtCount: 2,
isErr: func(err error) bool {
return err == nil
},
},
},
{
name: "reduce fails",
args: args{
ctx: context.Background(),
reduce: testReduceErr(errReduce),
sequences: currentSequences{
"testAgg": 5,
},
stmtSeq: 10,
},
fields: fields{
eventstore: eventstore.NewEventstore(
es_repo_mock.NewRepo(t).ExpectFilterEvents(
&repository.Event{
ID: "id",
Sequence: 7,
PreviousAggregateSequence: 0,
CreationDate: time.Now(),
Type: "test.added",
Version: "v1",
AggregateID: "testid",
AggregateType: "testAgg",
},
),
),
aggregates: []eventstore.AggregateType{"testAgg"},
},
want: want{
stmtCount: 0,
isErr: func(err error) bool {
return errors.Is(err, errReduce)
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &StatementHandler{
ProjectionHandler: handler.NewProjectionHandler(handler.ProjectionHandlerConfig{
HandlerConfig: handler.HandlerConfig{
Eventstore: tt.fields.eventstore,
},
ProjectionName: "my_projection",
RequeueEvery: 0,
}),
aggregates: tt.fields.aggregates,
}
stmts, err := h.fetchPreviousStmts(tt.args.ctx, tt.args.stmtSeq, tt.args.sequences, tt.args.reduce)
if !tt.want.isErr(err) {
t.Errorf("ProjectionHandler.prepareBulkStmts() error = %v", err)
return
}
if tt.want.stmtCount != len(stmts) {
t.Errorf("unexpected length of stmts: got: %d want %d", len(stmts), tt.want.stmtCount)
}
})
}
}
func TestStatementHandler_executeStmts(t *testing.T) {
type fields struct {
projectionName string
maxFailureCount uint
failedEventsTable string
}
type args struct {
stmts []handler.Statement
sequences currentSequences
}
type want struct {
expectations []mockExpectation
idx int
}
tests := []struct {
name string
fields fields
args args
want want
}{
{
name: "already inserted",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 5,
previousSequence: 2,
},
[]handler.Column{
{
Name: "col",
Value: "val1",
},
}),
},
sequences: currentSequences{
"agg": 5,
},
},
want: want{
expectations: []mockExpectation{},
idx: -1,
},
},
{
name: "previous sequence higher than sequence",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 5,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col1",
Value: "val1",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 8,
previousSequence: 7,
},
[]handler.Column{
{
Name: "col2",
Value: "val2",
},
}),
},
sequences: currentSequences{
"agg": 2,
},
},
want: want{
expectations: []mockExpectation{
expectSavePoint(),
expectCreate("my_projection", []string{"col1"}, []string{"$1"}),
expectSavePointRelease(),
},
idx: 0,
},
},
{
name: "execute fails not continue",
fields: fields{
projectionName: "my_projection",
maxFailureCount: 5,
failedEventsTable: "failed_events",
},
args: args{
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 5,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 6,
previousSequence: 5,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 7,
previousSequence: 6,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
sequences: currentSequences{
"agg": 2,
},
},
want: want{
expectations: []mockExpectation{
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
expectSavePoint(),
expectCreateErr("my_projection", []string{"col"}, []string{"$1"}, sql.ErrConnDone),
expectSavePointRollback(),
expectFailureCount("failed_events", "my_projection", 6, 3),
expectUpdateFailureCount("failed_events", "my_projection", 6, 4),
},
idx: 0,
},
},
{
name: "execute fails continue",
fields: fields{
projectionName: "my_projection",
maxFailureCount: 5,
failedEventsTable: "failed_events",
},
args: args{
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 5,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col1",
Value: "val1",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 6,
previousSequence: 5,
},
[]handler.Column{
{
Name: "col2",
Value: "val2",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 7,
previousSequence: 6,
},
[]handler.Column{
{
Name: "col3",
Value: "val3",
},
}),
},
sequences: currentSequences{
"agg": 2,
},
},
want: want{
expectations: []mockExpectation{
expectSavePoint(),
expectCreate("my_projection", []string{"col1"}, []string{"$1"}),
expectSavePointRelease(),
expectSavePoint(),
expectCreateErr("my_projection", []string{"col2"}, []string{"$1"}, sql.ErrConnDone),
expectSavePointRollback(),
expectFailureCount("failed_events", "my_projection", 6, 4),
expectUpdateFailureCount("failed_events", "my_projection", 6, 5),
expectSavePoint(),
expectCreate("my_projection", []string{"col3"}, []string{"$1"}),
expectSavePointRelease(),
},
idx: 2,
},
},
{
name: "correct",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmts: []handler.Statement{
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 5,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 6,
previousSequence: 5,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 7,
previousSequence: 6,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
sequences: currentSequences{
"agg": 2,
},
},
want: want{
expectations: []mockExpectation{
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
},
idx: 2,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
h := NewStatementHandler(
context.Background(),
StatementHandlerConfig{
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
HandlerConfig: handler.HandlerConfig{
Eventstore: nil,
},
ProjectionName: tt.fields.projectionName,
RequeueEvery: 0,
},
Client: client,
FailedEventsTable: tt.fields.failedEventsTable,
MaxFailureCount: tt.fields.maxFailureCount,
},
)
mock.ExpectBegin()
for _, expectation := range tt.want.expectations {
expectation(mock)
}
mock.ExpectCommit()
tx, err := client.Begin()
if err != nil {
t.Fatalf("unexpected err in begin: %v", err)
}
idx := h.executeStmts(tx, tt.args.stmts, tt.args.sequences)
if idx != tt.want.idx {
t.Errorf("unexpected index want: %d got %d", tt.want.idx, idx)
}
if err := tx.Commit(); err != nil {
t.Fatalf("unexpected err in commit: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
})
}
}
func TestStatementHandler_executeStmt(t *testing.T) {
type fields struct {
projectionName string
}
type args struct {
stmt handler.Statement
}
type want struct {
expectations []mockExpectation
isErr func(error) bool
}
tests := []struct {
name string
fields fields
args args
want want
}{
{
name: "create savepoint fails",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmt: NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 1,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
expectations: []mockExpectation{
expectSavePointErr(sql.ErrConnDone),
},
},
},
{
name: "execute fails",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmt: NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 1,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrNoRows)
},
expectations: []mockExpectation{
expectSavePoint(),
expectCreateErr("my_projection", []string{"col"}, []string{"$1"}, sql.ErrNoRows),
expectSavePointRollback(),
},
},
},
{
name: "rollback savepoint fails",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmt: NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 1,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
expectations: []mockExpectation{
expectSavePoint(),
expectCreateErr("my_projection", []string{"col"}, []string{"$1"}, sql.ErrNoRows),
expectSavePointRollbackErr(sql.ErrConnDone),
},
},
},
{
name: "no op",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmt: NewNoOpStatement(&testEvent{
aggregateType: "agg",
sequence: 1,
previousSequence: 0,
}),
},
want: want{
isErr: func(err error) bool {
return err == nil
},
expectations: []mockExpectation{},
},
},
{
name: "with op",
fields: fields{
projectionName: "my_projection",
},
args: args{
stmt: NewCreateStatement(
&testEvent{
aggregateType: "agg",
sequence: 1,
previousSequence: 0,
},
[]handler.Column{
{
Name: "col",
Value: "val",
},
}),
},
want: want{
isErr: func(err error) bool {
return err == nil
},
expectations: []mockExpectation{
expectSavePoint(),
expectCreate("my_projection", []string{"col"}, []string{"$1"}),
expectSavePointRelease(),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := &StatementHandler{
ProjectionHandler: &handler.ProjectionHandler{
ProjectionName: tt.fields.projectionName,
},
}
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
mock.ExpectBegin()
for _, expectation := range tt.want.expectations {
expectation(mock)
}
mock.ExpectCommit()
tx, err := client.Begin()
if err != nil {
t.Fatalf("unexpected err in begin: %v", err)
}
err = h.executeStmt(tx, tt.args.stmt)
if !tt.want.isErr(err) {
t.Errorf("unexpected error: %v", err)
}
if err = tx.Commit(); err != nil {
t.Fatalf("unexpected err in begin: %v", err)
}
mock.MatchExpectationsInOrder(true)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
})
}
}
func TestStatementHandler_currentSequence(t *testing.T) {
type fields struct {
sequenceTable string
projectionName string
aggregates []eventstore.AggregateType
}
type args struct {
stmt handler.Statement
}
type want struct {
expectations []mockExpectation
isErr func(error) bool
sequences currentSequences
}
tests := []struct {
name string
fields fields
args args
want want
}{
{
name: "error in query",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
},
args: args{
stmt: handler.Statement{},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
expectations: []mockExpectation{
expectCurrentSequenceErr("my_table", "my_projection", sql.ErrConnDone),
},
},
},
{
name: "no rows",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
stmt: handler.Statement{},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, nil)
},
expectations: []mockExpectation{
expectCurrentSequenceNoRows("my_table", "my_projection"),
},
sequences: currentSequences{
"agg": 0,
},
},
},
{
name: "scan err",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
stmt: handler.Statement{},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrTxDone)
},
expectations: []mockExpectation{
expectCurrentSequenceScanErr("my_table", "my_projection"),
},
sequences: currentSequences{
"agg": 0,
},
},
},
{
name: "found",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
stmt: handler.Statement{},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, nil)
},
expectations: []mockExpectation{
expectCurrentSequence("my_table", "my_projection", 5, "agg"),
},
sequences: currentSequences{
"agg": 5,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := NewStatementHandler(context.Background(), StatementHandlerConfig{
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
ProjectionName: tt.fields.projectionName,
},
SequenceTable: tt.fields.sequenceTable,
})
h.aggregates = tt.fields.aggregates
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
mock.ExpectBegin()
for _, expectation := range tt.want.expectations {
expectation(mock)
}
mock.ExpectCommit()
tx, err := client.Begin()
if err != nil {
t.Fatalf("unexpected err in begin: %v", err)
}
seq, err := h.currentSequences(tx.Query)
if !tt.want.isErr(err) {
t.Errorf("unexpected error: %v", err)
}
if err = tx.Commit(); err != nil {
t.Fatalf("unexpected err in commit: %v", err)
}
mock.MatchExpectationsInOrder(true)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
for _, aggregateType := range tt.fields.aggregates {
if seq[aggregateType] != tt.want.sequences[aggregateType] {
t.Errorf("unexpected sequence in aggregate type %s: want %d got %d", aggregateType, tt.want.sequences[aggregateType], seq[aggregateType])
}
}
})
}
}
func TestStatementHandler_updateCurrentSequence(t *testing.T) {
type fields struct {
sequenceTable string
projectionName string
aggregates []eventstore.AggregateType
}
type args struct {
sequences currentSequences
}
type want struct {
expectations []mockExpectation
isErr func(error) bool
}
tests := []struct {
name string
fields fields
args args
want want
}{
{
name: "update sequence fails",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
sequences: currentSequences{
"agg": 5,
},
},
want: want{
isErr: func(err error) bool {
return errors.Is(err, sql.ErrConnDone)
},
expectations: []mockExpectation{
expectUpdateCurrentSequenceErr("my_table", "my_projection", 5, sql.ErrConnDone, "agg"),
},
},
},
{
name: "update sequence returns no rows",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
sequences: currentSequences{
"agg": 5,
},
},
want: want{
isErr: func(err error) bool {
return errors.As(err, &errSeqNotUpdated)
},
expectations: []mockExpectation{
expectUpdateCurrentSequenceNoRows("my_table", "my_projection", 5, "agg"),
},
},
},
{
name: "correct",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
sequences: currentSequences{
"agg": 5,
},
},
want: want{
isErr: func(err error) bool {
return err == nil
},
expectations: []mockExpectation{
expectUpdateCurrentSequence("my_table", "my_projection", 5, "agg"),
},
},
},
{
name: "multiple sequences",
fields: fields{
sequenceTable: "my_table",
projectionName: "my_projection",
aggregates: []eventstore.AggregateType{"agg"},
},
args: args{
sequences: currentSequences{
"agg": 5,
"agg2": 6,
},
},
want: want{
isErr: func(err error) bool {
return err == nil
},
expectations: []mockExpectation{
expectUpdateTwoCurrentSequence("my_table", "my_projection", currentSequences{
"agg": 5,
"agg2": 6},
),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := NewStatementHandler(context.Background(), StatementHandlerConfig{
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
ProjectionName: tt.fields.projectionName,
},
SequenceTable: tt.fields.sequenceTable,
})
h.aggregates = tt.fields.aggregates
client, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
defer client.Close()
mock.ExpectBegin()
for _, expectation := range tt.want.expectations {
expectation(mock)
}
mock.ExpectCommit()
tx, err := client.Begin()
if err != nil {
t.Fatalf("unexpected error in begin: %v", err)
}
err = h.updateCurrentSequences(tx, tt.args.sequences)
if !tt.want.isErr(err) {
t.Errorf("unexpected error: %v", err)
}
err = tx.Commit()
if err != nil {
t.Fatalf("unexpected error in commit: %v", err)
}
mock.MatchExpectationsInOrder(true)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("expectations not met: %v", err)
}
})
}
}
func testReduce(stmts ...handler.Statement) handler.Reduce {
return func(event eventstore.EventReader) ([]handler.Statement, error) {
return []handler.Statement{
NewNoOpStatement(event),
}, nil
}
}
func testReduceErr(err error) handler.Reduce {
return func(event eventstore.EventReader) ([]handler.Statement, error) {
return nil, err
}
}