summary history files

desktop/backend/model/attachment.go
// Code generated by SQLBoiler 4.15.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.

package model

import (
	"context"
	"database/sql"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/friendsofgo/errors"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/volatiletech/sqlboiler/v4/queries/qmhelper"
	"github.com/volatiletech/strmangle"
)

// Attachment is an object representing the database table.
type Attachment struct {
	ID        int64  `boil:"id" json:"id" toml:"id" yaml:"id"`
	Name      string `boil:"name" json:"name" toml:"name" yaml:"name"`
	SZ        int64  `boil:"sz" json:"sz" toml:"sz" yaml:"sz"`
	Data      []byte `boil:"data" json:"data" toml:"data" yaml:"data"`
	CreatedAt int64  `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"`

	R *attachmentR `boil:"-" json:"-" toml:"-" yaml:"-"`
	L attachmentL  `boil:"-" json:"-" toml:"-" yaml:"-"`
}

var AttachmentColumns = struct {
	ID        string
	Name      string
	SZ        string
	Data      string
	CreatedAt string
}{
	ID:        "id",
	Name:      "name",
	SZ:        "sz",
	Data:      "data",
	CreatedAt: "created_at",
}

var AttachmentTableColumns = struct {
	ID        string
	Name      string
	SZ        string
	Data      string
	CreatedAt string
}{
	ID:        "attachment.id",
	Name:      "attachment.name",
	SZ:        "attachment.sz",
	Data:      "attachment.data",
	CreatedAt: "attachment.created_at",
}

// Generated where

type whereHelper__byte struct{ field string }

func (w whereHelper__byte) EQ(x []byte) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelper__byte) NEQ(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelper__byte) LT(x []byte) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelper__byte) LTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelper__byte) GT(x []byte) qm.QueryMod  { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelper__byte) GTE(x []byte) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }

var AttachmentWhere = struct {
	ID        whereHelperint64
	Name      whereHelperstring
	SZ        whereHelperint64
	Data      whereHelper__byte
	CreatedAt whereHelperint64
}{
	ID:        whereHelperint64{field: "\"attachment\".\"id\""},
	Name:      whereHelperstring{field: "\"attachment\".\"name\""},
	SZ:        whereHelperint64{field: "\"attachment\".\"sz\""},
	Data:      whereHelper__byte{field: "\"attachment\".\"data\""},
	CreatedAt: whereHelperint64{field: "\"attachment\".\"created_at\""},
}

// AttachmentRels is where relationship names are stored.
var AttachmentRels = struct {
	AttachmentTransactions string
}{
	AttachmentTransactions: "AttachmentTransactions",
}

// attachmentR is where relationships are stored.
type attachmentR struct {
	AttachmentTransactions AttachmentTransactionSlice `boil:"AttachmentTransactions" json:"AttachmentTransactions" toml:"AttachmentTransactions" yaml:"AttachmentTransactions"`
}

// NewStruct creates a new relationship struct
func (*attachmentR) NewStruct() *attachmentR {
	return &attachmentR{}
}

func (r *attachmentR) GetAttachmentTransactions() AttachmentTransactionSlice {
	if r == nil {
		return nil
	}
	return r.AttachmentTransactions
}

// attachmentL is where Load methods for each relationship are stored.
type attachmentL struct{}

var (
	attachmentAllColumns            = []string{"id", "name", "sz", "data", "created_at"}
	attachmentColumnsWithoutDefault = []string{"name", "sz", "data", "created_at"}
	attachmentColumnsWithDefault    = []string{"id"}
	attachmentPrimaryKeyColumns     = []string{"id"}
	attachmentGeneratedColumns      = []string{"id"}
)

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

	attachmentQuery struct {
		*queries.Query
	}
)

// Cache for insert, update and upsert
var (
	attachmentType                 = reflect.TypeOf(&Attachment{})
	attachmentMapping              = queries.MakeStructMapping(attachmentType)
	attachmentPrimaryKeyMapping, _ = queries.BindMapping(attachmentType, attachmentMapping, attachmentPrimaryKeyColumns)
	attachmentInsertCacheMut       sync.RWMutex
	attachmentInsertCache          = make(map[string]insertCache)
	attachmentUpdateCacheMut       sync.RWMutex
	attachmentUpdateCache          = make(map[string]updateCache)
	attachmentUpsertCacheMut       sync.RWMutex
	attachmentUpsertCache          = make(map[string]insertCache)
)

var (
	// Force time package dependency for automated UpdatedAt/CreatedAt.
	_ = time.Second
	// Force qmhelper dependency for where clause generation (which doesn't
	// always happen)
	_ = qmhelper.Where
)

// One returns a single attachment record from the query.
func (q attachmentQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Attachment, error) {
	o := &Attachment{}

	queries.SetLimit(q.Query, 1)

	err := q.Bind(ctx, exec, o)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, sql.ErrNoRows
		}
		return nil, errors.Wrap(err, "model: failed to execute a one query for attachment")
	}

	return o, nil
}

// All returns all Attachment records from the query.
func (q attachmentQuery) All(ctx context.Context, exec boil.ContextExecutor) (AttachmentSlice, error) {
	var o []*Attachment

	err := q.Bind(ctx, exec, &o)
	if err != nil {
		return nil, errors.Wrap(err, "model: failed to assign all query results to Attachment slice")
	}

	return o, nil
}

// Count returns the count of all Attachment records in the query.
func (q attachmentQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	var count int64

	queries.SetSelect(q.Query, nil)
	queries.SetCount(q.Query)

	err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
	if err != nil {
		return 0, errors.Wrap(err, "model: failed to count attachment rows")
	}

	return count, nil
}

// Exists checks if the row exists in the table.
func (q attachmentQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
	var count int64

	queries.SetSelect(q.Query, nil)
	queries.SetCount(q.Query)
	queries.SetLimit(q.Query, 1)

	err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
	if err != nil {
		return false, errors.Wrap(err, "model: failed to check if attachment exists")
	}

	return count > 0, nil
}

// AttachmentTransactions retrieves all the attachment_transaction's AttachmentTransactions with an executor.
func (o *Attachment) AttachmentTransactions(mods ...qm.QueryMod) attachmentTransactionQuery {
	var queryMods []qm.QueryMod
	if len(mods) != 0 {
		queryMods = append(queryMods, mods...)
	}

	queryMods = append(queryMods,
		qm.Where("\"attachment_transactions\".\"attachment_id\"=?", o.ID),
	)

	return AttachmentTransactions(queryMods...)
}

// LoadAttachmentTransactions allows an eager lookup of values, cached into the
// loaded structs of the objects. This is for a 1-M or N-M relationship.
func (attachmentL) LoadAttachmentTransactions(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAttachment interface{}, mods queries.Applicator) error {
	var slice []*Attachment
	var object *Attachment

	if singular {
		var ok bool
		object, ok = maybeAttachment.(*Attachment)
		if !ok {
			object = new(Attachment)
			ok = queries.SetFromEmbeddedStruct(&object, &maybeAttachment)
			if !ok {
				return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeAttachment))
			}
		}
	} else {
		s, ok := maybeAttachment.(*[]*Attachment)
		if ok {
			slice = *s
		} else {
			ok = queries.SetFromEmbeddedStruct(&slice, maybeAttachment)
			if !ok {
				return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeAttachment))
			}
		}
	}

	args := make([]interface{}, 0, 1)
	if singular {
		if object.R == nil {
			object.R = &attachmentR{}
		}
		args = append(args, object.ID)
	} else {
	Outer:
		for _, obj := range slice {
			if obj.R == nil {
				obj.R = &attachmentR{}
			}

			for _, a := range args {
				if a == obj.ID {
					continue Outer
				}
			}

			args = append(args, obj.ID)
		}
	}

	if len(args) == 0 {
		return nil
	}

	query := NewQuery(
		qm.From(`attachment_transactions`),
		qm.WhereIn(`attachment_transactions.attachment_id in ?`, args...),
	)
	if mods != nil {
		mods.Apply(query)
	}

	results, err := query.QueryContext(ctx, e)
	if err != nil {
		return errors.Wrap(err, "failed to eager load attachment_transactions")
	}

	var resultSlice []*AttachmentTransaction
	if err = queries.Bind(results, &resultSlice); err != nil {
		return errors.Wrap(err, "failed to bind eager loaded slice attachment_transactions")
	}

	if err = results.Close(); err != nil {
		return errors.Wrap(err, "failed to close results in eager load on attachment_transactions")
	}
	if err = results.Err(); err != nil {
		return errors.Wrap(err, "error occurred during iteration of eager loaded relations for attachment_transactions")
	}

	if singular {
		object.R.AttachmentTransactions = resultSlice
		for _, foreign := range resultSlice {
			if foreign.R == nil {
				foreign.R = &attachmentTransactionR{}
			}
			foreign.R.Attachment = object
		}
		return nil
	}

	for _, foreign := range resultSlice {
		for _, local := range slice {
			if local.ID == foreign.AttachmentID {
				local.R.AttachmentTransactions = append(local.R.AttachmentTransactions, foreign)
				if foreign.R == nil {
					foreign.R = &attachmentTransactionR{}
				}
				foreign.R.Attachment = local
				break
			}
		}
	}

	return nil
}

// AddAttachmentTransactions adds the given related objects to the existing relationships
// of the attachment, optionally inserting them as new records.
// Appends related to o.R.AttachmentTransactions.
// Sets related.R.Attachment appropriately.
func (o *Attachment) AddAttachmentTransactions(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*AttachmentTransaction) error {
	var err error
	for _, rel := range related {
		if insert {
			rel.AttachmentID = o.ID
			if err = rel.Insert(ctx, exec, boil.Infer()); err != nil {
				return errors.Wrap(err, "failed to insert into foreign table")
			}
		} else {
			updateQuery := fmt.Sprintf(
				"UPDATE \"attachment_transactions\" SET %s WHERE %s",
				strmangle.SetParamNames("\"", "\"", 0, []string{"attachment_id"}),
				strmangle.WhereClause("\"", "\"", 0, attachmentTransactionPrimaryKeyColumns),
			)
			values := []interface{}{o.ID, rel.ID}

			if boil.IsDebug(ctx) {
				writer := boil.DebugWriterFrom(ctx)
				fmt.Fprintln(writer, updateQuery)
				fmt.Fprintln(writer, values)
			}
			if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {
				return errors.Wrap(err, "failed to update foreign table")
			}

			rel.AttachmentID = o.ID
		}
	}

	if o.R == nil {
		o.R = &attachmentR{
			AttachmentTransactions: related,
		}
	} else {
		o.R.AttachmentTransactions = append(o.R.AttachmentTransactions, related...)
	}

	for _, rel := range related {
		if rel.R == nil {
			rel.R = &attachmentTransactionR{
				Attachment: o,
			}
		} else {
			rel.R.Attachment = o
		}
	}
	return nil
}

// Attachments retrieves all the records using an executor.
func Attachments(mods ...qm.QueryMod) attachmentQuery {
	mods = append(mods, qm.From("\"attachment\""))
	q := NewQuery(mods...)
	if len(queries.GetSelect(q)) == 0 {
		queries.SetSelect(q, []string{"\"attachment\".*"})
	}

	return attachmentQuery{q}
}

// FindAttachment retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func FindAttachment(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*Attachment, error) {
	attachmentObj := &Attachment{}

	sel := "*"
	if len(selectCols) > 0 {
		sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
	}
	query := fmt.Sprintf(
		"select %s from \"attachment\" where \"id\"=?", sel,
	)

	q := queries.Raw(query, iD)

	err := q.Bind(ctx, exec, attachmentObj)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, sql.ErrNoRows
		}
		return nil, errors.Wrap(err, "model: unable to select from attachment")
	}

	return attachmentObj, nil
}

// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *Attachment) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
	if o == nil {
		return errors.New("model: no attachment provided for insertion")
	}

	var err error

	nzDefaults := queries.NonZeroDefaultSet(attachmentColumnsWithDefault, o)

	key := makeCacheKey(columns, nzDefaults)
	attachmentInsertCacheMut.RLock()
	cache, cached := attachmentInsertCache[key]
	attachmentInsertCacheMut.RUnlock()

	if !cached {
		wl, returnColumns := columns.InsertColumnSet(
			attachmentAllColumns,
			attachmentColumnsWithDefault,
			attachmentColumnsWithoutDefault,
			nzDefaults,
		)
		wl = strmangle.SetComplement(wl, attachmentGeneratedColumns)

		cache.valueMapping, err = queries.BindMapping(attachmentType, attachmentMapping, wl)
		if err != nil {
			return err
		}
		cache.retMapping, err = queries.BindMapping(attachmentType, attachmentMapping, returnColumns)
		if err != nil {
			return err
		}
		if len(wl) != 0 {
			cache.query = fmt.Sprintf("INSERT INTO \"attachment\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
		} else {
			cache.query = "INSERT INTO \"attachment\" %sDEFAULT VALUES%s"
		}

		var queryOutput, queryReturning string

		if len(cache.retMapping) != 0 {
			queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\""))
		}

		cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
	}

	value := reflect.Indirect(reflect.ValueOf(o))
	vals := queries.ValuesFromMapping(value, cache.valueMapping)

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, vals)
	}

	if len(cache.retMapping) != 0 {
		err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
	} else {
		_, err = exec.ExecContext(ctx, cache.query, vals...)
	}

	if err != nil {
		return errors.Wrap(err, "model: unable to insert into attachment")
	}

	if !cached {
		attachmentInsertCacheMut.Lock()
		attachmentInsertCache[key] = cache
		attachmentInsertCacheMut.Unlock()
	}

	return nil
}

// Update uses an executor to update the Attachment.
// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates.
// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records.
func (o *Attachment) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
	var err error
	key := makeCacheKey(columns, nil)
	attachmentUpdateCacheMut.RLock()
	cache, cached := attachmentUpdateCache[key]
	attachmentUpdateCacheMut.RUnlock()

	if !cached {
		wl := columns.UpdateColumnSet(
			attachmentAllColumns,
			attachmentPrimaryKeyColumns,
		)
		wl = strmangle.SetComplement(wl, attachmentGeneratedColumns)

		if len(wl) == 0 {
			return 0, errors.New("model: unable to update attachment, could not build whitelist")
		}

		cache.query = fmt.Sprintf("UPDATE \"attachment\" SET %s WHERE %s",
			strmangle.SetParamNames("\"", "\"", 0, wl),
			strmangle.WhereClause("\"", "\"", 0, attachmentPrimaryKeyColumns),
		)
		cache.valueMapping, err = queries.BindMapping(attachmentType, attachmentMapping, append(wl, attachmentPrimaryKeyColumns...))
		if err != nil {
			return 0, err
		}
	}

	values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, values)
	}
	var result sql.Result
	result, err = exec.ExecContext(ctx, cache.query, values...)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to update attachment row")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: failed to get rows affected by update for attachment")
	}

	if !cached {
		attachmentUpdateCacheMut.Lock()
		attachmentUpdateCache[key] = cache
		attachmentUpdateCacheMut.Unlock()
	}

	return rowsAff, nil
}

// UpdateAll updates all rows with the specified column values.
func (q attachmentQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
	queries.SetUpdate(q.Query, cols)

	result, err := q.Query.ExecContext(ctx, exec)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to update all for attachment")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to retrieve rows affected for attachment")
	}

	return rowsAff, nil
}

// UpdateAll updates all rows with the specified column values, using an executor.
func (o AttachmentSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
	ln := int64(len(o))
	if ln == 0 {
		return 0, nil
	}

	if len(cols) == 0 {
		return 0, errors.New("model: update all requires at least one column argument")
	}

	colNames := make([]string, len(cols))
	args := make([]interface{}, len(cols))

	i := 0
	for name, value := range cols {
		colNames[i] = name
		args[i] = value
		i++
	}

	// Append all of the primary key values for each column
	for _, obj := range o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), attachmentPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := fmt.Sprintf("UPDATE \"attachment\" SET %s WHERE %s",
		strmangle.SetParamNames("\"", "\"", 0, colNames),
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, attachmentPrimaryKeyColumns, len(o)))

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args...)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to update all in attachment slice")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to retrieve rows affected all in update all attachment")
	}
	return rowsAff, nil
}

// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *Attachment) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns) error {
	if o == nil {
		return errors.New("model: no attachment provided for upsert")
	}

	nzDefaults := queries.NonZeroDefaultSet(attachmentColumnsWithDefault, o)

	// Build cache key in-line uglily - mysql vs psql problems
	buf := strmangle.GetBuffer()
	if updateOnConflict {
		buf.WriteByte('t')
	} else {
		buf.WriteByte('f')
	}
	buf.WriteByte('.')
	for _, c := range conflictColumns {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	buf.WriteString(strconv.Itoa(updateColumns.Kind))
	for _, c := range updateColumns.Cols {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	buf.WriteString(strconv.Itoa(insertColumns.Kind))
	for _, c := range insertColumns.Cols {
		buf.WriteString(c)
	}
	buf.WriteByte('.')
	for _, c := range nzDefaults {
		buf.WriteString(c)
	}
	key := buf.String()
	strmangle.PutBuffer(buf)

	attachmentUpsertCacheMut.RLock()
	cache, cached := attachmentUpsertCache[key]
	attachmentUpsertCacheMut.RUnlock()

	var err error

	if !cached {
		insert, ret := insertColumns.InsertColumnSet(
			attachmentAllColumns,
			attachmentColumnsWithDefault,
			attachmentColumnsWithoutDefault,
			nzDefaults,
		)
		update := updateColumns.UpdateColumnSet(
			attachmentAllColumns,
			attachmentPrimaryKeyColumns,
		)

		if updateOnConflict && len(update) == 0 {
			return errors.New("model: unable to upsert attachment, could not build update column list")
		}

		conflict := conflictColumns
		if len(conflict) == 0 {
			conflict = make([]string, len(attachmentPrimaryKeyColumns))
			copy(conflict, attachmentPrimaryKeyColumns)
		}
		cache.query = buildUpsertQuerySQLite(dialect, "\"attachment\"", updateOnConflict, ret, update, conflict, insert)

		cache.valueMapping, err = queries.BindMapping(attachmentType, attachmentMapping, insert)
		if err != nil {
			return err
		}
		if len(ret) != 0 {
			cache.retMapping, err = queries.BindMapping(attachmentType, attachmentMapping, ret)
			if err != nil {
				return err
			}
		}
	}

	value := reflect.Indirect(reflect.ValueOf(o))
	vals := queries.ValuesFromMapping(value, cache.valueMapping)
	var returns []interface{}
	if len(cache.retMapping) != 0 {
		returns = queries.PtrsFromMapping(value, cache.retMapping)
	}

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, cache.query)
		fmt.Fprintln(writer, vals)
	}
	if len(cache.retMapping) != 0 {
		err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...)
		if errors.Is(err, sql.ErrNoRows) {
			err = nil // Postgres doesn't return anything when there's no update
		}
	} else {
		_, err = exec.ExecContext(ctx, cache.query, vals...)
	}
	if err != nil {
		return errors.Wrap(err, "model: unable to upsert attachment")
	}

	if !cached {
		attachmentUpsertCacheMut.Lock()
		attachmentUpsertCache[key] = cache
		attachmentUpsertCacheMut.Unlock()
	}

	return nil
}

// Delete deletes a single Attachment record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *Attachment) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if o == nil {
		return 0, errors.New("model: no Attachment provided for delete")
	}

	args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), attachmentPrimaryKeyMapping)
	sql := "DELETE FROM \"attachment\" WHERE \"id\"=?"

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args...)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to delete from attachment")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: failed to get rows affected by delete for attachment")
	}

	return rowsAff, nil
}

// DeleteAll deletes all matching rows.
func (q attachmentQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if q.Query == nil {
		return 0, errors.New("model: no attachmentQuery provided for delete all")
	}

	queries.SetDelete(q.Query)

	result, err := q.Query.ExecContext(ctx, exec)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to delete all from attachment")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: failed to get rows affected by deleteall for attachment")
	}

	return rowsAff, nil
}

// DeleteAll deletes all rows in the slice, using an executor.
func (o AttachmentSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
	if len(o) == 0 {
		return 0, nil
	}

	var args []interface{}
	for _, obj := range o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), attachmentPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := "DELETE FROM \"attachment\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, attachmentPrimaryKeyColumns, len(o))

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, args)
	}
	result, err := exec.ExecContext(ctx, sql, args...)
	if err != nil {
		return 0, errors.Wrap(err, "model: unable to delete all from attachment slice")
	}

	rowsAff, err := result.RowsAffected()
	if err != nil {
		return 0, errors.Wrap(err, "model: failed to get rows affected by deleteall for attachment")
	}

	return rowsAff, nil
}

// Reload refetches the object from the database
// using the primary keys with an executor.
func (o *Attachment) Reload(ctx context.Context, exec boil.ContextExecutor) error {
	ret, err := FindAttachment(ctx, exec, o.ID)
	if err != nil {
		return err
	}

	*o = *ret
	return nil
}

// ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice.
func (o *AttachmentSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
	if o == nil || len(*o) == 0 {
		return nil
	}

	slice := AttachmentSlice{}
	var args []interface{}
	for _, obj := range *o {
		pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), attachmentPrimaryKeyMapping)
		args = append(args, pkeyArgs...)
	}

	sql := "SELECT \"attachment\".* FROM \"attachment\" WHERE " +
		strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, attachmentPrimaryKeyColumns, len(*o))

	q := queries.Raw(sql, args...)

	err := q.Bind(ctx, exec, &slice)
	if err != nil {
		return errors.Wrap(err, "model: unable to reload all in AttachmentSlice")
	}

	*o = slice

	return nil
}

// AttachmentExists checks if the Attachment row exists.
func AttachmentExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) {
	var exists bool
	sql := "select exists(select 1 from \"attachment\" where \"id\"=? limit 1)"

	if boil.IsDebug(ctx) {
		writer := boil.DebugWriterFrom(ctx)
		fmt.Fprintln(writer, sql)
		fmt.Fprintln(writer, iD)
	}
	row := exec.QueryRowContext(ctx, sql, iD)

	err := row.Scan(&exists)
	if err != nil {
		return false, errors.Wrap(err, "model: unable to check if attachment exists")
	}

	return exists, nil
}

// Exists checks if the Attachment row exists.
func (o *Attachment) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
	return AttachmentExists(ctx, exec, o.ID)
}