mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-23 13:28:45 +00:00
feat(backend): state persisted objects (#9870)
This PR initiates the rework of Zitadel's backend to state-persisted objects. This change is a step towards a more scalable and maintainable architecture. ## Changes * **New `/backend/v3` package**: A new package structure has been introduced to house the reworked backend logic. This includes: * `domain`: Contains the core business logic, commands, and repository interfaces. * `storage`: Implements the repository interfaces for database interactions with new transactional tables. * `telemetry`: Provides logging and tracing capabilities. * **Transactional Tables**: New database tables have been defined for `instances`, `instance_domains`, `organizations`, and `org_domains`. * **Projections**: New projections have been created to populate the new relational tables from the existing event store, ensuring data consistency during the migration. * **Repositories**: New repositories provide an abstraction layer for accessing and manipulating the data in the new tables. * **Setup**: A new setup step for `TransactionalTables` has been added to manage the database migrations for the new tables. This PR lays the foundation for future work to fully transition to state-persisted objects for these components, which will improve performance and simplify data access patterns. This PR initiates the rework of ZITADEL's backend to state-persisted objects. This is a foundational step towards a new architecture that will improve performance and maintainability. The following objects are migrated from event-sourced aggregates to state-persisted objects: * Instances * incl. Domains * Orgs * incl. Domains The structure of the new backend implementation follows the software architecture defined in this [wiki page](https://github.com/zitadel/zitadel/wiki/Software-Architecturel). This PR includes: * The initial implementation of the new transactional repositories for the objects listed above. * Projections to populate the new relational tables from the existing event store. * Adjustments to the build and test process to accommodate the new backend structure. This is a work in progress and further changes will be made to complete the migration. --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Iraq Jaber <[email protected]> Co-authored-by: Iraq <[email protected]> Co-authored-by: Tim Möhlmann <[email protected]>
This commit is contained in:
co-authored by
Copilot
Iraq Jaber
Iraq
Tim Möhlmann
parent
8cc79c1376
commit
61cab8878e
@@ -0,0 +1,5 @@
|
||||
// Package implements the repositories defined in the domain package.
|
||||
// The repositories are used by the domain package to access the database.
|
||||
// the inheritance.sql file is me over-engineering table inheritance.
|
||||
// I would create a user table which is inherited by human_user and machine_user and the same for objects like idps.
|
||||
package repository
|
||||
@@ -0,0 +1,135 @@
|
||||
CREATE TABLE objects (
|
||||
id SERIAL PRIMARY KEY,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
deleted_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TABLE instances(
|
||||
name VARCHAR(50) NOT NULL
|
||||
, PRIMARY KEY (id)
|
||||
) INHERITS (objects);
|
||||
|
||||
CREATE TRIGGER set_updated_at
|
||||
BEFORE UPDATE
|
||||
ON instances
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TABLE instance_objects(
|
||||
instance_id INT NOT NULL
|
||||
, PRIMARY KEY (instance_id, id)
|
||||
-- as foreign keys are not inherited we need to define them on the child tables
|
||||
--, CONSTRAINT fk_instance FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (objects);
|
||||
|
||||
CREATE TABLE orgs(
|
||||
name VARCHAR(50) NOT NULL
|
||||
, PRIMARY KEY (instance_id, id)
|
||||
, CONSTRAINT fk_instance FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (instance_objects);
|
||||
|
||||
CREATE TRIGGER set_updated_at
|
||||
BEFORE UPDATE
|
||||
ON orgs
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TABLE org_objects(
|
||||
org_id INT NOT NULL
|
||||
, PRIMARY KEY (instance_id, org_id, id)
|
||||
-- as foreign keys are not inherited we need to define them on the child tables
|
||||
-- CONSTRAINT fk_org FOREIGN KEY (instance_id, org_id) REFERENCES orgs(instance_id, id),
|
||||
-- CONSTRAINT fk_instance FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (instance_objects);
|
||||
|
||||
CREATE TABLE users (
|
||||
username VARCHAR(50) NOT NULL
|
||||
, PRIMARY KEY (instance_id, org_id, id)
|
||||
-- as foreign keys are not inherited we need to define them on the child tables
|
||||
-- , CONSTRAINT fk_org FOREIGN KEY (instance_id, org_id) REFERENCES orgs(instance_id, id)
|
||||
-- , CONSTRAINT fk_instances FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (org_objects);
|
||||
|
||||
CREATE INDEX idx_users_username ON users(username);
|
||||
|
||||
CREATE TRIGGER set_updated_at
|
||||
BEFORE UPDATE
|
||||
ON users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TABLE human_users(
|
||||
first_name VARCHAR(50)
|
||||
, last_name VARCHAR(50)
|
||||
, PRIMARY KEY (instance_id, org_id, id)
|
||||
-- CONSTRAINT fk_user FOREIGN KEY (instance_id, org_id, id) REFERENCES users(instance_id, org_id, id),
|
||||
, CONSTRAINT fk_org FOREIGN KEY (instance_id, org_id) REFERENCES orgs(instance_id, id)
|
||||
, CONSTRAINT fk_instances FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (users);
|
||||
|
||||
CREATE INDEX idx_human_users_username ON human_users(username);
|
||||
|
||||
CREATE TRIGGER set_updated_at
|
||||
BEFORE UPDATE
|
||||
ON human_users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TABLE machine_users(
|
||||
description VARCHAR(50)
|
||||
, PRIMARY KEY (instance_id, org_id, id)
|
||||
-- , CONSTRAINT fk_user FOREIGN KEY (instance_id, org_id, id) REFERENCES users(instance_id, org_id, id)
|
||||
, CONSTRAINT fk_org FOREIGN KEY (instance_id, org_id) REFERENCES orgs(instance_id, id)
|
||||
, CONSTRAINT fk_instances FOREIGN KEY (instance_id) REFERENCES instances(id)
|
||||
) INHERITS (users);
|
||||
|
||||
CREATE INDEX idx_machine_users_username ON machine_users(username);
|
||||
|
||||
CREATE TRIGGER set_updated_at
|
||||
BEFORE UPDATE
|
||||
ON machine_users
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE VIEW users_view AS (
|
||||
SELECT
|
||||
id
|
||||
, created_at
|
||||
, updated_at
|
||||
, deleted_at
|
||||
, instance_id
|
||||
, org_id
|
||||
, username
|
||||
, tableoid::regclass::TEXT AS type
|
||||
, first_name
|
||||
, last_name
|
||||
, NULL AS description
|
||||
FROM
|
||||
human_users
|
||||
|
||||
UNION
|
||||
|
||||
SELECT
|
||||
id
|
||||
, created_at
|
||||
, updated_at
|
||||
, deleted_at
|
||||
, instance_id
|
||||
, org_id
|
||||
, username
|
||||
, tableoid::regclass::TEXT AS type
|
||||
, NULL AS first_name
|
||||
, NULL AS last_name
|
||||
, description
|
||||
FROM
|
||||
machine_users
|
||||
);
|
||||
@@ -0,0 +1,306 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
var _ domain.InstanceRepository = (*instance)(nil)
|
||||
|
||||
type instance struct {
|
||||
repository
|
||||
shouldLoadDomains bool
|
||||
domainRepo *instanceDomain
|
||||
}
|
||||
|
||||
func InstanceRepository(client database.QueryExecutor) domain.InstanceRepository {
|
||||
return &instance{
|
||||
repository: repository{
|
||||
client: client,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
const (
|
||||
queryInstanceStmt = `SELECT instances.id, instances.name, instances.default_org_id, instances.iam_project_id, instances.console_client_id, instances.console_app_id, instances.default_language, instances.created_at, instances.updated_at` +
|
||||
` , CASE WHEN count(instance_domains.domain) > 0 THEN jsonb_agg(json_build_object('domain', instance_domains.domain, 'isPrimary', instance_domains.is_primary, 'isGenerated', instance_domains.is_generated, 'createdAt', instance_domains.created_at, 'updatedAt', instance_domains.updated_at)) ELSE NULL::JSONB END domains` +
|
||||
` FROM zitadel.instances`
|
||||
)
|
||||
|
||||
// Get implements [domain.InstanceRepository].
|
||||
func (i *instance) Get(ctx context.Context, opts ...database.QueryOption) (*domain.Instance, error) {
|
||||
opts = append(opts,
|
||||
i.joinDomains(),
|
||||
database.WithGroupBy(i.IDColumn()),
|
||||
)
|
||||
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryInstanceStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanInstance(ctx, i.client, &builder)
|
||||
}
|
||||
|
||||
// List implements [domain.InstanceRepository].
|
||||
func (i *instance) List(ctx context.Context, opts ...database.QueryOption) ([]*domain.Instance, error) {
|
||||
opts = append(opts,
|
||||
i.joinDomains(),
|
||||
database.WithGroupBy(i.IDColumn()),
|
||||
)
|
||||
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryInstanceStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanInstances(ctx, i.client, &builder)
|
||||
}
|
||||
|
||||
func (i *instance) joinDomains() database.QueryOption {
|
||||
columns := make([]database.Condition, 0, 2)
|
||||
columns = append(columns, database.NewColumnCondition(i.IDColumn(), i.Domains(false).InstanceIDColumn()))
|
||||
|
||||
// If domains should not be joined, we make sure to return null for the domain columns
|
||||
// the query optimizer of the dialect should optimize this away if no domains are requested
|
||||
if !i.shouldLoadDomains {
|
||||
columns = append(columns, database.IsNull(i.Domains(false).InstanceIDColumn()))
|
||||
}
|
||||
|
||||
return database.WithLeftJoin(
|
||||
"zitadel.instance_domains",
|
||||
database.And(columns...),
|
||||
)
|
||||
}
|
||||
|
||||
// Create implements [domain.InstanceRepository].
|
||||
func (i *instance) Create(ctx context.Context, instance *domain.Instance) error {
|
||||
var (
|
||||
builder database.StatementBuilder
|
||||
createdAt, updatedAt any = database.DefaultInstruction, database.DefaultInstruction
|
||||
)
|
||||
if !instance.CreatedAt.IsZero() {
|
||||
createdAt = instance.CreatedAt
|
||||
}
|
||||
if !instance.UpdatedAt.IsZero() {
|
||||
updatedAt = instance.UpdatedAt
|
||||
}
|
||||
|
||||
builder.WriteString(`INSERT INTO zitadel.instances (id, name, default_org_id, iam_project_id, console_client_id, console_app_id, default_language, created_at, updated_at) VALUES (`)
|
||||
builder.WriteArgs(instance.ID, instance.Name, instance.DefaultOrgID, instance.IAMProjectID, instance.ConsoleClientID, instance.ConsoleAppID, instance.DefaultLanguage, createdAt, updatedAt)
|
||||
builder.WriteString(`) RETURNING created_at, updated_at`)
|
||||
|
||||
return i.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&instance.CreatedAt, &instance.UpdatedAt)
|
||||
}
|
||||
|
||||
// Update implements [domain.InstanceRepository].
|
||||
func (i instance) Update(ctx context.Context, id string, changes ...database.Change) (int64, error) {
|
||||
if len(changes) == 0 {
|
||||
return 0, database.ErrNoChanges
|
||||
}
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`UPDATE zitadel.instances SET `)
|
||||
|
||||
database.Changes(changes).Write(&builder)
|
||||
|
||||
idCondition := i.IDCondition(id)
|
||||
writeCondition(&builder, idCondition)
|
||||
|
||||
stmt := builder.String()
|
||||
|
||||
return i.client.Exec(ctx, stmt, builder.Args()...)
|
||||
}
|
||||
|
||||
// Delete implements [domain.InstanceRepository].
|
||||
func (i instance) Delete(ctx context.Context, id string) (int64, error) {
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`DELETE FROM zitadel.instances`)
|
||||
|
||||
idCondition := i.IDCondition(id)
|
||||
writeCondition(&builder, idCondition)
|
||||
|
||||
return i.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetName implements [domain.instanceChanges].
|
||||
func (i instance) SetName(name string) database.Change {
|
||||
return database.NewChange(i.NameColumn(), name)
|
||||
}
|
||||
|
||||
// SetUpdatedAt implements [domain.instanceChanges].
|
||||
func (i instance) SetUpdatedAt(time time.Time) database.Change {
|
||||
return database.NewChange(i.UpdatedAtColumn(), time)
|
||||
}
|
||||
|
||||
func (i instance) SetIAMProject(id string) database.Change {
|
||||
return database.NewChange(i.IAMProjectIDColumn(), id)
|
||||
}
|
||||
func (i instance) SetDefaultOrg(id string) database.Change {
|
||||
return database.NewChange(i.DefaultOrgIDColumn(), id)
|
||||
}
|
||||
func (i instance) SetDefaultLanguage(lang language.Tag) database.Change {
|
||||
return database.NewChange(i.DefaultLanguageColumn(), lang.String())
|
||||
}
|
||||
func (i instance) SetConsoleClientID(id string) database.Change {
|
||||
return database.NewChange(i.ConsoleClientIDColumn(), id)
|
||||
}
|
||||
func (i instance) SetConsoleAppID(id string) database.Change {
|
||||
return database.NewChange(i.ConsoleAppIDColumn(), id)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// IDCondition implements [domain.instanceConditions].
|
||||
func (i instance) IDCondition(id string) database.Condition {
|
||||
return database.NewTextCondition(i.IDColumn(), database.TextOperationEqual, id)
|
||||
}
|
||||
|
||||
// NameCondition implements [domain.instanceConditions].
|
||||
func (i instance) NameCondition(op database.TextOperation, name string) database.Condition {
|
||||
return database.NewTextCondition(i.NameColumn(), op, name)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// IDColumn implements [domain.instanceColumns].
|
||||
func (instance) IDColumn() database.Column {
|
||||
return database.NewColumn("instances", "id")
|
||||
}
|
||||
|
||||
// NameColumn implements [domain.instanceColumns].
|
||||
func (instance) NameColumn() database.Column {
|
||||
return database.NewColumn("instances", "name")
|
||||
}
|
||||
|
||||
// CreatedAtColumn implements [domain.instanceColumns].
|
||||
func (instance) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn("instances", "created_at")
|
||||
}
|
||||
|
||||
// DefaultOrgIdColumn implements [domain.instanceColumns].
|
||||
func (instance) DefaultOrgIDColumn() database.Column {
|
||||
return database.NewColumn("instances", "default_org_id")
|
||||
}
|
||||
|
||||
// IAMProjectIDColumn implements [domain.instanceColumns].
|
||||
func (instance) IAMProjectIDColumn() database.Column {
|
||||
return database.NewColumn("instances", "iam_project_id")
|
||||
}
|
||||
|
||||
// ConsoleClientIDColumn implements [domain.instanceColumns].
|
||||
func (instance) ConsoleClientIDColumn() database.Column {
|
||||
return database.NewColumn("instances", "console_client_id")
|
||||
}
|
||||
|
||||
// ConsoleAppIDColumn implements [domain.instanceColumns].
|
||||
func (instance) ConsoleAppIDColumn() database.Column {
|
||||
return database.NewColumn("instances", "console_app_id")
|
||||
}
|
||||
|
||||
// DefaultLanguageColumn implements [domain.instanceColumns].
|
||||
func (instance) DefaultLanguageColumn() database.Column {
|
||||
return database.NewColumn("instances", "default_language")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.instanceColumns].
|
||||
func (instance) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn("instances", "updated_at")
|
||||
}
|
||||
|
||||
type rawInstance struct {
|
||||
*domain.Instance
|
||||
RawDomains sql.Null[json.RawMessage] `json:"domains,omitzero" db:"domains"`
|
||||
}
|
||||
|
||||
func scanInstance(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) (*domain.Instance, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var instance rawInstance
|
||||
if err := rows.(database.CollectableRows).CollectExactlyOneRow(&instance); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if instance.RawDomains.Valid {
|
||||
if err := json.Unmarshal(instance.RawDomains.V, &instance.Domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return instance.Instance, nil
|
||||
}
|
||||
|
||||
func scanInstances(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) ([]*domain.Instance, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rawInstances []*rawInstance
|
||||
if err := rows.(database.CollectableRows).Collect(&rawInstances); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
instances := make([]*domain.Instance, len(rawInstances))
|
||||
for i, instance := range rawInstances {
|
||||
if instance.RawDomains.Valid {
|
||||
if err := json.Unmarshal(instance.RawDomains.V, &instance.Domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
instances[i] = instance.Instance
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// sub repositories
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// Domains implements [domain.InstanceRepository].
|
||||
func (i *instance) Domains(shouldLoad bool) domain.InstanceDomainRepository {
|
||||
if !i.shouldLoadDomains {
|
||||
i.shouldLoadDomains = shouldLoad
|
||||
}
|
||||
|
||||
if i.domainRepo != nil {
|
||||
return i.domainRepo
|
||||
}
|
||||
|
||||
i.domainRepo = &instanceDomain{
|
||||
repository: i.repository,
|
||||
instance: i,
|
||||
}
|
||||
return i.domainRepo
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
var _ domain.InstanceDomainRepository = (*instanceDomain)(nil)
|
||||
|
||||
type instanceDomain struct {
|
||||
repository
|
||||
*instance
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
const queryInstanceDomainStmt = `SELECT instance_domains.instance_id, instance_domains.domain, instance_domains.is_primary, instance_domains.created_at, instance_domains.updated_at ` +
|
||||
`FROM zitadel.instance_domains`
|
||||
|
||||
// Get implements [domain.InstanceDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.InstanceRepository]).Get of instanceDomain.instance.
|
||||
func (i *instanceDomain) Get(ctx context.Context, opts ...database.QueryOption) (*domain.InstanceDomain, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryInstanceDomainStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanInstanceDomain(ctx, i.client, &builder)
|
||||
}
|
||||
|
||||
// List implements [domain.InstanceDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.InstanceRepository]).List of instanceDomain.instance.
|
||||
func (i *instanceDomain) List(ctx context.Context, opts ...database.QueryOption) ([]*domain.InstanceDomain, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryInstanceDomainStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanInstanceDomains(ctx, i.client, &builder)
|
||||
}
|
||||
|
||||
// Add implements [domain.InstanceDomainRepository].
|
||||
func (i *instanceDomain) Add(ctx context.Context, domain *domain.AddInstanceDomain) error {
|
||||
var (
|
||||
builder database.StatementBuilder
|
||||
createdAt, updatedAt any = database.DefaultInstruction, database.DefaultInstruction
|
||||
)
|
||||
if !domain.CreatedAt.IsZero() {
|
||||
createdAt = domain.CreatedAt
|
||||
}
|
||||
if !domain.UpdatedAt.IsZero() {
|
||||
updatedAt = domain.UpdatedAt
|
||||
}
|
||||
|
||||
builder.WriteString(`INSERT INTO zitadel.instance_domains (instance_id, domain, is_primary, is_generated, type, created_at, updated_at) VALUES (`)
|
||||
builder.WriteArgs(domain.InstanceID, domain.Domain, domain.IsPrimary, domain.IsGenerated, domain.Type, createdAt, updatedAt)
|
||||
builder.WriteString(`) RETURNING created_at, updated_at`)
|
||||
|
||||
return i.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&domain.CreatedAt, &domain.UpdatedAt)
|
||||
}
|
||||
|
||||
// Update implements [domain.InstanceDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.InstanceRepository]).Update of instanceDomain.instance.
|
||||
func (i *instanceDomain) Update(ctx context.Context, condition database.Condition, changes ...database.Change) (int64, error) {
|
||||
if len(changes) == 0 {
|
||||
return 0, database.ErrNoChanges
|
||||
}
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`UPDATE zitadel.instance_domains SET `)
|
||||
database.Changes(changes).Write(&builder)
|
||||
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
return i.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// Remove implements [domain.InstanceDomainRepository].
|
||||
func (i *instanceDomain) Remove(ctx context.Context, condition database.Condition) (int64, error) {
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`DELETE FROM zitadel.instance_domains WHERE `)
|
||||
condition.Write(&builder)
|
||||
|
||||
return i.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetPrimary implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) SetPrimary() database.Change {
|
||||
return database.NewChange(i.IsPrimaryColumn(), true)
|
||||
}
|
||||
|
||||
// SetUpdatedAt implements [domain.OrganizationDomainRepository].
|
||||
func (i instanceDomain) SetUpdatedAt(updatedAt time.Time) database.Change {
|
||||
return database.NewChange(i.UpdatedAtColumn(), updatedAt)
|
||||
}
|
||||
|
||||
// SetType implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) SetType(typ domain.DomainType) database.Change {
|
||||
return database.NewChange(i.TypeColumn(), typ)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// DomainCondition implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) DomainCondition(op database.TextOperation, domain string) database.Condition {
|
||||
return database.NewTextCondition(i.DomainColumn(), op, domain)
|
||||
}
|
||||
|
||||
// InstanceIDCondition implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) InstanceIDCondition(instanceID string) database.Condition {
|
||||
return database.NewTextCondition(i.InstanceIDColumn(), database.TextOperationEqual, instanceID)
|
||||
}
|
||||
|
||||
// IsPrimaryCondition implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) IsPrimaryCondition(isPrimary bool) database.Condition {
|
||||
return database.NewBooleanCondition(i.IsPrimaryColumn(), isPrimary)
|
||||
}
|
||||
|
||||
// TypeCondition implements [domain.InstanceDomainRepository].
|
||||
func (i instanceDomain) TypeCondition(typ domain.DomainType) database.Condition {
|
||||
return database.NewTextCondition(i.TypeColumn(), database.TextOperationEqual, typ.String())
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// CreatedAtColumn implements [domain.InstanceDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.InstanceRepository]).CreatedAtColumn of instanceDomain.instance.
|
||||
func (instanceDomain) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "created_at")
|
||||
}
|
||||
|
||||
// DomainColumn implements [domain.InstanceDomainRepository].
|
||||
func (instanceDomain) DomainColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "domain")
|
||||
}
|
||||
|
||||
// InstanceIDColumn implements [domain.InstanceDomainRepository].
|
||||
func (instanceDomain) InstanceIDColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "instance_id")
|
||||
}
|
||||
|
||||
// IsPrimaryColumn implements [domain.InstanceDomainRepository].
|
||||
func (instanceDomain) IsPrimaryColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "is_primary")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.InstanceDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.InstanceRepository]).UpdatedAtColumn of instanceDomain.instance.
|
||||
func (instanceDomain) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "updated_at")
|
||||
}
|
||||
|
||||
// IsGeneratedColumn implements [domain.InstanceDomainRepository].
|
||||
func (instanceDomain) IsGeneratedColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "is_generated")
|
||||
}
|
||||
|
||||
// TypeColumn implements [domain.InstanceDomainRepository].
|
||||
func (instanceDomain) TypeColumn() database.Column {
|
||||
return database.NewColumn("instance_domains", "type")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// scanners
|
||||
// -------------------------------------------------------------
|
||||
|
||||
func scanInstanceDomains(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) ([]*domain.InstanceDomain, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var domains []*domain.InstanceDomain
|
||||
if err := rows.(database.CollectableRows).Collect(&domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return domains, nil
|
||||
}
|
||||
|
||||
func scanInstanceDomain(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) (*domain.InstanceDomain, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
domain := new(domain.InstanceDomain)
|
||||
if err := rows.(database.CollectableRows).CollectExactlyOneRow(domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return domain, nil
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
package repository_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/brianvoe/gofakeit/v6"
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
|
||||
)
|
||||
|
||||
func TestAddInstanceDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
err := instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T, domainRepo domain.InstanceDomainRepository) *domain.AddInstanceDomain
|
||||
instanceDomain domain.AddInstanceDomain
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "happy path custom domain",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "happy path trusted domain",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeTrusted,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add primary domain",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(true),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add custom domain without domain name",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: "",
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add trusted domain without domain name",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: "",
|
||||
Type: domain.DomainTypeTrusted,
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add custom domain with same domain twice",
|
||||
testFunc: func(ctx context.Context, t *testing.T, domainRepo domain.InstanceDomainRepository) *domain.AddInstanceDomain {
|
||||
domainName := gofakeit.DomainName()
|
||||
|
||||
instanceDomain := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName,
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
}
|
||||
|
||||
err := domainRepo.Add(ctx, instanceDomain)
|
||||
require.NoError(t, err)
|
||||
|
||||
// return same domain again
|
||||
return &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName,
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
}
|
||||
},
|
||||
err: new(database.UniqueError),
|
||||
},
|
||||
{
|
||||
name: "add trusted domain with same domain twice",
|
||||
testFunc: func(ctx context.Context, t *testing.T, domainRepo domain.InstanceDomainRepository) *domain.AddInstanceDomain {
|
||||
domainName := gofakeit.DomainName()
|
||||
|
||||
instanceDomain := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName,
|
||||
Type: domain.DomainTypeTrusted,
|
||||
}
|
||||
|
||||
err := domainRepo.Add(ctx, instanceDomain)
|
||||
require.NoError(t, err)
|
||||
|
||||
// return same domain again
|
||||
return &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName,
|
||||
Type: domain.DomainTypeTrusted,
|
||||
}
|
||||
},
|
||||
err: new(database.UniqueError),
|
||||
},
|
||||
{
|
||||
name: "add domain with non-existent instance",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
InstanceID: "non-existent-instance",
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
{
|
||||
name: "add domain without instance id",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
{
|
||||
name: "add custom domain without primary",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add custom domain without generated",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeCustom,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add trusted domain with primary",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeTrusted,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add trusted domain with generated",
|
||||
instanceDomain: domain.AddInstanceDomain{
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeTrusted,
|
||||
IsGenerated: gu.Ptr(false),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
// we take now here because the timestamp of the transaction is used to set the createdAt and updatedAt fields
|
||||
beforeAdd := time.Now()
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
|
||||
var instanceDomain *domain.AddInstanceDomain
|
||||
if test.testFunc != nil {
|
||||
instanceDomain = test.testFunc(ctx, t, domainRepo)
|
||||
} else {
|
||||
instanceDomain = &test.instanceDomain
|
||||
}
|
||||
|
||||
err = domainRepo.Add(ctx, instanceDomain)
|
||||
afterAdd := time.Now()
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, instanceDomain.CreatedAt)
|
||||
assert.NotZero(t, instanceDomain.UpdatedAt)
|
||||
assert.WithinRange(t, instanceDomain.CreatedAt, beforeAdd, afterAdd)
|
||||
assert.WithinRange(t, instanceDomain.UpdatedAt, beforeAdd, afterAdd)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInstanceDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domains
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
domainName1 := gofakeit.DomainName()
|
||||
domainName2 := gofakeit.DomainName()
|
||||
|
||||
domain1 := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName1,
|
||||
IsPrimary: gu.Ptr(true),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
domain2 := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName2,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), domain1)
|
||||
require.NoError(t, err)
|
||||
err = domainRepo.Add(t.Context(), domain2)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
opts []database.QueryOption
|
||||
expected *domain.InstanceDomain
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "get primary domain",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsPrimaryCondition(true)),
|
||||
},
|
||||
expected: &domain.InstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName1,
|
||||
IsPrimary: gu.Ptr(true),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get by domain name",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.DomainCondition(database.TextOperationEqual, domainName2)),
|
||||
},
|
||||
expected: &domain.InstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName2,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get non-existent domain",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com")),
|
||||
},
|
||||
err: new(database.NoRowFoundError),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
result, err := domainRepo.Get(ctx, test.opts...)
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected.InstanceID, result.InstanceID)
|
||||
assert.Equal(t, test.expected.Domain, result.Domain)
|
||||
assert.Equal(t, test.expected.IsPrimary, result.IsPrimary)
|
||||
assert.NotEmpty(t, result.CreatedAt)
|
||||
assert.NotEmpty(t, result.UpdatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListInstanceDomains(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add multiple domains
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
domains := []domain.AddInstanceDomain{
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsPrimary: gu.Ptr(true),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
},
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
},
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
Type: domain.DomainTypeTrusted,
|
||||
},
|
||||
}
|
||||
|
||||
for i := range domains {
|
||||
err = domainRepo.Add(t.Context(), &domains[i])
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
opts []database.QueryOption
|
||||
expectedCount int
|
||||
}{
|
||||
{
|
||||
name: "list all domains",
|
||||
opts: []database.QueryOption{},
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "list primary domains",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsPrimaryCondition(true)),
|
||||
},
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "list by instance",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.InstanceIDCondition(instanceID)),
|
||||
},
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "list non-existent instance",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.InstanceIDCondition("non-existent")),
|
||||
},
|
||||
expectedCount: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
results, err := domainRepo.List(ctx, test.opts...)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, test.expectedCount)
|
||||
|
||||
for _, result := range results {
|
||||
assert.Equal(t, instanceID, result.InstanceID)
|
||||
assert.NotEmpty(t, result.Domain)
|
||||
assert.NotEmpty(t, result.CreatedAt)
|
||||
assert.NotEmpty(t, result.UpdatedAt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstanceDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domain
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
domainName := gofakeit.DomainName()
|
||||
instanceDomain := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName,
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), instanceDomain)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
changes []database.Change
|
||||
expected int64
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "set primary",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{domainRepo.SetPrimary()},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "update non-existent domain",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com"),
|
||||
changes: []database.Change{domainRepo.SetPrimary()},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "no changes",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{},
|
||||
expected: 0,
|
||||
err: database.ErrNoChanges,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
rowsAffected, err := domainRepo.Update(ctx, test.condition, test.changes...)
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected, rowsAffected)
|
||||
|
||||
// verify changes were applied if rows were affected
|
||||
if rowsAffected > 0 && len(test.changes) > 0 {
|
||||
result, err := domainRepo.Get(ctx, database.WithCondition(test.condition))
|
||||
require.NoError(t, err)
|
||||
|
||||
// We know changes were applied since rowsAffected > 0
|
||||
// The specific verification of what changed is less important
|
||||
// than knowing the operation succeeded
|
||||
assert.NotNil(t, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveInstanceDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domains
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
domainName1 := gofakeit.DomainName()
|
||||
|
||||
domain1 := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: domainName1,
|
||||
IsPrimary: gu.Ptr(true),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
domain2 := &domain.AddInstanceDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsPrimary: gu.Ptr(false),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), domain1)
|
||||
require.NoError(t, err)
|
||||
err = domainRepo.Add(t.Context(), domain2)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
expected int64
|
||||
}{
|
||||
{
|
||||
name: "remove by domain name",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName1),
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "remove by primary condition",
|
||||
condition: domainRepo.IsPrimaryCondition(false),
|
||||
expected: 1, // domain2 should still exist and be non-primary
|
||||
},
|
||||
{
|
||||
name: "remove non-existent domain",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com"),
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
// count before removal
|
||||
beforeCount, err := domainRepo.List(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
rowsAffected, err := domainRepo.Remove(ctx, test.condition)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected, rowsAffected)
|
||||
|
||||
// verify removal
|
||||
afterCount, err := domainRepo.List(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, len(beforeCount)-int(test.expected), len(afterCount))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceDomainConditions(t *testing.T) {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "domain condition equal",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "example.com"),
|
||||
expected: "instance_domains.domain = $1",
|
||||
},
|
||||
{
|
||||
name: "domain condition starts with",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationStartsWith, "example"),
|
||||
expected: "instance_domains.domain LIKE $1 || '%'",
|
||||
},
|
||||
{
|
||||
name: "instance id condition",
|
||||
condition: domainRepo.InstanceIDCondition("instance-123"),
|
||||
expected: "instance_domains.instance_id = $1",
|
||||
},
|
||||
{
|
||||
name: "is primary true",
|
||||
condition: domainRepo.IsPrimaryCondition(true),
|
||||
expected: "instance_domains.is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "is primary false",
|
||||
condition: domainRepo.IsPrimaryCondition(false),
|
||||
expected: "instance_domains.is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "is type custom",
|
||||
condition: domainRepo.TypeCondition(domain.DomainTypeCustom),
|
||||
expected: "instance_domains.type = $1",
|
||||
},
|
||||
{
|
||||
name: "is type trusted",
|
||||
condition: domainRepo.TypeCondition(domain.DomainTypeTrusted),
|
||||
expected: "instance_domains.type = $1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var builder database.StatementBuilder
|
||||
test.condition.Write(&builder)
|
||||
assert.Equal(t, test.expected, builder.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceDomainChanges(t *testing.T) {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
change database.Change
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "set primary",
|
||||
change: domainRepo.SetPrimary(),
|
||||
expected: "is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "set type",
|
||||
change: domainRepo.SetType(domain.DomainTypeCustom),
|
||||
expected: "type = $1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var builder database.StatementBuilder
|
||||
test.change.Write(&builder)
|
||||
assert.Equal(t, test.expected, builder.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,723 @@
|
||||
package repository_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/brianvoe/gofakeit/v6"
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
|
||||
)
|
||||
|
||||
func TestCreateInstance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) *domain.Instance
|
||||
instance domain.Instance
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "happy path",
|
||||
instance: func() domain.Instance {
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
return instance
|
||||
}(),
|
||||
},
|
||||
{
|
||||
name: "create instance without name",
|
||||
instance: func() domain.Instance {
|
||||
instanceId := gofakeit.Name()
|
||||
// instanceName := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: "",
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
return instance
|
||||
}(),
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "adding same instance twice",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
// change the name to make sure same only the id clashes
|
||||
inst.Name = gofakeit.Name()
|
||||
require.NoError(t, err)
|
||||
return &inst
|
||||
},
|
||||
err: new(database.UniqueError),
|
||||
},
|
||||
func() struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) *domain.Instance
|
||||
instance domain.Instance
|
||||
err error
|
||||
} {
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
return struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) *domain.Instance
|
||||
instance domain.Instance
|
||||
err error
|
||||
}{
|
||||
name: "adding instance with same name twice",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: gofakeit.Name(),
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
// change the id
|
||||
inst.ID = instanceId
|
||||
inst.CreatedAt = time.Time{}
|
||||
inst.UpdatedAt = time.Time{}
|
||||
return &inst
|
||||
},
|
||||
instance: domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
},
|
||||
// two instances can have the sane name
|
||||
err: nil,
|
||||
}
|
||||
}(),
|
||||
{
|
||||
name: "adding instance with no id",
|
||||
instance: func() domain.Instance {
|
||||
// instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
instance := domain.Instance{
|
||||
// ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
return instance
|
||||
}(),
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
var instance *domain.Instance
|
||||
if tt.testFunc != nil {
|
||||
instance = tt.testFunc(ctx, t)
|
||||
} else {
|
||||
instance = &tt.instance
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
// create instance
|
||||
beforeCreate := time.Now()
|
||||
err := instanceRepo.Create(ctx, instance)
|
||||
assert.ErrorIs(t, err, tt.err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
afterCreate := time.Now()
|
||||
|
||||
// check instance values
|
||||
instance, err = instanceRepo.Get(ctx,
|
||||
database.WithCondition(
|
||||
instanceRepo.IDCondition(instance.ID),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tt.instance.ID, instance.ID)
|
||||
assert.Equal(t, tt.instance.Name, instance.Name)
|
||||
assert.Equal(t, tt.instance.DefaultOrgID, instance.DefaultOrgID)
|
||||
assert.Equal(t, tt.instance.IAMProjectID, instance.IAMProjectID)
|
||||
assert.Equal(t, tt.instance.ConsoleClientID, instance.ConsoleClientID)
|
||||
assert.Equal(t, tt.instance.ConsoleAppID, instance.ConsoleAppID)
|
||||
assert.Equal(t, tt.instance.DefaultLanguage, instance.DefaultLanguage)
|
||||
assert.WithinRange(t, instance.CreatedAt, beforeCreate, afterCreate)
|
||||
assert.WithinRange(t, instance.UpdatedAt, beforeCreate, afterCreate)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) *domain.Instance
|
||||
rowsAffected int64
|
||||
getErr error
|
||||
}{
|
||||
{
|
||||
name: "happy path",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
return &inst
|
||||
},
|
||||
rowsAffected: 1,
|
||||
},
|
||||
{
|
||||
name: "update deleted instance",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
// delete instance
|
||||
affectedRows, err := instanceRepo.Delete(ctx,
|
||||
inst.ID,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), affectedRows)
|
||||
|
||||
return &inst
|
||||
},
|
||||
rowsAffected: 0,
|
||||
},
|
||||
{
|
||||
name: "update non existent instance",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceId := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
}
|
||||
return &inst
|
||||
},
|
||||
rowsAffected: 0,
|
||||
getErr: new(database.NoRowFoundError),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
instance := tt.testFunc(ctx, t)
|
||||
|
||||
beforeUpdate := time.Now()
|
||||
// update name
|
||||
newName := "new_" + instance.Name
|
||||
rowsAffected, err := instanceRepo.Update(ctx,
|
||||
instance.ID,
|
||||
instanceRepo.SetName(newName),
|
||||
)
|
||||
afterUpdate := time.Now()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tt.rowsAffected, rowsAffected)
|
||||
|
||||
if rowsAffected == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// check instance values
|
||||
instance, err = instanceRepo.Get(ctx,
|
||||
database.WithCondition(
|
||||
instanceRepo.IDCondition(instance.ID),
|
||||
),
|
||||
)
|
||||
require.Equal(t, tt.getErr, err)
|
||||
|
||||
assert.Equal(t, newName, instance.Name)
|
||||
assert.WithinRange(t, instance.UpdatedAt, beforeUpdate, afterUpdate)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetInstance(t *testing.T) {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
type test struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) *domain.Instance
|
||||
err error
|
||||
}
|
||||
|
||||
tests := []test{
|
||||
func() test {
|
||||
instanceId := gofakeit.Name()
|
||||
return test{
|
||||
name: "happy path get using id",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceName := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
return &inst
|
||||
},
|
||||
}
|
||||
}(),
|
||||
{
|
||||
name: "happy path including domains",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
instanceName := gofakeit.Name()
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
domainRepo := instanceRepo.Domains(false)
|
||||
d := &domain.AddInstanceDomain{
|
||||
InstanceID: inst.ID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsPrimary: gu.Ptr(true),
|
||||
IsGenerated: gu.Ptr(false),
|
||||
Type: domain.DomainTypeCustom,
|
||||
}
|
||||
err = domainRepo.Add(ctx, d)
|
||||
require.NoError(t, err)
|
||||
|
||||
inst.Domains = append(inst.Domains, &domain.InstanceDomain{
|
||||
InstanceID: d.InstanceID,
|
||||
Domain: d.Domain,
|
||||
IsPrimary: d.IsPrimary,
|
||||
IsGenerated: d.IsGenerated,
|
||||
Type: d.Type,
|
||||
CreatedAt: d.CreatedAt,
|
||||
UpdatedAt: d.UpdatedAt,
|
||||
})
|
||||
|
||||
return &inst
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get non existent instance",
|
||||
testFunc: func(ctx context.Context, t *testing.T) *domain.Instance {
|
||||
inst := domain.Instance{
|
||||
ID: "get non existent instance",
|
||||
}
|
||||
return &inst
|
||||
},
|
||||
err: new(database.NoRowFoundError),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
var instance *domain.Instance
|
||||
if tt.testFunc != nil {
|
||||
instance = tt.testFunc(ctx, t)
|
||||
}
|
||||
|
||||
// check instance values
|
||||
returnedInstance, err := instanceRepo.Get(ctx,
|
||||
database.WithCondition(
|
||||
instanceRepo.IDCondition(instance.ID),
|
||||
),
|
||||
)
|
||||
if tt.err != nil {
|
||||
require.ErrorIs(t, err, tt.err)
|
||||
return
|
||||
}
|
||||
|
||||
if instance.ID == "get non existent instance" {
|
||||
assert.Nil(t, returnedInstance)
|
||||
return
|
||||
}
|
||||
|
||||
assert.Equal(t, returnedInstance.ID, instance.ID)
|
||||
assert.Equal(t, returnedInstance.Name, instance.Name)
|
||||
assert.Equal(t, returnedInstance.DefaultOrgID, instance.DefaultOrgID)
|
||||
assert.Equal(t, returnedInstance.IAMProjectID, instance.IAMProjectID)
|
||||
assert.Equal(t, returnedInstance.ConsoleClientID, instance.ConsoleClientID)
|
||||
assert.Equal(t, returnedInstance.ConsoleAppID, instance.ConsoleAppID)
|
||||
assert.Equal(t, returnedInstance.DefaultLanguage, instance.DefaultLanguage)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListInstance(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
pool, stop, err := newEmbeddedDB(ctx)
|
||||
require.NoError(t, err)
|
||||
defer stop()
|
||||
|
||||
type test struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T) []*domain.Instance
|
||||
conditionClauses []database.Condition
|
||||
noInstanceReturned bool
|
||||
}
|
||||
tests := []test{
|
||||
{
|
||||
name: "happy path single instance no filter",
|
||||
testFunc: func(ctx context.Context, t *testing.T) []*domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
noOfInstances := 1
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: gofakeit.Name(),
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
|
||||
return instances
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "happy path multiple instance no filter",
|
||||
testFunc: func(ctx context.Context, t *testing.T) []*domain.Instance {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
noOfInstances := 5
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: gofakeit.Name(),
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
|
||||
return instances
|
||||
},
|
||||
},
|
||||
func() test {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
return test{
|
||||
name: "instance filter on id",
|
||||
testFunc: func(ctx context.Context, t *testing.T) []*domain.Instance {
|
||||
noOfInstances := 1
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
|
||||
return instances
|
||||
},
|
||||
conditionClauses: []database.Condition{instanceRepo.IDCondition(instanceId)},
|
||||
}
|
||||
}(),
|
||||
func() test {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceName := gofakeit.Name()
|
||||
return test{
|
||||
name: "multiple instance filter on name",
|
||||
testFunc: func(ctx context.Context, t *testing.T) []*domain.Instance {
|
||||
noOfInstances := 5
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: gofakeit.Name(),
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
|
||||
return instances
|
||||
},
|
||||
conditionClauses: []database.Condition{instanceRepo.NameCondition(database.TextOperationEqual, instanceName)},
|
||||
}
|
||||
}(),
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
_, err := pool.Exec(ctx, "DELETE FROM zitadel.instances")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
instances := tt.testFunc(ctx, t)
|
||||
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
var condition database.Condition
|
||||
if len(tt.conditionClauses) > 0 {
|
||||
condition = database.And(tt.conditionClauses...)
|
||||
}
|
||||
|
||||
// check instance values
|
||||
returnedInstances, err := instanceRepo.List(ctx,
|
||||
database.WithCondition(condition),
|
||||
database.WithOrderByAscending(instanceRepo.CreatedAtColumn()),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
if tt.noInstanceReturned {
|
||||
assert.Nil(t, returnedInstances)
|
||||
return
|
||||
}
|
||||
|
||||
assert.Equal(t, len(instances), len(returnedInstances))
|
||||
for i, instance := range instances {
|
||||
assert.Equal(t, returnedInstances[i].ID, instance.ID)
|
||||
assert.Equal(t, returnedInstances[i].Name, instance.Name)
|
||||
assert.Equal(t, returnedInstances[i].DefaultOrgID, instance.DefaultOrgID)
|
||||
assert.Equal(t, returnedInstances[i].IAMProjectID, instance.IAMProjectID)
|
||||
assert.Equal(t, returnedInstances[i].ConsoleClientID, instance.ConsoleClientID)
|
||||
assert.Equal(t, returnedInstances[i].ConsoleAppID, instance.ConsoleAppID)
|
||||
assert.Equal(t, returnedInstances[i].DefaultLanguage, instance.DefaultLanguage)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteInstance(t *testing.T) {
|
||||
type test struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T)
|
||||
instanceID string
|
||||
noOfDeletedRows int64
|
||||
}
|
||||
tests := []test{
|
||||
func() test {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceId := gofakeit.Name()
|
||||
var noOfInstances int64 = 1
|
||||
return test{
|
||||
name: "happy path delete single instance filter id",
|
||||
testFunc: func(ctx context.Context, t *testing.T) {
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: instanceId,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
},
|
||||
instanceID: instanceId,
|
||||
noOfDeletedRows: noOfInstances,
|
||||
}
|
||||
}(),
|
||||
func() test {
|
||||
non_existent_instance_name := gofakeit.Name()
|
||||
return test{
|
||||
name: "delete non existent instance",
|
||||
instanceID: non_existent_instance_name,
|
||||
}
|
||||
}(),
|
||||
func() test {
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
instanceName := gofakeit.Name()
|
||||
return test{
|
||||
name: "deleted already deleted instance",
|
||||
testFunc: func(ctx context.Context, t *testing.T) {
|
||||
noOfInstances := 1
|
||||
instances := make([]*domain.Instance, noOfInstances)
|
||||
for i := range noOfInstances {
|
||||
|
||||
inst := domain.Instance{
|
||||
ID: gofakeit.Name(),
|
||||
Name: instanceName,
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleCLient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create instance
|
||||
err := instanceRepo.Create(ctx, &inst)
|
||||
require.NoError(t, err)
|
||||
|
||||
instances[i] = &inst
|
||||
}
|
||||
|
||||
// delete instance
|
||||
affectedRows, err := instanceRepo.Delete(ctx,
|
||||
instances[0].ID,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, int64(1), affectedRows)
|
||||
},
|
||||
instanceID: instanceName,
|
||||
// this test should return 0 affected rows as the instance was already deleted
|
||||
noOfDeletedRows: 0,
|
||||
}
|
||||
}(),
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
|
||||
if tt.testFunc != nil {
|
||||
tt.testFunc(ctx, t)
|
||||
}
|
||||
|
||||
// delete instance
|
||||
noOfDeletedRows, err := instanceRepo.Delete(ctx,
|
||||
tt.instanceID,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, noOfDeletedRows, tt.noOfDeletedRows)
|
||||
|
||||
// check instance was deleted
|
||||
instance, err := instanceRepo.Get(ctx,
|
||||
database.WithCondition(
|
||||
instanceRepo.IDCondition(tt.instanceID),
|
||||
),
|
||||
)
|
||||
require.ErrorIs(t, err, new(database.NoRowFoundError))
|
||||
assert.Nil(t, instance)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
var _ domain.OrganizationRepository = (*org)(nil)
|
||||
|
||||
type org struct {
|
||||
repository
|
||||
shouldLoadDomains bool
|
||||
domainRepo domain.OrganizationDomainRepository
|
||||
}
|
||||
|
||||
func OrganizationRepository(client database.QueryExecutor) domain.OrganizationRepository {
|
||||
return &org{
|
||||
repository: repository{
|
||||
client: client,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const queryOrganizationStmt = `SELECT organizations.id, organizations.name, organizations.instance_id, organizations.state, organizations.created_at, organizations.updated_at` +
|
||||
` , CASE WHEN count(org_domains.domain) > 0 THEN jsonb_agg(json_build_object('domain', org_domains.domain, 'isVerified', org_domains.is_verified, 'isPrimary', org_domains.is_primary, 'validationType', org_domains.validation_type, 'createdAt', org_domains.created_at, 'updatedAt', org_domains.updated_at)) ELSE NULL::JSONB END domains` +
|
||||
` FROM zitadel.organizations`
|
||||
|
||||
// Get implements [domain.OrganizationRepository].
|
||||
func (o *org) Get(ctx context.Context, opts ...database.QueryOption) (*domain.Organization, error) {
|
||||
opts = append(opts,
|
||||
o.joinDomains(),
|
||||
database.WithGroupBy(o.InstanceIDColumn(), o.IDColumn()),
|
||||
)
|
||||
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryOrganizationStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanOrganization(ctx, o.client, &builder)
|
||||
}
|
||||
|
||||
// List implements [domain.OrganizationRepository].
|
||||
func (o *org) List(ctx context.Context, opts ...database.QueryOption) ([]*domain.Organization, error) {
|
||||
opts = append(opts,
|
||||
o.joinDomains(),
|
||||
database.WithGroupBy(o.InstanceIDColumn(), o.IDColumn()),
|
||||
)
|
||||
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryOrganizationStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanOrganizations(ctx, o.client, &builder)
|
||||
}
|
||||
|
||||
func (o *org) joinDomains() database.QueryOption {
|
||||
columns := make([]database.Condition, 0, 3)
|
||||
columns = append(columns,
|
||||
database.NewColumnCondition(o.InstanceIDColumn(), o.Domains(false).InstanceIDColumn()),
|
||||
database.NewColumnCondition(o.IDColumn(), o.Domains(false).OrgIDColumn()),
|
||||
)
|
||||
|
||||
// If domains should not be joined, we make sure to return null for the domain columns
|
||||
// the query optimizer of the dialect should optimize this away if no domains are requested
|
||||
if !o.shouldLoadDomains {
|
||||
columns = append(columns, database.IsNull(o.domainRepo.OrgIDColumn()))
|
||||
}
|
||||
|
||||
return database.WithLeftJoin(
|
||||
"zitadel.org_domains",
|
||||
database.And(columns...),
|
||||
)
|
||||
}
|
||||
|
||||
const createOrganizationStmt = `INSERT INTO zitadel.organizations (id, name, instance_id, state)` +
|
||||
` VALUES ($1, $2, $3, $4)` +
|
||||
` RETURNING created_at, updated_at`
|
||||
|
||||
// Create implements [domain.OrganizationRepository].
|
||||
func (o *org) Create(ctx context.Context, organization *domain.Organization) error {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.AppendArgs(organization.ID, organization.Name, organization.InstanceID, organization.State)
|
||||
builder.WriteString(createOrganizationStmt)
|
||||
|
||||
return o.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&organization.CreatedAt, &organization.UpdatedAt)
|
||||
}
|
||||
|
||||
// Update implements [domain.OrganizationRepository].
|
||||
func (o *org) Update(ctx context.Context, id domain.OrgIdentifierCondition, instanceID string, changes ...database.Change) (int64, error) {
|
||||
if len(changes) == 0 {
|
||||
return 0, database.ErrNoChanges
|
||||
}
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(`UPDATE zitadel.organizations SET `)
|
||||
|
||||
instanceIDCondition := o.InstanceIDCondition(instanceID)
|
||||
|
||||
conditions := []database.Condition{id, instanceIDCondition}
|
||||
database.Changes(changes).Write(&builder)
|
||||
writeCondition(&builder, database.And(conditions...))
|
||||
|
||||
stmt := builder.String()
|
||||
|
||||
rowsAffected, err := o.client.Exec(ctx, stmt, builder.Args()...)
|
||||
return rowsAffected, err
|
||||
}
|
||||
|
||||
// Delete implements [domain.OrganizationRepository].
|
||||
func (o *org) Delete(ctx context.Context, id domain.OrgIdentifierCondition, instanceID string) (int64, error) {
|
||||
builder := database.StatementBuilder{}
|
||||
|
||||
builder.WriteString(`DELETE FROM zitadel.organizations`)
|
||||
|
||||
instanceIDCondition := o.InstanceIDCondition(instanceID)
|
||||
|
||||
conditions := []database.Condition{id, instanceIDCondition}
|
||||
writeCondition(&builder, database.And(conditions...))
|
||||
|
||||
return o.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetName implements [domain.organizationChanges].
|
||||
func (o org) SetName(name string) database.Change {
|
||||
return database.NewChange(o.NameColumn(), name)
|
||||
}
|
||||
|
||||
// SetState implements [domain.organizationChanges].
|
||||
func (o org) SetState(state domain.OrgState) database.Change {
|
||||
return database.NewChange(o.StateColumn(), state)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// IDCondition implements [domain.organizationConditions].
|
||||
func (o org) IDCondition(id string) domain.OrgIdentifierCondition {
|
||||
return database.NewTextCondition(o.IDColumn(), database.TextOperationEqual, id)
|
||||
}
|
||||
|
||||
// NameCondition implements [domain.organizationConditions].
|
||||
func (o org) NameCondition(name string) domain.OrgIdentifierCondition {
|
||||
return database.NewTextCondition(o.NameColumn(), database.TextOperationEqual, name)
|
||||
}
|
||||
|
||||
// InstanceIDCondition implements [domain.organizationConditions].
|
||||
func (o org) InstanceIDCondition(instanceID string) database.Condition {
|
||||
return database.NewTextCondition(o.InstanceIDColumn(), database.TextOperationEqual, instanceID)
|
||||
}
|
||||
|
||||
// StateCondition implements [domain.organizationConditions].
|
||||
func (o org) StateCondition(state domain.OrgState) database.Condition {
|
||||
return database.NewTextCondition(o.StateColumn(), database.TextOperationEqual, state.String())
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// IDColumn implements [domain.organizationColumns].
|
||||
func (org) IDColumn() database.Column {
|
||||
return database.NewColumn("organizations", "id")
|
||||
}
|
||||
|
||||
// NameColumn implements [domain.organizationColumns].
|
||||
func (org) NameColumn() database.Column {
|
||||
return database.NewColumn("organizations", "name")
|
||||
}
|
||||
|
||||
// InstanceIDColumn implements [domain.organizationColumns].
|
||||
func (org) InstanceIDColumn() database.Column {
|
||||
return database.NewColumn("organizations", "instance_id")
|
||||
}
|
||||
|
||||
// StateColumn implements [domain.organizationColumns].
|
||||
func (org) StateColumn() database.Column {
|
||||
return database.NewColumn("organizations", "state")
|
||||
}
|
||||
|
||||
// CreatedAtColumn implements [domain.organizationColumns].
|
||||
func (org) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn("organizations", "created_at")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.organizationColumns].
|
||||
func (org) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn("organizations", "updated_at")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// scanners
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type rawOrganization struct {
|
||||
*domain.Organization
|
||||
RawDomains json.RawMessage `json:"domains,omitempty" db:"domains"`
|
||||
}
|
||||
|
||||
func scanOrganization(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) (*domain.Organization, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var org rawOrganization
|
||||
if err := rows.(database.CollectableRows).CollectExactlyOneRow(&org); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(org.RawDomains) > 0 {
|
||||
if err := json.Unmarshal(org.RawDomains, &org.Domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return org.Organization, nil
|
||||
}
|
||||
|
||||
func scanOrganizations(ctx context.Context, querier database.Querier, builder *database.StatementBuilder) ([]*domain.Organization, error) {
|
||||
rows, err := querier.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rawOrgs []*rawOrganization
|
||||
if err := rows.(database.CollectableRows).Collect(&rawOrgs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
organizations := make([]*domain.Organization, len(rawOrgs))
|
||||
for i, org := range rawOrgs {
|
||||
if len(org.RawDomains) > 0 {
|
||||
if err := json.Unmarshal(org.RawDomains, &org.Domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
organizations[i] = org.Organization
|
||||
}
|
||||
return organizations, nil
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// sub repositories
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// Domains implements [domain.OrganizationRepository].
|
||||
func (o *org) Domains(shouldLoad bool) domain.OrganizationDomainRepository {
|
||||
if !o.shouldLoadDomains {
|
||||
o.shouldLoadDomains = shouldLoad
|
||||
}
|
||||
|
||||
if o.domainRepo != nil {
|
||||
return o.domainRepo
|
||||
}
|
||||
|
||||
o.domainRepo = &orgDomain{
|
||||
repository: o.repository,
|
||||
org: o,
|
||||
}
|
||||
|
||||
return o.domainRepo
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
var _ domain.OrganizationDomainRepository = (*orgDomain)(nil)
|
||||
|
||||
type orgDomain struct {
|
||||
repository
|
||||
*org
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
const queryOrganizationDomainStmt = `SELECT instance_id, org_id, domain, is_verified, is_primary, validation_type, created_at, updated_at ` +
|
||||
`FROM zitadel.org_domains`
|
||||
|
||||
// Get implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).Get of orgDomain.org.
|
||||
func (o *orgDomain) Get(ctx context.Context, opts ...database.QueryOption) (*domain.OrganizationDomain, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryOrganizationDomainStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanOrganizationDomain(ctx, o.client, &builder)
|
||||
}
|
||||
|
||||
// List implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).List of orgDomain.org.
|
||||
func (o *orgDomain) List(ctx context.Context, opts ...database.QueryOption) ([]*domain.OrganizationDomain, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
builder.WriteString(queryOrganizationDomainStmt)
|
||||
options.Write(&builder)
|
||||
|
||||
return scanOrganizationDomains(ctx, o.client, &builder)
|
||||
}
|
||||
|
||||
// Add implements [domain.OrganizationDomainRepository].
|
||||
func (o *orgDomain) Add(ctx context.Context, domain *domain.AddOrganizationDomain) error {
|
||||
var (
|
||||
builder database.StatementBuilder
|
||||
createdAt, updatedAt any = database.DefaultInstruction, database.DefaultInstruction
|
||||
)
|
||||
if !domain.CreatedAt.IsZero() {
|
||||
createdAt = domain.CreatedAt
|
||||
}
|
||||
if !domain.UpdatedAt.IsZero() {
|
||||
updatedAt = domain.UpdatedAt
|
||||
}
|
||||
|
||||
builder.WriteString(`INSERT INTO zitadel.org_domains (instance_id, org_id, domain, is_verified, is_primary, validation_type, created_at, updated_at) VALUES (`)
|
||||
builder.WriteArgs(domain.InstanceID, domain.OrgID, domain.Domain, domain.IsVerified, domain.IsPrimary, domain.ValidationType, createdAt, updatedAt)
|
||||
builder.WriteString(`) RETURNING created_at, updated_at`)
|
||||
|
||||
return o.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&domain.CreatedAt, &domain.UpdatedAt)
|
||||
}
|
||||
|
||||
// Update implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).Update of orgDomain.org.
|
||||
func (o *orgDomain) Update(ctx context.Context, condition database.Condition, changes ...database.Change) (int64, error) {
|
||||
if len(changes) == 0 {
|
||||
return 0, database.ErrNoChanges
|
||||
}
|
||||
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`UPDATE zitadel.org_domains SET `)
|
||||
database.Changes(changes).Write(&builder)
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
return o.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// Remove implements [domain.OrganizationDomainRepository].
|
||||
func (o *orgDomain) Remove(ctx context.Context, condition database.Condition) (int64, error) {
|
||||
var builder database.StatementBuilder
|
||||
|
||||
builder.WriteString(`DELETE FROM zitadel.org_domains `)
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
return o.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetPrimary implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) SetPrimary() database.Change {
|
||||
return database.NewChange(o.IsPrimaryColumn(), true)
|
||||
}
|
||||
|
||||
// SetValidationType implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) SetValidationType(verificationType domain.DomainValidationType) database.Change {
|
||||
return database.NewChange(o.ValidationTypeColumn(), verificationType)
|
||||
}
|
||||
|
||||
// SetVerified implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) SetVerified() database.Change {
|
||||
return database.NewChange(o.IsVerifiedColumn(), true)
|
||||
}
|
||||
|
||||
// SetUpdatedAt implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) SetUpdatedAt(updatedAt time.Time) database.Change {
|
||||
return database.NewChange(o.UpdatedAtColumn(), updatedAt)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// DomainCondition implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) DomainCondition(op database.TextOperation, domain string) database.Condition {
|
||||
return database.NewTextCondition(o.DomainColumn(), op, domain)
|
||||
}
|
||||
|
||||
// InstanceIDCondition implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).InstanceIDCondition of orgDomain.org.
|
||||
func (o orgDomain) InstanceIDCondition(instanceID string) database.Condition {
|
||||
return database.NewTextCondition(o.InstanceIDColumn(), database.TextOperationEqual, instanceID)
|
||||
}
|
||||
|
||||
// IsPrimaryCondition implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) IsPrimaryCondition(isPrimary bool) database.Condition {
|
||||
return database.NewBooleanCondition(o.IsPrimaryColumn(), isPrimary)
|
||||
}
|
||||
|
||||
// IsVerifiedCondition implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) IsVerifiedCondition(isVerified bool) database.Condition {
|
||||
return database.NewBooleanCondition(o.IsVerifiedColumn(), isVerified)
|
||||
}
|
||||
|
||||
// OrgIDCondition implements [domain.OrganizationDomainRepository].
|
||||
func (o orgDomain) OrgIDCondition(orgID string) database.Condition {
|
||||
return database.NewTextCondition(o.OrgIDColumn(), database.TextOperationEqual, orgID)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// CreatedAtColumn implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).CreatedAtColumn of orgDomain.org.
|
||||
func (orgDomain) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "created_at")
|
||||
}
|
||||
|
||||
// DomainColumn implements [domain.OrganizationDomainRepository].
|
||||
func (orgDomain) DomainColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "domain")
|
||||
}
|
||||
|
||||
// InstanceIDColumn implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).InstanceIDColumn of orgDomain.org.
|
||||
func (orgDomain) InstanceIDColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "instance_id")
|
||||
}
|
||||
|
||||
// IsPrimaryColumn implements [domain.OrganizationDomainRepository].
|
||||
func (orgDomain) IsPrimaryColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "is_primary")
|
||||
}
|
||||
|
||||
// IsVerifiedColumn implements [domain.OrganizationDomainRepository].
|
||||
func (orgDomain) IsVerifiedColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "is_verified")
|
||||
}
|
||||
|
||||
// OrgIDColumn implements [domain.OrganizationDomainRepository].
|
||||
func (orgDomain) OrgIDColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "org_id")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.OrganizationDomainRepository].
|
||||
// Subtle: this method shadows the method ([domain.OrganizationRepository]).UpdatedAtColumn of orgDomain.org.
|
||||
func (orgDomain) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "updated_at")
|
||||
}
|
||||
|
||||
// ValidationTypeColumn implements [domain.OrganizationDomainRepository].
|
||||
func (orgDomain) ValidationTypeColumn() database.Column {
|
||||
return database.NewColumn("org_domains", "validation_type")
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// scanners
|
||||
// -------------------------------------------------------------
|
||||
|
||||
func scanOrganizationDomain(ctx context.Context, client database.Querier, builder *database.StatementBuilder) (*domain.OrganizationDomain, error) {
|
||||
rows, err := client.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
domain := &domain.OrganizationDomain{}
|
||||
if err := rows.(database.CollectableRows).CollectExactlyOneRow(domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return domain, nil
|
||||
}
|
||||
|
||||
func scanOrganizationDomains(ctx context.Context, client database.Querier, builder *database.StatementBuilder) ([]*domain.OrganizationDomain, error) {
|
||||
rows, err := client.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var domains []*domain.OrganizationDomain
|
||||
if err := rows.(database.CollectableRows).Collect(&domains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return domains, nil
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
package repository_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/brianvoe/gofakeit/v6"
|
||||
"github.com/muhlemmer/gu"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/repository"
|
||||
)
|
||||
|
||||
func TestAddOrganizationDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
instanceRepo := repository.InstanceRepository(pool)
|
||||
err := instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
// create organization
|
||||
orgID := gofakeit.UUID()
|
||||
organization := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceID,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
testFunc func(ctx context.Context, t *testing.T, domainRepo domain.OrganizationDomainRepository) *domain.AddOrganizationDomain
|
||||
organizationDomain domain.AddOrganizationDomain
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "happy path",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add verified domain",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: true,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add primary domain",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "add domain without domain name",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: "",
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
err: new(database.CheckError),
|
||||
},
|
||||
{
|
||||
name: "add domain with same domain twice",
|
||||
testFunc: func(ctx context.Context, t *testing.T, domainRepo domain.OrganizationDomainRepository) *domain.AddOrganizationDomain {
|
||||
domainName := gofakeit.DomainName()
|
||||
|
||||
organizationDomain := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName,
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
}
|
||||
|
||||
err := domainRepo.Add(ctx, organizationDomain)
|
||||
require.NoError(t, err)
|
||||
|
||||
// return same domain again
|
||||
return &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
}
|
||||
},
|
||||
err: new(database.UniqueError),
|
||||
},
|
||||
{
|
||||
name: "add domain with non-existent instance",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: "non-existent-instance",
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
{
|
||||
name: "add domain with non-existent organization",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: "non-existent-org",
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
{
|
||||
name: "add domain without instance id",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
{
|
||||
name: "add domain without org id",
|
||||
organizationDomain: domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
err: new(database.ForeignKeyError),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
orgRepo := repository.OrganizationRepository(tx)
|
||||
err = orgRepo.Create(t.Context(), &organization)
|
||||
require.NoError(t, err)
|
||||
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
|
||||
var organizationDomain *domain.AddOrganizationDomain
|
||||
if test.testFunc != nil {
|
||||
organizationDomain = test.testFunc(ctx, t, domainRepo)
|
||||
} else {
|
||||
organizationDomain = &test.organizationDomain
|
||||
}
|
||||
|
||||
err = domainRepo.Add(ctx, organizationDomain)
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, organizationDomain.CreatedAt)
|
||||
assert.NotZero(t, organizationDomain.UpdatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOrganizationDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create organization
|
||||
orgID := gofakeit.UUID()
|
||||
organization := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceID,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRepo := repository.OrganizationRepository(tx)
|
||||
err = orgRepo.Create(t.Context(), &organization)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domains
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
domainName1 := gofakeit.DomainName()
|
||||
domainName2 := gofakeit.DomainName()
|
||||
|
||||
domain1 := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName1,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
}
|
||||
domain2 := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName2,
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), domain1)
|
||||
require.NoError(t, err)
|
||||
err = domainRepo.Add(t.Context(), domain2)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
opts []database.QueryOption
|
||||
expected *domain.OrganizationDomain
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "get primary domain",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsPrimaryCondition(true)),
|
||||
},
|
||||
expected: &domain.OrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName1,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get by domain name",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.DomainCondition(database.TextOperationEqual, domainName2)),
|
||||
},
|
||||
expected: &domain.OrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName2,
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get by org ID",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.OrgIDCondition(orgID)),
|
||||
database.WithCondition(domainRepo.IsPrimaryCondition(true)),
|
||||
},
|
||||
expected: &domain.OrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName1,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get verified domain",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsVerifiedCondition(true)),
|
||||
},
|
||||
expected: &domain.OrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName1,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get non-existent domain",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com")),
|
||||
},
|
||||
err: new(database.NoRowFoundError),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
result, err := domainRepo.Get(ctx, test.opts...)
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected.InstanceID, result.InstanceID)
|
||||
assert.Equal(t, test.expected.OrgID, result.OrgID)
|
||||
assert.Equal(t, test.expected.Domain, result.Domain)
|
||||
assert.Equal(t, test.expected.IsVerified, result.IsVerified)
|
||||
assert.Equal(t, test.expected.IsPrimary, result.IsPrimary)
|
||||
assert.Equal(t, test.expected.ValidationType, result.ValidationType)
|
||||
assert.NotEmpty(t, result.CreatedAt)
|
||||
assert.NotEmpty(t, result.UpdatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestListOrganizationDomains(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create organization
|
||||
orgID := gofakeit.UUID()
|
||||
organization := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceID,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRepo := repository.OrganizationRepository(tx)
|
||||
err = orgRepo.Create(t.Context(), &organization)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add multiple domains
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
domains := []domain.AddOrganizationDomain{
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
},
|
||||
{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: gofakeit.DomainName(),
|
||||
IsVerified: true,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
}
|
||||
|
||||
for i := range domains {
|
||||
err = domainRepo.Add(t.Context(), &domains[i])
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
opts []database.QueryOption
|
||||
expectedCount int
|
||||
}{
|
||||
{
|
||||
name: "list all domains",
|
||||
opts: []database.QueryOption{},
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "list verified domains",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsVerifiedCondition(true)),
|
||||
},
|
||||
expectedCount: 2,
|
||||
},
|
||||
{
|
||||
name: "list primary domains",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.IsPrimaryCondition(true)),
|
||||
},
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "list by organization",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.OrgIDCondition(orgID)),
|
||||
},
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "list by instance",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.InstanceIDCondition(instanceID)),
|
||||
},
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "list non-existent organization",
|
||||
opts: []database.QueryOption{
|
||||
database.WithCondition(domainRepo.OrgIDCondition("non-existent")),
|
||||
},
|
||||
expectedCount: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
results, err := domainRepo.List(ctx, test.opts...)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, results, test.expectedCount)
|
||||
|
||||
for _, result := range results {
|
||||
assert.Equal(t, instanceID, result.InstanceID)
|
||||
assert.Equal(t, orgID, result.OrgID)
|
||||
assert.NotEmpty(t, result.Domain)
|
||||
assert.NotEmpty(t, result.CreatedAt)
|
||||
assert.NotEmpty(t, result.UpdatedAt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateOrganizationDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create organization
|
||||
orgID := gofakeit.UUID()
|
||||
organization := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceID,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRepo := repository.OrganizationRepository(tx)
|
||||
err = orgRepo.Create(t.Context(), &organization)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domain
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
domainName := gofakeit.DomainName()
|
||||
organizationDomain := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName,
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), organizationDomain)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
changes []database.Change
|
||||
expected int64
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "set verified",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{domainRepo.SetVerified()},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "set primary",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{domainRepo.SetPrimary()},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "set validation type",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{domainRepo.SetValidationType(domain.DomainValidationTypeHTTP)},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "multiple changes",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{
|
||||
domainRepo.SetVerified(),
|
||||
domainRepo.SetPrimary(),
|
||||
domainRepo.SetValidationType(domain.DomainValidationTypeDNS),
|
||||
},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "update by org ID and domain",
|
||||
condition: database.And(domainRepo.OrgIDCondition(orgID), domainRepo.DomainCondition(database.TextOperationEqual, domainName)),
|
||||
changes: []database.Change{domainRepo.SetVerified()},
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "update non-existent domain",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com"),
|
||||
changes: []database.Change{domainRepo.SetVerified()},
|
||||
expected: 0,
|
||||
},
|
||||
{
|
||||
name: "no changes",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName),
|
||||
changes: []database.Change{},
|
||||
expected: 0,
|
||||
err: database.ErrNoChanges,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
rowsAffected, err := domainRepo.Update(ctx, test.condition, test.changes...)
|
||||
if test.err != nil {
|
||||
assert.ErrorIs(t, err, test.err)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected, rowsAffected)
|
||||
|
||||
// verify changes were applied if rows were affected
|
||||
if rowsAffected > 0 && len(test.changes) > 0 {
|
||||
result, err := domainRepo.Get(ctx, database.WithCondition(test.condition))
|
||||
require.NoError(t, err)
|
||||
|
||||
// We know changes were applied since rowsAffected > 0
|
||||
// The specific verification of what changed is less important
|
||||
// than knowing the operation succeeded
|
||||
assert.NotNil(t, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveOrganizationDomain(t *testing.T) {
|
||||
// create instance
|
||||
instanceID := gofakeit.UUID()
|
||||
instance := domain.Instance{
|
||||
ID: instanceID,
|
||||
Name: gofakeit.Name(),
|
||||
DefaultOrgID: "defaultOrgId",
|
||||
IAMProjectID: "iamProject",
|
||||
ConsoleClientID: "consoleClient",
|
||||
ConsoleAppID: "consoleApp",
|
||||
DefaultLanguage: "defaultLanguage",
|
||||
}
|
||||
|
||||
// create organization
|
||||
orgID := gofakeit.UUID()
|
||||
organization := domain.Organization{
|
||||
ID: orgID,
|
||||
Name: gofakeit.Name(),
|
||||
InstanceID: instanceID,
|
||||
State: domain.OrgStateActive,
|
||||
}
|
||||
|
||||
tx, err := pool.Begin(t.Context(), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, tx.Rollback(t.Context()))
|
||||
}()
|
||||
|
||||
instanceRepo := repository.InstanceRepository(tx)
|
||||
err = instanceRepo.Create(t.Context(), &instance)
|
||||
require.NoError(t, err)
|
||||
|
||||
orgRepo := repository.OrganizationRepository(tx)
|
||||
err = orgRepo.Create(t.Context(), &organization)
|
||||
require.NoError(t, err)
|
||||
|
||||
// add domains
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
domainName1 := gofakeit.DomainName()
|
||||
domainName2 := gofakeit.DomainName()
|
||||
|
||||
domain1 := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName1,
|
||||
IsVerified: true,
|
||||
IsPrimary: true,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeDNS),
|
||||
}
|
||||
domain2 := &domain.AddOrganizationDomain{
|
||||
InstanceID: instanceID,
|
||||
OrgID: orgID,
|
||||
Domain: domainName2,
|
||||
IsVerified: false,
|
||||
IsPrimary: false,
|
||||
ValidationType: gu.Ptr(domain.DomainValidationTypeHTTP),
|
||||
}
|
||||
|
||||
err = domainRepo.Add(t.Context(), domain1)
|
||||
require.NoError(t, err)
|
||||
err = domainRepo.Add(t.Context(), domain2)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
expected int64
|
||||
}{
|
||||
{
|
||||
name: "remove by domain name",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, domainName1),
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "remove by primary condition",
|
||||
condition: domainRepo.IsPrimaryCondition(false),
|
||||
expected: 1, // domain2 should still exist and be non-primary
|
||||
},
|
||||
{
|
||||
name: "remove by org ID and domain",
|
||||
condition: database.And(domainRepo.OrgIDCondition(orgID), domainRepo.DomainCondition(database.TextOperationEqual, domainName2)),
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "remove non-existent domain",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "non-existent.com"),
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
snapshot, err := tx.Begin(ctx)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, snapshot.Rollback(ctx))
|
||||
}()
|
||||
|
||||
orgRepo := repository.OrganizationRepository(snapshot)
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
|
||||
// count before removal
|
||||
beforeCount, err := domainRepo.List(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
rowsAffected, err := domainRepo.Remove(ctx, test.condition)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected, rowsAffected)
|
||||
|
||||
// verify removal
|
||||
afterCount, err := domainRepo.List(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, len(beforeCount)-int(test.expected), len(afterCount))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationDomainConditions(t *testing.T) {
|
||||
orgRepo := repository.OrganizationRepository(pool)
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
condition database.Condition
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "domain condition equal",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationEqual, "example.com"),
|
||||
expected: "org_domains.domain = $1",
|
||||
},
|
||||
{
|
||||
name: "domain condition starts with",
|
||||
condition: domainRepo.DomainCondition(database.TextOperationStartsWith, "example"),
|
||||
expected: "org_domains.domain LIKE $1 || '%'",
|
||||
},
|
||||
{
|
||||
name: "instance id condition",
|
||||
condition: domainRepo.InstanceIDCondition("instance-123"),
|
||||
expected: "org_domains.instance_id = $1",
|
||||
},
|
||||
{
|
||||
name: "org id condition",
|
||||
condition: domainRepo.OrgIDCondition("org-123"),
|
||||
expected: "org_domains.org_id = $1",
|
||||
},
|
||||
{
|
||||
name: "is primary true",
|
||||
condition: domainRepo.IsPrimaryCondition(true),
|
||||
expected: "org_domains.is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "is primary false",
|
||||
condition: domainRepo.IsPrimaryCondition(false),
|
||||
expected: "org_domains.is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "is verified true",
|
||||
condition: domainRepo.IsVerifiedCondition(true),
|
||||
expected: "org_domains.is_verified = $1",
|
||||
},
|
||||
{
|
||||
name: "is verified false",
|
||||
condition: domainRepo.IsVerifiedCondition(false),
|
||||
expected: "org_domains.is_verified = $1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var builder database.StatementBuilder
|
||||
test.condition.Write(&builder)
|
||||
assert.Equal(t, test.expected, builder.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationDomainChanges(t *testing.T) {
|
||||
orgRepo := repository.OrganizationRepository(pool)
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
change database.Change
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "set verified",
|
||||
change: domainRepo.SetVerified(),
|
||||
expected: "is_verified = $1",
|
||||
},
|
||||
{
|
||||
name: "set primary",
|
||||
change: domainRepo.SetPrimary(),
|
||||
expected: "is_primary = $1",
|
||||
},
|
||||
{
|
||||
name: "set validation type DNS",
|
||||
change: domainRepo.SetValidationType(domain.DomainValidationTypeDNS),
|
||||
expected: "validation_type = $1",
|
||||
},
|
||||
{
|
||||
name: "set validation type HTTP",
|
||||
change: domainRepo.SetValidationType(domain.DomainValidationTypeHTTP),
|
||||
expected: "validation_type = $1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var builder database.StatementBuilder
|
||||
test.change.Write(&builder)
|
||||
assert.Equal(t, test.expected, builder.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationDomainColumns(t *testing.T) {
|
||||
orgRepo := repository.OrganizationRepository(pool)
|
||||
domainRepo := orgRepo.Domains(false)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
column database.Column
|
||||
qualified bool
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "instance id column qualified",
|
||||
column: domainRepo.InstanceIDColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.instance_id",
|
||||
},
|
||||
{
|
||||
name: "instance id column unqualified",
|
||||
column: domainRepo.InstanceIDColumn(),
|
||||
qualified: false,
|
||||
expected: "instance_id",
|
||||
},
|
||||
{
|
||||
name: "org id column qualified",
|
||||
column: domainRepo.OrgIDColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.org_id",
|
||||
},
|
||||
{
|
||||
name: "org id column unqualified",
|
||||
column: domainRepo.OrgIDColumn(),
|
||||
qualified: false,
|
||||
expected: "org_id",
|
||||
},
|
||||
{
|
||||
name: "domain column qualified",
|
||||
column: domainRepo.DomainColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.domain",
|
||||
},
|
||||
{
|
||||
name: "domain column unqualified",
|
||||
column: domainRepo.DomainColumn(),
|
||||
qualified: false,
|
||||
expected: "domain",
|
||||
},
|
||||
{
|
||||
name: "is verified column qualified",
|
||||
column: domainRepo.IsVerifiedColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.is_verified",
|
||||
},
|
||||
{
|
||||
name: "is verified column unqualified",
|
||||
column: domainRepo.IsVerifiedColumn(),
|
||||
qualified: false,
|
||||
expected: "is_verified",
|
||||
},
|
||||
{
|
||||
name: "is primary column qualified",
|
||||
column: domainRepo.IsPrimaryColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.is_primary",
|
||||
},
|
||||
{
|
||||
name: "is primary column unqualified",
|
||||
column: domainRepo.IsPrimaryColumn(),
|
||||
qualified: false,
|
||||
expected: "is_primary",
|
||||
},
|
||||
{
|
||||
name: "validation type column qualified",
|
||||
column: domainRepo.ValidationTypeColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.validation_type",
|
||||
},
|
||||
{
|
||||
name: "validation type column unqualified",
|
||||
column: domainRepo.ValidationTypeColumn(),
|
||||
qualified: false,
|
||||
expected: "validation_type",
|
||||
},
|
||||
{
|
||||
name: "created at column qualified",
|
||||
column: domainRepo.CreatedAtColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.created_at",
|
||||
},
|
||||
{
|
||||
name: "created at column unqualified",
|
||||
column: domainRepo.CreatedAtColumn(),
|
||||
qualified: false,
|
||||
expected: "created_at",
|
||||
},
|
||||
{
|
||||
name: "updated at column qualified",
|
||||
column: domainRepo.UpdatedAtColumn(),
|
||||
qualified: true,
|
||||
expected: "org_domains.updated_at",
|
||||
},
|
||||
{
|
||||
name: "updated at column unqualified",
|
||||
column: domainRepo.UpdatedAtColumn(),
|
||||
qualified: false,
|
||||
expected: "updated_at",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var builder database.StatementBuilder
|
||||
if test.qualified {
|
||||
test.column.WriteQualified(&builder)
|
||||
} else {
|
||||
test.column.WriteUnqualified(&builder)
|
||||
}
|
||||
assert.Equal(t, test.expected, builder.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
)
|
||||
|
||||
type orgMember struct {
|
||||
*org
|
||||
}
|
||||
|
||||
// AddMember implements [domain.MemberRepository].
|
||||
func (o *orgMember) AddMember(ctx context.Context, orgID string, userID string, roles []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveMember implements [domain.MemberRepository].
|
||||
func (o *orgMember) RemoveMember(ctx context.Context, orgID string, userID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMemberRoles implements [domain.MemberRepository].
|
||||
func (o *orgMember) SetMemberRoles(ctx context.Context, orgID string, userID string, roles []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ domain.MemberRepository = (*orgMember)(nil)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client database.QueryExecutor
|
||||
}
|
||||
|
||||
func writeCondition(
|
||||
builder *database.StatementBuilder,
|
||||
condition database.Condition,
|
||||
) {
|
||||
if condition == nil {
|
||||
return
|
||||
}
|
||||
builder.WriteString(" WHERE ")
|
||||
condition.Write(builder)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package repository_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database/dialect/postgres/embedded"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
os.Exit(runTests(m))
|
||||
}
|
||||
|
||||
var pool database.PoolTest
|
||||
|
||||
func runTests(m *testing.M) int {
|
||||
var stop func()
|
||||
var err error
|
||||
ctx := context.Background()
|
||||
pool, stop, err = newEmbeddedDB(ctx)
|
||||
if err != nil {
|
||||
log.Printf("error with embedded postgres database: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer stop()
|
||||
|
||||
return m.Run()
|
||||
}
|
||||
|
||||
func newEmbeddedDB(ctx context.Context) (pool database.PoolTest, stop func(), err error) {
|
||||
connector, stop, err := embedded.StartEmbedded()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("unable to start embedded postgres: %w", err)
|
||||
}
|
||||
|
||||
pool_, err := connector.Connect(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("unable to connect to embedded postgres: %w", err)
|
||||
}
|
||||
pool = pool_.(database.PoolTest)
|
||||
|
||||
err = pool.MigrateTest(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("unable to migrate database: %w", err)
|
||||
}
|
||||
return pool, stop, err
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
const queryUserStmt = `SELECT instance_id, org_id, id, username, type, created_at, updated_at, deleted_at,` +
|
||||
` first_name, last_name, email_address, email_verified_at, phone_number, phone_verified_at, description` +
|
||||
` FROM users_view users`
|
||||
|
||||
type user struct {
|
||||
repository
|
||||
}
|
||||
|
||||
func UserRepository(client database.QueryExecutor) domain.UserRepository {
|
||||
return &user{
|
||||
repository: repository{
|
||||
client: client,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
var _ domain.UserRepository = (*user)(nil)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// Human implements [domain.UserRepository].
|
||||
func (u *user) Human() domain.HumanRepository {
|
||||
return &userHuman{user: u}
|
||||
}
|
||||
|
||||
// Machine implements [domain.UserRepository].
|
||||
func (u *user) Machine() domain.MachineRepository {
|
||||
return &userMachine{user: u}
|
||||
}
|
||||
|
||||
// List implements [domain.UserRepository].
|
||||
func (u *user) List(ctx context.Context, opts ...database.QueryOption) (users []*domain.User, err error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(queryUserStmt)
|
||||
options.WriteCondition(&builder)
|
||||
options.WriteOrderBy(&builder)
|
||||
options.WriteLimit(&builder)
|
||||
options.WriteOffset(&builder)
|
||||
|
||||
rows, err := u.client.Query(ctx, builder.String(), builder.Args()...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = closeErr
|
||||
}()
|
||||
for rows.Next() {
|
||||
user, err := scanUser(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// Get implements [domain.UserRepository].
|
||||
func (u *user) Get(ctx context.Context, opts ...database.QueryOption) (*domain.User, error) {
|
||||
options := new(database.QueryOpts)
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(queryUserStmt)
|
||||
options.WriteCondition(&builder)
|
||||
options.WriteOrderBy(&builder)
|
||||
options.WriteLimit(&builder)
|
||||
options.WriteOffset(&builder)
|
||||
|
||||
return scanUser(u.client.QueryRow(ctx, builder.String(), builder.Args()...))
|
||||
}
|
||||
|
||||
const (
|
||||
createHumanStmt = `INSERT INTO human_users (instance_id, org_id, user_id, username, first_name, last_name, email_address, email_verified_at, phone_number, phone_verified_at)` +
|
||||
` VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)` +
|
||||
` RETURNING created_at, updated_at`
|
||||
createMachineStmt = `INSERT INTO user_machines (instance_id, org_id, user_id, username, description)` +
|
||||
` VALUES ($1, $2, $3, $4, $5)` +
|
||||
` RETURNING created_at, updated_at`
|
||||
)
|
||||
|
||||
// Create implements [domain.UserRepository].
|
||||
func (u *user) Create(ctx context.Context, user *domain.User) error {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.AppendArgs(user.InstanceID, user.OrgID, user.ID, user.Username, user.Traits.Type())
|
||||
switch trait := user.Traits.(type) {
|
||||
case *domain.Human:
|
||||
builder.WriteString(createHumanStmt)
|
||||
builder.AppendArgs(trait.FirstName, trait.LastName, trait.Email.Address, trait.Email.VerifiedAt, trait.Phone.Number, trait.Phone.VerifiedAt)
|
||||
case *domain.Machine:
|
||||
builder.WriteString(createMachineStmt)
|
||||
builder.AppendArgs(trait.Description)
|
||||
}
|
||||
return u.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(&user.CreatedAt, &user.UpdatedAt)
|
||||
}
|
||||
|
||||
// Delete implements [domain.UserRepository].
|
||||
func (u *user) Delete(ctx context.Context, condition database.Condition) error {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString("DELETE FROM users")
|
||||
writeCondition(&builder, condition)
|
||||
_, err := u.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
return err
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetUsername implements [domain.userChanges].
|
||||
func (u user) SetUsername(username string) database.Change {
|
||||
return database.NewChange(u.UsernameColumn(), username)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// InstanceIDCondition implements [domain.userConditions].
|
||||
func (u user) InstanceIDCondition(instanceID string) database.Condition {
|
||||
return database.NewTextCondition(u.InstanceIDColumn(), database.TextOperationEqual, instanceID)
|
||||
}
|
||||
|
||||
// OrgIDCondition implements [domain.userConditions].
|
||||
func (u user) OrgIDCondition(orgID string) database.Condition {
|
||||
return database.NewTextCondition(u.OrgIDColumn(), database.TextOperationEqual, orgID)
|
||||
}
|
||||
|
||||
// IDCondition implements [domain.userConditions].
|
||||
func (u user) IDCondition(userID string) database.Condition {
|
||||
return database.NewTextCondition(u.IDColumn(), database.TextOperationEqual, userID)
|
||||
}
|
||||
|
||||
// UsernameCondition implements [domain.userConditions].
|
||||
func (u user) UsernameCondition(op database.TextOperation, username string) database.Condition {
|
||||
return database.NewTextCondition(u.UsernameColumn(), op, username)
|
||||
}
|
||||
|
||||
// CreatedAtCondition implements [domain.userConditions].
|
||||
func (u user) CreatedAtCondition(op database.NumberOperation, createdAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(u.CreatedAtColumn(), op, createdAt)
|
||||
}
|
||||
|
||||
// UpdatedAtCondition implements [domain.userConditions].
|
||||
func (u user) UpdatedAtCondition(op database.NumberOperation, updatedAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(u.UpdatedAtColumn(), op, updatedAt)
|
||||
}
|
||||
|
||||
// DeletedCondition implements [domain.userConditions].
|
||||
func (u user) DeletedCondition(isDeleted bool) database.Condition {
|
||||
if isDeleted {
|
||||
return database.IsNotNull(u.DeletedAtColumn())
|
||||
}
|
||||
return database.IsNull(u.DeletedAtColumn())
|
||||
}
|
||||
|
||||
// DeletedAtCondition implements [domain.userConditions].
|
||||
func (u user) DeletedAtCondition(op database.NumberOperation, deletedAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(u.DeletedAtColumn(), op, deletedAt)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// InstanceIDColumn implements [domain.userColumns].
|
||||
func (user) InstanceIDColumn() database.Column {
|
||||
return database.NewColumn("users", "instance_id")
|
||||
}
|
||||
|
||||
// OrgIDColumn implements [domain.userColumns].
|
||||
func (user) OrgIDColumn() database.Column {
|
||||
return database.NewColumn("users", "org_id")
|
||||
}
|
||||
|
||||
// IDColumn implements [domain.userColumns].
|
||||
func (user) IDColumn() database.Column {
|
||||
return database.NewColumn("users", "id")
|
||||
}
|
||||
|
||||
// UsernameColumn implements [domain.userColumns].
|
||||
func (user) UsernameColumn() database.Column {
|
||||
return database.NewColumn("users", "username")
|
||||
}
|
||||
|
||||
// FirstNameColumn implements [domain.userColumns].
|
||||
func (user) CreatedAtColumn() database.Column {
|
||||
return database.NewColumn("users", "created_at")
|
||||
}
|
||||
|
||||
// UpdatedAtColumn implements [domain.userColumns].
|
||||
func (user) UpdatedAtColumn() database.Column {
|
||||
return database.NewColumn("users", "updated_at")
|
||||
}
|
||||
|
||||
// DeletedAtColumn implements [domain.userColumns].
|
||||
func (user) DeletedAtColumn() database.Column {
|
||||
return database.NewColumn("users", "deleted_at")
|
||||
}
|
||||
|
||||
func (u user) columns() database.Columns {
|
||||
return database.Columns{
|
||||
u.InstanceIDColumn(),
|
||||
u.OrgIDColumn(),
|
||||
u.IDColumn(),
|
||||
u.UsernameColumn(),
|
||||
u.CreatedAtColumn(),
|
||||
u.UpdatedAtColumn(),
|
||||
u.DeletedAtColumn(),
|
||||
}
|
||||
}
|
||||
|
||||
func scanUser(scanner database.Scanner) (*domain.User, error) {
|
||||
var (
|
||||
user domain.User
|
||||
human domain.Human
|
||||
email domain.Email
|
||||
phone domain.Phone
|
||||
machine domain.Machine
|
||||
typ domain.UserType
|
||||
)
|
||||
err := scanner.Scan(
|
||||
&user.InstanceID,
|
||||
&user.OrgID,
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&typ,
|
||||
&user.CreatedAt,
|
||||
&user.UpdatedAt,
|
||||
&user.DeletedAt,
|
||||
&human.FirstName,
|
||||
&human.LastName,
|
||||
&email.Address,
|
||||
&email.VerifiedAt,
|
||||
&phone.Number,
|
||||
&phone.VerifiedAt,
|
||||
&machine.Description,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch typ {
|
||||
case domain.UserTypeHuman:
|
||||
if email.Address != "" {
|
||||
human.Email = &email
|
||||
}
|
||||
if phone.Number != "" {
|
||||
human.Phone = &phone
|
||||
}
|
||||
user.Traits = &human
|
||||
case domain.UserTypeMachine:
|
||||
user.Traits = &machine
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
type userHuman struct {
|
||||
*user
|
||||
}
|
||||
|
||||
var _ domain.HumanRepository = (*userHuman)(nil)
|
||||
|
||||
const userEmailQuery = `SELECT h.email_address, h.email_verified_at FROM user_humans h`
|
||||
|
||||
// GetEmail implements [domain.HumanRepository].
|
||||
func (u *userHuman) GetEmail(ctx context.Context, condition database.Condition) (*domain.Email, error) {
|
||||
var email domain.Email
|
||||
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(userEmailQuery)
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
err := u.client.QueryRow(ctx, builder.String(), builder.Args()...).Scan(
|
||||
&email.Address,
|
||||
&email.VerifiedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &email, nil
|
||||
}
|
||||
|
||||
// Update implements [domain.HumanRepository].
|
||||
func (h userHuman) Update(ctx context.Context, condition database.Condition, changes ...database.Change) error {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(`UPDATE human_users SET `)
|
||||
database.Changes(changes).Write(&builder)
|
||||
writeCondition(&builder, condition)
|
||||
|
||||
stmt := builder.String()
|
||||
|
||||
_, err := h.client.Exec(ctx, stmt, builder.Args()...)
|
||||
return err
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetFirstName implements [domain.humanChanges].
|
||||
func (h userHuman) SetFirstName(firstName string) database.Change {
|
||||
return database.NewChange(h.FirstNameColumn(), firstName)
|
||||
}
|
||||
|
||||
// SetLastName implements [domain.humanChanges].
|
||||
func (h userHuman) SetLastName(lastName string) database.Change {
|
||||
return database.NewChange(h.LastNameColumn(), lastName)
|
||||
}
|
||||
|
||||
// SetEmail implements [domain.humanChanges].
|
||||
func (h userHuman) SetEmail(address string, verified *time.Time) database.Change {
|
||||
return database.NewChanges(
|
||||
h.SetEmailAddress(address),
|
||||
database.NewChangePtr(h.EmailVerifiedAtColumn(), verified),
|
||||
)
|
||||
}
|
||||
|
||||
// SetEmailAddress implements [domain.humanChanges].
|
||||
func (h userHuman) SetEmailAddress(address string) database.Change {
|
||||
return database.NewChange(h.EmailAddressColumn(), address)
|
||||
}
|
||||
|
||||
// SetEmailVerifiedAt implements [domain.humanChanges].
|
||||
func (h userHuman) SetEmailVerifiedAt(at time.Time) database.Change {
|
||||
if at.IsZero() {
|
||||
return database.NewChange(h.EmailVerifiedAtColumn(), database.NowInstruction)
|
||||
}
|
||||
return database.NewChange(h.EmailVerifiedAtColumn(), at)
|
||||
}
|
||||
|
||||
// SetPhone implements [domain.humanChanges].
|
||||
func (h userHuman) SetPhone(number string, verifiedAt *time.Time) database.Change {
|
||||
return database.NewChanges(
|
||||
h.SetPhoneNumber(number),
|
||||
database.NewChangePtr(h.PhoneVerifiedAtColumn(), verifiedAt),
|
||||
)
|
||||
}
|
||||
|
||||
// SetPhoneNumber implements [domain.humanChanges].
|
||||
func (h userHuman) SetPhoneNumber(number string) database.Change {
|
||||
return database.NewChange(h.PhoneNumberColumn(), number)
|
||||
}
|
||||
|
||||
// SetPhoneVerifiedAt implements [domain.humanChanges].
|
||||
func (h userHuman) SetPhoneVerifiedAt(at time.Time) database.Change {
|
||||
if at.IsZero() {
|
||||
return database.NewChange(h.PhoneVerifiedAtColumn(), database.NowInstruction)
|
||||
}
|
||||
return database.NewChange(h.PhoneVerifiedAtColumn(), at)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// FirstNameCondition implements [domain.humanConditions].
|
||||
func (h userHuman) FirstNameCondition(op database.TextOperation, firstName string) database.Condition {
|
||||
return database.NewTextCondition(h.FirstNameColumn(), op, firstName)
|
||||
}
|
||||
|
||||
// LastNameCondition implements [domain.humanConditions].
|
||||
func (h userHuman) LastNameCondition(op database.TextOperation, lastName string) database.Condition {
|
||||
return database.NewTextCondition(h.LastNameColumn(), op, lastName)
|
||||
}
|
||||
|
||||
// EmailAddressCondition implements [domain.humanConditions].
|
||||
func (h userHuman) EmailAddressCondition(op database.TextOperation, email string) database.Condition {
|
||||
return database.NewTextCondition(h.EmailAddressColumn(), op, email)
|
||||
}
|
||||
|
||||
// EmailVerifiedCondition implements [domain.humanConditions].
|
||||
func (h *userHuman) EmailVerifiedCondition(isVerified bool) database.Condition {
|
||||
if isVerified {
|
||||
return database.IsNotNull(h.EmailVerifiedAtColumn())
|
||||
}
|
||||
return database.IsNull(h.EmailVerifiedAtColumn())
|
||||
}
|
||||
|
||||
// EmailVerifiedAtCondition implements [domain.humanConditions].
|
||||
func (h userHuman) EmailVerifiedAtCondition(op database.NumberOperation, verifiedAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(h.EmailVerifiedAtColumn(), op, verifiedAt)
|
||||
}
|
||||
|
||||
// PhoneNumberCondition implements [domain.humanConditions].
|
||||
func (h userHuman) PhoneNumberCondition(op database.TextOperation, phoneNumber string) database.Condition {
|
||||
return database.NewTextCondition(h.PhoneNumberColumn(), op, phoneNumber)
|
||||
}
|
||||
|
||||
// PhoneVerifiedCondition implements [domain.humanConditions].
|
||||
func (h userHuman) PhoneVerifiedCondition(isVerified bool) database.Condition {
|
||||
if isVerified {
|
||||
return database.IsNotNull(h.PhoneVerifiedAtColumn())
|
||||
}
|
||||
return database.IsNull(h.PhoneVerifiedAtColumn())
|
||||
}
|
||||
|
||||
// PhoneVerifiedAtCondition implements [domain.humanConditions].
|
||||
func (h userHuman) PhoneVerifiedAtCondition(op database.NumberOperation, verifiedAt time.Time) database.Condition {
|
||||
return database.NewNumberCondition(h.PhoneVerifiedAtColumn(), op, verifiedAt)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// FirstNameColumn implements [domain.humanColumns].
|
||||
func (h userHuman) FirstNameColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "first_name")
|
||||
}
|
||||
|
||||
// LastNameColumn implements [domain.humanColumns].
|
||||
func (h userHuman) LastNameColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "last_name")
|
||||
}
|
||||
|
||||
// EmailAddressColumn implements [domain.humanColumns].
|
||||
func (h userHuman) EmailAddressColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "email_address")
|
||||
}
|
||||
|
||||
// EmailVerifiedAtColumn implements [domain.humanColumns].
|
||||
func (h userHuman) EmailVerifiedAtColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "email_verified_at")
|
||||
}
|
||||
|
||||
// PhoneNumberColumn implements [domain.humanColumns].
|
||||
func (h userHuman) PhoneNumberColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "phone_number")
|
||||
}
|
||||
|
||||
// PhoneVerifiedAtColumn implements [domain.humanColumns].
|
||||
func (h userHuman) PhoneVerifiedAtColumn() database.Column {
|
||||
return database.NewColumn("user_humans", "phone_verified_at")
|
||||
}
|
||||
|
||||
// func (h userHuman) columns() database.Columns {
|
||||
// return append(h.user.columns(),
|
||||
// h.FirstNameColumn(),
|
||||
// h.LastNameColumn(),
|
||||
// h.EmailAddressColumn(),
|
||||
// h.EmailVerifiedAtColumn(),
|
||||
// h.PhoneNumberColumn(),
|
||||
// h.PhoneVerifiedAtColumn(),
|
||||
// )
|
||||
// }
|
||||
|
||||
// func (h userHuman) writeReturning(builder *database.StatementBuilder) {
|
||||
// builder.WriteString(" RETURNING ")
|
||||
// h.columns().Write(builder)
|
||||
// }
|
||||
@@ -0,0 +1,67 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/zitadel/zitadel/backend/v3/domain"
|
||||
"github.com/zitadel/zitadel/backend/v3/storage/database"
|
||||
)
|
||||
|
||||
type userMachine struct {
|
||||
*user
|
||||
}
|
||||
|
||||
var _ domain.MachineRepository = (*userMachine)(nil)
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// repository
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// Update implements [domain.MachineRepository].
|
||||
func (m userMachine) Update(ctx context.Context, condition database.Condition, changes ...database.Change) error {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString("UPDATE user_machines SET ")
|
||||
database.Changes(changes).Write(&builder)
|
||||
writeCondition(&builder, condition)
|
||||
m.writeReturning()
|
||||
|
||||
_, err := m.client.Exec(ctx, builder.String(), builder.Args()...)
|
||||
return err
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// changes
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// SetDescription implements [domain.machineChanges].
|
||||
func (m userMachine) SetDescription(description string) database.Change {
|
||||
return database.NewChange(m.DescriptionColumn(), description)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// conditions
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// DescriptionCondition implements [domain.machineConditions].
|
||||
func (m userMachine) DescriptionCondition(op database.TextOperation, description string) database.Condition {
|
||||
return database.NewTextCondition(m.DescriptionColumn(), op, description)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// columns
|
||||
// -------------------------------------------------------------
|
||||
|
||||
// DescriptionColumn implements [domain.machineColumns].
|
||||
func (m userMachine) DescriptionColumn() database.Column {
|
||||
return database.NewColumn("user_machines", "description")
|
||||
}
|
||||
|
||||
func (m userMachine) columns() database.Columns {
|
||||
return append(m.user.columns(), m.DescriptionColumn())
|
||||
}
|
||||
|
||||
func (m *userMachine) writeReturning() {
|
||||
builder := database.StatementBuilder{}
|
||||
builder.WriteString(" RETURNING ")
|
||||
m.columns().WriteQualified(&builder)
|
||||
}
|
||||
Reference in New Issue
Block a user