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

// NoteImageBreadcrumb is an object representing the database table.
type NoteImageBreadcrumb struct {
	Cell             string    `db:"cell" `
	Created          time.Time `db:"created" `
	ManuallySelected bool      `db:"manually_selected" `
	NoteImageVersion int32     `db:"note_image_version,pk" `
	NoteImageUUID    uuid.UUID `db:"note_image_uuid,pk" `
	Position         int32     `db:"position,pk" `

	R noteImageBreadcrumbR `db:"-" `
}

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

// NoteImageBreadcrumbs contains methods to work with the note_image_breadcrumb table
var NoteImageBreadcrumbs = psql.NewTablex[*NoteImageBreadcrumb, NoteImageBreadcrumbSlice, *NoteImageBreadcrumbSetter]("", "note_image_breadcrumb", buildNoteImageBreadcrumbColumns("note_image_breadcrumb"))

// NoteImageBreadcrumbsQuery is a query on the note_image_breadcrumb table
type NoteImageBreadcrumbsQuery = *psql.ViewQuery[*NoteImageBreadcrumb, NoteImageBreadcrumbSlice]

// noteImageBreadcrumbR is where relationships are stored.
type noteImageBreadcrumbR struct {
	NoteImage *NoteImage // note_image_breadcrumb.note_image_breadcrumb_note_image_version_note_image_uuid_fkey
}

func buildNoteImageBreadcrumbColumns(alias string) noteImageBreadcrumbColumns {
	return noteImageBreadcrumbColumns{
		ColumnsExpr: expr.NewColumnsExpr(
			"cell", "created", "manually_selected", "note_image_version", "note_image_uuid", "position",
		).WithParent("note_image_breadcrumb"),
		tableAlias:       alias,
		Cell:             psql.Quote(alias, "cell"),
		Created:          psql.Quote(alias, "created"),
		ManuallySelected: psql.Quote(alias, "manually_selected"),
		NoteImageVersion: psql.Quote(alias, "note_image_version"),
		NoteImageUUID:    psql.Quote(alias, "note_image_uuid"),
		Position:         psql.Quote(alias, "position"),
	}
}

type noteImageBreadcrumbColumns struct {
	expr.ColumnsExpr
	tableAlias       string
	Cell             psql.Expression
	Created          psql.Expression
	ManuallySelected psql.Expression
	NoteImageVersion psql.Expression
	NoteImageUUID    psql.Expression
	Position         psql.Expression
}

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

func (noteImageBreadcrumbColumns) AliasedAs(alias string) noteImageBreadcrumbColumns {
	return buildNoteImageBreadcrumbColumns(alias)
}

// NoteImageBreadcrumbSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type NoteImageBreadcrumbSetter struct {
	Cell             omit.Val[string]    `db:"cell" `
	Created          omit.Val[time.Time] `db:"created" `
	ManuallySelected omit.Val[bool]      `db:"manually_selected" `
	NoteImageVersion omit.Val[int32]     `db:"note_image_version,pk" `
	NoteImageUUID    omit.Val[uuid.UUID] `db:"note_image_uuid,pk" `
	Position         omit.Val[int32]     `db:"position,pk" `
}

func (s NoteImageBreadcrumbSetter) SetColumns() []string {
	vals := make([]string, 0, 6)
	if s.Cell.IsValue() {
		vals = append(vals, "cell")
	}
	if s.Created.IsValue() {
		vals = append(vals, "created")
	}
	if s.ManuallySelected.IsValue() {
		vals = append(vals, "manually_selected")
	}
	if s.NoteImageVersion.IsValue() {
		vals = append(vals, "note_image_version")
	}
	if s.NoteImageUUID.IsValue() {
		vals = append(vals, "note_image_uuid")
	}
	if s.Position.IsValue() {
		vals = append(vals, "position")
	}
	return vals
}

func (s NoteImageBreadcrumbSetter) Overwrite(t *NoteImageBreadcrumb) {
	if s.Cell.IsValue() {
		t.Cell = s.Cell.MustGet()
	}
	if s.Created.IsValue() {
		t.Created = s.Created.MustGet()
	}
	if s.ManuallySelected.IsValue() {
		t.ManuallySelected = s.ManuallySelected.MustGet()
	}
	if s.NoteImageVersion.IsValue() {
		t.NoteImageVersion = s.NoteImageVersion.MustGet()
	}
	if s.NoteImageUUID.IsValue() {
		t.NoteImageUUID = s.NoteImageUUID.MustGet()
	}
	if s.Position.IsValue() {
		t.Position = s.Position.MustGet()
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return exprs
}

// FindNoteImageBreadcrumb retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindNoteImageBreadcrumb(ctx context.Context, exec bob.Executor, NoteImageVersionPK int32, NoteImageUUIDPK uuid.UUID, PositionPK int32, cols ...string) (*NoteImageBreadcrumb, error) {
	if len(cols) == 0 {
		return NoteImageBreadcrumbs.Query(
			sm.Where(NoteImageBreadcrumbs.Columns.NoteImageVersion.EQ(psql.Arg(NoteImageVersionPK))),
			sm.Where(NoteImageBreadcrumbs.Columns.NoteImageUUID.EQ(psql.Arg(NoteImageUUIDPK))),
			sm.Where(NoteImageBreadcrumbs.Columns.Position.EQ(psql.Arg(PositionPK))),
		).One(ctx, exec)
	}

	return NoteImageBreadcrumbs.Query(
		sm.Where(NoteImageBreadcrumbs.Columns.NoteImageVersion.EQ(psql.Arg(NoteImageVersionPK))),
		sm.Where(NoteImageBreadcrumbs.Columns.NoteImageUUID.EQ(psql.Arg(NoteImageUUIDPK))),
		sm.Where(NoteImageBreadcrumbs.Columns.Position.EQ(psql.Arg(PositionPK))),
		sm.Columns(NoteImageBreadcrumbs.Columns.Only(cols...)),
	).One(ctx, exec)
}

// NoteImageBreadcrumbExists checks the presence of a single record by primary key
func NoteImageBreadcrumbExists(ctx context.Context, exec bob.Executor, NoteImageVersionPK int32, NoteImageUUIDPK uuid.UUID, PositionPK int32) (bool, error) {
	return NoteImageBreadcrumbs.Query(
		sm.Where(NoteImageBreadcrumbs.Columns.NoteImageVersion.EQ(psql.Arg(NoteImageVersionPK))),
		sm.Where(NoteImageBreadcrumbs.Columns.NoteImageUUID.EQ(psql.Arg(NoteImageUUIDPK))),
		sm.Where(NoteImageBreadcrumbs.Columns.Position.EQ(psql.Arg(PositionPK))),
	).Exists(ctx, exec)
}

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

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

	return err
}

// primaryKeyVals returns the primary key values of the NoteImageBreadcrumb
func (o *NoteImageBreadcrumb) primaryKeyVals() bob.Expression {
	return psql.ArgGroup(
		o.NoteImageVersion,
		o.NoteImageUUID,
		o.Position,
	)
}

func (o *NoteImageBreadcrumb) pkEQ() dialect.Expression {
	return psql.Group(psql.Quote("note_image_breadcrumb", "note_image_version"), psql.Quote("note_image_breadcrumb", "note_image_uuid"), psql.Quote("note_image_breadcrumb", "position")).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 NoteImageBreadcrumb
func (o *NoteImageBreadcrumb) Update(ctx context.Context, exec bob.Executor, s *NoteImageBreadcrumbSetter) error {
	v, err := NoteImageBreadcrumbs.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 NoteImageBreadcrumb record with an executor
func (o *NoteImageBreadcrumb) Delete(ctx context.Context, exec bob.Executor) error {
	_, err := NoteImageBreadcrumbs.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
	return err
}

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

	return nil
}

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

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

	return err
}

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

	return psql.Group(psql.Quote("note_image_breadcrumb", "note_image_version"), psql.Quote("note_image_breadcrumb", "note_image_uuid"), psql.Quote("note_image_breadcrumb", "position")).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 NoteImageBreadcrumbSlice) copyMatchingRows(from ...*NoteImageBreadcrumb) {
	for i, old := range o {
		for _, new := range from {
			if new.NoteImageVersion != old.NoteImageVersion {
				continue
			}
			if new.NoteImageUUID != old.NoteImageUUID {
				continue
			}
			if new.Position != old.Position {
				continue
			}
			new.R = old.R
			o[i] = new
			break
		}
	}
}

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

			return err
		}))

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

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

			return err
		}))

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

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

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

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

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

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

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

	o.copyMatchingRows(o2...)

	return nil
}

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

func (os NoteImageBreadcrumbSlice) NoteImage(mods ...bob.Mod[*dialect.SelectQuery]) NoteImagesQuery {
	pkNoteImageVersion := make(pgtypes.Array[int32], 0, len(os))

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

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

func attachNoteImageBreadcrumbNoteImage0(ctx context.Context, exec bob.Executor, count int, noteImageBreadcrumb0 *NoteImageBreadcrumb, noteImage1 *NoteImage) (*NoteImageBreadcrumb, error) {
	setter := &NoteImageBreadcrumbSetter{
		NoteImageVersion: omit.From(noteImage1.Version),
		NoteImageUUID:    omit.From(noteImage1.UUID),
	}

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

	return noteImageBreadcrumb0, nil
}

func (noteImageBreadcrumb0 *NoteImageBreadcrumb) InsertNoteImage(ctx context.Context, exec bob.Executor, related *NoteImageSetter) error {
	var err error

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

	_, err = attachNoteImageBreadcrumbNoteImage0(ctx, exec, 1, noteImageBreadcrumb0, noteImage1)
	if err != nil {
		return err
	}

	noteImageBreadcrumb0.R.NoteImage = noteImage1

	noteImage1.R.NoteImageBreadcrumbs = append(noteImage1.R.NoteImageBreadcrumbs, noteImageBreadcrumb0)

	return nil
}

func (noteImageBreadcrumb0 *NoteImageBreadcrumb) AttachNoteImage(ctx context.Context, exec bob.Executor, noteImage1 *NoteImage) error {
	var err error

	_, err = attachNoteImageBreadcrumbNoteImage0(ctx, exec, 1, noteImageBreadcrumb0, noteImage1)
	if err != nil {
		return err
	}

	noteImageBreadcrumb0.R.NoteImage = noteImage1

	noteImage1.R.NoteImageBreadcrumbs = append(noteImage1.R.NoteImageBreadcrumbs, noteImageBreadcrumb0)

	return nil
}

type noteImageBreadcrumbWhere[Q psql.Filterable] struct {
	Cell             psql.WhereMod[Q, string]
	Created          psql.WhereMod[Q, time.Time]
	ManuallySelected psql.WhereMod[Q, bool]
	NoteImageVersion psql.WhereMod[Q, int32]
	NoteImageUUID    psql.WhereMod[Q, uuid.UUID]
	Position         psql.WhereMod[Q, int32]
}

func (noteImageBreadcrumbWhere[Q]) AliasedAs(alias string) noteImageBreadcrumbWhere[Q] {
	return buildNoteImageBreadcrumbWhere[Q](buildNoteImageBreadcrumbColumns(alias))
}

func buildNoteImageBreadcrumbWhere[Q psql.Filterable](cols noteImageBreadcrumbColumns) noteImageBreadcrumbWhere[Q] {
	return noteImageBreadcrumbWhere[Q]{
		Cell:             psql.Where[Q, string](cols.Cell),
		Created:          psql.Where[Q, time.Time](cols.Created),
		ManuallySelected: psql.Where[Q, bool](cols.ManuallySelected),
		NoteImageVersion: psql.Where[Q, int32](cols.NoteImageVersion),
		NoteImageUUID:    psql.Where[Q, uuid.UUID](cols.NoteImageUUID),
		Position:         psql.Where[Q, int32](cols.Position),
	}
}

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

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

		o.R.NoteImage = rel

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

type noteImageBreadcrumbPreloader struct {
	NoteImage func(...psql.PreloadOption) psql.Preloader
}

func buildNoteImageBreadcrumbPreloader() noteImageBreadcrumbPreloader {
	return noteImageBreadcrumbPreloader{
		NoteImage: func(opts ...psql.PreloadOption) psql.Preloader {
			return psql.Preload[*NoteImage, NoteImageSlice](psql.PreloadRel{
				Name: "NoteImage",
				Sides: []psql.PreloadSide{
					{
						From:        NoteImageBreadcrumbs,
						To:          NoteImages,
						FromColumns: []string{"note_image_version", "note_image_uuid"},
						ToColumns:   []string{"version", "uuid"},
					},
				},
			}, NoteImages.Columns.Names(), opts...)
		},
	}
}

type noteImageBreadcrumbThenLoader[Q orm.Loadable] struct {
	NoteImage func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}

func buildNoteImageBreadcrumbThenLoader[Q orm.Loadable]() noteImageBreadcrumbThenLoader[Q] {
	type NoteImageLoadInterface interface {
		LoadNoteImage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
	}

	return noteImageBreadcrumbThenLoader[Q]{
		NoteImage: thenLoadBuilder[Q](
			"NoteImage",
			func(ctx context.Context, exec bob.Executor, retrieved NoteImageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
				return retrieved.LoadNoteImage(ctx, exec, mods...)
			},
		),
	}
}

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

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

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

	related.R.NoteImageBreadcrumbs = NoteImageBreadcrumbSlice{o}

	o.R.NoteImage = related
	return nil
}

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

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

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

		for _, rel := range noteImages {

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

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

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

			o.R.NoteImage = rel
			break
		}
	}

	return nil
}
