// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package models

import (
	"context"
	"fmt"
	"io"
	"time"

	"github.com/Gleipnir-Technology/bob"
	"github.com/Gleipnir-Technology/bob/dialect/psql"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
	"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
	"github.com/Gleipnir-Technology/bob/dialect/psql/um"
	"github.com/Gleipnir-Technology/bob/expr"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/null"
	"github.com/aarondl/opt/omit"
	"github.com/aarondl/opt/omitnull"
	enums "source.gleipnir.technology/Gleipnir/nidus-sync/db/enums"
)

// ReviewTask is an object representing the database table.
type ReviewTask struct {
	Created        time.Time                                `db:"created" `
	CreatorID      null.Val[int32]                          `db:"creator_id" `
	ID             int32                                    `db:"id,pk" `
	OrganizationID int32                                    `db:"organization_id" `
	Reviewed       null.Val[time.Time]                      `db:"reviewed" `
	ReviewerID     null.Val[int32]                          `db:"reviewer_id" `
	Resolution     null.Val[enums.Reviewtaskresolutiontype] `db:"resolution" `

	R reviewTaskR `db:"-" `
}

// ReviewTaskSlice is an alias for a slice of pointers to ReviewTask.
// This should almost always be used instead of []*ReviewTask.
type ReviewTaskSlice []*ReviewTask

// ReviewTasks contains methods to work with the review_task table
var ReviewTasks = psql.NewTablex[*ReviewTask, ReviewTaskSlice, *ReviewTaskSetter]("", "review_task", buildReviewTaskColumns("review_task"))

// ReviewTasksQuery is a query on the review_task table
type ReviewTasksQuery = *psql.ViewQuery[*ReviewTask, ReviewTaskSlice]

// reviewTaskR is where relationships are stored.
type reviewTaskR struct {
	CreatorUser    *User           // review_task.review_task_creator_id_fkey
	Organization   *Organization   // review_task.review_task_organization_id_fkey
	ReviewerUser   *User           // review_task.review_task_reviewer_id_fkey
	ReviewTaskPool *ReviewTaskPool // review_task_pool.review_task_pool_review_task_id_fkey
}

func buildReviewTaskColumns(alias string) reviewTaskColumns {
	return reviewTaskColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator_id", "id", "organization_id", "reviewed", "reviewer_id", "resolution",
		).WithParent("review_task"),
		tableAlias:     alias,
		Created:        psql.Quote(alias, "created"),
		CreatorID:      psql.Quote(alias, "creator_id"),
		ID:             psql.Quote(alias, "id"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		Reviewed:       psql.Quote(alias, "reviewed"),
		ReviewerID:     psql.Quote(alias, "reviewer_id"),
		Resolution:     psql.Quote(alias, "resolution"),
	}
}

type reviewTaskColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Created        psql.Expression
	CreatorID      psql.Expression
	ID             psql.Expression
	OrganizationID psql.Expression
	Reviewed       psql.Expression
	ReviewerID     psql.Expression
	Resolution     psql.Expression
}

func (c reviewTaskColumns) Alias() string {
	return c.tableAlias
}

func (reviewTaskColumns) AliasedAs(alias string) reviewTaskColumns {
	return buildReviewTaskColumns(alias)
}

// ReviewTaskSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ReviewTaskSetter struct {
	Created        omit.Val[time.Time]                          `db:"created" `
	CreatorID      omitnull.Val[int32]                          `db:"creator_id" `
	ID             omit.Val[int32]                              `db:"id,pk" `
	OrganizationID omit.Val[int32]                              `db:"organization_id" `
	Reviewed       omitnull.Val[time.Time]                      `db:"reviewed" `
	ReviewerID     omitnull.Val[int32]                          `db:"reviewer_id" `
	Resolution     omitnull.Val[enums.Reviewtaskresolutiontype] `db:"resolution" `
}

func (s ReviewTaskSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if !s.CreatorID.IsUnset() {
		vals = append(vals, "creator_id")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if !s.Reviewed.IsUnset() {
		vals = append(vals, "reviewed")
	}
	if !s.ReviewerID.IsUnset() {
		vals = append(vals, "reviewer_id")
	}
	if !s.Resolution.IsUnset() {
		vals = append(vals, "resolution")
	}
	return vals
}

func (s ReviewTaskSetter) Overwrite(t *ReviewTask) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if !s.CreatorID.IsUnset() {
		t.CreatorID = s.CreatorID.MustGetNull()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if !s.Reviewed.IsUnset() {
		t.Reviewed = s.Reviewed.MustGetNull()
	}
	if !s.ReviewerID.IsUnset() {
		t.ReviewerID = s.ReviewerID.MustGetNull()
	}
	if !s.Resolution.IsUnset() {
		t.Resolution = s.Resolution.MustGetNull()
	}
}

func (s *ReviewTaskSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return ReviewTasks.BeforeInsertHooks.RunHooks(ctx, exec, s)
	})

	q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		vals := make([]bob.Expression, 7)
		if s.Created.IsValue() {
			vals[0] = psql.Arg(s.Created.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

		if !s.CreatorID.IsUnset() {
			vals[1] = psql.Arg(s.CreatorID.MustGetNull())
		} else {
			vals[1] = psql.Raw("DEFAULT")
		}

		if s.ID.IsValue() {
			vals[2] = psql.Arg(s.ID.MustGet())
		} else {
			vals[2] = psql.Raw("DEFAULT")
		}

		if s.OrganizationID.IsValue() {
			vals[3] = psql.Arg(s.OrganizationID.MustGet())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

		if !s.Reviewed.IsUnset() {
			vals[4] = psql.Arg(s.Reviewed.MustGetNull())
		} else {
			vals[4] = psql.Raw("DEFAULT")
		}

		if !s.ReviewerID.IsUnset() {
			vals[5] = psql.Arg(s.ReviewerID.MustGetNull())
		} else {
			vals[5] = psql.Raw("DEFAULT")
		}

		if !s.Resolution.IsUnset() {
			vals[6] = psql.Arg(s.Resolution.MustGetNull())
		} else {
			vals[6] = psql.Raw("DEFAULT")
		}

		return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
	}))
}

func (s ReviewTaskSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return um.Set(s.Expressions()...)
}

func (s ReviewTaskSetter) Expressions(prefix ...string) []bob.Expression {
	exprs := make([]bob.Expression, 0, 7)

	if s.Created.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "created")...),
			psql.Arg(s.Created),
		}})
	}

	if !s.CreatorID.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "creator_id")...),
			psql.Arg(s.CreatorID),
		}})
	}

	if s.ID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "id")...),
			psql.Arg(s.ID),
		}})
	}

	if s.OrganizationID.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "organization_id")...),
			psql.Arg(s.OrganizationID),
		}})
	}

	if !s.Reviewed.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "reviewed")...),
			psql.Arg(s.Reviewed),
		}})
	}

	if !s.ReviewerID.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "reviewer_id")...),
			psql.Arg(s.ReviewerID),
		}})
	}

	if !s.Resolution.IsUnset() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "resolution")...),
			psql.Arg(s.Resolution),
		}})
	}

	return exprs
}

// FindReviewTask retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindReviewTask(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*ReviewTask, error) {
	if len(cols) == 0 {
		return ReviewTasks.Query(
			sm.Where(ReviewTasks.Columns.ID.EQ(psql.Arg(IDPK))),
		).One(ctx, exec)
	}

	return ReviewTasks.Query(
		sm.Where(ReviewTasks.Columns.ID.EQ(psql.Arg(IDPK))),
		sm.Columns(ReviewTasks.Columns.Only(cols...)),
	).One(ctx, exec)
}

// ReviewTaskExists checks the presence of a single record by primary key
func ReviewTaskExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) {
	return ReviewTasks.Query(
		sm.Where(ReviewTasks.Columns.ID.EQ(psql.Arg(IDPK))),
	).Exists(ctx, exec)
}

// AfterQueryHook is called after ReviewTask is retrieved from the database
func (o *ReviewTask) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ReviewTasks.AfterSelectHooks.RunHooks(ctx, exec, ReviewTaskSlice{o})
	case bob.QueryTypeInsert:
		ctx, err = ReviewTasks.AfterInsertHooks.RunHooks(ctx, exec, ReviewTaskSlice{o})
	case bob.QueryTypeUpdate:
		ctx, err = ReviewTasks.AfterUpdateHooks.RunHooks(ctx, exec, ReviewTaskSlice{o})
	case bob.QueryTypeDelete:
		ctx, err = ReviewTasks.AfterDeleteHooks.RunHooks(ctx, exec, ReviewTaskSlice{o})
	}

	return err
}

// primaryKeyVals returns the primary key values of the ReviewTask
func (o *ReviewTask) primaryKeyVals() bob.Expression {
	return psql.Arg(o.ID)
}

func (o *ReviewTask) pkEQ() dialect.Expression {
	return psql.Quote("review_task", "id").EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
	}))
}

// Update uses an executor to update the ReviewTask
func (o *ReviewTask) Update(ctx context.Context, exec bob.Executor, s *ReviewTaskSetter) error {
	v, err := ReviewTasks.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec)
	if err != nil {
		return err
	}

	o.R = v.R
	*o = *v

	return nil
}

// Delete deletes a single ReviewTask record with an executor
func (o *ReviewTask) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := ReviewTasks.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

// Reload refreshes the ReviewTask using the executor
func (o *ReviewTask) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := ReviewTasks.Query(
		sm.Where(ReviewTasks.Columns.ID.EQ(psql.Arg(o.ID))),
	).One(ctx, exec)
	if err != nil {
		return err
	}
	o2.R = o.R
	*o = *o2

	return nil
}

// AfterQueryHook is called after ReviewTaskSlice is retrieved from the database
func (o ReviewTaskSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

	switch queryType {
	case bob.QueryTypeSelect:
		ctx, err = ReviewTasks.AfterSelectHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeInsert:
		ctx, err = ReviewTasks.AfterInsertHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeUpdate:
		ctx, err = ReviewTasks.AfterUpdateHooks.RunHooks(ctx, exec, o)
	case bob.QueryTypeDelete:
		ctx, err = ReviewTasks.AfterDeleteHooks.RunHooks(ctx, exec, o)
	}

	return err
}

func (o ReviewTaskSlice) pkIN() dialect.Expression {
	if len(o) == 0 {
		return psql.Raw("NULL")
	}

	return psql.Quote("review_task", "id").In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
		pkPairs := make([]bob.Expression, len(o))
		for i, row := range o {
			pkPairs[i] = row.primaryKeyVals()
		}
		return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
	}))
}

// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o ReviewTaskSlice) copyMatchingRows(from ...*ReviewTask) {
	for i, old := range o {
		for _, new := range from {
			if new.ID != old.ID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o ReviewTaskSlice) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
	return bob.ModFunc[*dialect.UpdateQuery](func(q *dialect.UpdateQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return ReviewTasks.BeforeUpdateHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *ReviewTask:
				o.copyMatchingRows(retrieved)
			case []*ReviewTask:
				o.copyMatchingRows(retrieved...)
			case ReviewTaskSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ReviewTask or a slice of ReviewTask
				// then run the AfterUpdateHooks on the slice
				_, err = ReviewTasks.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o ReviewTaskSlice) DeleteMod() bob.Mod[*dialect.DeleteQuery] {
	return bob.ModFunc[*dialect.DeleteQuery](func(q *dialect.DeleteQuery) {
		q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
			return ReviewTasks.BeforeDeleteHooks.RunHooks(ctx, exec, o)
		})

		q.AppendLoader(bob.LoaderFunc(func(ctx context.Context, exec bob.Executor, retrieved any) error {
			var err error
			switch retrieved := retrieved.(type) {
			case *ReviewTask:
				o.copyMatchingRows(retrieved)
			case []*ReviewTask:
				o.copyMatchingRows(retrieved...)
			case ReviewTaskSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ReviewTask or a slice of ReviewTask
				// then run the AfterDeleteHooks on the slice
				_, err = ReviewTasks.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

		q.AppendWhere(o.pkIN())
	})
}

func (o ReviewTaskSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ReviewTaskSetter) error {
	if len(o) == 0 {
		return nil
	}

	_, err := ReviewTasks.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
	return err
}

func (o ReviewTaskSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	_, err := ReviewTasks.Delete(o.DeleteMod()).Exec(ctx, exec)
	return err
}

func (o ReviewTaskSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
	if len(o) == 0 {
		return nil
	}

	o2, err := ReviewTasks.Query(sm.Where(o.pkIN())).All(ctx, exec)
	if err != nil {
		return err
	}

	o.copyMatchingRows(o2...)

	return nil
}

// CreatorUser starts a query for related objects on user_
func (o *ReviewTask) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.CreatorID))),
	)...)
}

func (os ReviewTaskSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkCreatorID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkCreatorID = append(pkCreatorID, o.CreatorID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkCreatorID), "integer[]")),
	))

	return Users.Query(append(mods,
		sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

// Organization starts a query for related objects on organization
func (o *ReviewTask) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

func (os ReviewTaskSlice) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	pkOrganizationID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkOrganizationID = append(pkOrganizationID, o.OrganizationID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkOrganizationID), "integer[]")),
	))

	return Organizations.Query(append(mods,
		sm.Where(psql.Group(Organizations.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

// ReviewerUser starts a query for related objects on user_
func (o *ReviewTask) ReviewerUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.ReviewerID))),
	)...)
}

func (os ReviewTaskSlice) ReviewerUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkReviewerID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkReviewerID = append(pkReviewerID, o.ReviewerID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkReviewerID), "integer[]")),
	))

	return Users.Query(append(mods,
		sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)),
	)...)
}

// ReviewTaskPool starts a query for related objects on review_task_pool
func (o *ReviewTask) ReviewTaskPool(mods ...bob.Mod[*dialect.SelectQuery]) ReviewTaskPoolsQuery {
	return ReviewTaskPools.Query(append(mods,
		sm.Where(ReviewTaskPools.Columns.ReviewTaskID.EQ(psql.Arg(o.ID))),
	)...)
}

func (os ReviewTaskSlice) ReviewTaskPool(mods ...bob.Mod[*dialect.SelectQuery]) ReviewTaskPoolsQuery {
	pkID := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkID = append(pkID, o.ID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")),
	))

	return ReviewTaskPools.Query(append(mods,
		sm.Where(psql.Group(ReviewTaskPools.Columns.ReviewTaskID).OP("IN", PKArgExpr)),
	)...)
}

func attachReviewTaskCreatorUser0(ctx context.Context, exec bob.Executor, count int, reviewTask0 *ReviewTask, user1 *User) (*ReviewTask, error) {
	setter := &ReviewTaskSetter{
		CreatorID: omitnull.From(user1.ID),
	}

	err := reviewTask0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskCreatorUser0: %w", err)
	}

	return reviewTask0, nil
}

func (reviewTask0 *ReviewTask) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

	user1, err := Users.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachReviewTaskCreatorUser0(ctx, exec, 1, reviewTask0, user1)
	if err != nil {
		return err
	}

	reviewTask0.R.CreatorUser = user1

	user1.R.CreatorReviewTasks = append(user1.R.CreatorReviewTasks, reviewTask0)

	return nil
}

func (reviewTask0 *ReviewTask) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachReviewTaskCreatorUser0(ctx, exec, 1, reviewTask0, user1)
	if err != nil {
		return err
	}

	reviewTask0.R.CreatorUser = user1

	user1.R.CreatorReviewTasks = append(user1.R.CreatorReviewTasks, reviewTask0)

	return nil
}

func attachReviewTaskOrganization0(ctx context.Context, exec bob.Executor, count int, reviewTask0 *ReviewTask, organization1 *Organization) (*ReviewTask, error) {
	setter := &ReviewTaskSetter{
		OrganizationID: omit.From(organization1.ID),
	}

	err := reviewTask0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskOrganization0: %w", err)
	}

	return reviewTask0, nil
}

func (reviewTask0 *ReviewTask) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error {
	var err error

	organization1, err := Organizations.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachReviewTaskOrganization0(ctx, exec, 1, reviewTask0, organization1)
	if err != nil {
		return err
	}

	reviewTask0.R.Organization = organization1

	organization1.R.ReviewTasks = append(organization1.R.ReviewTasks, reviewTask0)

	return nil
}

func (reviewTask0 *ReviewTask) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error {
	var err error

	_, err = attachReviewTaskOrganization0(ctx, exec, 1, reviewTask0, organization1)
	if err != nil {
		return err
	}

	reviewTask0.R.Organization = organization1

	organization1.R.ReviewTasks = append(organization1.R.ReviewTasks, reviewTask0)

	return nil
}

func attachReviewTaskReviewerUser0(ctx context.Context, exec bob.Executor, count int, reviewTask0 *ReviewTask, user1 *User) (*ReviewTask, error) {
	setter := &ReviewTaskSetter{
		ReviewerID: omitnull.From(user1.ID),
	}

	err := reviewTask0.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskReviewerUser0: %w", err)
	}

	return reviewTask0, nil
}

func (reviewTask0 *ReviewTask) InsertReviewerUser(ctx context.Context, exec bob.Executor, related *UserSetter) error {
	var err error

	user1, err := Users.Insert(related).One(ctx, exec)
	if err != nil {
		return fmt.Errorf("inserting related objects: %w", err)
	}

	_, err = attachReviewTaskReviewerUser0(ctx, exec, 1, reviewTask0, user1)
	if err != nil {
		return err
	}

	reviewTask0.R.ReviewerUser = user1

	user1.R.ReviewerReviewTasks = append(user1.R.ReviewerReviewTasks, reviewTask0)

	return nil
}

func (reviewTask0 *ReviewTask) AttachReviewerUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

	_, err = attachReviewTaskReviewerUser0(ctx, exec, 1, reviewTask0, user1)
	if err != nil {
		return err
	}

	reviewTask0.R.ReviewerUser = user1

	user1.R.ReviewerReviewTasks = append(user1.R.ReviewerReviewTasks, reviewTask0)

	return nil
}

func insertReviewTaskReviewTaskPool0(ctx context.Context, exec bob.Executor, reviewTaskPool1 *ReviewTaskPoolSetter, reviewTask0 *ReviewTask) (*ReviewTaskPool, error) {
	reviewTaskPool1.ReviewTaskID = omit.From(reviewTask0.ID)

	ret, err := ReviewTaskPools.Insert(reviewTaskPool1).One(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertReviewTaskReviewTaskPool0: %w", err)
	}

	return ret, nil
}

func attachReviewTaskReviewTaskPool0(ctx context.Context, exec bob.Executor, count int, reviewTaskPool1 *ReviewTaskPool, reviewTask0 *ReviewTask) (*ReviewTaskPool, error) {
	setter := &ReviewTaskPoolSetter{
		ReviewTaskID: omit.From(reviewTask0.ID),
	}

	err := reviewTaskPool1.Update(ctx, exec, setter)
	if err != nil {
		return nil, fmt.Errorf("attachReviewTaskReviewTaskPool0: %w", err)
	}

	return reviewTaskPool1, nil
}

func (reviewTask0 *ReviewTask) InsertReviewTaskPool(ctx context.Context, exec bob.Executor, related *ReviewTaskPoolSetter) error {
	var err error

	reviewTaskPool1, err := insertReviewTaskReviewTaskPool0(ctx, exec, related, reviewTask0)
	if err != nil {
		return err
	}

	reviewTask0.R.ReviewTaskPool = reviewTaskPool1

	reviewTaskPool1.R.ReviewTask = reviewTask0

	return nil
}

func (reviewTask0 *ReviewTask) AttachReviewTaskPool(ctx context.Context, exec bob.Executor, reviewTaskPool1 *ReviewTaskPool) error {
	var err error

	_, err = attachReviewTaskReviewTaskPool0(ctx, exec, 1, reviewTaskPool1, reviewTask0)
	if err != nil {
		return err
	}

	reviewTask0.R.ReviewTaskPool = reviewTaskPool1

	reviewTaskPool1.R.ReviewTask = reviewTask0

	return nil
}

type reviewTaskWhere[Q psql.Filterable] struct {
	Created        psql.WhereMod[Q, time.Time]
	CreatorID      psql.WhereNullMod[Q, int32]
	ID             psql.WhereMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
	Reviewed       psql.WhereNullMod[Q, time.Time]
	ReviewerID     psql.WhereNullMod[Q, int32]
	Resolution     psql.WhereNullMod[Q, enums.Reviewtaskresolutiontype]
}

func (reviewTaskWhere[Q]) AliasedAs(alias string) reviewTaskWhere[Q] {
	return buildReviewTaskWhere[Q](buildReviewTaskColumns(alias))
}

func buildReviewTaskWhere[Q psql.Filterable](cols reviewTaskColumns) reviewTaskWhere[Q] {
	return reviewTaskWhere[Q]{
		Created:        psql.Where[Q, time.Time](cols.Created),
		CreatorID:      psql.WhereNull[Q, int32](cols.CreatorID),
		ID:             psql.Where[Q, int32](cols.ID),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		Reviewed:       psql.WhereNull[Q, time.Time](cols.Reviewed),
		ReviewerID:     psql.WhereNull[Q, int32](cols.ReviewerID),
		Resolution:     psql.WhereNull[Q, enums.Reviewtaskresolutiontype](cols.Resolution),
	}
}

func (o *ReviewTask) Preload(name string, retrieved any) error {
	if o == nil {
		return nil
	}

	switch name {
	case "CreatorUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("reviewTask cannot load %T as %q", retrieved, name)
		}

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorReviewTasks = ReviewTaskSlice{o}
		}
		return nil
	case "Organization":
		rel, ok := retrieved.(*Organization)
		if !ok {
			return fmt.Errorf("reviewTask cannot load %T as %q", retrieved, name)
		}

		o.R.Organization = rel

		if rel != nil {
			rel.R.ReviewTasks = ReviewTaskSlice{o}
		}
		return nil
	case "ReviewerUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("reviewTask cannot load %T as %q", retrieved, name)
		}

		o.R.ReviewerUser = rel

		if rel != nil {
			rel.R.ReviewerReviewTasks = ReviewTaskSlice{o}
		}
		return nil
	case "ReviewTaskPool":
		rel, ok := retrieved.(*ReviewTaskPool)
		if !ok {
			return fmt.Errorf("reviewTask cannot load %T as %q", retrieved, name)
		}

		o.R.ReviewTaskPool = rel

		if rel != nil {
			rel.R.ReviewTask = o
		}
		return nil
	default:
		return fmt.Errorf("reviewTask has no relationship %q", name)
	}
}

type reviewTaskPreloader struct {
	CreatorUser    func(...psql.PreloadOption) psql.Preloader
	Organization   func(...psql.PreloadOption) psql.Preloader
	ReviewerUser   func(...psql.PreloadOption) psql.Preloader
	ReviewTaskPool func(...psql.PreloadOption) psql.Preloader
}

func buildReviewTaskPreloader() reviewTaskPreloader {
	return reviewTaskPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTasks,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Organization: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
				Name: "Organization",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTasks,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
		ReviewerUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "ReviewerUser",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTasks,
						To:          Users,
						FromColumns: []string{"reviewer_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		ReviewTaskPool: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*ReviewTaskPool, ReviewTaskPoolSlice](psql.PreloadRel{
				Name: "ReviewTaskPool",
				Sides: []psql.PreloadSide{
					{
						From:        ReviewTasks,
						To:          ReviewTaskPools,
						FromColumns: []string{"id"},
						ToColumns:   []string{"review_task_id"},
					},
				},
			}, ReviewTaskPools.Columns.Names(), opts...)
		},
	}
}

type reviewTaskThenLoader[Q orm.Loadable] struct {
	CreatorUser    func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organization   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReviewerUser   func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	ReviewTaskPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildReviewTaskThenLoader[Q orm.Loadable]() reviewTaskThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReviewerUserLoadInterface interface {
		LoadReviewerUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type ReviewTaskPoolLoadInterface interface {
		LoadReviewTaskPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return reviewTaskThenLoader[Q]{
		CreatorUser: thenLoadBuilder[Q](
			"CreatorUser",
			func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadCreatorUser(ctx, exec, mods...)
			},
		),
		Organization: thenLoadBuilder[Q](
			"Organization",
			func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadOrganization(ctx, exec, mods...)
			},
		),
		ReviewerUser: thenLoadBuilder[Q](
			"ReviewerUser",
			func(ctx context.Context, exec bob.Executor, retrieved ReviewerUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReviewerUser(ctx, exec, mods...)
			},
		),
		ReviewTaskPool: thenLoadBuilder[Q](
			"ReviewTaskPool",
			func(ctx context.Context, exec bob.Executor, retrieved ReviewTaskPoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadReviewTaskPool(ctx, exec, mods...)
			},
		),
	}
}

// LoadCreatorUser loads the reviewTask's CreatorUser into the .R struct
func (o *ReviewTask) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.CreatorUser = nil

	related, err := o.CreatorUser(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.CreatorReviewTasks = ReviewTaskSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the reviewTask's CreatorUser into the .R struct
func (os ReviewTaskSlice) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	users, err := os.CreatorUser(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range users {
			if !o.CreatorID.IsValue() {
				continue
			}

			if !(o.CreatorID.IsValue() && o.CreatorID.MustGet() == rel.ID) {
				continue
			}

			rel.R.CreatorReviewTasks = append(rel.R.CreatorReviewTasks, o)

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

// LoadOrganization loads the reviewTask's Organization into the .R struct
func (o *ReviewTask) LoadOrganization(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.Organization = nil

	related, err := o.Organization(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ReviewTasks = ReviewTaskSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the reviewTask's Organization into the .R struct
func (os ReviewTaskSlice) LoadOrganization(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	organizations, err := os.Organization(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range organizations {

			if !(o.OrganizationID == rel.ID) {
				continue
			}

			rel.R.ReviewTasks = append(rel.R.ReviewTasks, o)

			o.R.Organization = rel
			break
		}
	}

	return nil
}

// LoadReviewerUser loads the reviewTask's ReviewerUser into the .R struct
func (o *ReviewTask) LoadReviewerUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.ReviewerUser = nil

	related, err := o.ReviewerUser(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ReviewerReviewTasks = ReviewTaskSlice{o}

	o.R.ReviewerUser = related
	return nil
}

// LoadReviewerUser loads the reviewTask's ReviewerUser into the .R struct
func (os ReviewTaskSlice) LoadReviewerUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	users, err := os.ReviewerUser(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range users {
			if !o.ReviewerID.IsValue() {
				continue
			}

			if !(o.ReviewerID.IsValue() && o.ReviewerID.MustGet() == rel.ID) {
				continue
			}

			rel.R.ReviewerReviewTasks = append(rel.R.ReviewerReviewTasks, o)

			o.R.ReviewerUser = rel
			break
		}
	}

	return nil
}

// LoadReviewTaskPool loads the reviewTask's ReviewTaskPool into the .R struct
func (o *ReviewTask) LoadReviewTaskPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if o == nil {
		return nil
	}

	// Reset the relationship
	o.R.ReviewTaskPool = nil

	related, err := o.ReviewTaskPool(mods...).One(ctx, exec)
	if err != nil {
		return err
	}

	related.R.ReviewTask = o

	o.R.ReviewTaskPool = related
	return nil
}

// LoadReviewTaskPool loads the reviewTask's ReviewTaskPool into the .R struct
func (os ReviewTaskSlice) LoadReviewTaskPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
	if len(os) == 0 {
		return nil
	}

	reviewTaskPools, err := os.ReviewTaskPool(mods...).All(ctx, exec)
	if err != nil {
		return err
	}

	for _, o := range os {
		if o == nil {
			continue
		}

		for _, rel := range reviewTaskPools {

			if !(o.ID == rel.ReviewTaskID) {
				continue
			}

			rel.R.ReviewTask = o

			o.R.ReviewTaskPool = rel
			break
		}
	}

	return nil
}
