// 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/mods"
	"github.com/Gleipnir-Technology/bob/orm"
	"github.com/Gleipnir-Technology/bob/types/pgtypes"
	"github.com/aarondl/opt/omit"
)

// ComplianceReportRequest is an object representing the database table.
type ComplianceReportRequest struct {
	Created     time.Time `db:"created" `
	Creator     int32     `db:"creator" `
	ID          int32     `db:"id,pk" `
	PublicID    string    `db:"public_id" `
	SiteID      int32     `db:"site_id" `
	SiteVersion int32     `db:"site_version" `

	R complianceReportRequestR `db:"-" `
}

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

// ComplianceReportRequests contains methods to work with the compliance_report_request table
var ComplianceReportRequests = psql.NewTablex[*ComplianceReportRequest, ComplianceReportRequestSlice, *ComplianceReportRequestSetter]("", "compliance_report_request", buildComplianceReportRequestColumns("compliance_report_request"))

// ComplianceReportRequestsQuery is a query on the compliance_report_request table
type ComplianceReportRequestsQuery = *psql.ViewQuery[*ComplianceReportRequest, ComplianceReportRequestSlice]

// complianceReportRequestR is where relationships are stored.
type complianceReportRequestR struct {
	CreatorUser *User // compliance_report_request.compliance_report_request_creator_fkey
	Site        *Site // compliance_report_request.compliance_report_request_site_id_site_version_fkey
}

func buildComplianceReportRequestColumns(alias string) complianceReportRequestColumns {
	return complianceReportRequestColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator", "id", "public_id", "site_id", "site_version",
		).WithParent("compliance_report_request"),
		tableAlias:  alias,
		Created:     psql.Quote(alias, "created"),
		Creator:     psql.Quote(alias, "creator"),
		ID:          psql.Quote(alias, "id"),
		PublicID:    psql.Quote(alias, "public_id"),
		SiteID:      psql.Quote(alias, "site_id"),
		SiteVersion: psql.Quote(alias, "site_version"),
	}
}

type complianceReportRequestColumns struct {
	expr.ColumnsExpr
	tableAlias  string
	Created     psql.Expression
	Creator     psql.Expression
	ID          psql.Expression
	PublicID    psql.Expression
	SiteID      psql.Expression
	SiteVersion psql.Expression
}

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

func (complianceReportRequestColumns) AliasedAs(alias string) complianceReportRequestColumns {
	return buildComplianceReportRequestColumns(alias)
}

// ComplianceReportRequestSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type ComplianceReportRequestSetter struct {
	Created     omit.Val[time.Time] `db:"created" `
	Creator     omit.Val[int32]     `db:"creator" `
	ID          omit.Val[int32]     `db:"id,pk" `
	PublicID    omit.Val[string]    `db:"public_id" `
	SiteID      omit.Val[int32]     `db:"site_id" `
	SiteVersion omit.Val[int32]     `db:"site_version" `
}

func (s ComplianceReportRequestSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.Creator.IsValue() {
		vals = append(vals, "creator")
	}
	if s.ID.IsValue() {
		vals = append(vals, "id")
	}
	if s.PublicID.IsValue() {
		vals = append(vals, "public_id")
	}
	if s.SiteID.IsValue() {
		vals = append(vals, "site_id")
	}
	if s.SiteVersion.IsValue() {
		vals = append(vals, "site_version")
	}
	return vals
}

func (s ComplianceReportRequestSetter) Overwrite(t *ComplianceReportRequest) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.Creator.IsValue() {
		t.Creator = s.Creator.MustGet()
	}
	if s.ID.IsValue() {
		t.ID = s.ID.MustGet()
	}
	if s.PublicID.IsValue() {
		t.PublicID = s.PublicID.MustGet()
	}
	if s.SiteID.IsValue() {
		t.SiteID = s.SiteID.MustGet()
	}
	if s.SiteVersion.IsValue() {
		t.SiteVersion = s.SiteVersion.MustGet()
	}
}

func (s *ComplianceReportRequestSetter) Apply(q *dialect.InsertQuery) {
	q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
		return ComplianceReportRequests.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, 6)
		if s.Created.IsValue() {
			vals[0] = psql.Arg(s.Created.MustGet())
		} else {
			vals[0] = psql.Raw("DEFAULT")
		}

		if s.Creator.IsValue() {
			vals[1] = psql.Arg(s.Creator.MustGet())
		} 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.PublicID.IsValue() {
			vals[3] = psql.Arg(s.PublicID.MustGet())
		} else {
			vals[3] = psql.Raw("DEFAULT")
		}

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

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

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

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

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

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

	return err
}

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

func (o *ComplianceReportRequest) pkEQ() dialect.Expression {
	return psql.Quote("compliance_report_request", "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 ComplianceReportRequest
func (o *ComplianceReportRequest) Update(ctx context.Context, exec bob.Executor, s *ComplianceReportRequestSetter) error {
	v, err := ComplianceReportRequests.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 ComplianceReportRequest record with an executor
func (o *ComplianceReportRequest) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := ComplianceReportRequests.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

// Reload refreshes the ComplianceReportRequest using the executor
func (o *ComplianceReportRequest) Reload(ctx context.Context, exec bob.Executor) error {
	o2, err := ComplianceReportRequests.Query(
		sm.Where(ComplianceReportRequests.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 ComplianceReportRequestSlice is retrieved from the database
func (o ComplianceReportRequestSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
	var err error

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

	return err
}

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

	return psql.Quote("compliance_report_request", "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 ComplianceReportRequestSlice) copyMatchingRows(from ...*ComplianceReportRequest) {
	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 ComplianceReportRequestSlice) 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 ComplianceReportRequests.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 *ComplianceReportRequest:
				o.copyMatchingRows(retrieved)
			case []*ComplianceReportRequest:
				o.copyMatchingRows(retrieved...)
			case ComplianceReportRequestSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ComplianceReportRequest or a slice of ComplianceReportRequest
				// then run the AfterUpdateHooks on the slice
				_, err = ComplianceReportRequests.AfterUpdateHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o ComplianceReportRequestSlice) 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 ComplianceReportRequests.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 *ComplianceReportRequest:
				o.copyMatchingRows(retrieved)
			case []*ComplianceReportRequest:
				o.copyMatchingRows(retrieved...)
			case ComplianceReportRequestSlice:
				o.copyMatchingRows(retrieved...)
			default:
				// If the retrieved value is not a ComplianceReportRequest or a slice of ComplianceReportRequest
				// then run the AfterDeleteHooks on the slice
				_, err = ComplianceReportRequests.AfterDeleteHooks.RunHooks(ctx, exec, o)
			}

			return err
		}))

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

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

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

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

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

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

	o2, err := ComplianceReportRequests.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 *ComplianceReportRequest) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	return Users.Query(append(mods,
		sm.Where(Users.Columns.ID.EQ(psql.Arg(o.Creator))),
	)...)
}

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

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

// Site starts a query for related objects on site
func (o *ComplianceReportRequest) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	return Sites.Query(append(mods,
		sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))), sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.SiteVersion))),
	)...)
}

func (os ComplianceReportRequestSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery {
	pkSiteID := make(pgtypes.Array[int32], 0, len(os))

	pkSiteVersion := make(pgtypes.Array[int32], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkSiteID = append(pkSiteID, o.SiteID)
		pkSiteVersion = append(pkSiteVersion, o.SiteVersion)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkSiteID), "integer[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkSiteVersion), "integer[]")),
	))

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

func attachComplianceReportRequestCreatorUser0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, user1 *User) (*ComplianceReportRequest, error) {
	setter := &ComplianceReportRequestSetter{
		Creator: omit.From(user1.ID),
	}

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

	return complianceReportRequest0, nil
}

func (complianceReportRequest0 *ComplianceReportRequest) 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 = attachComplianceReportRequestCreatorUser0(ctx, exec, 1, complianceReportRequest0, user1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.CreatorUser = user1

	user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0)

	return nil
}

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

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

	complianceReportRequest0.R.CreatorUser = user1

	user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0)

	return nil
}

func attachComplianceReportRequestSite0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, site1 *Site) (*ComplianceReportRequest, error) {
	setter := &ComplianceReportRequestSetter{
		SiteID:      omit.From(site1.ID),
		SiteVersion: omit.From(site1.Version),
	}

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

	return complianceReportRequest0, nil
}

func (complianceReportRequest0 *ComplianceReportRequest) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error {
	var err error

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

	_, err = attachComplianceReportRequestSite0(ctx, exec, 1, complianceReportRequest0, site1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.Site = site1

	site1.R.ComplianceReportRequests = append(site1.R.ComplianceReportRequests, complianceReportRequest0)

	return nil
}

func (complianceReportRequest0 *ComplianceReportRequest) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error {
	var err error

	_, err = attachComplianceReportRequestSite0(ctx, exec, 1, complianceReportRequest0, site1)
	if err != nil {
		return err
	}

	complianceReportRequest0.R.Site = site1

	site1.R.ComplianceReportRequests = append(site1.R.ComplianceReportRequests, complianceReportRequest0)

	return nil
}

type complianceReportRequestWhere[Q psql.Filterable] struct {
	Created     psql.WhereMod[Q, time.Time]
	Creator     psql.WhereMod[Q, int32]
	ID          psql.WhereMod[Q, int32]
	PublicID    psql.WhereMod[Q, string]
	SiteID      psql.WhereMod[Q, int32]
	SiteVersion psql.WhereMod[Q, int32]
}

func (complianceReportRequestWhere[Q]) AliasedAs(alias string) complianceReportRequestWhere[Q] {
	return buildComplianceReportRequestWhere[Q](buildComplianceReportRequestColumns(alias))
}

func buildComplianceReportRequestWhere[Q psql.Filterable](cols complianceReportRequestColumns) complianceReportRequestWhere[Q] {
	return complianceReportRequestWhere[Q]{
		Created:     psql.Where[Q, time.Time](cols.Created),
		Creator:     psql.Where[Q, int32](cols.Creator),
		ID:          psql.Where[Q, int32](cols.ID),
		PublicID:    psql.Where[Q, string](cols.PublicID),
		SiteID:      psql.Where[Q, int32](cols.SiteID),
		SiteVersion: psql.Where[Q, int32](cols.SiteVersion),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o}
		}
		return nil
	case "Site":
		rel, ok := retrieved.(*Site)
		if !ok {
			return fmt.Errorf("complianceReportRequest cannot load %T as %q", retrieved, name)
		}

		o.R.Site = rel

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

type complianceReportRequestPreloader struct {
	CreatorUser func(...psql.PreloadOption) psql.Preloader
	Site        func(...psql.PreloadOption) psql.Preloader
}

func buildComplianceReportRequestPreloader() complianceReportRequestPreloader {
	return complianceReportRequestPreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequests,
						To:          Users,
						FromColumns: []string{"creator"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		Site: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*Site, SiteSlice](psql.PreloadRel{
				Name: "Site",
				Sides: []psql.PreloadSide{
					{
						From:        ComplianceReportRequests,
						To:          Sites,
						FromColumns: []string{"site_id", "site_version"},
						ToColumns:   []string{"id", "version"},
					},
				},
			}, Sites.Columns.Names(), opts...)
		},
	}
}

type complianceReportRequestThenLoader[Q orm.Loadable] struct {
	CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Site        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildComplianceReportRequestThenLoader[Q orm.Loadable]() complianceReportRequestThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type SiteLoadInterface interface {
		LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return complianceReportRequestThenLoader[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...)
			},
		),
		Site: thenLoadBuilder[Q](
			"Site",
			func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadSite(ctx, exec, mods...)
			},
		),
	}
}

// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct
func (o *ComplianceReportRequest) 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.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o}

	o.R.CreatorUser = related
	return nil
}

// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct
func (os ComplianceReportRequestSlice) 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.Creator == rel.ID) {
				continue
			}

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.ComplianceReportRequests = ComplianceReportRequestSlice{o}

	o.R.Site = related
	return nil
}

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

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

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

		for _, rel := range sites {

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

			if !(o.SiteVersion == rel.Version) {
				continue
			}

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

			o.R.Site = rel
			break
		}
	}

	return nil
}

type complianceReportRequestJoins[Q dialect.Joinable] struct {
	typ         string
	CreatorUser modAs[Q, userColumns]
	Site        modAs[Q, siteColumns]
}

func (j complianceReportRequestJoins[Q]) aliasedAs(alias string) complianceReportRequestJoins[Q] {
	return buildComplianceReportRequestJoins[Q](buildComplianceReportRequestColumns(alias), j.typ)
}

func buildComplianceReportRequestJoins[Q dialect.Joinable](cols complianceReportRequestColumns, typ string) complianceReportRequestJoins[Q] {
	return complianceReportRequestJoins[Q]{
		typ: typ,
		CreatorUser: modAs[Q, userColumns]{
			c: Users.Columns,
			f: func(to userColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, Users.Name().As(to.Alias())).On(
						to.ID.EQ(cols.Creator),
					))
				}

				return mods
			},
		},
		Site: modAs[Q, siteColumns]{
			c: Sites.Columns,
			f: func(to siteColumns) bob.Mod[Q] {
				mods := make(mods.QueryMods[Q], 0, 1)

				{
					mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On(
						to.ID.EQ(cols.SiteID), to.Version.EQ(cols.SiteVersion),
					))
				}

				return mods
			},
		},
	}
}
