Files
zitadel/backend/v3/storage/database/operators_test.go

245 lines
6.4 KiB
Go
Raw Normal View History

refactor: database interaction and error handling (#10762) This pull request introduces a significant refactoring of the database interaction layer, focusing on improving explicitness, transactional control, and error handling. The core change is the removal of the stateful `QueryExecutor` from repository instances. Instead, it is now passed as an argument to each method that interacts with the database. This change makes transaction management more explicit and flexible, as the same repository instance can be used with a database pool or a specific transaction without needing to be re-instantiated. ### Key Changes - **Explicit `QueryExecutor` Passing:** - All repository methods (`Get`, `List`, `Create`, `Update`, `Delete`, etc.) in `InstanceRepository`, `OrganizationRepository`, `UserRepository`, and their sub-repositories now require a `database.QueryExecutor` (e.g., a `*pgxpool.Pool` or `pgx.Tx`) as the first argument. - Repository constructors no longer accept a `QueryExecutor`. For example, `repository.InstanceRepository(pool)` is now `repository.InstanceRepository()`. - **Enhanced Error Handling:** - A new `database.MissingConditionError` is introduced to enforce required query conditions, such as ensuring an `instance_id` is always present in `UPDATE` and `DELETE` operations. - The database error wrapper in the `postgres` package now correctly identifies and wraps `pgx.ErrTooManyRows` and similar errors from the `scany` library into a `database.MultipleRowsFoundError`. - **Improved Database Conditions:** - The `database.Condition` interface now includes a `ContainsColumn(Column) bool` method. This allows for runtime checks to ensure that critical filters (like `instance_id`) are included in a query, preventing accidental cross-tenant data modification. - A new `database.Exists()` condition has been added to support `EXISTS` subqueries, enabling more complex filtering logic, such as finding an organization that has a specific domain. - **Repository and Interface Refactoring:** - The method for loading related entities (e.g., domains for an organization) has been changed from a boolean flag (`Domains(true)`) to a more explicit, chainable method (`LoadDomains()`). This returns a new repository instance configured to load the sub-resource, promoting immutability. - The custom `OrgIdentifierCondition` has been removed in favor of using the standard `database.Condition` interface, simplifying the API. - **Code Cleanup and Test Updates:** - Unnecessary struct embeddings and metadata have been removed. - All integration and repository tests have been updated to reflect the new method signatures, passing the database pool or transaction object explicitly. - New tests have been added to cover the new `ExistsDomain` functionality and other enhancements. These changes make the data access layer more robust, predictable, and easier to work with, especially in the context of database transactions.
2025-09-24 12:12:31 +02:00
package database
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_writeOperation(t *testing.T) {
type want struct {
shouldPanic bool
stmt string
args []any
}
tests := []struct {
name string
write func(builder *StatementBuilder)
// col Column
// op string
// value any
want want
}{
{
name: "unsupported operation panics",
write: func(builder *StatementBuilder) {
writeOperation[string](builder, NewColumn("table", "column"), "", "value")
},
want: want{
shouldPanic: true,
},
},
{
name: "unsupported value type panics",
write: func(builder *StatementBuilder) {
writeOperation[string](builder, NewColumn("table", "column"), " = ", struct{}{})
},
want: want{
shouldPanic: true,
},
},
{
name: "unsupported wrapped value type panics",
write: func(builder *StatementBuilder) {
writeOperation[string](builder, NewColumn("table", "column"), " = ", SHA256Value(123))
},
want: want{
shouldPanic: true,
},
},
{
name: "text equal",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, NewColumn("table", "column"), TextOperationEqual, "value")
},
want: want{
stmt: "table.column = $1",
args: []any{"value"},
},
},
{
name: "text not equal",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, NewColumn("table", "column"), TextOperationNotEqual, "value")
},
want: want{
stmt: "table.column <> $1",
args: []any{"value"},
},
},
{
name: "text starts with",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, NewColumn("table", "column"), TextOperationStartsWith, "value")
},
want: want{
stmt: "table.column LIKE $1 || '%'",
args: []any{"value"},
},
},
{
name: "text equal with wrapped value",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, LowerColumn(NewColumn("table", "column")), TextOperationEqual, LowerValue("value"))
},
want: want{
stmt: "LOWER(table.column) = LOWER($1)",
args: []any{"value"},
},
},
{
name: "text not equal with wrapped value",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, LowerColumn(NewColumn("table", "column")), TextOperationNotEqual, LowerValue("value"))
},
want: want{
stmt: "LOWER(table.column) <> LOWER($1)",
args: []any{"value"},
},
},
{
name: "text starts with with wrapped value",
write: func(builder *StatementBuilder) {
writeTextOperation[string](builder, LowerColumn(NewColumn("table", "column")), TextOperationStartsWith, LowerValue("value"))
},
want: want{
stmt: "LOWER(table.column) LIKE LOWER($1) || '%'",
args: []any{"value"},
},
},
{
name: "number equal",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationEqual, 123)
},
want: want{
stmt: "table.column = $1",
args: []any{123},
},
},
{
name: "number not equal",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationNotEqual, 123)
},
want: want{
stmt: "table.column <> $1",
args: []any{123},
},
},
{
name: "number less than",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationLessThan, 123)
},
want: want{
stmt: "table.column < $1",
args: []any{123},
},
},
{
name: "number less than or equal",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationAtLeast, 123)
},
want: want{
stmt: "table.column <= $1",
args: []any{123},
},
},
{
name: "number greater than",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationGreaterThan, 123)
},
want: want{
stmt: "table.column > $1",
args: []any{123},
},
},
{
name: "number greater than or equal",
write: func(builder *StatementBuilder) {
writeNumberOperation[int](builder, NewColumn("table", "column"), NumberOperationAtMost, 123)
},
want: want{
stmt: "table.column >= $1",
args: []any{123},
},
},
{
name: "boolean is true",
write: func(builder *StatementBuilder) {
writeBooleanOperation[bool](builder, NewColumn("table", "column"), true)
},
want: want{
stmt: "table.column = $1",
args: []any{true},
},
},
{
name: "boolean is false",
write: func(builder *StatementBuilder) {
writeBooleanOperation[bool](builder, NewColumn("table", "column"), false)
},
want: want{
stmt: "table.column = $1",
args: []any{false},
},
},
{
name: "bytes equal",
write: func(builder *StatementBuilder) {
writeBytesOperation[[]byte](builder, NewColumn("table", "column"), BytesOperationEqual, []byte{0x01, 0x02, 0x03})
},
want: want{
stmt: "table.column = $1",
args: []any{[]byte{0x01, 0x02, 0x03}},
},
},
{
name: "bytes not equal",
write: func(builder *StatementBuilder) {
writeBytesOperation[[]byte](builder, NewColumn("table", "column"), BytesOperationNotEqual, []byte{0x01, 0x02, 0x03})
},
want: want{
stmt: "table.column <> $1",
args: []any{[]byte{0x01, 0x02, 0x03}},
},
},
{
name: "bytes equal with wrapped value",
write: func(builder *StatementBuilder) {
writeBytesOperation[[]byte](builder, SHA256Column(NewColumn("table", "column")), BytesOperationEqual, SHA256Value([]byte{0x01, 0x02, 0x03}))
},
want: want{
stmt: "SHA256(table.column) = SHA256($1)",
args: []any{[]byte{0x01, 0x02, 0x03}},
},
},
{
name: "bytes not equal with wrapped value",
write: func(builder *StatementBuilder) {
writeBytesOperation[[]byte](builder, SHA256Column(NewColumn("table", "column")), BytesOperationNotEqual, SHA256Value([]byte{0x01, 0x02, 0x03}))
},
want: want{
stmt: "SHA256(table.column) <> SHA256($1)",
args: []any{[]byte{0x01, 0x02, 0x03}},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
r := recover()
assert.Equal(t, tt.want.shouldPanic, r != nil)
}()
var builder StatementBuilder
tt.write(&builder)
assert.Equal(t, tt.want.stmt, builder.String())
assert.Equal(t, tt.want.args, builder.Args())
})
}
}