diff --git a/arcgis.go b/arcgis.go index 6afc19e2..850d9c89 100644 --- a/arcgis.go +++ b/arcgis.go @@ -22,6 +22,7 @@ import ( "github.com/Gleipnir-Technology/arcgis-go" "github.com/Gleipnir-Technology/arcgis-go/fieldseeker" + enums "github.com/Gleipnir-Technology/nidus-sync/enums" "github.com/Gleipnir-Technology/nidus-sync/models" "github.com/Gleipnir-Technology/nidus-sync/sql" "github.com/aarondl/opt/omit" @@ -415,6 +416,7 @@ func maintainOAuth(ctx context.Context, oauth *models.OauthToken) { err := refreshOAuth(ctx, oauth) if err != nil { slog.Error("Failed to refresh token", slog.String("err", err.Error())) + markTokenFailed(ctx, oauth) return } refreshDelay = time.Until(oauth.AccessTokenExpires) @@ -435,6 +437,33 @@ func maintainOAuth(ctx context.Context, oauth *models.OauthToken) { } +// Mark that a given oauth token has failed. This includes a notification to +// the user. +func markTokenFailed(ctx context.Context, oauth *models.OauthToken) { + oauthSetter := models.OauthTokenSetter{ + InvalidatedAt: omitnull.From(time.Now()), + } + err := oauth.Update(ctx, PGInstance.BobDB, &oauthSetter) + if err != nil { + slog.Error("Failed to mark token failed", slog.String("err", err.Error())) + } + user, err := models.FindUser(ctx, PGInstance.BobDB, oauth.UserID) + if err != nil { + slog.Error("Failed to get oauth user", slog.String("err", err.Error())) + return + } + notificationSetter := models.NotificationSetter{ + Message: omitnull.From("Oauth token invalidated"), + Link: omitnull.From("/oauth/refresh"), + Type: omitnull.From(enums.NotificationtypeOauthTokenInvalidated), + } + err = user.InsertUserNotifications(ctx, PGInstance.BobDB, ¬ificationSetter) + if err != nil { + slog.Error("Failed to get oauth user", slog.String("err", err.Error())) + return + } + slog.Info("Marked oauth token invalid", slog.Int("id", int(oauth.ID))) +} func refreshOAuth(ctx context.Context, oauth *models.OauthToken) error { baseURL := "https://www.arcgis.com/sharing/rest/oauth2/token/" diff --git a/dberrors/notification.bob.go b/dberrors/notification.bob.go new file mode 100644 index 00000000..49b22b5b --- /dev/null +++ b/dberrors/notification.bob.go @@ -0,0 +1,17 @@ +// Code generated by BobGen psql v0.41.1. DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package dberrors + +var NotificationErrors = ¬ificationErrors{ + ErrUniqueNotificationPkey: &UniqueConstraintError{ + schema: "", + table: "notification", + columns: []string{"id"}, + s: "notification_pkey", + }, +} + +type notificationErrors struct { + ErrUniqueNotificationPkey *UniqueConstraintError +} diff --git a/dbinfo/history_pointlocation.bob.go b/dbinfo/history_pointlocation.bob.go index 57efe864..804350f5 100644 --- a/dbinfo/history_pointlocation.bob.go +++ b/dbinfo/history_pointlocation.bob.go @@ -51,6 +51,15 @@ var HistoryPointlocations = Table[ Generated: false, AutoIncr: false, }, + Created: column{ + Name: "created", + DBType: "timestamp without time zone", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, Creationdate: column{ Name: "creationdate", DBType: "bigint", @@ -497,6 +506,7 @@ type historyPointlocationColumns struct { Accessdesc column Active column Comments column + Created column Creationdate column Creator column Description column @@ -545,7 +555,7 @@ type historyPointlocationColumns struct { func (c historyPointlocationColumns) AsSlice() []column { return []column{ - c.OrganizationID, c.Accessdesc, c.Active, c.Comments, c.Creationdate, c.Creator, c.Description, c.Externalid, c.Editdate, c.Editor, c.Globalid, c.Habitat, c.Jurisdiction, c.Larvinspectinterval, c.Lastinspectactiontaken, c.Lastinspectactivity, c.Lastinspectavglarvae, c.Lastinspectavgpupae, c.Lastinspectbreeding, c.Lastinspectconditions, c.Lastinspectdate, c.Lastinspectfieldspecies, c.Lastinspectlstages, c.Lasttreatactivity, c.Lasttreatdate, c.Lasttreatproduct, c.Lasttreatqty, c.Lasttreatqtyunit, c.Locationnumber, c.Name, c.Nextactiondatescheduled, c.Objectid, c.Priority, c.Stype, c.Symbology, c.Usetype, c.Waterorigin, c.X, c.Y, c.Zone, c.Zone2, c.GeometryX, c.GeometryY, c.Assignedtech, c.DeactivateReason, c.Scalarpriority, c.Sourcestatus, c.Version, + c.OrganizationID, c.Accessdesc, c.Active, c.Comments, c.Created, c.Creationdate, c.Creator, c.Description, c.Externalid, c.Editdate, c.Editor, c.Globalid, c.Habitat, c.Jurisdiction, c.Larvinspectinterval, c.Lastinspectactiontaken, c.Lastinspectactivity, c.Lastinspectavglarvae, c.Lastinspectavgpupae, c.Lastinspectbreeding, c.Lastinspectconditions, c.Lastinspectdate, c.Lastinspectfieldspecies, c.Lastinspectlstages, c.Lasttreatactivity, c.Lasttreatdate, c.Lasttreatproduct, c.Lasttreatqty, c.Lasttreatqtyunit, c.Locationnumber, c.Name, c.Nextactiondatescheduled, c.Objectid, c.Priority, c.Stype, c.Symbology, c.Usetype, c.Waterorigin, c.X, c.Y, c.Zone, c.Zone2, c.GeometryX, c.GeometryY, c.Assignedtech, c.DeactivateReason, c.Scalarpriority, c.Sourcestatus, c.Version, } } diff --git a/dbinfo/notification.bob.go b/dbinfo/notification.bob.go new file mode 100644 index 00000000..a601dfe3 --- /dev/null +++ b/dbinfo/notification.bob.go @@ -0,0 +1,147 @@ +// Code generated by BobGen psql v0.41.1. DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package dbinfo + +import "github.com/aarondl/opt/null" + +var Notifications = Table[ + notificationColumns, + notificationIndexes, + notificationForeignKeys, + notificationUniques, + notificationChecks, +]{ + Schema: "", + Name: "notification", + Columns: notificationColumns{ + ID: column{ + Name: "id", + DBType: "integer", + Default: "nextval('notification_id_seq'::regclass)", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + UserID: column{ + Name: "user_id", + DBType: "integer", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + Message: column{ + Name: "message", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + Link: column{ + Name: "link", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + Type: column{ + Name: "type", + DBType: "public.notificationtype", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: notificationIndexes{ + NotificationPkey: index{ + Type: "btree", + Name: "notification_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "notification_pkey", + Columns: []string{"id"}, + Comment: "", + }, + ForeignKeys: notificationForeignKeys{ + NotificationNotificationUserIDFkey: foreignKey{ + constraint: constraint{ + Name: "notification.notification_user_id_fkey", + Columns: []string{"user_id"}, + Comment: "", + }, + ForeignTable: "user_", + ForeignColumns: []string{"id"}, + }, + }, + + Comment: "", +} + +type notificationColumns struct { + ID column + UserID column + Message column + Link column + Type column +} + +func (c notificationColumns) AsSlice() []column { + return []column{ + c.ID, c.UserID, c.Message, c.Link, c.Type, + } +} + +type notificationIndexes struct { + NotificationPkey index +} + +func (i notificationIndexes) AsSlice() []index { + return []index{ + i.NotificationPkey, + } +} + +type notificationForeignKeys struct { + NotificationNotificationUserIDFkey foreignKey +} + +func (f notificationForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.NotificationNotificationUserIDFkey, + } +} + +type notificationUniques struct{} + +func (u notificationUniques) AsSlice() []constraint { + return []constraint{} +} + +type notificationChecks struct{} + +func (c notificationChecks) AsSlice() []check { + return []check{} +} diff --git a/dbinfo/oauth_token.bob.go b/dbinfo/oauth_token.bob.go index cfb49837..227a4bbd 100644 --- a/dbinfo/oauth_token.bob.go +++ b/dbinfo/oauth_token.bob.go @@ -96,6 +96,15 @@ var OauthTokens = Table[ Generated: false, AutoIncr: false, }, + InvalidatedAt: column{ + Name: "invalidated_at", + DBType: "timestamp without time zone", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, }, Indexes: oauthTokenIndexes{ OauthTokenPkey: index{ @@ -146,11 +155,12 @@ type oauthTokenColumns struct { ArcgisID column ArcgisLicenseTypeID column RefreshTokenExpires column + InvalidatedAt column } func (c oauthTokenColumns) AsSlice() []column { return []column{ - c.ID, c.AccessToken, c.AccessTokenExpires, c.RefreshToken, c.Username, c.UserID, c.ArcgisID, c.ArcgisLicenseTypeID, c.RefreshTokenExpires, + c.ID, c.AccessToken, c.AccessTokenExpires, c.RefreshToken, c.Username, c.UserID, c.ArcgisID, c.ArcgisLicenseTypeID, c.RefreshTokenExpires, c.InvalidatedAt, } } diff --git a/enums/enums.bob.go b/enums/enums.bob.go index f46609c2..4f38af90 100644 --- a/enums/enums.bob.go +++ b/enums/enums.bob.go @@ -186,3 +186,73 @@ func (e *Hashtype) Scan(value any) error { return nil } + +// Enum values for Notificationtype +const ( + NotificationtypeOauthTokenInvalidated Notificationtype = "oauth_token_invalidated" +) + +func AllNotificationtype() []Notificationtype { + return []Notificationtype{ + NotificationtypeOauthTokenInvalidated, + } +} + +type Notificationtype string + +func (e Notificationtype) String() string { + return string(e) +} + +func (e Notificationtype) Valid() bool { + switch e { + case NotificationtypeOauthTokenInvalidated: + return true + default: + return false + } +} + +// useful when testing in other packages +func (e Notificationtype) All() []Notificationtype { + return AllNotificationtype() +} + +func (e Notificationtype) MarshalText() ([]byte, error) { + return []byte(e), nil +} + +func (e *Notificationtype) UnmarshalText(text []byte) error { + return e.Scan(text) +} + +func (e Notificationtype) MarshalBinary() ([]byte, error) { + return []byte(e), nil +} + +func (e *Notificationtype) UnmarshalBinary(data []byte) error { + return e.Scan(data) +} + +func (e Notificationtype) Value() (driver.Value, error) { + return string(e), nil +} + +func (e *Notificationtype) Scan(value any) error { + switch x := value.(type) { + case string: + *e = Notificationtype(x) + case []byte: + *e = Notificationtype(x) + case nil: + return fmt.Errorf("cannot nil into Notificationtype") + default: + return fmt.Errorf("cannot scan type %T: %v", value, value) + } + + if !e.Valid() { + return fmt.Errorf("invalid Notificationtype value: %s", *e) + } + + return nil +} diff --git a/factory/bobfactory_context.bob.go b/factory/bobfactory_context.bob.go index 7a657129..b80fb70e 100644 --- a/factory/bobfactory_context.bob.go +++ b/factory/bobfactory_context.bob.go @@ -231,6 +231,10 @@ var ( historyZones2WithParentsCascadingCtx = newContextual[bool]("historyZones2WithParentsCascading") historyZones2RelOrganizationCtx = newContextual[bool]("history_zones2.organization.history_zones2.history_zones2_organization_id_fkey") + // Relationship Contexts for notification + notificationWithParentsCascadingCtx = newContextual[bool]("notificationWithParentsCascading") + notificationRelUserUserCtx = newContextual[bool]("notification.user_.notification.notification_user_id_fkey") + // Relationship Contexts for oauth_token oauthTokenWithParentsCascadingCtx = newContextual[bool]("oauthTokenWithParentsCascading") oauthTokenRelUserUserCtx = newContextual[bool]("oauth_token.user_.oauth_token.oauth_token_user_id_fkey") @@ -299,6 +303,7 @@ var ( // Relationship Contexts for user_ userWithParentsCascadingCtx = newContextual[bool]("userWithParentsCascading") + userRelUserNotificationsCtx = newContextual[bool]("notification.user_.notification.notification_user_id_fkey") userRelUserOauthTokensCtx = newContextual[bool]("oauth_token.user_.oauth_token.oauth_token_user_id_fkey") userRelOrganizationCtx = newContextual[bool]("organization.user_.user_.user__organization_id_fkey") ) diff --git a/factory/bobfactory_main.bob.go b/factory/bobfactory_main.bob.go index 1d559af4..c87d314e 100644 --- a/factory/bobfactory_main.bob.go +++ b/factory/bobfactory_main.bob.go @@ -69,6 +69,7 @@ type Factory struct { baseHistoryTreatmentareaMods HistoryTreatmentareaModSlice baseHistoryZoneMods HistoryZoneModSlice baseHistoryZones2Mods HistoryZones2ModSlice + baseNotificationMods NotificationModSlice baseOauthTokenMods OauthTokenModSlice baseOrganizationMods OrganizationModSlice baseSessionMods SessionModSlice @@ -2333,6 +2334,7 @@ func (f *Factory) FromExistingHistoryPointlocation(m *models.HistoryPointlocatio o.Accessdesc = func() null.Val[string] { return m.Accessdesc } o.Active = func() null.Val[int16] { return m.Active } o.Comments = func() null.Val[string] { return m.Comments } + o.Created = func() null.Val[time.Time] { return m.Created } o.Creationdate = func() null.Val[int64] { return m.Creationdate } o.Creator = func() null.Val[string] { return m.Creator } o.Description = func() null.Val[string] { return m.Description } @@ -3589,6 +3591,39 @@ func (f *Factory) FromExistingHistoryZones2(m *models.HistoryZones2) *HistoryZon return o } +func (f *Factory) NewNotification(mods ...NotificationMod) *NotificationTemplate { + return f.NewNotificationWithContext(context.Background(), mods...) +} + +func (f *Factory) NewNotificationWithContext(ctx context.Context, mods ...NotificationMod) *NotificationTemplate { + o := &NotificationTemplate{f: f} + + if f != nil { + f.baseNotificationMods.Apply(ctx, o) + } + + NotificationModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingNotification(m *models.Notification) *NotificationTemplate { + o := &NotificationTemplate{f: f, alreadyPersisted: true} + + o.ID = func() int32 { return m.ID } + o.UserID = func() null.Val[int32] { return m.UserID } + o.Message = func() null.Val[string] { return m.Message } + o.Link = func() null.Val[string] { return m.Link } + o.Type = func() null.Val[enums.Notificationtype] { return m.Type } + + ctx := context.Background() + if m.R.UserUser != nil { + NotificationMods.WithExistingUserUser(m.R.UserUser).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewOauthToken(mods ...OauthTokenMod) *OauthTokenTemplate { return f.NewOauthTokenWithContext(context.Background(), mods...) } @@ -3617,6 +3652,7 @@ func (f *Factory) FromExistingOauthToken(m *models.OauthToken) *OauthTokenTempla o.ArcgisID = func() null.Val[string] { return m.ArcgisID } o.ArcgisLicenseTypeID = func() null.Val[string] { return m.ArcgisLicenseTypeID } o.RefreshTokenExpires = func() time.Time { return m.RefreshTokenExpires } + o.InvalidatedAt = func() null.Val[time.Time] { return m.InvalidatedAt } ctx := context.Background() if m.R.UserUser != nil { @@ -3883,6 +3919,9 @@ func (f *Factory) FromExistingUser(m *models.User) *UserTemplate { o.PasswordHash = func() string { return m.PasswordHash } ctx := context.Background() + if len(m.R.UserNotifications) > 0 { + UserMods.AddExistingUserNotifications(m.R.UserNotifications...).Apply(ctx, o) + } if len(m.R.UserOauthTokens) > 0 { UserMods.AddExistingUserOauthTokens(m.R.UserOauthTokens...).Apply(ctx, o) } @@ -4341,6 +4380,14 @@ func (f *Factory) AddBaseHistoryZones2Mod(mods ...HistoryZones2Mod) { f.baseHistoryZones2Mods = append(f.baseHistoryZones2Mods, mods...) } +func (f *Factory) ClearBaseNotificationMods() { + f.baseNotificationMods = nil +} + +func (f *Factory) AddBaseNotificationMod(mods ...NotificationMod) { + f.baseNotificationMods = append(f.baseNotificationMods, mods...) +} + func (f *Factory) ClearBaseOauthTokenMods() { f.baseOauthTokenMods = nil } diff --git a/factory/bobfactory_main.bob_test.go b/factory/bobfactory_main.bob_test.go index bd614c5d..b8ee4f6a 100644 --- a/factory/bobfactory_main.bob_test.go +++ b/factory/bobfactory_main.bob_test.go @@ -1352,6 +1352,30 @@ func TestCreateHistoryZones2(t *testing.T) { } } +func TestCreateNotification(t *testing.T) { + if testDB == nil { + t.Skip("skipping test, no DSN provided") + } + + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + + tx, err := testDB.Begin(ctx) + if err != nil { + t.Fatalf("Error starting transaction: %v", err) + } + + defer func() { + if err := tx.Rollback(ctx); err != nil { + t.Fatalf("Error rolling back transaction: %v", err) + } + }() + + if _, err := New().NewNotificationWithContext(ctx).Create(ctx, tx); err != nil { + t.Fatalf("Error creating Notification: %v", err) + } +} + func TestCreateOauthToken(t *testing.T) { if testDB == nil { t.Skip("skipping test, no DSN provided") diff --git a/factory/bobfactory_random.bob.go b/factory/bobfactory_random.bob.go index db6097b6..7ae36acd 100644 --- a/factory/bobfactory_random.bob.go +++ b/factory/bobfactory_random.bob.go @@ -51,6 +51,16 @@ func random_enums_Hashtype(f *faker.Faker, limits ...string) enums.Hashtype { return all[f.IntBetween(0, len(all)-1)] } +func random_enums_Notificationtype(f *faker.Faker, limits ...string) enums.Notificationtype { + if f == nil { + f = &defaultFaker + } + + var e enums.Notificationtype + all := e.All() + return all[f.IntBetween(0, len(all)-1)] +} + func random_float64(f *faker.Faker, limits ...string) float64 { if f == nil { f = &defaultFaker diff --git a/factory/history_pointlocation.bob.go b/factory/history_pointlocation.bob.go index 4bbf27b2..14fa6c2c 100644 --- a/factory/history_pointlocation.bob.go +++ b/factory/history_pointlocation.bob.go @@ -6,6 +6,7 @@ package factory import ( "context" "testing" + "time" models "github.com/Gleipnir-Technology/nidus-sync/models" "github.com/aarondl/opt/null" @@ -40,6 +41,7 @@ type HistoryPointlocationTemplate struct { Accessdesc func() null.Val[string] Active func() null.Val[int16] Comments func() null.Val[string] + Created func() null.Val[time.Time] Creationdate func() null.Val[int64] Creator func() null.Val[string] Description func() null.Val[string] @@ -138,6 +140,10 @@ func (o HistoryPointlocationTemplate) BuildSetter() *models.HistoryPointlocation val := o.Comments() m.Comments = omitnull.FromNull(val) } + if o.Created != nil { + val := o.Created() + m.Created = omitnull.FromNull(val) + } if o.Creationdate != nil { val := o.Creationdate() m.Creationdate = omitnull.FromNull(val) @@ -348,6 +354,9 @@ func (o HistoryPointlocationTemplate) Build() *models.HistoryPointlocation { if o.Comments != nil { m.Comments = o.Comments() } + if o.Created != nil { + m.Created = o.Created() + } if o.Creationdate != nil { m.Creationdate = o.Creationdate() } @@ -635,6 +644,7 @@ func (m historyPointlocationMods) RandomizeAllColumns(f *faker.Faker) HistoryPoi HistoryPointlocationMods.RandomAccessdesc(f), HistoryPointlocationMods.RandomActive(f), HistoryPointlocationMods.RandomComments(f), + HistoryPointlocationMods.RandomCreated(f), HistoryPointlocationMods.RandomCreationdate(f), HistoryPointlocationMods.RandomCreator(f), HistoryPointlocationMods.RandomDescription(f), @@ -872,6 +882,59 @@ func (m historyPointlocationMods) RandomCommentsNotNull(f *faker.Faker) HistoryP }) } +// Set the model columns to this value +func (m historyPointlocationMods) Created(val null.Val[time.Time]) HistoryPointlocationMod { + return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { + o.Created = func() null.Val[time.Time] { return val } + }) +} + +// Set the Column from the function +func (m historyPointlocationMods) CreatedFunc(f func() null.Val[time.Time]) HistoryPointlocationMod { + return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { + o.Created = f + }) +} + +// Clear any values for the column +func (m historyPointlocationMods) UnsetCreated() HistoryPointlocationMod { + return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { + o.Created = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m historyPointlocationMods) RandomCreated(f *faker.Faker) HistoryPointlocationMod { + return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { + o.Created = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m historyPointlocationMods) RandomCreatedNotNull(f *faker.Faker) HistoryPointlocationMod { + return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { + o.Created = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + // Set the model columns to this value func (m historyPointlocationMods) Creationdate(val null.Val[int64]) HistoryPointlocationMod { return HistoryPointlocationModFunc(func(_ context.Context, o *HistoryPointlocationTemplate) { diff --git a/factory/notification.bob.go b/factory/notification.bob.go new file mode 100644 index 00000000..2224ceb9 --- /dev/null +++ b/factory/notification.bob.go @@ -0,0 +1,572 @@ +// Code generated by BobGen psql v0.41.1. DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package factory + +import ( + "context" + "testing" + + enums "github.com/Gleipnir-Technology/nidus-sync/enums" + models "github.com/Gleipnir-Technology/nidus-sync/models" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/jaswdr/faker/v2" + "github.com/stephenafamo/bob" +) + +type NotificationMod interface { + Apply(context.Context, *NotificationTemplate) +} + +type NotificationModFunc func(context.Context, *NotificationTemplate) + +func (f NotificationModFunc) Apply(ctx context.Context, n *NotificationTemplate) { + f(ctx, n) +} + +type NotificationModSlice []NotificationMod + +func (mods NotificationModSlice) Apply(ctx context.Context, n *NotificationTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// NotificationTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type NotificationTemplate struct { + ID func() int32 + UserID func() null.Val[int32] + Message func() null.Val[string] + Link func() null.Val[string] + Type func() null.Val[enums.Notificationtype] + + r notificationR + f *Factory + + alreadyPersisted bool +} + +type notificationR struct { + UserUser *notificationRUserUserR +} + +type notificationRUserUserR struct { + o *UserTemplate +} + +// Apply mods to the NotificationTemplate +func (o *NotificationTemplate) Apply(ctx context.Context, mods ...NotificationMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.Notification +// according to the relationships in the template. Nothing is inserted into the db +func (t NotificationTemplate) setModelRels(o *models.Notification) { + if t.r.UserUser != nil { + rel := t.r.UserUser.o.Build() + rel.R.UserNotifications = append(rel.R.UserNotifications, o) + o.UserID = null.From(rel.ID) // h2 + o.R.UserUser = rel + } +} + +// BuildSetter returns an *models.NotificationSetter +// this does nothing with the relationship templates +func (o NotificationTemplate) BuildSetter() *models.NotificationSetter { + m := &models.NotificationSetter{} + + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.UserID != nil { + val := o.UserID() + m.UserID = omitnull.FromNull(val) + } + if o.Message != nil { + val := o.Message() + m.Message = omitnull.FromNull(val) + } + if o.Link != nil { + val := o.Link() + m.Link = omitnull.FromNull(val) + } + if o.Type != nil { + val := o.Type() + m.Type = omitnull.FromNull(val) + } + + return m +} + +// BuildManySetter returns an []*models.NotificationSetter +// this does nothing with the relationship templates +func (o NotificationTemplate) BuildManySetter(number int) []*models.NotificationSetter { + m := make([]*models.NotificationSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.Notification +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use NotificationTemplate.Create +func (o NotificationTemplate) Build() *models.Notification { + m := &models.Notification{} + + if o.ID != nil { + m.ID = o.ID() + } + if o.UserID != nil { + m.UserID = o.UserID() + } + if o.Message != nil { + m.Message = o.Message() + } + if o.Link != nil { + m.Link = o.Link() + } + if o.Type != nil { + m.Type = o.Type() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.NotificationSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use NotificationTemplate.CreateMany +func (o NotificationTemplate) BuildMany(number int) models.NotificationSlice { + m := make(models.NotificationSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableNotification(m *models.NotificationSetter) { +} + +// insertOptRels creates and inserts any optional the relationships on *models.Notification +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *NotificationTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Notification) error { + var err error + + isUserUserDone, _ := notificationRelUserUserCtx.Value(ctx) + if !isUserUserDone && o.r.UserUser != nil { + ctx = notificationRelUserUserCtx.WithValue(ctx, true) + if o.r.UserUser.o.alreadyPersisted { + m.R.UserUser = o.r.UserUser.o.Build() + } else { + var rel0 *models.User + rel0, err = o.r.UserUser.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachUserUser(ctx, exec, rel0) + if err != nil { + return err + } + } + + } + + return err +} + +// Create builds a notification and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *NotificationTemplate) Create(ctx context.Context, exec bob.Executor) (*models.Notification, error) { + var err error + opt := o.BuildSetter() + ensureCreatableNotification(opt) + + m, err := models.Notifications.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a notification and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *NotificationTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.Notification { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a notification and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *NotificationTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.Notification { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple notifications and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o NotificationTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.NotificationSlice, error) { + var err error + m := make(models.NotificationSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple notifications and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o NotificationTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.NotificationSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple notifications and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o NotificationTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.NotificationSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// Notification has methods that act as mods for the NotificationTemplate +var NotificationMods notificationMods + +type notificationMods struct{} + +func (m notificationMods) RandomizeAllColumns(f *faker.Faker) NotificationMod { + return NotificationModSlice{ + NotificationMods.RandomID(f), + NotificationMods.RandomUserID(f), + NotificationMods.RandomMessage(f), + NotificationMods.RandomLink(f), + NotificationMods.RandomType(f), + } +} + +// Set the model columns to this value +func (m notificationMods) ID(val int32) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.ID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m notificationMods) IDFunc(f func() int32) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m notificationMods) UnsetID() NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m notificationMods) RandomID(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.ID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m notificationMods) UserID(val null.Val[int32]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.UserID = func() null.Val[int32] { return val } + }) +} + +// Set the Column from the function +func (m notificationMods) UserIDFunc(f func() null.Val[int32]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.UserID = f + }) +} + +// Clear any values for the column +func (m notificationMods) UnsetUserID() NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.UserID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m notificationMods) RandomUserID(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.UserID = func() null.Val[int32] { + if f == nil { + f = &defaultFaker + } + + val := random_int32(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m notificationMods) RandomUserIDNotNull(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.UserID = func() null.Val[int32] { + if f == nil { + f = &defaultFaker + } + + val := random_int32(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m notificationMods) Message(val null.Val[string]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Message = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m notificationMods) MessageFunc(f func() null.Val[string]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Message = f + }) +} + +// Clear any values for the column +func (m notificationMods) UnsetMessage() NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Message = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m notificationMods) RandomMessage(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Message = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m notificationMods) RandomMessageNotNull(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Message = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m notificationMods) Link(val null.Val[string]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Link = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m notificationMods) LinkFunc(f func() null.Val[string]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Link = f + }) +} + +// Clear any values for the column +func (m notificationMods) UnsetLink() NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Link = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m notificationMods) RandomLink(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Link = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m notificationMods) RandomLinkNotNull(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Link = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m notificationMods) Type(val null.Val[enums.Notificationtype]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Type = func() null.Val[enums.Notificationtype] { return val } + }) +} + +// Set the Column from the function +func (m notificationMods) TypeFunc(f func() null.Val[enums.Notificationtype]) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Type = f + }) +} + +// Clear any values for the column +func (m notificationMods) UnsetType() NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Type = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m notificationMods) RandomType(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Type = func() null.Val[enums.Notificationtype] { + if f == nil { + f = &defaultFaker + } + + val := random_enums_Notificationtype(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m notificationMods) RandomTypeNotNull(f *faker.Faker) NotificationMod { + return NotificationModFunc(func(_ context.Context, o *NotificationTemplate) { + o.Type = func() null.Val[enums.Notificationtype] { + if f == nil { + f = &defaultFaker + } + + val := random_enums_Notificationtype(f) + return null.From(val) + } + }) +} + +func (m notificationMods) WithParentsCascading() NotificationMod { + return NotificationModFunc(func(ctx context.Context, o *NotificationTemplate) { + if isDone, _ := notificationWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = notificationWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewUserWithContext(ctx, UserMods.WithParentsCascading()) + m.WithUserUser(related).Apply(ctx, o) + } + }) +} + +func (m notificationMods) WithUserUser(rel *UserTemplate) NotificationMod { + return NotificationModFunc(func(ctx context.Context, o *NotificationTemplate) { + o.r.UserUser = ¬ificationRUserUserR{ + o: rel, + } + }) +} + +func (m notificationMods) WithNewUserUser(mods ...UserMod) NotificationMod { + return NotificationModFunc(func(ctx context.Context, o *NotificationTemplate) { + related := o.f.NewUserWithContext(ctx, mods...) + + m.WithUserUser(related).Apply(ctx, o) + }) +} + +func (m notificationMods) WithExistingUserUser(em *models.User) NotificationMod { + return NotificationModFunc(func(ctx context.Context, o *NotificationTemplate) { + o.r.UserUser = ¬ificationRUserUserR{ + o: o.f.FromExistingUser(em), + } + }) +} + +func (m notificationMods) WithoutUserUser() NotificationMod { + return NotificationModFunc(func(ctx context.Context, o *NotificationTemplate) { + o.r.UserUser = nil + }) +} diff --git a/factory/oauth_token.bob.go b/factory/oauth_token.bob.go index 44c1aa65..1d36bf85 100644 --- a/factory/oauth_token.bob.go +++ b/factory/oauth_token.bob.go @@ -46,6 +46,7 @@ type OauthTokenTemplate struct { ArcgisID func() null.Val[string] ArcgisLicenseTypeID func() null.Val[string] RefreshTokenExpires func() time.Time + InvalidatedAt func() null.Val[time.Time] r oauthTokenR f *Factory @@ -120,6 +121,10 @@ func (o OauthTokenTemplate) BuildSetter() *models.OauthTokenSetter { val := o.RefreshTokenExpires() m.RefreshTokenExpires = omit.From(val) } + if o.InvalidatedAt != nil { + val := o.InvalidatedAt() + m.InvalidatedAt = omitnull.FromNull(val) + } return m } @@ -169,6 +174,9 @@ func (o OauthTokenTemplate) Build() *models.OauthToken { if o.RefreshTokenExpires != nil { m.RefreshTokenExpires = o.RefreshTokenExpires() } + if o.InvalidatedAt != nil { + m.InvalidatedAt = o.InvalidatedAt() + } o.setModelRels(m) @@ -337,6 +345,7 @@ func (m oauthTokenMods) RandomizeAllColumns(f *faker.Faker) OauthTokenMod { OauthTokenMods.RandomArcgisID(f), OauthTokenMods.RandomArcgisLicenseTypeID(f), OauthTokenMods.RandomRefreshTokenExpires(f), + OauthTokenMods.RandomInvalidatedAt(f), } } @@ -663,6 +672,59 @@ func (m oauthTokenMods) RandomRefreshTokenExpires(f *faker.Faker) OauthTokenMod }) } +// Set the model columns to this value +func (m oauthTokenMods) InvalidatedAt(val null.Val[time.Time]) OauthTokenMod { + return OauthTokenModFunc(func(_ context.Context, o *OauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { return val } + }) +} + +// Set the Column from the function +func (m oauthTokenMods) InvalidatedAtFunc(f func() null.Val[time.Time]) OauthTokenMod { + return OauthTokenModFunc(func(_ context.Context, o *OauthTokenTemplate) { + o.InvalidatedAt = f + }) +} + +// Clear any values for the column +func (m oauthTokenMods) UnsetInvalidatedAt() OauthTokenMod { + return OauthTokenModFunc(func(_ context.Context, o *OauthTokenTemplate) { + o.InvalidatedAt = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m oauthTokenMods) RandomInvalidatedAt(f *faker.Faker) OauthTokenMod { + return OauthTokenModFunc(func(_ context.Context, o *OauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m oauthTokenMods) RandomInvalidatedAtNotNull(f *faker.Faker) OauthTokenMod { + return OauthTokenModFunc(func(_ context.Context, o *OauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + func (m oauthTokenMods) WithParentsCascading() OauthTokenMod { return OauthTokenModFunc(func(ctx context.Context, o *OauthTokenTemplate) { if isDone, _ := oauthTokenWithParentsCascadingCtx.Value(ctx); isDone { diff --git a/factory/user_.bob.go b/factory/user_.bob.go index 2ec98b0d..be02c99d 100644 --- a/factory/user_.bob.go +++ b/factory/user_.bob.go @@ -58,10 +58,15 @@ type UserTemplate struct { } type userR struct { - UserOauthTokens []*userRUserOauthTokensR - Organization *userROrganizationR + UserNotifications []*userRUserNotificationsR + UserOauthTokens []*userRUserOauthTokensR + Organization *userROrganizationR } +type userRUserNotificationsR struct { + number int + o *NotificationTemplate +} type userRUserOauthTokensR struct { number int o *OauthTokenTemplate @@ -80,6 +85,19 @@ func (o *UserTemplate) Apply(ctx context.Context, mods ...UserMod) { // setModelRels creates and sets the relationships on *models.User // according to the relationships in the template. Nothing is inserted into the db func (t UserTemplate) setModelRels(o *models.User) { + if t.r.UserNotifications != nil { + rel := models.NotificationSlice{} + for _, r := range t.r.UserNotifications { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.UserID = null.From(o.ID) // h2 + rel.R.UserUser = o + } + rel = append(rel, related...) + } + o.R.UserNotifications = rel + } + if t.r.UserOauthTokens != nil { rel := models.OauthTokenSlice{} for _, r := range t.r.UserOauthTokens { @@ -256,6 +274,26 @@ func ensureCreatableUser(m *models.UserSetter) { func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.User) error { var err error + isUserNotificationsDone, _ := userRelUserNotificationsCtx.Value(ctx) + if !isUserNotificationsDone && o.r.UserNotifications != nil { + ctx = userRelUserNotificationsCtx.WithValue(ctx, true) + for _, r := range o.r.UserNotifications { + if r.o.alreadyPersisted { + m.R.UserNotifications = append(m.R.UserNotifications, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachUserNotifications(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + isUserOauthTokensDone, _ := userRelUserOauthTokensCtx.Value(ctx) if !isUserOauthTokensDone && o.r.UserOauthTokens != nil { ctx = userRelUserOauthTokensCtx.WithValue(ctx, true) @@ -263,12 +301,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.UserOauthTokens = append(m.R.UserOauthTokens, r.o.Build()) } else { - rel0, err := r.o.CreateMany(ctx, exec, r.number) + rel1, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachUserOauthTokens(ctx, exec, rel0...) + err = m.AttachUserOauthTokens(ctx, exec, rel1...) if err != nil { return err } @@ -282,12 +320,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if o.r.Organization.o.alreadyPersisted { m.R.Organization = o.r.Organization.o.Build() } else { - var rel1 *models.Organization - rel1, err = o.r.Organization.o.Create(ctx, exec) + var rel2 *models.Organization + rel2, err = o.r.Organization.o.Create(ctx, exec) if err != nil { return err } - err = m.AttachOrganization(ctx, exec, rel1) + err = m.AttachOrganization(ctx, exec, rel2) if err != nil { return err } @@ -972,6 +1010,54 @@ func (m userMods) WithoutOrganization() UserMod { }) } +func (m userMods) WithUserNotifications(number int, related *NotificationTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserNotifications = []*userRUserNotificationsR{{ + number: number, + o: related, + }} + }) +} + +func (m userMods) WithNewUserNotifications(number int, mods ...NotificationMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewNotificationWithContext(ctx, mods...) + m.WithUserNotifications(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddUserNotifications(number int, related *NotificationTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserNotifications = append(o.r.UserNotifications, &userRUserNotificationsR{ + number: number, + o: related, + }) + }) +} + +func (m userMods) AddNewUserNotifications(number int, mods ...NotificationMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewNotificationWithContext(ctx, mods...) + m.AddUserNotifications(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddExistingUserNotifications(existingModels ...*models.Notification) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + for _, em := range existingModels { + o.r.UserNotifications = append(o.r.UserNotifications, &userRUserNotificationsR{ + o: o.f.FromExistingNotification(em), + }) + } + }) +} + +func (m userMods) WithoutUserNotifications() UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserNotifications = nil + }) +} + func (m userMods) WithUserOauthTokens(number int, related *OauthTokenTemplate) UserMod { return UserModFunc(func(ctx context.Context, o *UserTemplate) { o.r.UserOauthTokens = []*userRUserOauthTokensR{{ diff --git a/html.go b/html.go index 2129aab4..32d45cb8 100644 --- a/html.go +++ b/html.go @@ -133,8 +133,10 @@ func htmlDashboard(ctx context.Context, w http.ResponseWriter, user *models.User var lastSync time.Time sync, err := org.FieldseekerSyncs(sm.OrderBy("created")).One(ctx, PGInstance.BobDB) if err != nil { - respondError(w, "Failed to get syncs", err, http.StatusInternalServerError) - return + if err.Error() != "sql: no rows in result set" { + respondError(w, "Failed to get syncs", err, http.StatusInternalServerError) + return + } } else { lastSync = sync.Created } diff --git a/migrations/00009_add_oauth_invalidated.sql b/migrations/00009_add_oauth_invalidated.sql new file mode 100644 index 00000000..4497fe7f --- /dev/null +++ b/migrations/00009_add_oauth_invalidated.sql @@ -0,0 +1,5 @@ +-- +goose Up +ALTER TABLE oauth_token ADD COLUMN invalidated_at timestamp without time zone; + +-- +goose Down +ALTER TABLE oauth_token DROP COLUMN invalidated_at; diff --git a/migrations/00010_add_notification.sql b/migrations/00010_add_notification.sql new file mode 100644 index 00000000..e8cb4d1b --- /dev/null +++ b/migrations/00010_add_notification.sql @@ -0,0 +1,16 @@ +-- +goose Up +CREATE TYPE NotificationType AS ENUM ( + 'oauth_token_invalidated'); + +CREATE TABLE notification ( + id SERIAL PRIMARY KEY, + user_id INTEGER REFERENCES user_(id), + message TEXT, + link TEXT, + type NotificationType); + + + +-- +goose Down +DROP TABLE notification; +DROP TYPE NotificationType; diff --git a/models/bob_joins.bob.go b/models/bob_joins.bob.go index 94bcb54d..f639286e 100644 --- a/models/bob_joins.bob.go +++ b/models/bob_joins.bob.go @@ -87,6 +87,7 @@ type joins[Q dialect.Joinable] struct { HistoryTreatmentareas joinSet[historyTreatmentareaJoins[Q]] HistoryZones joinSet[historyZoneJoins[Q]] HistoryZones2s joinSet[historyZones2Joins[Q]] + Notifications joinSet[notificationJoins[Q]] OauthTokens joinSet[oauthTokenJoins[Q]] Organizations joinSet[organizationJoins[Q]] Users joinSet[userJoins[Q]] @@ -157,6 +158,7 @@ func getJoins[Q dialect.Joinable]() joins[Q] { HistoryTreatmentareas: buildJoinSet[historyTreatmentareaJoins[Q]](HistoryTreatmentareas.Columns, buildHistoryTreatmentareaJoins), HistoryZones: buildJoinSet[historyZoneJoins[Q]](HistoryZones.Columns, buildHistoryZoneJoins), HistoryZones2s: buildJoinSet[historyZones2Joins[Q]](HistoryZones2s.Columns, buildHistoryZones2Joins), + Notifications: buildJoinSet[notificationJoins[Q]](Notifications.Columns, buildNotificationJoins), OauthTokens: buildJoinSet[oauthTokenJoins[Q]](OauthTokens.Columns, buildOauthTokenJoins), Organizations: buildJoinSet[organizationJoins[Q]](Organizations.Columns, buildOrganizationJoins), Users: buildJoinSet[userJoins[Q]](Users.Columns, buildUserJoins), diff --git a/models/bob_loaders.bob.go b/models/bob_loaders.bob.go index 4246fca1..3441ba56 100644 --- a/models/bob_loaders.bob.go +++ b/models/bob_loaders.bob.go @@ -72,6 +72,7 @@ type preloaders struct { HistoryTreatmentarea historyTreatmentareaPreloader HistoryZone historyZonePreloader HistoryZones2 historyZones2Preloader + Notification notificationPreloader OauthToken oauthTokenPreloader Organization organizationPreloader User userPreloader @@ -134,6 +135,7 @@ func getPreloaders() preloaders { HistoryTreatmentarea: buildHistoryTreatmentareaPreloader(), HistoryZone: buildHistoryZonePreloader(), HistoryZones2: buildHistoryZones2Preloader(), + Notification: buildNotificationPreloader(), OauthToken: buildOauthTokenPreloader(), Organization: buildOrganizationPreloader(), User: buildUserPreloader(), @@ -202,6 +204,7 @@ type thenLoaders[Q orm.Loadable] struct { HistoryTreatmentarea historyTreatmentareaThenLoader[Q] HistoryZone historyZoneThenLoader[Q] HistoryZones2 historyZones2ThenLoader[Q] + Notification notificationThenLoader[Q] OauthToken oauthTokenThenLoader[Q] Organization organizationThenLoader[Q] User userThenLoader[Q] @@ -264,6 +267,7 @@ func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] { HistoryTreatmentarea: buildHistoryTreatmentareaThenLoader[Q](), HistoryZone: buildHistoryZoneThenLoader[Q](), HistoryZones2: buildHistoryZones2ThenLoader[Q](), + Notification: buildNotificationThenLoader[Q](), OauthToken: buildOauthTokenThenLoader[Q](), Organization: buildOrganizationThenLoader[Q](), User: buildUserThenLoader[Q](), diff --git a/models/bob_types.bob_test.go b/models/bob_types.bob_test.go index 98e19510..2c853e3e 100644 --- a/models/bob_types.bob_test.go +++ b/models/bob_types.bob_test.go @@ -182,6 +182,9 @@ var _ bob.HookableType = &HistoryZone{} // Make sure the type HistoryZones2 runs hooks after queries var _ bob.HookableType = &HistoryZones2{} +// Make sure the type Notification runs hooks after queries +var _ bob.HookableType = &Notification{} + // Make sure the type OauthToken runs hooks after queries var _ bob.HookableType = &OauthToken{} @@ -194,6 +197,12 @@ var _ bob.HookableType = &Session{} // Make sure the type User runs hooks after queries var _ bob.HookableType = &User{} +// Make sure the type enums.Notificationtype satisfies database/sql.Scanner +var _ sql.Scanner = (*enums.Notificationtype)(nil) + +// Make sure the type enums.Notificationtype satisfies database/sql/driver.Valuer +var _ driver.Valuer = *new(enums.Notificationtype) + // Make sure the type enums.Arcgislicensetype satisfies database/sql.Scanner var _ sql.Scanner = (*enums.Arcgislicensetype)(nil) diff --git a/models/bob_where.bob.go b/models/bob_where.bob.go index 11d30f97..d6517dcd 100644 --- a/models/bob_where.bob.go +++ b/models/bob_where.bob.go @@ -73,6 +73,7 @@ func Where[Q psql.Filterable]() struct { HistoryTreatmentareas historyTreatmentareaWhere[Q] HistoryZones historyZoneWhere[Q] HistoryZones2s historyZones2Where[Q] + Notifications notificationWhere[Q] OauthTokens oauthTokenWhere[Q] Organizations organizationWhere[Q] Sessions sessionWhere[Q] @@ -135,6 +136,7 @@ func Where[Q psql.Filterable]() struct { HistoryTreatmentareas historyTreatmentareaWhere[Q] HistoryZones historyZoneWhere[Q] HistoryZones2s historyZones2Where[Q] + Notifications notificationWhere[Q] OauthTokens oauthTokenWhere[Q] Organizations organizationWhere[Q] Sessions sessionWhere[Q] @@ -196,6 +198,7 @@ func Where[Q psql.Filterable]() struct { HistoryTreatmentareas: buildHistoryTreatmentareaWhere[Q](HistoryTreatmentareas.Columns), HistoryZones: buildHistoryZoneWhere[Q](HistoryZones.Columns), HistoryZones2s: buildHistoryZones2Where[Q](HistoryZones2s.Columns), + Notifications: buildNotificationWhere[Q](Notifications.Columns), OauthTokens: buildOauthTokenWhere[Q](OauthTokens.Columns), Organizations: buildOrganizationWhere[Q](Organizations.Columns), Sessions: buildSessionWhere[Q](Sessions.Columns), diff --git a/models/history_pointlocation.bob.go b/models/history_pointlocation.bob.go index f709c1c7..83b75639 100644 --- a/models/history_pointlocation.bob.go +++ b/models/history_pointlocation.bob.go @@ -7,6 +7,7 @@ import ( "context" "fmt" "io" + "time" "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" @@ -25,54 +26,55 @@ import ( // HistoryPointlocation is an object representing the database table. type HistoryPointlocation struct { - OrganizationID int32 `db:"organization_id" ` - Accessdesc null.Val[string] `db:"accessdesc" ` - Active null.Val[int16] `db:"active" ` - Comments null.Val[string] `db:"comments" ` - Creationdate null.Val[int64] `db:"creationdate" ` - Creator null.Val[string] `db:"creator" ` - Description null.Val[string] `db:"description" ` - Externalid null.Val[string] `db:"externalid" ` - Editdate null.Val[int64] `db:"editdate" ` - Editor null.Val[string] `db:"editor" ` - Globalid null.Val[string] `db:"globalid" ` - Habitat null.Val[string] `db:"habitat" ` - Jurisdiction null.Val[string] `db:"jurisdiction" ` - Larvinspectinterval null.Val[int16] `db:"larvinspectinterval" ` - Lastinspectactiontaken null.Val[string] `db:"lastinspectactiontaken" ` - Lastinspectactivity null.Val[string] `db:"lastinspectactivity" ` - Lastinspectavglarvae null.Val[float64] `db:"lastinspectavglarvae" ` - Lastinspectavgpupae null.Val[float64] `db:"lastinspectavgpupae" ` - Lastinspectbreeding null.Val[string] `db:"lastinspectbreeding" ` - Lastinspectconditions null.Val[string] `db:"lastinspectconditions" ` - Lastinspectdate null.Val[int64] `db:"lastinspectdate" ` - Lastinspectfieldspecies null.Val[string] `db:"lastinspectfieldspecies" ` - Lastinspectlstages null.Val[string] `db:"lastinspectlstages" ` - Lasttreatactivity null.Val[string] `db:"lasttreatactivity" ` - Lasttreatdate null.Val[int64] `db:"lasttreatdate" ` - Lasttreatproduct null.Val[string] `db:"lasttreatproduct" ` - Lasttreatqty null.Val[float64] `db:"lasttreatqty" ` - Lasttreatqtyunit null.Val[string] `db:"lasttreatqtyunit" ` - Locationnumber null.Val[int64] `db:"locationnumber" ` - Name null.Val[string] `db:"name" ` - Nextactiondatescheduled null.Val[int64] `db:"nextactiondatescheduled" ` - Objectid int32 `db:"objectid,pk" ` - Priority null.Val[string] `db:"priority" ` - Stype null.Val[string] `db:"stype" ` - Symbology null.Val[string] `db:"symbology" ` - Usetype null.Val[string] `db:"usetype" ` - Waterorigin null.Val[string] `db:"waterorigin" ` - X null.Val[float64] `db:"x" ` - Y null.Val[float64] `db:"y" ` - Zone null.Val[string] `db:"zone" ` - Zone2 null.Val[string] `db:"zone2" ` - GeometryX null.Val[float64] `db:"geometry_x" ` - GeometryY null.Val[float64] `db:"geometry_y" ` - Assignedtech null.Val[string] `db:"assignedtech" ` - DeactivateReason null.Val[string] `db:"deactivate_reason" ` - Scalarpriority null.Val[int64] `db:"scalarpriority" ` - Sourcestatus null.Val[string] `db:"sourcestatus" ` - Version int32 `db:"version,pk" ` + OrganizationID int32 `db:"organization_id" ` + Accessdesc null.Val[string] `db:"accessdesc" ` + Active null.Val[int16] `db:"active" ` + Comments null.Val[string] `db:"comments" ` + Created null.Val[time.Time] `db:"created" ` + Creationdate null.Val[int64] `db:"creationdate" ` + Creator null.Val[string] `db:"creator" ` + Description null.Val[string] `db:"description" ` + Externalid null.Val[string] `db:"externalid" ` + Editdate null.Val[int64] `db:"editdate" ` + Editor null.Val[string] `db:"editor" ` + Globalid null.Val[string] `db:"globalid" ` + Habitat null.Val[string] `db:"habitat" ` + Jurisdiction null.Val[string] `db:"jurisdiction" ` + Larvinspectinterval null.Val[int16] `db:"larvinspectinterval" ` + Lastinspectactiontaken null.Val[string] `db:"lastinspectactiontaken" ` + Lastinspectactivity null.Val[string] `db:"lastinspectactivity" ` + Lastinspectavglarvae null.Val[float64] `db:"lastinspectavglarvae" ` + Lastinspectavgpupae null.Val[float64] `db:"lastinspectavgpupae" ` + Lastinspectbreeding null.Val[string] `db:"lastinspectbreeding" ` + Lastinspectconditions null.Val[string] `db:"lastinspectconditions" ` + Lastinspectdate null.Val[int64] `db:"lastinspectdate" ` + Lastinspectfieldspecies null.Val[string] `db:"lastinspectfieldspecies" ` + Lastinspectlstages null.Val[string] `db:"lastinspectlstages" ` + Lasttreatactivity null.Val[string] `db:"lasttreatactivity" ` + Lasttreatdate null.Val[int64] `db:"lasttreatdate" ` + Lasttreatproduct null.Val[string] `db:"lasttreatproduct" ` + Lasttreatqty null.Val[float64] `db:"lasttreatqty" ` + Lasttreatqtyunit null.Val[string] `db:"lasttreatqtyunit" ` + Locationnumber null.Val[int64] `db:"locationnumber" ` + Name null.Val[string] `db:"name" ` + Nextactiondatescheduled null.Val[int64] `db:"nextactiondatescheduled" ` + Objectid int32 `db:"objectid,pk" ` + Priority null.Val[string] `db:"priority" ` + Stype null.Val[string] `db:"stype" ` + Symbology null.Val[string] `db:"symbology" ` + Usetype null.Val[string] `db:"usetype" ` + Waterorigin null.Val[string] `db:"waterorigin" ` + X null.Val[float64] `db:"x" ` + Y null.Val[float64] `db:"y" ` + Zone null.Val[string] `db:"zone" ` + Zone2 null.Val[string] `db:"zone2" ` + GeometryX null.Val[float64] `db:"geometry_x" ` + GeometryY null.Val[float64] `db:"geometry_y" ` + Assignedtech null.Val[string] `db:"assignedtech" ` + DeactivateReason null.Val[string] `db:"deactivate_reason" ` + Scalarpriority null.Val[int64] `db:"scalarpriority" ` + Sourcestatus null.Val[string] `db:"sourcestatus" ` + Version int32 `db:"version,pk" ` R historyPointlocationR `db:"-" ` } @@ -95,13 +97,14 @@ type historyPointlocationR struct { func buildHistoryPointlocationColumns(alias string) historyPointlocationColumns { return historyPointlocationColumns{ ColumnsExpr: expr.NewColumnsExpr( - "organization_id", "accessdesc", "active", "comments", "creationdate", "creator", "description", "externalid", "editdate", "editor", "globalid", "habitat", "jurisdiction", "larvinspectinterval", "lastinspectactiontaken", "lastinspectactivity", "lastinspectavglarvae", "lastinspectavgpupae", "lastinspectbreeding", "lastinspectconditions", "lastinspectdate", "lastinspectfieldspecies", "lastinspectlstages", "lasttreatactivity", "lasttreatdate", "lasttreatproduct", "lasttreatqty", "lasttreatqtyunit", "locationnumber", "name", "nextactiondatescheduled", "objectid", "priority", "stype", "symbology", "usetype", "waterorigin", "x", "y", "zone", "zone2", "geometry_x", "geometry_y", "assignedtech", "deactivate_reason", "scalarpriority", "sourcestatus", "version", + "organization_id", "accessdesc", "active", "comments", "created", "creationdate", "creator", "description", "externalid", "editdate", "editor", "globalid", "habitat", "jurisdiction", "larvinspectinterval", "lastinspectactiontaken", "lastinspectactivity", "lastinspectavglarvae", "lastinspectavgpupae", "lastinspectbreeding", "lastinspectconditions", "lastinspectdate", "lastinspectfieldspecies", "lastinspectlstages", "lasttreatactivity", "lasttreatdate", "lasttreatproduct", "lasttreatqty", "lasttreatqtyunit", "locationnumber", "name", "nextactiondatescheduled", "objectid", "priority", "stype", "symbology", "usetype", "waterorigin", "x", "y", "zone", "zone2", "geometry_x", "geometry_y", "assignedtech", "deactivate_reason", "scalarpriority", "sourcestatus", "version", ).WithParent("history_pointlocation"), tableAlias: alias, OrganizationID: psql.Quote(alias, "organization_id"), Accessdesc: psql.Quote(alias, "accessdesc"), Active: psql.Quote(alias, "active"), Comments: psql.Quote(alias, "comments"), + Created: psql.Quote(alias, "created"), Creationdate: psql.Quote(alias, "creationdate"), Creator: psql.Quote(alias, "creator"), Description: psql.Quote(alias, "description"), @@ -156,6 +159,7 @@ type historyPointlocationColumns struct { Accessdesc psql.Expression Active psql.Expression Comments psql.Expression + Created psql.Expression Creationdate psql.Expression Creator psql.Expression Description psql.Expression @@ -214,58 +218,59 @@ func (historyPointlocationColumns) AliasedAs(alias string) historyPointlocationC // All values are optional, and do not have to be set // Generated columns are not included type HistoryPointlocationSetter struct { - OrganizationID omit.Val[int32] `db:"organization_id" ` - Accessdesc omitnull.Val[string] `db:"accessdesc" ` - Active omitnull.Val[int16] `db:"active" ` - Comments omitnull.Val[string] `db:"comments" ` - Creationdate omitnull.Val[int64] `db:"creationdate" ` - Creator omitnull.Val[string] `db:"creator" ` - Description omitnull.Val[string] `db:"description" ` - Externalid omitnull.Val[string] `db:"externalid" ` - Editdate omitnull.Val[int64] `db:"editdate" ` - Editor omitnull.Val[string] `db:"editor" ` - Globalid omitnull.Val[string] `db:"globalid" ` - Habitat omitnull.Val[string] `db:"habitat" ` - Jurisdiction omitnull.Val[string] `db:"jurisdiction" ` - Larvinspectinterval omitnull.Val[int16] `db:"larvinspectinterval" ` - Lastinspectactiontaken omitnull.Val[string] `db:"lastinspectactiontaken" ` - Lastinspectactivity omitnull.Val[string] `db:"lastinspectactivity" ` - Lastinspectavglarvae omitnull.Val[float64] `db:"lastinspectavglarvae" ` - Lastinspectavgpupae omitnull.Val[float64] `db:"lastinspectavgpupae" ` - Lastinspectbreeding omitnull.Val[string] `db:"lastinspectbreeding" ` - Lastinspectconditions omitnull.Val[string] `db:"lastinspectconditions" ` - Lastinspectdate omitnull.Val[int64] `db:"lastinspectdate" ` - Lastinspectfieldspecies omitnull.Val[string] `db:"lastinspectfieldspecies" ` - Lastinspectlstages omitnull.Val[string] `db:"lastinspectlstages" ` - Lasttreatactivity omitnull.Val[string] `db:"lasttreatactivity" ` - Lasttreatdate omitnull.Val[int64] `db:"lasttreatdate" ` - Lasttreatproduct omitnull.Val[string] `db:"lasttreatproduct" ` - Lasttreatqty omitnull.Val[float64] `db:"lasttreatqty" ` - Lasttreatqtyunit omitnull.Val[string] `db:"lasttreatqtyunit" ` - Locationnumber omitnull.Val[int64] `db:"locationnumber" ` - Name omitnull.Val[string] `db:"name" ` - Nextactiondatescheduled omitnull.Val[int64] `db:"nextactiondatescheduled" ` - Objectid omit.Val[int32] `db:"objectid,pk" ` - Priority omitnull.Val[string] `db:"priority" ` - Stype omitnull.Val[string] `db:"stype" ` - Symbology omitnull.Val[string] `db:"symbology" ` - Usetype omitnull.Val[string] `db:"usetype" ` - Waterorigin omitnull.Val[string] `db:"waterorigin" ` - X omitnull.Val[float64] `db:"x" ` - Y omitnull.Val[float64] `db:"y" ` - Zone omitnull.Val[string] `db:"zone" ` - Zone2 omitnull.Val[string] `db:"zone2" ` - GeometryX omitnull.Val[float64] `db:"geometry_x" ` - GeometryY omitnull.Val[float64] `db:"geometry_y" ` - Assignedtech omitnull.Val[string] `db:"assignedtech" ` - DeactivateReason omitnull.Val[string] `db:"deactivate_reason" ` - Scalarpriority omitnull.Val[int64] `db:"scalarpriority" ` - Sourcestatus omitnull.Val[string] `db:"sourcestatus" ` - Version omit.Val[int32] `db:"version,pk" ` + OrganizationID omit.Val[int32] `db:"organization_id" ` + Accessdesc omitnull.Val[string] `db:"accessdesc" ` + Active omitnull.Val[int16] `db:"active" ` + Comments omitnull.Val[string] `db:"comments" ` + Created omitnull.Val[time.Time] `db:"created" ` + Creationdate omitnull.Val[int64] `db:"creationdate" ` + Creator omitnull.Val[string] `db:"creator" ` + Description omitnull.Val[string] `db:"description" ` + Externalid omitnull.Val[string] `db:"externalid" ` + Editdate omitnull.Val[int64] `db:"editdate" ` + Editor omitnull.Val[string] `db:"editor" ` + Globalid omitnull.Val[string] `db:"globalid" ` + Habitat omitnull.Val[string] `db:"habitat" ` + Jurisdiction omitnull.Val[string] `db:"jurisdiction" ` + Larvinspectinterval omitnull.Val[int16] `db:"larvinspectinterval" ` + Lastinspectactiontaken omitnull.Val[string] `db:"lastinspectactiontaken" ` + Lastinspectactivity omitnull.Val[string] `db:"lastinspectactivity" ` + Lastinspectavglarvae omitnull.Val[float64] `db:"lastinspectavglarvae" ` + Lastinspectavgpupae omitnull.Val[float64] `db:"lastinspectavgpupae" ` + Lastinspectbreeding omitnull.Val[string] `db:"lastinspectbreeding" ` + Lastinspectconditions omitnull.Val[string] `db:"lastinspectconditions" ` + Lastinspectdate omitnull.Val[int64] `db:"lastinspectdate" ` + Lastinspectfieldspecies omitnull.Val[string] `db:"lastinspectfieldspecies" ` + Lastinspectlstages omitnull.Val[string] `db:"lastinspectlstages" ` + Lasttreatactivity omitnull.Val[string] `db:"lasttreatactivity" ` + Lasttreatdate omitnull.Val[int64] `db:"lasttreatdate" ` + Lasttreatproduct omitnull.Val[string] `db:"lasttreatproduct" ` + Lasttreatqty omitnull.Val[float64] `db:"lasttreatqty" ` + Lasttreatqtyunit omitnull.Val[string] `db:"lasttreatqtyunit" ` + Locationnumber omitnull.Val[int64] `db:"locationnumber" ` + Name omitnull.Val[string] `db:"name" ` + Nextactiondatescheduled omitnull.Val[int64] `db:"nextactiondatescheduled" ` + Objectid omit.Val[int32] `db:"objectid,pk" ` + Priority omitnull.Val[string] `db:"priority" ` + Stype omitnull.Val[string] `db:"stype" ` + Symbology omitnull.Val[string] `db:"symbology" ` + Usetype omitnull.Val[string] `db:"usetype" ` + Waterorigin omitnull.Val[string] `db:"waterorigin" ` + X omitnull.Val[float64] `db:"x" ` + Y omitnull.Val[float64] `db:"y" ` + Zone omitnull.Val[string] `db:"zone" ` + Zone2 omitnull.Val[string] `db:"zone2" ` + GeometryX omitnull.Val[float64] `db:"geometry_x" ` + GeometryY omitnull.Val[float64] `db:"geometry_y" ` + Assignedtech omitnull.Val[string] `db:"assignedtech" ` + DeactivateReason omitnull.Val[string] `db:"deactivate_reason" ` + Scalarpriority omitnull.Val[int64] `db:"scalarpriority" ` + Sourcestatus omitnull.Val[string] `db:"sourcestatus" ` + Version omit.Val[int32] `db:"version,pk" ` } func (s HistoryPointlocationSetter) SetColumns() []string { - vals := make([]string, 0, 48) + vals := make([]string, 0, 49) if s.OrganizationID.IsValue() { vals = append(vals, "organization_id") } @@ -278,6 +283,9 @@ func (s HistoryPointlocationSetter) SetColumns() []string { if !s.Comments.IsUnset() { vals = append(vals, "comments") } + if !s.Created.IsUnset() { + vals = append(vals, "created") + } if !s.Creationdate.IsUnset() { vals = append(vals, "creationdate") } @@ -426,6 +434,9 @@ func (s HistoryPointlocationSetter) Overwrite(t *HistoryPointlocation) { if !s.Comments.IsUnset() { t.Comments = s.Comments.MustGetNull() } + if !s.Created.IsUnset() { + t.Created = s.Created.MustGetNull() + } if !s.Creationdate.IsUnset() { t.Creationdate = s.Creationdate.MustGetNull() } @@ -566,7 +577,7 @@ func (s *HistoryPointlocationSetter) Apply(q *dialect.InsertQuery) { }) q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { - vals := make([]bob.Expression, 48) + vals := make([]bob.Expression, 49) if s.OrganizationID.IsValue() { vals[0] = psql.Arg(s.OrganizationID.MustGet()) } else { @@ -591,270 +602,276 @@ func (s *HistoryPointlocationSetter) Apply(q *dialect.InsertQuery) { vals[3] = psql.Raw("DEFAULT") } - if !s.Creationdate.IsUnset() { - vals[4] = psql.Arg(s.Creationdate.MustGetNull()) + if !s.Created.IsUnset() { + vals[4] = psql.Arg(s.Created.MustGetNull()) } else { vals[4] = psql.Raw("DEFAULT") } - if !s.Creator.IsUnset() { - vals[5] = psql.Arg(s.Creator.MustGetNull()) + if !s.Creationdate.IsUnset() { + vals[5] = psql.Arg(s.Creationdate.MustGetNull()) } else { vals[5] = psql.Raw("DEFAULT") } - if !s.Description.IsUnset() { - vals[6] = psql.Arg(s.Description.MustGetNull()) + if !s.Creator.IsUnset() { + vals[6] = psql.Arg(s.Creator.MustGetNull()) } else { vals[6] = psql.Raw("DEFAULT") } - if !s.Externalid.IsUnset() { - vals[7] = psql.Arg(s.Externalid.MustGetNull()) + if !s.Description.IsUnset() { + vals[7] = psql.Arg(s.Description.MustGetNull()) } else { vals[7] = psql.Raw("DEFAULT") } - if !s.Editdate.IsUnset() { - vals[8] = psql.Arg(s.Editdate.MustGetNull()) + if !s.Externalid.IsUnset() { + vals[8] = psql.Arg(s.Externalid.MustGetNull()) } else { vals[8] = psql.Raw("DEFAULT") } - if !s.Editor.IsUnset() { - vals[9] = psql.Arg(s.Editor.MustGetNull()) + if !s.Editdate.IsUnset() { + vals[9] = psql.Arg(s.Editdate.MustGetNull()) } else { vals[9] = psql.Raw("DEFAULT") } - if !s.Globalid.IsUnset() { - vals[10] = psql.Arg(s.Globalid.MustGetNull()) + if !s.Editor.IsUnset() { + vals[10] = psql.Arg(s.Editor.MustGetNull()) } else { vals[10] = psql.Raw("DEFAULT") } - if !s.Habitat.IsUnset() { - vals[11] = psql.Arg(s.Habitat.MustGetNull()) + if !s.Globalid.IsUnset() { + vals[11] = psql.Arg(s.Globalid.MustGetNull()) } else { vals[11] = psql.Raw("DEFAULT") } - if !s.Jurisdiction.IsUnset() { - vals[12] = psql.Arg(s.Jurisdiction.MustGetNull()) + if !s.Habitat.IsUnset() { + vals[12] = psql.Arg(s.Habitat.MustGetNull()) } else { vals[12] = psql.Raw("DEFAULT") } - if !s.Larvinspectinterval.IsUnset() { - vals[13] = psql.Arg(s.Larvinspectinterval.MustGetNull()) + if !s.Jurisdiction.IsUnset() { + vals[13] = psql.Arg(s.Jurisdiction.MustGetNull()) } else { vals[13] = psql.Raw("DEFAULT") } - if !s.Lastinspectactiontaken.IsUnset() { - vals[14] = psql.Arg(s.Lastinspectactiontaken.MustGetNull()) + if !s.Larvinspectinterval.IsUnset() { + vals[14] = psql.Arg(s.Larvinspectinterval.MustGetNull()) } else { vals[14] = psql.Raw("DEFAULT") } - if !s.Lastinspectactivity.IsUnset() { - vals[15] = psql.Arg(s.Lastinspectactivity.MustGetNull()) + if !s.Lastinspectactiontaken.IsUnset() { + vals[15] = psql.Arg(s.Lastinspectactiontaken.MustGetNull()) } else { vals[15] = psql.Raw("DEFAULT") } - if !s.Lastinspectavglarvae.IsUnset() { - vals[16] = psql.Arg(s.Lastinspectavglarvae.MustGetNull()) + if !s.Lastinspectactivity.IsUnset() { + vals[16] = psql.Arg(s.Lastinspectactivity.MustGetNull()) } else { vals[16] = psql.Raw("DEFAULT") } - if !s.Lastinspectavgpupae.IsUnset() { - vals[17] = psql.Arg(s.Lastinspectavgpupae.MustGetNull()) + if !s.Lastinspectavglarvae.IsUnset() { + vals[17] = psql.Arg(s.Lastinspectavglarvae.MustGetNull()) } else { vals[17] = psql.Raw("DEFAULT") } - if !s.Lastinspectbreeding.IsUnset() { - vals[18] = psql.Arg(s.Lastinspectbreeding.MustGetNull()) + if !s.Lastinspectavgpupae.IsUnset() { + vals[18] = psql.Arg(s.Lastinspectavgpupae.MustGetNull()) } else { vals[18] = psql.Raw("DEFAULT") } - if !s.Lastinspectconditions.IsUnset() { - vals[19] = psql.Arg(s.Lastinspectconditions.MustGetNull()) + if !s.Lastinspectbreeding.IsUnset() { + vals[19] = psql.Arg(s.Lastinspectbreeding.MustGetNull()) } else { vals[19] = psql.Raw("DEFAULT") } - if !s.Lastinspectdate.IsUnset() { - vals[20] = psql.Arg(s.Lastinspectdate.MustGetNull()) + if !s.Lastinspectconditions.IsUnset() { + vals[20] = psql.Arg(s.Lastinspectconditions.MustGetNull()) } else { vals[20] = psql.Raw("DEFAULT") } - if !s.Lastinspectfieldspecies.IsUnset() { - vals[21] = psql.Arg(s.Lastinspectfieldspecies.MustGetNull()) + if !s.Lastinspectdate.IsUnset() { + vals[21] = psql.Arg(s.Lastinspectdate.MustGetNull()) } else { vals[21] = psql.Raw("DEFAULT") } - if !s.Lastinspectlstages.IsUnset() { - vals[22] = psql.Arg(s.Lastinspectlstages.MustGetNull()) + if !s.Lastinspectfieldspecies.IsUnset() { + vals[22] = psql.Arg(s.Lastinspectfieldspecies.MustGetNull()) } else { vals[22] = psql.Raw("DEFAULT") } - if !s.Lasttreatactivity.IsUnset() { - vals[23] = psql.Arg(s.Lasttreatactivity.MustGetNull()) + if !s.Lastinspectlstages.IsUnset() { + vals[23] = psql.Arg(s.Lastinspectlstages.MustGetNull()) } else { vals[23] = psql.Raw("DEFAULT") } - if !s.Lasttreatdate.IsUnset() { - vals[24] = psql.Arg(s.Lasttreatdate.MustGetNull()) + if !s.Lasttreatactivity.IsUnset() { + vals[24] = psql.Arg(s.Lasttreatactivity.MustGetNull()) } else { vals[24] = psql.Raw("DEFAULT") } - if !s.Lasttreatproduct.IsUnset() { - vals[25] = psql.Arg(s.Lasttreatproduct.MustGetNull()) + if !s.Lasttreatdate.IsUnset() { + vals[25] = psql.Arg(s.Lasttreatdate.MustGetNull()) } else { vals[25] = psql.Raw("DEFAULT") } - if !s.Lasttreatqty.IsUnset() { - vals[26] = psql.Arg(s.Lasttreatqty.MustGetNull()) + if !s.Lasttreatproduct.IsUnset() { + vals[26] = psql.Arg(s.Lasttreatproduct.MustGetNull()) } else { vals[26] = psql.Raw("DEFAULT") } - if !s.Lasttreatqtyunit.IsUnset() { - vals[27] = psql.Arg(s.Lasttreatqtyunit.MustGetNull()) + if !s.Lasttreatqty.IsUnset() { + vals[27] = psql.Arg(s.Lasttreatqty.MustGetNull()) } else { vals[27] = psql.Raw("DEFAULT") } - if !s.Locationnumber.IsUnset() { - vals[28] = psql.Arg(s.Locationnumber.MustGetNull()) + if !s.Lasttreatqtyunit.IsUnset() { + vals[28] = psql.Arg(s.Lasttreatqtyunit.MustGetNull()) } else { vals[28] = psql.Raw("DEFAULT") } - if !s.Name.IsUnset() { - vals[29] = psql.Arg(s.Name.MustGetNull()) + if !s.Locationnumber.IsUnset() { + vals[29] = psql.Arg(s.Locationnumber.MustGetNull()) } else { vals[29] = psql.Raw("DEFAULT") } - if !s.Nextactiondatescheduled.IsUnset() { - vals[30] = psql.Arg(s.Nextactiondatescheduled.MustGetNull()) + if !s.Name.IsUnset() { + vals[30] = psql.Arg(s.Name.MustGetNull()) } else { vals[30] = psql.Raw("DEFAULT") } - if s.Objectid.IsValue() { - vals[31] = psql.Arg(s.Objectid.MustGet()) + if !s.Nextactiondatescheduled.IsUnset() { + vals[31] = psql.Arg(s.Nextactiondatescheduled.MustGetNull()) } else { vals[31] = psql.Raw("DEFAULT") } - if !s.Priority.IsUnset() { - vals[32] = psql.Arg(s.Priority.MustGetNull()) + if s.Objectid.IsValue() { + vals[32] = psql.Arg(s.Objectid.MustGet()) } else { vals[32] = psql.Raw("DEFAULT") } - if !s.Stype.IsUnset() { - vals[33] = psql.Arg(s.Stype.MustGetNull()) + if !s.Priority.IsUnset() { + vals[33] = psql.Arg(s.Priority.MustGetNull()) } else { vals[33] = psql.Raw("DEFAULT") } - if !s.Symbology.IsUnset() { - vals[34] = psql.Arg(s.Symbology.MustGetNull()) + if !s.Stype.IsUnset() { + vals[34] = psql.Arg(s.Stype.MustGetNull()) } else { vals[34] = psql.Raw("DEFAULT") } - if !s.Usetype.IsUnset() { - vals[35] = psql.Arg(s.Usetype.MustGetNull()) + if !s.Symbology.IsUnset() { + vals[35] = psql.Arg(s.Symbology.MustGetNull()) } else { vals[35] = psql.Raw("DEFAULT") } - if !s.Waterorigin.IsUnset() { - vals[36] = psql.Arg(s.Waterorigin.MustGetNull()) + if !s.Usetype.IsUnset() { + vals[36] = psql.Arg(s.Usetype.MustGetNull()) } else { vals[36] = psql.Raw("DEFAULT") } - if !s.X.IsUnset() { - vals[37] = psql.Arg(s.X.MustGetNull()) + if !s.Waterorigin.IsUnset() { + vals[37] = psql.Arg(s.Waterorigin.MustGetNull()) } else { vals[37] = psql.Raw("DEFAULT") } - if !s.Y.IsUnset() { - vals[38] = psql.Arg(s.Y.MustGetNull()) + if !s.X.IsUnset() { + vals[38] = psql.Arg(s.X.MustGetNull()) } else { vals[38] = psql.Raw("DEFAULT") } - if !s.Zone.IsUnset() { - vals[39] = psql.Arg(s.Zone.MustGetNull()) + if !s.Y.IsUnset() { + vals[39] = psql.Arg(s.Y.MustGetNull()) } else { vals[39] = psql.Raw("DEFAULT") } - if !s.Zone2.IsUnset() { - vals[40] = psql.Arg(s.Zone2.MustGetNull()) + if !s.Zone.IsUnset() { + vals[40] = psql.Arg(s.Zone.MustGetNull()) } else { vals[40] = psql.Raw("DEFAULT") } - if !s.GeometryX.IsUnset() { - vals[41] = psql.Arg(s.GeometryX.MustGetNull()) + if !s.Zone2.IsUnset() { + vals[41] = psql.Arg(s.Zone2.MustGetNull()) } else { vals[41] = psql.Raw("DEFAULT") } - if !s.GeometryY.IsUnset() { - vals[42] = psql.Arg(s.GeometryY.MustGetNull()) + if !s.GeometryX.IsUnset() { + vals[42] = psql.Arg(s.GeometryX.MustGetNull()) } else { vals[42] = psql.Raw("DEFAULT") } - if !s.Assignedtech.IsUnset() { - vals[43] = psql.Arg(s.Assignedtech.MustGetNull()) + if !s.GeometryY.IsUnset() { + vals[43] = psql.Arg(s.GeometryY.MustGetNull()) } else { vals[43] = psql.Raw("DEFAULT") } - if !s.DeactivateReason.IsUnset() { - vals[44] = psql.Arg(s.DeactivateReason.MustGetNull()) + if !s.Assignedtech.IsUnset() { + vals[44] = psql.Arg(s.Assignedtech.MustGetNull()) } else { vals[44] = psql.Raw("DEFAULT") } - if !s.Scalarpriority.IsUnset() { - vals[45] = psql.Arg(s.Scalarpriority.MustGetNull()) + if !s.DeactivateReason.IsUnset() { + vals[45] = psql.Arg(s.DeactivateReason.MustGetNull()) } else { vals[45] = psql.Raw("DEFAULT") } - if !s.Sourcestatus.IsUnset() { - vals[46] = psql.Arg(s.Sourcestatus.MustGetNull()) + if !s.Scalarpriority.IsUnset() { + vals[46] = psql.Arg(s.Scalarpriority.MustGetNull()) } else { vals[46] = psql.Raw("DEFAULT") } - if s.Version.IsValue() { - vals[47] = psql.Arg(s.Version.MustGet()) + if !s.Sourcestatus.IsUnset() { + vals[47] = psql.Arg(s.Sourcestatus.MustGetNull()) } else { vals[47] = psql.Raw("DEFAULT") } + if s.Version.IsValue() { + vals[48] = psql.Arg(s.Version.MustGet()) + } else { + vals[48] = psql.Raw("DEFAULT") + } + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") })) } @@ -864,7 +881,7 @@ func (s HistoryPointlocationSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { } func (s HistoryPointlocationSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 48) + exprs := make([]bob.Expression, 0, 49) if s.OrganizationID.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ @@ -894,6 +911,13 @@ func (s HistoryPointlocationSetter) Expressions(prefix ...string) []bob.Expressi }}) } + if !s.Created.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "created")...), + psql.Arg(s.Created), + }}) + } + if !s.Creationdate.IsUnset() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "creationdate")...), @@ -1515,6 +1539,7 @@ type historyPointlocationWhere[Q psql.Filterable] struct { Accessdesc psql.WhereNullMod[Q, string] Active psql.WhereNullMod[Q, int16] Comments psql.WhereNullMod[Q, string] + Created psql.WhereNullMod[Q, time.Time] Creationdate psql.WhereNullMod[Q, int64] Creator psql.WhereNullMod[Q, string] Description psql.WhereNullMod[Q, string] @@ -1571,6 +1596,7 @@ func buildHistoryPointlocationWhere[Q psql.Filterable](cols historyPointlocation Accessdesc: psql.WhereNull[Q, string](cols.Accessdesc), Active: psql.WhereNull[Q, int16](cols.Active), Comments: psql.WhereNull[Q, string](cols.Comments), + Created: psql.WhereNull[Q, time.Time](cols.Created), Creationdate: psql.WhereNull[Q, int64](cols.Creationdate), Creator: psql.WhereNull[Q, string](cols.Creator), Description: psql.WhereNull[Q, string](cols.Description), diff --git a/models/notification.bob.go b/models/notification.bob.go new file mode 100644 index 00000000..dbff0a62 --- /dev/null +++ b/models/notification.bob.go @@ -0,0 +1,683 @@ +// Code generated by BobGen psql v0.41.1. 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" + + enums "github.com/Gleipnir-Technology/nidus-sync/enums" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/stephenafamo/bob" + "github.com/stephenafamo/bob/dialect/psql" + "github.com/stephenafamo/bob/dialect/psql/dialect" + "github.com/stephenafamo/bob/dialect/psql/dm" + "github.com/stephenafamo/bob/dialect/psql/sm" + "github.com/stephenafamo/bob/dialect/psql/um" + "github.com/stephenafamo/bob/expr" + "github.com/stephenafamo/bob/mods" + "github.com/stephenafamo/bob/orm" + "github.com/stephenafamo/bob/types/pgtypes" +) + +// Notification is an object representing the database table. +type Notification struct { + ID int32 `db:"id,pk" ` + UserID null.Val[int32] `db:"user_id" ` + Message null.Val[string] `db:"message" ` + Link null.Val[string] `db:"link" ` + Type null.Val[enums.Notificationtype] `db:"type" ` + + R notificationR `db:"-" ` +} + +// NotificationSlice is an alias for a slice of pointers to Notification. +// This should almost always be used instead of []*Notification. +type NotificationSlice []*Notification + +// Notifications contains methods to work with the notification table +var Notifications = psql.NewTablex[*Notification, NotificationSlice, *NotificationSetter]("", "notification", buildNotificationColumns("notification")) + +// NotificationsQuery is a query on the notification table +type NotificationsQuery = *psql.ViewQuery[*Notification, NotificationSlice] + +// notificationR is where relationships are stored. +type notificationR struct { + UserUser *User // notification.notification_user_id_fkey +} + +func buildNotificationColumns(alias string) notificationColumns { + return notificationColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "id", "user_id", "message", "link", "type", + ).WithParent("notification"), + tableAlias: alias, + ID: psql.Quote(alias, "id"), + UserID: psql.Quote(alias, "user_id"), + Message: psql.Quote(alias, "message"), + Link: psql.Quote(alias, "link"), + Type: psql.Quote(alias, "type"), + } +} + +type notificationColumns struct { + expr.ColumnsExpr + tableAlias string + ID psql.Expression + UserID psql.Expression + Message psql.Expression + Link psql.Expression + Type psql.Expression +} + +func (c notificationColumns) Alias() string { + return c.tableAlias +} + +func (notificationColumns) AliasedAs(alias string) notificationColumns { + return buildNotificationColumns(alias) +} + +// NotificationSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type NotificationSetter struct { + ID omit.Val[int32] `db:"id,pk" ` + UserID omitnull.Val[int32] `db:"user_id" ` + Message omitnull.Val[string] `db:"message" ` + Link omitnull.Val[string] `db:"link" ` + Type omitnull.Val[enums.Notificationtype] `db:"type" ` +} + +func (s NotificationSetter) SetColumns() []string { + vals := make([]string, 0, 5) + if s.ID.IsValue() { + vals = append(vals, "id") + } + if !s.UserID.IsUnset() { + vals = append(vals, "user_id") + } + if !s.Message.IsUnset() { + vals = append(vals, "message") + } + if !s.Link.IsUnset() { + vals = append(vals, "link") + } + if !s.Type.IsUnset() { + vals = append(vals, "type") + } + return vals +} + +func (s NotificationSetter) Overwrite(t *Notification) { + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if !s.UserID.IsUnset() { + t.UserID = s.UserID.MustGetNull() + } + if !s.Message.IsUnset() { + t.Message = s.Message.MustGetNull() + } + if !s.Link.IsUnset() { + t.Link = s.Link.MustGetNull() + } + if !s.Type.IsUnset() { + t.Type = s.Type.MustGetNull() + } +} + +func (s *NotificationSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return Notifications.BeforeInsertHooks.RunHooks(ctx, exec, s) + }) + + q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { + vals := make([]bob.Expression, 5) + if s.ID.IsValue() { + vals[0] = psql.Arg(s.ID.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if !s.UserID.IsUnset() { + vals[1] = psql.Arg(s.UserID.MustGetNull()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if !s.Message.IsUnset() { + vals[2] = psql.Arg(s.Message.MustGetNull()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if !s.Link.IsUnset() { + vals[3] = psql.Arg(s.Link.MustGetNull()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if !s.Type.IsUnset() { + vals[4] = psql.Arg(s.Type.MustGetNull()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s NotificationSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s NotificationSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 5) + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if !s.UserID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "user_id")...), + psql.Arg(s.UserID), + }}) + } + + if !s.Message.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "message")...), + psql.Arg(s.Message), + }}) + } + + if !s.Link.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "link")...), + psql.Arg(s.Link), + }}) + } + + if !s.Type.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "type")...), + psql.Arg(s.Type), + }}) + } + + return exprs +} + +// FindNotification retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindNotification(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*Notification, error) { + if len(cols) == 0 { + return Notifications.Query( + sm.Where(Notifications.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return Notifications.Query( + sm.Where(Notifications.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(Notifications.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// NotificationExists checks the presence of a single record by primary key +func NotificationExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) { + return Notifications.Query( + sm.Where(Notifications.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after Notification is retrieved from the database +func (o *Notification) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = Notifications.AfterSelectHooks.RunHooks(ctx, exec, NotificationSlice{o}) + case bob.QueryTypeInsert: + ctx, err = Notifications.AfterInsertHooks.RunHooks(ctx, exec, NotificationSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = Notifications.AfterUpdateHooks.RunHooks(ctx, exec, NotificationSlice{o}) + case bob.QueryTypeDelete: + ctx, err = Notifications.AfterDeleteHooks.RunHooks(ctx, exec, NotificationSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the Notification +func (o *Notification) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *Notification) pkEQ() dialect.Expression { + return psql.Quote("notification", "id").EQ(bob.ExpressionFunc(func(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { + return o.primaryKeyVals().WriteSQL(ctx, w, d, start) + })) +} + +// Update uses an executor to update the Notification +func (o *Notification) Update(ctx context.Context, exec bob.Executor, s *NotificationSetter) error { + v, err := Notifications.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 Notification record with an executor +func (o *Notification) Delete(ctx context.Context, exec bob.Executor) error { + _, err := Notifications.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the Notification using the executor +func (o *Notification) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := Notifications.Query( + sm.Where(Notifications.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after NotificationSlice is retrieved from the database +func (o NotificationSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = Notifications.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = Notifications.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = Notifications.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = Notifications.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o NotificationSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("notification", "id").In(bob.ExpressionFunc(func(ctx context.Context, w io.Writer, 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 NotificationSlice) copyMatchingRows(from ...*Notification) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o NotificationSlice) 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 Notifications.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 *Notification: + o.copyMatchingRows(retrieved) + case []*Notification: + o.copyMatchingRows(retrieved...) + case NotificationSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a Notification or a slice of Notification + // then run the AfterUpdateHooks on the slice + _, err = Notifications.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o NotificationSlice) 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 Notifications.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 *Notification: + o.copyMatchingRows(retrieved) + case []*Notification: + o.copyMatchingRows(retrieved...) + case NotificationSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a Notification or a slice of Notification + // then run the AfterDeleteHooks on the slice + _, err = Notifications.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o NotificationSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals NotificationSetter) error { + if len(o) == 0 { + return nil + } + + _, err := Notifications.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o NotificationSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := Notifications.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o NotificationSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := Notifications.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// UserUser starts a query for related objects on user_ +func (o *Notification) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + return Users.Query(append(mods, + sm.Where(Users.Columns.ID.EQ(psql.Arg(o.UserID))), + )...) +} + +func (os NotificationSlice) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + pkUserID := make(pgtypes.Array[null.Val[int32]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkUserID = append(pkUserID, o.UserID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkUserID), "integer[]")), + )) + + return Users.Query(append(mods, + sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +func attachNotificationUserUser0(ctx context.Context, exec bob.Executor, count int, notification0 *Notification, user1 *User) (*Notification, error) { + setter := &NotificationSetter{ + UserID: omitnull.From(user1.ID), + } + + err := notification0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachNotificationUserUser0: %w", err) + } + + return notification0, nil +} + +func (notification0 *Notification) InsertUserUser(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 = attachNotificationUserUser0(ctx, exec, 1, notification0, user1) + if err != nil { + return err + } + + notification0.R.UserUser = user1 + + user1.R.UserNotifications = append(user1.R.UserNotifications, notification0) + + return nil +} + +func (notification0 *Notification) AttachUserUser(ctx context.Context, exec bob.Executor, user1 *User) error { + var err error + + _, err = attachNotificationUserUser0(ctx, exec, 1, notification0, user1) + if err != nil { + return err + } + + notification0.R.UserUser = user1 + + user1.R.UserNotifications = append(user1.R.UserNotifications, notification0) + + return nil +} + +type notificationWhere[Q psql.Filterable] struct { + ID psql.WhereMod[Q, int32] + UserID psql.WhereNullMod[Q, int32] + Message psql.WhereNullMod[Q, string] + Link psql.WhereNullMod[Q, string] + Type psql.WhereNullMod[Q, enums.Notificationtype] +} + +func (notificationWhere[Q]) AliasedAs(alias string) notificationWhere[Q] { + return buildNotificationWhere[Q](buildNotificationColumns(alias)) +} + +func buildNotificationWhere[Q psql.Filterable](cols notificationColumns) notificationWhere[Q] { + return notificationWhere[Q]{ + ID: psql.Where[Q, int32](cols.ID), + UserID: psql.WhereNull[Q, int32](cols.UserID), + Message: psql.WhereNull[Q, string](cols.Message), + Link: psql.WhereNull[Q, string](cols.Link), + Type: psql.WhereNull[Q, enums.Notificationtype](cols.Type), + } +} + +func (o *Notification) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "UserUser": + rel, ok := retrieved.(*User) + if !ok { + return fmt.Errorf("notification cannot load %T as %q", retrieved, name) + } + + o.R.UserUser = rel + + if rel != nil { + rel.R.UserNotifications = NotificationSlice{o} + } + return nil + default: + return fmt.Errorf("notification has no relationship %q", name) + } +} + +type notificationPreloader struct { + UserUser func(...psql.PreloadOption) psql.Preloader +} + +func buildNotificationPreloader() notificationPreloader { + return notificationPreloader{ + UserUser: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*User, UserSlice](psql.PreloadRel{ + Name: "UserUser", + Sides: []psql.PreloadSide{ + { + From: Notifications, + To: Users, + FromColumns: []string{"user_id"}, + ToColumns: []string{"id"}, + }, + }, + }, Users.Columns.Names(), opts...) + }, + } +} + +type notificationThenLoader[Q orm.Loadable] struct { + UserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildNotificationThenLoader[Q orm.Loadable]() notificationThenLoader[Q] { + type UserUserLoadInterface interface { + LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return notificationThenLoader[Q]{ + UserUser: thenLoadBuilder[Q]( + "UserUser", + func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadUserUser(ctx, exec, mods...) + }, + ), + } +} + +// LoadUserUser loads the notification's UserUser into the .R struct +func (o *Notification) LoadUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.UserUser = nil + + related, err := o.UserUser(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.UserNotifications = NotificationSlice{o} + + o.R.UserUser = related + return nil +} + +// LoadUserUser loads the notification's UserUser into the .R struct +func (os NotificationSlice) LoadUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + users, err := os.UserUser(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range users { + if !o.UserID.IsValue() { + continue + } + + if !(o.UserID.IsValue() && o.UserID.MustGet() == rel.ID) { + continue + } + + rel.R.UserNotifications = append(rel.R.UserNotifications, o) + + o.R.UserUser = rel + break + } + } + + return nil +} + +type notificationJoins[Q dialect.Joinable] struct { + typ string + UserUser modAs[Q, userColumns] +} + +func (j notificationJoins[Q]) aliasedAs(alias string) notificationJoins[Q] { + return buildNotificationJoins[Q](buildNotificationColumns(alias), j.typ) +} + +func buildNotificationJoins[Q dialect.Joinable](cols notificationColumns, typ string) notificationJoins[Q] { + return notificationJoins[Q]{ + typ: typ, + UserUser: modAs[Q, userColumns]{ + c: Users.Columns, + f: func(to userColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Users.Name().As(to.Alias())).On( + to.ID.EQ(cols.UserID), + )) + } + + return mods + }, + }, + } +} diff --git a/models/oauth_token.bob.go b/models/oauth_token.bob.go index 89d20aa4..109ec9ed 100644 --- a/models/oauth_token.bob.go +++ b/models/oauth_token.bob.go @@ -26,15 +26,16 @@ import ( // OauthToken is an object representing the database table. type OauthToken struct { - ID int32 `db:"id,pk" ` - AccessToken string `db:"access_token" ` - AccessTokenExpires time.Time `db:"access_token_expires" ` - RefreshToken string `db:"refresh_token" ` - Username string `db:"username" ` - UserID int32 `db:"user_id" ` - ArcgisID null.Val[string] `db:"arcgis_id" ` - ArcgisLicenseTypeID null.Val[string] `db:"arcgis_license_type_id" ` - RefreshTokenExpires time.Time `db:"refresh_token_expires" ` + ID int32 `db:"id,pk" ` + AccessToken string `db:"access_token" ` + AccessTokenExpires time.Time `db:"access_token_expires" ` + RefreshToken string `db:"refresh_token" ` + Username string `db:"username" ` + UserID int32 `db:"user_id" ` + ArcgisID null.Val[string] `db:"arcgis_id" ` + ArcgisLicenseTypeID null.Val[string] `db:"arcgis_license_type_id" ` + RefreshTokenExpires time.Time `db:"refresh_token_expires" ` + InvalidatedAt null.Val[time.Time] `db:"invalidated_at" ` R oauthTokenR `db:"-" ` } @@ -57,7 +58,7 @@ type oauthTokenR struct { func buildOauthTokenColumns(alias string) oauthTokenColumns { return oauthTokenColumns{ ColumnsExpr: expr.NewColumnsExpr( - "id", "access_token", "access_token_expires", "refresh_token", "username", "user_id", "arcgis_id", "arcgis_license_type_id", "refresh_token_expires", + "id", "access_token", "access_token_expires", "refresh_token", "username", "user_id", "arcgis_id", "arcgis_license_type_id", "refresh_token_expires", "invalidated_at", ).WithParent("oauth_token"), tableAlias: alias, ID: psql.Quote(alias, "id"), @@ -69,6 +70,7 @@ func buildOauthTokenColumns(alias string) oauthTokenColumns { ArcgisID: psql.Quote(alias, "arcgis_id"), ArcgisLicenseTypeID: psql.Quote(alias, "arcgis_license_type_id"), RefreshTokenExpires: psql.Quote(alias, "refresh_token_expires"), + InvalidatedAt: psql.Quote(alias, "invalidated_at"), } } @@ -84,6 +86,7 @@ type oauthTokenColumns struct { ArcgisID psql.Expression ArcgisLicenseTypeID psql.Expression RefreshTokenExpires psql.Expression + InvalidatedAt psql.Expression } func (c oauthTokenColumns) Alias() string { @@ -98,19 +101,20 @@ func (oauthTokenColumns) AliasedAs(alias string) oauthTokenColumns { // All values are optional, and do not have to be set // Generated columns are not included type OauthTokenSetter struct { - ID omit.Val[int32] `db:"id,pk" ` - AccessToken omit.Val[string] `db:"access_token" ` - AccessTokenExpires omit.Val[time.Time] `db:"access_token_expires" ` - RefreshToken omit.Val[string] `db:"refresh_token" ` - Username omit.Val[string] `db:"username" ` - UserID omit.Val[int32] `db:"user_id" ` - ArcgisID omitnull.Val[string] `db:"arcgis_id" ` - ArcgisLicenseTypeID omitnull.Val[string] `db:"arcgis_license_type_id" ` - RefreshTokenExpires omit.Val[time.Time] `db:"refresh_token_expires" ` + ID omit.Val[int32] `db:"id,pk" ` + AccessToken omit.Val[string] `db:"access_token" ` + AccessTokenExpires omit.Val[time.Time] `db:"access_token_expires" ` + RefreshToken omit.Val[string] `db:"refresh_token" ` + Username omit.Val[string] `db:"username" ` + UserID omit.Val[int32] `db:"user_id" ` + ArcgisID omitnull.Val[string] `db:"arcgis_id" ` + ArcgisLicenseTypeID omitnull.Val[string] `db:"arcgis_license_type_id" ` + RefreshTokenExpires omit.Val[time.Time] `db:"refresh_token_expires" ` + InvalidatedAt omitnull.Val[time.Time] `db:"invalidated_at" ` } func (s OauthTokenSetter) SetColumns() []string { - vals := make([]string, 0, 9) + vals := make([]string, 0, 10) if s.ID.IsValue() { vals = append(vals, "id") } @@ -138,6 +142,9 @@ func (s OauthTokenSetter) SetColumns() []string { if s.RefreshTokenExpires.IsValue() { vals = append(vals, "refresh_token_expires") } + if !s.InvalidatedAt.IsUnset() { + vals = append(vals, "invalidated_at") + } return vals } @@ -169,6 +176,9 @@ func (s OauthTokenSetter) Overwrite(t *OauthToken) { if s.RefreshTokenExpires.IsValue() { t.RefreshTokenExpires = s.RefreshTokenExpires.MustGet() } + if !s.InvalidatedAt.IsUnset() { + t.InvalidatedAt = s.InvalidatedAt.MustGetNull() + } } func (s *OauthTokenSetter) Apply(q *dialect.InsertQuery) { @@ -177,7 +187,7 @@ func (s *OauthTokenSetter) Apply(q *dialect.InsertQuery) { }) q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.Writer, d bob.Dialect, start int) ([]any, error) { - vals := make([]bob.Expression, 9) + vals := make([]bob.Expression, 10) if s.ID.IsValue() { vals[0] = psql.Arg(s.ID.MustGet()) } else { @@ -232,6 +242,12 @@ func (s *OauthTokenSetter) Apply(q *dialect.InsertQuery) { vals[8] = psql.Raw("DEFAULT") } + if !s.InvalidatedAt.IsUnset() { + vals[9] = psql.Arg(s.InvalidatedAt.MustGetNull()) + } else { + vals[9] = psql.Raw("DEFAULT") + } + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") })) } @@ -241,7 +257,7 @@ func (s OauthTokenSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { } func (s OauthTokenSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 9) + exprs := make([]bob.Expression, 0, 10) if s.ID.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ @@ -306,6 +322,13 @@ func (s OauthTokenSetter) Expressions(prefix ...string) []bob.Expression { }}) } + if !s.InvalidatedAt.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "invalidated_at")...), + psql.Arg(s.InvalidatedAt), + }}) + } + return exprs } @@ -614,6 +637,7 @@ type oauthTokenWhere[Q psql.Filterable] struct { ArcgisID psql.WhereNullMod[Q, string] ArcgisLicenseTypeID psql.WhereNullMod[Q, string] RefreshTokenExpires psql.WhereMod[Q, time.Time] + InvalidatedAt psql.WhereNullMod[Q, time.Time] } func (oauthTokenWhere[Q]) AliasedAs(alias string) oauthTokenWhere[Q] { @@ -631,6 +655,7 @@ func buildOauthTokenWhere[Q psql.Filterable](cols oauthTokenColumns) oauthTokenW ArcgisID: psql.WhereNull[Q, string](cols.ArcgisID), ArcgisLicenseTypeID: psql.WhereNull[Q, string](cols.ArcgisLicenseTypeID), RefreshTokenExpires: psql.Where[Q, time.Time](cols.RefreshTokenExpires), + InvalidatedAt: psql.WhereNull[Q, time.Time](cols.InvalidatedAt), } } diff --git a/models/user_.bob.go b/models/user_.bob.go index 32bbc3bb..d21f84de 100644 --- a/models/user_.bob.go +++ b/models/user_.bob.go @@ -55,8 +55,9 @@ type UsersQuery = *psql.ViewQuery[*User, UserSlice] // userR is where relationships are stored. type userR struct { - UserOauthTokens OauthTokenSlice // oauth_token.oauth_token_user_id_fkey - Organization *Organization // user_.user__organization_id_fkey + UserNotifications NotificationSlice // notification.notification_user_id_fkey + UserOauthTokens OauthTokenSlice // oauth_token.oauth_token_user_id_fkey + Organization *Organization // user_.user__organization_id_fkey } func buildUserColumns(alias string) userColumns { @@ -603,6 +604,30 @@ func (o UserSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { return nil } +// UserNotifications starts a query for related objects on notification +func (o *User) UserNotifications(mods ...bob.Mod[*dialect.SelectQuery]) NotificationsQuery { + return Notifications.Query(append(mods, + sm.Where(Notifications.Columns.UserID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os UserSlice) UserNotifications(mods ...bob.Mod[*dialect.SelectQuery]) NotificationsQuery { + pkID := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkID = append(pkID, o.ID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")), + )) + + return Notifications.Query(append(mods, + sm.Where(psql.Group(Notifications.Columns.UserID).OP("IN", PKArgExpr)), + )...) +} + // UserOauthTokens starts a query for related objects on oauth_token func (o *User) UserOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) OauthTokensQuery { return OauthTokens.Query(append(mods, @@ -651,6 +676,74 @@ func (os UserSlice) Organization(mods ...bob.Mod[*dialect.SelectQuery]) Organiza )...) } +func insertUserUserNotifications0(ctx context.Context, exec bob.Executor, notifications1 []*NotificationSetter, user0 *User) (NotificationSlice, error) { + for i := range notifications1 { + notifications1[i].UserID = omitnull.From(user0.ID) + } + + ret, err := Notifications.Insert(bob.ToMods(notifications1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertUserUserNotifications0: %w", err) + } + + return ret, nil +} + +func attachUserUserNotifications0(ctx context.Context, exec bob.Executor, count int, notifications1 NotificationSlice, user0 *User) (NotificationSlice, error) { + setter := &NotificationSetter{ + UserID: omitnull.From(user0.ID), + } + + err := notifications1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachUserUserNotifications0: %w", err) + } + + return notifications1, nil +} + +func (user0 *User) InsertUserNotifications(ctx context.Context, exec bob.Executor, related ...*NotificationSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + notifications1, err := insertUserUserNotifications0(ctx, exec, related, user0) + if err != nil { + return err + } + + user0.R.UserNotifications = append(user0.R.UserNotifications, notifications1...) + + for _, rel := range notifications1 { + rel.R.UserUser = user0 + } + return nil +} + +func (user0 *User) AttachUserNotifications(ctx context.Context, exec bob.Executor, related ...*Notification) error { + if len(related) == 0 { + return nil + } + + var err error + notifications1 := NotificationSlice(related) + + _, err = attachUserUserNotifications0(ctx, exec, len(related), notifications1, user0) + if err != nil { + return err + } + + user0.R.UserNotifications = append(user0.R.UserNotifications, notifications1...) + + for _, rel := range related { + rel.R.UserUser = user0 + } + + return nil +} + func insertUserUserOauthTokens0(ctx context.Context, exec bob.Executor, oauthTokens1 []*OauthTokenSetter, user0 *User) (OauthTokenSlice, error) { for i := range oauthTokens1 { oauthTokens1[i].UserID = omit.From(user0.ID) @@ -809,6 +902,20 @@ func (o *User) Preload(name string, retrieved any) error { } switch name { + case "UserNotifications": + rels, ok := retrieved.(NotificationSlice) + if !ok { + return fmt.Errorf("user cannot load %T as %q", retrieved, name) + } + + o.R.UserNotifications = rels + + for _, rel := range rels { + if rel != nil { + rel.R.UserUser = o + } + } + return nil case "UserOauthTokens": rels, ok := retrieved.(OauthTokenSlice) if !ok { @@ -863,11 +970,15 @@ func buildUserPreloader() userPreloader { } type userThenLoader[Q orm.Loadable] struct { - UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserNotifications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { + type UserNotificationsLoadInterface interface { + LoadUserNotifications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type UserOauthTokensLoadInterface interface { LoadUserOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -876,6 +987,12 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { } return userThenLoader[Q]{ + UserNotifications: thenLoadBuilder[Q]( + "UserNotifications", + func(ctx context.Context, exec bob.Executor, retrieved UserNotificationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadUserNotifications(ctx, exec, mods...) + }, + ), UserOauthTokens: thenLoadBuilder[Q]( "UserOauthTokens", func(ctx context.Context, exec bob.Executor, retrieved UserOauthTokensLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -891,6 +1008,70 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { } } +// LoadUserNotifications loads the user's UserNotifications into the .R struct +func (o *User) LoadUserNotifications(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.UserNotifications = nil + + related, err := o.UserNotifications(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.UserUser = o + } + + o.R.UserNotifications = related + return nil +} + +// LoadUserNotifications loads the user's UserNotifications into the .R struct +func (os UserSlice) LoadUserNotifications(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + notifications, err := os.UserNotifications(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.UserNotifications = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range notifications { + + if !rel.UserID.IsValue() { + continue + } + if !(rel.UserID.IsValue() && o.ID == rel.UserID.MustGet()) { + continue + } + + rel.R.UserUser = o + + o.R.UserNotifications = append(o.R.UserNotifications, rel) + } + } + + return nil +} + // LoadUserOauthTokens loads the user's UserOauthTokens into the .R struct func (o *User) LoadUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -1008,9 +1189,10 @@ func (os UserSlice) LoadOrganization(ctx context.Context, exec bob.Executor, mod } type userJoins[Q dialect.Joinable] struct { - typ string - UserOauthTokens modAs[Q, oauthTokenColumns] - Organization modAs[Q, organizationColumns] + typ string + UserNotifications modAs[Q, notificationColumns] + UserOauthTokens modAs[Q, oauthTokenColumns] + Organization modAs[Q, organizationColumns] } func (j userJoins[Q]) aliasedAs(alias string) userJoins[Q] { @@ -1020,6 +1202,20 @@ func (j userJoins[Q]) aliasedAs(alias string) userJoins[Q] { func buildUserJoins[Q dialect.Joinable](cols userColumns, typ string) userJoins[Q] { return userJoins[Q]{ typ: typ, + UserNotifications: modAs[Q, notificationColumns]{ + c: Notifications.Columns, + f: func(to notificationColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Notifications.Name().As(to.Alias())).On( + to.UserID.EQ(cols.ID), + )) + } + + return mods + }, + }, UserOauthTokens: modAs[Q, oauthTokenColumns]{ c: OauthTokens.Columns, f: func(to oauthTokenColumns) bob.Mod[Q] { diff --git a/sql/oauth_by_user_id.bob.go b/sql/oauth_by_user_id.bob.go index 69e7b765..6fe52be6 100644 --- a/sql/oauth_by_user_id.bob.go +++ b/sql/oauth_by_user_id.bob.go @@ -21,7 +21,7 @@ import ( //go:embed oauth_by_user_id.bob.sql var formattedQueries_oauth_by_user_id string -var oauthTokenByUserIdSQL = formattedQueries_oauth_by_user_id[156:642] +var oauthTokenByUserIdSQL = formattedQueries_oauth_by_user_id[156:694] type OauthTokenByUserIdQuery = orm.ModQuery[*dialect.SelectQuery, oauthTokenByUserId, OauthTokenByUserIdRow, []OauthTokenByUserIdRow, oauthTokenByUserIdTransformer] @@ -51,6 +51,7 @@ func OauthTokenByUserId(UserID int32) *OauthTokenByUserIdQuery { row.ScheduleScanByIndex(6, &t.ArcgisID) row.ScheduleScanByIndex(7, &t.ArcgisLicenseTypeID) row.ScheduleScanByIndex(8, &t.RefreshTokenExpires) + row.ScheduleScanByIndex(9, &t.InvalidatedAt) return &t, nil }, func(v any) (OauthTokenByUserIdRow, error) { return *(v.(*OauthTokenByUserIdRow)), nil @@ -58,23 +59,24 @@ func OauthTokenByUserId(UserID int32) *OauthTokenByUserIdQuery { }, }, Mod: bob.ModFunc[*dialect.SelectQuery](func(q *dialect.SelectQuery) { - q.AppendSelect(expressionTypArgs.subExpr(7, 449)) - q.SetTable(expressionTypArgs.subExpr(455, 466)) - q.AppendWhere(expressionTypArgs.subExpr(474, 486)) + q.AppendSelect(expressionTypArgs.subExpr(7, 501)) + q.SetTable(expressionTypArgs.subExpr(507, 518)) + q.AppendWhere(expressionTypArgs.subExpr(526, 538)) }), } } type OauthTokenByUserIdRow = struct { - ID int32 `db:"id"` - AccessToken string `db:"access_token"` - AccessTokenExpires time.Time `db:"access_token_expires"` - RefreshToken string `db:"refresh_token"` - Username string `db:"username"` - UserID int32 `db:"user_id"` - ArcgisID null.Val[string] `db:"arcgis_id"` - ArcgisLicenseTypeID null.Val[string] `db:"arcgis_license_type_id"` - RefreshTokenExpires time.Time `db:"refresh_token_expires"` + ID int32 `db:"id"` + AccessToken string `db:"access_token"` + AccessTokenExpires time.Time `db:"access_token_expires"` + RefreshToken string `db:"refresh_token"` + Username string `db:"username"` + UserID int32 `db:"user_id"` + ArcgisID null.Val[string] `db:"arcgis_id"` + ArcgisLicenseTypeID null.Val[string] `db:"arcgis_license_type_id"` + RefreshTokenExpires time.Time `db:"refresh_token_expires"` + InvalidatedAt null.Val[time.Time] `db:"invalidated_at"` } type oauthTokenByUserIdTransformer = bob.SliceTransformer[OauthTokenByUserIdRow, []OauthTokenByUserIdRow] @@ -87,8 +89,8 @@ func (o oauthTokenByUserId) args() iter.Seq[orm.ArgWithPosition] { return func(yield func(arg orm.ArgWithPosition) bool) { if !yield(orm.ArgWithPosition{ Name: "userID", - Start: 484, - Stop: 486, + Start: 536, + Stop: 538, Expression: o.UserID, }) { return diff --git a/sql/oauth_by_user_id.bob.sql b/sql/oauth_by_user_id.bob.sql index a2e32b78..093d7c45 100644 --- a/sql/oauth_by_user_id.bob.sql +++ b/sql/oauth_by_user_id.bob.sql @@ -2,5 +2,5 @@ -- This file is meant to be re-generated in place and/or deleted at any time. -- OauthTokenByUserId -SELECT "oauth_token"."id" AS "id", "oauth_token"."access_token" AS "access_token", "oauth_token"."access_token_expires" AS "access_token_expires", "oauth_token"."refresh_token" AS "refresh_token", "oauth_token"."username" AS "username", "oauth_token"."user_id" AS "user_id", "oauth_token"."arcgis_id" AS "arcgis_id", "oauth_token"."arcgis_license_type_id" AS "arcgis_license_type_id", "oauth_token"."refresh_token_expires" AS "refresh_token_expires" FROM oauth_token WHERE +SELECT "oauth_token"."id" AS "id", "oauth_token"."access_token" AS "access_token", "oauth_token"."access_token_expires" AS "access_token_expires", "oauth_token"."refresh_token" AS "refresh_token", "oauth_token"."username" AS "username", "oauth_token"."user_id" AS "user_id", "oauth_token"."arcgis_id" AS "arcgis_id", "oauth_token"."arcgis_license_type_id" AS "arcgis_license_type_id", "oauth_token"."refresh_token_expires" AS "refresh_token_expires", "oauth_token"."invalidated_at" AS "invalidated_at" FROM oauth_token WHERE user_id = $1; diff --git a/sql/oauth_by_user_id.bob_test.go b/sql/oauth_by_user_id.bob_test.go index 09a040c0..314df39a 100644 --- a/sql/oauth_by_user_id.bob_test.go +++ b/sql/oauth_by_user_id.bob_test.go @@ -84,8 +84,8 @@ func TestOauthTokenByUserId(t *testing.T) { t.Fatal(err) } - if len(columns) != 9 { - t.Fatalf("expected %d columns, got %d", 9, len(columns)) + if len(columns) != 10 { + t.Fatalf("expected %d columns, got %d", 10, len(columns)) } if columns[0] != "id" { @@ -123,5 +123,9 @@ func TestOauthTokenByUserId(t *testing.T) { if columns[8] != "refresh_token_expires" { t.Fatalf("expected column %d to be %s, got %s", 8, "refresh_token_expires", columns[8]) } + + if columns[9] != "invalidated_at" { + t.Fatalf("expected column %d to be %s, got %s", 9, "invalidated_at", columns[9]) + } }) }