feat(domain): Organization APIs with relational tables (#10704)

# Which Problems Are Solved

This PR implements the endpoints listed in #10445 using relational
tables.

- [x] UpdateOrganization
- [x] ListOrganizations
- [x] DeleteOrganization
- [x] DeactivateOrganization
- [x] ActivateOrganization

# How the Problems Are Solved

- **UpdateOrganization:** Implemented logic for `Validate()`,
`Execute()` and `Events()`. On CQRS side, updating an organization emits
events related to the organization and its domains. Separate commanders
have been made for the domain events so that their logic is run
accordingly and we keep separation of concerns. Implementation of the
domains is left to its own ticket.

Because some domain-related data is changed during the organization
update, its original values are saved as pointers inside
[UpdateOrgCommand](https://github.com/zitadel/zitadel/blob/4f87cd8d0cfd75f290aa13c342e4939cecebef73/backend/v3/domain/org_update.go#L20).

These variables will be then used as input for the domain commanders
(that will run after the update organization one).
- **ListOrganizations:** Implemented logic for `Validate()`,
`Execute()`. Utility methods have been made to parse the input queries.
This commander is used both by the v2 and v2beta endpoint, so a
translation layer has been put in place to translate all v2beta requests
into v2. The commander strictly handles v2 request only.

The translation layer between v2beta and v2 APIs was made so to make it
simple to remove it once the v2beta APIs will be removed (a simple
deletion should suffice). A `converter` package [is
shipped](https://github.com/zitadel/zitadel/blob/4f87cd8d0cfd75f290aa13c342e4939cecebef73/backend/v3/api/org/v2/convert/README.md#L5)
as well with instruction for removal. TODOs have been put in place all
over the code to indicate that the related piece of code needs to be
removed once v2beta -> v2 transition is complete.
- **DeleteOrganization:** Implemented logic for `Validate()`,
`Execute()` and `Events()`. The `Events()` method is mostly incomplete
as it requires a lot of data that is currently not retrievable due to
the lack of their relational tables.
- **DeactivateOrganization** and **ActivateOrganization**: Implemented
logic for `Validate()`, `Execute()` and `Events()`. No notable remarks.

👉 All endpoints return matching errors to the CQRS counterpart: this way
allows re-using the integration tests and

👉 All endpoints have been unit-tested through DB mocking

👉 A bunch of TODOs have been put in place for future reworks that are
needed (e.g. `Update()` method on repository should also return a
timestamp)

# Additional Changes

- A test utility method to allow mocking query options have been made.
This was necessary because `database.QueryOption` is a function and the
only comparison possible with functions is `nil` check. So, to mock
this, `database.QueryOption` is converted first to `database.QueryOpts`.
See 2276742adaef1998ea4844e1f0dca2079e45ccfb

- A `BaseCommand` has been created with the idea to collect methods that
are going to be needed by other commands. For the moment, it only offers
a method to convert query text operations from gRPC to `domain` model.
See bb85456dd101282fa76d2e2ad165eed4c8ef61b9

- SQL operations have been reworked to allow for queries using
`ContainsIgnoreCase`, `EndsWithIgnoreCase` and other `IgnoreCase`
operations. This change is pending approval and might be reworked. See
https://github.com/zitadel/zitadel/pull/10704#discussion_r2392886177

# Additional Context

`UpdateOrganization` is partially working because the logic for handling
domain updates is not done (there is only a draft of the commanders to
showcase the call chain). See
https://github.com/zitadel/zitadel/pull/10704#discussion_r2356143178

Permissions are not implemented as they are missing. See
https://github.com/zitadel/zitadel/pull/10771

- Closes: #10445

---------

Co-authored-by: Silvan <[email protected]>
This commit is contained in:
Marco A.
2025-10-21 15:27:38 +02:00
committed by GitHub
co-authored by Silvan
parent 88213d785a
commit f04d873270
67 changed files with 8592 additions and 769 deletions
+49 -2
View File
@@ -1,10 +1,16 @@
package database
import "slices"
import (
"reflect"
"slices"
"go.uber.org/mock/gomock"
)
// Change represents a change to a column in a database table.
// Its written in the SET clause of an UPDATE statement.
type Change interface {
gomock.Matcher
// Write writes the change to the given statement builder.
Write(builder *StatementBuilder)
// IsOnColumn checks if the change is on the given column.
@@ -16,7 +22,26 @@ type change[V Value] struct {
value V
}
var _ Change = (*change[string])(nil)
// Matches implements [gomock.Matcher].
func (c *change[V]) Matches(x any) bool {
toMatch, ok := x.(*change[V])
if !ok {
return false
}
colMatch := c.column.Equals(toMatch.column)
valueMatch := reflect.DeepEqual(c.value, toMatch.value)
return colMatch && valueMatch
}
// String implements [gomock.Matcher].
func (c *change[V]) String() string {
return "database.change"
}
var (
_ Change = (*change[string])(nil)
_ gomock.Matcher = (*change[string])(nil)
)
// NewChange creates a new Change for the given column and value.
// If you want to set a column to NULL, use [NewChangePtr].
@@ -71,4 +96,26 @@ func (m Changes) Write(builder *StatementBuilder) {
}
}
// Matches implements [gomock.Matcher].
func (c Changes) Matches(x any) bool {
toMatch, ok := x.(*Changes)
if !ok {
return false
}
if len(c) != len(*toMatch) {
return false
}
for i := range c {
if !c[i].Matches((*toMatch)[i]) {
return false
}
}
return true
}
// String implements [gomock.Matcher].
func (c Changes) String() string {
return "database.Changes"
}
var _ Change = Changes(nil)
+53
View File
@@ -1,7 +1,25 @@
package database
import "go.uber.org/mock/gomock"
type Columns []Column
// Matches implements [Column].
func (c Columns) Matches(x any) bool {
for _, col := range c {
if !col.Matches(x) {
return false
}
}
return true
}
// String implements [Column].
func (c Columns) String() string {
return "database.Columns"
}
// WriteQualified implements [Column].
// Columns are separated by ", ".
func (c Columns) WriteQualified(builder *StatementBuilder) {
@@ -45,6 +63,7 @@ var _ Column = (Columns)(nil)
// Column represents a column in a database table.
type Column interface {
gomock.Matcher
// WriteQualified writes the column with the table name as prefix.
WriteQualified(builder *StatementBuilder)
// WriteUnqualified writes the column without the table name as prefix.
@@ -58,6 +77,20 @@ type column struct {
name string
}
// Matches implements [Column].
func (c column) Matches(x any) bool {
toMatch, ok := x.(*column)
if !ok {
return false
}
return c.table == toMatch.table && c.name == toMatch.name
}
// String implements [Column].
func (c column) String() string {
return "database.column"
}
func NewColumn(table, name string) Column {
return &column{table: table, name: name}
}
@@ -102,6 +135,26 @@ type functionColumn struct {
col Column
}
// Matches implements [Column].
func (c *functionColumn) Matches(x any) bool {
toMatch, ok := x.(*functionColumn)
if !ok || toMatch.fn != c.fn {
return false
}
if toMatch.col == nil {
return c.col == nil
}
if c.col == nil {
return false
}
return toMatch.col.Matches(c.col)
}
// String implements [Column].
func (c *functionColumn) String() string {
return "database.functionColumn"
}
type function string
const (
+112 -3
View File
@@ -1,11 +1,14 @@
package database
import "go.uber.org/mock/gomock"
// Condition represents a SQL condition.
// Its written after the WHERE keyword in a SQL statement.
type Condition interface {
gomock.Matcher
Write(builder *StatementBuilder)
// IsRestrictingColumn is used to check if the condition filters for a specific column.
// It acts as a save guard database operations that should be specific on the given column.
// It acts as a safeguard database operations that should be specific on the given column.
IsRestrictingColumn(col Column) bool
}
@@ -13,6 +16,28 @@ type and struct {
conditions []Condition
}
// Matches implements [Condition].
func (a *and) Matches(x any) bool {
toMatch, ok := x.(*and)
if !ok {
return false
}
if len(a.conditions) != len(toMatch.conditions) {
return false
}
for i, condition := range a.conditions {
if !condition.Matches(toMatch.conditions[i]) {
return false
}
}
return true
}
// String implements [Condition].
func (a *and) String() string {
return "database.and"
}
// Write implements [Condition].
func (a and) Write(builder *StatementBuilder) {
if len(a.conditions) > 1 {
@@ -48,6 +73,28 @@ type or struct {
conditions []Condition
}
// Matches implements [Condition].
func (o *or) Matches(x any) bool {
toMatch, ok := x.(*or)
if !ok {
return false
}
if len(o.conditions) != len(toMatch.conditions) {
return false
}
for i, condition := range o.conditions {
if !condition.Matches(toMatch.conditions[i]) {
return false
}
}
return true
}
// String implements [Condition].
func (o *or) String() string {
return "database.or"
}
// Write implements [Condition].
func (o or) Write(builder *StatementBuilder) {
if len(o.conditions) > 1 {
@@ -84,6 +131,20 @@ type isNull struct {
column Column
}
// Matches implements [Condition].
func (i *isNull) Matches(x any) bool {
toMatch, ok := x.(*isNull)
if !ok {
return false
}
return i.column.Matches(toMatch.column)
}
// String implements [Condition].
func (i *isNull) String() string {
return "database.isNull"
}
// Write implements [Condition].
func (i isNull) Write(builder *StatementBuilder) {
i.column.WriteQualified(builder)
@@ -107,6 +168,20 @@ type isNotNull struct {
column Column
}
// Matches implements [Condition].
func (i *isNotNull) Matches(x any) bool {
toMatch, ok := x.(*isNotNull)
if !ok {
return false
}
return i.column.Matches(toMatch.column)
}
// String implements [Condition].
func (i *isNotNull) String() string {
return "database.isNotNull"
}
// Write implements [Condition].
func (i isNotNull) Write(builder *StatementBuilder) {
i.column.WriteQualified(builder)
@@ -131,9 +206,32 @@ type valueCondition struct {
col Column
}
// Matches implements [Condition].
func (c valueCondition) Matches(x any) bool {
toMatch, ok := x.(valueCondition)
if !ok {
return false
}
if !c.col.Matches(toMatch.col) {
return false
}
var expectedStatement, inputStatement StatementBuilder
c.write(&expectedStatement)
toMatch.write(&inputStatement)
return expectedStatement.String() == inputStatement.String()
}
// String implements [Condition].
func (c valueCondition) String() string {
return "database.valueCondition"
}
// NewTextCondition creates a condition that compares a text column with a value.
// If you want to use ignore case operations, consider using [NewTextIgnoreCaseCondition].
// if `op.IsIgnoreCaseOperation()` is true the response is created using [NewTextIgnoreCaseCondition]
func NewTextCondition[T Text](col Column, op TextOperation, value T) Condition {
if op.IsIgnoreCaseOperation() {
return NewTextIgnoreCaseCondition(col, op.Value(), value)
}
return valueCondition{
col: col,
write: func(builder *StatementBuilder) {
@@ -207,12 +305,23 @@ func (i valueCondition) IsRestrictingColumn(col Column) bool {
var _ Condition = (*valueCondition)(nil)
// existsCondition is a helper to write an EXISTS (SELECT 1 FROM <table> WHERE <condition>) clause.
// It implements Condition so it can be composed with other conditions using And/Or.
// It implements [Condition] so it can be composed with other conditions using And/Or.
type existsCondition struct {
table string
condition Condition
}
// Matches implements [Condition].
func (e *existsCondition) Matches(x any) bool {
// Unimplemented
return false
}
// String implements [Condition].
func (e *existsCondition) String() string {
return "unimplemented"
}
// Exists creates a condition that checks for the existence of rows in a subquery.
func Exists(table string, condition Condition) Condition {
return &existsCondition{
@@ -99,6 +99,14 @@ func TestWrite(t *testing.T) {
args: []any{"some text"},
},
},
{
name: "text condition with ignore case",
cond: NewTextCondition(NewColumn("table", "column1"), TextOperationEqualIgnoreCase, "some text"),
want: want{
stmt: "LOWER(table.column1) = LOWER($1)",
args: []any{"some text"},
},
},
{
name: "text ignore case condition",
cond: NewTextIgnoreCaseCondition(NewColumn("table", "column1"), TextOperationNotEqual, "some TEXT"),
@@ -0,0 +1,15 @@
package dbmock
import (
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
// QueryOptions converts database.QueryOption to *database.QueryOpts which
// can then be used as a gomock Matcher.
func QueryOptions(optsFunc database.QueryOption) *database.QueryOpts {
opts := &database.QueryOpts{}
optsFunc(opts)
return opts
}
@@ -0,0 +1,46 @@
package noopdb
import (
"context"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type Client struct{}
// Ping implements [database.Client].
func (n *Client) Ping(ctx context.Context) error {
return nil
}
// Begin implements [database.Client].
func (n *Client) Begin(ctx context.Context, opts *database.TransactionOptions) (database.Transaction, error) {
return new(Transaction), nil
}
// Exec implements [database.Client].
func (n *Client) Exec(ctx context.Context, stmt string, args ...any) (int64, error) {
return 0, nil
}
// Migrate implements [database.Client].
func (n *Client) Migrate(ctx context.Context) error {
return nil
}
// Query implements [database.Client].
func (n *Client) Query(ctx context.Context, stmt string, args ...any) (database.Rows, error) {
return new(rows), nil
}
// QueryRow implements [database.Client].
func (n *Client) QueryRow(ctx context.Context, stmt string, args ...any) database.Row {
return new(row)
}
// Release implements [database.Client].
func (n *Client) Release(ctx context.Context) error {
return nil
}
var _ database.Connection = (*Client)(nil)
@@ -0,0 +1,51 @@
package noopdb
import (
"context"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type Pool struct{}
// Ping implements [database.Pool].
func (n *Pool) Ping(ctx context.Context) error {
return nil
}
// Acquire implements [database.Pool].
func (n *Pool) Acquire(ctx context.Context) (database.Connection, error) {
return new(Client), nil
}
// Begin implements [database.Pool].
func (n *Pool) Begin(ctx context.Context, opts *database.TransactionOptions) (database.Transaction, error) {
return new(Transaction), nil
}
// Close implements [database.Pool].
func (n *Pool) Close(ctx context.Context) error {
return nil
}
// Exec implements [database.Pool].
func (n *Pool) Exec(ctx context.Context, stmt string, args ...any) (int64, error) {
return 0, nil
}
// Migrate implements [database.Pool].
func (n *Pool) Migrate(ctx context.Context) error {
return nil
}
// Query implements [database.Pool].
func (n *Pool) Query(ctx context.Context, stmt string, args ...any) (database.Rows, error) {
return new(rows), nil
}
// QueryRow implements [database.Pool].
func (n *Pool) QueryRow(ctx context.Context, stmt string, args ...any) database.Row {
return new(row)
}
var _ database.Pool = (*Pool)(nil)
@@ -0,0 +1,36 @@
package noopdb
import "github.com/zitadel/zitadel/backend/v3/storage/database"
type rows struct{}
// Close implements [database.Rows].
func (r *rows) Close() error {
return nil
}
// Err implements [database.Rows].
func (r *rows) Err() error {
return nil
}
// Next implements [database.Rows].
func (r *rows) Next() bool {
return false
}
// Scan implements [database.Rows].
func (r *rows) Scan(dest ...any) error {
return nil
}
var _ database.Rows = (*rows)(nil)
type row struct{}
// Scan implements database.Row.
func (r *row) Scan(dest ...any) error {
return nil
}
var _ database.Row = (*row)(nil)
@@ -0,0 +1,46 @@
package noopdb
import (
"context"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
type Transaction struct{}
// Begin implements [database.Transaction].
func (n *Transaction) Begin(ctx context.Context) (database.Transaction, error) {
return new(Transaction), nil
}
// Commit implements [database.Transaction].
func (n *Transaction) Commit(ctx context.Context) error {
return nil
}
// End implements [database.Transaction].
func (n *Transaction) End(ctx context.Context, err error) error {
return err
}
// Exec implements [database.Transaction].
func (n *Transaction) Exec(ctx context.Context, stmt string, args ...any) (int64, error) {
return 0, nil
}
// Query implements [database.Transaction].
func (n *Transaction) Query(ctx context.Context, stmt string, args ...any) (database.Rows, error) {
return new(rows), nil
}
// QueryRow implements [database.Transaction].
func (n *Transaction) QueryRow(ctx context.Context, stmt string, args ...any) database.Row {
return new(row)
}
// Rollback implements [database.Transaction].
func (n *Transaction) Rollback(ctx context.Context) error {
return nil
}
var _ database.Transaction = (*Transaction)(nil)
+59 -2
View File
@@ -1,6 +1,7 @@
package database
import (
"fmt"
"time"
"golang.org/x/exp/constraints"
@@ -52,12 +53,68 @@ const (
TextOperationNotEqual // <>
// TextOperationStartsWith checks if the first string starts with the second.
TextOperationStartsWith // LIKE
// TextOperationContains checks if the first string contains the second
TextOperationContains // LIKE
// TextOperationEndsWith checks if the first string ends with the second.
TextOperationEndsWith // LIKE
// TextOperationContainsIgnoreCase checks if the first string contains the second ignoring case
TextOperationContainsIgnoreCase // LIKE
// TextOperationEndsWith checks if the first string ends with the second ignoring case
TextOperationEndsWithIgnoreCase // LIKE
// TextOperationStartsWith checks if the first string starts with the second ignoring case
TextOperationStartsWithIgnoreCase // LIKE
// TextOperationEqualIgnoreCase compares two strings for equality ignoring case
TextOperationEqualIgnoreCase // =
// TextOperationNotEqualIgnoreCase compares two strings for inequality ignoring case
TextOperationNotEqualIgnoreCase // <>
)
func (op TextOperation) IsIgnoreCaseOperation() bool {
return op == TextOperationContainsIgnoreCase ||
op == TextOperationEndsWithIgnoreCase ||
op == TextOperationStartsWithIgnoreCase ||
op == TextOperationEqualIgnoreCase ||
op == TextOperationNotEqualIgnoreCase
}
func (op TextOperation) Value() TextOperation {
switch op {
case TextOperationStartsWith, TextOperationContains, TextOperationEndsWith, TextOperationEqual, TextOperationNotEqual:
return op
case TextOperationContainsIgnoreCase:
return TextOperationContains
case TextOperationEndsWithIgnoreCase:
return TextOperationEndsWith
case TextOperationStartsWithIgnoreCase:
return TextOperationStartsWith
case TextOperationEqualIgnoreCase:
return TextOperationEqual
case TextOperationNotEqualIgnoreCase:
return TextOperationNotEqual
default:
panic(fmt.Sprintf("unexpected database.TextOperation: %#v", op))
}
}
func writeTextOperation[T Text](builder *StatementBuilder, col Column, op TextOperation, value any) {
writeOperation[T](builder, col, op.String(), value)
if op == TextOperationStartsWith {
switch op {
case TextOperationContains:
writeOperation[T](builder, col, op.String()+" '%' ||", value)
builder.WriteString(" || '%'")
case TextOperationEndsWith:
writeOperation[T](builder, col, op.String()+" '%' ||", value)
case TextOperationEqual, TextOperationNotEqual:
writeOperation[T](builder, col, op.String(), value)
case TextOperationStartsWith:
writeOperation[T](builder, col, op.String(), value)
builder.WriteString(" || '%'")
case TextOperationContainsIgnoreCase, TextOperationEndsWithIgnoreCase, TextOperationStartsWithIgnoreCase, TextOperationEqualIgnoreCase, TextOperationNotEqualIgnoreCase:
fallthrough
default:
panic(fmt.Sprintf("unexpected database.TextOperation: %#v", op))
}
}
+30 -10
View File
@@ -94,11 +94,11 @@ func (i NumberOperation) IsANumberOperation() bool {
return false
}
const _TextOperationName = "=<>LIKE"
const _TextOperationName = "=<>LIKELIKELIKELIKELIKELIKE"
var _TextOperationIndex = [...]uint8{0, 1, 3, 7}
var _TextOperationIndex = [...]uint8{0, 1, 3, 7, 11, 15, 19, 23, 27}
const _TextOperationLowerName = "=<>like"
const _TextOperationLowerName = "=<>likelikelikelikelikelike"
func (i TextOperation) String() string {
i -= 1
@@ -115,23 +115,43 @@ func _TextOperationNoOp() {
_ = x[TextOperationEqual-(1)]
_ = x[TextOperationNotEqual-(2)]
_ = x[TextOperationStartsWith-(3)]
_ = x[TextOperationContains-(4)]
_ = x[TextOperationEndsWith-(5)]
_ = x[TextOperationContainsIgnoreCase-(6)]
_ = x[TextOperationEndsWithIgnoreCase-(7)]
_ = x[TextOperationStartsWithIgnoreCase-(8)]
}
var _TextOperationValues = []TextOperation{TextOperationEqual, TextOperationNotEqual, TextOperationStartsWith}
var _TextOperationValues = []TextOperation{TextOperationEqual, TextOperationNotEqual, TextOperationStartsWith, TextOperationContains, TextOperationEndsWith, TextOperationContainsIgnoreCase, TextOperationEndsWithIgnoreCase, TextOperationStartsWithIgnoreCase}
var _TextOperationNameToValueMap = map[string]TextOperation{
_TextOperationName[0:1]: TextOperationEqual,
_TextOperationLowerName[0:1]: TextOperationEqual,
_TextOperationName[1:3]: TextOperationNotEqual,
_TextOperationLowerName[1:3]: TextOperationNotEqual,
_TextOperationName[3:7]: TextOperationStartsWith,
_TextOperationLowerName[3:7]: TextOperationStartsWith,
_TextOperationName[0:1]: TextOperationEqual,
_TextOperationLowerName[0:1]: TextOperationEqual,
_TextOperationName[1:3]: TextOperationNotEqual,
_TextOperationLowerName[1:3]: TextOperationNotEqual,
_TextOperationName[3:7]: TextOperationStartsWith,
_TextOperationLowerName[3:7]: TextOperationStartsWith,
_TextOperationName[7:11]: TextOperationContains,
_TextOperationLowerName[7:11]: TextOperationContains,
_TextOperationName[11:15]: TextOperationEndsWith,
_TextOperationLowerName[11:15]: TextOperationEndsWith,
_TextOperationName[15:19]: TextOperationContainsIgnoreCase,
_TextOperationLowerName[15:19]: TextOperationContainsIgnoreCase,
_TextOperationName[19:23]: TextOperationEndsWithIgnoreCase,
_TextOperationLowerName[19:23]: TextOperationEndsWithIgnoreCase,
_TextOperationName[23:27]: TextOperationStartsWithIgnoreCase,
_TextOperationLowerName[23:27]: TextOperationStartsWithIgnoreCase,
}
var _TextOperationNames = []string{
_TextOperationName[0:1],
_TextOperationName[1:3],
_TextOperationName[3:7],
_TextOperationName[7:11],
_TextOperationName[11:15],
_TextOperationName[15:19],
_TextOperationName[19:23],
_TextOperationName[23:27],
}
// TextOperationString retrieves an enum value from the enum constants string name.
@@ -77,6 +77,26 @@ func Test_writeOperation(t *testing.T) {
args: []any{"value"},
},
},
{
name: "text ends with",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, NewColumn("table", "column"), TextOperationEndsWith, "value")
},
want: want{
stmt: "table.column LIKE '%' || $1",
args: []any{"value"},
},
},
{
name: "text contains",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, NewColumn("table", "column"), TextOperationContains, "value")
},
want: want{
stmt: "table.column LIKE '%' || $1 || '%'",
args: []any{"value"},
},
},
{
name: "text equal with wrapped value",
write: func(builder *StatementBuilder) {
@@ -107,6 +127,27 @@ func Test_writeOperation(t *testing.T) {
args: []any{"value"},
},
},
{
name: "text ends with with wrapped value",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, LowerColumn(NewColumn("table", "column")), TextOperationEndsWith, LowerValue("value"))
},
want: want{
stmt: "LOWER(table.column) LIKE '%' || LOWER($1)",
args: []any{"value"},
},
},
{
name: "text contains with wrapped value",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, LowerColumn(NewColumn("table", "column")), TextOperationContains, LowerValue("value"))
},
want: want{
stmt: "LOWER(table.column) LIKE '%' || LOWER($1) || '%'",
args: []any{"value"},
},
},
{
name: "number equal",
write: func(builder *StatementBuilder) {
@@ -167,6 +208,7 @@ func Test_writeOperation(t *testing.T) {
args: []any{123},
},
},
{
name: "boolean is true",
write: func(builder *StatementBuilder) {
@@ -187,6 +229,7 @@ func Test_writeOperation(t *testing.T) {
args: []any{false},
},
},
{
name: "bytes equal",
write: func(builder *StatementBuilder) {
@@ -242,3 +285,137 @@ func Test_writeOperation(t *testing.T) {
})
}
}
func TestTextOperation_Value(t *testing.T) {
t.Parallel()
tests := []struct {
name string
op TextOperation
want TextOperation
}{
{
name: "TextOperationStartsWith returns self",
op: TextOperationStartsWith,
want: TextOperationStartsWith,
},
{
name: "TextOperationContains returns self",
op: TextOperationContains,
want: TextOperationContains,
},
{
name: "TextOperationEndsWith returns self",
op: TextOperationEndsWith,
want: TextOperationEndsWith,
},
{
name: "TextOperationEqual returns self",
op: TextOperationEqual,
want: TextOperationEqual,
},
{
name: "TextOperationNotEqual returns self",
op: TextOperationNotEqual,
want: TextOperationNotEqual,
},
{
name: "TextOperationContainsIgnoreCase returns Contains",
op: TextOperationContainsIgnoreCase,
want: TextOperationContains,
},
{
name: "TextOperationEndsWithIgnoreCase returns EndsWith",
op: TextOperationEndsWithIgnoreCase,
want: TextOperationEndsWith,
},
{
name: "TextOperationStartsWithIgnoreCase returns StartsWith",
op: TextOperationStartsWithIgnoreCase,
want: TextOperationStartsWith,
},
{
name: "TextOperationEqualIgnoreCase returns Equal",
op: TextOperationEqualIgnoreCase,
want: TextOperationEqual,
},
{
name: "TextOperationNotEqualIgnoreCase returns NotEqual",
op: TextOperationNotEqualIgnoreCase,
want: TextOperationNotEqual,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := tt.op.Value()
assert.Equal(t, tt.want, got)
})
}
}
func TestTextOperation_IsIgnoreCaseOperation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
op TextOperation
want bool
}{
{
name: "TextOperationContainsIgnoreCase returns true",
op: TextOperationContainsIgnoreCase,
want: true,
},
{
name: "TextOperationEndsWithIgnoreCase returns true",
op: TextOperationEndsWithIgnoreCase,
want: true,
},
{
name: "TextOperationStartsWithIgnoreCase returns true",
op: TextOperationStartsWithIgnoreCase,
want: true,
},
{
name: "TextOperationEqualIgnoreCase returns true",
op: TextOperationEqualIgnoreCase,
want: true,
},
{
name: "TextOperationNotEqualIgnoreCase returns true",
op: TextOperationNotEqualIgnoreCase,
want: true,
},
{
name: "TextOperationContains returns false",
op: TextOperationContains,
want: false,
},
{
name: "TextOperationEndsWith returns false",
op: TextOperationEndsWith,
want: false,
},
{
name: "TextOperationStartsWith returns false",
op: TextOperationStartsWith,
want: false,
},
{
name: "TextOperationEqual returns false",
op: TextOperationEqual,
want: false,
},
{
name: "TextOperationNotEqual returns false",
op: TextOperationNotEqual,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := tt.op.IsIgnoreCaseOperation()
assert.Equal(t, tt.want, got)
})
}
}
+65
View File
@@ -1,5 +1,12 @@
package database
import (
"fmt"
"reflect"
"go.uber.org/mock/gomock"
)
type QueryOption func(opts *QueryOpts)
// WithCondition sets the condition for the query.
@@ -113,6 +120,64 @@ type QueryOpts struct {
Permission string
}
// Matches implements [gomock.Matcher].
func (q *QueryOpts) Matches(x any) bool {
// first check if the x is a [QueryOpt]
inputOpts, ok := x.(*QueryOpts)
if !ok {
// second possibility is a [QueryOption]
optFunc, ok := x.(QueryOption)
if !ok {
return false
}
// QueryOption is a function that takes a *QueryOpts in input and fills it with its data.
// QueryOption data is not accessible because it's a function, so we exploit this "hack"
// to read the data.
inputOpts = new(QueryOpts)
optFunc(inputOpts)
}
// inputOpts now contains the actual data but made of other interfaces and functions/decorator.
// Doing a reflect.DeepEqual() will fail because you will end up into comparing functions
// which is not possible (comparison is successful only if both functions are nil).
// So we exploit the Write() method of QueryOpts to fill up the StatementBuilders:
// these objects are basically string builders, so we can leverage their String()
// method (implementing Stringer interface) to make an easy and safe comparison.
inputBuilder, expectedBuilder := &StatementBuilder{}, &StatementBuilder{}
inputOpts.Write(inputBuilder)
q.Write(expectedBuilder)
if len(inputBuilder.Args()) != len(expectedBuilder.Args()) {
return false
}
for i := range inputBuilder.Args() {
argIn, argExp := inputBuilder.Args()[i], expectedBuilder.Args()[i]
isEqual := reflect.DeepEqual(argIn, argExp)
if !isEqual {
return false
}
}
return inputBuilder.String() == expectedBuilder.String()
}
// String implements [gomock.Matcher].
func (q *QueryOpts) String() string {
return fmt.Sprintf("QueryOpts: {%v,%v,%v,%v,%v,%v,%v}\n",
q.Condition,
q.OrderBy,
q.Ordering,
q.Limit,
q.Offset,
q.GroupBy,
q.Joins,
)
}
var _ (gomock.Matcher) = (*QueryOpts)(nil)
func (opts *QueryOpts) Write(builder *StatementBuilder) {
opts.WriteLeftJoins(builder)
opts.WriteCondition(builder)