Rework publicreport addressing

This adds the ability to link a proper address in the database to the
report and harmonizes the field names with the address table. It also
migrates away from mapbox entirely.

And I fixed the "pool" naming for the publicreports, which are supposed
to be the more generic 'water'.
This commit is contained in:
Eli Ribble 2026-03-09 18:02:22 +00:00
parent 884634a2d7
commit e932c2c473
No known key found for this signature in database
60 changed files with 4511 additions and 5072 deletions

View file

@ -26,7 +26,6 @@ var (
ForwardEmailNidusAddress string
ForwardEmailNidusPassword string
ForwardEmailNidusUsername string
MapboxToken string
PGDSN string
PhoneNumberReport phonenumbers.PhoneNumber
PhoneNumberReportStr string
@ -136,10 +135,6 @@ func Parse() (err error) {
if ForwardEmailNidusPassword == "" {
return fmt.Errorf("You must specify a non-empty FORWARDEMAIL_NIDUS_PASSWORD")
}
MapboxToken = os.Getenv("MAPBOX_TOKEN")
if MapboxToken == "" {
return fmt.Errorf("You must specify a non-empty MAPBOX_TOKEN")
}
PGDSN = os.Getenv("POSTGRES_DSN")
if PGDSN == "" {
return fmt.Errorf("You must specify a non-empty POSTGRES_DSN")

View file

@ -3,15 +3,15 @@
package dberrors
var PublicreportNotifyEmailPoolErrors = &publicreportNotifyEmailPoolErrors{
var PublicreportNotifyEmailWaterErrors = &publicreportNotifyEmailWaterErrors{
ErrUniqueNotifyEmailPoolPkey: &UniqueConstraintError{
schema: "publicreport",
table: "notify_email_pool",
columns: []string{"pool_id", "email_address"},
table: "notify_email_water",
columns: []string{"water_id", "email_address"},
s: "notify_email_pool_pkey",
},
}
type publicreportNotifyEmailPoolErrors struct {
type publicreportNotifyEmailWaterErrors struct {
ErrUniqueNotifyEmailPoolPkey *UniqueConstraintError
}

View file

@ -3,15 +3,15 @@
package dberrors
var PublicreportNotifyPhonePoolErrors = &publicreportNotifyPhonePoolErrors{
var PublicreportNotifyPhoneWaterErrors = &publicreportNotifyPhoneWaterErrors{
ErrUniqueNotifyPhonePoolPkey: &UniqueConstraintError{
schema: "publicreport",
table: "notify_phone_pool",
columns: []string{"pool_id", "phone_e164"},
table: "notify_phone_water",
columns: []string{"water_id", "phone_e164"},
s: "notify_phone_pool_pkey",
},
}
type publicreportNotifyPhonePoolErrors struct {
type publicreportNotifyPhoneWaterErrors struct {
ErrUniqueNotifyPhonePoolPkey *UniqueConstraintError
}

View file

@ -3,23 +3,23 @@
package dberrors
var PublicreportPoolErrors = &publicreportPoolErrors{
var PublicreportWaterErrors = &publicreportWaterErrors{
ErrUniquePoolPkey: &UniqueConstraintError{
schema: "publicreport",
table: "pool",
table: "water",
columns: []string{"id"},
s: "pool_pkey",
},
ErrUniquePoolPublicIdKey: &UniqueConstraintError{
schema: "publicreport",
table: "pool",
table: "water",
columns: []string{"public_id"},
s: "pool_public_id_key",
},
}
type publicreportPoolErrors struct {
type publicreportWaterErrors struct {
ErrUniquePoolPkey *UniqueConstraintError
ErrUniquePoolPublicIdKey *UniqueConstraintError

View file

@ -3,15 +3,15 @@
package dberrors
var PublicreportPoolImageErrors = &publicreportPoolImageErrors{
var PublicreportWaterImageErrors = &publicreportWaterImageErrors{
ErrUniquePoolImagePkey: &UniqueConstraintError{
schema: "publicreport",
table: "pool_image",
columns: []string{"image_id", "pool_id"},
table: "water_image",
columns: []string{"image_id", "water_id"},
s: "pool_image_pkey",
},
}
type publicreportPoolImageErrors struct {
type publicreportWaterImageErrors struct {
ErrUniquePoolImagePkey *UniqueConstraintError
}

View file

@ -5,16 +5,16 @@ package dbinfo
import "github.com/aarondl/opt/null"
var PublicreportNotifyEmailPools = Table[
publicreportNotifyEmailPoolColumns,
publicreportNotifyEmailPoolIndexes,
publicreportNotifyEmailPoolForeignKeys,
publicreportNotifyEmailPoolUniques,
publicreportNotifyEmailPoolChecks,
var PublicreportNotifyEmailWaters = Table[
publicreportNotifyEmailWaterColumns,
publicreportNotifyEmailWaterIndexes,
publicreportNotifyEmailWaterForeignKeys,
publicreportNotifyEmailWaterUniques,
publicreportNotifyEmailWaterChecks,
]{
Schema: "publicreport",
Name: "notify_email_pool",
Columns: publicreportNotifyEmailPoolColumns{
Name: "notify_email_water",
Columns: publicreportNotifyEmailWaterColumns{
Created: column{
Name: "created",
DBType: "timestamp without time zone",
@ -33,8 +33,8 @@ var PublicreportNotifyEmailPools = Table[
Generated: false,
AutoIncr: false,
},
PoolID: column{
Name: "pool_id",
WaterID: column{
Name: "water_id",
DBType: "integer",
Default: "",
Comment: "",
@ -52,13 +52,13 @@ var PublicreportNotifyEmailPools = Table[
AutoIncr: false,
},
},
Indexes: publicreportNotifyEmailPoolIndexes{
Indexes: publicreportNotifyEmailWaterIndexes{
NotifyEmailPoolPkey: index{
Type: "btree",
Name: "notify_email_pool_pkey",
Columns: []indexColumn{
{
Name: "pool_id",
Name: "water_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
@ -78,26 +78,26 @@ var PublicreportNotifyEmailPools = Table[
},
PrimaryKey: &constraint{
Name: "notify_email_pool_pkey",
Columns: []string{"pool_id", "email_address"},
Columns: []string{"water_id", "email_address"},
Comment: "",
},
ForeignKeys: publicreportNotifyEmailPoolForeignKeys{
PublicreportNotifyEmailPoolNotifyEmailPoolEmailAddressFkey: foreignKey{
ForeignKeys: publicreportNotifyEmailWaterForeignKeys{
PublicreportNotifyEmailWaterNotifyEmailPoolEmailAddressFkey: foreignKey{
constraint: constraint{
Name: "publicreport.notify_email_pool.notify_email_pool_email_address_fkey",
Name: "publicreport.notify_email_water.notify_email_pool_email_address_fkey",
Columns: []string{"email_address"},
Comment: "",
},
ForeignTable: "comms.email_contact",
ForeignColumns: []string{"address"},
},
PublicreportNotifyEmailPoolNotifyEmailPoolPoolIDFkey: foreignKey{
PublicreportNotifyEmailWaterNotifyEmailPoolPoolIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.notify_email_pool.notify_email_pool_pool_id_fkey",
Columns: []string{"pool_id"},
Name: "publicreport.notify_email_water.notify_email_pool_pool_id_fkey",
Columns: []string{"water_id"},
Comment: "",
},
ForeignTable: "publicreport.pool",
ForeignTable: "publicreport.water",
ForeignColumns: []string{"id"},
},
},
@ -105,48 +105,48 @@ var PublicreportNotifyEmailPools = Table[
Comment: "",
}
type publicreportNotifyEmailPoolColumns struct {
type publicreportNotifyEmailWaterColumns struct {
Created column
Deleted column
PoolID column
WaterID column
EmailAddress column
}
func (c publicreportNotifyEmailPoolColumns) AsSlice() []column {
func (c publicreportNotifyEmailWaterColumns) AsSlice() []column {
return []column{
c.Created, c.Deleted, c.PoolID, c.EmailAddress,
c.Created, c.Deleted, c.WaterID, c.EmailAddress,
}
}
type publicreportNotifyEmailPoolIndexes struct {
type publicreportNotifyEmailWaterIndexes struct {
NotifyEmailPoolPkey index
}
func (i publicreportNotifyEmailPoolIndexes) AsSlice() []index {
func (i publicreportNotifyEmailWaterIndexes) AsSlice() []index {
return []index{
i.NotifyEmailPoolPkey,
}
}
type publicreportNotifyEmailPoolForeignKeys struct {
PublicreportNotifyEmailPoolNotifyEmailPoolEmailAddressFkey foreignKey
PublicreportNotifyEmailPoolNotifyEmailPoolPoolIDFkey foreignKey
type publicreportNotifyEmailWaterForeignKeys struct {
PublicreportNotifyEmailWaterNotifyEmailPoolEmailAddressFkey foreignKey
PublicreportNotifyEmailWaterNotifyEmailPoolPoolIDFkey foreignKey
}
func (f publicreportNotifyEmailPoolForeignKeys) AsSlice() []foreignKey {
func (f publicreportNotifyEmailWaterForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportNotifyEmailPoolNotifyEmailPoolEmailAddressFkey, f.PublicreportNotifyEmailPoolNotifyEmailPoolPoolIDFkey,
f.PublicreportNotifyEmailWaterNotifyEmailPoolEmailAddressFkey, f.PublicreportNotifyEmailWaterNotifyEmailPoolPoolIDFkey,
}
}
type publicreportNotifyEmailPoolUniques struct{}
type publicreportNotifyEmailWaterUniques struct{}
func (u publicreportNotifyEmailPoolUniques) AsSlice() []constraint {
func (u publicreportNotifyEmailWaterUniques) AsSlice() []constraint {
return []constraint{}
}
type publicreportNotifyEmailPoolChecks struct{}
type publicreportNotifyEmailWaterChecks struct{}
func (c publicreportNotifyEmailPoolChecks) AsSlice() []check {
func (c publicreportNotifyEmailWaterChecks) AsSlice() []check {
return []check{}
}

View file

@ -5,16 +5,16 @@ package dbinfo
import "github.com/aarondl/opt/null"
var PublicreportNotifyPhonePools = Table[
publicreportNotifyPhonePoolColumns,
publicreportNotifyPhonePoolIndexes,
publicreportNotifyPhonePoolForeignKeys,
publicreportNotifyPhonePoolUniques,
publicreportNotifyPhonePoolChecks,
var PublicreportNotifyPhoneWaters = Table[
publicreportNotifyPhoneWaterColumns,
publicreportNotifyPhoneWaterIndexes,
publicreportNotifyPhoneWaterForeignKeys,
publicreportNotifyPhoneWaterUniques,
publicreportNotifyPhoneWaterChecks,
]{
Schema: "publicreport",
Name: "notify_phone_pool",
Columns: publicreportNotifyPhonePoolColumns{
Name: "notify_phone_water",
Columns: publicreportNotifyPhoneWaterColumns{
Created: column{
Name: "created",
DBType: "timestamp without time zone",
@ -42,8 +42,8 @@ var PublicreportNotifyPhonePools = Table[
Generated: false,
AutoIncr: false,
},
PoolID: column{
Name: "pool_id",
WaterID: column{
Name: "water_id",
DBType: "integer",
Default: "",
Comment: "",
@ -52,13 +52,13 @@ var PublicreportNotifyPhonePools = Table[
AutoIncr: false,
},
},
Indexes: publicreportNotifyPhonePoolIndexes{
Indexes: publicreportNotifyPhoneWaterIndexes{
NotifyPhonePoolPkey: index{
Type: "btree",
Name: "notify_phone_pool_pkey",
Columns: []indexColumn{
{
Name: "pool_id",
Name: "water_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
@ -78,26 +78,26 @@ var PublicreportNotifyPhonePools = Table[
},
PrimaryKey: &constraint{
Name: "notify_phone_pool_pkey",
Columns: []string{"pool_id", "phone_e164"},
Columns: []string{"water_id", "phone_e164"},
Comment: "",
},
ForeignKeys: publicreportNotifyPhonePoolForeignKeys{
PublicreportNotifyPhonePoolNotifyPhonePoolPhoneE164Fkey: foreignKey{
ForeignKeys: publicreportNotifyPhoneWaterForeignKeys{
PublicreportNotifyPhoneWaterNotifyPhonePoolPhoneE164Fkey: foreignKey{
constraint: constraint{
Name: "publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey",
Name: "publicreport.notify_phone_water.notify_phone_pool_phone_e164_fkey",
Columns: []string{"phone_e164"},
Comment: "",
},
ForeignTable: "comms.phone",
ForeignColumns: []string{"e164"},
},
PublicreportNotifyPhonePoolNotifyPhonePoolPoolIDFkey: foreignKey{
PublicreportNotifyPhoneWaterNotifyPhonePoolPoolIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.notify_phone_pool.notify_phone_pool_pool_id_fkey",
Columns: []string{"pool_id"},
Name: "publicreport.notify_phone_water.notify_phone_pool_pool_id_fkey",
Columns: []string{"water_id"},
Comment: "",
},
ForeignTable: "publicreport.pool",
ForeignTable: "publicreport.water",
ForeignColumns: []string{"id"},
},
},
@ -105,48 +105,48 @@ var PublicreportNotifyPhonePools = Table[
Comment: "",
}
type publicreportNotifyPhonePoolColumns struct {
type publicreportNotifyPhoneWaterColumns struct {
Created column
Deleted column
PhoneE164 column
PoolID column
WaterID column
}
func (c publicreportNotifyPhonePoolColumns) AsSlice() []column {
func (c publicreportNotifyPhoneWaterColumns) AsSlice() []column {
return []column{
c.Created, c.Deleted, c.PhoneE164, c.PoolID,
c.Created, c.Deleted, c.PhoneE164, c.WaterID,
}
}
type publicreportNotifyPhonePoolIndexes struct {
type publicreportNotifyPhoneWaterIndexes struct {
NotifyPhonePoolPkey index
}
func (i publicreportNotifyPhonePoolIndexes) AsSlice() []index {
func (i publicreportNotifyPhoneWaterIndexes) AsSlice() []index {
return []index{
i.NotifyPhonePoolPkey,
}
}
type publicreportNotifyPhonePoolForeignKeys struct {
PublicreportNotifyPhonePoolNotifyPhonePoolPhoneE164Fkey foreignKey
PublicreportNotifyPhonePoolNotifyPhonePoolPoolIDFkey foreignKey
type publicreportNotifyPhoneWaterForeignKeys struct {
PublicreportNotifyPhoneWaterNotifyPhonePoolPhoneE164Fkey foreignKey
PublicreportNotifyPhoneWaterNotifyPhonePoolPoolIDFkey foreignKey
}
func (f publicreportNotifyPhonePoolForeignKeys) AsSlice() []foreignKey {
func (f publicreportNotifyPhoneWaterForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportNotifyPhonePoolNotifyPhonePoolPhoneE164Fkey, f.PublicreportNotifyPhonePoolNotifyPhonePoolPoolIDFkey,
f.PublicreportNotifyPhoneWaterNotifyPhonePoolPhoneE164Fkey, f.PublicreportNotifyPhoneWaterNotifyPhonePoolPoolIDFkey,
}
}
type publicreportNotifyPhonePoolUniques struct{}
type publicreportNotifyPhoneWaterUniques struct{}
func (u publicreportNotifyPhonePoolUniques) AsSlice() []constraint {
func (u publicreportNotifyPhoneWaterUniques) AsSlice() []constraint {
return []constraint{}
}
type publicreportNotifyPhonePoolChecks struct{}
type publicreportNotifyPhoneWaterChecks struct{}
func (c publicreportNotifyPhonePoolChecks) AsSlice() []check {
func (c publicreportNotifyPhoneWaterChecks) AsSlice() []check {
return []check{}
}

View file

@ -114,8 +114,8 @@ var PublicreportNuisances = Table[
Generated: false,
AutoIncr: false,
},
Address: column{
Name: "address",
AddressRaw: column{
Name: "address_raw",
DBType: "text",
Default: "",
Comment: "",
@ -168,8 +168,8 @@ var PublicreportNuisances = Table[
Generated: false,
AutoIncr: false,
},
AddressPlace: column{
Name: "address_place",
AddressLocality: column{
Name: "address_locality",
DBType: "text",
Default: "",
Comment: "",
@ -177,8 +177,8 @@ var PublicreportNuisances = Table[
Generated: false,
AutoIncr: false,
},
AddressPostcode: column{
Name: "address_postcode",
AddressPostalCode: column{
Name: "address_postal_code",
DBType: "text",
Default: "",
Comment: "",
@ -339,6 +339,15 @@ var PublicreportNuisances = Table[
Generated: false,
AutoIncr: false,
},
AddressID: column{
Name: "address_id",
DBType: "integer",
Default: "NULL",
Comment: "",
Nullable: true,
Generated: false,
AutoIncr: false,
},
},
Indexes: publicreportNuisanceIndexes{
NuisancePkey: index{
@ -382,6 +391,15 @@ var PublicreportNuisances = Table[
Comment: "",
},
ForeignKeys: publicreportNuisanceForeignKeys{
PublicreportNuisanceNuisanceAddressIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.nuisance.nuisance_address_id_fkey",
Columns: []string{"address_id"},
Comment: "",
},
ForeignTable: "address",
ForeignColumns: []string{"id"},
},
PublicreportNuisanceNuisanceOrganizationIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.nuisance.nuisance_organization_id_fkey",
@ -415,14 +433,14 @@ type publicreportNuisanceColumns struct {
ReporterEmail column
ReporterName column
ReporterPhone column
Address column
AddressRaw column
Status column
OrganizationID column
SourceGutter column
H3cell column
AddressCountry column
AddressPlace column
AddressPostcode column
AddressLocality column
AddressPostalCode column
AddressRegion column
AddressStreet column
IsLocationBackyard column
@ -440,11 +458,12 @@ type publicreportNuisanceColumns struct {
ReporterContactConsent column
Location column
AddressNumber column
AddressID column
}
func (c publicreportNuisanceColumns) AsSlice() []column {
return []column{
c.ID, c.AdditionalInfo, c.Created, c.Duration, c.SourceContainer, c.SourceDescription, c.SourceStagnant, c.PublicID, c.ReporterEmail, c.ReporterName, c.ReporterPhone, c.Address, c.Status, c.OrganizationID, c.SourceGutter, c.H3cell, c.AddressCountry, c.AddressPlace, c.AddressPostcode, c.AddressRegion, c.AddressStreet, c.IsLocationBackyard, c.IsLocationFrontyard, c.IsLocationGarden, c.IsLocationOther, c.IsLocationPool, c.MapZoom, c.TodEarly, c.TodDay, c.TodEvening, c.TodNight, c.LatlngAccuracyType, c.LatlngAccuracyValue, c.ReporterContactConsent, c.Location, c.AddressNumber,
c.ID, c.AdditionalInfo, c.Created, c.Duration, c.SourceContainer, c.SourceDescription, c.SourceStagnant, c.PublicID, c.ReporterEmail, c.ReporterName, c.ReporterPhone, c.AddressRaw, c.Status, c.OrganizationID, c.SourceGutter, c.H3cell, c.AddressCountry, c.AddressLocality, c.AddressPostalCode, c.AddressRegion, c.AddressStreet, c.IsLocationBackyard, c.IsLocationFrontyard, c.IsLocationGarden, c.IsLocationOther, c.IsLocationPool, c.MapZoom, c.TodEarly, c.TodDay, c.TodEvening, c.TodNight, c.LatlngAccuracyType, c.LatlngAccuracyValue, c.ReporterContactConsent, c.Location, c.AddressNumber, c.AddressID,
}
}
@ -460,12 +479,13 @@ func (i publicreportNuisanceIndexes) AsSlice() []index {
}
type publicreportNuisanceForeignKeys struct {
PublicreportNuisanceNuisanceAddressIDFkey foreignKey
PublicreportNuisanceNuisanceOrganizationIDFkey foreignKey
}
func (f publicreportNuisanceForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportNuisanceNuisanceOrganizationIDFkey,
f.PublicreportNuisanceNuisanceAddressIDFkey, f.PublicreportNuisanceNuisanceOrganizationIDFkey,
}
}

View file

@ -1,132 +0,0 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package dbinfo
import "github.com/aarondl/opt/null"
var PublicreportPoolImages = Table[
publicreportPoolImageColumns,
publicreportPoolImageIndexes,
publicreportPoolImageForeignKeys,
publicreportPoolImageUniques,
publicreportPoolImageChecks,
]{
Schema: "publicreport",
Name: "pool_image",
Columns: publicreportPoolImageColumns{
ImageID: column{
Name: "image_id",
DBType: "integer",
Default: "",
Comment: "",
Nullable: false,
Generated: false,
AutoIncr: false,
},
PoolID: column{
Name: "pool_id",
DBType: "integer",
Default: "",
Comment: "",
Nullable: false,
Generated: false,
AutoIncr: false,
},
},
Indexes: publicreportPoolImageIndexes{
PoolImagePkey: index{
Type: "btree",
Name: "pool_image_pkey",
Columns: []indexColumn{
{
Name: "image_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
{
Name: "pool_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
},
Unique: true,
Comment: "",
NullsFirst: []bool{false, false},
NullsDistinct: false,
Where: "",
Include: []string{},
},
},
PrimaryKey: &constraint{
Name: "pool_image_pkey",
Columns: []string{"image_id", "pool_id"},
Comment: "",
},
ForeignKeys: publicreportPoolImageForeignKeys{
PublicreportPoolImagePoolImageImageIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.pool_image.pool_image_image_id_fkey",
Columns: []string{"image_id"},
Comment: "",
},
ForeignTable: "publicreport.image",
ForeignColumns: []string{"id"},
},
PublicreportPoolImagePoolImagePoolIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.pool_image.pool_image_pool_id_fkey",
Columns: []string{"pool_id"},
Comment: "",
},
ForeignTable: "publicreport.pool",
ForeignColumns: []string{"id"},
},
},
Comment: "",
}
type publicreportPoolImageColumns struct {
ImageID column
PoolID column
}
func (c publicreportPoolImageColumns) AsSlice() []column {
return []column{
c.ImageID, c.PoolID,
}
}
type publicreportPoolImageIndexes struct {
PoolImagePkey index
}
func (i publicreportPoolImageIndexes) AsSlice() []index {
return []index{
i.PoolImagePkey,
}
}
type publicreportPoolImageForeignKeys struct {
PublicreportPoolImagePoolImageImageIDFkey foreignKey
PublicreportPoolImagePoolImagePoolIDFkey foreignKey
}
func (f publicreportPoolImageForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportPoolImagePoolImageImageIDFkey, f.PublicreportPoolImagePoolImagePoolIDFkey,
}
}
type publicreportPoolImageUniques struct{}
func (u publicreportPoolImageUniques) AsSlice() []constraint {
return []constraint{}
}
type publicreportPoolImageChecks struct{}
func (c publicreportPoolImageChecks) AsSlice() []check {
return []check{}
}

View file

@ -5,16 +5,16 @@ package dbinfo
import "github.com/aarondl/opt/null"
var PublicreportPools = Table[
publicreportPoolColumns,
publicreportPoolIndexes,
publicreportPoolForeignKeys,
publicreportPoolUniques,
publicreportPoolChecks,
var PublicreportWaters = Table[
publicreportWaterColumns,
publicreportWaterIndexes,
publicreportWaterForeignKeys,
publicreportWaterUniques,
publicreportWaterChecks,
]{
Schema: "publicreport",
Name: "pool",
Columns: publicreportPoolColumns{
Name: "water",
Columns: publicreportWaterColumns{
ID: column{
Name: "id",
DBType: "integer",
@ -78,8 +78,8 @@ var PublicreportPools = Table[
Generated: false,
AutoIncr: false,
},
Address: column{
Name: "address",
AddressRaw: column{
Name: "address_raw",
DBType: "text",
Default: "",
Comment: "",
@ -96,8 +96,8 @@ var PublicreportPools = Table[
Generated: false,
AutoIncr: false,
},
AddressPostCode: column{
Name: "address_post_code",
AddressPostalCode: column{
Name: "address_postal_code",
DBType: "text",
Default: "",
Comment: "",
@ -105,8 +105,8 @@ var PublicreportPools = Table[
Generated: false,
AutoIncr: false,
},
AddressPlace: column{
Name: "address_place",
AddressLocality: column{
Name: "address_locality",
DBType: "text",
Default: "",
Comment: "",
@ -330,8 +330,17 @@ var PublicreportPools = Table[
Generated: false,
AutoIncr: false,
},
AddressID: column{
Name: "address_id",
DBType: "integer",
Default: "NULL",
Comment: "",
Nullable: true,
Generated: false,
AutoIncr: false,
},
Indexes: publicreportPoolIndexes{
},
Indexes: publicreportWaterIndexes{
PoolPkey: index{
Type: "btree",
Name: "pool_pkey",
@ -372,10 +381,19 @@ var PublicreportPools = Table[
Columns: []string{"id"},
Comment: "",
},
ForeignKeys: publicreportPoolForeignKeys{
PublicreportPoolPoolOrganizationIDFkey: foreignKey{
ForeignKeys: publicreportWaterForeignKeys{
PublicreportWaterPoolAddressIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.pool.pool_organization_id_fkey",
Name: "publicreport.water.pool_address_id_fkey",
Columns: []string{"address_id"},
Comment: "",
},
ForeignTable: "address",
ForeignColumns: []string{"id"},
},
PublicreportWaterPoolOrganizationIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.water.pool_organization_id_fkey",
Columns: []string{"organization_id"},
Comment: "",
},
@ -383,7 +401,7 @@ var PublicreportPools = Table[
ForeignColumns: []string{"id"},
},
},
Uniques: publicreportPoolUniques{
Uniques: publicreportWaterUniques{
PoolPublicIDKey: constraint{
Name: "pool_public_id_key",
Columns: []string{"public_id"},
@ -394,7 +412,7 @@ var PublicreportPools = Table[
Comment: "",
}
type publicreportPoolColumns struct {
type publicreportWaterColumns struct {
ID column
AccessComments column
AccessGate column
@ -402,10 +420,10 @@ type publicreportPoolColumns struct {
AccessLocked column
AccessDog column
AccessOther column
Address column
AddressRaw column
AddressCountry column
AddressPostCode column
AddressPlace column
AddressPostalCode column
AddressLocality column
AddressStreet column
AddressRegion column
Comments column
@ -430,47 +448,49 @@ type publicreportPoolColumns struct {
ReporterContactConsent column
Location column
AddressNumber column
AddressID column
}
func (c publicreportPoolColumns) AsSlice() []column {
func (c publicreportWaterColumns) AsSlice() []column {
return []column{
c.ID, c.AccessComments, c.AccessGate, c.AccessFence, c.AccessLocked, c.AccessDog, c.AccessOther, c.Address, c.AddressCountry, c.AddressPostCode, c.AddressPlace, c.AddressStreet, c.AddressRegion, c.Comments, c.Created, c.H3cell, c.HasAdult, c.HasLarvae, c.HasPupae, c.MapZoom, c.OwnerEmail, c.OwnerName, c.OwnerPhone, c.PublicID, c.ReporterEmail, c.ReporterName, c.ReporterPhone, c.Status, c.OrganizationID, c.HasBackyardPermission, c.IsReporterConfidential, c.IsReporterOwner, c.ReporterContactConsent, c.Location, c.AddressNumber,
c.ID, c.AccessComments, c.AccessGate, c.AccessFence, c.AccessLocked, c.AccessDog, c.AccessOther, c.AddressRaw, c.AddressCountry, c.AddressPostalCode, c.AddressLocality, c.AddressStreet, c.AddressRegion, c.Comments, c.Created, c.H3cell, c.HasAdult, c.HasLarvae, c.HasPupae, c.MapZoom, c.OwnerEmail, c.OwnerName, c.OwnerPhone, c.PublicID, c.ReporterEmail, c.ReporterName, c.ReporterPhone, c.Status, c.OrganizationID, c.HasBackyardPermission, c.IsReporterConfidential, c.IsReporterOwner, c.ReporterContactConsent, c.Location, c.AddressNumber, c.AddressID,
}
}
type publicreportPoolIndexes struct {
type publicreportWaterIndexes struct {
PoolPkey index
PoolPublicIDKey index
}
func (i publicreportPoolIndexes) AsSlice() []index {
func (i publicreportWaterIndexes) AsSlice() []index {
return []index{
i.PoolPkey, i.PoolPublicIDKey,
}
}
type publicreportPoolForeignKeys struct {
PublicreportPoolPoolOrganizationIDFkey foreignKey
type publicreportWaterForeignKeys struct {
PublicreportWaterPoolAddressIDFkey foreignKey
PublicreportWaterPoolOrganizationIDFkey foreignKey
}
func (f publicreportPoolForeignKeys) AsSlice() []foreignKey {
func (f publicreportWaterForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportPoolPoolOrganizationIDFkey,
f.PublicreportWaterPoolAddressIDFkey, f.PublicreportWaterPoolOrganizationIDFkey,
}
}
type publicreportPoolUniques struct {
type publicreportWaterUniques struct {
PoolPublicIDKey constraint
}
func (u publicreportPoolUniques) AsSlice() []constraint {
func (u publicreportWaterUniques) AsSlice() []constraint {
return []constraint{
u.PoolPublicIDKey,
}
}
type publicreportPoolChecks struct{}
type publicreportWaterChecks struct{}
func (c publicreportPoolChecks) AsSlice() []check {
func (c publicreportWaterChecks) AsSlice() []check {
return []check{}
}

View file

@ -0,0 +1,132 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package dbinfo
import "github.com/aarondl/opt/null"
var PublicreportWaterImages = Table[
publicreportWaterImageColumns,
publicreportWaterImageIndexes,
publicreportWaterImageForeignKeys,
publicreportWaterImageUniques,
publicreportWaterImageChecks,
]{
Schema: "publicreport",
Name: "water_image",
Columns: publicreportWaterImageColumns{
ImageID: column{
Name: "image_id",
DBType: "integer",
Default: "",
Comment: "",
Nullable: false,
Generated: false,
AutoIncr: false,
},
WaterID: column{
Name: "water_id",
DBType: "integer",
Default: "",
Comment: "",
Nullable: false,
Generated: false,
AutoIncr: false,
},
},
Indexes: publicreportWaterImageIndexes{
PoolImagePkey: index{
Type: "btree",
Name: "pool_image_pkey",
Columns: []indexColumn{
{
Name: "image_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
{
Name: "water_id",
Desc: null.FromCond(false, true),
IsExpression: false,
},
},
Unique: true,
Comment: "",
NullsFirst: []bool{false, false},
NullsDistinct: false,
Where: "",
Include: []string{},
},
},
PrimaryKey: &constraint{
Name: "pool_image_pkey",
Columns: []string{"image_id", "water_id"},
Comment: "",
},
ForeignKeys: publicreportWaterImageForeignKeys{
PublicreportWaterImagePoolImageImageIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.water_image.pool_image_image_id_fkey",
Columns: []string{"image_id"},
Comment: "",
},
ForeignTable: "publicreport.image",
ForeignColumns: []string{"id"},
},
PublicreportWaterImagePoolImagePoolIDFkey: foreignKey{
constraint: constraint{
Name: "publicreport.water_image.pool_image_pool_id_fkey",
Columns: []string{"water_id"},
Comment: "",
},
ForeignTable: "publicreport.water",
ForeignColumns: []string{"id"},
},
},
Comment: "",
}
type publicreportWaterImageColumns struct {
ImageID column
WaterID column
}
func (c publicreportWaterImageColumns) AsSlice() []column {
return []column{
c.ImageID, c.WaterID,
}
}
type publicreportWaterImageIndexes struct {
PoolImagePkey index
}
func (i publicreportWaterImageIndexes) AsSlice() []index {
return []index{
i.PoolImagePkey,
}
}
type publicreportWaterImageForeignKeys struct {
PublicreportWaterImagePoolImageImageIDFkey foreignKey
PublicreportWaterImagePoolImagePoolIDFkey foreignKey
}
func (f publicreportWaterImageForeignKeys) AsSlice() []foreignKey {
return []foreignKey{
f.PublicreportWaterImagePoolImageImageIDFkey, f.PublicreportWaterImagePoolImagePoolIDFkey,
}
}
type publicreportWaterImageUniques struct{}
func (u publicreportWaterImageUniques) AsSlice() []constraint {
return []constraint{}
}
type publicreportWaterImageChecks struct{}
func (c publicreportWaterImageChecks) AsSlice() []check {
return []check{}
}

View file

@ -0,0 +1,46 @@
-- +goose Up
ALTER TABLE publicreport.nuisance RENAME COLUMN address TO address_raw;
ALTER TABLE publicreport.nuisance RENAME COLUMN address_place TO address_locality;
ALTER TABLE publicreport.nuisance RENAME COLUMN address_postcode TO address_postal_code;
ALTER TABLE publicreport.nuisance ADD COLUMN address_id INTEGER REFERENCES address(id);
ALTER TABLE publicreport.pool RENAME COLUMN address TO address_raw;
ALTER TABLE publicreport.pool RENAME COLUMN address_place TO address_locality;
ALTER TABLE publicreport.pool RENAME COLUMN address_post_code TO address_postal_code;
ALTER TABLE publicreport.pool ADD COLUMN address_id INTEGER REFERENCES address(id);
ALTER TABLE publicreport.pool RENAME TO water;
ALTER TABLE publicreport.pool_image RENAME COLUMN pool_id TO water_id;
ALTER TABLE publicreport.pool_image RENAME TO water_image;
ALTER TABLE publicreport.notify_email_pool RENAME COLUMN pool_id TO water_id;
ALTER TABLE publicreport.notify_email_pool RENAME TO notify_email_water;
ALTER TABLE publicreport.notify_phone_pool RENAME COLUMN pool_id TO water_id;
ALTER TABLE publicreport.notify_phone_pool RENAME TO notify_phone_water;
-- +goose Down
ALTER TABLE publicreport.notify_phone_water RENAME TO notify_phone_pool;
ALTER TABLE publicreport.notify_phone_pool RENAME COLUMN water_id TO pool_id;
ALTER TABLE publicreport.notify_email_water RENAME TO notify_email_pool;
ALTER TABLE publicreport.notify_email_pool RENAME COLUMN water_id TO pool_id;
ALTER TABLE publicreport.water_image RENAME COLUMN water_id TO pool_id;
ALTER TABLE publicreport.water_image RENAME TO pool_image;
ALTER TABLE publicreport.water RENAME TO pool;
ALTER TABLE publicreport.pool DROP COLUMN address_id;
ALTER TABLE publicreport.pool RENAME COLUMN address_postal_code TO address_post_code;
ALTER TABLE publicreport.pool RENAME COLUMN address_locality TO address_place;
ALTER TABLE publicreport.pool RENAME COLUMN address_raw TO address;
ALTER TABLE publicreport.nuisance DROP COLUMN address_id;
ALTER TABLE publicreport.nuisance RENAME COLUMN address_postal_code TO address_postcode;
ALTER TABLE publicreport.nuisance RENAME COLUMN address_locality TO address_place;
ALTER TABLE publicreport.nuisance RENAME COLUMN address_raw TO address;

View file

@ -20,6 +20,7 @@ import (
"github.com/Gleipnir-Technology/bob/types/pgtypes"
enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
)
// Address is an object representing the database table.
@ -52,6 +53,8 @@ type AddressesQuery = *psql.ViewQuery[*Address, AddressSlice]
// addressR is where relationships are stored.
type addressR struct {
Mailers CommsMailerSlice // comms.mailer.mailer_address_id_fkey
Nuisances PublicreportNuisanceSlice // publicreport.nuisance.nuisance_address_id_fkey
Waters PublicreportWaterSlice // publicreport.water.pool_address_id_fkey
Residents ResidentSlice // resident.resident_address_id_fkey
Site *Site // site.site_address_id_fkey
}
@ -602,6 +605,54 @@ func (os AddressSlice) Mailers(mods ...bob.Mod[*dialect.SelectQuery]) CommsMaile
)...)
}
// Nuisances starts a query for related objects on publicreport.nuisance
func (o *Address) Nuisances(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisancesQuery {
return PublicreportNuisances.Query(append(mods,
sm.Where(PublicreportNuisances.Columns.AddressID.EQ(psql.Arg(o.ID))),
)...)
}
func (os AddressSlice) Nuisances(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisancesQuery {
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 PublicreportNuisances.Query(append(mods,
sm.Where(psql.Group(PublicreportNuisances.Columns.AddressID).OP("IN", PKArgExpr)),
)...)
}
// Waters starts a query for related objects on publicreport.water
func (o *Address) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.Where(PublicreportWaters.Columns.AddressID.EQ(psql.Arg(o.ID))),
)...)
}
func (os AddressSlice) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
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 PublicreportWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportWaters.Columns.AddressID).OP("IN", PKArgExpr)),
)...)
}
// Residents starts a query for related objects on resident
func (o *Address) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery {
return Residents.Query(append(mods,
@ -718,6 +769,142 @@ func (address0 *Address) AttachMailers(ctx context.Context, exec bob.Executor, r
return nil
}
func insertAddressNuisances0(ctx context.Context, exec bob.Executor, publicreportNuisances1 []*PublicreportNuisanceSetter, address0 *Address) (PublicreportNuisanceSlice, error) {
for i := range publicreportNuisances1 {
publicreportNuisances1[i].AddressID = omitnull.From(address0.ID)
}
ret, err := PublicreportNuisances.Insert(bob.ToMods(publicreportNuisances1...)).All(ctx, exec)
if err != nil {
return ret, fmt.Errorf("insertAddressNuisances0: %w", err)
}
return ret, nil
}
func attachAddressNuisances0(ctx context.Context, exec bob.Executor, count int, publicreportNuisances1 PublicreportNuisanceSlice, address0 *Address) (PublicreportNuisanceSlice, error) {
setter := &PublicreportNuisanceSetter{
AddressID: omitnull.From(address0.ID),
}
err := publicreportNuisances1.UpdateAll(ctx, exec, *setter)
if err != nil {
return nil, fmt.Errorf("attachAddressNuisances0: %w", err)
}
return publicreportNuisances1, nil
}
func (address0 *Address) InsertNuisances(ctx context.Context, exec bob.Executor, related ...*PublicreportNuisanceSetter) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNuisances1, err := insertAddressNuisances0(ctx, exec, related, address0)
if err != nil {
return err
}
address0.R.Nuisances = append(address0.R.Nuisances, publicreportNuisances1...)
for _, rel := range publicreportNuisances1 {
rel.R.Address = address0
}
return nil
}
func (address0 *Address) AttachNuisances(ctx context.Context, exec bob.Executor, related ...*PublicreportNuisance) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNuisances1 := PublicreportNuisanceSlice(related)
_, err = attachAddressNuisances0(ctx, exec, len(related), publicreportNuisances1, address0)
if err != nil {
return err
}
address0.R.Nuisances = append(address0.R.Nuisances, publicreportNuisances1...)
for _, rel := range related {
rel.R.Address = address0
}
return nil
}
func insertAddressWaters0(ctx context.Context, exec bob.Executor, publicreportWaters1 []*PublicreportWaterSetter, address0 *Address) (PublicreportWaterSlice, error) {
for i := range publicreportWaters1 {
publicreportWaters1[i].AddressID = omitnull.From(address0.ID)
}
ret, err := PublicreportWaters.Insert(bob.ToMods(publicreportWaters1...)).All(ctx, exec)
if err != nil {
return ret, fmt.Errorf("insertAddressWaters0: %w", err)
}
return ret, nil
}
func attachAddressWaters0(ctx context.Context, exec bob.Executor, count int, publicreportWaters1 PublicreportWaterSlice, address0 *Address) (PublicreportWaterSlice, error) {
setter := &PublicreportWaterSetter{
AddressID: omitnull.From(address0.ID),
}
err := publicreportWaters1.UpdateAll(ctx, exec, *setter)
if err != nil {
return nil, fmt.Errorf("attachAddressWaters0: %w", err)
}
return publicreportWaters1, nil
}
func (address0 *Address) InsertWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWaterSetter) error {
if len(related) == 0 {
return nil
}
var err error
publicreportWaters1, err := insertAddressWaters0(ctx, exec, related, address0)
if err != nil {
return err
}
address0.R.Waters = append(address0.R.Waters, publicreportWaters1...)
for _, rel := range publicreportWaters1 {
rel.R.Address = address0
}
return nil
}
func (address0 *Address) AttachWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWater) error {
if len(related) == 0 {
return nil
}
var err error
publicreportWaters1 := PublicreportWaterSlice(related)
_, err = attachAddressWaters0(ctx, exec, len(related), publicreportWaters1, address0)
if err != nil {
return err
}
address0.R.Waters = append(address0.R.Waters, publicreportWaters1...)
for _, rel := range related {
rel.R.Address = address0
}
return nil
}
func insertAddressResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, address0 *Address) (ResidentSlice, error) {
for i := range residents1 {
residents1[i].AddressID = omit.From(address0.ID)
@ -888,6 +1075,34 @@ func (o *Address) Preload(name string, retrieved any) error {
o.R.Mailers = rels
for _, rel := range rels {
if rel != nil {
rel.R.Address = o
}
}
return nil
case "Nuisances":
rels, ok := retrieved.(PublicreportNuisanceSlice)
if !ok {
return fmt.Errorf("address cannot load %T as %q", retrieved, name)
}
o.R.Nuisances = rels
for _, rel := range rels {
if rel != nil {
rel.R.Address = o
}
}
return nil
case "Waters":
rels, ok := retrieved.(PublicreportWaterSlice)
if !ok {
return fmt.Errorf("address cannot load %T as %q", retrieved, name)
}
o.R.Waters = rels
for _, rel := range rels {
if rel != nil {
rel.R.Address = o
@ -949,6 +1164,8 @@ func buildAddressPreloader() addressPreloader {
type addressThenLoader[Q orm.Loadable] struct {
Mailers func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Nuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Waters func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Residents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Site func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
@ -957,6 +1174,12 @@ func buildAddressThenLoader[Q orm.Loadable]() addressThenLoader[Q] {
type MailersLoadInterface interface {
LoadMailers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type NuisancesLoadInterface interface {
LoadNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type WatersLoadInterface interface {
LoadWaters(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type ResidentsLoadInterface interface {
LoadResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
@ -971,6 +1194,18 @@ func buildAddressThenLoader[Q orm.Loadable]() addressThenLoader[Q] {
return retrieved.LoadMailers(ctx, exec, mods...)
},
),
Nuisances: thenLoadBuilder[Q](
"Nuisances",
func(ctx context.Context, exec bob.Executor, retrieved NuisancesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadNuisances(ctx, exec, mods...)
},
),
Waters: thenLoadBuilder[Q](
"Waters",
func(ctx context.Context, exec bob.Executor, retrieved WatersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWaters(ctx, exec, mods...)
},
),
Residents: thenLoadBuilder[Q](
"Residents",
func(ctx context.Context, exec bob.Executor, retrieved ResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
@ -1047,6 +1282,134 @@ func (os AddressSlice) LoadMailers(ctx context.Context, exec bob.Executor, mods
return nil
}
// LoadNuisances loads the address's Nuisances into the .R struct
func (o *Address) LoadNuisances(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Nuisances = nil
related, err := o.Nuisances(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, rel := range related {
rel.R.Address = o
}
o.R.Nuisances = related
return nil
}
// LoadNuisances loads the address's Nuisances into the .R struct
func (os AddressSlice) LoadNuisances(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportNuisances, err := os.Nuisances(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
o.R.Nuisances = nil
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportNuisances {
if !rel.AddressID.IsValue() {
continue
}
if !(rel.AddressID.IsValue() && o.ID == rel.AddressID.MustGet()) {
continue
}
rel.R.Address = o
o.R.Nuisances = append(o.R.Nuisances, rel)
}
}
return nil
}
// LoadWaters loads the address's Waters into the .R struct
func (o *Address) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Waters = nil
related, err := o.Waters(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, rel := range related {
rel.R.Address = o
}
o.R.Waters = related
return nil
}
// LoadWaters loads the address's Waters into the .R struct
func (os AddressSlice) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportWaters, err := os.Waters(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
o.R.Waters = nil
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportWaters {
if !rel.AddressID.IsValue() {
continue
}
if !(rel.AddressID.IsValue() && o.ID == rel.AddressID.MustGet()) {
continue
}
rel.R.Address = o
o.R.Waters = append(o.R.Waters, rel)
}
}
return nil
}
// LoadResidents loads the address's Residents into the .R struct
func (o *Address) LoadResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {

View file

@ -88,15 +88,15 @@ type preloaders struct {
PublicreportImage publicreportImagePreloader
PublicreportImageExif publicreportImageExifPreloader
PublicreportNotifyEmailNuisance publicreportNotifyEmailNuisancePreloader
PublicreportNotifyEmailPool publicreportNotifyEmailPoolPreloader
PublicreportNotifyEmailWater publicreportNotifyEmailWaterPreloader
PublicreportNotifyPhoneNuisance publicreportNotifyPhoneNuisancePreloader
PublicreportNotifyPhonePool publicreportNotifyPhonePoolPreloader
PublicreportNotifyPhoneWater publicreportNotifyPhoneWaterPreloader
PublicreportNuisance publicreportNuisancePreloader
PublicreportNuisanceImage publicreportNuisanceImagePreloader
PublicreportPool publicreportPoolPreloader
PublicreportPoolImage publicreportPoolImagePreloader
PublicreportSubscribeEmail publicreportSubscribeEmailPreloader
PublicreportSubscribePhone publicreportSubscribePhonePreloader
PublicreportWater publicreportWaterPreloader
PublicreportWaterImage publicreportWaterImagePreloader
Resident residentPreloader
ReviewTask reviewTaskPreloader
ReviewTaskPool reviewTaskPoolPreloader
@ -179,15 +179,15 @@ func getPreloaders() preloaders {
PublicreportImage: buildPublicreportImagePreloader(),
PublicreportImageExif: buildPublicreportImageExifPreloader(),
PublicreportNotifyEmailNuisance: buildPublicreportNotifyEmailNuisancePreloader(),
PublicreportNotifyEmailPool: buildPublicreportNotifyEmailPoolPreloader(),
PublicreportNotifyEmailWater: buildPublicreportNotifyEmailWaterPreloader(),
PublicreportNotifyPhoneNuisance: buildPublicreportNotifyPhoneNuisancePreloader(),
PublicreportNotifyPhonePool: buildPublicreportNotifyPhonePoolPreloader(),
PublicreportNotifyPhoneWater: buildPublicreportNotifyPhoneWaterPreloader(),
PublicreportNuisance: buildPublicreportNuisancePreloader(),
PublicreportNuisanceImage: buildPublicreportNuisanceImagePreloader(),
PublicreportPool: buildPublicreportPoolPreloader(),
PublicreportPoolImage: buildPublicreportPoolImagePreloader(),
PublicreportSubscribeEmail: buildPublicreportSubscribeEmailPreloader(),
PublicreportSubscribePhone: buildPublicreportSubscribePhonePreloader(),
PublicreportWater: buildPublicreportWaterPreloader(),
PublicreportWaterImage: buildPublicreportWaterImagePreloader(),
Resident: buildResidentPreloader(),
ReviewTask: buildReviewTaskPreloader(),
ReviewTaskPool: buildReviewTaskPoolPreloader(),
@ -276,15 +276,15 @@ type thenLoaders[Q orm.Loadable] struct {
PublicreportImage publicreportImageThenLoader[Q]
PublicreportImageExif publicreportImageExifThenLoader[Q]
PublicreportNotifyEmailNuisance publicreportNotifyEmailNuisanceThenLoader[Q]
PublicreportNotifyEmailPool publicreportNotifyEmailPoolThenLoader[Q]
PublicreportNotifyEmailWater publicreportNotifyEmailWaterThenLoader[Q]
PublicreportNotifyPhoneNuisance publicreportNotifyPhoneNuisanceThenLoader[Q]
PublicreportNotifyPhonePool publicreportNotifyPhonePoolThenLoader[Q]
PublicreportNotifyPhoneWater publicreportNotifyPhoneWaterThenLoader[Q]
PublicreportNuisance publicreportNuisanceThenLoader[Q]
PublicreportNuisanceImage publicreportNuisanceImageThenLoader[Q]
PublicreportPool publicreportPoolThenLoader[Q]
PublicreportPoolImage publicreportPoolImageThenLoader[Q]
PublicreportSubscribeEmail publicreportSubscribeEmailThenLoader[Q]
PublicreportSubscribePhone publicreportSubscribePhoneThenLoader[Q]
PublicreportWater publicreportWaterThenLoader[Q]
PublicreportWaterImage publicreportWaterImageThenLoader[Q]
Resident residentThenLoader[Q]
ReviewTask reviewTaskThenLoader[Q]
ReviewTaskPool reviewTaskPoolThenLoader[Q]
@ -367,15 +367,15 @@ func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] {
PublicreportImage: buildPublicreportImageThenLoader[Q](),
PublicreportImageExif: buildPublicreportImageExifThenLoader[Q](),
PublicreportNotifyEmailNuisance: buildPublicreportNotifyEmailNuisanceThenLoader[Q](),
PublicreportNotifyEmailPool: buildPublicreportNotifyEmailPoolThenLoader[Q](),
PublicreportNotifyEmailWater: buildPublicreportNotifyEmailWaterThenLoader[Q](),
PublicreportNotifyPhoneNuisance: buildPublicreportNotifyPhoneNuisanceThenLoader[Q](),
PublicreportNotifyPhonePool: buildPublicreportNotifyPhonePoolThenLoader[Q](),
PublicreportNotifyPhoneWater: buildPublicreportNotifyPhoneWaterThenLoader[Q](),
PublicreportNuisance: buildPublicreportNuisanceThenLoader[Q](),
PublicreportNuisanceImage: buildPublicreportNuisanceImageThenLoader[Q](),
PublicreportPool: buildPublicreportPoolThenLoader[Q](),
PublicreportPoolImage: buildPublicreportPoolImageThenLoader[Q](),
PublicreportSubscribeEmail: buildPublicreportSubscribeEmailThenLoader[Q](),
PublicreportSubscribePhone: buildPublicreportSubscribePhoneThenLoader[Q](),
PublicreportWater: buildPublicreportWaterThenLoader[Q](),
PublicreportWaterImage: buildPublicreportWaterImageThenLoader[Q](),
Resident: buildResidentThenLoader[Q](),
ReviewTask: buildReviewTaskThenLoader[Q](),
ReviewTaskPool: buildReviewTaskPoolThenLoader[Q](),

View file

@ -91,16 +91,16 @@ func Where[Q psql.Filterable]() struct {
PublicreportImages publicreportImageWhere[Q]
PublicreportImageExifs publicreportImageExifWhere[Q]
PublicreportNotifyEmailNuisances publicreportNotifyEmailNuisanceWhere[Q]
PublicreportNotifyEmailPools publicreportNotifyEmailPoolWhere[Q]
PublicreportNotifyEmailWaters publicreportNotifyEmailWaterWhere[Q]
PublicreportNotifyPhoneNuisances publicreportNotifyPhoneNuisanceWhere[Q]
PublicreportNotifyPhonePools publicreportNotifyPhonePoolWhere[Q]
PublicreportNotifyPhoneWaters publicreportNotifyPhoneWaterWhere[Q]
PublicreportNuisances publicreportNuisanceWhere[Q]
PublicreportNuisanceImages publicreportNuisanceImageWhere[Q]
PublicreportPools publicreportPoolWhere[Q]
PublicreportPoolImages publicreportPoolImageWhere[Q]
PublicreportReportLocations publicreportReportLocationWhere[Q]
PublicreportSubscribeEmails publicreportSubscribeEmailWhere[Q]
PublicreportSubscribePhones publicreportSubscribePhoneWhere[Q]
PublicreportWaters publicreportWaterWhere[Q]
PublicreportWaterImages publicreportWaterImageWhere[Q]
RasterColumns rasterColumnWhere[Q]
RasterOverviews rasterOverviewWhere[Q]
Residents residentWhere[Q]
@ -188,16 +188,16 @@ func Where[Q psql.Filterable]() struct {
PublicreportImages publicreportImageWhere[Q]
PublicreportImageExifs publicreportImageExifWhere[Q]
PublicreportNotifyEmailNuisances publicreportNotifyEmailNuisanceWhere[Q]
PublicreportNotifyEmailPools publicreportNotifyEmailPoolWhere[Q]
PublicreportNotifyEmailWaters publicreportNotifyEmailWaterWhere[Q]
PublicreportNotifyPhoneNuisances publicreportNotifyPhoneNuisanceWhere[Q]
PublicreportNotifyPhonePools publicreportNotifyPhonePoolWhere[Q]
PublicreportNotifyPhoneWaters publicreportNotifyPhoneWaterWhere[Q]
PublicreportNuisances publicreportNuisanceWhere[Q]
PublicreportNuisanceImages publicreportNuisanceImageWhere[Q]
PublicreportPools publicreportPoolWhere[Q]
PublicreportPoolImages publicreportPoolImageWhere[Q]
PublicreportReportLocations publicreportReportLocationWhere[Q]
PublicreportSubscribeEmails publicreportSubscribeEmailWhere[Q]
PublicreportSubscribePhones publicreportSubscribePhoneWhere[Q]
PublicreportWaters publicreportWaterWhere[Q]
PublicreportWaterImages publicreportWaterImageWhere[Q]
RasterColumns rasterColumnWhere[Q]
RasterOverviews rasterOverviewWhere[Q]
Residents residentWhere[Q]
@ -284,16 +284,16 @@ func Where[Q psql.Filterable]() struct {
PublicreportImages: buildPublicreportImageWhere[Q](PublicreportImages.Columns),
PublicreportImageExifs: buildPublicreportImageExifWhere[Q](PublicreportImageExifs.Columns),
PublicreportNotifyEmailNuisances: buildPublicreportNotifyEmailNuisanceWhere[Q](PublicreportNotifyEmailNuisances.Columns),
PublicreportNotifyEmailPools: buildPublicreportNotifyEmailPoolWhere[Q](PublicreportNotifyEmailPools.Columns),
PublicreportNotifyEmailWaters: buildPublicreportNotifyEmailWaterWhere[Q](PublicreportNotifyEmailWaters.Columns),
PublicreportNotifyPhoneNuisances: buildPublicreportNotifyPhoneNuisanceWhere[Q](PublicreportNotifyPhoneNuisances.Columns),
PublicreportNotifyPhonePools: buildPublicreportNotifyPhonePoolWhere[Q](PublicreportNotifyPhonePools.Columns),
PublicreportNotifyPhoneWaters: buildPublicreportNotifyPhoneWaterWhere[Q](PublicreportNotifyPhoneWaters.Columns),
PublicreportNuisances: buildPublicreportNuisanceWhere[Q](PublicreportNuisances.Columns),
PublicreportNuisanceImages: buildPublicreportNuisanceImageWhere[Q](PublicreportNuisanceImages.Columns),
PublicreportPools: buildPublicreportPoolWhere[Q](PublicreportPools.Columns),
PublicreportPoolImages: buildPublicreportPoolImageWhere[Q](PublicreportPoolImages.Columns),
PublicreportReportLocations: buildPublicreportReportLocationWhere[Q](PublicreportReportLocations.Columns),
PublicreportSubscribeEmails: buildPublicreportSubscribeEmailWhere[Q](PublicreportSubscribeEmails.Columns),
PublicreportSubscribePhones: buildPublicreportSubscribePhoneWhere[Q](PublicreportSubscribePhones.Columns),
PublicreportWaters: buildPublicreportWaterWhere[Q](PublicreportWaters.Columns),
PublicreportWaterImages: buildPublicreportWaterImageWhere[Q](PublicreportWaterImages.Columns),
RasterColumns: buildRasterColumnWhere[Q](RasterColumns.Columns),
RasterOverviews: buildRasterOverviewWhere[Q](RasterOverviews.Columns),
Residents: buildResidentWhere[Q](Residents.Columns),

View file

@ -46,7 +46,7 @@ type commsEmailContactR struct {
DestinationEmailLogs CommsEmailLogSlice // comms.email_log.email_log_destination_fkey
Organizations OrganizationSlice // district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey
EmailAddressNotifyEmailNuisances PublicreportNotifyEmailNuisanceSlice // publicreport.notify_email_nuisance.notify_email_nuisance_email_address_fkey
EmailAddressNotifyEmailPools PublicreportNotifyEmailPoolSlice // publicreport.notify_email_pool.notify_email_pool_email_address_fkey
EmailAddressNotifyEmailWaters PublicreportNotifyEmailWaterSlice // publicreport.notify_email_water.notify_email_pool_email_address_fkey
EmailAddressSubscribeEmails PublicreportSubscribeEmailSlice // publicreport.subscribe_email.subscribe_email_email_address_fkey
}
@ -495,14 +495,14 @@ func (os CommsEmailContactSlice) EmailAddressNotifyEmailNuisances(mods ...bob.Mo
)...)
}
// EmailAddressNotifyEmailPools starts a query for related objects on publicreport.notify_email_pool
func (o *CommsEmailContact) EmailAddressNotifyEmailPools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailPoolsQuery {
return PublicreportNotifyEmailPools.Query(append(mods,
sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(o.Address))),
// EmailAddressNotifyEmailWaters starts a query for related objects on publicreport.notify_email_water
func (o *CommsEmailContact) EmailAddressNotifyEmailWaters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailWatersQuery {
return PublicreportNotifyEmailWaters.Query(append(mods,
sm.Where(PublicreportNotifyEmailWaters.Columns.EmailAddress.EQ(psql.Arg(o.Address))),
)...)
}
func (os CommsEmailContactSlice) EmailAddressNotifyEmailPools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailPoolsQuery {
func (os CommsEmailContactSlice) EmailAddressNotifyEmailWaters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyEmailWatersQuery {
pkAddress := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
@ -514,8 +514,8 @@ func (os CommsEmailContactSlice) EmailAddressNotifyEmailPools(mods ...bob.Mod[*d
psql.F("unnest", psql.Cast(psql.Arg(pkAddress), "text[]")),
))
return PublicreportNotifyEmailPools.Query(append(mods,
sm.Where(psql.Group(PublicreportNotifyEmailPools.Columns.EmailAddress).OP("IN", PKArgExpr)),
return PublicreportNotifyEmailWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportNotifyEmailWaters.Columns.EmailAddress).OP("IN", PKArgExpr)),
)...)
}
@ -744,66 +744,66 @@ func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressNotifyEmailNuisan
return nil
}
func insertCommsEmailContactEmailAddressNotifyEmailPools0(ctx context.Context, exec bob.Executor, publicreportNotifyEmailPools1 []*PublicreportNotifyEmailPoolSetter, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailPoolSlice, error) {
for i := range publicreportNotifyEmailPools1 {
publicreportNotifyEmailPools1[i].EmailAddress = omit.From(commsEmailContact0.Address)
func insertCommsEmailContactEmailAddressNotifyEmailWaters0(ctx context.Context, exec bob.Executor, publicreportNotifyEmailWaters1 []*PublicreportNotifyEmailWaterSetter, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailWaterSlice, error) {
for i := range publicreportNotifyEmailWaters1 {
publicreportNotifyEmailWaters1[i].EmailAddress = omit.From(commsEmailContact0.Address)
}
ret, err := PublicreportNotifyEmailPools.Insert(bob.ToMods(publicreportNotifyEmailPools1...)).All(ctx, exec)
ret, err := PublicreportNotifyEmailWaters.Insert(bob.ToMods(publicreportNotifyEmailWaters1...)).All(ctx, exec)
if err != nil {
return ret, fmt.Errorf("insertCommsEmailContactEmailAddressNotifyEmailPools0: %w", err)
return ret, fmt.Errorf("insertCommsEmailContactEmailAddressNotifyEmailWaters0: %w", err)
}
return ret, nil
}
func attachCommsEmailContactEmailAddressNotifyEmailPools0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPools1 PublicreportNotifyEmailPoolSlice, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailPoolSlice, error) {
setter := &PublicreportNotifyEmailPoolSetter{
func attachCommsEmailContactEmailAddressNotifyEmailWaters0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailWaters1 PublicreportNotifyEmailWaterSlice, commsEmailContact0 *CommsEmailContact) (PublicreportNotifyEmailWaterSlice, error) {
setter := &PublicreportNotifyEmailWaterSetter{
EmailAddress: omit.From(commsEmailContact0.Address),
}
err := publicreportNotifyEmailPools1.UpdateAll(ctx, exec, *setter)
err := publicreportNotifyEmailWaters1.UpdateAll(ctx, exec, *setter)
if err != nil {
return nil, fmt.Errorf("attachCommsEmailContactEmailAddressNotifyEmailPools0: %w", err)
return nil, fmt.Errorf("attachCommsEmailContactEmailAddressNotifyEmailWaters0: %w", err)
}
return publicreportNotifyEmailPools1, nil
return publicreportNotifyEmailWaters1, nil
}
func (commsEmailContact0 *CommsEmailContact) InsertEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailPoolSetter) error {
func (commsEmailContact0 *CommsEmailContact) InsertEmailAddressNotifyEmailWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailWaterSetter) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNotifyEmailPools1, err := insertCommsEmailContactEmailAddressNotifyEmailPools0(ctx, exec, related, commsEmailContact0)
publicreportNotifyEmailWaters1, err := insertCommsEmailContactEmailAddressNotifyEmailWaters0(ctx, exec, related, commsEmailContact0)
if err != nil {
return err
}
commsEmailContact0.R.EmailAddressNotifyEmailPools = append(commsEmailContact0.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPools1...)
commsEmailContact0.R.EmailAddressNotifyEmailWaters = append(commsEmailContact0.R.EmailAddressNotifyEmailWaters, publicreportNotifyEmailWaters1...)
for _, rel := range publicreportNotifyEmailPools1 {
for _, rel := range publicreportNotifyEmailWaters1 {
rel.R.EmailAddressEmailContact = commsEmailContact0
}
return nil
}
func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailPool) error {
func (commsEmailContact0 *CommsEmailContact) AttachEmailAddressNotifyEmailWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyEmailWater) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNotifyEmailPools1 := PublicreportNotifyEmailPoolSlice(related)
publicreportNotifyEmailWaters1 := PublicreportNotifyEmailWaterSlice(related)
_, err = attachCommsEmailContactEmailAddressNotifyEmailPools0(ctx, exec, len(related), publicreportNotifyEmailPools1, commsEmailContact0)
_, err = attachCommsEmailContactEmailAddressNotifyEmailWaters0(ctx, exec, len(related), publicreportNotifyEmailWaters1, commsEmailContact0)
if err != nil {
return err
}
commsEmailContact0.R.EmailAddressNotifyEmailPools = append(commsEmailContact0.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPools1...)
commsEmailContact0.R.EmailAddressNotifyEmailWaters = append(commsEmailContact0.R.EmailAddressNotifyEmailWaters, publicreportNotifyEmailWaters1...)
for _, rel := range related {
rel.R.EmailAddressEmailContact = commsEmailContact0
@ -948,13 +948,13 @@ func (o *CommsEmailContact) Preload(name string, retrieved any) error {
}
}
return nil
case "EmailAddressNotifyEmailPools":
rels, ok := retrieved.(PublicreportNotifyEmailPoolSlice)
case "EmailAddressNotifyEmailWaters":
rels, ok := retrieved.(PublicreportNotifyEmailWaterSlice)
if !ok {
return fmt.Errorf("commsEmailContact cannot load %T as %q", retrieved, name)
}
o.R.EmailAddressNotifyEmailPools = rels
o.R.EmailAddressNotifyEmailWaters = rels
for _, rel := range rels {
if rel != nil {
@ -991,7 +991,7 @@ type commsEmailContactThenLoader[Q orm.Loadable] struct {
DestinationEmailLogs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Organizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
EmailAddressNotifyEmailNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
EmailAddressNotifyEmailPools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
EmailAddressNotifyEmailWaters func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
EmailAddressSubscribeEmails func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
@ -1005,8 +1005,8 @@ func buildCommsEmailContactThenLoader[Q orm.Loadable]() commsEmailContactThenLoa
type EmailAddressNotifyEmailNuisancesLoadInterface interface {
LoadEmailAddressNotifyEmailNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type EmailAddressNotifyEmailPoolsLoadInterface interface {
LoadEmailAddressNotifyEmailPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
type EmailAddressNotifyEmailWatersLoadInterface interface {
LoadEmailAddressNotifyEmailWaters(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type EmailAddressSubscribeEmailsLoadInterface interface {
LoadEmailAddressSubscribeEmails(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
@ -1031,10 +1031,10 @@ func buildCommsEmailContactThenLoader[Q orm.Loadable]() commsEmailContactThenLoa
return retrieved.LoadEmailAddressNotifyEmailNuisances(ctx, exec, mods...)
},
),
EmailAddressNotifyEmailPools: thenLoadBuilder[Q](
"EmailAddressNotifyEmailPools",
func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailPoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadEmailAddressNotifyEmailPools(ctx, exec, mods...)
EmailAddressNotifyEmailWaters: thenLoadBuilder[Q](
"EmailAddressNotifyEmailWaters",
func(ctx context.Context, exec bob.Executor, retrieved EmailAddressNotifyEmailWatersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadEmailAddressNotifyEmailWaters(ctx, exec, mods...)
},
),
EmailAddressSubscribeEmails: thenLoadBuilder[Q](
@ -1249,16 +1249,16 @@ func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailNuisances(ctx contex
return nil
}
// LoadEmailAddressNotifyEmailPools loads the commsEmailContact's EmailAddressNotifyEmailPools into the .R struct
func (o *CommsEmailContact) LoadEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadEmailAddressNotifyEmailWaters loads the commsEmailContact's EmailAddressNotifyEmailWaters into the .R struct
func (o *CommsEmailContact) LoadEmailAddressNotifyEmailWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.EmailAddressNotifyEmailPools = nil
o.R.EmailAddressNotifyEmailWaters = nil
related, err := o.EmailAddressNotifyEmailPools(mods...).All(ctx, exec)
related, err := o.EmailAddressNotifyEmailWaters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -1267,17 +1267,17 @@ func (o *CommsEmailContact) LoadEmailAddressNotifyEmailPools(ctx context.Context
rel.R.EmailAddressEmailContact = o
}
o.R.EmailAddressNotifyEmailPools = related
o.R.EmailAddressNotifyEmailWaters = related
return nil
}
// LoadEmailAddressNotifyEmailPools loads the commsEmailContact's EmailAddressNotifyEmailPools into the .R struct
func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadEmailAddressNotifyEmailWaters loads the commsEmailContact's EmailAddressNotifyEmailWaters into the .R struct
func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportNotifyEmailPools, err := os.EmailAddressNotifyEmailPools(mods...).All(ctx, exec)
publicreportNotifyEmailWaters, err := os.EmailAddressNotifyEmailWaters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -1287,7 +1287,7 @@ func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailPools(ctx context.Co
continue
}
o.R.EmailAddressNotifyEmailPools = nil
o.R.EmailAddressNotifyEmailWaters = nil
}
for _, o := range os {
@ -1295,7 +1295,7 @@ func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailPools(ctx context.Co
continue
}
for _, rel := range publicreportNotifyEmailPools {
for _, rel := range publicreportNotifyEmailWaters {
if !(o.Address == rel.EmailAddress) {
continue
@ -1303,7 +1303,7 @@ func (os CommsEmailContactSlice) LoadEmailAddressNotifyEmailPools(ctx context.Co
rel.R.EmailAddressEmailContact = o
o.R.EmailAddressNotifyEmailPools = append(o.R.EmailAddressNotifyEmailPools, rel)
o.R.EmailAddressNotifyEmailWaters = append(o.R.EmailAddressNotifyEmailWaters, rel)
}
}

View file

@ -51,7 +51,7 @@ type commsPhoneR struct {
PropertyOwnerPhoneE164Pools FileuploadPoolSlice // fileupload.pool.pool_property_owner_phone_e164_fkey
ResidentPhoneE164Pools FileuploadPoolSlice // fileupload.pool.pool_resident_phone_e164_fkey
PhoneE164NotifyPhoneNuisances PublicreportNotifyPhoneNuisanceSlice // publicreport.notify_phone_nuisance.notify_phone_nuisance_phone_e164_fkey
PhoneE164NotifyPhonePools PublicreportNotifyPhonePoolSlice // publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey
PhoneE164NotifyPhoneWaters PublicreportNotifyPhoneWaterSlice // publicreport.notify_phone_water.notify_phone_pool_phone_e164_fkey
PhoneE164SubscribePhones PublicreportSubscribePhoneSlice // publicreport.subscribe_phone.subscribe_phone_phone_e164_fkey
PhoneMobileResidents ResidentSlice // resident.resident_phone_mobile_fkey
}
@ -575,14 +575,14 @@ func (os CommsPhoneSlice) PhoneE164NotifyPhoneNuisances(mods ...bob.Mod[*dialect
)...)
}
// PhoneE164NotifyPhonePools starts a query for related objects on publicreport.notify_phone_pool
func (o *CommsPhone) PhoneE164NotifyPhonePools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhonePoolsQuery {
return PublicreportNotifyPhonePools.Query(append(mods,
sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
// PhoneE164NotifyPhoneWaters starts a query for related objects on publicreport.notify_phone_water
func (o *CommsPhone) PhoneE164NotifyPhoneWaters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneWatersQuery {
return PublicreportNotifyPhoneWaters.Query(append(mods,
sm.Where(PublicreportNotifyPhoneWaters.Columns.PhoneE164.EQ(psql.Arg(o.E164))),
)...)
}
func (os CommsPhoneSlice) PhoneE164NotifyPhonePools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhonePoolsQuery {
func (os CommsPhoneSlice) PhoneE164NotifyPhoneWaters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNotifyPhoneWatersQuery {
pkE164 := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
@ -594,8 +594,8 @@ func (os CommsPhoneSlice) PhoneE164NotifyPhonePools(mods ...bob.Mod[*dialect.Sel
psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")),
))
return PublicreportNotifyPhonePools.Query(append(mods,
sm.Where(psql.Group(PublicreportNotifyPhonePools.Columns.PhoneE164).OP("IN", PKArgExpr)),
return PublicreportNotifyPhoneWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportNotifyPhoneWaters.Columns.PhoneE164).OP("IN", PKArgExpr)),
)...)
}
@ -1120,66 +1120,66 @@ func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhoneNuisances(ctx context.C
return nil
}
func insertCommsPhonePhoneE164NotifyPhonePools0(ctx context.Context, exec bob.Executor, publicreportNotifyPhonePools1 []*PublicreportNotifyPhonePoolSetter, commsPhone0 *CommsPhone) (PublicreportNotifyPhonePoolSlice, error) {
for i := range publicreportNotifyPhonePools1 {
publicreportNotifyPhonePools1[i].PhoneE164 = omit.From(commsPhone0.E164)
func insertCommsPhonePhoneE164NotifyPhoneWaters0(ctx context.Context, exec bob.Executor, publicreportNotifyPhoneWaters1 []*PublicreportNotifyPhoneWaterSetter, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneWaterSlice, error) {
for i := range publicreportNotifyPhoneWaters1 {
publicreportNotifyPhoneWaters1[i].PhoneE164 = omit.From(commsPhone0.E164)
}
ret, err := PublicreportNotifyPhonePools.Insert(bob.ToMods(publicreportNotifyPhonePools1...)).All(ctx, exec)
ret, err := PublicreportNotifyPhoneWaters.Insert(bob.ToMods(publicreportNotifyPhoneWaters1...)).All(ctx, exec)
if err != nil {
return ret, fmt.Errorf("insertCommsPhonePhoneE164NotifyPhonePools0: %w", err)
return ret, fmt.Errorf("insertCommsPhonePhoneE164NotifyPhoneWaters0: %w", err)
}
return ret, nil
}
func attachCommsPhonePhoneE164NotifyPhonePools0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhonePools1 PublicreportNotifyPhonePoolSlice, commsPhone0 *CommsPhone) (PublicreportNotifyPhonePoolSlice, error) {
setter := &PublicreportNotifyPhonePoolSetter{
func attachCommsPhonePhoneE164NotifyPhoneWaters0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWaters1 PublicreportNotifyPhoneWaterSlice, commsPhone0 *CommsPhone) (PublicreportNotifyPhoneWaterSlice, error) {
setter := &PublicreportNotifyPhoneWaterSetter{
PhoneE164: omit.From(commsPhone0.E164),
}
err := publicreportNotifyPhonePools1.UpdateAll(ctx, exec, *setter)
err := publicreportNotifyPhoneWaters1.UpdateAll(ctx, exec, *setter)
if err != nil {
return nil, fmt.Errorf("attachCommsPhonePhoneE164NotifyPhonePools0: %w", err)
return nil, fmt.Errorf("attachCommsPhonePhoneE164NotifyPhoneWaters0: %w", err)
}
return publicreportNotifyPhonePools1, nil
return publicreportNotifyPhoneWaters1, nil
}
func (commsPhone0 *CommsPhone) InsertPhoneE164NotifyPhonePools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhonePoolSetter) error {
func (commsPhone0 *CommsPhone) InsertPhoneE164NotifyPhoneWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneWaterSetter) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNotifyPhonePools1, err := insertCommsPhonePhoneE164NotifyPhonePools0(ctx, exec, related, commsPhone0)
publicreportNotifyPhoneWaters1, err := insertCommsPhonePhoneE164NotifyPhoneWaters0(ctx, exec, related, commsPhone0)
if err != nil {
return err
}
commsPhone0.R.PhoneE164NotifyPhonePools = append(commsPhone0.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePools1...)
commsPhone0.R.PhoneE164NotifyPhoneWaters = append(commsPhone0.R.PhoneE164NotifyPhoneWaters, publicreportNotifyPhoneWaters1...)
for _, rel := range publicreportNotifyPhonePools1 {
for _, rel := range publicreportNotifyPhoneWaters1 {
rel.R.PhoneE164Phone = commsPhone0
}
return nil
}
func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhonePools(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhonePool) error {
func (commsPhone0 *CommsPhone) AttachPhoneE164NotifyPhoneWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportNotifyPhoneWater) error {
if len(related) == 0 {
return nil
}
var err error
publicreportNotifyPhonePools1 := PublicreportNotifyPhonePoolSlice(related)
publicreportNotifyPhoneWaters1 := PublicreportNotifyPhoneWaterSlice(related)
_, err = attachCommsPhonePhoneE164NotifyPhonePools0(ctx, exec, len(related), publicreportNotifyPhonePools1, commsPhone0)
_, err = attachCommsPhonePhoneE164NotifyPhoneWaters0(ctx, exec, len(related), publicreportNotifyPhoneWaters1, commsPhone0)
if err != nil {
return err
}
commsPhone0.R.PhoneE164NotifyPhonePools = append(commsPhone0.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePools1...)
commsPhone0.R.PhoneE164NotifyPhoneWaters = append(commsPhone0.R.PhoneE164NotifyPhoneWaters, publicreportNotifyPhoneWaters1...)
for _, rel := range related {
rel.R.PhoneE164Phone = commsPhone0
@ -1446,13 +1446,13 @@ func (o *CommsPhone) Preload(name string, retrieved any) error {
}
}
return nil
case "PhoneE164NotifyPhonePools":
rels, ok := retrieved.(PublicreportNotifyPhonePoolSlice)
case "PhoneE164NotifyPhoneWaters":
rels, ok := retrieved.(PublicreportNotifyPhoneWaterSlice)
if !ok {
return fmt.Errorf("commsPhone cannot load %T as %q", retrieved, name)
}
o.R.PhoneE164NotifyPhonePools = rels
o.R.PhoneE164NotifyPhoneWaters = rels
for _, rel := range rels {
if rel != nil {
@ -1507,7 +1507,7 @@ type commsPhoneThenLoader[Q orm.Loadable] struct {
PropertyOwnerPhoneE164Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
ResidentPhoneE164Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PhoneE164NotifyPhoneNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PhoneE164NotifyPhonePools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PhoneE164NotifyPhoneWaters func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PhoneE164SubscribePhones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PhoneMobileResidents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
@ -1534,8 +1534,8 @@ func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] {
type PhoneE164NotifyPhoneNuisancesLoadInterface interface {
LoadPhoneE164NotifyPhoneNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PhoneE164NotifyPhonePoolsLoadInterface interface {
LoadPhoneE164NotifyPhonePools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
type PhoneE164NotifyPhoneWatersLoadInterface interface {
LoadPhoneE164NotifyPhoneWaters(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PhoneE164SubscribePhonesLoadInterface interface {
LoadPhoneE164SubscribePhones(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
@ -1587,10 +1587,10 @@ func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] {
return retrieved.LoadPhoneE164NotifyPhoneNuisances(ctx, exec, mods...)
},
),
PhoneE164NotifyPhonePools: thenLoadBuilder[Q](
"PhoneE164NotifyPhonePools",
func(ctx context.Context, exec bob.Executor, retrieved PhoneE164NotifyPhonePoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPhoneE164NotifyPhonePools(ctx, exec, mods...)
PhoneE164NotifyPhoneWaters: thenLoadBuilder[Q](
"PhoneE164NotifyPhoneWaters",
func(ctx context.Context, exec bob.Executor, retrieved PhoneE164NotifyPhoneWatersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPhoneE164NotifyPhoneWaters(ctx, exec, mods...)
},
),
PhoneE164SubscribePhones: thenLoadBuilder[Q](
@ -2061,16 +2061,16 @@ func (os CommsPhoneSlice) LoadPhoneE164NotifyPhoneNuisances(ctx context.Context,
return nil
}
// LoadPhoneE164NotifyPhonePools loads the commsPhone's PhoneE164NotifyPhonePools into the .R struct
func (o *CommsPhone) LoadPhoneE164NotifyPhonePools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadPhoneE164NotifyPhoneWaters loads the commsPhone's PhoneE164NotifyPhoneWaters into the .R struct
func (o *CommsPhone) LoadPhoneE164NotifyPhoneWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.PhoneE164NotifyPhonePools = nil
o.R.PhoneE164NotifyPhoneWaters = nil
related, err := o.PhoneE164NotifyPhonePools(mods...).All(ctx, exec)
related, err := o.PhoneE164NotifyPhoneWaters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -2079,17 +2079,17 @@ func (o *CommsPhone) LoadPhoneE164NotifyPhonePools(ctx context.Context, exec bob
rel.R.PhoneE164Phone = o
}
o.R.PhoneE164NotifyPhonePools = related
o.R.PhoneE164NotifyPhoneWaters = related
return nil
}
// LoadPhoneE164NotifyPhonePools loads the commsPhone's PhoneE164NotifyPhonePools into the .R struct
func (os CommsPhoneSlice) LoadPhoneE164NotifyPhonePools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadPhoneE164NotifyPhoneWaters loads the commsPhone's PhoneE164NotifyPhoneWaters into the .R struct
func (os CommsPhoneSlice) LoadPhoneE164NotifyPhoneWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportNotifyPhonePools, err := os.PhoneE164NotifyPhonePools(mods...).All(ctx, exec)
publicreportNotifyPhoneWaters, err := os.PhoneE164NotifyPhoneWaters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -2099,7 +2099,7 @@ func (os CommsPhoneSlice) LoadPhoneE164NotifyPhonePools(ctx context.Context, exe
continue
}
o.R.PhoneE164NotifyPhonePools = nil
o.R.PhoneE164NotifyPhoneWaters = nil
}
for _, o := range os {
@ -2107,7 +2107,7 @@ func (os CommsPhoneSlice) LoadPhoneE164NotifyPhonePools(ctx context.Context, exe
continue
}
for _, rel := range publicreportNotifyPhonePools {
for _, rel := range publicreportNotifyPhoneWaters {
if !(o.E164 == rel.PhoneE164) {
continue
@ -2115,7 +2115,7 @@ func (os CommsPhoneSlice) LoadPhoneE164NotifyPhonePools(ctx context.Context, exe
rel.R.PhoneE164Phone = o
o.R.PhoneE164NotifyPhonePools = append(o.R.PhoneE164NotifyPhonePools, rel)
o.R.PhoneE164NotifyPhoneWaters = append(o.R.PhoneE164NotifyPhoneWaters, rel)
}
}

View file

@ -119,7 +119,7 @@ type organizationR struct {
ArcgisMapServiceServiceMap *ArcgisServiceMap // organization.organization_arcgis_map_service_id_fkey
FieldseekerServiceFeatureItemServiceFeature *ArcgisServiceFeature // organization.organization_fieldseeker_service_feature_item_id_fkey
Nuisances PublicreportNuisanceSlice // publicreport.nuisance.nuisance_organization_id_fkey
PublicreportPool PublicreportPoolSlice // publicreport.pool.pool_organization_id_fkey
Waters PublicreportWaterSlice // publicreport.water.pool_organization_id_fkey
ReviewTasks ReviewTaskSlice // review_task.review_task_organization_id_fkey
Signals SignalSlice // signal.signal_organization_id_fkey
User UserSlice // user_.user__organization_id_fkey
@ -1973,14 +1973,14 @@ func (os OrganizationSlice) Nuisances(mods ...bob.Mod[*dialect.SelectQuery]) Pub
)...)
}
// PublicreportPool starts a query for related objects on publicreport.pool
func (o *Organization) PublicreportPool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
return PublicreportPools.Query(append(mods,
sm.Where(PublicreportPools.Columns.OrganizationID.EQ(psql.Arg(o.ID))),
// Waters starts a query for related objects on publicreport.water
func (o *Organization) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.Where(PublicreportWaters.Columns.OrganizationID.EQ(psql.Arg(o.ID))),
)...)
}
func (os OrganizationSlice) PublicreportPool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
func (os OrganizationSlice) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
pkID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
@ -1992,8 +1992,8 @@ func (os OrganizationSlice) PublicreportPool(mods ...bob.Mod[*dialect.SelectQuer
psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")),
))
return PublicreportPools.Query(append(mods,
sm.Where(psql.Group(PublicreportPools.Columns.OrganizationID).OP("IN", PKArgExpr)),
return PublicreportWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportWaters.Columns.OrganizationID).OP("IN", PKArgExpr)),
)...)
}
@ -4927,66 +4927,66 @@ func (organization0 *Organization) AttachNuisances(ctx context.Context, exec bob
return nil
}
func insertOrganizationPublicreportPool0(ctx context.Context, exec bob.Executor, publicreportPools1 []*PublicreportPoolSetter, organization0 *Organization) (PublicreportPoolSlice, error) {
for i := range publicreportPools1 {
publicreportPools1[i].OrganizationID = omitnull.From(organization0.ID)
func insertOrganizationWaters0(ctx context.Context, exec bob.Executor, publicreportWaters1 []*PublicreportWaterSetter, organization0 *Organization) (PublicreportWaterSlice, error) {
for i := range publicreportWaters1 {
publicreportWaters1[i].OrganizationID = omitnull.From(organization0.ID)
}
ret, err := PublicreportPools.Insert(bob.ToMods(publicreportPools1...)).All(ctx, exec)
ret, err := PublicreportWaters.Insert(bob.ToMods(publicreportWaters1...)).All(ctx, exec)
if err != nil {
return ret, fmt.Errorf("insertOrganizationPublicreportPool0: %w", err)
return ret, fmt.Errorf("insertOrganizationWaters0: %w", err)
}
return ret, nil
}
func attachOrganizationPublicreportPool0(ctx context.Context, exec bob.Executor, count int, publicreportPools1 PublicreportPoolSlice, organization0 *Organization) (PublicreportPoolSlice, error) {
setter := &PublicreportPoolSetter{
func attachOrganizationWaters0(ctx context.Context, exec bob.Executor, count int, publicreportWaters1 PublicreportWaterSlice, organization0 *Organization) (PublicreportWaterSlice, error) {
setter := &PublicreportWaterSetter{
OrganizationID: omitnull.From(organization0.ID),
}
err := publicreportPools1.UpdateAll(ctx, exec, *setter)
err := publicreportWaters1.UpdateAll(ctx, exec, *setter)
if err != nil {
return nil, fmt.Errorf("attachOrganizationPublicreportPool0: %w", err)
return nil, fmt.Errorf("attachOrganizationWaters0: %w", err)
}
return publicreportPools1, nil
return publicreportWaters1, nil
}
func (organization0 *Organization) InsertPublicreportPool(ctx context.Context, exec bob.Executor, related ...*PublicreportPoolSetter) error {
func (organization0 *Organization) InsertWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWaterSetter) error {
if len(related) == 0 {
return nil
}
var err error
publicreportPools1, err := insertOrganizationPublicreportPool0(ctx, exec, related, organization0)
publicreportWaters1, err := insertOrganizationWaters0(ctx, exec, related, organization0)
if err != nil {
return err
}
organization0.R.PublicreportPool = append(organization0.R.PublicreportPool, publicreportPools1...)
organization0.R.Waters = append(organization0.R.Waters, publicreportWaters1...)
for _, rel := range publicreportPools1 {
for _, rel := range publicreportWaters1 {
rel.R.Organization = organization0
}
return nil
}
func (organization0 *Organization) AttachPublicreportPool(ctx context.Context, exec bob.Executor, related ...*PublicreportPool) error {
func (organization0 *Organization) AttachWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWater) error {
if len(related) == 0 {
return nil
}
var err error
publicreportPools1 := PublicreportPoolSlice(related)
publicreportWaters1 := PublicreportWaterSlice(related)
_, err = attachOrganizationPublicreportPool0(ctx, exec, len(related), publicreportPools1, organization0)
_, err = attachOrganizationWaters0(ctx, exec, len(related), publicreportWaters1, organization0)
if err != nil {
return err
}
organization0.R.PublicreportPool = append(organization0.R.PublicreportPool, publicreportPools1...)
organization0.R.Waters = append(organization0.R.Waters, publicreportWaters1...)
for _, rel := range related {
rel.R.Organization = organization0
@ -5879,13 +5879,13 @@ func (o *Organization) Preload(name string, retrieved any) error {
}
}
return nil
case "PublicreportPool":
rels, ok := retrieved.(PublicreportPoolSlice)
case "Waters":
rels, ok := retrieved.(PublicreportWaterSlice)
if !ok {
return fmt.Errorf("organization cannot load %T as %q", retrieved, name)
}
o.R.PublicreportPool = rels
o.R.Waters = rels
for _, rel := range rels {
if rel != nil {
@ -6034,7 +6034,7 @@ type organizationThenLoader[Q orm.Loadable] struct {
ArcgisMapServiceServiceMap func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
FieldseekerServiceFeatureItemServiceFeature func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Nuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
PublicreportPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Waters func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
ReviewTasks func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Signals func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
User func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
@ -6170,8 +6170,8 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] {
type NuisancesLoadInterface interface {
LoadNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PublicreportPoolLoadInterface interface {
LoadPublicreportPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
type WatersLoadInterface interface {
LoadWaters(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type ReviewTasksLoadInterface interface {
LoadReviewTasks(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
@ -6442,10 +6442,10 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] {
return retrieved.LoadNuisances(ctx, exec, mods...)
},
),
PublicreportPool: thenLoadBuilder[Q](
"PublicreportPool",
func(ctx context.Context, exec bob.Executor, retrieved PublicreportPoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPublicreportPool(ctx, exec, mods...)
Waters: thenLoadBuilder[Q](
"Waters",
func(ctx context.Context, exec bob.Executor, retrieved WatersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWaters(ctx, exec, mods...)
},
),
ReviewTasks: thenLoadBuilder[Q](
@ -9117,16 +9117,16 @@ func (os OrganizationSlice) LoadNuisances(ctx context.Context, exec bob.Executor
return nil
}
// LoadPublicreportPool loads the organization's PublicreportPool into the .R struct
func (o *Organization) LoadPublicreportPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadWaters loads the organization's Waters into the .R struct
func (o *Organization) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.PublicreportPool = nil
o.R.Waters = nil
related, err := o.PublicreportPool(mods...).All(ctx, exec)
related, err := o.Waters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -9135,17 +9135,17 @@ func (o *Organization) LoadPublicreportPool(ctx context.Context, exec bob.Execut
rel.R.Organization = o
}
o.R.PublicreportPool = related
o.R.Waters = related
return nil
}
// LoadPublicreportPool loads the organization's PublicreportPool into the .R struct
func (os OrganizationSlice) LoadPublicreportPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadWaters loads the organization's Waters into the .R struct
func (os OrganizationSlice) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportPools, err := os.PublicreportPool(mods...).All(ctx, exec)
publicreportWaters, err := os.Waters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -9155,7 +9155,7 @@ func (os OrganizationSlice) LoadPublicreportPool(ctx context.Context, exec bob.E
continue
}
o.R.PublicreportPool = nil
o.R.Waters = nil
}
for _, o := range os {
@ -9163,7 +9163,7 @@ func (os OrganizationSlice) LoadPublicreportPool(ctx context.Context, exec bob.E
continue
}
for _, rel := range publicreportPools {
for _, rel := range publicreportWaters {
if !rel.OrganizationID.IsValue() {
continue
@ -9174,7 +9174,7 @@ func (os OrganizationSlice) LoadPublicreportPool(ctx context.Context, exec bob.E
rel.R.Organization = o
o.R.PublicreportPool = append(o.R.PublicreportPool, rel)
o.R.Waters = append(o.R.Waters, rel)
}
}

View file

@ -54,7 +54,7 @@ type PublicreportImagesQuery = *psql.ViewQuery[*PublicreportImage, PublicreportI
type publicreportImageR struct {
ImageExifs PublicreportImageExifSlice // publicreport.image_exif.image_exif_image_id_fkey
Nuisances PublicreportNuisanceSlice // publicreport.nuisance_image.nuisance_image_image_id_fkeypublicreport.nuisance_image.nuisance_image_nuisance_id_fkey
Pools PublicreportPoolSlice // publicreport.pool_image.pool_image_image_id_fkeypublicreport.pool_image.pool_image_pool_id_fkey
Waters PublicreportWaterSlice // publicreport.water_image.pool_image_image_id_fkeypublicreport.water_image.pool_image_pool_id_fkey
}
func buildPublicreportImageColumns(alias string) publicreportImageColumns {
@ -588,16 +588,16 @@ func (os PublicreportImageSlice) Nuisances(mods ...bob.Mod[*dialect.SelectQuery]
)...)
}
// Pools starts a query for related objects on publicreport.pool
func (o *PublicreportImage) Pools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
return PublicreportPools.Query(append(mods,
sm.InnerJoin(PublicreportPoolImages.NameAs()).On(
PublicreportPools.Columns.ID.EQ(PublicreportPoolImages.Columns.PoolID)),
sm.Where(PublicreportPoolImages.Columns.ImageID.EQ(psql.Arg(o.ID))),
// Waters starts a query for related objects on publicreport.water
func (o *PublicreportImage) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.InnerJoin(PublicreportWaterImages.NameAs()).On(
PublicreportWaters.Columns.ID.EQ(PublicreportWaterImages.Columns.WaterID)),
sm.Where(PublicreportWaterImages.Columns.ImageID.EQ(psql.Arg(o.ID))),
)...)
}
func (os PublicreportImageSlice) Pools(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
func (os PublicreportImageSlice) Waters(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
pkID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
@ -609,11 +609,11 @@ func (os PublicreportImageSlice) Pools(mods ...bob.Mod[*dialect.SelectQuery]) Pu
psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")),
))
return PublicreportPools.Query(append(mods,
sm.InnerJoin(PublicreportPoolImages.NameAs()).On(
PublicreportPools.Columns.ID.EQ(PublicreportPoolImages.Columns.PoolID),
return PublicreportWaters.Query(append(mods,
sm.InnerJoin(PublicreportWaterImages.NameAs()).On(
PublicreportWaters.Columns.ID.EQ(PublicreportWaterImages.Columns.WaterID),
),
sm.Where(psql.Group(PublicreportPoolImages.Columns.ImageID).OP("IN", PKArgExpr)),
sm.Where(psql.Group(PublicreportWaterImages.Columns.ImageID).OP("IN", PKArgExpr)),
)...)
}
@ -750,63 +750,63 @@ func (publicreportImage0 *PublicreportImage) AttachNuisances(ctx context.Context
return nil
}
func attachPublicreportImagePools0(ctx context.Context, exec bob.Executor, count int, publicreportImage0 *PublicreportImage, publicreportPools2 PublicreportPoolSlice) (PublicreportPoolImageSlice, error) {
setters := make([]*PublicreportPoolImageSetter, count)
func attachPublicreportImageWaters0(ctx context.Context, exec bob.Executor, count int, publicreportImage0 *PublicreportImage, publicreportWaters2 PublicreportWaterSlice) (PublicreportWaterImageSlice, error) {
setters := make([]*PublicreportWaterImageSetter, count)
for i := range count {
setters[i] = &PublicreportPoolImageSetter{
setters[i] = &PublicreportWaterImageSetter{
ImageID: omit.From(publicreportImage0.ID),
PoolID: omit.From(publicreportPools2[i].ID),
WaterID: omit.From(publicreportWaters2[i].ID),
}
}
publicreportPoolImages1, err := PublicreportPoolImages.Insert(bob.ToMods(setters...)).All(ctx, exec)
publicreportWaterImages1, err := PublicreportWaterImages.Insert(bob.ToMods(setters...)).All(ctx, exec)
if err != nil {
return nil, fmt.Errorf("attachPublicreportImagePools0: %w", err)
return nil, fmt.Errorf("attachPublicreportImageWaters0: %w", err)
}
return publicreportPoolImages1, nil
return publicreportWaterImages1, nil
}
func (publicreportImage0 *PublicreportImage) InsertPools(ctx context.Context, exec bob.Executor, related ...*PublicreportPoolSetter) error {
func (publicreportImage0 *PublicreportImage) InsertWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWaterSetter) error {
if len(related) == 0 {
return nil
}
var err error
inserted, err := PublicreportPools.Insert(bob.ToMods(related...)).All(ctx, exec)
inserted, err := PublicreportWaters.Insert(bob.ToMods(related...)).All(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
publicreportPools2 := PublicreportPoolSlice(inserted)
publicreportWaters2 := PublicreportWaterSlice(inserted)
_, err = attachPublicreportImagePools0(ctx, exec, len(related), publicreportImage0, publicreportPools2)
_, err = attachPublicreportImageWaters0(ctx, exec, len(related), publicreportImage0, publicreportWaters2)
if err != nil {
return err
}
publicreportImage0.R.Pools = append(publicreportImage0.R.Pools, publicreportPools2...)
publicreportImage0.R.Waters = append(publicreportImage0.R.Waters, publicreportWaters2...)
for _, rel := range publicreportPools2 {
for _, rel := range publicreportWaters2 {
rel.R.Images = append(rel.R.Images, publicreportImage0)
}
return nil
}
func (publicreportImage0 *PublicreportImage) AttachPools(ctx context.Context, exec bob.Executor, related ...*PublicreportPool) error {
func (publicreportImage0 *PublicreportImage) AttachWaters(ctx context.Context, exec bob.Executor, related ...*PublicreportWater) error {
if len(related) == 0 {
return nil
}
var err error
publicreportPools2 := PublicreportPoolSlice(related)
publicreportWaters2 := PublicreportWaterSlice(related)
_, err = attachPublicreportImagePools0(ctx, exec, len(related), publicreportImage0, publicreportPools2)
_, err = attachPublicreportImageWaters0(ctx, exec, len(related), publicreportImage0, publicreportWaters2)
if err != nil {
return err
}
publicreportImage0.R.Pools = append(publicreportImage0.R.Pools, publicreportPools2...)
publicreportImage0.R.Waters = append(publicreportImage0.R.Waters, publicreportWaters2...)
for _, rel := range related {
rel.R.Images = append(rel.R.Images, publicreportImage0)
@ -879,13 +879,13 @@ func (o *PublicreportImage) Preload(name string, retrieved any) error {
}
}
return nil
case "Pools":
rels, ok := retrieved.(PublicreportPoolSlice)
case "Waters":
rels, ok := retrieved.(PublicreportWaterSlice)
if !ok {
return fmt.Errorf("publicreportImage cannot load %T as %q", retrieved, name)
}
o.R.Pools = rels
o.R.Waters = rels
for _, rel := range rels {
if rel != nil {
@ -907,7 +907,7 @@ func buildPublicreportImagePreloader() publicreportImagePreloader {
type publicreportImageThenLoader[Q orm.Loadable] struct {
ImageExifs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Nuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Waters func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportImageThenLoader[Q orm.Loadable]() publicreportImageThenLoader[Q] {
@ -917,8 +917,8 @@ func buildPublicreportImageThenLoader[Q orm.Loadable]() publicreportImageThenLoa
type NuisancesLoadInterface interface {
LoadNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PoolsLoadInterface interface {
LoadPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
type WatersLoadInterface interface {
LoadWaters(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportImageThenLoader[Q]{
@ -934,10 +934,10 @@ func buildPublicreportImageThenLoader[Q orm.Loadable]() publicreportImageThenLoa
return retrieved.LoadNuisances(ctx, exec, mods...)
},
),
Pools: thenLoadBuilder[Q](
"Pools",
func(ctx context.Context, exec bob.Executor, retrieved PoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPools(ctx, exec, mods...)
Waters: thenLoadBuilder[Q](
"Waters",
func(ctx context.Context, exec bob.Executor, retrieved WatersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWaters(ctx, exec, mods...)
},
),
}
@ -1085,16 +1085,16 @@ func (os PublicreportImageSlice) LoadNuisances(ctx context.Context, exec bob.Exe
return nil
}
// LoadPools loads the publicreportImage's Pools into the .R struct
func (o *PublicreportImage) LoadPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadWaters loads the publicreportImage's Waters into the .R struct
func (o *PublicreportImage) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Pools = nil
o.R.Waters = nil
related, err := o.Pools(mods...).All(ctx, exec)
related, err := o.Waters(mods...).All(ctx, exec)
if err != nil {
return err
}
@ -1103,12 +1103,12 @@ func (o *PublicreportImage) LoadPools(ctx context.Context, exec bob.Executor, mo
rel.R.Images = PublicreportImageSlice{o}
}
o.R.Pools = related
o.R.Waters = related
return nil
}
// LoadPools loads the publicreportImage's Pools into the .R struct
func (os PublicreportImageSlice) LoadPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
// LoadWaters loads the publicreportImage's Waters into the .R struct
func (os PublicreportImageSlice) LoadWaters(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
@ -1120,17 +1120,17 @@ func (os PublicreportImageSlice) LoadPools(ctx context.Context, exec bob.Executo
}
if len(sq.SelectList.Columns) == 0 {
mods = append(mods, sm.Columns(PublicreportPools.Columns))
mods = append(mods, sm.Columns(PublicreportWaters.Columns))
}
q := os.Pools(append(
q := os.Waters(append(
mods,
sm.Columns(PublicreportPoolImages.Columns.ImageID.As("related_publicreport.image.ID")),
sm.Columns(PublicreportWaterImages.Columns.ImageID.As("related_publicreport.image.ID")),
)...)
IDSlice := []int32{}
mapper := scan.Mod(scan.StructMapper[*PublicreportPool](), func(ctx context.Context, cols []string) (scan.BeforeFunc, func(any, any) error) {
mapper := scan.Mod(scan.StructMapper[*PublicreportWater](), func(ctx context.Context, cols []string) (scan.BeforeFunc, func(any, any) error) {
return func(row *scan.Row) (any, error) {
IDSlice = append(IDSlice, *new(int32))
row.ScheduleScanByName("related_publicreport.image.ID", &IDSlice[len(IDSlice)-1])
@ -1142,24 +1142,24 @@ func (os PublicreportImageSlice) LoadPools(ctx context.Context, exec bob.Executo
}
})
publicreportPools, err := bob.Allx[bob.SliceTransformer[*PublicreportPool, PublicreportPoolSlice]](ctx, exec, q, mapper)
publicreportWaters, err := bob.Allx[bob.SliceTransformer[*PublicreportWater, PublicreportWaterSlice]](ctx, exec, q, mapper)
if err != nil {
return err
}
for _, o := range os {
o.R.Pools = nil
o.R.Waters = nil
}
for _, o := range os {
for i, rel := range publicreportPools {
for i, rel := range publicreportWaters {
if !(o.ID == IDSlice[i]) {
continue
}
rel.R.Images = append(rel.R.Images, o)
o.R.Pools = append(o.R.Pools, rel)
o.R.Waters = append(o.R.Waters, rel)
}
}

View file

@ -1,796 +0,0 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/null"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
)
// PublicreportNotifyEmailPool is an object representing the database table.
type PublicreportNotifyEmailPool struct {
Created time.Time `db:"created" `
Deleted null.Val[time.Time] `db:"deleted" `
PoolID int32 `db:"pool_id,pk" `
EmailAddress string `db:"email_address,pk" `
R publicreportNotifyEmailPoolR `db:"-" `
}
// PublicreportNotifyEmailPoolSlice is an alias for a slice of pointers to PublicreportNotifyEmailPool.
// This should almost always be used instead of []*PublicreportNotifyEmailPool.
type PublicreportNotifyEmailPoolSlice []*PublicreportNotifyEmailPool
// PublicreportNotifyEmailPools contains methods to work with the notify_email_pool table
var PublicreportNotifyEmailPools = psql.NewTablex[*PublicreportNotifyEmailPool, PublicreportNotifyEmailPoolSlice, *PublicreportNotifyEmailPoolSetter]("publicreport", "notify_email_pool", buildPublicreportNotifyEmailPoolColumns("publicreport.notify_email_pool"))
// PublicreportNotifyEmailPoolsQuery is a query on the notify_email_pool table
type PublicreportNotifyEmailPoolsQuery = *psql.ViewQuery[*PublicreportNotifyEmailPool, PublicreportNotifyEmailPoolSlice]
// publicreportNotifyEmailPoolR is where relationships are stored.
type publicreportNotifyEmailPoolR struct {
EmailAddressEmailContact *CommsEmailContact // publicreport.notify_email_pool.notify_email_pool_email_address_fkey
Pool *PublicreportPool // publicreport.notify_email_pool.notify_email_pool_pool_id_fkey
}
func buildPublicreportNotifyEmailPoolColumns(alias string) publicreportNotifyEmailPoolColumns {
return publicreportNotifyEmailPoolColumns{
ColumnsExpr: expr.NewColumnsExpr(
"created", "deleted", "pool_id", "email_address",
).WithParent("publicreport.notify_email_pool"),
tableAlias: alias,
Created: psql.Quote(alias, "created"),
Deleted: psql.Quote(alias, "deleted"),
PoolID: psql.Quote(alias, "pool_id"),
EmailAddress: psql.Quote(alias, "email_address"),
}
}
type publicreportNotifyEmailPoolColumns struct {
expr.ColumnsExpr
tableAlias string
Created psql.Expression
Deleted psql.Expression
PoolID psql.Expression
EmailAddress psql.Expression
}
func (c publicreportNotifyEmailPoolColumns) Alias() string {
return c.tableAlias
}
func (publicreportNotifyEmailPoolColumns) AliasedAs(alias string) publicreportNotifyEmailPoolColumns {
return buildPublicreportNotifyEmailPoolColumns(alias)
}
// PublicreportNotifyEmailPoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyEmailPoolSetter struct {
Created omit.Val[time.Time] `db:"created" `
Deleted omitnull.Val[time.Time] `db:"deleted" `
PoolID omit.Val[int32] `db:"pool_id,pk" `
EmailAddress omit.Val[string] `db:"email_address,pk" `
}
func (s PublicreportNotifyEmailPoolSetter) SetColumns() []string {
vals := make([]string, 0, 4)
if s.Created.IsValue() {
vals = append(vals, "created")
}
if !s.Deleted.IsUnset() {
vals = append(vals, "deleted")
}
if s.PoolID.IsValue() {
vals = append(vals, "pool_id")
}
if s.EmailAddress.IsValue() {
vals = append(vals, "email_address")
}
return vals
}
func (s PublicreportNotifyEmailPoolSetter) Overwrite(t *PublicreportNotifyEmailPool) {
if s.Created.IsValue() {
t.Created = s.Created.MustGet()
}
if !s.Deleted.IsUnset() {
t.Deleted = s.Deleted.MustGetNull()
}
if s.PoolID.IsValue() {
t.PoolID = s.PoolID.MustGet()
}
if s.EmailAddress.IsValue() {
t.EmailAddress = s.EmailAddress.MustGet()
}
}
func (s *PublicreportNotifyEmailPoolSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportNotifyEmailPools.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 4)
if s.Created.IsValue() {
vals[0] = psql.Arg(s.Created.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if !s.Deleted.IsUnset() {
vals[1] = psql.Arg(s.Deleted.MustGetNull())
} else {
vals[1] = psql.Raw("DEFAULT")
}
if s.PoolID.IsValue() {
vals[2] = psql.Arg(s.PoolID.MustGet())
} else {
vals[2] = psql.Raw("DEFAULT")
}
if s.EmailAddress.IsValue() {
vals[3] = psql.Arg(s.EmailAddress.MustGet())
} else {
vals[3] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportNotifyEmailPoolSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportNotifyEmailPoolSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 4)
if s.Created.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "created")...),
psql.Arg(s.Created),
}})
}
if !s.Deleted.IsUnset() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "deleted")...),
psql.Arg(s.Deleted),
}})
}
if s.PoolID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "pool_id")...),
psql.Arg(s.PoolID),
}})
}
if s.EmailAddress.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "email_address")...),
psql.Arg(s.EmailAddress),
}})
}
return exprs
}
// FindPublicreportNotifyEmailPool retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyEmailPool(ctx context.Context, exec bob.Executor, PoolIDPK int32, EmailAddressPK string, cols ...string) (*PublicreportNotifyEmailPool, error) {
if len(cols) == 0 {
return PublicreportNotifyEmailPools.Query(
sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
).One(ctx, exec)
}
return PublicreportNotifyEmailPools.Query(
sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
sm.Columns(PublicreportNotifyEmailPools.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportNotifyEmailPoolExists checks the presence of a single record by primary key
func PublicreportNotifyEmailPoolExists(ctx context.Context, exec bob.Executor, PoolIDPK int32, EmailAddressPK string) (bool, error) {
return PublicreportNotifyEmailPools.Query(
sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportNotifyEmailPool is retrieved from the database
func (o *PublicreportNotifyEmailPool) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyEmailPools.AfterSelectHooks.RunHooks(ctx, exec, PublicreportNotifyEmailPoolSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyEmailPools.AfterInsertHooks.RunHooks(ctx, exec, PublicreportNotifyEmailPoolSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyEmailPools.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportNotifyEmailPoolSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyEmailPools.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportNotifyEmailPoolSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportNotifyEmailPool
func (o *PublicreportNotifyEmailPool) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.PoolID,
o.EmailAddress,
)
}
func (o *PublicreportNotifyEmailPool) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.notify_email_pool", "pool_id"), psql.Quote("publicreport.notify_email_pool", "email_address")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportNotifyEmailPool
func (o *PublicreportNotifyEmailPool) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyEmailPoolSetter) error {
v, err := PublicreportNotifyEmailPools.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 PublicreportNotifyEmailPool record with an executor
func (o *PublicreportNotifyEmailPool) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportNotifyEmailPools.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportNotifyEmailPool using the executor
func (o *PublicreportNotifyEmailPool) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportNotifyEmailPools.Query(
sm.Where(PublicreportNotifyEmailPools.Columns.PoolID.EQ(psql.Arg(o.PoolID))),
sm.Where(PublicreportNotifyEmailPools.Columns.EmailAddress.EQ(psql.Arg(o.EmailAddress))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportNotifyEmailPoolSlice is retrieved from the database
func (o PublicreportNotifyEmailPoolSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyEmailPools.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyEmailPools.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyEmailPools.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyEmailPools.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportNotifyEmailPoolSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.notify_email_pool", "pool_id"), psql.Quote("publicreport.notify_email_pool", "email_address")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportNotifyEmailPoolSlice) copyMatchingRows(from ...*PublicreportNotifyEmailPool) {
for i, old := range o {
for _, new := range from {
if new.PoolID != old.PoolID {
continue
}
if new.EmailAddress != old.EmailAddress {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyEmailPoolSlice) 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 PublicreportNotifyEmailPools.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 *PublicreportNotifyEmailPool:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyEmailPool:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyEmailPoolSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyEmailPool or a slice of PublicreportNotifyEmailPool
// then run the AfterUpdateHooks on the slice
_, err = PublicreportNotifyEmailPools.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyEmailPoolSlice) 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 PublicreportNotifyEmailPools.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 *PublicreportNotifyEmailPool:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyEmailPool:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyEmailPoolSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyEmailPool or a slice of PublicreportNotifyEmailPool
// then run the AfterDeleteHooks on the slice
_, err = PublicreportNotifyEmailPools.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportNotifyEmailPoolSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportNotifyEmailPoolSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyEmailPools.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportNotifyEmailPoolSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyEmailPools.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportNotifyEmailPoolSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportNotifyEmailPools.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// EmailAddressEmailContact starts a query for related objects on comms.email_contact
func (o *PublicreportNotifyEmailPool) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
return CommsEmailContacts.Query(append(mods,
sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(o.EmailAddress))),
)...)
}
func (os PublicreportNotifyEmailPoolSlice) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
pkEmailAddress := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkEmailAddress = append(pkEmailAddress, o.EmailAddress)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkEmailAddress), "text[]")),
))
return CommsEmailContacts.Query(append(mods,
sm.Where(psql.Group(CommsEmailContacts.Columns.Address).OP("IN", PKArgExpr)),
)...)
}
// Pool starts a query for related objects on publicreport.pool
func (o *PublicreportNotifyEmailPool) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
return PublicreportPools.Query(append(mods,
sm.Where(PublicreportPools.Columns.ID.EQ(psql.Arg(o.PoolID))),
)...)
}
func (os PublicreportNotifyEmailPoolSlice) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
pkPoolID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkPoolID = append(pkPoolID, o.PoolID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkPoolID), "integer[]")),
))
return PublicreportPools.Query(append(mods,
sm.Where(psql.Group(PublicreportPools.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailPool, error) {
setter := &PublicreportNotifyEmailPoolSetter{
EmailAddress: omit.From(commsEmailContact1.Address),
}
err := publicreportNotifyEmailPool0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyEmailPoolEmailAddressEmailContact0: %w", err)
}
return publicreportNotifyEmailPool0, nil
}
func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) InsertEmailAddressEmailContact(ctx context.Context, exec bob.Executor, related *CommsEmailContactSetter) error {
var err error
commsEmailContact1, err := CommsEmailContacts.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailPool0, commsEmailContact1)
if err != nil {
return err
}
publicreportNotifyEmailPool0.R.EmailAddressEmailContact = commsEmailContact1
commsEmailContact1.R.EmailAddressNotifyEmailPools = append(commsEmailContact1.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPool0)
return nil
}
func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) AttachEmailAddressEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
var err error
_, err = attachPublicreportNotifyEmailPoolEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailPool0, commsEmailContact1)
if err != nil {
return err
}
publicreportNotifyEmailPool0.R.EmailAddressEmailContact = commsEmailContact1
commsEmailContact1.R.EmailAddressNotifyEmailPools = append(commsEmailContact1.R.EmailAddressNotifyEmailPools, publicreportNotifyEmailPool0)
return nil
}
func attachPublicreportNotifyEmailPoolPool0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool, publicreportPool1 *PublicreportPool) (*PublicreportNotifyEmailPool, error) {
setter := &PublicreportNotifyEmailPoolSetter{
PoolID: omit.From(publicreportPool1.ID),
}
err := publicreportNotifyEmailPool0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyEmailPoolPool0: %w", err)
}
return publicreportNotifyEmailPool0, nil
}
func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) InsertPool(ctx context.Context, exec bob.Executor, related *PublicreportPoolSetter) error {
var err error
publicreportPool1, err := PublicreportPools.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyEmailPoolPool0(ctx, exec, 1, publicreportNotifyEmailPool0, publicreportPool1)
if err != nil {
return err
}
publicreportNotifyEmailPool0.R.Pool = publicreportPool1
publicreportPool1.R.NotifyEmailPools = append(publicreportPool1.R.NotifyEmailPools, publicreportNotifyEmailPool0)
return nil
}
func (publicreportNotifyEmailPool0 *PublicreportNotifyEmailPool) AttachPool(ctx context.Context, exec bob.Executor, publicreportPool1 *PublicreportPool) error {
var err error
_, err = attachPublicreportNotifyEmailPoolPool0(ctx, exec, 1, publicreportNotifyEmailPool0, publicreportPool1)
if err != nil {
return err
}
publicreportNotifyEmailPool0.R.Pool = publicreportPool1
publicreportPool1.R.NotifyEmailPools = append(publicreportPool1.R.NotifyEmailPools, publicreportNotifyEmailPool0)
return nil
}
type publicreportNotifyEmailPoolWhere[Q psql.Filterable] struct {
Created psql.WhereMod[Q, time.Time]
Deleted psql.WhereNullMod[Q, time.Time]
PoolID psql.WhereMod[Q, int32]
EmailAddress psql.WhereMod[Q, string]
}
func (publicreportNotifyEmailPoolWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailPoolWhere[Q] {
return buildPublicreportNotifyEmailPoolWhere[Q](buildPublicreportNotifyEmailPoolColumns(alias))
}
func buildPublicreportNotifyEmailPoolWhere[Q psql.Filterable](cols publicreportNotifyEmailPoolColumns) publicreportNotifyEmailPoolWhere[Q] {
return publicreportNotifyEmailPoolWhere[Q]{
Created: psql.Where[Q, time.Time](cols.Created),
Deleted: psql.WhereNull[Q, time.Time](cols.Deleted),
PoolID: psql.Where[Q, int32](cols.PoolID),
EmailAddress: psql.Where[Q, string](cols.EmailAddress),
}
}
func (o *PublicreportNotifyEmailPool) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "EmailAddressEmailContact":
rel, ok := retrieved.(*CommsEmailContact)
if !ok {
return fmt.Errorf("publicreportNotifyEmailPool cannot load %T as %q", retrieved, name)
}
o.R.EmailAddressEmailContact = rel
if rel != nil {
rel.R.EmailAddressNotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}
}
return nil
case "Pool":
rel, ok := retrieved.(*PublicreportPool)
if !ok {
return fmt.Errorf("publicreportNotifyEmailPool cannot load %T as %q", retrieved, name)
}
o.R.Pool = rel
if rel != nil {
rel.R.NotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}
}
return nil
default:
return fmt.Errorf("publicreportNotifyEmailPool has no relationship %q", name)
}
}
type publicreportNotifyEmailPoolPreloader struct {
EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
Pool func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportNotifyEmailPoolPreloader() publicreportNotifyEmailPoolPreloader {
return publicreportNotifyEmailPoolPreloader{
EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
Name: "EmailAddressEmailContact",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyEmailPools,
To: CommsEmailContacts,
FromColumns: []string{"email_address"},
ToColumns: []string{"address"},
},
},
}, CommsEmailContacts.Columns.Names(), opts...)
},
Pool: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportPool, PublicreportPoolSlice](psql.PreloadRel{
Name: "Pool",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyEmailPools,
To: PublicreportPools,
FromColumns: []string{"pool_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportPools.Columns.Names(), opts...)
},
}
}
type publicreportNotifyEmailPoolThenLoader[Q orm.Loadable] struct {
EmailAddressEmailContact func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Pool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportNotifyEmailPoolThenLoader[Q orm.Loadable]() publicreportNotifyEmailPoolThenLoader[Q] {
type EmailAddressEmailContactLoadInterface interface {
LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PoolLoadInterface interface {
LoadPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportNotifyEmailPoolThenLoader[Q]{
EmailAddressEmailContact: thenLoadBuilder[Q](
"EmailAddressEmailContact",
func(ctx context.Context, exec bob.Executor, retrieved EmailAddressEmailContactLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadEmailAddressEmailContact(ctx, exec, mods...)
},
),
Pool: thenLoadBuilder[Q](
"Pool",
func(ctx context.Context, exec bob.Executor, retrieved PoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPool(ctx, exec, mods...)
},
),
}
}
// LoadEmailAddressEmailContact loads the publicreportNotifyEmailPool's EmailAddressEmailContact into the .R struct
func (o *PublicreportNotifyEmailPool) LoadEmailAddressEmailContact(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.EmailAddressEmailContact = nil
related, err := o.EmailAddressEmailContact(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.EmailAddressNotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}
o.R.EmailAddressEmailContact = related
return nil
}
// LoadEmailAddressEmailContact loads the publicreportNotifyEmailPool's EmailAddressEmailContact into the .R struct
func (os PublicreportNotifyEmailPoolSlice) LoadEmailAddressEmailContact(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
commsEmailContacts, err := os.EmailAddressEmailContact(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range commsEmailContacts {
if !(o.EmailAddress == rel.Address) {
continue
}
rel.R.EmailAddressNotifyEmailPools = append(rel.R.EmailAddressNotifyEmailPools, o)
o.R.EmailAddressEmailContact = rel
break
}
}
return nil
}
// LoadPool loads the publicreportNotifyEmailPool's Pool into the .R struct
func (o *PublicreportNotifyEmailPool) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Pool = nil
related, err := o.Pool(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.NotifyEmailPools = PublicreportNotifyEmailPoolSlice{o}
o.R.Pool = related
return nil
}
// LoadPool loads the publicreportNotifyEmailPool's Pool into the .R struct
func (os PublicreportNotifyEmailPoolSlice) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportPools, err := os.Pool(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportPools {
if !(o.PoolID == rel.ID) {
continue
}
rel.R.NotifyEmailPools = append(rel.R.NotifyEmailPools, o)
o.R.Pool = rel
break
}
}
return nil
}

View file

@ -0,0 +1,796 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/null"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
)
// PublicreportNotifyEmailWater is an object representing the database table.
type PublicreportNotifyEmailWater struct {
Created time.Time `db:"created" `
Deleted null.Val[time.Time] `db:"deleted" `
WaterID int32 `db:"water_id,pk" `
EmailAddress string `db:"email_address,pk" `
R publicreportNotifyEmailWaterR `db:"-" `
}
// PublicreportNotifyEmailWaterSlice is an alias for a slice of pointers to PublicreportNotifyEmailWater.
// This should almost always be used instead of []*PublicreportNotifyEmailWater.
type PublicreportNotifyEmailWaterSlice []*PublicreportNotifyEmailWater
// PublicreportNotifyEmailWaters contains methods to work with the notify_email_water table
var PublicreportNotifyEmailWaters = psql.NewTablex[*PublicreportNotifyEmailWater, PublicreportNotifyEmailWaterSlice, *PublicreportNotifyEmailWaterSetter]("publicreport", "notify_email_water", buildPublicreportNotifyEmailWaterColumns("publicreport.notify_email_water"))
// PublicreportNotifyEmailWatersQuery is a query on the notify_email_water table
type PublicreportNotifyEmailWatersQuery = *psql.ViewQuery[*PublicreportNotifyEmailWater, PublicreportNotifyEmailWaterSlice]
// publicreportNotifyEmailWaterR is where relationships are stored.
type publicreportNotifyEmailWaterR struct {
EmailAddressEmailContact *CommsEmailContact // publicreport.notify_email_water.notify_email_pool_email_address_fkey
Water *PublicreportWater // publicreport.notify_email_water.notify_email_pool_pool_id_fkey
}
func buildPublicreportNotifyEmailWaterColumns(alias string) publicreportNotifyEmailWaterColumns {
return publicreportNotifyEmailWaterColumns{
ColumnsExpr: expr.NewColumnsExpr(
"created", "deleted", "water_id", "email_address",
).WithParent("publicreport.notify_email_water"),
tableAlias: alias,
Created: psql.Quote(alias, "created"),
Deleted: psql.Quote(alias, "deleted"),
WaterID: psql.Quote(alias, "water_id"),
EmailAddress: psql.Quote(alias, "email_address"),
}
}
type publicreportNotifyEmailWaterColumns struct {
expr.ColumnsExpr
tableAlias string
Created psql.Expression
Deleted psql.Expression
WaterID psql.Expression
EmailAddress psql.Expression
}
func (c publicreportNotifyEmailWaterColumns) Alias() string {
return c.tableAlias
}
func (publicreportNotifyEmailWaterColumns) AliasedAs(alias string) publicreportNotifyEmailWaterColumns {
return buildPublicreportNotifyEmailWaterColumns(alias)
}
// PublicreportNotifyEmailWaterSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyEmailWaterSetter struct {
Created omit.Val[time.Time] `db:"created" `
Deleted omitnull.Val[time.Time] `db:"deleted" `
WaterID omit.Val[int32] `db:"water_id,pk" `
EmailAddress omit.Val[string] `db:"email_address,pk" `
}
func (s PublicreportNotifyEmailWaterSetter) SetColumns() []string {
vals := make([]string, 0, 4)
if s.Created.IsValue() {
vals = append(vals, "created")
}
if !s.Deleted.IsUnset() {
vals = append(vals, "deleted")
}
if s.WaterID.IsValue() {
vals = append(vals, "water_id")
}
if s.EmailAddress.IsValue() {
vals = append(vals, "email_address")
}
return vals
}
func (s PublicreportNotifyEmailWaterSetter) Overwrite(t *PublicreportNotifyEmailWater) {
if s.Created.IsValue() {
t.Created = s.Created.MustGet()
}
if !s.Deleted.IsUnset() {
t.Deleted = s.Deleted.MustGetNull()
}
if s.WaterID.IsValue() {
t.WaterID = s.WaterID.MustGet()
}
if s.EmailAddress.IsValue() {
t.EmailAddress = s.EmailAddress.MustGet()
}
}
func (s *PublicreportNotifyEmailWaterSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportNotifyEmailWaters.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 4)
if s.Created.IsValue() {
vals[0] = psql.Arg(s.Created.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if !s.Deleted.IsUnset() {
vals[1] = psql.Arg(s.Deleted.MustGetNull())
} else {
vals[1] = psql.Raw("DEFAULT")
}
if s.WaterID.IsValue() {
vals[2] = psql.Arg(s.WaterID.MustGet())
} else {
vals[2] = psql.Raw("DEFAULT")
}
if s.EmailAddress.IsValue() {
vals[3] = psql.Arg(s.EmailAddress.MustGet())
} else {
vals[3] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportNotifyEmailWaterSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportNotifyEmailWaterSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 4)
if s.Created.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "created")...),
psql.Arg(s.Created),
}})
}
if !s.Deleted.IsUnset() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "deleted")...),
psql.Arg(s.Deleted),
}})
}
if s.WaterID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "water_id")...),
psql.Arg(s.WaterID),
}})
}
if s.EmailAddress.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "email_address")...),
psql.Arg(s.EmailAddress),
}})
}
return exprs
}
// FindPublicreportNotifyEmailWater retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyEmailWater(ctx context.Context, exec bob.Executor, WaterIDPK int32, EmailAddressPK string, cols ...string) (*PublicreportNotifyEmailWater, error) {
if len(cols) == 0 {
return PublicreportNotifyEmailWaters.Query(
sm.Where(PublicreportNotifyEmailWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyEmailWaters.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
).One(ctx, exec)
}
return PublicreportNotifyEmailWaters.Query(
sm.Where(PublicreportNotifyEmailWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyEmailWaters.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
sm.Columns(PublicreportNotifyEmailWaters.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportNotifyEmailWaterExists checks the presence of a single record by primary key
func PublicreportNotifyEmailWaterExists(ctx context.Context, exec bob.Executor, WaterIDPK int32, EmailAddressPK string) (bool, error) {
return PublicreportNotifyEmailWaters.Query(
sm.Where(PublicreportNotifyEmailWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyEmailWaters.Columns.EmailAddress.EQ(psql.Arg(EmailAddressPK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportNotifyEmailWater is retrieved from the database
func (o *PublicreportNotifyEmailWater) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyEmailWaters.AfterSelectHooks.RunHooks(ctx, exec, PublicreportNotifyEmailWaterSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyEmailWaters.AfterInsertHooks.RunHooks(ctx, exec, PublicreportNotifyEmailWaterSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyEmailWaters.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportNotifyEmailWaterSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyEmailWaters.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportNotifyEmailWaterSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportNotifyEmailWater
func (o *PublicreportNotifyEmailWater) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.WaterID,
o.EmailAddress,
)
}
func (o *PublicreportNotifyEmailWater) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.notify_email_water", "water_id"), psql.Quote("publicreport.notify_email_water", "email_address")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportNotifyEmailWater
func (o *PublicreportNotifyEmailWater) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyEmailWaterSetter) error {
v, err := PublicreportNotifyEmailWaters.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 PublicreportNotifyEmailWater record with an executor
func (o *PublicreportNotifyEmailWater) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportNotifyEmailWaters.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportNotifyEmailWater using the executor
func (o *PublicreportNotifyEmailWater) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportNotifyEmailWaters.Query(
sm.Where(PublicreportNotifyEmailWaters.Columns.WaterID.EQ(psql.Arg(o.WaterID))),
sm.Where(PublicreportNotifyEmailWaters.Columns.EmailAddress.EQ(psql.Arg(o.EmailAddress))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportNotifyEmailWaterSlice is retrieved from the database
func (o PublicreportNotifyEmailWaterSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyEmailWaters.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyEmailWaters.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyEmailWaters.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyEmailWaters.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportNotifyEmailWaterSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.notify_email_water", "water_id"), psql.Quote("publicreport.notify_email_water", "email_address")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportNotifyEmailWaterSlice) copyMatchingRows(from ...*PublicreportNotifyEmailWater) {
for i, old := range o {
for _, new := range from {
if new.WaterID != old.WaterID {
continue
}
if new.EmailAddress != old.EmailAddress {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyEmailWaterSlice) 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 PublicreportNotifyEmailWaters.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 *PublicreportNotifyEmailWater:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyEmailWater:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyEmailWaterSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyEmailWater or a slice of PublicreportNotifyEmailWater
// then run the AfterUpdateHooks on the slice
_, err = PublicreportNotifyEmailWaters.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyEmailWaterSlice) 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 PublicreportNotifyEmailWaters.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 *PublicreportNotifyEmailWater:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyEmailWater:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyEmailWaterSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyEmailWater or a slice of PublicreportNotifyEmailWater
// then run the AfterDeleteHooks on the slice
_, err = PublicreportNotifyEmailWaters.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportNotifyEmailWaterSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportNotifyEmailWaterSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyEmailWaters.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportNotifyEmailWaterSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyEmailWaters.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportNotifyEmailWaterSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportNotifyEmailWaters.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// EmailAddressEmailContact starts a query for related objects on comms.email_contact
func (o *PublicreportNotifyEmailWater) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
return CommsEmailContacts.Query(append(mods,
sm.Where(CommsEmailContacts.Columns.Address.EQ(psql.Arg(o.EmailAddress))),
)...)
}
func (os PublicreportNotifyEmailWaterSlice) EmailAddressEmailContact(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery {
pkEmailAddress := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkEmailAddress = append(pkEmailAddress, o.EmailAddress)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkEmailAddress), "text[]")),
))
return CommsEmailContacts.Query(append(mods,
sm.Where(psql.Group(CommsEmailContacts.Columns.Address).OP("IN", PKArgExpr)),
)...)
}
// Water starts a query for related objects on publicreport.water
func (o *PublicreportNotifyEmailWater) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.Where(PublicreportWaters.Columns.ID.EQ(psql.Arg(o.WaterID))),
)...)
}
func (os PublicreportNotifyEmailWaterSlice) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
pkWaterID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkWaterID = append(pkWaterID, o.WaterID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkWaterID), "integer[]")),
))
return PublicreportWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportWaters.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportNotifyEmailWaterEmailAddressEmailContact0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater, commsEmailContact1 *CommsEmailContact) (*PublicreportNotifyEmailWater, error) {
setter := &PublicreportNotifyEmailWaterSetter{
EmailAddress: omit.From(commsEmailContact1.Address),
}
err := publicreportNotifyEmailWater0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyEmailWaterEmailAddressEmailContact0: %w", err)
}
return publicreportNotifyEmailWater0, nil
}
func (publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater) InsertEmailAddressEmailContact(ctx context.Context, exec bob.Executor, related *CommsEmailContactSetter) error {
var err error
commsEmailContact1, err := CommsEmailContacts.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyEmailWaterEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailWater0, commsEmailContact1)
if err != nil {
return err
}
publicreportNotifyEmailWater0.R.EmailAddressEmailContact = commsEmailContact1
commsEmailContact1.R.EmailAddressNotifyEmailWaters = append(commsEmailContact1.R.EmailAddressNotifyEmailWaters, publicreportNotifyEmailWater0)
return nil
}
func (publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater) AttachEmailAddressEmailContact(ctx context.Context, exec bob.Executor, commsEmailContact1 *CommsEmailContact) error {
var err error
_, err = attachPublicreportNotifyEmailWaterEmailAddressEmailContact0(ctx, exec, 1, publicreportNotifyEmailWater0, commsEmailContact1)
if err != nil {
return err
}
publicreportNotifyEmailWater0.R.EmailAddressEmailContact = commsEmailContact1
commsEmailContact1.R.EmailAddressNotifyEmailWaters = append(commsEmailContact1.R.EmailAddressNotifyEmailWaters, publicreportNotifyEmailWater0)
return nil
}
func attachPublicreportNotifyEmailWaterWater0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater, publicreportWater1 *PublicreportWater) (*PublicreportNotifyEmailWater, error) {
setter := &PublicreportNotifyEmailWaterSetter{
WaterID: omit.From(publicreportWater1.ID),
}
err := publicreportNotifyEmailWater0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyEmailWaterWater0: %w", err)
}
return publicreportNotifyEmailWater0, nil
}
func (publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater) InsertWater(ctx context.Context, exec bob.Executor, related *PublicreportWaterSetter) error {
var err error
publicreportWater1, err := PublicreportWaters.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyEmailWaterWater0(ctx, exec, 1, publicreportNotifyEmailWater0, publicreportWater1)
if err != nil {
return err
}
publicreportNotifyEmailWater0.R.Water = publicreportWater1
publicreportWater1.R.NotifyEmailWaters = append(publicreportWater1.R.NotifyEmailWaters, publicreportNotifyEmailWater0)
return nil
}
func (publicreportNotifyEmailWater0 *PublicreportNotifyEmailWater) AttachWater(ctx context.Context, exec bob.Executor, publicreportWater1 *PublicreportWater) error {
var err error
_, err = attachPublicreportNotifyEmailWaterWater0(ctx, exec, 1, publicreportNotifyEmailWater0, publicreportWater1)
if err != nil {
return err
}
publicreportNotifyEmailWater0.R.Water = publicreportWater1
publicreportWater1.R.NotifyEmailWaters = append(publicreportWater1.R.NotifyEmailWaters, publicreportNotifyEmailWater0)
return nil
}
type publicreportNotifyEmailWaterWhere[Q psql.Filterable] struct {
Created psql.WhereMod[Q, time.Time]
Deleted psql.WhereNullMod[Q, time.Time]
WaterID psql.WhereMod[Q, int32]
EmailAddress psql.WhereMod[Q, string]
}
func (publicreportNotifyEmailWaterWhere[Q]) AliasedAs(alias string) publicreportNotifyEmailWaterWhere[Q] {
return buildPublicreportNotifyEmailWaterWhere[Q](buildPublicreportNotifyEmailWaterColumns(alias))
}
func buildPublicreportNotifyEmailWaterWhere[Q psql.Filterable](cols publicreportNotifyEmailWaterColumns) publicreportNotifyEmailWaterWhere[Q] {
return publicreportNotifyEmailWaterWhere[Q]{
Created: psql.Where[Q, time.Time](cols.Created),
Deleted: psql.WhereNull[Q, time.Time](cols.Deleted),
WaterID: psql.Where[Q, int32](cols.WaterID),
EmailAddress: psql.Where[Q, string](cols.EmailAddress),
}
}
func (o *PublicreportNotifyEmailWater) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "EmailAddressEmailContact":
rel, ok := retrieved.(*CommsEmailContact)
if !ok {
return fmt.Errorf("publicreportNotifyEmailWater cannot load %T as %q", retrieved, name)
}
o.R.EmailAddressEmailContact = rel
if rel != nil {
rel.R.EmailAddressNotifyEmailWaters = PublicreportNotifyEmailWaterSlice{o}
}
return nil
case "Water":
rel, ok := retrieved.(*PublicreportWater)
if !ok {
return fmt.Errorf("publicreportNotifyEmailWater cannot load %T as %q", retrieved, name)
}
o.R.Water = rel
if rel != nil {
rel.R.NotifyEmailWaters = PublicreportNotifyEmailWaterSlice{o}
}
return nil
default:
return fmt.Errorf("publicreportNotifyEmailWater has no relationship %q", name)
}
}
type publicreportNotifyEmailWaterPreloader struct {
EmailAddressEmailContact func(...psql.PreloadOption) psql.Preloader
Water func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportNotifyEmailWaterPreloader() publicreportNotifyEmailWaterPreloader {
return publicreportNotifyEmailWaterPreloader{
EmailAddressEmailContact: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*CommsEmailContact, CommsEmailContactSlice](psql.PreloadRel{
Name: "EmailAddressEmailContact",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyEmailWaters,
To: CommsEmailContacts,
FromColumns: []string{"email_address"},
ToColumns: []string{"address"},
},
},
}, CommsEmailContacts.Columns.Names(), opts...)
},
Water: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportWater, PublicreportWaterSlice](psql.PreloadRel{
Name: "Water",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyEmailWaters,
To: PublicreportWaters,
FromColumns: []string{"water_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportWaters.Columns.Names(), opts...)
},
}
}
type publicreportNotifyEmailWaterThenLoader[Q orm.Loadable] struct {
EmailAddressEmailContact func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Water func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportNotifyEmailWaterThenLoader[Q orm.Loadable]() publicreportNotifyEmailWaterThenLoader[Q] {
type EmailAddressEmailContactLoadInterface interface {
LoadEmailAddressEmailContact(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type WaterLoadInterface interface {
LoadWater(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportNotifyEmailWaterThenLoader[Q]{
EmailAddressEmailContact: thenLoadBuilder[Q](
"EmailAddressEmailContact",
func(ctx context.Context, exec bob.Executor, retrieved EmailAddressEmailContactLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadEmailAddressEmailContact(ctx, exec, mods...)
},
),
Water: thenLoadBuilder[Q](
"Water",
func(ctx context.Context, exec bob.Executor, retrieved WaterLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWater(ctx, exec, mods...)
},
),
}
}
// LoadEmailAddressEmailContact loads the publicreportNotifyEmailWater's EmailAddressEmailContact into the .R struct
func (o *PublicreportNotifyEmailWater) LoadEmailAddressEmailContact(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.EmailAddressEmailContact = nil
related, err := o.EmailAddressEmailContact(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.EmailAddressNotifyEmailWaters = PublicreportNotifyEmailWaterSlice{o}
o.R.EmailAddressEmailContact = related
return nil
}
// LoadEmailAddressEmailContact loads the publicreportNotifyEmailWater's EmailAddressEmailContact into the .R struct
func (os PublicreportNotifyEmailWaterSlice) LoadEmailAddressEmailContact(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
commsEmailContacts, err := os.EmailAddressEmailContact(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range commsEmailContacts {
if !(o.EmailAddress == rel.Address) {
continue
}
rel.R.EmailAddressNotifyEmailWaters = append(rel.R.EmailAddressNotifyEmailWaters, o)
o.R.EmailAddressEmailContact = rel
break
}
}
return nil
}
// LoadWater loads the publicreportNotifyEmailWater's Water into the .R struct
func (o *PublicreportNotifyEmailWater) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Water = nil
related, err := o.Water(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.NotifyEmailWaters = PublicreportNotifyEmailWaterSlice{o}
o.R.Water = related
return nil
}
// LoadWater loads the publicreportNotifyEmailWater's Water into the .R struct
func (os PublicreportNotifyEmailWaterSlice) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportWaters, err := os.Water(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportWaters {
if !(o.WaterID == rel.ID) {
continue
}
rel.R.NotifyEmailWaters = append(rel.R.NotifyEmailWaters, o)
o.R.Water = rel
break
}
}
return nil
}

View file

@ -1,796 +0,0 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/null"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
)
// PublicreportNotifyPhonePool is an object representing the database table.
type PublicreportNotifyPhonePool struct {
Created time.Time `db:"created" `
Deleted null.Val[time.Time] `db:"deleted" `
PhoneE164 string `db:"phone_e164,pk" `
PoolID int32 `db:"pool_id,pk" `
R publicreportNotifyPhonePoolR `db:"-" `
}
// PublicreportNotifyPhonePoolSlice is an alias for a slice of pointers to PublicreportNotifyPhonePool.
// This should almost always be used instead of []*PublicreportNotifyPhonePool.
type PublicreportNotifyPhonePoolSlice []*PublicreportNotifyPhonePool
// PublicreportNotifyPhonePools contains methods to work with the notify_phone_pool table
var PublicreportNotifyPhonePools = psql.NewTablex[*PublicreportNotifyPhonePool, PublicreportNotifyPhonePoolSlice, *PublicreportNotifyPhonePoolSetter]("publicreport", "notify_phone_pool", buildPublicreportNotifyPhonePoolColumns("publicreport.notify_phone_pool"))
// PublicreportNotifyPhonePoolsQuery is a query on the notify_phone_pool table
type PublicreportNotifyPhonePoolsQuery = *psql.ViewQuery[*PublicreportNotifyPhonePool, PublicreportNotifyPhonePoolSlice]
// publicreportNotifyPhonePoolR is where relationships are stored.
type publicreportNotifyPhonePoolR struct {
PhoneE164Phone *CommsPhone // publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey
Pool *PublicreportPool // publicreport.notify_phone_pool.notify_phone_pool_pool_id_fkey
}
func buildPublicreportNotifyPhonePoolColumns(alias string) publicreportNotifyPhonePoolColumns {
return publicreportNotifyPhonePoolColumns{
ColumnsExpr: expr.NewColumnsExpr(
"created", "deleted", "phone_e164", "pool_id",
).WithParent("publicreport.notify_phone_pool"),
tableAlias: alias,
Created: psql.Quote(alias, "created"),
Deleted: psql.Quote(alias, "deleted"),
PhoneE164: psql.Quote(alias, "phone_e164"),
PoolID: psql.Quote(alias, "pool_id"),
}
}
type publicreportNotifyPhonePoolColumns struct {
expr.ColumnsExpr
tableAlias string
Created psql.Expression
Deleted psql.Expression
PhoneE164 psql.Expression
PoolID psql.Expression
}
func (c publicreportNotifyPhonePoolColumns) Alias() string {
return c.tableAlias
}
func (publicreportNotifyPhonePoolColumns) AliasedAs(alias string) publicreportNotifyPhonePoolColumns {
return buildPublicreportNotifyPhonePoolColumns(alias)
}
// PublicreportNotifyPhonePoolSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyPhonePoolSetter struct {
Created omit.Val[time.Time] `db:"created" `
Deleted omitnull.Val[time.Time] `db:"deleted" `
PhoneE164 omit.Val[string] `db:"phone_e164,pk" `
PoolID omit.Val[int32] `db:"pool_id,pk" `
}
func (s PublicreportNotifyPhonePoolSetter) SetColumns() []string {
vals := make([]string, 0, 4)
if s.Created.IsValue() {
vals = append(vals, "created")
}
if !s.Deleted.IsUnset() {
vals = append(vals, "deleted")
}
if s.PhoneE164.IsValue() {
vals = append(vals, "phone_e164")
}
if s.PoolID.IsValue() {
vals = append(vals, "pool_id")
}
return vals
}
func (s PublicreportNotifyPhonePoolSetter) Overwrite(t *PublicreportNotifyPhonePool) {
if s.Created.IsValue() {
t.Created = s.Created.MustGet()
}
if !s.Deleted.IsUnset() {
t.Deleted = s.Deleted.MustGetNull()
}
if s.PhoneE164.IsValue() {
t.PhoneE164 = s.PhoneE164.MustGet()
}
if s.PoolID.IsValue() {
t.PoolID = s.PoolID.MustGet()
}
}
func (s *PublicreportNotifyPhonePoolSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportNotifyPhonePools.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 4)
if s.Created.IsValue() {
vals[0] = psql.Arg(s.Created.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if !s.Deleted.IsUnset() {
vals[1] = psql.Arg(s.Deleted.MustGetNull())
} else {
vals[1] = psql.Raw("DEFAULT")
}
if s.PhoneE164.IsValue() {
vals[2] = psql.Arg(s.PhoneE164.MustGet())
} else {
vals[2] = psql.Raw("DEFAULT")
}
if s.PoolID.IsValue() {
vals[3] = psql.Arg(s.PoolID.MustGet())
} else {
vals[3] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportNotifyPhonePoolSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportNotifyPhonePoolSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 4)
if s.Created.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "created")...),
psql.Arg(s.Created),
}})
}
if !s.Deleted.IsUnset() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "deleted")...),
psql.Arg(s.Deleted),
}})
}
if s.PhoneE164.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "phone_e164")...),
psql.Arg(s.PhoneE164),
}})
}
if s.PoolID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "pool_id")...),
psql.Arg(s.PoolID),
}})
}
return exprs
}
// FindPublicreportNotifyPhonePool retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyPhonePool(ctx context.Context, exec bob.Executor, PoolIDPK int32, PhoneE164PK string, cols ...string) (*PublicreportNotifyPhonePool, error) {
if len(cols) == 0 {
return PublicreportNotifyPhonePools.Query(
sm.Where(PublicreportNotifyPhonePools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
).One(ctx, exec)
}
return PublicreportNotifyPhonePools.Query(
sm.Where(PublicreportNotifyPhonePools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
sm.Columns(PublicreportNotifyPhonePools.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportNotifyPhonePoolExists checks the presence of a single record by primary key
func PublicreportNotifyPhonePoolExists(ctx context.Context, exec bob.Executor, PoolIDPK int32, PhoneE164PK string) (bool, error) {
return PublicreportNotifyPhonePools.Query(
sm.Where(PublicreportNotifyPhonePools.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportNotifyPhonePool is retrieved from the database
func (o *PublicreportNotifyPhonePool) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyPhonePools.AfterSelectHooks.RunHooks(ctx, exec, PublicreportNotifyPhonePoolSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyPhonePools.AfterInsertHooks.RunHooks(ctx, exec, PublicreportNotifyPhonePoolSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyPhonePools.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportNotifyPhonePoolSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyPhonePools.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportNotifyPhonePoolSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportNotifyPhonePool
func (o *PublicreportNotifyPhonePool) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.PoolID,
o.PhoneE164,
)
}
func (o *PublicreportNotifyPhonePool) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.notify_phone_pool", "pool_id"), psql.Quote("publicreport.notify_phone_pool", "phone_e164")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportNotifyPhonePool
func (o *PublicreportNotifyPhonePool) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyPhonePoolSetter) error {
v, err := PublicreportNotifyPhonePools.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 PublicreportNotifyPhonePool record with an executor
func (o *PublicreportNotifyPhonePool) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportNotifyPhonePools.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportNotifyPhonePool using the executor
func (o *PublicreportNotifyPhonePool) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportNotifyPhonePools.Query(
sm.Where(PublicreportNotifyPhonePools.Columns.PoolID.EQ(psql.Arg(o.PoolID))),
sm.Where(PublicreportNotifyPhonePools.Columns.PhoneE164.EQ(psql.Arg(o.PhoneE164))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportNotifyPhonePoolSlice is retrieved from the database
func (o PublicreportNotifyPhonePoolSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyPhonePools.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyPhonePools.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyPhonePools.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyPhonePools.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportNotifyPhonePoolSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.notify_phone_pool", "pool_id"), psql.Quote("publicreport.notify_phone_pool", "phone_e164")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportNotifyPhonePoolSlice) copyMatchingRows(from ...*PublicreportNotifyPhonePool) {
for i, old := range o {
for _, new := range from {
if new.PoolID != old.PoolID {
continue
}
if new.PhoneE164 != old.PhoneE164 {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyPhonePoolSlice) 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 PublicreportNotifyPhonePools.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 *PublicreportNotifyPhonePool:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyPhonePool:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyPhonePoolSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyPhonePool or a slice of PublicreportNotifyPhonePool
// then run the AfterUpdateHooks on the slice
_, err = PublicreportNotifyPhonePools.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyPhonePoolSlice) 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 PublicreportNotifyPhonePools.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 *PublicreportNotifyPhonePool:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyPhonePool:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyPhonePoolSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyPhonePool or a slice of PublicreportNotifyPhonePool
// then run the AfterDeleteHooks on the slice
_, err = PublicreportNotifyPhonePools.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportNotifyPhonePoolSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportNotifyPhonePoolSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyPhonePools.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportNotifyPhonePoolSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyPhonePools.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportNotifyPhonePoolSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportNotifyPhonePools.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// PhoneE164Phone starts a query for related objects on comms.phone
func (o *PublicreportNotifyPhonePool) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
return CommsPhones.Query(append(mods,
sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneE164))),
)...)
}
func (os PublicreportNotifyPhonePoolSlice) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
pkPhoneE164 := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkPhoneE164 = append(pkPhoneE164, o.PhoneE164)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkPhoneE164), "text[]")),
))
return CommsPhones.Query(append(mods,
sm.Where(psql.Group(CommsPhones.Columns.E164).OP("IN", PKArgExpr)),
)...)
}
// Pool starts a query for related objects on publicreport.pool
func (o *PublicreportNotifyPhonePool) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
return PublicreportPools.Query(append(mods,
sm.Where(PublicreportPools.Columns.ID.EQ(psql.Arg(o.PoolID))),
)...)
}
func (os PublicreportNotifyPhonePoolSlice) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
pkPoolID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkPoolID = append(pkPoolID, o.PoolID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkPoolID), "integer[]")),
))
return PublicreportPools.Query(append(mods,
sm.Where(psql.Group(PublicreportPools.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportNotifyPhonePoolPhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool, commsPhone1 *CommsPhone) (*PublicreportNotifyPhonePool, error) {
setter := &PublicreportNotifyPhonePoolSetter{
PhoneE164: omit.From(commsPhone1.E164),
}
err := publicreportNotifyPhonePool0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyPhonePoolPhoneE164Phone0: %w", err)
}
return publicreportNotifyPhonePool0, nil
}
func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) InsertPhoneE164Phone(ctx context.Context, exec bob.Executor, related *CommsPhoneSetter) error {
var err error
commsPhone1, err := CommsPhones.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyPhonePoolPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhonePool0, commsPhone1)
if err != nil {
return err
}
publicreportNotifyPhonePool0.R.PhoneE164Phone = commsPhone1
commsPhone1.R.PhoneE164NotifyPhonePools = append(commsPhone1.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePool0)
return nil
}
func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) AttachPhoneE164Phone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
var err error
_, err = attachPublicreportNotifyPhonePoolPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhonePool0, commsPhone1)
if err != nil {
return err
}
publicreportNotifyPhonePool0.R.PhoneE164Phone = commsPhone1
commsPhone1.R.PhoneE164NotifyPhonePools = append(commsPhone1.R.PhoneE164NotifyPhonePools, publicreportNotifyPhonePool0)
return nil
}
func attachPublicreportNotifyPhonePoolPool0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool, publicreportPool1 *PublicreportPool) (*PublicreportNotifyPhonePool, error) {
setter := &PublicreportNotifyPhonePoolSetter{
PoolID: omit.From(publicreportPool1.ID),
}
err := publicreportNotifyPhonePool0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyPhonePoolPool0: %w", err)
}
return publicreportNotifyPhonePool0, nil
}
func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) InsertPool(ctx context.Context, exec bob.Executor, related *PublicreportPoolSetter) error {
var err error
publicreportPool1, err := PublicreportPools.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyPhonePoolPool0(ctx, exec, 1, publicreportNotifyPhonePool0, publicreportPool1)
if err != nil {
return err
}
publicreportNotifyPhonePool0.R.Pool = publicreportPool1
publicreportPool1.R.NotifyPhonePools = append(publicreportPool1.R.NotifyPhonePools, publicreportNotifyPhonePool0)
return nil
}
func (publicreportNotifyPhonePool0 *PublicreportNotifyPhonePool) AttachPool(ctx context.Context, exec bob.Executor, publicreportPool1 *PublicreportPool) error {
var err error
_, err = attachPublicreportNotifyPhonePoolPool0(ctx, exec, 1, publicreportNotifyPhonePool0, publicreportPool1)
if err != nil {
return err
}
publicreportNotifyPhonePool0.R.Pool = publicreportPool1
publicreportPool1.R.NotifyPhonePools = append(publicreportPool1.R.NotifyPhonePools, publicreportNotifyPhonePool0)
return nil
}
type publicreportNotifyPhonePoolWhere[Q psql.Filterable] struct {
Created psql.WhereMod[Q, time.Time]
Deleted psql.WhereNullMod[Q, time.Time]
PhoneE164 psql.WhereMod[Q, string]
PoolID psql.WhereMod[Q, int32]
}
func (publicreportNotifyPhonePoolWhere[Q]) AliasedAs(alias string) publicreportNotifyPhonePoolWhere[Q] {
return buildPublicreportNotifyPhonePoolWhere[Q](buildPublicreportNotifyPhonePoolColumns(alias))
}
func buildPublicreportNotifyPhonePoolWhere[Q psql.Filterable](cols publicreportNotifyPhonePoolColumns) publicreportNotifyPhonePoolWhere[Q] {
return publicreportNotifyPhonePoolWhere[Q]{
Created: psql.Where[Q, time.Time](cols.Created),
Deleted: psql.WhereNull[Q, time.Time](cols.Deleted),
PhoneE164: psql.Where[Q, string](cols.PhoneE164),
PoolID: psql.Where[Q, int32](cols.PoolID),
}
}
func (o *PublicreportNotifyPhonePool) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "PhoneE164Phone":
rel, ok := retrieved.(*CommsPhone)
if !ok {
return fmt.Errorf("publicreportNotifyPhonePool cannot load %T as %q", retrieved, name)
}
o.R.PhoneE164Phone = rel
if rel != nil {
rel.R.PhoneE164NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}
}
return nil
case "Pool":
rel, ok := retrieved.(*PublicreportPool)
if !ok {
return fmt.Errorf("publicreportNotifyPhonePool cannot load %T as %q", retrieved, name)
}
o.R.Pool = rel
if rel != nil {
rel.R.NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}
}
return nil
default:
return fmt.Errorf("publicreportNotifyPhonePool has no relationship %q", name)
}
}
type publicreportNotifyPhonePoolPreloader struct {
PhoneE164Phone func(...psql.PreloadOption) psql.Preloader
Pool func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportNotifyPhonePoolPreloader() publicreportNotifyPhonePoolPreloader {
return publicreportNotifyPhonePoolPreloader{
PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
Name: "PhoneE164Phone",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyPhonePools,
To: CommsPhones,
FromColumns: []string{"phone_e164"},
ToColumns: []string{"e164"},
},
},
}, CommsPhones.Columns.Names(), opts...)
},
Pool: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportPool, PublicreportPoolSlice](psql.PreloadRel{
Name: "Pool",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyPhonePools,
To: PublicreportPools,
FromColumns: []string{"pool_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportPools.Columns.Names(), opts...)
},
}
}
type publicreportNotifyPhonePoolThenLoader[Q orm.Loadable] struct {
PhoneE164Phone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Pool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportNotifyPhonePoolThenLoader[Q orm.Loadable]() publicreportNotifyPhonePoolThenLoader[Q] {
type PhoneE164PhoneLoadInterface interface {
LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PoolLoadInterface interface {
LoadPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportNotifyPhonePoolThenLoader[Q]{
PhoneE164Phone: thenLoadBuilder[Q](
"PhoneE164Phone",
func(ctx context.Context, exec bob.Executor, retrieved PhoneE164PhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPhoneE164Phone(ctx, exec, mods...)
},
),
Pool: thenLoadBuilder[Q](
"Pool",
func(ctx context.Context, exec bob.Executor, retrieved PoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPool(ctx, exec, mods...)
},
),
}
}
// LoadPhoneE164Phone loads the publicreportNotifyPhonePool's PhoneE164Phone into the .R struct
func (o *PublicreportNotifyPhonePool) LoadPhoneE164Phone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.PhoneE164Phone = nil
related, err := o.PhoneE164Phone(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.PhoneE164NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}
o.R.PhoneE164Phone = related
return nil
}
// LoadPhoneE164Phone loads the publicreportNotifyPhonePool's PhoneE164Phone into the .R struct
func (os PublicreportNotifyPhonePoolSlice) LoadPhoneE164Phone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
commsPhones, err := os.PhoneE164Phone(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range commsPhones {
if !(o.PhoneE164 == rel.E164) {
continue
}
rel.R.PhoneE164NotifyPhonePools = append(rel.R.PhoneE164NotifyPhonePools, o)
o.R.PhoneE164Phone = rel
break
}
}
return nil
}
// LoadPool loads the publicreportNotifyPhonePool's Pool into the .R struct
func (o *PublicreportNotifyPhonePool) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Pool = nil
related, err := o.Pool(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.NotifyPhonePools = PublicreportNotifyPhonePoolSlice{o}
o.R.Pool = related
return nil
}
// LoadPool loads the publicreportNotifyPhonePool's Pool into the .R struct
func (os PublicreportNotifyPhonePoolSlice) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportPools, err := os.Pool(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportPools {
if !(o.PoolID == rel.ID) {
continue
}
rel.R.NotifyPhonePools = append(rel.R.NotifyPhonePools, o)
o.R.Pool = rel
break
}
}
return nil
}

View file

@ -0,0 +1,796 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/null"
"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull"
)
// PublicreportNotifyPhoneWater is an object representing the database table.
type PublicreportNotifyPhoneWater struct {
Created time.Time `db:"created" `
Deleted null.Val[time.Time] `db:"deleted" `
PhoneE164 string `db:"phone_e164,pk" `
WaterID int32 `db:"water_id,pk" `
R publicreportNotifyPhoneWaterR `db:"-" `
}
// PublicreportNotifyPhoneWaterSlice is an alias for a slice of pointers to PublicreportNotifyPhoneWater.
// This should almost always be used instead of []*PublicreportNotifyPhoneWater.
type PublicreportNotifyPhoneWaterSlice []*PublicreportNotifyPhoneWater
// PublicreportNotifyPhoneWaters contains methods to work with the notify_phone_water table
var PublicreportNotifyPhoneWaters = psql.NewTablex[*PublicreportNotifyPhoneWater, PublicreportNotifyPhoneWaterSlice, *PublicreportNotifyPhoneWaterSetter]("publicreport", "notify_phone_water", buildPublicreportNotifyPhoneWaterColumns("publicreport.notify_phone_water"))
// PublicreportNotifyPhoneWatersQuery is a query on the notify_phone_water table
type PublicreportNotifyPhoneWatersQuery = *psql.ViewQuery[*PublicreportNotifyPhoneWater, PublicreportNotifyPhoneWaterSlice]
// publicreportNotifyPhoneWaterR is where relationships are stored.
type publicreportNotifyPhoneWaterR struct {
PhoneE164Phone *CommsPhone // publicreport.notify_phone_water.notify_phone_pool_phone_e164_fkey
Water *PublicreportWater // publicreport.notify_phone_water.notify_phone_pool_pool_id_fkey
}
func buildPublicreportNotifyPhoneWaterColumns(alias string) publicreportNotifyPhoneWaterColumns {
return publicreportNotifyPhoneWaterColumns{
ColumnsExpr: expr.NewColumnsExpr(
"created", "deleted", "phone_e164", "water_id",
).WithParent("publicreport.notify_phone_water"),
tableAlias: alias,
Created: psql.Quote(alias, "created"),
Deleted: psql.Quote(alias, "deleted"),
PhoneE164: psql.Quote(alias, "phone_e164"),
WaterID: psql.Quote(alias, "water_id"),
}
}
type publicreportNotifyPhoneWaterColumns struct {
expr.ColumnsExpr
tableAlias string
Created psql.Expression
Deleted psql.Expression
PhoneE164 psql.Expression
WaterID psql.Expression
}
func (c publicreportNotifyPhoneWaterColumns) Alias() string {
return c.tableAlias
}
func (publicreportNotifyPhoneWaterColumns) AliasedAs(alias string) publicreportNotifyPhoneWaterColumns {
return buildPublicreportNotifyPhoneWaterColumns(alias)
}
// PublicreportNotifyPhoneWaterSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportNotifyPhoneWaterSetter struct {
Created omit.Val[time.Time] `db:"created" `
Deleted omitnull.Val[time.Time] `db:"deleted" `
PhoneE164 omit.Val[string] `db:"phone_e164,pk" `
WaterID omit.Val[int32] `db:"water_id,pk" `
}
func (s PublicreportNotifyPhoneWaterSetter) SetColumns() []string {
vals := make([]string, 0, 4)
if s.Created.IsValue() {
vals = append(vals, "created")
}
if !s.Deleted.IsUnset() {
vals = append(vals, "deleted")
}
if s.PhoneE164.IsValue() {
vals = append(vals, "phone_e164")
}
if s.WaterID.IsValue() {
vals = append(vals, "water_id")
}
return vals
}
func (s PublicreportNotifyPhoneWaterSetter) Overwrite(t *PublicreportNotifyPhoneWater) {
if s.Created.IsValue() {
t.Created = s.Created.MustGet()
}
if !s.Deleted.IsUnset() {
t.Deleted = s.Deleted.MustGetNull()
}
if s.PhoneE164.IsValue() {
t.PhoneE164 = s.PhoneE164.MustGet()
}
if s.WaterID.IsValue() {
t.WaterID = s.WaterID.MustGet()
}
}
func (s *PublicreportNotifyPhoneWaterSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportNotifyPhoneWaters.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 4)
if s.Created.IsValue() {
vals[0] = psql.Arg(s.Created.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if !s.Deleted.IsUnset() {
vals[1] = psql.Arg(s.Deleted.MustGetNull())
} else {
vals[1] = psql.Raw("DEFAULT")
}
if s.PhoneE164.IsValue() {
vals[2] = psql.Arg(s.PhoneE164.MustGet())
} else {
vals[2] = psql.Raw("DEFAULT")
}
if s.WaterID.IsValue() {
vals[3] = psql.Arg(s.WaterID.MustGet())
} else {
vals[3] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportNotifyPhoneWaterSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportNotifyPhoneWaterSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 4)
if s.Created.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "created")...),
psql.Arg(s.Created),
}})
}
if !s.Deleted.IsUnset() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "deleted")...),
psql.Arg(s.Deleted),
}})
}
if s.PhoneE164.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "phone_e164")...),
psql.Arg(s.PhoneE164),
}})
}
if s.WaterID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "water_id")...),
psql.Arg(s.WaterID),
}})
}
return exprs
}
// FindPublicreportNotifyPhoneWater retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportNotifyPhoneWater(ctx context.Context, exec bob.Executor, WaterIDPK int32, PhoneE164PK string, cols ...string) (*PublicreportNotifyPhoneWater, error) {
if len(cols) == 0 {
return PublicreportNotifyPhoneWaters.Query(
sm.Where(PublicreportNotifyPhoneWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyPhoneWaters.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
).One(ctx, exec)
}
return PublicreportNotifyPhoneWaters.Query(
sm.Where(PublicreportNotifyPhoneWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyPhoneWaters.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
sm.Columns(PublicreportNotifyPhoneWaters.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportNotifyPhoneWaterExists checks the presence of a single record by primary key
func PublicreportNotifyPhoneWaterExists(ctx context.Context, exec bob.Executor, WaterIDPK int32, PhoneE164PK string) (bool, error) {
return PublicreportNotifyPhoneWaters.Query(
sm.Where(PublicreportNotifyPhoneWaters.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Where(PublicreportNotifyPhoneWaters.Columns.PhoneE164.EQ(psql.Arg(PhoneE164PK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportNotifyPhoneWater is retrieved from the database
func (o *PublicreportNotifyPhoneWater) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyPhoneWaters.AfterSelectHooks.RunHooks(ctx, exec, PublicreportNotifyPhoneWaterSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyPhoneWaters.AfterInsertHooks.RunHooks(ctx, exec, PublicreportNotifyPhoneWaterSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyPhoneWaters.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportNotifyPhoneWaterSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyPhoneWaters.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportNotifyPhoneWaterSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportNotifyPhoneWater
func (o *PublicreportNotifyPhoneWater) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.WaterID,
o.PhoneE164,
)
}
func (o *PublicreportNotifyPhoneWater) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.notify_phone_water", "water_id"), psql.Quote("publicreport.notify_phone_water", "phone_e164")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportNotifyPhoneWater
func (o *PublicreportNotifyPhoneWater) Update(ctx context.Context, exec bob.Executor, s *PublicreportNotifyPhoneWaterSetter) error {
v, err := PublicreportNotifyPhoneWaters.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 PublicreportNotifyPhoneWater record with an executor
func (o *PublicreportNotifyPhoneWater) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportNotifyPhoneWaters.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportNotifyPhoneWater using the executor
func (o *PublicreportNotifyPhoneWater) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportNotifyPhoneWaters.Query(
sm.Where(PublicreportNotifyPhoneWaters.Columns.WaterID.EQ(psql.Arg(o.WaterID))),
sm.Where(PublicreportNotifyPhoneWaters.Columns.PhoneE164.EQ(psql.Arg(o.PhoneE164))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportNotifyPhoneWaterSlice is retrieved from the database
func (o PublicreportNotifyPhoneWaterSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportNotifyPhoneWaters.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportNotifyPhoneWaters.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportNotifyPhoneWaters.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportNotifyPhoneWaters.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportNotifyPhoneWaterSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.notify_phone_water", "water_id"), psql.Quote("publicreport.notify_phone_water", "phone_e164")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportNotifyPhoneWaterSlice) copyMatchingRows(from ...*PublicreportNotifyPhoneWater) {
for i, old := range o {
for _, new := range from {
if new.WaterID != old.WaterID {
continue
}
if new.PhoneE164 != old.PhoneE164 {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyPhoneWaterSlice) 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 PublicreportNotifyPhoneWaters.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 *PublicreportNotifyPhoneWater:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyPhoneWater:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyPhoneWaterSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyPhoneWater or a slice of PublicreportNotifyPhoneWater
// then run the AfterUpdateHooks on the slice
_, err = PublicreportNotifyPhoneWaters.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportNotifyPhoneWaterSlice) 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 PublicreportNotifyPhoneWaters.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 *PublicreportNotifyPhoneWater:
o.copyMatchingRows(retrieved)
case []*PublicreportNotifyPhoneWater:
o.copyMatchingRows(retrieved...)
case PublicreportNotifyPhoneWaterSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportNotifyPhoneWater or a slice of PublicreportNotifyPhoneWater
// then run the AfterDeleteHooks on the slice
_, err = PublicreportNotifyPhoneWaters.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportNotifyPhoneWaterSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportNotifyPhoneWaterSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyPhoneWaters.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportNotifyPhoneWaterSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportNotifyPhoneWaters.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportNotifyPhoneWaterSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportNotifyPhoneWaters.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// PhoneE164Phone starts a query for related objects on comms.phone
func (o *PublicreportNotifyPhoneWater) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
return CommsPhones.Query(append(mods,
sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneE164))),
)...)
}
func (os PublicreportNotifyPhoneWaterSlice) PhoneE164Phone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery {
pkPhoneE164 := make(pgtypes.Array[string], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkPhoneE164 = append(pkPhoneE164, o.PhoneE164)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkPhoneE164), "text[]")),
))
return CommsPhones.Query(append(mods,
sm.Where(psql.Group(CommsPhones.Columns.E164).OP("IN", PKArgExpr)),
)...)
}
// Water starts a query for related objects on publicreport.water
func (o *PublicreportNotifyPhoneWater) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.Where(PublicreportWaters.Columns.ID.EQ(psql.Arg(o.WaterID))),
)...)
}
func (os PublicreportNotifyPhoneWaterSlice) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
pkWaterID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkWaterID = append(pkWaterID, o.WaterID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkWaterID), "integer[]")),
))
return PublicreportWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportWaters.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportNotifyPhoneWaterPhoneE164Phone0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater, commsPhone1 *CommsPhone) (*PublicreportNotifyPhoneWater, error) {
setter := &PublicreportNotifyPhoneWaterSetter{
PhoneE164: omit.From(commsPhone1.E164),
}
err := publicreportNotifyPhoneWater0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyPhoneWaterPhoneE164Phone0: %w", err)
}
return publicreportNotifyPhoneWater0, nil
}
func (publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater) InsertPhoneE164Phone(ctx context.Context, exec bob.Executor, related *CommsPhoneSetter) error {
var err error
commsPhone1, err := CommsPhones.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyPhoneWaterPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhoneWater0, commsPhone1)
if err != nil {
return err
}
publicreportNotifyPhoneWater0.R.PhoneE164Phone = commsPhone1
commsPhone1.R.PhoneE164NotifyPhoneWaters = append(commsPhone1.R.PhoneE164NotifyPhoneWaters, publicreportNotifyPhoneWater0)
return nil
}
func (publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater) AttachPhoneE164Phone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error {
var err error
_, err = attachPublicreportNotifyPhoneWaterPhoneE164Phone0(ctx, exec, 1, publicreportNotifyPhoneWater0, commsPhone1)
if err != nil {
return err
}
publicreportNotifyPhoneWater0.R.PhoneE164Phone = commsPhone1
commsPhone1.R.PhoneE164NotifyPhoneWaters = append(commsPhone1.R.PhoneE164NotifyPhoneWaters, publicreportNotifyPhoneWater0)
return nil
}
func attachPublicreportNotifyPhoneWaterWater0(ctx context.Context, exec bob.Executor, count int, publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater, publicreportWater1 *PublicreportWater) (*PublicreportNotifyPhoneWater, error) {
setter := &PublicreportNotifyPhoneWaterSetter{
WaterID: omit.From(publicreportWater1.ID),
}
err := publicreportNotifyPhoneWater0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNotifyPhoneWaterWater0: %w", err)
}
return publicreportNotifyPhoneWater0, nil
}
func (publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater) InsertWater(ctx context.Context, exec bob.Executor, related *PublicreportWaterSetter) error {
var err error
publicreportWater1, err := PublicreportWaters.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNotifyPhoneWaterWater0(ctx, exec, 1, publicreportNotifyPhoneWater0, publicreportWater1)
if err != nil {
return err
}
publicreportNotifyPhoneWater0.R.Water = publicreportWater1
publicreportWater1.R.NotifyPhoneWaters = append(publicreportWater1.R.NotifyPhoneWaters, publicreportNotifyPhoneWater0)
return nil
}
func (publicreportNotifyPhoneWater0 *PublicreportNotifyPhoneWater) AttachWater(ctx context.Context, exec bob.Executor, publicreportWater1 *PublicreportWater) error {
var err error
_, err = attachPublicreportNotifyPhoneWaterWater0(ctx, exec, 1, publicreportNotifyPhoneWater0, publicreportWater1)
if err != nil {
return err
}
publicreportNotifyPhoneWater0.R.Water = publicreportWater1
publicreportWater1.R.NotifyPhoneWaters = append(publicreportWater1.R.NotifyPhoneWaters, publicreportNotifyPhoneWater0)
return nil
}
type publicreportNotifyPhoneWaterWhere[Q psql.Filterable] struct {
Created psql.WhereMod[Q, time.Time]
Deleted psql.WhereNullMod[Q, time.Time]
PhoneE164 psql.WhereMod[Q, string]
WaterID psql.WhereMod[Q, int32]
}
func (publicreportNotifyPhoneWaterWhere[Q]) AliasedAs(alias string) publicreportNotifyPhoneWaterWhere[Q] {
return buildPublicreportNotifyPhoneWaterWhere[Q](buildPublicreportNotifyPhoneWaterColumns(alias))
}
func buildPublicreportNotifyPhoneWaterWhere[Q psql.Filterable](cols publicreportNotifyPhoneWaterColumns) publicreportNotifyPhoneWaterWhere[Q] {
return publicreportNotifyPhoneWaterWhere[Q]{
Created: psql.Where[Q, time.Time](cols.Created),
Deleted: psql.WhereNull[Q, time.Time](cols.Deleted),
PhoneE164: psql.Where[Q, string](cols.PhoneE164),
WaterID: psql.Where[Q, int32](cols.WaterID),
}
}
func (o *PublicreportNotifyPhoneWater) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "PhoneE164Phone":
rel, ok := retrieved.(*CommsPhone)
if !ok {
return fmt.Errorf("publicreportNotifyPhoneWater cannot load %T as %q", retrieved, name)
}
o.R.PhoneE164Phone = rel
if rel != nil {
rel.R.PhoneE164NotifyPhoneWaters = PublicreportNotifyPhoneWaterSlice{o}
}
return nil
case "Water":
rel, ok := retrieved.(*PublicreportWater)
if !ok {
return fmt.Errorf("publicreportNotifyPhoneWater cannot load %T as %q", retrieved, name)
}
o.R.Water = rel
if rel != nil {
rel.R.NotifyPhoneWaters = PublicreportNotifyPhoneWaterSlice{o}
}
return nil
default:
return fmt.Errorf("publicreportNotifyPhoneWater has no relationship %q", name)
}
}
type publicreportNotifyPhoneWaterPreloader struct {
PhoneE164Phone func(...psql.PreloadOption) psql.Preloader
Water func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportNotifyPhoneWaterPreloader() publicreportNotifyPhoneWaterPreloader {
return publicreportNotifyPhoneWaterPreloader{
PhoneE164Phone: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{
Name: "PhoneE164Phone",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyPhoneWaters,
To: CommsPhones,
FromColumns: []string{"phone_e164"},
ToColumns: []string{"e164"},
},
},
}, CommsPhones.Columns.Names(), opts...)
},
Water: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportWater, PublicreportWaterSlice](psql.PreloadRel{
Name: "Water",
Sides: []psql.PreloadSide{
{
From: PublicreportNotifyPhoneWaters,
To: PublicreportWaters,
FromColumns: []string{"water_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportWaters.Columns.Names(), opts...)
},
}
}
type publicreportNotifyPhoneWaterThenLoader[Q orm.Loadable] struct {
PhoneE164Phone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Water func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportNotifyPhoneWaterThenLoader[Q orm.Loadable]() publicreportNotifyPhoneWaterThenLoader[Q] {
type PhoneE164PhoneLoadInterface interface {
LoadPhoneE164Phone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type WaterLoadInterface interface {
LoadWater(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportNotifyPhoneWaterThenLoader[Q]{
PhoneE164Phone: thenLoadBuilder[Q](
"PhoneE164Phone",
func(ctx context.Context, exec bob.Executor, retrieved PhoneE164PhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPhoneE164Phone(ctx, exec, mods...)
},
),
Water: thenLoadBuilder[Q](
"Water",
func(ctx context.Context, exec bob.Executor, retrieved WaterLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWater(ctx, exec, mods...)
},
),
}
}
// LoadPhoneE164Phone loads the publicreportNotifyPhoneWater's PhoneE164Phone into the .R struct
func (o *PublicreportNotifyPhoneWater) LoadPhoneE164Phone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.PhoneE164Phone = nil
related, err := o.PhoneE164Phone(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.PhoneE164NotifyPhoneWaters = PublicreportNotifyPhoneWaterSlice{o}
o.R.PhoneE164Phone = related
return nil
}
// LoadPhoneE164Phone loads the publicreportNotifyPhoneWater's PhoneE164Phone into the .R struct
func (os PublicreportNotifyPhoneWaterSlice) LoadPhoneE164Phone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
commsPhones, err := os.PhoneE164Phone(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range commsPhones {
if !(o.PhoneE164 == rel.E164) {
continue
}
rel.R.PhoneE164NotifyPhoneWaters = append(rel.R.PhoneE164NotifyPhoneWaters, o)
o.R.PhoneE164Phone = rel
break
}
}
return nil
}
// LoadWater loads the publicreportNotifyPhoneWater's Water into the .R struct
func (o *PublicreportNotifyPhoneWater) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Water = nil
related, err := o.Water(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.NotifyPhoneWaters = PublicreportNotifyPhoneWaterSlice{o}
o.R.Water = related
return nil
}
// LoadWater loads the publicreportNotifyPhoneWater's Water into the .R struct
func (os PublicreportNotifyPhoneWaterSlice) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportWaters, err := os.Water(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportWaters {
if !(o.WaterID == rel.ID) {
continue
}
rel.R.NotifyPhoneWaters = append(rel.R.NotifyPhoneWaters, o)
o.R.Water = rel
break
}
}
return nil
}

View file

@ -38,14 +38,14 @@ type PublicreportNuisance struct {
ReporterEmail null.Val[string] `db:"reporter_email" `
ReporterName null.Val[string] `db:"reporter_name" `
ReporterPhone null.Val[string] `db:"reporter_phone" `
Address string `db:"address" `
AddressRaw string `db:"address_raw" `
Status enums.PublicreportReportstatustype `db:"status" `
OrganizationID null.Val[int32] `db:"organization_id" `
SourceGutter bool `db:"source_gutter" `
H3cell null.Val[string] `db:"h3cell" `
AddressCountry string `db:"address_country" `
AddressPlace string `db:"address_place" `
AddressPostcode string `db:"address_postcode" `
AddressLocality string `db:"address_locality" `
AddressPostalCode string `db:"address_postal_code" `
AddressRegion string `db:"address_region" `
AddressStreet string `db:"address_street" `
IsLocationBackyard bool `db:"is_location_backyard" `
@ -63,6 +63,7 @@ type PublicreportNuisance struct {
ReporterContactConsent null.Val[bool] `db:"reporter_contact_consent" `
Location null.Val[string] `db:"location" `
AddressNumber string `db:"address_number" `
AddressID null.Val[int32] `db:"address_id" `
R publicreportNuisanceR `db:"-" `
}
@ -81,6 +82,7 @@ type PublicreportNuisancesQuery = *psql.ViewQuery[*PublicreportNuisance, Publicr
type publicreportNuisanceR struct {
NotifyEmailNuisances PublicreportNotifyEmailNuisanceSlice // publicreport.notify_email_nuisance.notify_email_nuisance_nuisance_id_fkey
NotifyPhoneNuisances PublicreportNotifyPhoneNuisanceSlice // publicreport.notify_phone_nuisance.notify_phone_nuisance_nuisance_id_fkey
Address *Address // publicreport.nuisance.nuisance_address_id_fkey
Organization *Organization // publicreport.nuisance.nuisance_organization_id_fkey
Images PublicreportImageSlice // publicreport.nuisance_image.nuisance_image_image_id_fkeypublicreport.nuisance_image.nuisance_image_nuisance_id_fkey
}
@ -88,7 +90,7 @@ type publicreportNuisanceR struct {
func buildPublicreportNuisanceColumns(alias string) publicreportNuisanceColumns {
return publicreportNuisanceColumns{
ColumnsExpr: expr.NewColumnsExpr(
"id", "additional_info", "created", "duration", "source_container", "source_description", "source_stagnant", "public_id", "reporter_email", "reporter_name", "reporter_phone", "address", "status", "organization_id", "source_gutter", "h3cell", "address_country", "address_place", "address_postcode", "address_region", "address_street", "is_location_backyard", "is_location_frontyard", "is_location_garden", "is_location_other", "is_location_pool", "map_zoom", "tod_early", "tod_day", "tod_evening", "tod_night", "latlng_accuracy_type", "latlng_accuracy_value", "reporter_contact_consent", "location", "address_number",
"id", "additional_info", "created", "duration", "source_container", "source_description", "source_stagnant", "public_id", "reporter_email", "reporter_name", "reporter_phone", "address_raw", "status", "organization_id", "source_gutter", "h3cell", "address_country", "address_locality", "address_postal_code", "address_region", "address_street", "is_location_backyard", "is_location_frontyard", "is_location_garden", "is_location_other", "is_location_pool", "map_zoom", "tod_early", "tod_day", "tod_evening", "tod_night", "latlng_accuracy_type", "latlng_accuracy_value", "reporter_contact_consent", "location", "address_number", "address_id",
).WithParent("publicreport.nuisance"),
tableAlias: alias,
ID: psql.Quote(alias, "id"),
@ -102,14 +104,14 @@ func buildPublicreportNuisanceColumns(alias string) publicreportNuisanceColumns
ReporterEmail: psql.Quote(alias, "reporter_email"),
ReporterName: psql.Quote(alias, "reporter_name"),
ReporterPhone: psql.Quote(alias, "reporter_phone"),
Address: psql.Quote(alias, "address"),
AddressRaw: psql.Quote(alias, "address_raw"),
Status: psql.Quote(alias, "status"),
OrganizationID: psql.Quote(alias, "organization_id"),
SourceGutter: psql.Quote(alias, "source_gutter"),
H3cell: psql.Quote(alias, "h3cell"),
AddressCountry: psql.Quote(alias, "address_country"),
AddressPlace: psql.Quote(alias, "address_place"),
AddressPostcode: psql.Quote(alias, "address_postcode"),
AddressLocality: psql.Quote(alias, "address_locality"),
AddressPostalCode: psql.Quote(alias, "address_postal_code"),
AddressRegion: psql.Quote(alias, "address_region"),
AddressStreet: psql.Quote(alias, "address_street"),
IsLocationBackyard: psql.Quote(alias, "is_location_backyard"),
@ -127,6 +129,7 @@ func buildPublicreportNuisanceColumns(alias string) publicreportNuisanceColumns
ReporterContactConsent: psql.Quote(alias, "reporter_contact_consent"),
Location: psql.Quote(alias, "location"),
AddressNumber: psql.Quote(alias, "address_number"),
AddressID: psql.Quote(alias, "address_id"),
}
}
@ -144,14 +147,14 @@ type publicreportNuisanceColumns struct {
ReporterEmail psql.Expression
ReporterName psql.Expression
ReporterPhone psql.Expression
Address psql.Expression
AddressRaw psql.Expression
Status psql.Expression
OrganizationID psql.Expression
SourceGutter psql.Expression
H3cell psql.Expression
AddressCountry psql.Expression
AddressPlace psql.Expression
AddressPostcode psql.Expression
AddressLocality psql.Expression
AddressPostalCode psql.Expression
AddressRegion psql.Expression
AddressStreet psql.Expression
IsLocationBackyard psql.Expression
@ -169,6 +172,7 @@ type publicreportNuisanceColumns struct {
ReporterContactConsent psql.Expression
Location psql.Expression
AddressNumber psql.Expression
AddressID psql.Expression
}
func (c publicreportNuisanceColumns) Alias() string {
@ -194,14 +198,14 @@ type PublicreportNuisanceSetter struct {
ReporterEmail omitnull.Val[string] `db:"reporter_email" `
ReporterName omitnull.Val[string] `db:"reporter_name" `
ReporterPhone omitnull.Val[string] `db:"reporter_phone" `
Address omit.Val[string] `db:"address" `
AddressRaw omit.Val[string] `db:"address_raw" `
Status omit.Val[enums.PublicreportReportstatustype] `db:"status" `
OrganizationID omitnull.Val[int32] `db:"organization_id" `
SourceGutter omit.Val[bool] `db:"source_gutter" `
H3cell omitnull.Val[string] `db:"h3cell" `
AddressCountry omit.Val[string] `db:"address_country" `
AddressPlace omit.Val[string] `db:"address_place" `
AddressPostcode omit.Val[string] `db:"address_postcode" `
AddressLocality omit.Val[string] `db:"address_locality" `
AddressPostalCode omit.Val[string] `db:"address_postal_code" `
AddressRegion omit.Val[string] `db:"address_region" `
AddressStreet omit.Val[string] `db:"address_street" `
IsLocationBackyard omit.Val[bool] `db:"is_location_backyard" `
@ -219,10 +223,11 @@ type PublicreportNuisanceSetter struct {
ReporterContactConsent omitnull.Val[bool] `db:"reporter_contact_consent" `
Location omitnull.Val[string] `db:"location" `
AddressNumber omit.Val[string] `db:"address_number" `
AddressID omitnull.Val[int32] `db:"address_id" `
}
func (s PublicreportNuisanceSetter) SetColumns() []string {
vals := make([]string, 0, 36)
vals := make([]string, 0, 37)
if s.ID.IsValue() {
vals = append(vals, "id")
}
@ -256,8 +261,8 @@ func (s PublicreportNuisanceSetter) SetColumns() []string {
if !s.ReporterPhone.IsUnset() {
vals = append(vals, "reporter_phone")
}
if s.Address.IsValue() {
vals = append(vals, "address")
if s.AddressRaw.IsValue() {
vals = append(vals, "address_raw")
}
if s.Status.IsValue() {
vals = append(vals, "status")
@ -274,11 +279,11 @@ func (s PublicreportNuisanceSetter) SetColumns() []string {
if s.AddressCountry.IsValue() {
vals = append(vals, "address_country")
}
if s.AddressPlace.IsValue() {
vals = append(vals, "address_place")
if s.AddressLocality.IsValue() {
vals = append(vals, "address_locality")
}
if s.AddressPostcode.IsValue() {
vals = append(vals, "address_postcode")
if s.AddressPostalCode.IsValue() {
vals = append(vals, "address_postal_code")
}
if s.AddressRegion.IsValue() {
vals = append(vals, "address_region")
@ -331,6 +336,9 @@ func (s PublicreportNuisanceSetter) SetColumns() []string {
if s.AddressNumber.IsValue() {
vals = append(vals, "address_number")
}
if !s.AddressID.IsUnset() {
vals = append(vals, "address_id")
}
return vals
}
@ -368,8 +376,8 @@ func (s PublicreportNuisanceSetter) Overwrite(t *PublicreportNuisance) {
if !s.ReporterPhone.IsUnset() {
t.ReporterPhone = s.ReporterPhone.MustGetNull()
}
if s.Address.IsValue() {
t.Address = s.Address.MustGet()
if s.AddressRaw.IsValue() {
t.AddressRaw = s.AddressRaw.MustGet()
}
if s.Status.IsValue() {
t.Status = s.Status.MustGet()
@ -386,11 +394,11 @@ func (s PublicreportNuisanceSetter) Overwrite(t *PublicreportNuisance) {
if s.AddressCountry.IsValue() {
t.AddressCountry = s.AddressCountry.MustGet()
}
if s.AddressPlace.IsValue() {
t.AddressPlace = s.AddressPlace.MustGet()
if s.AddressLocality.IsValue() {
t.AddressLocality = s.AddressLocality.MustGet()
}
if s.AddressPostcode.IsValue() {
t.AddressPostcode = s.AddressPostcode.MustGet()
if s.AddressPostalCode.IsValue() {
t.AddressPostalCode = s.AddressPostalCode.MustGet()
}
if s.AddressRegion.IsValue() {
t.AddressRegion = s.AddressRegion.MustGet()
@ -443,6 +451,9 @@ func (s PublicreportNuisanceSetter) Overwrite(t *PublicreportNuisance) {
if s.AddressNumber.IsValue() {
t.AddressNumber = s.AddressNumber.MustGet()
}
if !s.AddressID.IsUnset() {
t.AddressID = s.AddressID.MustGetNull()
}
}
func (s *PublicreportNuisanceSetter) Apply(q *dialect.InsertQuery) {
@ -451,7 +462,7 @@ func (s *PublicreportNuisanceSetter) Apply(q *dialect.InsertQuery) {
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 36)
vals := make([]bob.Expression, 37)
if s.ID.IsValue() {
vals[0] = psql.Arg(s.ID.MustGet())
} else {
@ -518,8 +529,8 @@ func (s *PublicreportNuisanceSetter) Apply(q *dialect.InsertQuery) {
vals[10] = psql.Raw("DEFAULT")
}
if s.Address.IsValue() {
vals[11] = psql.Arg(s.Address.MustGet())
if s.AddressRaw.IsValue() {
vals[11] = psql.Arg(s.AddressRaw.MustGet())
} else {
vals[11] = psql.Raw("DEFAULT")
}
@ -554,14 +565,14 @@ func (s *PublicreportNuisanceSetter) Apply(q *dialect.InsertQuery) {
vals[16] = psql.Raw("DEFAULT")
}
if s.AddressPlace.IsValue() {
vals[17] = psql.Arg(s.AddressPlace.MustGet())
if s.AddressLocality.IsValue() {
vals[17] = psql.Arg(s.AddressLocality.MustGet())
} else {
vals[17] = psql.Raw("DEFAULT")
}
if s.AddressPostcode.IsValue() {
vals[18] = psql.Arg(s.AddressPostcode.MustGet())
if s.AddressPostalCode.IsValue() {
vals[18] = psql.Arg(s.AddressPostalCode.MustGet())
} else {
vals[18] = psql.Raw("DEFAULT")
}
@ -668,6 +679,12 @@ func (s *PublicreportNuisanceSetter) Apply(q *dialect.InsertQuery) {
vals[35] = psql.Raw("DEFAULT")
}
if !s.AddressID.IsUnset() {
vals[36] = psql.Arg(s.AddressID.MustGetNull())
} else {
vals[36] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
@ -677,7 +694,7 @@ func (s PublicreportNuisanceSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
}
func (s PublicreportNuisanceSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 36)
exprs := make([]bob.Expression, 0, 37)
if s.ID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
@ -756,10 +773,10 @@ func (s PublicreportNuisanceSetter) Expressions(prefix ...string) []bob.Expressi
}})
}
if s.Address.IsValue() {
if s.AddressRaw.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "address")...),
psql.Arg(s.Address),
psql.Quote(append(prefix, "address_raw")...),
psql.Arg(s.AddressRaw),
}})
}
@ -798,17 +815,17 @@ func (s PublicreportNuisanceSetter) Expressions(prefix ...string) []bob.Expressi
}})
}
if s.AddressPlace.IsValue() {
if s.AddressLocality.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "address_place")...),
psql.Arg(s.AddressPlace),
psql.Quote(append(prefix, "address_locality")...),
psql.Arg(s.AddressLocality),
}})
}
if s.AddressPostcode.IsValue() {
if s.AddressPostalCode.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "address_postcode")...),
psql.Arg(s.AddressPostcode),
psql.Quote(append(prefix, "address_postal_code")...),
psql.Arg(s.AddressPostalCode),
}})
}
@ -931,6 +948,13 @@ func (s PublicreportNuisanceSetter) Expressions(prefix ...string) []bob.Expressi
}})
}
if !s.AddressID.IsUnset() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "address_id")...),
psql.Arg(s.AddressID),
}})
}
return exprs
}
@ -1205,6 +1229,30 @@ func (os PublicreportNuisanceSlice) NotifyPhoneNuisances(mods ...bob.Mod[*dialec
)...)
}
// Address starts a query for related objects on address
func (o *PublicreportNuisance) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery {
return Addresses.Query(append(mods,
sm.Where(Addresses.Columns.ID.EQ(psql.Arg(o.AddressID))),
)...)
}
func (os PublicreportNuisanceSlice) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery {
pkAddressID := make(pgtypes.Array[null.Val[int32]], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkAddressID = append(pkAddressID, o.AddressID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkAddressID), "integer[]")),
))
return Addresses.Query(append(mods,
sm.Where(psql.Group(Addresses.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
// Organization starts a query for related objects on organization
func (o *PublicreportNuisance) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery {
return Organizations.Query(append(mods,
@ -1394,6 +1442,54 @@ func (publicreportNuisance0 *PublicreportNuisance) AttachNotifyPhoneNuisances(ct
return nil
}
func attachPublicreportNuisanceAddress0(ctx context.Context, exec bob.Executor, count int, publicreportNuisance0 *PublicreportNuisance, address1 *Address) (*PublicreportNuisance, error) {
setter := &PublicreportNuisanceSetter{
AddressID: omitnull.From(address1.ID),
}
err := publicreportNuisance0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportNuisanceAddress0: %w", err)
}
return publicreportNuisance0, nil
}
func (publicreportNuisance0 *PublicreportNuisance) InsertAddress(ctx context.Context, exec bob.Executor, related *AddressSetter) error {
var err error
address1, err := Addresses.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportNuisanceAddress0(ctx, exec, 1, publicreportNuisance0, address1)
if err != nil {
return err
}
publicreportNuisance0.R.Address = address1
address1.R.Nuisances = append(address1.R.Nuisances, publicreportNuisance0)
return nil
}
func (publicreportNuisance0 *PublicreportNuisance) AttachAddress(ctx context.Context, exec bob.Executor, address1 *Address) error {
var err error
_, err = attachPublicreportNuisanceAddress0(ctx, exec, 1, publicreportNuisance0, address1)
if err != nil {
return err
}
publicreportNuisance0.R.Address = address1
address1.R.Nuisances = append(address1.R.Nuisances, publicreportNuisance0)
return nil
}
func attachPublicreportNuisanceOrganization0(ctx context.Context, exec bob.Executor, count int, publicreportNuisance0 *PublicreportNuisance, organization1 *Organization) (*PublicreportNuisance, error) {
setter := &PublicreportNuisanceSetter{
OrganizationID: omitnull.From(organization1.ID),
@ -1519,14 +1615,14 @@ type publicreportNuisanceWhere[Q psql.Filterable] struct {
ReporterEmail psql.WhereNullMod[Q, string]
ReporterName psql.WhereNullMod[Q, string]
ReporterPhone psql.WhereNullMod[Q, string]
Address psql.WhereMod[Q, string]
AddressRaw psql.WhereMod[Q, string]
Status psql.WhereMod[Q, enums.PublicreportReportstatustype]
OrganizationID psql.WhereNullMod[Q, int32]
SourceGutter psql.WhereMod[Q, bool]
H3cell psql.WhereNullMod[Q, string]
AddressCountry psql.WhereMod[Q, string]
AddressPlace psql.WhereMod[Q, string]
AddressPostcode psql.WhereMod[Q, string]
AddressLocality psql.WhereMod[Q, string]
AddressPostalCode psql.WhereMod[Q, string]
AddressRegion psql.WhereMod[Q, string]
AddressStreet psql.WhereMod[Q, string]
IsLocationBackyard psql.WhereMod[Q, bool]
@ -1544,6 +1640,7 @@ type publicreportNuisanceWhere[Q psql.Filterable] struct {
ReporterContactConsent psql.WhereNullMod[Q, bool]
Location psql.WhereNullMod[Q, string]
AddressNumber psql.WhereMod[Q, string]
AddressID psql.WhereNullMod[Q, int32]
}
func (publicreportNuisanceWhere[Q]) AliasedAs(alias string) publicreportNuisanceWhere[Q] {
@ -1563,14 +1660,14 @@ func buildPublicreportNuisanceWhere[Q psql.Filterable](cols publicreportNuisance
ReporterEmail: psql.WhereNull[Q, string](cols.ReporterEmail),
ReporterName: psql.WhereNull[Q, string](cols.ReporterName),
ReporterPhone: psql.WhereNull[Q, string](cols.ReporterPhone),
Address: psql.Where[Q, string](cols.Address),
AddressRaw: psql.Where[Q, string](cols.AddressRaw),
Status: psql.Where[Q, enums.PublicreportReportstatustype](cols.Status),
OrganizationID: psql.WhereNull[Q, int32](cols.OrganizationID),
SourceGutter: psql.Where[Q, bool](cols.SourceGutter),
H3cell: psql.WhereNull[Q, string](cols.H3cell),
AddressCountry: psql.Where[Q, string](cols.AddressCountry),
AddressPlace: psql.Where[Q, string](cols.AddressPlace),
AddressPostcode: psql.Where[Q, string](cols.AddressPostcode),
AddressLocality: psql.Where[Q, string](cols.AddressLocality),
AddressPostalCode: psql.Where[Q, string](cols.AddressPostalCode),
AddressRegion: psql.Where[Q, string](cols.AddressRegion),
AddressStreet: psql.Where[Q, string](cols.AddressStreet),
IsLocationBackyard: psql.Where[Q, bool](cols.IsLocationBackyard),
@ -1588,6 +1685,7 @@ func buildPublicreportNuisanceWhere[Q psql.Filterable](cols publicreportNuisance
ReporterContactConsent: psql.WhereNull[Q, bool](cols.ReporterContactConsent),
Location: psql.WhereNull[Q, string](cols.Location),
AddressNumber: psql.Where[Q, string](cols.AddressNumber),
AddressID: psql.WhereNull[Q, int32](cols.AddressID),
}
}
@ -1625,6 +1723,18 @@ func (o *PublicreportNuisance) Preload(name string, retrieved any) error {
}
}
return nil
case "Address":
rel, ok := retrieved.(*Address)
if !ok {
return fmt.Errorf("publicreportNuisance cannot load %T as %q", retrieved, name)
}
o.R.Address = rel
if rel != nil {
rel.R.Nuisances = PublicreportNuisanceSlice{o}
}
return nil
case "Organization":
rel, ok := retrieved.(*Organization)
if !ok {
@ -1657,11 +1767,25 @@ func (o *PublicreportNuisance) Preload(name string, retrieved any) error {
}
type publicreportNuisancePreloader struct {
Address func(...psql.PreloadOption) psql.Preloader
Organization func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportNuisancePreloader() publicreportNuisancePreloader {
return publicreportNuisancePreloader{
Address: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*Address, AddressSlice](psql.PreloadRel{
Name: "Address",
Sides: []psql.PreloadSide{
{
From: PublicreportNuisances,
To: Addresses,
FromColumns: []string{"address_id"},
ToColumns: []string{"id"},
},
},
}, Addresses.Columns.Names(), opts...)
},
Organization: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{
Name: "Organization",
@ -1681,6 +1805,7 @@ func buildPublicreportNuisancePreloader() publicreportNuisancePreloader {
type publicreportNuisanceThenLoader[Q orm.Loadable] struct {
NotifyEmailNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
NotifyPhoneNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Address func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Images func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
@ -1692,6 +1817,9 @@ func buildPublicreportNuisanceThenLoader[Q orm.Loadable]() publicreportNuisanceT
type NotifyPhoneNuisancesLoadInterface interface {
LoadNotifyPhoneNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type AddressLoadInterface interface {
LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type OrganizationLoadInterface interface {
LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
@ -1712,6 +1840,12 @@ func buildPublicreportNuisanceThenLoader[Q orm.Loadable]() publicreportNuisanceT
return retrieved.LoadNotifyPhoneNuisances(ctx, exec, mods...)
},
),
Address: thenLoadBuilder[Q](
"Address",
func(ctx context.Context, exec bob.Executor, retrieved AddressLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadAddress(ctx, exec, mods...)
},
),
Organization: thenLoadBuilder[Q](
"Organization",
func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
@ -1849,6 +1983,61 @@ func (os PublicreportNuisanceSlice) LoadNotifyPhoneNuisances(ctx context.Context
return nil
}
// LoadAddress loads the publicreportNuisance's Address into the .R struct
func (o *PublicreportNuisance) LoadAddress(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Address = nil
related, err := o.Address(mods...).One(ctx, exec)
if err != nil {
return err
}
related.R.Nuisances = PublicreportNuisanceSlice{o}
o.R.Address = related
return nil
}
// LoadAddress loads the publicreportNuisance's Address into the .R struct
func (os PublicreportNuisanceSlice) LoadAddress(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
addresses, err := os.Address(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range addresses {
if !o.AddressID.IsValue() {
continue
}
if !(o.AddressID.IsValue() && o.AddressID.MustGet() == rel.ID) {
continue
}
rel.R.Nuisances = append(rel.R.Nuisances, o)
o.R.Address = rel
break
}
}
return nil
}
// LoadOrganization loads the publicreportNuisance's Organization into the .R struct
func (o *PublicreportNuisance) LoadOrganization(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {

View file

@ -1,721 +0,0 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/omit"
)
// PublicreportPoolImage is an object representing the database table.
type PublicreportPoolImage struct {
ImageID int32 `db:"image_id,pk" `
PoolID int32 `db:"pool_id,pk" `
R publicreportPoolImageR `db:"-" `
}
// PublicreportPoolImageSlice is an alias for a slice of pointers to PublicreportPoolImage.
// This should almost always be used instead of []*PublicreportPoolImage.
type PublicreportPoolImageSlice []*PublicreportPoolImage
// PublicreportPoolImages contains methods to work with the pool_image table
var PublicreportPoolImages = psql.NewTablex[*PublicreportPoolImage, PublicreportPoolImageSlice, *PublicreportPoolImageSetter]("publicreport", "pool_image", buildPublicreportPoolImageColumns("publicreport.pool_image"))
// PublicreportPoolImagesQuery is a query on the pool_image table
type PublicreportPoolImagesQuery = *psql.ViewQuery[*PublicreportPoolImage, PublicreportPoolImageSlice]
// publicreportPoolImageR is where relationships are stored.
type publicreportPoolImageR struct {
Image *PublicreportImage // publicreport.pool_image.pool_image_image_id_fkey
Pool *PublicreportPool // publicreport.pool_image.pool_image_pool_id_fkey
}
func buildPublicreportPoolImageColumns(alias string) publicreportPoolImageColumns {
return publicreportPoolImageColumns{
ColumnsExpr: expr.NewColumnsExpr(
"image_id", "pool_id",
).WithParent("publicreport.pool_image"),
tableAlias: alias,
ImageID: psql.Quote(alias, "image_id"),
PoolID: psql.Quote(alias, "pool_id"),
}
}
type publicreportPoolImageColumns struct {
expr.ColumnsExpr
tableAlias string
ImageID psql.Expression
PoolID psql.Expression
}
func (c publicreportPoolImageColumns) Alias() string {
return c.tableAlias
}
func (publicreportPoolImageColumns) AliasedAs(alias string) publicreportPoolImageColumns {
return buildPublicreportPoolImageColumns(alias)
}
// PublicreportPoolImageSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportPoolImageSetter struct {
ImageID omit.Val[int32] `db:"image_id,pk" `
PoolID omit.Val[int32] `db:"pool_id,pk" `
}
func (s PublicreportPoolImageSetter) SetColumns() []string {
vals := make([]string, 0, 2)
if s.ImageID.IsValue() {
vals = append(vals, "image_id")
}
if s.PoolID.IsValue() {
vals = append(vals, "pool_id")
}
return vals
}
func (s PublicreportPoolImageSetter) Overwrite(t *PublicreportPoolImage) {
if s.ImageID.IsValue() {
t.ImageID = s.ImageID.MustGet()
}
if s.PoolID.IsValue() {
t.PoolID = s.PoolID.MustGet()
}
}
func (s *PublicreportPoolImageSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportPoolImages.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 2)
if s.ImageID.IsValue() {
vals[0] = psql.Arg(s.ImageID.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if s.PoolID.IsValue() {
vals[1] = psql.Arg(s.PoolID.MustGet())
} else {
vals[1] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportPoolImageSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportPoolImageSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 2)
if s.ImageID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "image_id")...),
psql.Arg(s.ImageID),
}})
}
if s.PoolID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "pool_id")...),
psql.Arg(s.PoolID),
}})
}
return exprs
}
// FindPublicreportPoolImage retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportPoolImage(ctx context.Context, exec bob.Executor, ImageIDPK int32, PoolIDPK int32, cols ...string) (*PublicreportPoolImage, error) {
if len(cols) == 0 {
return PublicreportPoolImages.Query(
sm.Where(PublicreportPoolImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportPoolImages.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
).One(ctx, exec)
}
return PublicreportPoolImages.Query(
sm.Where(PublicreportPoolImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportPoolImages.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
sm.Columns(PublicreportPoolImages.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportPoolImageExists checks the presence of a single record by primary key
func PublicreportPoolImageExists(ctx context.Context, exec bob.Executor, ImageIDPK int32, PoolIDPK int32) (bool, error) {
return PublicreportPoolImages.Query(
sm.Where(PublicreportPoolImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportPoolImages.Columns.PoolID.EQ(psql.Arg(PoolIDPK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportPoolImage is retrieved from the database
func (o *PublicreportPoolImage) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportPoolImages.AfterSelectHooks.RunHooks(ctx, exec, PublicreportPoolImageSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportPoolImages.AfterInsertHooks.RunHooks(ctx, exec, PublicreportPoolImageSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportPoolImages.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportPoolImageSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportPoolImages.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportPoolImageSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportPoolImage
func (o *PublicreportPoolImage) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.ImageID,
o.PoolID,
)
}
func (o *PublicreportPoolImage) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.pool_image", "image_id"), psql.Quote("publicreport.pool_image", "pool_id")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportPoolImage
func (o *PublicreportPoolImage) Update(ctx context.Context, exec bob.Executor, s *PublicreportPoolImageSetter) error {
v, err := PublicreportPoolImages.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 PublicreportPoolImage record with an executor
func (o *PublicreportPoolImage) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportPoolImages.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportPoolImage using the executor
func (o *PublicreportPoolImage) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportPoolImages.Query(
sm.Where(PublicreportPoolImages.Columns.ImageID.EQ(psql.Arg(o.ImageID))),
sm.Where(PublicreportPoolImages.Columns.PoolID.EQ(psql.Arg(o.PoolID))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportPoolImageSlice is retrieved from the database
func (o PublicreportPoolImageSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportPoolImages.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportPoolImages.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportPoolImages.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportPoolImages.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportPoolImageSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.pool_image", "image_id"), psql.Quote("publicreport.pool_image", "pool_id")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportPoolImageSlice) copyMatchingRows(from ...*PublicreportPoolImage) {
for i, old := range o {
for _, new := range from {
if new.ImageID != old.ImageID {
continue
}
if new.PoolID != old.PoolID {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportPoolImageSlice) 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 PublicreportPoolImages.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 *PublicreportPoolImage:
o.copyMatchingRows(retrieved)
case []*PublicreportPoolImage:
o.copyMatchingRows(retrieved...)
case PublicreportPoolImageSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportPoolImage or a slice of PublicreportPoolImage
// then run the AfterUpdateHooks on the slice
_, err = PublicreportPoolImages.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportPoolImageSlice) 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 PublicreportPoolImages.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 *PublicreportPoolImage:
o.copyMatchingRows(retrieved)
case []*PublicreportPoolImage:
o.copyMatchingRows(retrieved...)
case PublicreportPoolImageSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportPoolImage or a slice of PublicreportPoolImage
// then run the AfterDeleteHooks on the slice
_, err = PublicreportPoolImages.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportPoolImageSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportPoolImageSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportPoolImages.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportPoolImageSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportPoolImages.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportPoolImageSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportPoolImages.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// Image starts a query for related objects on publicreport.image
func (o *PublicreportPoolImage) Image(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
return PublicreportImages.Query(append(mods,
sm.Where(PublicreportImages.Columns.ID.EQ(psql.Arg(o.ImageID))),
)...)
}
func (os PublicreportPoolImageSlice) Image(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
pkImageID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkImageID = append(pkImageID, o.ImageID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkImageID), "integer[]")),
))
return PublicreportImages.Query(append(mods,
sm.Where(psql.Group(PublicreportImages.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
// Pool starts a query for related objects on publicreport.pool
func (o *PublicreportPoolImage) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
return PublicreportPools.Query(append(mods,
sm.Where(PublicreportPools.Columns.ID.EQ(psql.Arg(o.PoolID))),
)...)
}
func (os PublicreportPoolImageSlice) Pool(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportPoolsQuery {
pkPoolID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkPoolID = append(pkPoolID, o.PoolID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkPoolID), "integer[]")),
))
return PublicreportPools.Query(append(mods,
sm.Where(psql.Group(PublicreportPools.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportPoolImageImage0(ctx context.Context, exec bob.Executor, count int, publicreportPoolImage0 *PublicreportPoolImage, publicreportImage1 *PublicreportImage) (*PublicreportPoolImage, error) {
setter := &PublicreportPoolImageSetter{
ImageID: omit.From(publicreportImage1.ID),
}
err := publicreportPoolImage0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportPoolImageImage0: %w", err)
}
return publicreportPoolImage0, nil
}
func (publicreportPoolImage0 *PublicreportPoolImage) InsertImage(ctx context.Context, exec bob.Executor, related *PublicreportImageSetter) error {
var err error
publicreportImage1, err := PublicreportImages.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportPoolImageImage0(ctx, exec, 1, publicreportPoolImage0, publicreportImage1)
if err != nil {
return err
}
publicreportPoolImage0.R.Image = publicreportImage1
return nil
}
func (publicreportPoolImage0 *PublicreportPoolImage) AttachImage(ctx context.Context, exec bob.Executor, publicreportImage1 *PublicreportImage) error {
var err error
_, err = attachPublicreportPoolImageImage0(ctx, exec, 1, publicreportPoolImage0, publicreportImage1)
if err != nil {
return err
}
publicreportPoolImage0.R.Image = publicreportImage1
return nil
}
func attachPublicreportPoolImagePool0(ctx context.Context, exec bob.Executor, count int, publicreportPoolImage0 *PublicreportPoolImage, publicreportPool1 *PublicreportPool) (*PublicreportPoolImage, error) {
setter := &PublicreportPoolImageSetter{
PoolID: omit.From(publicreportPool1.ID),
}
err := publicreportPoolImage0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportPoolImagePool0: %w", err)
}
return publicreportPoolImage0, nil
}
func (publicreportPoolImage0 *PublicreportPoolImage) InsertPool(ctx context.Context, exec bob.Executor, related *PublicreportPoolSetter) error {
var err error
publicreportPool1, err := PublicreportPools.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportPoolImagePool0(ctx, exec, 1, publicreportPoolImage0, publicreportPool1)
if err != nil {
return err
}
publicreportPoolImage0.R.Pool = publicreportPool1
return nil
}
func (publicreportPoolImage0 *PublicreportPoolImage) AttachPool(ctx context.Context, exec bob.Executor, publicreportPool1 *PublicreportPool) error {
var err error
_, err = attachPublicreportPoolImagePool0(ctx, exec, 1, publicreportPoolImage0, publicreportPool1)
if err != nil {
return err
}
publicreportPoolImage0.R.Pool = publicreportPool1
return nil
}
type publicreportPoolImageWhere[Q psql.Filterable] struct {
ImageID psql.WhereMod[Q, int32]
PoolID psql.WhereMod[Q, int32]
}
func (publicreportPoolImageWhere[Q]) AliasedAs(alias string) publicreportPoolImageWhere[Q] {
return buildPublicreportPoolImageWhere[Q](buildPublicreportPoolImageColumns(alias))
}
func buildPublicreportPoolImageWhere[Q psql.Filterable](cols publicreportPoolImageColumns) publicreportPoolImageWhere[Q] {
return publicreportPoolImageWhere[Q]{
ImageID: psql.Where[Q, int32](cols.ImageID),
PoolID: psql.Where[Q, int32](cols.PoolID),
}
}
func (o *PublicreportPoolImage) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "Image":
rel, ok := retrieved.(*PublicreportImage)
if !ok {
return fmt.Errorf("publicreportPoolImage cannot load %T as %q", retrieved, name)
}
o.R.Image = rel
return nil
case "Pool":
rel, ok := retrieved.(*PublicreportPool)
if !ok {
return fmt.Errorf("publicreportPoolImage cannot load %T as %q", retrieved, name)
}
o.R.Pool = rel
return nil
default:
return fmt.Errorf("publicreportPoolImage has no relationship %q", name)
}
}
type publicreportPoolImagePreloader struct {
Image func(...psql.PreloadOption) psql.Preloader
Pool func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportPoolImagePreloader() publicreportPoolImagePreloader {
return publicreportPoolImagePreloader{
Image: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportImage, PublicreportImageSlice](psql.PreloadRel{
Name: "Image",
Sides: []psql.PreloadSide{
{
From: PublicreportPoolImages,
To: PublicreportImages,
FromColumns: []string{"image_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportImages.Columns.Names(), opts...)
},
Pool: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportPool, PublicreportPoolSlice](psql.PreloadRel{
Name: "Pool",
Sides: []psql.PreloadSide{
{
From: PublicreportPoolImages,
To: PublicreportPools,
FromColumns: []string{"pool_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportPools.Columns.Names(), opts...)
},
}
}
type publicreportPoolImageThenLoader[Q orm.Loadable] struct {
Image func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Pool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportPoolImageThenLoader[Q orm.Loadable]() publicreportPoolImageThenLoader[Q] {
type ImageLoadInterface interface {
LoadImage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type PoolLoadInterface interface {
LoadPool(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportPoolImageThenLoader[Q]{
Image: thenLoadBuilder[Q](
"Image",
func(ctx context.Context, exec bob.Executor, retrieved ImageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadImage(ctx, exec, mods...)
},
),
Pool: thenLoadBuilder[Q](
"Pool",
func(ctx context.Context, exec bob.Executor, retrieved PoolLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadPool(ctx, exec, mods...)
},
),
}
}
// LoadImage loads the publicreportPoolImage's Image into the .R struct
func (o *PublicreportPoolImage) LoadImage(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Image = nil
related, err := o.Image(mods...).One(ctx, exec)
if err != nil {
return err
}
o.R.Image = related
return nil
}
// LoadImage loads the publicreportPoolImage's Image into the .R struct
func (os PublicreportPoolImageSlice) LoadImage(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportImages, err := os.Image(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportImages {
if !(o.ImageID == rel.ID) {
continue
}
o.R.Image = rel
break
}
}
return nil
}
// LoadPool loads the publicreportPoolImage's Pool into the .R struct
func (o *PublicreportPoolImage) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Pool = nil
related, err := o.Pool(mods...).One(ctx, exec)
if err != nil {
return err
}
o.R.Pool = related
return nil
}
// LoadPool loads the publicreportPoolImage's Pool into the .R struct
func (os PublicreportPoolImageSlice) LoadPool(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportPools, err := os.Pool(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportPools {
if !(o.PoolID == rel.ID) {
continue
}
o.R.Pool = rel
break
}
}
return nil
}

View file

@ -0,0 +1,721 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"fmt"
"io"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/dialect/psql/dm"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/bob/expr"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/Gleipnir-Technology/bob/types/pgtypes"
"github.com/aarondl/opt/omit"
)
// PublicreportWaterImage is an object representing the database table.
type PublicreportWaterImage struct {
ImageID int32 `db:"image_id,pk" `
WaterID int32 `db:"water_id,pk" `
R publicreportWaterImageR `db:"-" `
}
// PublicreportWaterImageSlice is an alias for a slice of pointers to PublicreportWaterImage.
// This should almost always be used instead of []*PublicreportWaterImage.
type PublicreportWaterImageSlice []*PublicreportWaterImage
// PublicreportWaterImages contains methods to work with the water_image table
var PublicreportWaterImages = psql.NewTablex[*PublicreportWaterImage, PublicreportWaterImageSlice, *PublicreportWaterImageSetter]("publicreport", "water_image", buildPublicreportWaterImageColumns("publicreport.water_image"))
// PublicreportWaterImagesQuery is a query on the water_image table
type PublicreportWaterImagesQuery = *psql.ViewQuery[*PublicreportWaterImage, PublicreportWaterImageSlice]
// publicreportWaterImageR is where relationships are stored.
type publicreportWaterImageR struct {
Image *PublicreportImage // publicreport.water_image.pool_image_image_id_fkey
Water *PublicreportWater // publicreport.water_image.pool_image_pool_id_fkey
}
func buildPublicreportWaterImageColumns(alias string) publicreportWaterImageColumns {
return publicreportWaterImageColumns{
ColumnsExpr: expr.NewColumnsExpr(
"image_id", "water_id",
).WithParent("publicreport.water_image"),
tableAlias: alias,
ImageID: psql.Quote(alias, "image_id"),
WaterID: psql.Quote(alias, "water_id"),
}
}
type publicreportWaterImageColumns struct {
expr.ColumnsExpr
tableAlias string
ImageID psql.Expression
WaterID psql.Expression
}
func (c publicreportWaterImageColumns) Alias() string {
return c.tableAlias
}
func (publicreportWaterImageColumns) AliasedAs(alias string) publicreportWaterImageColumns {
return buildPublicreportWaterImageColumns(alias)
}
// PublicreportWaterImageSetter is used for insert/upsert/update operations
// All values are optional, and do not have to be set
// Generated columns are not included
type PublicreportWaterImageSetter struct {
ImageID omit.Val[int32] `db:"image_id,pk" `
WaterID omit.Val[int32] `db:"water_id,pk" `
}
func (s PublicreportWaterImageSetter) SetColumns() []string {
vals := make([]string, 0, 2)
if s.ImageID.IsValue() {
vals = append(vals, "image_id")
}
if s.WaterID.IsValue() {
vals = append(vals, "water_id")
}
return vals
}
func (s PublicreportWaterImageSetter) Overwrite(t *PublicreportWaterImage) {
if s.ImageID.IsValue() {
t.ImageID = s.ImageID.MustGet()
}
if s.WaterID.IsValue() {
t.WaterID = s.WaterID.MustGet()
}
}
func (s *PublicreportWaterImageSetter) Apply(q *dialect.InsertQuery) {
q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) {
return PublicreportWaterImages.BeforeInsertHooks.RunHooks(ctx, exec, s)
})
q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
vals := make([]bob.Expression, 2)
if s.ImageID.IsValue() {
vals[0] = psql.Arg(s.ImageID.MustGet())
} else {
vals[0] = psql.Raw("DEFAULT")
}
if s.WaterID.IsValue() {
vals[1] = psql.Arg(s.WaterID.MustGet())
} else {
vals[1] = psql.Raw("DEFAULT")
}
return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "")
}))
}
func (s PublicreportWaterImageSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] {
return um.Set(s.Expressions()...)
}
func (s PublicreportWaterImageSetter) Expressions(prefix ...string) []bob.Expression {
exprs := make([]bob.Expression, 0, 2)
if s.ImageID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "image_id")...),
psql.Arg(s.ImageID),
}})
}
if s.WaterID.IsValue() {
exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{
psql.Quote(append(prefix, "water_id")...),
psql.Arg(s.WaterID),
}})
}
return exprs
}
// FindPublicreportWaterImage retrieves a single record by primary key
// If cols is empty Find will return all columns.
func FindPublicreportWaterImage(ctx context.Context, exec bob.Executor, ImageIDPK int32, WaterIDPK int32, cols ...string) (*PublicreportWaterImage, error) {
if len(cols) == 0 {
return PublicreportWaterImages.Query(
sm.Where(PublicreportWaterImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportWaterImages.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
).One(ctx, exec)
}
return PublicreportWaterImages.Query(
sm.Where(PublicreportWaterImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportWaterImages.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
sm.Columns(PublicreportWaterImages.Columns.Only(cols...)),
).One(ctx, exec)
}
// PublicreportWaterImageExists checks the presence of a single record by primary key
func PublicreportWaterImageExists(ctx context.Context, exec bob.Executor, ImageIDPK int32, WaterIDPK int32) (bool, error) {
return PublicreportWaterImages.Query(
sm.Where(PublicreportWaterImages.Columns.ImageID.EQ(psql.Arg(ImageIDPK))),
sm.Where(PublicreportWaterImages.Columns.WaterID.EQ(psql.Arg(WaterIDPK))),
).Exists(ctx, exec)
}
// AfterQueryHook is called after PublicreportWaterImage is retrieved from the database
func (o *PublicreportWaterImage) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportWaterImages.AfterSelectHooks.RunHooks(ctx, exec, PublicreportWaterImageSlice{o})
case bob.QueryTypeInsert:
ctx, err = PublicreportWaterImages.AfterInsertHooks.RunHooks(ctx, exec, PublicreportWaterImageSlice{o})
case bob.QueryTypeUpdate:
ctx, err = PublicreportWaterImages.AfterUpdateHooks.RunHooks(ctx, exec, PublicreportWaterImageSlice{o})
case bob.QueryTypeDelete:
ctx, err = PublicreportWaterImages.AfterDeleteHooks.RunHooks(ctx, exec, PublicreportWaterImageSlice{o})
}
return err
}
// primaryKeyVals returns the primary key values of the PublicreportWaterImage
func (o *PublicreportWaterImage) primaryKeyVals() bob.Expression {
return psql.ArgGroup(
o.ImageID,
o.WaterID,
)
}
func (o *PublicreportWaterImage) pkEQ() dialect.Expression {
return psql.Group(psql.Quote("publicreport.water_image", "image_id"), psql.Quote("publicreport.water_image", "water_id")).EQ(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.primaryKeyVals().WriteSQL(ctx, w, d, start)
}))
}
// Update uses an executor to update the PublicreportWaterImage
func (o *PublicreportWaterImage) Update(ctx context.Context, exec bob.Executor, s *PublicreportWaterImageSetter) error {
v, err := PublicreportWaterImages.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 PublicreportWaterImage record with an executor
func (o *PublicreportWaterImage) Delete(ctx context.Context, exec bob.Executor) error {
_, err := PublicreportWaterImages.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec)
return err
}
// Reload refreshes the PublicreportWaterImage using the executor
func (o *PublicreportWaterImage) Reload(ctx context.Context, exec bob.Executor) error {
o2, err := PublicreportWaterImages.Query(
sm.Where(PublicreportWaterImages.Columns.ImageID.EQ(psql.Arg(o.ImageID))),
sm.Where(PublicreportWaterImages.Columns.WaterID.EQ(psql.Arg(o.WaterID))),
).One(ctx, exec)
if err != nil {
return err
}
o2.R = o.R
*o = *o2
return nil
}
// AfterQueryHook is called after PublicreportWaterImageSlice is retrieved from the database
func (o PublicreportWaterImageSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error {
var err error
switch queryType {
case bob.QueryTypeSelect:
ctx, err = PublicreportWaterImages.AfterSelectHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeInsert:
ctx, err = PublicreportWaterImages.AfterInsertHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeUpdate:
ctx, err = PublicreportWaterImages.AfterUpdateHooks.RunHooks(ctx, exec, o)
case bob.QueryTypeDelete:
ctx, err = PublicreportWaterImages.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}
func (o PublicreportWaterImageSlice) pkIN() dialect.Expression {
if len(o) == 0 {
return psql.Raw("NULL")
}
return psql.Group(psql.Quote("publicreport.water_image", "image_id"), psql.Quote("publicreport.water_image", "water_id")).In(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
pkPairs := make([]bob.Expression, len(o))
for i, row := range o {
pkPairs[i] = row.primaryKeyVals()
}
return bob.ExpressSlice(ctx, w, d, start, pkPairs, "", ", ", "")
}))
}
// copyMatchingRows finds models in the given slice that have the same primary key
// then it first copies the existing relationships from the old model to the new model
// and then replaces the old model in the slice with the new model
func (o PublicreportWaterImageSlice) copyMatchingRows(from ...*PublicreportWaterImage) {
for i, old := range o {
for _, new := range from {
if new.ImageID != old.ImageID {
continue
}
if new.WaterID != old.WaterID {
continue
}
new.R = old.R
o[i] = new
break
}
}
}
// UpdateMod modifies an update query with "WHERE primary_key IN (o...)"
func (o PublicreportWaterImageSlice) 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 PublicreportWaterImages.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 *PublicreportWaterImage:
o.copyMatchingRows(retrieved)
case []*PublicreportWaterImage:
o.copyMatchingRows(retrieved...)
case PublicreportWaterImageSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportWaterImage or a slice of PublicreportWaterImage
// then run the AfterUpdateHooks on the slice
_, err = PublicreportWaterImages.AfterUpdateHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)"
func (o PublicreportWaterImageSlice) 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 PublicreportWaterImages.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 *PublicreportWaterImage:
o.copyMatchingRows(retrieved)
case []*PublicreportWaterImage:
o.copyMatchingRows(retrieved...)
case PublicreportWaterImageSlice:
o.copyMatchingRows(retrieved...)
default:
// If the retrieved value is not a PublicreportWaterImage or a slice of PublicreportWaterImage
// then run the AfterDeleteHooks on the slice
_, err = PublicreportWaterImages.AfterDeleteHooks.RunHooks(ctx, exec, o)
}
return err
}))
q.AppendWhere(o.pkIN())
})
}
func (o PublicreportWaterImageSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals PublicreportWaterImageSetter) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportWaterImages.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec)
return err
}
func (o PublicreportWaterImageSlice) DeleteAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
_, err := PublicreportWaterImages.Delete(o.DeleteMod()).Exec(ctx, exec)
return err
}
func (o PublicreportWaterImageSlice) ReloadAll(ctx context.Context, exec bob.Executor) error {
if len(o) == 0 {
return nil
}
o2, err := PublicreportWaterImages.Query(sm.Where(o.pkIN())).All(ctx, exec)
if err != nil {
return err
}
o.copyMatchingRows(o2...)
return nil
}
// Image starts a query for related objects on publicreport.image
func (o *PublicreportWaterImage) Image(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
return PublicreportImages.Query(append(mods,
sm.Where(PublicreportImages.Columns.ID.EQ(psql.Arg(o.ImageID))),
)...)
}
func (os PublicreportWaterImageSlice) Image(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportImagesQuery {
pkImageID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkImageID = append(pkImageID, o.ImageID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkImageID), "integer[]")),
))
return PublicreportImages.Query(append(mods,
sm.Where(psql.Group(PublicreportImages.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
// Water starts a query for related objects on publicreport.water
func (o *PublicreportWaterImage) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
return PublicreportWaters.Query(append(mods,
sm.Where(PublicreportWaters.Columns.ID.EQ(psql.Arg(o.WaterID))),
)...)
}
func (os PublicreportWaterImageSlice) Water(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportWatersQuery {
pkWaterID := make(pgtypes.Array[int32], 0, len(os))
for _, o := range os {
if o == nil {
continue
}
pkWaterID = append(pkWaterID, o.WaterID)
}
PKArgExpr := psql.Select(sm.Columns(
psql.F("unnest", psql.Cast(psql.Arg(pkWaterID), "integer[]")),
))
return PublicreportWaters.Query(append(mods,
sm.Where(psql.Group(PublicreportWaters.Columns.ID).OP("IN", PKArgExpr)),
)...)
}
func attachPublicreportWaterImageImage0(ctx context.Context, exec bob.Executor, count int, publicreportWaterImage0 *PublicreportWaterImage, publicreportImage1 *PublicreportImage) (*PublicreportWaterImage, error) {
setter := &PublicreportWaterImageSetter{
ImageID: omit.From(publicreportImage1.ID),
}
err := publicreportWaterImage0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportWaterImageImage0: %w", err)
}
return publicreportWaterImage0, nil
}
func (publicreportWaterImage0 *PublicreportWaterImage) InsertImage(ctx context.Context, exec bob.Executor, related *PublicreportImageSetter) error {
var err error
publicreportImage1, err := PublicreportImages.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportWaterImageImage0(ctx, exec, 1, publicreportWaterImage0, publicreportImage1)
if err != nil {
return err
}
publicreportWaterImage0.R.Image = publicreportImage1
return nil
}
func (publicreportWaterImage0 *PublicreportWaterImage) AttachImage(ctx context.Context, exec bob.Executor, publicreportImage1 *PublicreportImage) error {
var err error
_, err = attachPublicreportWaterImageImage0(ctx, exec, 1, publicreportWaterImage0, publicreportImage1)
if err != nil {
return err
}
publicreportWaterImage0.R.Image = publicreportImage1
return nil
}
func attachPublicreportWaterImageWater0(ctx context.Context, exec bob.Executor, count int, publicreportWaterImage0 *PublicreportWaterImage, publicreportWater1 *PublicreportWater) (*PublicreportWaterImage, error) {
setter := &PublicreportWaterImageSetter{
WaterID: omit.From(publicreportWater1.ID),
}
err := publicreportWaterImage0.Update(ctx, exec, setter)
if err != nil {
return nil, fmt.Errorf("attachPublicreportWaterImageWater0: %w", err)
}
return publicreportWaterImage0, nil
}
func (publicreportWaterImage0 *PublicreportWaterImage) InsertWater(ctx context.Context, exec bob.Executor, related *PublicreportWaterSetter) error {
var err error
publicreportWater1, err := PublicreportWaters.Insert(related).One(ctx, exec)
if err != nil {
return fmt.Errorf("inserting related objects: %w", err)
}
_, err = attachPublicreportWaterImageWater0(ctx, exec, 1, publicreportWaterImage0, publicreportWater1)
if err != nil {
return err
}
publicreportWaterImage0.R.Water = publicreportWater1
return nil
}
func (publicreportWaterImage0 *PublicreportWaterImage) AttachWater(ctx context.Context, exec bob.Executor, publicreportWater1 *PublicreportWater) error {
var err error
_, err = attachPublicreportWaterImageWater0(ctx, exec, 1, publicreportWaterImage0, publicreportWater1)
if err != nil {
return err
}
publicreportWaterImage0.R.Water = publicreportWater1
return nil
}
type publicreportWaterImageWhere[Q psql.Filterable] struct {
ImageID psql.WhereMod[Q, int32]
WaterID psql.WhereMod[Q, int32]
}
func (publicreportWaterImageWhere[Q]) AliasedAs(alias string) publicreportWaterImageWhere[Q] {
return buildPublicreportWaterImageWhere[Q](buildPublicreportWaterImageColumns(alias))
}
func buildPublicreportWaterImageWhere[Q psql.Filterable](cols publicreportWaterImageColumns) publicreportWaterImageWhere[Q] {
return publicreportWaterImageWhere[Q]{
ImageID: psql.Where[Q, int32](cols.ImageID),
WaterID: psql.Where[Q, int32](cols.WaterID),
}
}
func (o *PublicreportWaterImage) Preload(name string, retrieved any) error {
if o == nil {
return nil
}
switch name {
case "Image":
rel, ok := retrieved.(*PublicreportImage)
if !ok {
return fmt.Errorf("publicreportWaterImage cannot load %T as %q", retrieved, name)
}
o.R.Image = rel
return nil
case "Water":
rel, ok := retrieved.(*PublicreportWater)
if !ok {
return fmt.Errorf("publicreportWaterImage cannot load %T as %q", retrieved, name)
}
o.R.Water = rel
return nil
default:
return fmt.Errorf("publicreportWaterImage has no relationship %q", name)
}
}
type publicreportWaterImagePreloader struct {
Image func(...psql.PreloadOption) psql.Preloader
Water func(...psql.PreloadOption) psql.Preloader
}
func buildPublicreportWaterImagePreloader() publicreportWaterImagePreloader {
return publicreportWaterImagePreloader{
Image: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportImage, PublicreportImageSlice](psql.PreloadRel{
Name: "Image",
Sides: []psql.PreloadSide{
{
From: PublicreportWaterImages,
To: PublicreportImages,
FromColumns: []string{"image_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportImages.Columns.Names(), opts...)
},
Water: func(opts ...psql.PreloadOption) psql.Preloader {
return psql.Preload[*PublicreportWater, PublicreportWaterSlice](psql.PreloadRel{
Name: "Water",
Sides: []psql.PreloadSide{
{
From: PublicreportWaterImages,
To: PublicreportWaters,
FromColumns: []string{"water_id"},
ToColumns: []string{"id"},
},
},
}, PublicreportWaters.Columns.Names(), opts...)
},
}
}
type publicreportWaterImageThenLoader[Q orm.Loadable] struct {
Image func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
Water func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q]
}
func buildPublicreportWaterImageThenLoader[Q orm.Loadable]() publicreportWaterImageThenLoader[Q] {
type ImageLoadInterface interface {
LoadImage(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
type WaterLoadInterface interface {
LoadWater(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error
}
return publicreportWaterImageThenLoader[Q]{
Image: thenLoadBuilder[Q](
"Image",
func(ctx context.Context, exec bob.Executor, retrieved ImageLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadImage(ctx, exec, mods...)
},
),
Water: thenLoadBuilder[Q](
"Water",
func(ctx context.Context, exec bob.Executor, retrieved WaterLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error {
return retrieved.LoadWater(ctx, exec, mods...)
},
),
}
}
// LoadImage loads the publicreportWaterImage's Image into the .R struct
func (o *PublicreportWaterImage) LoadImage(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Image = nil
related, err := o.Image(mods...).One(ctx, exec)
if err != nil {
return err
}
o.R.Image = related
return nil
}
// LoadImage loads the publicreportWaterImage's Image into the .R struct
func (os PublicreportWaterImageSlice) LoadImage(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportImages, err := os.Image(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportImages {
if !(o.ImageID == rel.ID) {
continue
}
o.R.Image = rel
break
}
}
return nil
}
// LoadWater loads the publicreportWaterImage's Water into the .R struct
func (o *PublicreportWaterImage) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if o == nil {
return nil
}
// Reset the relationship
o.R.Water = nil
related, err := o.Water(mods...).One(ctx, exec)
if err != nil {
return err
}
o.R.Water = related
return nil
}
// LoadWater loads the publicreportWaterImage's Water into the .R struct
func (os PublicreportWaterImageSlice) LoadWater(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error {
if len(os) == 0 {
return nil
}
publicreportWaters, err := os.Water(mods...).All(ctx, exec)
if err != nil {
return err
}
for _, o := range os {
if o == nil {
continue
}
for _, rel := range publicreportWaters {
if !(o.WaterID == rel.ID) {
continue
}
o.R.Water = rel
break
}
}
return nil
}

View file

@ -1,112 +0,0 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sql
import (
"context"
_ "embed"
"io"
"iter"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/aarondl/opt/null"
"github.com/google/uuid"
"github.com/stephenafamo/scan"
)
//go:embed publicreport_image_with_json_by_pool_id.bob.sql
var formattedQueries_publicreport_image_with_json_by_pool_id string
var publicreportImageWithJSONByPoolIDSQL = formattedQueries_publicreport_image_with_json_by_pool_id[171:975]
type PublicreportImageWithJSONByPoolIDQuery = orm.ModQuery[*dialect.SelectQuery, publicreportImageWithJSONByPoolID, PublicreportImageWithJSONByPoolIDRow, []PublicreportImageWithJSONByPoolIDRow, publicreportImageWithJSONByPoolIDTransformer]
func PublicreportImageWithJSONByPoolID(PoolID int32) *PublicreportImageWithJSONByPoolIDQuery {
var expressionTypArgs publicreportImageWithJSONByPoolID
expressionTypArgs.PoolID = psql.Arg(PoolID)
return &PublicreportImageWithJSONByPoolIDQuery{
Query: orm.Query[publicreportImageWithJSONByPoolID, PublicreportImageWithJSONByPoolIDRow, []PublicreportImageWithJSONByPoolIDRow, publicreportImageWithJSONByPoolIDTransformer]{
ExecQuery: orm.ExecQuery[publicreportImageWithJSONByPoolID]{
BaseQuery: bob.BaseQuery[publicreportImageWithJSONByPoolID]{
Expression: expressionTypArgs,
Dialect: dialect.Dialect,
QueryType: bob.QueryTypeSelect,
},
},
Scanner: func(context.Context, []string) (func(*scan.Row) (any, error), func(any) (PublicreportImageWithJSONByPoolIDRow, error)) {
return func(row *scan.Row) (any, error) {
var t PublicreportImageWithJSONByPoolIDRow
row.ScheduleScanByIndex(0, &t.ID)
row.ScheduleScanByIndex(1, &t.ContentType)
row.ScheduleScanByIndex(2, &t.Created)
row.ScheduleScanByIndex(3, &t.Location)
row.ScheduleScanByIndex(4, &t.LocationJSON)
row.ScheduleScanByIndex(5, &t.ResolutionX)
row.ScheduleScanByIndex(6, &t.ResolutionY)
row.ScheduleScanByIndex(7, &t.StorageUUID)
row.ScheduleScanByIndex(8, &t.StorageSize)
row.ScheduleScanByIndex(9, &t.UploadedFilename)
return &t, nil
}, func(v any) (PublicreportImageWithJSONByPoolIDRow, error) {
return *(v.(*PublicreportImageWithJSONByPoolIDRow)), nil
}
},
},
Mod: bob.ModFunc[*dialect.SelectQuery](func(q *dialect.SelectQuery) {
q.AppendSelect(expressionTypArgs.subExpr(9, 565))
q.SetTable(expressionTypArgs.subExpr(571, 755))
q.AppendWhere(expressionTypArgs.subExpr(763, 803))
}),
}
}
type PublicreportImageWithJSONByPoolIDRow = struct {
ID int32 `db:"id"`
ContentType string `db:"content_type"`
Created time.Time `db:"created"`
Location null.Val[string] `db:"location"`
LocationJSON string `db:"location_json"`
ResolutionX int32 `db:"resolution_x"`
ResolutionY int32 `db:"resolution_y"`
StorageUUID uuid.UUID `db:"storage_uuid"`
StorageSize int64 `db:"storage_size"`
UploadedFilename string `db:"uploaded_filename"`
}
type publicreportImageWithJSONByPoolIDTransformer = bob.SliceTransformer[PublicreportImageWithJSONByPoolIDRow, []PublicreportImageWithJSONByPoolIDRow]
type publicreportImageWithJSONByPoolID struct {
PoolID bob.Expression
}
func (o publicreportImageWithJSONByPoolID) args() iter.Seq[orm.ArgWithPosition] {
return func(yield func(arg orm.ArgWithPosition) bool) {
if !yield(orm.ArgWithPosition{
Name: "poolID",
Start: 801,
Stop: 803,
Expression: o.PoolID,
}) {
return
}
}
}
func (o publicreportImageWithJSONByPoolID) raw(from, to int) string {
return publicreportImageWithJSONByPoolIDSQL[from:to]
}
func (o publicreportImageWithJSONByPoolID) subExpr(from, to int) bob.Expression {
return orm.ArgsToExpression(publicreportImageWithJSONByPoolIDSQL, from, to, o.args())
}
func (o publicreportImageWithJSONByPoolID) WriteSQL(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.subExpr(0, len(publicreportImageWithJSONByPoolIDSQL)).WriteSQL(ctx, w, d, start)
}

View file

@ -1,18 +0,0 @@
-- Code generated by BobGen psql v0.42.5. DO NOT EDIT.
-- This file is meant to be re-generated in place and/or deleted at any time.
-- PublicreportImageWithJSONByPoolID
SELECT
"publicreport.image"."id" AS "id",
"publicreport.image"."content_type" AS "content_type",
"publicreport.image"."created" AS "created",
"publicreport.image"."location" AS "location",
COALESCE(ST_AsGeoJSON("publicreport.image"."location"), '{}') AS "location_json",
"publicreport.image"."resolution_x" AS "resolution_x",
"publicreport.image"."resolution_y" AS "resolution_y",
"publicreport.image"."storage_uuid" AS "storage_uuid",
"publicreport.image"."storage_size" AS "storage_size",
"publicreport.image"."uploaded_filename" AS "uploaded_filename"
FROM "publicreport"."image" AS "publicreport.image"
INNER JOIN "publicreport"."pool_image" AS "publicreport.pool_image" ON ("publicreport.image"."id" = "publicreport.pool_image"."image_id")
WHERE ("publicreport.pool_image"."pool_id" = $1);

View file

@ -0,0 +1,112 @@
// Code generated by BobGen psql v0.42.5. DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package sql
import (
"context"
_ "embed"
"io"
"iter"
"time"
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/dialect"
"github.com/Gleipnir-Technology/bob/orm"
"github.com/aarondl/opt/null"
"github.com/google/uuid"
"github.com/stephenafamo/scan"
)
//go:embed publicreport_image_with_json_by_water_id.bob.sql
var formattedQueries_publicreport_image_with_json_by_water_id string
var publicreportImageWithJSONByWaterIDSQL = formattedQueries_publicreport_image_with_json_by_water_id[172:981]
type PublicreportImageWithJSONByWaterIDQuery = orm.ModQuery[*dialect.SelectQuery, publicreportImageWithJSONByWaterID, PublicreportImageWithJSONByWaterIDRow, []PublicreportImageWithJSONByWaterIDRow, publicreportImageWithJSONByWaterIDTransformer]
func PublicreportImageWithJSONByWaterID(WaterID int32) *PublicreportImageWithJSONByWaterIDQuery {
var expressionTypArgs publicreportImageWithJSONByWaterID
expressionTypArgs.WaterID = psql.Arg(WaterID)
return &PublicreportImageWithJSONByWaterIDQuery{
Query: orm.Query[publicreportImageWithJSONByWaterID, PublicreportImageWithJSONByWaterIDRow, []PublicreportImageWithJSONByWaterIDRow, publicreportImageWithJSONByWaterIDTransformer]{
ExecQuery: orm.ExecQuery[publicreportImageWithJSONByWaterID]{
BaseQuery: bob.BaseQuery[publicreportImageWithJSONByWaterID]{
Expression: expressionTypArgs,
Dialect: dialect.Dialect,
QueryType: bob.QueryTypeSelect,
},
},
Scanner: func(context.Context, []string) (func(*scan.Row) (any, error), func(any) (PublicreportImageWithJSONByWaterIDRow, error)) {
return func(row *scan.Row) (any, error) {
var t PublicreportImageWithJSONByWaterIDRow
row.ScheduleScanByIndex(0, &t.ID)
row.ScheduleScanByIndex(1, &t.ContentType)
row.ScheduleScanByIndex(2, &t.Created)
row.ScheduleScanByIndex(3, &t.Location)
row.ScheduleScanByIndex(4, &t.LocationJSON)
row.ScheduleScanByIndex(5, &t.ResolutionX)
row.ScheduleScanByIndex(6, &t.ResolutionY)
row.ScheduleScanByIndex(7, &t.StorageUUID)
row.ScheduleScanByIndex(8, &t.StorageSize)
row.ScheduleScanByIndex(9, &t.UploadedFilename)
return &t, nil
}, func(v any) (PublicreportImageWithJSONByWaterIDRow, error) {
return *(v.(*PublicreportImageWithJSONByWaterIDRow)), nil
}
},
},
Mod: bob.ModFunc[*dialect.SelectQuery](func(q *dialect.SelectQuery) {
q.AppendSelect(expressionTypArgs.subExpr(9, 565))
q.SetTable(expressionTypArgs.subExpr(571, 758))
q.AppendWhere(expressionTypArgs.subExpr(766, 808))
}),
}
}
type PublicreportImageWithJSONByWaterIDRow = struct {
ID int32 `db:"id"`
ContentType string `db:"content_type"`
Created time.Time `db:"created"`
Location null.Val[string] `db:"location"`
LocationJSON string `db:"location_json"`
ResolutionX int32 `db:"resolution_x"`
ResolutionY int32 `db:"resolution_y"`
StorageUUID uuid.UUID `db:"storage_uuid"`
StorageSize int64 `db:"storage_size"`
UploadedFilename string `db:"uploaded_filename"`
}
type publicreportImageWithJSONByWaterIDTransformer = bob.SliceTransformer[PublicreportImageWithJSONByWaterIDRow, []PublicreportImageWithJSONByWaterIDRow]
type publicreportImageWithJSONByWaterID struct {
WaterID bob.Expression
}
func (o publicreportImageWithJSONByWaterID) args() iter.Seq[orm.ArgWithPosition] {
return func(yield func(arg orm.ArgWithPosition) bool) {
if !yield(orm.ArgWithPosition{
Name: "waterID",
Start: 806,
Stop: 808,
Expression: o.WaterID,
}) {
return
}
}
}
func (o publicreportImageWithJSONByWaterID) raw(from, to int) string {
return publicreportImageWithJSONByWaterIDSQL[from:to]
}
func (o publicreportImageWithJSONByWaterID) subExpr(from, to int) bob.Expression {
return orm.ArgsToExpression(publicreportImageWithJSONByWaterIDSQL, from, to, o.args())
}
func (o publicreportImageWithJSONByWaterID) WriteSQL(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) {
return o.subExpr(0, len(publicreportImageWithJSONByWaterIDSQL)).WriteSQL(ctx, w, d, start)
}

View file

@ -1,4 +1,4 @@
-- PublicreportImageWithJSONByPoolID
-- PublicreportImageWithJSONByWaterID
SELECT
"publicreport.image"."id" AS "id",
"publicreport.image"."content_type" AS "content_type",
@ -11,5 +11,5 @@ SELECT
"publicreport.image"."storage_size" AS "storage_size",
"publicreport.image"."uploaded_filename" AS "uploaded_filename"
FROM "publicreport"."image" AS "publicreport.image"
INNER JOIN "publicreport"."pool_image" AS "publicreport.pool_image" ON ("publicreport.image"."id" = "publicreport.pool_image"."image_id")
WHERE ("publicreport.pool_image"."pool_id" = $1)
INNER JOIN "publicreport"."water_image" AS "publicreport.water_image" ON ("publicreport.image"."id" = "publicreport.water_image"."image_id")
WHERE ("publicreport.water_image"."water_id" = $1)

View file

@ -21,7 +21,7 @@ import (
//go:embed publicreport_publicid_suggestion.bob.sql
var formattedQueries_publicreport_publicid_suggestion string
var publicreportPublicIDSuggestionSQL = formattedQueries_publicreport_publicid_suggestion[168:426]
var publicreportPublicIDSuggestionSQL = formattedQueries_publicreport_publicid_suggestion[168:428]
type PublicreportPublicIDSuggestionQuery = orm.ModQuery[*dialect.SelectQuery, publicreportPublicIDSuggestion, PublicreportPublicIDSuggestionRow, []PublicreportPublicIDSuggestionRow, publicreportPublicIDSuggestionTransformer]
@ -60,12 +60,12 @@ func PublicreportPublicIDSuggestion(Arg1 string) *PublicreportPublicIDSuggestion
Strategy: "UNION",
All: true,
Query: bob.BaseQuery[bob.Expression]{
Expression: expressionTypArgs.subExpr(129, 237),
Expression: expressionTypArgs.subExpr(129, 239),
QueryType: bob.QueryTypeSelect,
Dialect: dialect.Dialect,
},
})
q.CombinedOrder.AppendOrder(expressionTypArgs.subExpr(249, 258))
q.CombinedOrder.AppendOrder(expressionTypArgs.subExpr(251, 260))
}),
}
}
@ -95,8 +95,8 @@ func (o publicreportPublicIDSuggestion) args() iter.Seq[orm.ArgWithPosition] {
if !yield(orm.ArgWithPosition{
Name: "arg1",
Start: 235,
Stop: 237,
Start: 237,
Stop: 239,
Expression: o.Arg1,
}) {
return

View file

@ -14,11 +14,11 @@ WHERE
UNION ALL
SELECT
'pool' AS table_name,
'water' AS table_name,
public_id,
location
FROM
publicreport.pool
publicreport.water
WHERE
public_id LIKE $2
ORDER BY

View file

@ -11,11 +11,11 @@ WHERE
UNION ALL
SELECT
'pool' AS table_name,
'water' AS table_name,
public_id,
location
FROM
publicreport.pool
publicreport.water
WHERE
public_id LIKE $1
ORDER BY

View file

@ -20,7 +20,7 @@ import (
//go:embed publicreport_publicid_table.bob.sql
var formattedQueries_publicreport_publicid_table string
var publicreportIDTableSQL = formattedQueries_publicreport_publicid_table[157:534]
var publicreportIDTableSQL = formattedQueries_publicreport_publicid_table[157:536]
type PublicreportIDTableQuery = orm.ModQuery[*dialect.SelectQuery, publicreportIDTable, PublicreportIDTableRow, []PublicreportIDTableRow, publicreportIDTableTransformer]
@ -51,9 +51,9 @@ func PublicreportIDTable(PublicID string) *PublicreportIDTableQuery {
},
},
Mod: bob.ModFunc[*dialect.SelectQuery](func(q *dialect.SelectQuery) {
q.AppendCTE(expressionTypArgs.subExpr(5, 221))
q.AppendSelect(expressionTypArgs.subExpr(231, 359))
q.SetTable(expressionTypArgs.subExpr(365, 377))
q.AppendCTE(expressionTypArgs.subExpr(5, 223))
q.AppendSelect(expressionTypArgs.subExpr(233, 361))
q.SetTable(expressionTypArgs.subExpr(367, 379))
}),
}
}
@ -83,8 +83,8 @@ func (o publicreportIDTable) args() iter.Seq[orm.ArgWithPosition] {
if !yield(orm.ArgWithPosition{
Name: "publicID",
Start: 217,
Stop: 219,
Start: 219,
Stop: 221,
Expression: o.PublicID,
}) {
return

View file

@ -12,9 +12,9 @@ WITH found_tables AS (
UNION ALL
SELECT
'pool' as table_name,
'water' as table_name,
id
FROM publicreport.pool
FROM publicreport.water
WHERE public_id = $2
)
SELECT

View file

@ -9,9 +9,9 @@ WITH found_tables AS (
UNION ALL
SELECT
'pool' as table_name,
'water' as table_name,
id
FROM publicreport.pool
FROM publicreport.water
WHERE public_id = $1
)
SELECT

View file

@ -269,7 +269,7 @@ function _formatReportID(id) {
function _formatReportType(type) {
if (type == "nuisance") {
return "Mosquito Nuisance Report";
} else if (type == "pool") {
} else if (type == "water") {
return "Standing Water Report";
} else {
return "Unknown Report Type";

View file

@ -35,7 +35,7 @@ class ReportTable extends HTMLElement {
return "bg-danger";
case "quick":
return "bg-primary";
case "pool":
case "water":
return "bg-success";
default:
return "bg-secondary";

View file

@ -1,2 +0,0 @@
{{ define "rmo/component/map-header.html" }}
{{ end }}

View file

@ -1,87 +0,0 @@
{{ define "rmo/component/map.html" }}
<script src="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.js"></script>
<link
href="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.css"
rel="stylesheet"
/>
<script>
const geojson = JSON.parse({{.GeoJSON}})
function addMarkers(map, markers) {
for (let i = 0; i < markers.length; i++) {
let marker = markers[i];
marker.addTo(map);
}
}
function mapMarkers() {
const markers = [
{{ range .Markers }}
new mapboxgl.Marker().setLngLat([{{.LatLng.Lng}}, {{.LatLng.Lat}}])
{{end}}
];
return markers;
}
function onLoad() {
console.log("Setting up the map...", geojson);
mapboxgl.accessToken = {{ .MapboxToken }};
const map = new mapboxgl.Map({
container: "map",
center: [{{.Center.Lng}}, {{.Center.Lat}}],
style: 'mapbox://styles/mapbox/streets-v12', // style URL
zoom: {{.Zoom}},
});
map.on("load", function() {
console.log("Map post-load...");
addMarkers(map, mapMarkers());
const sourceId = 'h3-hexes';
const layerId = 'h3-hexes-layer';
let source = map.getSource(sourceId);
if (!source) {
map.addSource(sourceId, {
type: 'geojson',
data: geojson
});
map.addLayer({
id: layerId,
source: sourceId,
type: 'fill',
interactive: false,
paint: {
'fill-color': '#F00000',
'fill-opacity': 0.3
}
});
source = map.getSource(sourceId);
}
source.setData(geojson);
console.log("Map post-load done.");
});
console.log("Map init done.");
}
window.addEventListener("load", onLoad);
</script>
<style>
.map-container {
background-color: #e9ecef;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
height: 500px;
display: flex;
align-items: center;
justify-content: center;
margin-top: 20px;
}
#map {
height: 500px;
width: 100%;
margin-bottom: 10px;
}
#map img {
max-width: none;
min-width: 0px;
height: auto;
}
</style>
{{ end }}

View file

@ -1,525 +0,0 @@
{{ template "base.html" . }}
{{ define "title" }}Nuisance{{ end }}
{{ define "extraheader" }}
<script src="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.js"></script>
<script src="/static/js/address-display.js"></script>
<script src="/static/js/address-suggestion.js"></script>
<script src="/static/js/geocode.js"></script>
<script src="/static/js/location.js"></script>
<script src="/static/js/map-locator.js"></script>
{{ template "photo-upload-header" }}
<script>
const MAPBOX_ACCESS_TOKEN = "{{.MapboxToken}}";
// Handle inspection type selection
function selectInspectionType(type) {
// Remove selected class from both cards
document.getElementById('propertyInspection').classList.remove('selected');
document.getElementById('neighborhoodInspection').classList.remove('selected');
// Add selected class to chosen card
if (type === 'property') {
document.getElementById('propertyInspection').classList.add('selected');
document.getElementById('inspectionTypeProperty').checked = true;
document.getElementById('schedulingSection').style.display = 'block';
} else {
document.getElementById('neighborhoodInspection').classList.add('selected');
document.getElementById('inspectionTypeNeighborhood').checked = true;
document.getElementById('schedulingSection').style.display = 'none';
}
}
function toggleCollapse(something) {
el = document.getElementById(something)
if (el.classList.contains('collapse')) {
el.classList.remove('collapse');
} else {
el.classList.add('collapse');
}
document.getElementById("toggle-additional").classList.add("visually-hidden");
}
// Check for source identification
document.addEventListener('DOMContentLoaded', function() {
const sourceCheckboxes = [
document.getElementById('sourceStagnantWater'),
document.getElementById('sourceContainers'),
document.getElementById('sourceGutters')
];
const sourceAlert = document.getElementById('sourceFoundAlert');
sourceCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
// If any source is checked, show the alert
if (sourceCheckboxes.some(cb => cb.checked)) {
sourceAlert.style.display = 'block';
} else {
sourceAlert.style.display = 'none';
}
});
});
// Elements
const photoInput = document.getElementById('photos');
// Handle photo selection
photoInput.addEventListener('change', handlePhotoSelection);
// Handle drag and drop
const photoDropArea = document.getElementById('photoDropArea');
photoDropArea.addEventListener('dragover', function(e) {
e.preventDefault();
photoDropArea.style.backgroundColor = '#e9ecef';
});
photoDropArea.addEventListener('dragleave', function() {
photoDropArea.style.backgroundColor = '#f8f9fa';
});
photoDropArea.addEventListener('drop', function(e) {
e.preventDefault();
photoDropArea.style.backgroundColor = '#f8f9fa';
if (e.dataTransfer.files.length) {
handleFiles(e.dataTransfer.files);
}
});
const mapLocator = document.querySelector("map-locator");
mapLocator.addEventListener("load", (event) => {
getGeolocation({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}).then(position => {
mapLocator.jumpTo({
center: {
lng: position.coords.longitude,
lat: position.coords.latitude,
},
zoom: 14,
});
mapLocator.setMarker([
position.coords.longitude,
position.coords.latitude,
]);
geocodeReverse(MAPBOX_ACCESS_TOKEN, {
lat: position.coords.latitude,
lng: position.coords.longitude,
});
}).catch(error => {
console.log("location error", error);
})
})
//mapLocator.addEventListener("markerdragend",
let mapZoom = document.getElementById('map-zoom');
mapLocator.addEventListener("zoomend", function(e) {
mapZoom.value = e.target.getZoom();
});
mapLocator.addEventListener("markerdragend", (e) => {
const lngLat = marker.getLngLat();
//displaySelectedCoordinates(lngLat);
geocodeReverse(MAPBOX_ACCESS_TOKEN, lngLat);
});
const addressDisplay = document.querySelector("address-display");
const addressInput = document.querySelector("address-input");
addressInput.addEventListener("address-selected", (event) => {
const l = event.detail.location;
console.log("Address selected", l);
// Center map on selected address
mapSetMarker(l.geometry.coordinates);
mapJumpTo({
center: l.geometry.coordinates,
zoom: 14,
});
addressDisplay.show(l);
setLocationInputs(l);
});
});
</script>
<style></style>
{{ end }}
{{ define "content" }}
{{ if .District }}
{{ template "header" . }}
{{ end }}
<div class="container">
<div class="row mb-4">
<div class="col-12">
<h2>Report Mosquito Nuisance</h2>
<p class="lead">Help us identify mosquito activity in your area</p>
</div>
</div>
<!-- Report Form -->
<form id="mosquitoNuisanceForm" action="/nuisance-submit" method="POST">
<!-- Location & Contact Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-geo-alt"></i>
<h3>Nuisance Location Information</h3>
</div>
<div class="col-md-12">
<div class="alert alert-info" role="info">
<p class="mb-0">
You can select the location by address or by moving the marker on
the map.
</p>
</div>
</div>
<div class="col-md-6">
<div class="mb-3 position-relative">
<address-input
placeholder="Start typing an address (min 3 characters)"
api-key="{{ .MapboxToken }}"
>
</address-input>
</div>
</div>
</div>
<p class="small text-muted mb-2">
You can also click on the map to mark the location precisely
</p>
<map-locator api-key="{{ .MapboxToken }}"></map-locator>
<input type="hidden" id="map-zoom" name="map-zoom" />
<!-- Mosquito Activity Section -->
<div class="form-section">
<div class="section-heading">
{{ template "mosquito-color.svg" }}
<h3>Mosquito Activity Information</h3>
</div>
<p class="mb-4">
The time when mosquitoes are active can help us identify the species
and likely breeding sources.
</p>
<!-- Time of Day -->
<div class="row mb-4">
<div class="col-12">
<label class="form-label"
>When do you typically notice mosquitoes? (Select all that
apply)</label
>
<div class="row">
<div class="col-6 col-md-3">
<input
type="checkbox"
class="btn-check"
id="earlyMorning"
name="tod-early"
autocomplete="off"
/>
<label
class="btn btn-outline-primary time-of-day-btn"
for="earlyMorning"
>
<span class="time-of-day-icon"
><i class="bi bi-sunrise"></i
></span>
<span class="time-label">Early Morning</span>
<small class="text-muted">5am-8am</small>
</label>
</div>
<div class="col-6 col-md-3">
<input
type="checkbox"
class="btn-check"
id="daytime"
name="tod-day"
autocomplete="off"
/>
<label
class="btn btn-outline-primary time-of-day-btn"
for="daytime"
>
<span class="time-of-day-icon"
><i class="bi bi-sun"></i
></span>
<span class="time-label">Daytime</span>
<small class="text-muted">8am-5pm</small>
</label>
</div>
<div class="col-6 col-md-3">
<input
type="checkbox"
class="btn-check"
id="evening"
name="tod-evening"
autocomplete="off"
/>
<label
class="btn btn-outline-primary time-of-day-btn"
for="evening"
>
<span class="time-of-day-icon"
><i class="bi bi-sunset"></i
></span>
<span class="time-label">Evening</span>
<small class="text-muted">5pm-9pm</small>
</label>
</div>
<div class="col-6 col-md-3">
<input
type="checkbox"
class="btn-check"
id="night"
name="tod-night"
autocomplete="off"
/>
<label
class="btn btn-outline-primary time-of-day-btn"
for="night"
>
<span class="time-of-day-icon"
><i class="bi bi-moon-stars"></i
></span>
<span class="time-label">Night</span>
<small class="text-muted">9pm-5am</small>
</label>
</div>
</div>
</div>
</div>
<!-- Duration -->
<div class="row mb-4">
<div class="col-md-6">
<label for="duration" class="form-label"
>How long have you been experiencing this mosquito problem?</label
>
<select class="form-select" name="duration">
<option value="just-noticed">Just noticed recently</option>
<option value="few-days">A few days</option>
<option value="1-2-weeks">1-2 weeks</option>
<option value="2-4-weeks">2-4 weeks</option>
<option value="1-3-months">1-3 months</option>
<option value="seasonal">All season (recurring issue)</option>
</select>
</div>
</div>
<!-- Location -->
<div class="row">
<div class="col-md-12">
<label for="source-location" class="form-label"
>Where on your property do you notice the most mosquito
activity?</label
>
<select
class="form-select tall"
multiple="true"
name="source-location"
>
<option value="">Please select</option>
<option value="front-yard">Front yard</option>
<option value="backyard">Back yard</option>
<option value="garden">Garden</option>
<option value="pool-area">Pool area</option>
<option value="other">Other area</option>
</select>
</div>
</div>
</div>
<button
id="toggle-additional"
class="btn btn-warning"
type="button"
onClick="toggleCollapse('collapse-additional-fields')"
>
Click here to answer a few more questions to better help us solve your
mosquito problem
</button>
<div class="collapse" id="collapse-additional-fields">
<!-- Potential Sources Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-search"></i>
<h3>Potential Mosquito Sources</h3>
</div>
<p class="mb-3">
Have you noticed any of these common mosquito breeding sources in
your area?
</p>
<div class="card card-highlight mb-4">
<div class="card-body">
<h5 class="card-title">Did you know?</h5>
<p class="card-text">
Mosquitoes can breed in as little as a bottle cap of water!
Eliminating standing water is the most effective way to reduce
mosquito populations.
</p>
</div>
</div>
<div class="row g-4 mb-4">
<!-- Source 1 -->
<div class="col-md-4">
<div class="card source-card">
<div class="card-body text-center">
<div class="source-icon">
<i class="bi bi-water"></i>
</div>
<h5 class="card-title">Stagnant Water</h5>
<p class="card-text">
Green pools, ponds, fountains, or birdbaths that aren't
maintained
</p>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
name="source-stagnant"
id="sourceStagnantWater"
/>
<label class="form-check-label" for="sourceStagnantWater">
I've noticed this
</label>
</div>
</div>
</div>
</div>
<!-- Source 2 -->
<div class="col-md-4">
<div class="card source-card">
<div class="card-body text-center">
<div class="source-icon">
<i class="bi bi-droplet"></i>
</div>
<h5 class="card-title">Containers</h5>
<p class="card-text">
Buckets, planters, toys, tires, or any items that collect
rainwater
</p>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
name="source-container"
id="sourceContainers"
/>
<label class="form-check-label" for="sourceContainers">
I've noticed this
</label>
</div>
</div>
</div>
</div>
<!-- Source 3 -->
<div class="col-md-4">
<div class="card source-card">
<div class="card-body text-center">
<div class="source-icon">
<i class="bi bi-house"></i>
</div>
<h5 class="card-title">Sprinklers & Gutters</h5>
<p class="card-text">
Clogged street gutters, yard drains, or AC units that
collect water
</p>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
name="source-gutters"
id="sourceGutters"
/>
<label class="form-check-label" for="sourceGutters">
I've noticed this
</label>
</div>
</div>
</div>
</div>
</div>
<div
class="alert alert-warning mb-4"
id="sourceFoundAlert"
style="display: none;"
>
<h5 class="alert-heading">
<i class="bi bi-exclamation-triangle me-2"></i>Potential Breeding
Source Found!
</h5>
<p>
It looks like you may have identified a mosquito breeding source.
If you'd like to report a specific source (like a green pool),
please use our
<a href="/report-green-pool" class="alert-link"
>Report a Green Pool</a
>
form for faster service.
</p>
</div>
<div class="row">
<div class="col-md-12">
<label for="otherSources" class="form-label"
>Have you noticed any other potential mosquito breeding
sources?</label
>
<textarea
class="form-control"
id="otherSources"
name="source-description"
rows="2"
placeholder="Describe any other potential breeding sites you've noticed..."
></textarea>
{{ template "photo-upload" }}
</div>
</div>
</div>
<div class="form-section">
<div class="section-heading">
<i class="bi bi-card-text"></i>
<h3>Additional Information</h3>
</div>
<div class="row">
<div class="col-md-12">
<label for="additionalInfo" class="form-label"
>Is there anything else you'd like us to know?</label
>
<textarea
class="form-control"
id="additionalInfo"
name="additional-info"
rows="4"
placeholder="Additional details about the mosquito issue..."
></textarea>
</div>
</div>
</div>
</div>
<!-- Submit Section -->
<div class="submit-container">
<div class="row align-items-center">
<div class="col-md-8">
<p class="mb-0">
<strong>Thank you for reporting this mosquito issue.</strong>
</p>
<p class="mb-0 small text-muted">
After submission, you'll receive a confirmation with a report ID
and further information.
</p>
</div>
<div class="col-md-4 text-md-end mt-3 mt-md-0">
<a
class="btn btn-primary btn-lg"
href="{{ .URL.NuisanceSubmitComplete }}"
>
Submit Report
</a>
</div>
</div>
</div>
</form>
</div>
{{ end }}

View file

@ -1,757 +0,0 @@
{{ template "base.html" . }}
{{ define "title" }}Standing Water{{ end }}
{{ define "extraheader" }}
<script src="https://api.mapbox.com/mapbox-gl-js/v3.17.0-beta.1/mapbox-gl.js"></script>
<script src="/static/js/address-display.js"></script>
<script src="/static/js/address-suggestion.js"></script>
<script src="/static/js/geocode.js"></script>
<script src="/static/js/location.js"></script>
<script src="/static/js/map-locator.js"></script>
{{ template "photo-upload-header" }}
<style>
.district-logo {
max-height: 80px;
width: auto;
}
.form-section {
margin-bottom: 2.5rem;
padding-bottom: 2rem;
border-bottom: 1px solid #dee2e6;
}
.form-section:last-child {
border-bottom: none;
margin-bottom: 1rem;
padding-bottom: 0;
}
.photo-upload-area {
border: 2px dashed #ccc;
border-radius: 8px;
padding: 20px;
text-align: center;
margin-bottom: 20px;
background-color: #f9f9f9;
}
.photo-preview {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 15px;
}
.photo-preview img {
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 4px;
}
.section-heading {
margin-bottom: 1.5rem;
display: flex;
align-items: center;
}
.section-heading i {
margin-right: 10px;
font-size: 1.5rem;
color: #0d6efd;
}
.submit-container {
background-color: #f8f9fa;
padding: 20px;
border-radius: 5px;
margin-top: 2rem;
}
</style>
<script>
const MAPBOX_ACCESS_TOKEN = '{{.MapboxToken}}';
function handlePhotoSelection() {
const photoInput = document.getElementById('photos');
const photoPreviewContainer = document.getElementById('photoPreviewContainer');
// Clear previous previews
photoPreviewContainer.innerHTML = '';
// Check if files were selected
if (photoInput.files && photoInput.files.length > 0) {
// Loop through selected files
Array.from(photoInput.files).forEach((file, index) => {
console.log("Handling", index, file);
if (!file.type.match('image.*')) {
console.log("Skipping non-image file", file.type);
return; // Skip non-image files
}
// Create preview container
const previewContainer = document.createElement('div');
previewContainer.className = 'position-relative m-1';
// Create image preview
const img = document.createElement('img');
img.className = 'img-thumbnail';
img.style.width = '100px';
img.style.height = '100px';
img.style.objectFit = 'cover';
// Read file and set preview
const reader = new FileReader();
reader.onload = (e) => {
img.src = e.target.result;
};
reader.readAsDataURL(file);
// Create remove button
const removeBtn = document.createElement('button');
removeBtn.type = 'button';
removeBtn.className = 'btn btn-sm btn-danger position-absolute top-0 end-0';
removeBtn.innerHTML = '&times;';
removeBtn.style.fontSize = '10px';
removeBtn.style.padding = '0 5px';
// Handle remove button click
removeBtn.addEventListener('click', function() {
// Create a new FileList without this file
// Since FileList is immutable, we need to reset the input
// This is a bit tricky and requires recreating the input
previewContainer.remove();
// If this was the last image, clear the input entirely
if (photoPreviewContainer.children.length === 0) {
photoInput.value = '';
}
// Note: Unfortunately, selectively removing files from a FileList isn't straightforward
// In a real implementation, we might track selected files in an array and recreate the input
});
// Add elements to the preview container
previewContainer.appendChild(img);
previewContainer.appendChild(removeBtn);
photoPreviewContainer.appendChild(previewContainer);
});
}
}
function setLocationInputs(location) {
let country = document.getElementById('address-country');
let latitude = document.getElementById('latitude');
let longitude = document.getElementById('longitude');
let latlngAccuracyType = document.getElementById('latlng-accuracy-type');
let postcode = document.getElementById('address-postcode');
let place = document.getElementById('address-place');
let region = document.getElementById('address-region');
let street = document.getElementById('address-street');
// Extract context data from properties
const props = location.properties;
const context = props.context || {};
// Populate structured fields
country.value = context.country.name;
latitude.value = props.coordinates.latitude;
longitude.value = props.coordinates.longitude;
latlngAccuracyType.value = props.coordinates.accuracy;
postcode.value = context.postcode.name;
place.value = context.place.name;
region.value = context.region.name;
street.value = context.country.name;
}
function toggleCollapse(something) {
el = document.getElementById(something)
if (el.classList.contains('collapse')) {
el.classList.remove('collapse');
} else {
el.classList.add('collapse');
}
document.getElementById("toggle-additional").classList.add("visually-hidden");
}
document.addEventListener('DOMContentLoaded', function() {
// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl, {
trigger: 'hover focus' // Works on hover (desktop) and tap (mobile)
});
});
// Elements
const photoInput = document.getElementById('photos');
// Handle photo selection
photoInput.addEventListener('change', handlePhotoSelection);
// Handle drag and drop
const photoDropArea = document.getElementById('photoDropArea');
photoDropArea.addEventListener('dragover', function(e) {
e.preventDefault();
photoDropArea.style.backgroundColor = '#e9ecef';
});
photoDropArea.addEventListener('dragleave', function() {
photoDropArea.style.backgroundColor = '#f8f9fa';
});
photoDropArea.addEventListener('drop', function(e) {
e.preventDefault();
photoDropArea.style.backgroundColor = '#f8f9fa';
if (e.dataTransfer.files.length) {
handleFiles(e.dataTransfer.files);
}
});
const mapLocator = document.querySelector("map-locator");
mapLocator.addEventListener("load", (event) => {
getGeolocation({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}).then(position => {
mapLocator.jumpTo({
center: {
lng: position.coords.longitude,
lat: position.coords.latitude,
},
zoom: 14,
});
mapLocator.setMarker([
position.coords.longitude,
position.coords.latitude,
]);
geocodeReverse(MAPBOX_ACCESS_TOKEN, {
lat: position.coords.latitude,
lng: position.coords.longitude,
});
}).catch(error => {
console.log("location error", error);
})
})
let mapZoom = document.getElementById('map-zoom');
mapLocator.addEventListener("zoomend", function(e) {
mapZoom.value = e.target.getZoom();
});
mapLocator.addEventListener("markerdragend", (e) => {
const lngLat = marker.getLngLat();
//displaySelectedCoordinates(lngLat);
geocodeReverse(MAPBOX_ACCESS_TOKEN, lngLat);
});
const addressDisplay = document.querySelector("address-display");
const addressInput = document.querySelector("address-input");
addressInput.addEventListener("address-selected", (event) => {
const l = event.detail.location;
console.log("Address selected", l);
// Center map on selected address
mapSetMarker(l.geometry.coordinates);
mapJumpTo({
center: l.geometry.coordinates,
zoom: 14,
});
addressDisplay.show(l);
setLocationInputs(l);
});
});
function displaySelectedCoordinates(lngLat) {
const gpsDisplay = document.getElementById("gps-display");
gpsDisplay.classList.remove('d-none');
longitude.textContent = lngLat.lng;
latitude.textContent = lngLat.lat;
}
</script>
{{ end }}
{{ define "content" }}
{{ if .District }}
{{ template "header" . }}
{{ end }}
<!-- Main Content -->
<main class="py-5">
<div class="container">
<!-- Page Title -->
<div class="row mb-4">
<div class="col-12">
<h2>Report Standing Water</h2>
<p class="lead">
Help us locate and treat potential mosquito production sources in
your area
</p>
</div>
</div>
<!-- Report Form -->
<form
id="standingWater"
action="/water-submit"
method="POST"
enctype="multipart/form-data"
>
<!-- Photo Upload Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-camera"></i>
<h3>Photos</h3>
</div>
<p class="mb-3">
Photos help us identify the severity of the issue and may contain
location data that can help us find the production source.
</p>
<div class="mb-4">
{{ template "photo-upload" }}
</div>
</div>
<!-- Additional Information Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-card-text"></i>
<h3>Additional Information</h3>
</div>
<p class="mb-3">
Please provide any other information that might help us address this
mosquito production source.
</p>
<div class="row">
<div class="col-md-12">
<label for="comments" class="form-label"
>Additional Details</label
>
<textarea
class="form-control"
id="comments"
name="comments"
rows="4"
placeholder="Example: The house appears to be vacant. There is algae growth in the pool. I've noticed increased mosquito activity in the evenings."
></textarea>
</div>
</div>
</div>
<!-- Location Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-geo-alt"></i>
<h3>Location</h3>
</div>
<p class="mb-3">
Please provide the location of the potential mosquito production
source. We may be able to extract this information from your photos
if they contain location data.
</p>
<div class="col-md-12">
<div class="alert alert-info" role="info">
<p class="mb-0">
You can select the location by address or by moving the marker
on the map.
</p>
</div>
</div>
<div class="row mb-3">
<!-- Hidden fields for location data -->
<input type="hidden" id="address-country" name="address-country" />
<input
type="hidden"
id="address-postcode"
name="address-postcode"
/>
<input type="hidden" id="address-place" name="address-place" />
<input type="hidden" id="address-region" name="address-region" />
<input type="hidden" id="address-street" name="address-street" />
<input type="hidden" id="latitude" name="latitude" />
<input type="hidden" id="longitude" name="longitude" />
<input
type="hidden"
id="latlng-accuracy-type"
name="latlng-accuracy-type"
/>
<input
type="hidden"
id="latlng-accuracy-value"
name="latlng-accuracy-value"
/>
<div class="col-md-6">
<div class="mb-3 position-relative">
<address-input
placeholder="Start typing an address (min 3 characters)"
api-key="{{ .MapboxToken }}"
>
</address-input>
</div>
</div>
</div>
<p class="small text-muted mb-2">
You can also click on the map to mark the location precisely
</p>
<map-locator api-key="{{ .MapboxToken }}"></map-locator>
<input type="hidden" id="map-zoom" name="map-zoom" />
</div>
<button
id="toggle-additional"
class="btn btn-warning"
type="button"
onClick="toggleCollapse('collapse-additional-fields')"
>
Click here to answer a few more questions to better help us solve your
mosquito problem
</button>
<div class="collapse" id="collapse-additional-fields">
<!-- Source Details Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-water"></i>
<h3>Source Details</h3>
</div>
<div class="row mb-4">
<div class="col-md-6">
<label for="duration" class="form-label"
>How long has this production source been present?</label
>
<select
class="form-select"
id="duration"
name="source-duration"
>
<option value="none">I don't know</option>
<option value="less-than-week">Less than a week</option>
<option value="1-2-weeks">1-2 weeks</option>
<option value="2-4-weeks">2-4 weeks</option>
<option value="1-3-months">1-3 months</option>
<option value="more-than-3-months">More than 3 months</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label d-block"
>Have you observed any of the following?
<a
href="#"
data-bs-toggle="modal"
data-bs-target="#larvaeInfoModal"
><i class="bi bi-question-circle small ms-1"></i></a
></label>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="larvae"
name="has-larvae"
/>
<label class="form-check-label" for="larvae">
Larvae (wigglers) in water
</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="pupae"
name="has-pupae"
/>
<label class="form-check-label" for="pupae">
Pupae (tumblers) in water
</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="adult"
name="has-adult"
/>
<label class="form-check-label" for="adult">
Adult mosquitoes near the source
</label>
</div>
</div>
</div>
</div>
<!-- Access Information Section -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-unlock"></i>
<h3>Access Information</h3>
</div>
<p class="mb-3">
Please provide any details about how to access the mosquito
source. This helps our technicians when they visit the site.
</p>
<div class="row mb-3">
<div class="col-md-12">
<label for="access-comments" class="form-label"
>How can the source be accessed?</label
>
<textarea
class="form-control"
id="access-comments"
name="access-comments"
rows="3"
placeholder="Example: The pool is in the backyard, which can be accessed through a side gate on the right side of the house."
></textarea>
</div>
</div>
<div class="row mb-3">
<div class="col-md-12">
<label class="form-label d-block"
>Access obstacles (check all that apply):</label
>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="gate"
name="access-gate"
/>
<label class="form-check-label" for="gate">Gate</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="fence"
name="access-fence"
/>
<label class="form-check-label" for="fence">Fence</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="locked"
name="access-locked"
/>
<label class="form-check-label" for="locked"
>Locked entrance</label
>
</div>
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="dogs"
name="access-dog"
/>
<label class="form-check-label" for="dogs"
>Dogs/pets</label
>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input
class="form-check-input"
type="checkbox"
id="access-other"
name="access-other"
/>
<label class="form-check-label" for="access-other"
>Other obstacle</label
>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Contact Information Sections -->
<div class="form-section">
<div class="section-heading">
<i class="bi bi-person-lines-fill"></i>
<h3>Property Owner Information (if known)</h3>
</div>
<div class="row mb-4">
<div class="col-md-4 mb-3">
<label for="owner-name" class="form-label">Owner Name</label>
<input
type="text"
class="form-control"
id="owner-name"
name="owner-name"
/>
</div>
<div class="col-md-4 mb-3">
<label for="owner-phone" class="form-label">Owner Phone</label>
<input
type="tel"
class="form-control"
id="owner-phone"
name="owner-phone"
/>
</div>
<div class="col-md-4 mb-3">
<label for="owner-email" class="form-label">Owner Email</label>
<input
type="email"
class="form-control"
id="owner-email"
name="owner-email"
/>
</div>
</div>
<div class="row mb-4">
<div class="col-md-6 mb-3 row">
<div class="form-check mt-4">
<input
type="checkbox"
class="form-check-input"
name="property-ownership"
/>
<label class="form-check-label" for="property-ownership"
>This is my property</label
>
</div>
<div class="form-check mt-4">
<input
type="checkbox"
class="form-check-input"
name="backyard-permission"
/>
<label class="form-check-label" for="backyard-permission"
>I grant permission to enter the back yard of this
property.</label
>
</div>
<div class="form-check mt-4">
<input
type="checkbox"
class="form-check-input"
name="reporter-confidential"
/>
<label class="form-check-label" for="reporter-confidential">
<i
class="bi bi-info-circle-fill text-primary ms-1"
data-bs-toggle="tooltip"
data-bs-placement="top"
title="We share your information with mosquito control districts so they can follow up with any questions they may have about your report. Check this box if you would like the district to be careful not to share your information outside of the district operations team."
></i>
I would like my personal information kept
confidential.</label
>
</div>
</div>
</div>
</div>
</div>
<!-- Submit Section -->
<div class="submit-container">
<div class="row align-items-center">
<div class="col-md-8">
<p class="mb-0">
<strong
>Thank you for helping us keep our community safe from
mosquito-borne illnesses.</strong
>
</p>
<p class="mb-0 small text-muted">
After submission, you will receive a confirmation with a report
ID for tracking purposes.
</p>
</div>
<div class="col-md-4 text-md-end mt-3 mt-md-0">
<a
class="btn btn-primary btn-lg"
href="{{ .URL.NuisanceSubmitComplete }}"
>
Submit Report
</a>
</div>
</div>
</div>
</form>
</div>
</main>
<!-- Larvae Info Modal -->
<div
class="modal fade"
id="larvaeInfoModal"
tabindex="-1"
aria-labelledby="larvaeInfoModalLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="larvaeInfoModalLabel">
How to Identify Mosquito Larvae and Pupae
</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<div class="row mb-4">
<div class="col-md-6">
<h6>Mosquito Larvae (Wigglers)</h6>
<p>Mosquito larvae, often called "wigglers," are:</p>
<ul>
<li>Small, worm-like aquatic organisms</li>
<li>Usually 1/4 to 1/2 inch long</li>
<li>Move with a wiggling motion in water</li>
<li>Hang upside-down at the water surface to breathe</li>
<li>Visible to the naked eye in standing water</li>
</ul>
</div>
<div class="col-md-6">
<h6>Mosquito Pupae (Tumblers)</h6>
<p>Mosquito pupae, often called "tumblers," are:</p>
<ul>
<li>Comma-shaped organisms</li>
<li>Typically darker than larvae</li>
<li>Move with a tumbling motion when disturbed</li>
<li>Rest at the water surface</li>
<li>The stage just before adult mosquitoes emerge</li>
</ul>
</div>
</div>
<p>
When looking for mosquito larvae and pupae, check standing water
sources like:
</p>
<ul>
<li>Swimming pools</li>
<li>Bird baths</li>
<li>Buckets or containers</li>
<li>Drainage ditches</li>
<li>Plant saucers</li>
<li>Rain gutters</li>
</ul>
<p>
If you see small creatures moving in standing water, there's a good
chance they're mosquito larvae or pupae.
</p>
<div class="text-center">
<a href="#" class="btn btn-outline-primary"
>View Detailed Identification Guide</a
>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Close
</button>
</div>
</div>
</div>
</div>
{{ end }}

View file

@ -27,12 +27,11 @@
<script src="/static/js/location.js"></script>
<script src="/static/js/map-locator.js"></script>
<script src="/static/js/photo-upload.js"></script>
<script>
const MAPBOX_ACCESS_TOKEN = "{{.MapboxToken}}";
async function handleMapClick(mapLocator, lngLat) {
<script>
async function handleMapClick(mapLocator, lngLat) {
mapLocator.SetMarker(lngLat);
mapLocator.PanTo(lngLat, {duration: 2000});
const response = await geocodeReverse(MAPBOX_ACCESS_TOKEN, {
mapLocator.PanTo(lngLat, { duration: 2000 });
const response = await geocodeReverse({
lat: lngLat.lat,
lng: lngLat.lng,
});
@ -42,93 +41,108 @@ async function handleMapClick(mapLocator, lngLat) {
addressInput.SetValue(response.features[0]);
setLocationInputs(response.features[0]);
}
}
async function handleMarkerDrag(lngLat) {
const response = await geocodeReverse(MAPBOX_ACCESS_TOKEN, {
}
async function handleMarkerDrag(lngLat) {
const response = await geocodeReverse({
lat: lngLat.lat,
lng: lngLat.lng,
})
});
console.log("marker drag reverse geocode", response);
if (response !== undefined && response.features.length > 0) {
const addressInput = document.querySelector("address-input");
addressInput.SetValue(response.features[0]);
setLocationInputs(response.features[0]);
}
}
function selectInspectionType(type) {
}
function selectInspectionType(type) {
// Remove selected class from both cards
document.getElementById('propertyInspection').classList.remove('selected');
document.getElementById('neighborhoodInspection').classList.remove('selected');
document
.getElementById("propertyInspection")
.classList.remove("selected");
document
.getElementById("neighborhoodInspection")
.classList.remove("selected");
// Add selected class to chosen card
if (type === 'property') {
document.getElementById('propertyInspection').classList.add('selected');
document.getElementById('inspectionTypeProperty').checked = true;
document.getElementById('schedulingSection').style.display = 'block';
if (type === "property") {
document.getElementById("propertyInspection").classList.add("selected");
document.getElementById("inspectionTypeProperty").checked = true;
document.getElementById("schedulingSection").style.display = "block";
} else {
document.getElementById('neighborhoodInspection').classList.add('selected');
document.getElementById('inspectionTypeNeighborhood').checked = true;
document.getElementById('schedulingSection').style.display = 'none';
document
.getElementById("neighborhoodInspection")
.classList.add("selected");
document.getElementById("inspectionTypeNeighborhood").checked = true;
document.getElementById("schedulingSection").style.display = "none";
}
}
function setLocationInputs(location) {
let country = document.getElementById('address-country');
let latitude = document.getElementById('latitude');
let longitude = document.getElementById('longitude');
let latlngAccuracyType = document.getElementById('latlng-accuracy-type');
let latlngAccuracyValue = document.getElementById('latlng-accuracy-value');
let number = document.getElementById('address-number');
let postcode = document.getElementById('address-postcode');
let place = document.getElementById('address-place');
let region = document.getElementById('address-region');
let street = document.getElementById('address-street');
}
function setLocationInputs(location) {
let country = document.getElementById("address-country");
let latitude = document.getElementById("latitude");
let longitude = document.getElementById("longitude");
let latlngAccuracyType = document.getElementById("latlng-accuracy-type");
let latlngAccuracyValue = document.getElementById(
"latlng-accuracy-value",
);
let number = document.getElementById("address-number");
let postalcode = document.getElementById("address-postalcode");
let locality = document.getElementById("address-locality");
let region = document.getElementById("address-region");
let street = document.getElementById("address-street");
// Extract context data from properties
const props = location.properties;
const context = props.context || {};
// Populate structured fields
country.value = context.country.name;
latitude.value = props.coordinates.latitude;
longitude.value = props.coordinates.longitude;
latlngAccuracyType.value = props.coordinates.accuracy;
latlngAccuracyValue.value = "0";
number.value = context.address.address_number;
postcode.value = context.postcode.name;
place.value = context.place.name;
region.value = context.region.name;
street.value = context.street.name;
}
function toggleCollapse(something) {
el = document.getElementById(something)
if (el.classList.contains('collapse')) {
el.classList.remove('collapse');
} else {
el.classList.add('collapse');
country.value = context.iso_3166_a3;
latitude.value = location.geometry.coordinates[1];
longitude.value = location.geometry.coordinates[0];
latlngAccuracyType.value = props.precision;
latlngAccuracyValue.value = props.distance;
number.value = props.address_components.number;
postalcode.value = props.address_components.postal_code;
locality.value = context.locality.name;
region.value = props.context.whosonfirst.region.abbreviation;
street.value = props.address_components.street;
}
function toggleCollapse(something) {
el = document.getElementById(something);
if (el.classList.contains("collapse")) {
el.classList.remove("collapse");
} else {
el.classList.add("collapse");
}
document
.getElementById("toggle-additional")
.classList.add("visually-hidden");
}
document.getElementById("toggle-additional").classList.add("visually-hidden");
}
// Check for source identification
document.addEventListener('DOMContentLoaded', function() {
// Check for source identification
document.addEventListener("DOMContentLoaded", function () {
// Elements
const addressInput = document.querySelector("address-input");
const latitudeInput = document.getElementById('latitude');
const longitudeInput = document.getElementById('longitude');
const latlngAccuracyType = document.getElementById('latlng-accuracy-type');
const latlngAccuracyValue = document.getElementById('latlng-accuracy-value');
const latitudeInput = document.getElementById("latitude");
const longitudeInput = document.getElementById("longitude");
const latlngAccuracyType = document.getElementById(
"latlng-accuracy-type",
);
const latlngAccuracyValue = document.getElementById(
"latlng-accuracy-value",
);
const mapLocator = document.querySelector("map-locator");
mapLocator.addEventListener("load", (event) => {
getGeolocation({
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}).then(position => {
maximumAge: 0,
})
.then((position) => {
console.log("Got location", position);
latitudeInput.value = position.coords.latitude;
longitudeInput.value = position.coords.longitude;
latlngAccuracyType.value = 'browser';
latlngAccuracyType.value = "browser";
latlngAccuracyValue.value = position.coords.accuracy;
mapLocator.JumpTo({
center: {
@ -142,17 +156,18 @@ document.addEventListener('DOMContentLoaded', function() {
position.coords.latitude,
];
mapLocator.SetMarker(coords);
mapLocator.JumpTo({center: coords, zoom: 14});
mapLocator.JumpTo({ center: coords, zoom: 14 });
handleMarkerDrag({
lat: position.coords.latitude,
lng: position.coords.longitude,
});
}).catch(error => {
})
.catch((error) => {
console.log("location error", error);
})
})
let mapZoom = document.getElementById('map-zoom');
mapLocator.addEventListener("zoomend", function(e) {
});
});
let mapZoom = document.getElementById("map-zoom");
mapLocator.addEventListener("zoomend", function (e) {
mapZoom.value = e.target.GetZoom();
});
mapLocator.addEventListener("click", (e) => {
@ -180,8 +195,8 @@ document.addEventListener('DOMContentLoaded', function() {
setLocationInputs(l);
});
});
</script>
});
</script>
<style></style>
{{ end }}
{{ define "content" }}
@ -240,7 +255,7 @@ document.addEventListener('DOMContentLoaded', function() {
<input type="hidden" id="address-country" name="address-country" />
<input type="hidden" id="address-number" name="address-number" />
<input type="hidden" id="address-postcode" name="address-postcode" />
<input type="hidden" id="address-place" name="address-place" />
<input type="hidden" id="address-locality" name="address-locality" />
<input type="hidden" id="address-region" name="address-region" />
<input type="hidden" id="address-street" name="address-street" />
<input type="hidden" id="latitude" name="latitude" />

View file

@ -61,7 +61,7 @@ function setLocationInputs(location) {
let latlngAccuracyType = document.getElementById('latlng-accuracy-type');
let latlngAccuracyValue = document.getElementById('latlng-accuracy-value');
let number = document.getElementById('address-number');
let postcode = document.getElementById('address-postcode');
let postalcode = document.getElementById('address-postalcode');
let place = document.getElementById('address-place');
let region = document.getElementById('address-region');
let street = document.getElementById('address-street');
@ -71,16 +71,16 @@ function setLocationInputs(location) {
const context = props.context || {};
// Populate structured fields
country.value = context.country.name;
latitude.value = props.coordinates.latitude;
longitude.value = props.coordinates.longitude;
latlngAccuracyType.value = props.coordinates.accuracy;
latlngAccuracyValue.value = "0";
number.value = context.address.address_number;
postcode.value = context.postcode.name;
place.value = context.place.name;
region.value = context.region.name;
street.value = context.street.name;
country.value = context.iso_3166_a3;
latitude.value = location.geometry.coordinates[1];
longitude.value = location.geometry.coordinates[0];
latlngAccuracyType.value = props.precision;
latlngAccuracyValue.value = props.distance;
number.value = props.address_components.number;
postalcode.value = props.address_components.postal_code;
locality.value = context.locality.name;
region.value = props.context.whosonfirst.region.abbreviation;
street.value = props.address_components.street;
}
function toggleCollapse(something) {
el = document.getElementById(something)

View file

@ -18,6 +18,7 @@ import (
"github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
"github.com/Gleipnir-Technology/nidus-sync/platform/geocode"
"github.com/Gleipnir-Technology/nidus-sync/platform/types"
//"github.com/Gleipnir-Technology/nidus-sync/h3utils"
//"github.com/Gleipnir-Technology/nidus-sync/platform/geom"
//"github.com/Gleipnir-Technology/nidus-sync/platform/text"
@ -53,8 +54,8 @@ func JobCommit(ctx context.Context, file_id int32) error {
return fmt.Errorf("Failed to get all rows of file %d: %w", file_id, err)
}
for _, row := range rows {
a := geocode.Address{
Country: enums.CountrytypeUsa,
a := types.Address{
Country: "usa",
Locality: row.AddressLocality,
Number: row.AddressNumber,
PostalCode: row.AddressPostalCode,
@ -62,7 +63,7 @@ func JobCommit(ctx context.Context, file_id int32) error {
Street: row.AddressStreet,
Unit: "",
}
address, err := geocode.EnsureAddress(ctx, txn, org, a)
address, err := geocode.EnsureAddressWithGeocode(ctx, txn, org, a)
if err != nil {
//return fmt.Errorf("ensure address: %w", err)
if address == nil {

View file

@ -19,6 +19,7 @@ import (
"github.com/Gleipnir-Technology/nidus-sync/platform/geocode"
"github.com/Gleipnir-Technology/nidus-sync/platform/geom"
"github.com/Gleipnir-Technology/nidus-sync/platform/text"
"github.com/Gleipnir-Technology/nidus-sync/platform/types"
"github.com/Gleipnir-Technology/nidus-sync/stadia"
"github.com/Gleipnir-Technology/nidus-sync/userfile"
"github.com/aarondl/opt/omit"
@ -132,7 +133,7 @@ type jobGeocode struct {
func geocodePool(ctx context.Context, txn bob.Tx, client *stadia.StadiaMaps, job *jobGeocode) error {
pool := job.pool
a := geocode.Address{
a := types.Address{
Number: pool.AddressNumber,
Locality: pool.AddressLocality,
PostalCode: pool.AddressPostalCode,

View file

@ -10,35 +10,22 @@ import (
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/im"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
"github.com/Gleipnir-Technology/nidus-sync/h3utils"
"github.com/Gleipnir-Technology/nidus-sync/platform/types"
"github.com/Gleipnir-Technology/nidus-sync/stadia"
"github.com/stephenafamo/scan"
//"github.com/rs/zerolog/log"
"github.com/uber/h3-go/v4"
)
type Address struct {
Country enums.Countrytype
Locality string
Number string
PostalCode string
Region string
Street string
Unit string
}
type GeocodeResult struct {
Address Address
Address types.Address
Cell h3.Cell
Longitude float64
Latitude float64
}
func (a Address) String() string {
return fmt.Sprintf("%s %s, %s, %s, %s, %s", a.Number, a.Street, a.Locality, a.Region, a.PostalCode, a.Country)
}
var client *stadia.StadiaMaps
func InitializeStadia(key string) {
@ -47,9 +34,9 @@ func InitializeStadia(key string) {
// Either get an address that matches, or create a new address. Either way, return an address
// This will make a call to a structured geocode service, so it's slow.
func EnsureAddress(ctx context.Context, txn bob.Tx, org *models.Organization, a Address) (*models.Address, error) {
func EnsureAddressWithGeocode(ctx context.Context, txn bob.Tx, org *models.Organization, a types.Address) (*models.Address, error) {
address, err := models.Addresses.Query(
models.SelectWhere.Addresses.Country.EQ(a.Country),
models.SelectWhere.Addresses.Country.EQ(a.CountryEnum()),
models.SelectWhere.Addresses.Locality.EQ(a.Locality),
models.SelectWhere.Addresses.Number.EQ(a.Number),
models.SelectWhere.Addresses.PostalCode.EQ(a.PostalCode),
@ -92,7 +79,7 @@ func EnsureAddress(ctx context.Context, txn bob.Tx, org *models.Organization, a
}
return &models.Address{
Country: geo.Address.Country,
Country: geo.Address.CountryEnum(),
Created: created,
H3cell: "",
ID: row.ID,
@ -106,9 +93,9 @@ func EnsureAddress(ctx context.Context, txn bob.Tx, org *models.Organization, a
}, nil
}
func Geocode(ctx context.Context, org *models.Organization, a Address) (GeocodeResult, error) {
func Geocode(ctx context.Context, org *models.Organization, a types.Address) (GeocodeResult, error) {
street := fmt.Sprintf("%s %s", a.Number, a.Street)
country_s := a.Country.String()
country_s := a.Country
/*
sublog := log.With().
Str("street", street).
@ -148,15 +135,10 @@ func Geocode(ctx context.Context, org *models.Organization, a Address) (GeocodeR
if err != nil {
return GeocodeResult{}, fmt.Errorf("failed to convert lat %f lng %f to h3 cell", longitude, latitude)
}
var country enums.Countrytype
country_s = strings.ToLower(feature.Properties.CountryA)
err = country.Scan(country_s)
if err != nil {
return GeocodeResult{}, fmt.Errorf("failed to scan country '%s': %w", country_s, err)
}
return GeocodeResult{
Address: Address{
Country: country,
Address: types.Address{
Country: country_s,
Locality: feature.Properties.Locality,
Number: feature.Properties.HouseNumber,
PostalCode: feature.Properties.PostalCode,

View file

@ -33,23 +33,28 @@ func loadImagesForReportNuisance(ctx context.Context, org_id int32, report_ids [
rows, err := bob.All(ctx, db.PGInstance.BobDB, psql.Select(
sm.Columns(
"i.storage_uuid AS uuid",
"ST_X(location) AS location.longitude",
"ST_Y(location) AS location.latitude",
"MAX(e.value) FILTER (WHERE e.name = 'Make') AS exif_make",
"MAX(e.value) FILTER (WHERE e.name = 'Model') AS exif_model",
"MAX(e.value) FILTER (WHERE e.name = 'DateTime') AS exif_datetime",
"COALESCE(ST_X(location), 0) AS \"location.longitude\"",
"COALESCE(ST_Y(location), 0) AS \"location.latitude\"",
"COALESCE(MAX(e.value) FILTER (WHERE e.name = 'Make'), '') AS exif_make",
"COALESCE(MAX(e.value) FILTER (WHERE e.name = 'Model'), '') AS exif_model",
"COALESCE(MAX(e.value) FILTER (WHERE e.name = 'DateTime'), '') AS exif_datetime",
"ni.nuisance_id AS nuisance_id",
),
sm.From("publicreport.image").As("i"),
sm.LeftJoin("publicreport.image_exif").As("e").OnEQ(
psql.Quote("r", "id"),
psql.Quote("i", "id"),
psql.Quote("e", "image_id"),
),
sm.InnerJoin("publicreport.nuisance_image").As("ni").OnEQ(
psql.Quote("ni", "image_id"),
psql.Quote("i", "id"),
),
sm.Where(psql.Quote("ni", "nuisance_id").In(psql.Arg(report_ids))),
sm.Where(psql.Quote("ni", "nuisance_id").EQ(psql.Any(report_ids))),
sm.GroupBy(
//psql.Quote("i", "id"),
//psql.Quote("ni", "nuisance_id"),
psql.Raw("i.id, ni.nuisance_id"),
),
), scan.StructMapper[types.Image]())
if err != nil {
return nil, fmt.Errorf("get images: %w", err)

View file

@ -18,45 +18,40 @@ import (
)
type Nuisance struct {
AdditionalInfo string `db:"additional_info"`
Address types.Address `db:"address"`
AddressAsGiven string `db:"address_as_given"`
Created time.Time `db:"created"`
Duration string `db:"duration"`
ID int32 `db:"id"`
Images []types.Image
IsLocationBackyard bool `db:"is_location_backyard"`
IsLocationFrontyard bool `db:"is_location_frontyard"`
IsLocationGarden bool `db:"is_location_garden"`
IsLocationOther bool `db:"is_location_other"`
IsLocationPool bool `db:"is_location_pool"`
Location types.Location `db:"location"`
PublicID string `db:"public_id"`
Reporter Reporter `db:"reporter"`
SourceContainer bool `db:"source_container"`
SourceDescription string `db:"source_description"`
SourceGutter bool `db:"source_gutter"`
SourceStagnant bool `db:"source_stagnant"`
TODDay bool `db:"tod_day"`
TODEarly bool `db:"tod_early"`
TODEvening bool `db:"tod_evening"`
TODNight bool `db:"tod_night"`
}
type Reporter struct {
Email *string `db:"reporter_email"`
Name *string `db:"reporter_name"`
Phone *string `db:"reporter_phone"`
AdditionalInfo string `db:"additional_info" json:"additional_info"`
Address types.Address `db:"address" json:"address"`
AddressRaw string `db:"address_raw" json:"address_raw"`
Created time.Time `db:"created" json:"created"`
Duration string `db:"duration" json:"duration"`
ID int32 `db:"id" json:"-"`
Images []types.Image `json:"images"`
IsLocationBackyard bool `db:"is_location_backyard" json:"is_location_backyard"`
IsLocationFrontyard bool `db:"is_location_frontyard" json:"is_location_frontyard"`
IsLocationGarden bool `db:"is_location_garden" json:"is_location_garden"`
IsLocationOther bool `db:"is_location_other" json:"is_location_other"`
IsLocationPool bool `db:"is_location_pool" json:"is_location_pool"`
Location types.Location `db:"location" json:"location"`
PublicID string `db:"public_id" json:"public_id"`
Reporter types.Contact `db:"reporter" json:"reporter"`
SourceContainer bool `db:"source_container" json:"source_container"`
SourceDescription string `db:"source_description" json:"source_description"`
SourceGutter bool `db:"source_gutter" json:"source_gutter"`
SourceStagnant bool `db:"source_stagnant" json:"source_stagnant"`
TODDay bool `db:"tod_day" json:"tod_day"`
TODEarly bool `db:"tod_early" json:"tod_early"`
TODEvening bool `db:"tod_evening" json:"tod_evening"`
TODNight bool `db:"tod_night" json:"tod_night"`
}
func NuisanceReportForOrganization(ctx context.Context, org_id int32) ([]Nuisance, error) {
reports, err := bob.All(ctx, db.PGInstance.BobDB, psql.Select(
sm.Columns(
"additional_info",
"address AS address_as_given",
"address_raw AS address_raw",
"address_country AS \"address.country\"",
"address_locality AS \"address.locality\"",
"address_number AS \"address.number\"",
"address_place AS \"address.place\"",
"address_postcode AS \"address.postcode\"",
"address_postal_code AS \"address.postal_code\"",
"address_region AS \"address.region\"",
"address_street AS \"address.street\"",
"created",

View file

@ -193,8 +193,8 @@ func findSomeReport(ctx context.Context, report_id string) (result SomeReport, e
switch row.FoundInTables[0] {
case "nuisance":
return newNuisance(ctx, report_id, int32(t))
case "pool":
return newPool(ctx, report_id, int32(t))
case "water":
return newWater(ctx, report_id, int32(t))
default:
log.Error().Err(e).Str("table_name", row.FoundInTables[0]).Msg("Unrecognized table")
return Nuisance{}, newErrorWithCode("internal-error", fmt.Sprintf("Unrecognized table '%s'", row.FoundInTables[0]))

View file

@ -21,50 +21,50 @@ import (
"github.com/stephenafamo/scan"
)
type Pool struct {
type Water struct {
id int32
publicReportID string
row *models.PublicreportPool
row *models.PublicreportWater
}
func (sr Pool) PublicReportID() string {
func (sr Water) PublicReportID() string {
return sr.publicReportID
}
func (sr Pool) addNotificationEmail(ctx context.Context, txn bob.Tx, email string) *ErrorWithCode {
setter := models.PublicreportNotifyEmailPoolSetter{
func (sr Water) addNotificationEmail(ctx context.Context, txn bob.Tx, email string) *ErrorWithCode {
setter := models.PublicreportNotifyEmailWaterSetter{
Created: omit.From(time.Now()),
Deleted: omitnull.FromPtr[time.Time](nil),
PoolID: omit.From(sr.id),
EmailAddress: omit.From(email),
WaterID: omit.From(sr.id),
}
_, err := models.PublicreportNotifyEmailPools.Insert(&setter).Exec(ctx, txn)
_, err := models.PublicreportNotifyEmailWaters.Insert(&setter).Exec(ctx, txn)
if err != nil {
log.Error().Err(err).Msg("Failed to save new notification email row")
return newInternalError(err, "Failed to save new notification email row")
}
return nil
}
func (sr Pool) addNotificationPhone(ctx context.Context, txn bob.Tx, phone text.E164) *ErrorWithCode {
setter := models.PublicreportNotifyPhonePoolSetter{
func (sr Water) addNotificationPhone(ctx context.Context, txn bob.Tx, phone text.E164) *ErrorWithCode {
setter := models.PublicreportNotifyPhoneWaterSetter{
Created: omit.From(time.Now()),
Deleted: omitnull.FromPtr[time.Time](nil),
PoolID: omit.From(sr.id),
PhoneE164: omit.From(text.PhoneString(phone)),
WaterID: omit.From(sr.id),
}
_, err := models.PublicreportNotifyPhonePools.Insert(&setter).Exec(ctx, txn)
_, err := models.PublicreportNotifyPhoneWaters.Insert(&setter).Exec(ctx, txn)
if err != nil {
log.Error().Err(err).Msg("Failed to save new notification phone row")
return newInternalError(err, "Failed to save new notification phone row")
}
return nil
}
func (sr Pool) districtID(ctx context.Context) *int32 {
func (sr Water) districtID(ctx context.Context) *int32 {
type _Row struct {
OrganizationID *int32
}
row, err := bob.One(ctx, db.PGInstance.BobDB, psql.Select(
sm.From("publicreport.pool"),
sm.From("publicreport.water"),
sm.Columns("organization_id"),
sm.Where(psql.Quote("public_id").EQ(psql.Arg(sr.publicReportID))),
), scan.StructMapper[_Row]())
@ -74,44 +74,44 @@ func (sr Pool) districtID(ctx context.Context) *int32 {
}
return row.OrganizationID
}
func (sr Pool) reportID() int32 {
func (sr Water) reportID() int32 {
return sr.id
}
func (sr Pool) updateReporterConsent(ctx context.Context, txn bob.Tx, has_consent bool) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportPoolSetter{
func (sr Water) updateReporterConsent(ctx context.Context, txn bob.Tx, has_consent bool) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportWaterSetter{
ReporterContactConsent: omitnull.From(has_consent),
})
}
func (sr Pool) updateReporterEmail(ctx context.Context, txn bob.Tx, email string) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportPoolSetter{
func (sr Water) updateReporterEmail(ctx context.Context, txn bob.Tx, email string) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportWaterSetter{
ReporterEmail: omit.From(email),
})
}
func (sr Pool) updateReporterName(ctx context.Context, txn bob.Tx, name string) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportPoolSetter{
func (sr Water) updateReporterName(ctx context.Context, txn bob.Tx, name string) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportWaterSetter{
ReporterName: omit.From(name),
})
}
func (sr Pool) updateReportCol(ctx context.Context, txn bob.Tx, setter *models.PublicreportPoolSetter) *ErrorWithCode {
func (sr Water) updateReportCol(ctx context.Context, txn bob.Tx, setter *models.PublicreportWaterSetter) *ErrorWithCode {
err := sr.row.Update(ctx, txn, setter)
if err != nil {
log.Error().Err(err).Str("public_id", sr.publicReportID).Int32("report_id", sr.id).Msg("Failed to update report")
return newInternalError(err, "Failed to update pool report in the database")
return newInternalError(err, "Failed to update water report in the database")
}
return nil
}
func (sr Pool) updateReporterPhone(ctx context.Context, txn bob.Tx, phone text.E164) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportPoolSetter{
func (sr Water) updateReporterPhone(ctx context.Context, txn bob.Tx, phone text.E164) *ErrorWithCode {
return sr.updateReportCol(ctx, txn, &models.PublicreportWaterSetter{
ReporterPhone: omit.From(text.PhoneString(phone)),
})
}
func newPool(ctx context.Context, public_id string, report_id int32) (Pool, *ErrorWithCode) {
row, err := models.FindPublicreportPool(ctx, db.PGInstance.BobDB, report_id)
func newWater(ctx context.Context, public_id string, report_id int32) (Water, *ErrorWithCode) {
row, err := models.FindPublicreportWater(ctx, db.PGInstance.BobDB, report_id)
if err != nil {
log.Error().Err(err).Msg("Failed to find pool report")
return Pool{}, newInternalError(err, "Failed to find pool report %d: %w", public_id, err)
log.Error().Err(err).Msg("Failed to find water report")
return Water{}, newInternalError(err, "Failed to find water report %d: %w", public_id, err)
}
return Pool{
return Water{
id: report_id,
publicReportID: public_id,
row: row,

View file

@ -1,5 +1,11 @@
package types
import (
"fmt"
"github.com/Gleipnir-Technology/nidus-sync/db/enums"
)
type Address struct {
Country string `db:"country" json:"country"`
Locality string `db:"locality" json:"locality"`
@ -9,3 +15,10 @@ type Address struct {
Street string `db:"street" json:"street"`
Unit string `db:"unit" json:"unit"`
}
func (a Address) String() string {
return fmt.Sprintf("%s %s, %s, %s, %s, %s", a.Number, a.Street, a.Locality, a.Region, a.PostalCode, a.Country)
}
func (a Address) CountryEnum() enums.Countrytype {
return enums.CountrytypeUsa
}

21
platform/types/contact.go Normal file
View file

@ -0,0 +1,21 @@
package types
import (
"encoding/json"
)
type Contact struct {
Email *string `db:"email" json:"-"`
HasEmail bool `json:"has_email"`
HasPhone bool `json:"has_phone"`
Name *string `db:"name"`
Phone *string `db:"phone" json:"-"`
}
func (c *Contact) MarshalJSON() ([]byte, error) {
to_marshal := make(map[string]interface{}, 0)
to_marshal["name"] = c.Name
to_marshal["has_email"] = (c.Email != nil && *c.Email != "")
to_marshal["has_phone"] = (c.Phone != nil && *c.Phone != "")
return json.Marshal(to_marshal)
}

View file

@ -10,7 +10,6 @@ import (
type ContentMock struct {
District ContentDistrict
MapboxToken string
ReportID string
URL ContentURL
}
@ -18,9 +17,7 @@ type ContentMock struct {
func addMockRoutes(r chi.Router) {
r.Get("/", renderMock("rmo/mock/root.html"))
r.Get("/district/{slug}", renderMock("rmo/mock/district-root.html"))
r.Get("/district/{slug}/nuisance", renderMock("rmo/mock/nuisance.html"))
r.Get("/district/{slug}/nuisance-submit-complete", renderMock("rmo/mock/nuisance-submit-complete.html"))
r.Get("/district/{slug}/water", renderMock("rmo/mock/water.html"))
r.Get("/nuisance", renderMock("rmo/mock/nuisance.html"))
r.Get("/nuisance-submit-complete", renderMock("rmo/mock/nuisance-submit-complete.html"))
}
@ -51,7 +48,6 @@ func renderMock(t string) func(http.ResponseWriter, *http.Request) {
URLLogo: config.MakeURLNidus("/api/district/%s/logo", slug),
URLWebsite: "http://www.deltavcd.com/",
},
MapboxToken: config.MapboxToken,
ReportID: "abcd-1234-5678",
URL: makeContentURLMock(slug),
},

View file

@ -9,7 +9,6 @@ import (
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/nidus-sync/config"
"github.com/Gleipnir-Technology/nidus-sync/db"
"github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
@ -37,7 +36,6 @@ func getNuisance(w http.ResponseWriter, r *http.Request) {
"rmo/nuisance.html",
ContentNuisance{
District: nil,
MapboxToken: config.MapboxToken,
URL: makeContentURL(nil),
},
)
@ -53,7 +51,6 @@ func getNuisanceDistrict(w http.ResponseWriter, r *http.Request) {
"rmo/nuisance.html",
ContentNuisance{
District: newContentDistrict(district),
MapboxToken: config.MapboxToken,
URL: makeContentURL(nil),
},
)
@ -85,9 +82,9 @@ func postNuisance(w http.ResponseWriter, r *http.Request) {
additional_info := r.PostFormValue("additional-info")
address := r.PostFormValue("address")
address_country := r.PostFormValue("address-country")
address_locality := r.PostFormValue("address-locality")
address_number := r.PostFormValue("address-number")
address_place := r.PostFormValue("address-place")
address_postcode := r.PostFormValue("address-postcode")
address_postal_code := r.PostFormValue("address-postalcode")
address_region := r.PostFormValue("address-region")
address_street := r.PostFormValue("address-street")
duration_str := postFormValueOrNone(r, "duration")
@ -171,11 +168,11 @@ func postNuisance(w http.ResponseWriter, r *http.Request) {
setter := models.PublicreportNuisanceSetter{
AdditionalInfo: omit.From(additional_info),
Address: omit.From(address),
AddressRaw: omit.From(address),
AddressCountry: omit.From(address_country),
AddressNumber: omit.From(address_number),
AddressPlace: omit.From(address_place),
AddressPostcode: omit.From(address_postcode),
AddressLocality: omit.From(address_locality),
AddressPostalCode: omit.From(address_postal_code),
AddressRegion: omit.From(address_region),
AddressStreet: omit.From(address_street),
Created: omit.From(time.Now()),

View file

@ -11,7 +11,6 @@ import (
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/nidus-sync/config"
"github.com/Gleipnir-Technology/nidus-sync/db"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
"github.com/Gleipnir-Technology/nidus-sync/db/sql"
@ -29,13 +28,11 @@ import (
type ContentStatus struct {
District *ContentDistrict
Error string
MapboxToken string
ReportID string
URL ContentURL
}
type ContentStatusByID struct {
District *ContentDistrict
MapboxToken string
Report Report
Timeline []TimelineEntry
URL ContentURL
@ -85,7 +82,6 @@ func getStatus(w http.ResponseWriter, r *http.Request) {
report_id_str := r.URL.Query().Get("report")
content := ContentStatus{
Error: "",
MapboxToken: config.MapboxToken,
ReportID: "",
URL: makeContentURL(nil),
}
@ -121,7 +117,7 @@ func contentFromNuisance(ctx context.Context, report_id string) (result ContentS
result.District = newContentDistrict(org)
}
result.Report.ID = report_id
result.Report.Address = nuisance.Address
result.Report.Address = nuisance.AddressRaw
result.Report.Created = nuisance.Created
result.Report.ImageCount = len(images)
result.Report.Status = strings.Title(nuisance.Status.String())
@ -205,15 +201,15 @@ func contentFromNuisance(ctx context.Context, report_id string) (result ContentS
return result, err
}
func contentFromPool(ctx context.Context, report_id string) (result ContentStatusByID, err error) {
pool, err := models.PublicreportPools.Query(
models.SelectWhere.PublicreportPools.PublicID.EQ(report_id),
func contentFromWater(ctx context.Context, report_id string) (result ContentStatusByID, err error) {
pool, err := models.PublicreportWaters.Query(
models.SelectWhere.PublicreportWaters.PublicID.EQ(report_id),
).One(ctx, db.PGInstance.BobDB)
if err != nil {
return result, fmt.Errorf("Failed to query pool %s: %w", report_id, err)
}
images, err := sql.PublicreportImageWithJSONByPoolID(pool.ID).All(ctx, db.PGInstance.BobDB)
images, err := sql.PublicreportImageWithJSONByWaterID(pool.ID).All(ctx, db.PGInstance.BobDB)
if err != nil {
return result, fmt.Errorf("Failed to get images %s: %w", report_id, err)
}
@ -228,7 +224,7 @@ func contentFromPool(ctx context.Context, report_id string) (result ContentStatu
}
result.Report.ID = report_id
result.Report.Address = pool.Address
result.Report.Address = pool.AddressRaw
result.Report.Created = pool.Created
result.Report.ImageCount = len(images)
result.Report.Status = strings.Title(pool.Status.String())
@ -304,13 +300,12 @@ func getStatusByID(w http.ResponseWriter, r *http.Request) {
case "nuisance":
content, err = contentFromNuisance(ctx, report_id)
case "pool":
content, err = contentFromPool(ctx, report_id)
content, err = contentFromWater(ctx, report_id)
}
if err != nil {
respondError(w, "Failed to generate report content", err, http.StatusInternalServerError)
return
}
content.MapboxToken = config.MapboxToken
content.URL = makeContentURL(nil)
html.RenderOrError(
w,

View file

@ -8,7 +8,6 @@ import (
"github.com/Gleipnir-Technology/bob"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/um"
"github.com/Gleipnir-Technology/nidus-sync/config"
"github.com/Gleipnir-Technology/nidus-sync/db"
"github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
@ -19,9 +18,8 @@ import (
"github.com/rs/zerolog/log"
)
type ContentPool struct {
type ContentWater struct {
District *ContentDistrict
MapboxToken string
URL ContentURL
}
@ -29,9 +27,8 @@ func getWater(w http.ResponseWriter, r *http.Request) {
html.RenderOrError(
w,
"rmo/water.html",
ContentPool{
ContentWater{
District: nil,
MapboxToken: config.MapboxToken,
URL: makeContentURL(nil),
},
)
@ -45,9 +42,8 @@ func getWaterDistrict(w http.ResponseWriter, r *http.Request) {
html.RenderOrError(
w,
"rmo/water.html",
ContentPool{
ContentWater{
District: newContentDistrict(district),
MapboxToken: config.MapboxToken,
URL: makeContentURL(district),
},
)
@ -65,11 +61,11 @@ func postWater(w http.ResponseWriter, r *http.Request) {
access_gate := boolFromForm(r, "access-gate")
access_locked := boolFromForm(r, "access-locked")
access_other := boolFromForm(r, "access-other")
address := r.FormValue("address")
address_raw := r.FormValue("address")
address_country := r.FormValue("address-country")
address_locality := r.FormValue("address-locality")
address_number := r.FormValue("address-number")
address_postcode := r.FormValue("address-postcode")
address_place := r.FormValue("address-place")
address_postalcode := r.FormValue("address-postalcode")
address_region := r.FormValue("address-region")
address_street := r.FormValue("address-street")
comments := r.FormValue("comments")
@ -125,18 +121,18 @@ func postWater(w http.ResponseWriter, r *http.Request) {
log.Warn().Err(err).Msg("Failed to match district")
}
setter := models.PublicreportPoolSetter{
setter := models.PublicreportWaterSetter{
AccessComments: omit.From(access_comments),
AccessDog: omit.From(access_dog),
AccessFence: omit.From(access_fence),
AccessGate: omit.From(access_gate),
AccessLocked: omit.From(access_locked),
AccessOther: omit.From(access_other),
Address: omit.From(address),
AddressRaw: omit.From(address_raw),
AddressCountry: omit.From(address_country),
AddressLocality: omit.From(address_locality),
AddressNumber: omit.From(address_number),
AddressPostCode: omit.From(address_postcode),
AddressPlace: omit.From(address_place),
AddressPostalCode: omit.From(address_postalcode),
AddressStreet: omit.From(address_street),
AddressRegion: omit.From(address_region),
Comments: omit.From(comments),
@ -160,7 +156,7 @@ func postWater(w http.ResponseWriter, r *http.Request) {
ReporterPhone: omit.From(""),
Status: omit.From(enums.PublicreportReportstatustypeReported),
}
pool, err := models.PublicreportPools.Insert(&setter).One(ctx, tx)
pool, err := models.PublicreportWaters.Insert(&setter).One(ctx, tx)
if err != nil {
respondError(w, "Failed to create database record", err, http.StatusInternalServerError)
return
@ -179,15 +175,15 @@ func postWater(w http.ResponseWriter, r *http.Request) {
}
}
log.Info().Int32("id", pool.ID).Str("public_id", pool.PublicID).Msg("Created pool report")
setters := make([]*models.PublicreportPoolImageSetter, 0)
setters := make([]*models.PublicreportWaterImageSetter, 0)
for _, image := range images {
setters = append(setters, &models.PublicreportPoolImageSetter{
setters = append(setters, &models.PublicreportWaterImageSetter{
ImageID: omit.From(int32(image.ID)),
PoolID: omit.From(int32(pool.ID)),
WaterID: omit.From(int32(pool.ID)),
})
}
if len(setters) > 0 {
_, err = models.PublicreportPoolImages.Insert(bob.ToMods(setters...)).Exec(r.Context(), tx)
_, err = models.PublicreportWaterImages.Insert(bob.ToMods(setters...)).Exec(r.Context(), tx)
if err != nil {
respondError(w, "Failed to save upload relationships", err, http.StatusInternalServerError)
return

View file

@ -10,7 +10,6 @@ import (
"github.com/Gleipnir-Technology/bob/dialect/psql/sm"
"github.com/Gleipnir-Technology/nidus-sync/auth"
"github.com/Gleipnir-Technology/nidus-sync/background"
"github.com/Gleipnir-Technology/nidus-sync/config"
"github.com/Gleipnir-Technology/nidus-sync/db"
"github.com/Gleipnir-Technology/nidus-sync/db/models"
"github.com/Gleipnir-Technology/nidus-sync/html"
@ -53,13 +52,10 @@ type contentLayoutTest struct {
User platform.User
}
type ContentDistrict struct {
MapboxToken string
}
func getDistrict(w http.ResponseWriter, r *http.Request) {
context := ContentDistrict{
MapboxToken: config.MapboxToken,
}
context := ContentDistrict{}
html.RenderOrError(w, "sync/district.html", &context)
}
@ -135,7 +131,6 @@ func getSource(ctx context.Context, r *http.Request, org *models.Organization, u
MapData: ComponentMap{
Center: latlng,
//GeoJSON:
MapboxToken: config.MapboxToken,
Markers: []MapMarker{
MapMarker{
LatLng: latlng,
@ -155,9 +150,7 @@ func getSource(ctx context.Context, r *http.Request, org *models.Organization, u
func getStadia(ctx context.Context, r *http.Request, org *models.Organization, u *models.User) (*html.Response[contentDashboard], *nhttp.ErrorWithStatus) {
data := contentDashboard{
MapData: ComponentMap{
MapboxToken: config.MapboxToken,
},
MapData: ComponentMap{},
}
return html.NewResponse("sync/stadia.html", data), nil
}
@ -189,7 +182,6 @@ func getTrap(ctx context.Context, r *http.Request, org *models.Organization, use
MapData: ComponentMap{
Center: latlng,
//GeoJSON:
MapboxToken: config.MapboxToken,
Markers: []MapMarker{
MapMarker{
LatLng: latlng,
@ -250,9 +242,7 @@ func dashboard(ctx context.Context, w http.ResponseWriter, org *models.Organizat
CountServiceRequests: int(serviceCount),
IsSyncOngoing: is_syncing,
LastSync: lastSync,
MapData: ComponentMap{
MapboxToken: config.MapboxToken,
},
MapData: ComponentMap{},
RecentRequests: requests,
}
userContent, err := auth.ContentForUser(ctx, user)

View file

@ -20,7 +20,6 @@ type MapMarker struct {
type ComponentMap struct {
Center h3.LatLng
GeoJSON interface{}
MapboxToken string
Markers []MapMarker
Zoom int
}