Demo application for me to test new backend/frontend technologies.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1695 lines
42 KiB

// Code generated by SQLBoiler (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 db
import (
"bytes"
"database/sql"
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries"
"github.com/volatiletech/sqlboiler/queries/qm"
"github.com/volatiletech/sqlboiler/strmangle"
"github.com/volatiletech/sqlboiler/types"
"gopkg.in/volatiletech/null.v6"
)
// User is an object representing the database table.
type User struct {
ID int `boil:"id" json:"id" toml:"id" yaml:"id"`
CreatedAt time.Time `boil:"created_at" json:"created_at" toml:"created_at" yaml:"created_at"`
UpdatedAt time.Time `boil:"updated_at" json:"updated_at" toml:"updated_at" yaml:"updated_at"`
Name string `boil:"name" json:"name" toml:"name" yaml:"name"`
Email string `boil:"email" json:"email" toml:"email" yaml:"email"`
Validated bool `boil:"validated" json:"validated" toml:"validated" yaml:"validated"`
Active bool `boil:"active" json:"active" toml:"active" yaml:"active"`
OrganizationID null.Int `boil:"organization_id" json:"organization_id,omitempty" toml:"organization_id" yaml:"organization_id,omitempty"`
CalendarData types.JSON `boil:"calendar_data" json:"calendar_data" toml:"calendar_data" yaml:"calendar_data"`
Admin bool `boil:"admin" json:"admin" toml:"admin" yaml:"admin"`
R *userR `boil:"-" json:"-" toml:"-" yaml:"-"`
L userL `boil:"-" json:"-" toml:"-" yaml:"-"`
}
var UserColumns = struct {
ID string
CreatedAt string
UpdatedAt string
Name string
Email string
Validated string
Active string
OrganizationID string
CalendarData string
Admin string
}{
ID: "id",
CreatedAt: "created_at",
UpdatedAt: "updated_at",
Name: "name",
Email: "email",
Validated: "validated",
Active: "active",
OrganizationID: "organization_id",
CalendarData: "calendar_data",
Admin: "admin",
}
// userR is where relationships are stored.
type userR struct {
Organization *Organization
CampaignTimes CampaignTimeSlice
CampaignUsers CampaignUserSlice
CreatorCampaigns CampaignSlice
}
// userL is where Load methods for each relationship are stored.
type userL struct{}
var (
userColumns = []string{"id", "created_at", "updated_at", "name", "email", "validated", "active", "organization_id", "calendar_data", "admin"}
userColumnsWithoutDefault = []string{"name", "email", "validated", "active", "organization_id", "calendar_data", "admin"}
userColumnsWithDefault = []string{"id", "created_at", "updated_at"}
userPrimaryKeyColumns = []string{"id"}
)
type (
// UserSlice is an alias for a slice of pointers to User.
// This should generally be used opposed to []User.
UserSlice []*User
// UserHook is the signature for custom User hook methods
UserHook func(boil.Executor, *User) error
userQuery struct {
*queries.Query
}
)
// Cache for insert, update and upsert
var (
userType = reflect.TypeOf(&User{})
userMapping = queries.MakeStructMapping(userType)
userPrimaryKeyMapping, _ = queries.BindMapping(userType, userMapping, userPrimaryKeyColumns)
userInsertCacheMut sync.RWMutex
userInsertCache = make(map[string]insertCache)
userUpdateCacheMut sync.RWMutex
userUpdateCache = make(map[string]updateCache)
userUpsertCacheMut sync.RWMutex
userUpsertCache = make(map[string]insertCache)
)
var (
// Force time package dependency for automated UpdatedAt/CreatedAt.
_ = time.Second
// Force bytes in case of primary key column that uses []byte (for relationship compares)
_ = bytes.MinRead
)
var userBeforeInsertHooks []UserHook
var userBeforeUpdateHooks []UserHook
var userBeforeDeleteHooks []UserHook
var userBeforeUpsertHooks []UserHook
var userAfterInsertHooks []UserHook
var userAfterSelectHooks []UserHook
var userAfterUpdateHooks []UserHook
var userAfterDeleteHooks []UserHook
var userAfterUpsertHooks []UserHook
// doBeforeInsertHooks executes all "before insert" hooks.
func (o *User) doBeforeInsertHooks(exec boil.Executor) (err error) {
for _, hook := range userBeforeInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *User) doBeforeUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range userBeforeUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *User) doBeforeDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range userBeforeDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *User) doBeforeUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range userBeforeUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *User) doAfterInsertHooks(exec boil.Executor) (err error) {
for _, hook := range userAfterInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doAfterSelectHooks executes all "after Select" hooks.
func (o *User) doAfterSelectHooks(exec boil.Executor) (err error) {
for _, hook := range userAfterSelectHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpdateHooks executes all "after Update" hooks.
func (o *User) doAfterUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range userAfterUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *User) doAfterDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range userAfterDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *User) doAfterUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range userAfterUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
}
// AddUserHook registers your hook function for all future operations.
func AddUserHook(hookPoint boil.HookPoint, userHook UserHook) {
switch hookPoint {
case boil.BeforeInsertHook:
userBeforeInsertHooks = append(userBeforeInsertHooks, userHook)
case boil.BeforeUpdateHook:
userBeforeUpdateHooks = append(userBeforeUpdateHooks, userHook)
case boil.BeforeDeleteHook:
userBeforeDeleteHooks = append(userBeforeDeleteHooks, userHook)
case boil.BeforeUpsertHook:
userBeforeUpsertHooks = append(userBeforeUpsertHooks, userHook)
case boil.AfterInsertHook:
userAfterInsertHooks = append(userAfterInsertHooks, userHook)
case boil.AfterSelectHook:
userAfterSelectHooks = append(userAfterSelectHooks, userHook)
case boil.AfterUpdateHook:
userAfterUpdateHooks = append(userAfterUpdateHooks, userHook)
case boil.AfterDeleteHook:
userAfterDeleteHooks = append(userAfterDeleteHooks, userHook)
case boil.AfterUpsertHook:
userAfterUpsertHooks = append(userAfterUpsertHooks, userHook)
}
}
// One returns a single user record from the query.
func (q userQuery) One() (*User, error) {
o := &User{}
queries.SetLimit(q.Query, 1)
err := q.Bind(o)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "db: failed to execute a one query for users")
}
if err := o.doAfterSelectHooks(queries.GetExecutor(q.Query)); err != nil {
return o, err
}
return o, nil
}
// All returns all User records from the query.
func (q userQuery) All() (UserSlice, error) {
var o []*User
err := q.Bind(&o)
if err != nil {
return nil, errors.Wrap(err, "db: failed to assign all query results to User slice")
}
if len(userAfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(queries.GetExecutor(q.Query)); err != nil {
return o, err
}
}
}
return o, nil
}
// Count returns the count of all User records in the query.
func (q userQuery) Count() (int64, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
err := q.Query.QueryRow().Scan(&count)
if err != nil {
return 0, errors.Wrap(err, "db: failed to count users rows")
}
return count, nil
}
// Exists checks if the row exists in the table.
func (q userQuery) Exists() (bool, error) {
var count int64
queries.SetCount(q.Query)
queries.SetLimit(q.Query, 1)
err := q.Query.QueryRow().Scan(&count)
if err != nil {
return false, errors.Wrap(err, "db: failed to check if users exists")
}
return count > 0, nil
}
// OrganizationG pointed to by the foreign key.
func (o *User) Organization(mods ...qm.QueryMod) organizationQuery {
queryMods := []qm.QueryMod{
qm.Where("id=?", o.OrganizationID),
}
queryMods = append(queryMods, mods...)
query := Organizations(boil.GetDB(), queryMods...)
queries.SetFrom(query.Query, "\"organizations\"")
return query
}
// CampaignTimes retrieves all the campaign_time's campaign times.
func (o *User) CampaignTimes(mods ...qm.QueryMod) campaignTimeQuery {
exec := boil.GetDB()
var queryMods []qm.QueryMod
if len(mods) != 0 {
queryMods = append(queryMods, mods...)
}
queryMods = append(queryMods,
qm.Where("\"campaign_times\".\"user_id\"=?", o.ID),
)
query := CampaignTimes(exec, queryMods...)
queries.SetFrom(query.Query, "\"campaign_times\"")
if len(queries.GetSelect(query.Query)) == 0 {
queries.SetSelect(query.Query, []string{"\"campaign_times\".*"})
}
return query
}
// CampaignUsers retrieves all the campaign_user's campaign users.
func (o *User) CampaignUsers(mods ...qm.QueryMod) campaignUserQuery {
exec := boil.GetDB()
var queryMods []qm.QueryMod
if len(mods) != 0 {
queryMods = append(queryMods, mods...)
}
queryMods = append(queryMods,
qm.Where("\"campaign_users\".\"user_id\"=?", o.ID),
)
query := CampaignUsers(exec, queryMods...)
queries.SetFrom(query.Query, "\"campaign_users\"")
if len(queries.GetSelect(query.Query)) == 0 {
queries.SetSelect(query.Query, []string{"\"campaign_users\".*"})
}
return query
}
// CreatorCampaigns retrieves all the campaign's campaigns via creator_id column.
func (o *User) CreatorCampaigns(mods ...qm.QueryMod) campaignQuery {
exec := boil.GetDB()
var queryMods []qm.QueryMod
if len(mods) != 0 {
queryMods = append(queryMods, mods...)
}
queryMods = append(queryMods,
qm.Where("\"campaigns\".\"creator_id\"=?", o.ID),
)
query := Campaigns(exec, queryMods...)
queries.SetFrom(query.Query, "\"campaigns\"")
if len(queries.GetSelect(query.Query)) == 0 {
queries.SetSelect(query.Query, []string{"\"campaigns\".*"})
}
return query
}
// LoadOrganization allows an eager lookup of values, cached into the
// loaded structs of the objects.
func (userL) LoadOrganization(singular bool, maybeUser interface{}) error {
e := boil.GetDB()
var slice []*User
var object *User
count := 1
if singular {
object = maybeUser.(*User)
} else {
slice = *maybeUser.(*[]*User)
count = len(slice)
}
args := make([]interface{}, count)
if singular {
if object.R == nil {
object.R = &userR{}
}
args[0] = object.OrganizationID
} else {
for i, obj := range slice {
if obj.R == nil {
obj.R = &userR{}
}
args[i] = obj.OrganizationID
}
}
query := fmt.Sprintf(
"select * from \"organizations\" where \"id\" in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
)
if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
}
results, err := e.Query(query, args...)
if err != nil {
return errors.Wrap(err, "failed to eager load Organization")
}
defer results.Close()
var resultSlice []*Organization
if err = queries.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice Organization")
}
if len(userAfterSelectHooks) != 0 {
for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil {
return err
}
}
}
if len(resultSlice) == 0 {
return nil
}
if singular {
object.R.Organization = resultSlice[0]
return nil
}
for _, local := range slice {
for _, foreign := range resultSlice {
if local.OrganizationID.Int == foreign.ID {
local.R.Organization = foreign
break
}
}
}
return nil
}
// LoadCampaignTimes allows an eager lookup of values, cached into the
// loaded structs of the objects.
func (userL) LoadCampaignTimes(singular bool, maybeUser interface{}) error {
e := boil.GetDB()
var slice []*User
var object *User
count := 1
if singular {
object = maybeUser.(*User)
} else {
slice = *maybeUser.(*[]*User)
count = len(slice)
}
args := make([]interface{}, count)
if singular {
if object.R == nil {
object.R = &userR{}
}
args[0] = object.ID
} else {
for i, obj := range slice {
if obj.R == nil {
obj.R = &userR{}
}
args[i] = obj.ID
}
}
query := fmt.Sprintf(
"select * from \"campaign_times\" where \"user_id\" in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
)
if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
}
results, err := e.Query(query, args...)
if err != nil {
return errors.Wrap(err, "failed to eager load campaign_times")
}
defer results.Close()
var resultSlice []*CampaignTime
if err = queries.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice campaign_times")
}
if len(campaignTimeAfterSelectHooks) != 0 {
for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil {
return err
}
}
}
if singular {
object.R.CampaignTimes = resultSlice
return nil
}
for _, foreign := range resultSlice {
for _, local := range slice {
if local.ID == foreign.UserID.Int {
local.R.CampaignTimes = append(local.R.CampaignTimes, foreign)
break
}
}
}
return nil
}
// LoadCampaignUsers allows an eager lookup of values, cached into the
// loaded structs of the objects.
func (userL) LoadCampaignUsers(singular bool, maybeUser interface{}) error {
e := boil.GetDB()
var slice []*User
var object *User
count := 1
if singular {
object = maybeUser.(*User)
} else {
slice = *maybeUser.(*[]*User)
count = len(slice)
}
args := make([]interface{}, count)
if singular {
if object.R == nil {
object.R = &userR{}
}
args[0] = object.ID
} else {
for i, obj := range slice {
if obj.R == nil {
obj.R = &userR{}
}
args[i] = obj.ID
}
}
query := fmt.Sprintf(
"select * from \"campaign_users\" where \"user_id\" in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
)
if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
}
results, err := e.Query(query, args...)
if err != nil {
return errors.Wrap(err, "failed to eager load campaign_users")
}
defer results.Close()
var resultSlice []*CampaignUser
if err = queries.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice campaign_users")
}
if len(campaignUserAfterSelectHooks) != 0 {
for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil {
return err
}
}
}
if singular {
object.R.CampaignUsers = resultSlice
return nil
}
for _, foreign := range resultSlice {
for _, local := range slice {
if local.ID == foreign.UserID.Int {
local.R.CampaignUsers = append(local.R.CampaignUsers, foreign)
break
}
}
}
return nil
}
// LoadCreatorCampaigns allows an eager lookup of values, cached into the
// loaded structs of the objects.
func (userL) LoadCreatorCampaigns(singular bool, maybeUser interface{}) error {
e := boil.GetDB()
var slice []*User
var object *User
count := 1
if singular {
object = maybeUser.(*User)
} else {
slice = *maybeUser.(*[]*User)
count = len(slice)
}
args := make([]interface{}, count)
if singular {
if object.R == nil {
object.R = &userR{}
}
args[0] = object.ID
} else {
for i, obj := range slice {
if obj.R == nil {
obj.R = &userR{}
}
args[i] = obj.ID
}
}
query := fmt.Sprintf(
"select * from \"campaigns\" where \"creator_id\" in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
)
if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
}
results, err := e.Query(query, args...)
if err != nil {
return errors.Wrap(err, "failed to eager load campaigns")
}
defer results.Close()
var resultSlice []*Campaign
if err = queries.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice campaigns")
}
if len(campaignAfterSelectHooks) != 0 {
for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil {
return err
}
}
}
if singular {
object.R.CreatorCampaigns = resultSlice
return nil
}
for _, foreign := range resultSlice {
for _, local := range slice {
if local.ID == foreign.CreatorID.Int {
local.R.CreatorCampaigns = append(local.R.CreatorCampaigns, foreign)
break
}
}
}
return nil
}
// SetOrganization of the user to the related item.
// Sets o.R.Organization to related.
// Adds o to related.R.Users.
func (o *User) SetOrganization(insert bool, related *Organization) error {
var err error
if insert {
if err = related.Insert(boil.GetDB()); err != nil {
return errors.Wrap(err, "failed to insert into foreign table")
}
}
updateQuery := fmt.Sprintf(
"UPDATE \"users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, []string{"organization_id"}),
strmangle.WhereClause("\"", "\"", 2, userPrimaryKeyColumns),
)
values := []interface{}{related.ID, o.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, updateQuery)
fmt.Fprintln(boil.DebugWriter, values)
}
if _, err = boil.GetDB().Exec(updateQuery, values...); err != nil {
return errors.Wrap(err, "failed to update local table")
}
o.OrganizationID.Int = related.ID
o.OrganizationID.Valid = true
if o.R == nil {
o.R = &userR{
Organization: related,
}
} else {
o.R.Organization = related
}
if related.R == nil {
related.R = &organizationR{
Users: UserSlice{o},
}
} else {
related.R.Users = append(related.R.Users, o)
}
return nil
}
// RemoveOrganization relationship.
// Sets o.R.Organization to nil.
// Removes o from all passed in related items' relationships struct (Optional).
func (o *User) RemoveOrganization(related *Organization) error {
var err error
exec := boil.GetDB()
o.OrganizationID.Valid = false
if err = o.Update(exec, "organization_id"); err != nil {
o.OrganizationID.Valid = true
return errors.Wrap(err, "failed to update local table")
}
o.R.Organization = nil
if related == nil || related.R == nil {
return nil
}
for i, ri := range related.R.Users {
if o.OrganizationID.Int != ri.OrganizationID.Int {
continue
}
ln := len(related.R.Users)
if ln > 1 && i < ln-1 {
related.R.Users[i] = related.R.Users[ln-1]
}
related.R.Users = related.R.Users[:ln-1]
break
}
return nil
}
// AddCampaignTimes adds the given related objects to the existing relationships
// of the user, optionally inserting them as new records.
// Appends related to o.R.CampaignTimes.
// Sets related.R.User appropriately.
func (o *User) AddCampaignTimes(exec boil.Executor, insert bool, related ...*CampaignTime) error {
var err error
exec := boil.GetDB()
for _, rel := range related {
if insert {
rel.UserID.Int = o.ID
rel.UserID.Valid = true
if err = rel.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table")
}
} else {
updateQuery := fmt.Sprintf(
"UPDATE \"campaign_times\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, []string{"user_id"}),
strmangle.WhereClause("\"", "\"", 2, campaignTimePrimaryKeyColumns),
)
values := []interface{}{o.ID, rel.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, updateQuery)
fmt.Fprintln(boil.DebugWriter, values)
}
if _, err = exec.Exec(updateQuery, values...); err != nil {
return errors.Wrap(err, "failed to update foreign table")
}
rel.UserID.Int = o.ID
rel.UserID.Valid = true
}
}
if o.R == nil {
o.R = &userR{
CampaignTimes: related,
}
} else {
o.R.CampaignTimes = append(o.R.CampaignTimes, related...)
}
for _, rel := range related {
if rel.R == nil {
rel.R = &campaignTimeR{
User: o,
}
} else {
rel.R.User = o
}
}
return nil
}
// SetCampaignTimes removes all previously related items of the
// user replacing them completely with the passed
// in related items, optionally inserting them as new records.
// Sets o.R.User's CampaignTimes accordingly.
// Replaces o.R.CampaignTimes with related.
// Sets related.R.User's CampaignTimes accordingly.
func (o *User) SetCampaignTimes(exec boil.Executor, insert bool, related ...*CampaignTime) error {
exec := boil.GetDB()
query := "update \"campaign_times\" set \"user_id\" = null where \"user_id\" = $1"
values := []interface{}{o.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values)
}
_, err := exec.Exec(query, values...)
if err != nil {
return errors.Wrap(err, "failed to remove relationships before set")
}
if o.R != nil {
for _, rel := range o.R.CampaignTimes {
rel.UserID.Valid = false
if rel.R == nil {
continue
}
rel.R.User = nil
}
o.R.CampaignTimes = nil
}
return o.AddCampaignTimes(exec, insert, related...)
}
// RemoveCampaignTimes relationships from objects passed in.
// Removes related items from R.CampaignTimes (uses pointer comparison, removal does not keep order)
// Sets related.R.User.
func (o *User) RemoveCampaignTimes(related ...*CampaignTime) error {
exec := boil.GetDB()
var err error
for _, rel := range related {
rel.UserID.Valid = false
if rel.R != nil {
rel.R.User = nil
}
if err = rel.Update(exec, "user_id"); err != nil {
return err
}
}
if o.R == nil {
return nil
}
for _, rel := range related {
for i, ri := range o.R.CampaignTimes {
if rel != ri {
continue
}
ln := len(o.R.CampaignTimes)
if ln > 1 && i < ln-1 {
o.R.CampaignTimes[i] = o.R.CampaignTimes[ln-1]
}
o.R.CampaignTimes = o.R.CampaignTimes[:ln-1]
break
}
}
return nil
}
// AddCampaignUsers adds the given related objects to the existing relationships
// of the user, optionally inserting them as new records.
// Appends related to o.R.CampaignUsers.
// Sets related.R.User appropriately.
func (o *User) AddCampaignUsers(exec boil.Executor, insert bool, related ...*CampaignUser) error {
var err error
exec := boil.GetDB()
for _, rel := range related {
if insert {
rel.UserID.Int = o.ID
rel.UserID.Valid = true
if err = rel.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table")
}
} else {
updateQuery := fmt.Sprintf(
"UPDATE \"campaign_users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, []string{"user_id"}),
strmangle.WhereClause("\"", "\"", 2, campaignUserPrimaryKeyColumns),
)
values := []interface{}{o.ID, rel.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, updateQuery)
fmt.Fprintln(boil.DebugWriter, values)
}
if _, err = exec.Exec(updateQuery, values...); err != nil {
return errors.Wrap(err, "failed to update foreign table")
}
rel.UserID.Int = o.ID
rel.UserID.Valid = true
}
}
if o.R == nil {
o.R = &userR{
CampaignUsers: related,
}
} else {
o.R.CampaignUsers = append(o.R.CampaignUsers, related...)
}
for _, rel := range related {
if rel.R == nil {
rel.R = &campaignUserR{
User: o,
}
} else {
rel.R.User = o
}
}
return nil
}
// SetCampaignUsers removes all previously related items of the
// user replacing them completely with the passed
// in related items, optionally inserting them as new records.
// Sets o.R.User's CampaignUsers accordingly.
// Replaces o.R.CampaignUsers with related.
// Sets related.R.User's CampaignUsers accordingly.
func (o *User) SetCampaignUsers(exec boil.Executor, insert bool, related ...*CampaignUser) error {
exec := boil.GetDB()
query := "update \"campaign_users\" set \"user_id\" = null where \"user_id\" = $1"
values := []interface{}{o.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values)
}
_, err := exec.Exec(query, values...)
if err != nil {
return errors.Wrap(err, "failed to remove relationships before set")
}
if o.R != nil {
for _, rel := range o.R.CampaignUsers {
rel.UserID.Valid = false
if rel.R == nil {
continue
}
rel.R.User = nil
}
o.R.CampaignUsers = nil
}
return o.AddCampaignUsers(exec, insert, related...)
}
// RemoveCampaignUsers relationships from objects passed in.
// Removes related items from R.CampaignUsers (uses pointer comparison, removal does not keep order)
// Sets related.R.User.
func (o *User) RemoveCampaignUsers(related ...*CampaignUser) error {
exec := boil.GetDB()
var err error
for _, rel := range related {
rel.UserID.Valid = false
if rel.R != nil {
rel.R.User = nil
}
if err = rel.Update(exec, "user_id"); err != nil {
return err
}
}
if o.R == nil {
return nil
}
for _, rel := range related {
for i, ri := range o.R.CampaignUsers {
if rel != ri {
continue
}
ln := len(o.R.CampaignUsers)
if ln > 1 && i < ln-1 {
o.R.CampaignUsers[i] = o.R.CampaignUsers[ln-1]
}
o.R.CampaignUsers = o.R.CampaignUsers[:ln-1]
break
}
}
return nil
}
// AddCreatorCampaigns adds the given related objects to the existing relationships
// of the user, optionally inserting them as new records.
// Appends related to o.R.CreatorCampaigns.
// Sets related.R.Creator appropriately.
func (o *User) AddCreatorCampaigns(exec boil.Executor, insert bool, related ...*Campaign) error {
var err error
exec := boil.GetDB()
for _, rel := range related {
if insert {
rel.CreatorID.Int = o.ID
rel.CreatorID.Valid = true
if err = rel.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table")
}
} else {
updateQuery := fmt.Sprintf(
"UPDATE \"campaigns\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, []string{"creator_id"}),
strmangle.WhereClause("\"", "\"", 2, campaignPrimaryKeyColumns),
)
values := []interface{}{o.ID, rel.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, updateQuery)
fmt.Fprintln(boil.DebugWriter, values)
}
if _, err = exec.Exec(updateQuery, values...); err != nil {
return errors.Wrap(err, "failed to update foreign table")
}
rel.CreatorID.Int = o.ID
rel.CreatorID.Valid = true
}
}
if o.R == nil {
o.R = &userR{
CreatorCampaigns: related,
}
} else {
o.R.CreatorCampaigns = append(o.R.CreatorCampaigns, related...)
}
for _, rel := range related {
if rel.R == nil {
rel.R = &campaignR{
Creator: o,
}
} else {
rel.R.Creator = o
}
}
return nil
}
// SetCreatorCampaigns removes all previously related items of the
// user replacing them completely with the passed
// in related items, optionally inserting them as new records.
// Sets o.R.Creator's CreatorCampaigns accordingly.
// Replaces o.R.CreatorCampaigns with related.
// Sets related.R.Creator's CreatorCampaigns accordingly.
func (o *User) SetCreatorCampaigns(exec boil.Executor, insert bool, related ...*Campaign) error {
exec := boil.GetDB()
query := "update \"campaigns\" set \"creator_id\" = null where \"creator_id\" = $1"
values := []interface{}{o.ID}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values)
}
_, err := exec.Exec(query, values...)
if err != nil {
return errors.Wrap(err, "failed to remove relationships before set")
}
if o.R != nil {
for _, rel := range o.R.CreatorCampaigns {
rel.CreatorID.Valid = false
if rel.R == nil {
continue
}
rel.R.Creator = nil
}
o.R.CreatorCampaigns = nil
}
return o.AddCreatorCampaigns(exec, insert, related...)
}
// RemoveCreatorCampaigns relationships from objects passed in.
// Removes related items from R.CreatorCampaigns (uses pointer comparison, removal does not keep order)
// Sets related.R.Creator.
func (o *User) RemoveCreatorCampaigns(related ...*Campaign) error {
exec := boil.GetDB()
var err error
for _, rel := range related {
rel.CreatorID.Valid = false
if rel.R != nil {
rel.R.Creator = nil
}
if err = rel.Update(exec, "creator_id"); err != nil {
return err
}
}
if o.R == nil {
return nil
}
for _, rel := range related {
for i, ri := range o.R.CreatorCampaigns {
if rel != ri {
continue
}
ln := len(o.R.CreatorCampaigns)
if ln > 1 && i < ln-1 {
o.R.CreatorCampaigns[i] = o.R.CreatorCampaigns[ln-1]
}
o.R.CreatorCampaigns = o.R.CreatorCampaigns[:ln-1]
break
}
}
return nil
}
// Users retrieves all the records.
func Users(mods ...qm.QueryMod) userQuery {
exec := boil.GetDB()
mods = append(mods, qm.From("\"users\""))
return userQuery{NewQuery(exec, mods...)}
}
// FindUser retrieves a single record by ID.
// If selectCols is empty Find will return all columns.
func FindUser(id int, selectCols ...string) (*User, error) {
exec := boil.GetDB()
userObj := &User{}
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
query := fmt.Sprintf(
"select %s from \"users\" where \"id\"=$1", sel,
)
q := queries.Raw(exec, query, id)
err := q.Bind(userObj)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "db: unable to select from users")
}
return userObj, nil
}
// Insert a single record.
// Whitelist behavior: If a whitelist is provided, only those columns supplied are inserted
// No whitelist behavior: Without a whitelist, columns are inferred by the following rules:
// - All columns without a default value are included (i.e. name, age)
// - All columns with a default, but non-zero are included (i.e. health = 75)
func (o *User) Insert(whitelist ...string) error {
exec := boil.GetDB()
if o == nil {
return errors.New("db: no users provided for insertion")
}
var err error
currTime := time.Now().In(boil.GetLocation())
if o.CreatedAt.IsZero() {
o.CreatedAt = currTime
}
if o.UpdatedAt.IsZero() {
o.UpdatedAt = currTime
}
if err := o.doBeforeInsertHooks(exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(userColumnsWithDefault, o)
key := makeCacheKey(whitelist, nzDefaults)
userInsertCacheMut.RLock()
cache, cached := userInsertCache[key]
userInsertCacheMut.RUnlock()
if !cached {
wl, returnColumns := strmangle.InsertColumnSet(
userColumns,
userColumnsWithDefault,
userColumnsWithoutDefault,
nzDefaults,
whitelist,
)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, wl)
if err != nil {
return err
}
cache.retMapping, err = queries.BindMapping(userType, userMapping, returnColumns)
if err != nil {
return err
}
if len(wl) != 0 {
cache.query = fmt.Sprintf("INSERT INTO \"users\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))
} else {
cache.query = "INSERT INTO \"users\" DEFAULT VALUES"
}
var queryOutput, queryReturning string
if len(cache.retMapping) != 0 {
queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\""))
}
if len(wl) != 0 {
cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
}
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRow(cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
} else {
_, err = exec.Exec(cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "db: unable to insert into users")
}
if !cached {
userInsertCacheMut.Lock()
userInsertCache[key] = cache
userInsertCacheMut.Unlock()
}
return o.doAfterInsertHooks(exec)
}
// Update updates the User.
// Whitelist behavior: If a whitelist is provided, only the columns given are updated.
// No whitelist behavior: Without a whitelist, columns are inferred by the following rules:
// - All columns are inferred to start with
// - All primary keys are subtracted from this set
// Update does not automatically update the record in case of default values. Use .Reload()
// to refresh the records.
func (o *User) Update(whitelist ...string) error {
exec := boil.GetDB()
currTime := time.Now().In(boil.GetLocation())
o.UpdatedAt = currTime
var err error
if err = o.doBeforeUpdateHooks(exec); err != nil {
return err
}
key := makeCacheKey(whitelist, nil)
userUpdateCacheMut.RLock()
cache, cached := userUpdateCache[key]
userUpdateCacheMut.RUnlock()
if !cached {
wl := strmangle.UpdateColumnSet(
userColumns,
userPrimaryKeyColumns,
whitelist,
)
if len(whitelist) == 0 {
wl = strmangle.SetComplement(wl, []string{"created_at"})
}
if len(wl) == 0 {
return errors.New("db: unable to update users, could not build whitelist")
}
cache.query = fmt.Sprintf("UPDATE \"users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, wl),
strmangle.WhereClause("\"", "\"", len(wl)+1, userPrimaryKeyColumns),
)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, append(wl, userPrimaryKeyColumns...))
if err != nil {
return err
}
}
values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, values)
}
_, err = exec.Exec(cache.query, values...)
if err != nil {
return errors.Wrap(err, "db: unable to update users row")
}
if !cached {
userUpdateCacheMut.Lock()
userUpdateCache[key] = cache
userUpdateCacheMut.Unlock()
}
return o.doAfterUpdateHooks(exec)
}
// UpdateAll updates all rows with the specified column values.
func (q userQuery) UpdateAll(cols M) error {
queries.SetUpdate(q.Query, cols)
_, err := q.Query.Exec()
if err != nil {
return errors.Wrap(err, "db: unable to update all for users")
}
return nil
}
// UpdateAll updates all rows with the specified column values.
func (o UserSlice) UpdateAll(exec boil.Executor, cols M) error {
exec := boil.GetDB()
ln := int64(len(o))
if ln == 0 {
return nil
}
if len(cols) == 0 {
return errors.New("db: 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)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := fmt.Sprintf("UPDATE \"users\" SET %s WHERE %s",
strmangle.SetParamNames("\"", "\"", 1, colNames),
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, userPrimaryKeyColumns, len(o)))
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "db: unable to update all in user slice")
}
return nil
}
// Upsert attempts an insert, and does an update or ignore on conflict.
func (o *User) Upsert(updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) error {
exec := boil.GetDB()
if o == nil {
return errors.New("db: no users provided for upsert")
}
currTime := time.Now().In(boil.GetLocation())
if o.CreatedAt.IsZero() {
o.CreatedAt = currTime
}
o.UpdatedAt = currTime
if err := o.doBeforeUpsertHooks(exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(userColumnsWithDefault, o)
// Build cache key in-line uglily - mysql vs postgres problems
buf := strmangle.GetBuffer()
if updateOnConflict {
buf.WriteByte('t')
} else {
buf.WriteByte('f')
}
buf.WriteByte('.')
for _, c := range conflictColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range updateColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range whitelist {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
key := buf.String()
strmangle.PutBuffer(buf)
userUpsertCacheMut.RLock()
cache, cached := userUpsertCache[key]
userUpsertCacheMut.RUnlock()
var err error
if !cached {
insert, ret := strmangle.InsertColumnSet(
userColumns,
userColumnsWithDefault,
userColumnsWithoutDefault,
nzDefaults,
whitelist,
)
update := strmangle.UpdateColumnSet(
userColumns,
userPrimaryKeyColumns,
updateColumns,
)
if len(update) == 0 {
return errors.New("db: unable to upsert users, could not build update column list")
}
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len(userPrimaryKeyColumns))
copy(conflict, userPrimaryKeyColumns)
}
cache.query = queries.BuildUpsertQueryPostgres(dialect, "\"users\"", updateOnConflict, ret, update, conflict, insert)
cache.valueMapping, err = queries.BindMapping(userType, userMapping, insert)
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping(userType, userMapping, 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.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, vals)
}
if len(cache.retMapping) != 0 {
err = exec.QueryRow(cache.query, vals...).Scan(returns...)
if err == sql.ErrNoRows {
err = nil // Postgres doesn't return anything when there's no update
}
} else {
_, err = exec.Exec(cache.query, vals...)
}
if err != nil {
return errors.Wrap(err, "db: unable to upsert users")
}
if !cached {
userUpsertCacheMut.Lock()
userUpsertCache[key] = cache
userUpsertCacheMut.Unlock()
}
return o.doAfterUpsertHooks(exec)
}
// Delete deletes a single User record.
// Delete will match against the primary key column to find the record to delete.
func (o *User) Delete() error {
exec := boil.GetDB()
if o == nil {
return errors.New("db: no User provided for delete")
}
if err := o.doBeforeDeleteHooks(exec); err != nil {
return err
}
args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), userPrimaryKeyMapping)
sql := "DELETE FROM \"users\" WHERE \"id\"=$1"
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "db: unable to delete from users")
}
if err := o.doAfterDeleteHooks(exec); err != nil {
return err
}
return nil
}
// DeleteAll deletes all matching rows.
func (q userQuery) DeleteAll() error {
if q.Query == nil {
return errors.New("db: no userQuery provided for delete all")
}
queries.SetDelete(q.Query)
_, err := q.Query.Exec()
if err != nil {
return errors.Wrap(err, "db: unable to delete all from users")
}
return nil
}
// DeleteAll deletes all rows in the slice.
func (o UserSlice) DeleteAll() error {
exec := boil.GetDB()
if o == nil {
return errors.New("db: no User slice provided for delete all")
}
if len(o) == 0 {
return nil
}
if len(userBeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(exec); err != nil {
return err
}
}
}
var args []interface{}
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "DELETE FROM \"users\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, userPrimaryKeyColumns, len(o))
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args)
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "db: unable to delete all from user slice")
}
if len(userAfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(exec); err != nil {
return err
}
}
}
return nil
}
// Reload refetches the object from the database
// using the primary keys.
func (o *User) Reload() error {
exec := boil.GetDB()
ret, err := FindUser(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 *UserSlice) ReloadAll() error {
exec := boil.GetDB()
if o == nil || len(*o) == 0 {
return nil
}
users := UserSlice{}
var args []interface{}
for _, obj := range *o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), userPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "SELECT \"users\".* FROM \"users\" WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, userPrimaryKeyColumns, len(*o))
q := queries.Raw(exec, sql, args...)
err := q.Bind(&users)
if err != nil {
return errors.Wrap(err, "db: unable to reload all in UserSlice")
}
*o = users
return nil
}
// UserExists checks if the User row exists.
func UserExists(id int) (bool, error) {
exec := boil.GetDB()
var exists bool
sql := "select exists(select 1 from \"users\" where \"id\"=$1 limit 1)"
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, id)
}
row := exec.QueryRow(sql, id)
err := row.Scan(&exists)
if err != nil {
return false, errors.Wrap(err, "db: unable to check if users exists")
}
return exists, nil
}