// 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"
	"github.com/google/uuid"
)

// NoteImage is an object representing the database table.
type NoteImage struct {
	Created        time.Time           `db:"created" `
	CreatorID      int32               `db:"creator_id" `
	Deleted        null.Val[time.Time] `db:"deleted" `
	DeletorID      null.Val[int32]     `db:"deletor_id" `
	OrganizationID int32               `db:"organization_id" `
	Version        int32               `db:"version,pk" `
	UUID           uuid.UUID           `db:"uuid,pk" `
	ID             int32               `db:"id,generated" `

	R noteImageR `db:"-" `
}

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

// NoteImages contains methods to work with the note_image table
var NoteImages = psql.NewTablex[*NoteImage, NoteImageSlice, *NoteImageSetter]("", "note_image", buildNoteImageColumns("note_image"))

// NoteImagesQuery is a query on the note_image table
type NoteImagesQuery = *psql.ViewQuery[*NoteImage, NoteImageSlice]

// noteImageR is where relationships are stored.
type noteImageR struct {
	CreatorUser          *User                    // note_image.note_image_creator_id_fkey
	DeletorUser          *User                    // note_image.note_image_deletor_id_fkey
	Organization         *Organization            // note_image.note_image_organization_id_fkey
	NoteImageBreadcrumbs NoteImageBreadcrumbSlice // note_image_breadcrumb.note_image_breadcrumb_note_image_version_note_image_uuid_fkey
	NoteImageData        NoteImageDatumSlice      // note_image_data.note_image_data_note_image_version_note_image_uuid_fkey
}

func buildNoteImageColumns(alias string) noteImageColumns {
	return noteImageColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"created", "creator_id", "deleted", "deletor_id", "organization_id", "version", "uuid", "id",
		).WithParent("note_image"),
		tableAlias:     alias,
		Created:        psql.Quote(alias, "created"),
		CreatorID:      psql.Quote(alias, "creator_id"),
		Deleted:        psql.Quote(alias, "deleted"),
		DeletorID:      psql.Quote(alias, "deletor_id"),
		OrganizationID: psql.Quote(alias, "organization_id"),
		Version:        psql.Quote(alias, "version"),
		UUID:           psql.Quote(alias, "uuid"),
		ID:             psql.Quote(alias, "id"),
	}
}

type noteImageColumns struct {
	expr.ColumnsExpr
	tableAlias     string
	Created        psql.Expression
	CreatorID      psql.Expression
	Deleted        psql.Expression
	DeletorID      psql.Expression
	OrganizationID psql.Expression
	Version        psql.Expression
	UUID           psql.Expression
	ID             psql.Expression
}

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

func (noteImageColumns) AliasedAs(alias string) noteImageColumns {
	return buildNoteImageColumns(alias)
}

// NoteImageSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type NoteImageSetter struct {
	Created        omit.Val[time.Time]     `db:"created" `
	CreatorID      omit.Val[int32]         `db:"creator_id" `
	Deleted        omitnull.Val[time.Time] `db:"deleted" `
	DeletorID      omitnull.Val[int32]     `db:"deletor_id" `
	OrganizationID omit.Val[int32]         `db:"organization_id" `
	Version        omit.Val[int32]         `db:"version,pk" `
	UUID           omit.Val[uuid.UUID]     `db:"uuid,pk" `
}

func (s NoteImageSetter) SetColumns() []string {
	vals := make([]string, 0, 7)
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.CreatorID.IsValue() {
		vals = append(vals, "creator_id")
	}
	if !s.Deleted.IsUnset() {
		vals = append(vals, "deleted")
	}
	if !s.DeletorID.IsUnset() {
		vals = append(vals, "deletor_id")
	}
	if s.OrganizationID.IsValue() {
		vals = append(vals, "organization_id")
	}
	if s.Version.IsValue() {
		vals = append(vals, "version")
	}
	if s.UUID.IsValue() {
		vals = append(vals, "uuid")
	}
	return vals
}

func (s NoteImageSetter) Overwrite(t *NoteImage) {
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.CreatorID.IsValue() {
		t.CreatorID = s.CreatorID.MustGet()
	}
	if !s.Deleted.IsUnset() {
		t.Deleted = s.Deleted.MustGetNull()
	}
	if !s.DeletorID.IsUnset() {
		t.DeletorID = s.DeletorID.MustGetNull()
	}
	if s.OrganizationID.IsValue() {
		t.OrganizationID = s.OrganizationID.MustGet()
	}
	if s.Version.IsValue() {
		t.Version = s.Version.MustGet()
	}
	if s.UUID.IsValue() {
		t.UUID = s.UUID.MustGet()
	}
}

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

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

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

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

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

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

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

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

func (s NoteImageSetter) 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.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "creator_id")...),
			psql.Arg(s.CreatorID),
		}})
	}

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

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

	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.Version.IsValue() {
		exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
			psql.Quote(append(prefix, "version")...),
			psql.Arg(s.Version),
		}})
	}

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

	return exprs
}

// FindNoteImage retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindNoteImage(ctx context.Context, exec bob.Executor, VersionPK int32, UUIDPK uuid.UUID, cols ...string) (*NoteImage, error) {
	if len(cols) == 0 {
		return NoteImages.Query(
			sm.Where(NoteImages.Columns.Version.EQ(psql.Arg(VersionPK))),
			sm.Where(NoteImages.Columns.UUID.EQ(psql.Arg(UUIDPK))),
		).One(ctx, exec)
	}

	return NoteImages.Query(
		sm.Where(NoteImages.Columns.Version.EQ(psql.Arg(VersionPK))),
		sm.Where(NoteImages.Columns.UUID.EQ(psql.Arg(UUIDPK))),
		sm.Columns(NoteImages.Columns.Only(cols...)),
	).One(ctx, exec)
}

// NoteImageExists checks the presence of a single record by primary key
func NoteImageExists(ctx context.Context, exec bob.Executor, VersionPK int32, UUIDPK uuid.UUID) (bool, error) {
	return NoteImages.Query(
		sm.Where(NoteImages.Columns.Version.EQ(psql.Arg(VersionPK))),
		sm.Where(NoteImages.Columns.UUID.EQ(psql.Arg(UUIDPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the NoteImage
func (o *NoteImage) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.Version,
		o.UUID,
	)
}

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

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("note_image", "version"), psql.Quote("note_image", "uuid")).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 NoteImageSlice) copyMatchingRows(from ...*NoteImage) {
	for i, old := range o {
		for _, new := range from {
			if new.Version != old.Version {
				continue
			}
			if new.UUID != old.UUID {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

func (os NoteImageSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkCreatorID := make(pgtypes.Array[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)),
	)...)
}

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

func (os NoteImageSlice) DeletorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery {
	pkDeletorID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkDeletorID = append(pkDeletorID, o.DeletorID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkDeletorID), "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 *NoteImage) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
	return Organizations.Query(append(mods,
		sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))),
	)...)
}

func (os NoteImageSlice) 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)),
	)...)
}

// NoteImageBreadcrumbs starts a query for related objects on note_image_breadcrumb
func (o *NoteImage) NoteImageBreadcrumbs(mods ...bob.Mod[*dialect.SelectQuery]) NoteImageBreadcrumbsQuery {
	return NoteImageBreadcrumbs.Query(append(mods,
		sm.Where(NoteImageBreadcrumbs.Columns.NoteImageVersion.EQ(psql.Arg(o.Version))), sm.Where(NoteImageBreadcrumbs.Columns.NoteImageUUID.EQ(psql.Arg(o.UUID))),
	)...)
}

func (os NoteImageSlice) NoteImageBreadcrumbs(mods ...bob.Mod[*dialect.SelectQuery]) NoteImageBreadcrumbsQuery {
	pkVersion := make(pgtypes.Array[int32], 0, len(os))

	pkUUID := make(pgtypes.Array[uuid.UUID], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkVersion = append(pkVersion, o.Version)
		pkUUID = append(pkUUID, o.UUID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkVersion), "integer[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkUUID), "uuid[]")),
	))

	return NoteImageBreadcrumbs.Query(append(mods,
		sm.Where(psql.Group(NoteImageBreadcrumbs.Columns.NoteImageVersion, NoteImageBreadcrumbs.Columns.NoteImageUUID).OP("IN", PKArgExpr)),
	)...)
}

// NoteImageData starts a query for related objects on note_image_data
func (o *NoteImage) NoteImageData(mods ...bob.Mod[*dialect.SelectQuery]) NoteImageDataQuery {
	return NoteImageData.Query(append(mods,
		sm.Where(NoteImageData.Columns.NoteImageVersion.EQ(psql.Arg(o.Version))), sm.Where(NoteImageData.Columns.NoteImageUUID.EQ(psql.Arg(o.UUID))),
	)...)
}

func (os NoteImageSlice) NoteImageData(mods ...bob.Mod[*dialect.SelectQuery]) NoteImageDataQuery {
	pkVersion := make(pgtypes.Array[int32], 0, len(os))

	pkUUID := make(pgtypes.Array[uuid.UUID], 0, len(os))
	for _, o := range os {
		if o == nil {
			continue
		}
		pkVersion = append(pkVersion, o.Version)
		pkUUID = append(pkUUID, o.UUID)
	}
	PKArgExpr := psql.Select(sm.Columns(
		psql.F("unnest", psql.Cast(psql.Arg(pkVersion), "integer[]")),
		psql.F("unnest", psql.Cast(psql.Arg(pkUUID), "uuid[]")),
	))

	return NoteImageData.Query(append(mods,
		sm.Where(psql.Group(NoteImageData.Columns.NoteImageVersion, NoteImageData.Columns.NoteImageUUID).OP("IN", PKArgExpr)),
	)...)
}

func attachNoteImageCreatorUser0(ctx context.Context, exec bob.Executor, count int, noteImage0 *NoteImage, user1 *User) (*NoteImage, error) {
	setter := &NoteImageSetter{
		CreatorID: omit.From(user1.ID),
	}

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

	return noteImage0, nil
}

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

	noteImage0.R.CreatorUser = user1

	user1.R.CreatorNoteImages = append(user1.R.CreatorNoteImages, noteImage0)

	return nil
}

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

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

	noteImage0.R.CreatorUser = user1

	user1.R.CreatorNoteImages = append(user1.R.CreatorNoteImages, noteImage0)

	return nil
}

func attachNoteImageDeletorUser0(ctx context.Context, exec bob.Executor, count int, noteImage0 *NoteImage, user1 *User) (*NoteImage, error) {
	setter := &NoteImageSetter{
		DeletorID: omitnull.From(user1.ID),
	}

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

	return noteImage0, nil
}

func (noteImage0 *NoteImage) InsertDeletorUser(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 = attachNoteImageDeletorUser0(ctx, exec, 1, noteImage0, user1)
	if err != nil {
		return err
	}

	noteImage0.R.DeletorUser = user1

	user1.R.DeletorNoteImages = append(user1.R.DeletorNoteImages, noteImage0)

	return nil
}

func (noteImage0 *NoteImage) AttachDeletorUser(ctx context.Context, exec bob.Executor, user1 *User) error {
	var err error

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

	noteImage0.R.DeletorUser = user1

	user1.R.DeletorNoteImages = append(user1.R.DeletorNoteImages, noteImage0)

	return nil
}

func attachNoteImageOrganization0(ctx context.Context, exec bob.Executor, count int, noteImage0 *NoteImage, organization1 *Organization) (*NoteImage, error) {
	setter := &NoteImageSetter{
		OrganizationID: omit.From(organization1.ID),
	}

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

	return noteImage0, nil
}

func (noteImage0 *NoteImage) 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 = attachNoteImageOrganization0(ctx, exec, 1, noteImage0, organization1)
	if err != nil {
		return err
	}

	noteImage0.R.Organization = organization1

	organization1.R.NoteImages = append(organization1.R.NoteImages, noteImage0)

	return nil
}

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

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

	noteImage0.R.Organization = organization1

	organization1.R.NoteImages = append(organization1.R.NoteImages, noteImage0)

	return nil
}

func insertNoteImageNoteImageBreadcrumbs0(ctx context.Context, exec bob.Executor, noteImageBreadcrumbs1 []*NoteImageBreadcrumbSetter, noteImage0 *NoteImage) (NoteImageBreadcrumbSlice, error) {
	for i := range noteImageBreadcrumbs1 {
		noteImageBreadcrumbs1[i].NoteImageVersion = omit.From(noteImage0.Version)
		noteImageBreadcrumbs1[i].NoteImageUUID = omit.From(noteImage0.UUID)
	}

	ret, err := NoteImageBreadcrumbs.Insert(bob.ToMods(noteImageBreadcrumbs1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertNoteImageNoteImageBreadcrumbs0: %w", err)
	}

	return ret, nil
}

func attachNoteImageNoteImageBreadcrumbs0(ctx context.Context, exec bob.Executor, count int, noteImageBreadcrumbs1 NoteImageBreadcrumbSlice, noteImage0 *NoteImage) (NoteImageBreadcrumbSlice, error) {
	setter := &NoteImageBreadcrumbSetter{
		NoteImageVersion: omit.From(noteImage0.Version),
		NoteImageUUID:    omit.From(noteImage0.UUID),
	}

	err := noteImageBreadcrumbs1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachNoteImageNoteImageBreadcrumbs0: %w", err)
	}

	return noteImageBreadcrumbs1, nil
}

func (noteImage0 *NoteImage) InsertNoteImageBreadcrumbs(ctx context.Context, exec bob.Executor, related ...*NoteImageBreadcrumbSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	noteImageBreadcrumbs1, err := insertNoteImageNoteImageBreadcrumbs0(ctx, exec, related, noteImage0)
	if err != nil {
		return err
	}

	noteImage0.R.NoteImageBreadcrumbs = append(noteImage0.R.NoteImageBreadcrumbs, noteImageBreadcrumbs1...)

	for _, rel := range noteImageBreadcrumbs1 {
		rel.R.NoteImage = noteImage0
	}
	return nil
}

func (noteImage0 *NoteImage) AttachNoteImageBreadcrumbs(ctx context.Context, exec bob.Executor, related ...*NoteImageBreadcrumb) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	noteImageBreadcrumbs1 := NoteImageBreadcrumbSlice(related)

	_, err = attachNoteImageNoteImageBreadcrumbs0(ctx, exec, len(related), noteImageBreadcrumbs1, noteImage0)
	if err != nil {
		return err
	}

	noteImage0.R.NoteImageBreadcrumbs = append(noteImage0.R.NoteImageBreadcrumbs, noteImageBreadcrumbs1...)

	for _, rel := range related {
		rel.R.NoteImage = noteImage0
	}

	return nil
}

func insertNoteImageNoteImageData0(ctx context.Context, exec bob.Executor, noteImageData1 []*NoteImageDatumSetter, noteImage0 *NoteImage) (NoteImageDatumSlice, error) {
	for i := range noteImageData1 {
		noteImageData1[i].NoteImageVersion = omit.From(noteImage0.Version)
		noteImageData1[i].NoteImageUUID = omit.From(noteImage0.UUID)
	}

	ret, err := NoteImageData.Insert(bob.ToMods(noteImageData1...)).All(ctx, exec)
	if err != nil {
		return ret, fmt.Errorf("insertNoteImageNoteImageData0: %w", err)
	}

	return ret, nil
}

func attachNoteImageNoteImageData0(ctx context.Context, exec bob.Executor, count int, noteImageData1 NoteImageDatumSlice, noteImage0 *NoteImage) (NoteImageDatumSlice, error) {
	setter := &NoteImageDatumSetter{
		NoteImageVersion: omit.From(noteImage0.Version),
		NoteImageUUID:    omit.From(noteImage0.UUID),
	}

	err := noteImageData1.UpdateAll(ctx, exec, *setter)
	if err != nil {
		return nil, fmt.Errorf("attachNoteImageNoteImageData0: %w", err)
	}

	return noteImageData1, nil
}

func (noteImage0 *NoteImage) InsertNoteImageData(ctx context.Context, exec bob.Executor, related ...*NoteImageDatumSetter) error {
	if len(related) == 0 {
		return nil
	}

	var err error

	noteImageData1, err := insertNoteImageNoteImageData0(ctx, exec, related, noteImage0)
	if err != nil {
		return err
	}

	noteImage0.R.NoteImageData = append(noteImage0.R.NoteImageData, noteImageData1...)

	for _, rel := range noteImageData1 {
		rel.R.NoteImage = noteImage0
	}
	return nil
}

func (noteImage0 *NoteImage) AttachNoteImageData(ctx context.Context, exec bob.Executor, related ...*NoteImageDatum) error {
	if len(related) == 0 {
		return nil
	}

	var err error
	noteImageData1 := NoteImageDatumSlice(related)

	_, err = attachNoteImageNoteImageData0(ctx, exec, len(related), noteImageData1, noteImage0)
	if err != nil {
		return err
	}

	noteImage0.R.NoteImageData = append(noteImage0.R.NoteImageData, noteImageData1...)

	for _, rel := range related {
		rel.R.NoteImage = noteImage0
	}

	return nil
}

type noteImageWhere[Q psql.Filterable] struct {
	Created        psql.WhereMod[Q, time.Time]
	CreatorID      psql.WhereMod[Q, int32]
	Deleted        psql.WhereNullMod[Q, time.Time]
	DeletorID      psql.WhereNullMod[Q, int32]
	OrganizationID psql.WhereMod[Q, int32]
	Version        psql.WhereMod[Q, int32]
	UUID           psql.WhereMod[Q, uuid.UUID]
	ID             psql.WhereMod[Q, int32]
}

func (noteImageWhere[Q]) AliasedAs(alias string) noteImageWhere[Q] {
	return buildNoteImageWhere[Q](buildNoteImageColumns(alias))
}

func buildNoteImageWhere[Q psql.Filterable](cols noteImageColumns) noteImageWhere[Q] {
	return noteImageWhere[Q]{
		Created:        psql.Where[Q, time.Time](cols.Created),
		CreatorID:      psql.Where[Q, int32](cols.CreatorID),
		Deleted:        psql.WhereNull[Q, time.Time](cols.Deleted),
		DeletorID:      psql.WhereNull[Q, int32](cols.DeletorID),
		OrganizationID: psql.Where[Q, int32](cols.OrganizationID),
		Version:        psql.Where[Q, int32](cols.Version),
		UUID:           psql.Where[Q, uuid.UUID](cols.UUID),
		ID:             psql.Where[Q, int32](cols.ID),
	}
}

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

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

		o.R.CreatorUser = rel

		if rel != nil {
			rel.R.CreatorNoteImages = NoteImageSlice{o}
		}
		return nil
	case "DeletorUser":
		rel, ok := retrieved.(*User)
		if !ok {
			return fmt.Errorf("noteImage cannot load %T as %q", retrieved, name)
		}

		o.R.DeletorUser = rel

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

		o.R.Organization = rel

		if rel != nil {
			rel.R.NoteImages = NoteImageSlice{o}
		}
		return nil
	case "NoteImageBreadcrumbs":
		rels, ok := retrieved.(NoteImageBreadcrumbSlice)
		if !ok {
			return fmt.Errorf("noteImage cannot load %T as %q", retrieved, name)
		}

		o.R.NoteImageBreadcrumbs = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.NoteImage = o
			}
		}
		return nil
	case "NoteImageData":
		rels, ok := retrieved.(NoteImageDatumSlice)
		if !ok {
			return fmt.Errorf("noteImage cannot load %T as %q", retrieved, name)
		}

		o.R.NoteImageData = rels

		for _, rel := range rels {
			if rel != nil {
				rel.R.NoteImage = o
			}
		}
		return nil
	default:
		return fmt.Errorf("noteImage has no relationship %q", name)
	}
}

type noteImagePreloader struct {
	CreatorUser  func(...psql.PreloadOption) psql.Preloader
	DeletorUser  func(...psql.PreloadOption) psql.Preloader
	Organization func(...psql.PreloadOption) psql.Preloader
}

func buildNoteImagePreloader() noteImagePreloader {
	return noteImagePreloader{
		CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "CreatorUser",
				Sides: []psql.PreloadSide{
					{
						From:        NoteImages,
						To:          Users,
						FromColumns: []string{"creator_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Users.Columns.Names(), opts...)
		},
		DeletorUser: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*User, UserSlice](psql.PreloadRel{
				Name: "DeletorUser",
				Sides: []psql.PreloadSide{
					{
						From:        NoteImages,
						To:          Users,
						FromColumns: []string{"deletor_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:        NoteImages,
						To:          Organizations,
						FromColumns: []string{"organization_id"},
						ToColumns:   []string{"id"},
					},
				},
			}, Organizations.Columns.Names(), opts...)
		},
	}
}

type noteImageThenLoader[Q orm.Loadable] struct {
	CreatorUser          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	DeletorUser          func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	Organization         func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	NoteImageBreadcrumbs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
	NoteImageData        func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildNoteImageThenLoader[Q orm.Loadable]() noteImageThenLoader[Q] {
	type CreatorUserLoadInterface interface {
		LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type DeletorUserLoadInterface interface {
		LoadDeletorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type OrganizationLoadInterface interface {
		LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type NoteImageBreadcrumbsLoadInterface interface {
		LoadNoteImageBreadcrumbs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}
	type NoteImageDataLoadInterface interface {
		LoadNoteImageData(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return noteImageThenLoader[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...)
			},
		),
		DeletorUser: thenLoadBuilder[Q](
			"DeletorUser",
			func(ctx context.Context, exec bob.Executor, retrieved DeletorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadDeletorUser(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...)
			},
		),
		NoteImageBreadcrumbs: thenLoadBuilder[Q](
			"NoteImageBreadcrumbs",
			func(ctx context.Context, exec bob.Executor, retrieved NoteImageBreadcrumbsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadNoteImageBreadcrumbs(ctx, exec, mods...)
			},
		),
		NoteImageData: thenLoadBuilder[Q](
			"NoteImageData",
			func(ctx context.Context, exec bob.Executor, retrieved NoteImageDataLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadNoteImageData(ctx, exec, mods...)
			},
		),
	}
}

// LoadCreatorUser loads the noteImage's CreatorUser into the .R struct
func (o *NoteImage) 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.CreatorNoteImages = NoteImageSlice{o}

	o.R.CreatorUser = related
	return nil
}

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

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

			o.R.CreatorUser = rel
			break
		}
	}

	return nil
}

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

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

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

	related.R.DeletorNoteImages = NoteImageSlice{o}

	o.R.DeletorUser = related
	return nil
}

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

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

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

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

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

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

			o.R.DeletorUser = rel
			break
		}
	}

	return nil
}

// LoadOrganization loads the noteImage's Organization into the .R struct
func (o *NoteImage) 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.NoteImages = NoteImageSlice{o}

	o.R.Organization = related
	return nil
}

// LoadOrganization loads the noteImage's Organization into the .R struct
func (os NoteImageSlice) 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.NoteImages = append(rel.R.NoteImages, o)

			o.R.Organization = rel
			break
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.NoteImage = o
	}

	o.R.NoteImageBreadcrumbs = related
	return nil
}

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

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

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

		o.R.NoteImageBreadcrumbs = nil
	}

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

		for _, rel := range noteImageBreadcrumbs {

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

			if !(o.UUID == rel.NoteImageUUID) {
				continue
			}

			rel.R.NoteImage = o

			o.R.NoteImageBreadcrumbs = append(o.R.NoteImageBreadcrumbs, rel)
		}
	}

	return nil
}

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

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

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

	for _, rel := range related {
		rel.R.NoteImage = o
	}

	o.R.NoteImageData = related
	return nil
}

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

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

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

		o.R.NoteImageData = nil
	}

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

		for _, rel := range noteImageData {

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

			if !(o.UUID == rel.NoteImageUUID) {
				continue
			}

			rel.R.NoteImage = o

			o.R.NoteImageData = append(o.R.NoteImageData, rel)
		}
	}

	return nil
}
