diff --git a/db/dberrors/address.bob.go b/db/dberrors/address.bob.go index 69797795..e45c65ee 100644 --- a/db/dberrors/address.bob.go +++ b/db/dberrors/address.bob.go @@ -11,16 +11,16 @@ var AddressErrors = &addressErrors{ s: "address_pkey", }, - ErrUniqueAddressCountryLocalityNumber_StreetKey: &UniqueConstraintError{ + ErrUniqueAddressCountryLocalityUnitNumber_StreetKey: &UniqueConstraintError{ schema: "", table: "address", - columns: []string{"country", "locality", "number_", "street"}, - s: "address_country_locality_number__street_key", + columns: []string{"country", "locality", "unit", "number_", "street"}, + s: "address_country_locality_unit_number__street_key", }, } type addressErrors struct { ErrUniqueAddressPkey *UniqueConstraintError - ErrUniqueAddressCountryLocalityNumber_StreetKey *UniqueConstraintError + ErrUniqueAddressCountryLocalityUnitNumber_StreetKey *UniqueConstraintError } diff --git a/db/dberrors/arcgis.account.bob.go b/db/dberrors/arcgis.account.bob.go new file mode 100644 index 00000000..dbd59c6b --- /dev/null +++ b/db/dberrors/arcgis.account.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var ArcgisAccountErrors = &arcgisAccountErrors{ + ErrUniqueAccountPkey: &UniqueConstraintError{ + schema: "arcgis", + table: "account", + columns: []string{"id"}, + s: "account_pkey", + }, +} + +type arcgisAccountErrors struct { + ErrUniqueAccountPkey *UniqueConstraintError +} diff --git a/db/dberrors/arcgis.oauth_token.bob.go b/db/dberrors/arcgis.oauth_token.bob.go new file mode 100644 index 00000000..0caef41d --- /dev/null +++ b/db/dberrors/arcgis.oauth_token.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var ArcgisOauthTokenErrors = &arcgisOauthTokenErrors{ + ErrUniqueOauthTokenPkey: &UniqueConstraintError{ + schema: "arcgis", + table: "oauth_token", + columns: []string{"id"}, + s: "oauth_token_pkey", + }, +} + +type arcgisOauthTokenErrors struct { + ErrUniqueOauthTokenPkey *UniqueConstraintError +} diff --git a/db/dberrors/arcgis.service_feature.bob.go b/db/dberrors/arcgis.service_feature.bob.go new file mode 100644 index 00000000..fb4e1d6c --- /dev/null +++ b/db/dberrors/arcgis.service_feature.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var ArcgisServiceFeatureErrors = &arcgisServiceFeatureErrors{ + ErrUniqueFeatureServicePkey: &UniqueConstraintError{ + schema: "arcgis", + table: "service_feature", + columns: []string{"item_id"}, + s: "feature_service_pkey", + }, +} + +type arcgisServiceFeatureErrors struct { + ErrUniqueFeatureServicePkey *UniqueConstraintError +} diff --git a/db/dberrors/arcgis.service_map.bob.go b/db/dberrors/arcgis.service_map.bob.go new file mode 100644 index 00000000..695fb572 --- /dev/null +++ b/db/dberrors/arcgis.service_map.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var ArcgisServiceMapErrors = &arcgisServiceMapErrors{ + ErrUniqueServiceMapPkey: &UniqueConstraintError{ + schema: "arcgis", + table: "service_map", + columns: []string{"arcgis_id"}, + s: "service_map_pkey", + }, +} + +type arcgisServiceMapErrors struct { + ErrUniqueServiceMapPkey *UniqueConstraintError +} diff --git a/db/dberrors/comms.mailer.bob.go b/db/dberrors/comms.mailer.bob.go new file mode 100644 index 00000000..a6955b13 --- /dev/null +++ b/db/dberrors/comms.mailer.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var CommsMailerErrors = &commsMailerErrors{ + ErrUniqueMailerPkey: &UniqueConstraintError{ + schema: "comms", + table: "mailer", + columns: []string{"id"}, + s: "mailer_pkey", + }, +} + +type commsMailerErrors struct { + ErrUniqueMailerPkey *UniqueConstraintError +} diff --git a/db/dberrors/compliance_report_request.bob.go b/db/dberrors/compliance_report_request.bob.go new file mode 100644 index 00000000..0320a8ba --- /dev/null +++ b/db/dberrors/compliance_report_request.bob.go @@ -0,0 +1,26 @@ +// 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 dberrors + +var ComplianceReportRequestErrors = &complianceReportRequestErrors{ + ErrUniqueComplianceReportRequestPkey: &UniqueConstraintError{ + schema: "", + table: "compliance_report_request", + columns: []string{"id"}, + s: "compliance_report_request_pkey", + }, + + ErrUniqueComplianceReportRequestPublicIdKey: &UniqueConstraintError{ + schema: "", + table: "compliance_report_request", + columns: []string{"public_id"}, + s: "compliance_report_request_public_id_key", + }, +} + +type complianceReportRequestErrors struct { + ErrUniqueComplianceReportRequestPkey *UniqueConstraintError + + ErrUniqueComplianceReportRequestPublicIdKey *UniqueConstraintError +} diff --git a/db/dberrors/resident.bob.go b/db/dberrors/resident.bob.go new file mode 100644 index 00000000..af60f427 --- /dev/null +++ b/db/dberrors/resident.bob.go @@ -0,0 +1,17 @@ +// 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 dberrors + +var ResidentErrors = &residentErrors{ + ErrUniqueResidentPkey: &UniqueConstraintError{ + schema: "", + table: "resident", + columns: []string{"id"}, + s: "resident_pkey", + }, +} + +type residentErrors struct { + ErrUniqueResidentPkey *UniqueConstraintError +} diff --git a/db/dbinfo/address.bob.go b/db/dbinfo/address.bob.go index cbcae265..28c32c5c 100644 --- a/db/dbinfo/address.bob.go +++ b/db/dbinfo/address.bob.go @@ -124,9 +124,9 @@ var Addresses = Table[ Where: "", Include: []string{}, }, - AddressCountryLocalityNumberStreetKey: index{ + AddressCountryLocalityUnitNumberStreetKey: index{ Type: "btree", - Name: "address_country_locality_number__street_key", + Name: "address_country_locality_unit_number__street_key", Columns: []indexColumn{ { Name: "country", @@ -138,6 +138,11 @@ var Addresses = Table[ Desc: null.FromCond(false, true), IsExpression: false, }, + { + Name: "unit", + Desc: null.FromCond(false, true), + IsExpression: false, + }, { Name: "number_", Desc: null.FromCond(false, true), @@ -151,7 +156,7 @@ var Addresses = Table[ }, Unique: true, Comment: "", - NullsFirst: []bool{false, false, false, false}, + NullsFirst: []bool{false, false, false, false, false}, NullsDistinct: false, Where: "", Include: []string{}, @@ -164,9 +169,9 @@ var Addresses = Table[ }, Uniques: addressUniques{ - AddressCountryLocalityNumberStreetKey: constraint{ - Name: "address_country_locality_number__street_key", - Columns: []string{"country", "locality", "number_", "street"}, + AddressCountryLocalityUnitNumberStreetKey: constraint{ + Name: "address_country_locality_unit_number__street_key", + Columns: []string{"country", "locality", "unit", "number_", "street"}, Comment: "", }, }, @@ -194,13 +199,13 @@ func (c addressColumns) AsSlice() []column { } type addressIndexes struct { - AddressPkey index - AddressCountryLocalityNumberStreetKey index + AddressPkey index + AddressCountryLocalityUnitNumberStreetKey index } func (i addressIndexes) AsSlice() []index { return []index{ - i.AddressPkey, i.AddressCountryLocalityNumberStreetKey, + i.AddressPkey, i.AddressCountryLocalityUnitNumberStreetKey, } } @@ -211,12 +216,12 @@ func (f addressForeignKeys) AsSlice() []foreignKey { } type addressUniques struct { - AddressCountryLocalityNumberStreetKey constraint + AddressCountryLocalityUnitNumberStreetKey constraint } func (u addressUniques) AsSlice() []constraint { return []constraint{ - u.AddressCountryLocalityNumberStreetKey, + u.AddressCountryLocalityUnitNumberStreetKey, } } diff --git a/db/dbinfo/arcgis.account.bob.go b/db/dbinfo/arcgis.account.bob.go new file mode 100644 index 00000000..8abee1e2 --- /dev/null +++ b/db/dbinfo/arcgis.account.bob.go @@ -0,0 +1,177 @@ +// 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 ArcgisAccounts = Table[ + arcgisAccountColumns, + arcgisAccountIndexes, + arcgisAccountForeignKeys, + arcgisAccountUniques, + arcgisAccountChecks, +]{ + Schema: "arcgis", + Name: "account", + Columns: arcgisAccountColumns{ + ID: column{ + Name: "id", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Name: column{ + Name: "name", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + OrganizationID: column{ + Name: "organization_id", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + URLFeatures: column{ + Name: "url_features", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + URLInsights: column{ + Name: "url_insights", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + URLGeometry: column{ + Name: "url_geometry", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + URLNotebooks: column{ + Name: "url_notebooks", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + URLTiles: column{ + Name: "url_tiles", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: arcgisAccountIndexes{ + AccountPkey: index{ + Type: "btree", + Name: "account_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "account_pkey", + Columns: []string{"id"}, + Comment: "", + }, + ForeignKeys: arcgisAccountForeignKeys{ + ArcgisAccountAccountOrganizationIDFkey: foreignKey{ + constraint: constraint{ + Name: "arcgis.account.account_organization_id_fkey", + Columns: []string{"organization_id"}, + Comment: "", + }, + ForeignTable: "organization", + ForeignColumns: []string{"id"}, + }, + }, + + Comment: "", +} + +type arcgisAccountColumns struct { + ID column + Name column + OrganizationID column + URLFeatures column + URLInsights column + URLGeometry column + URLNotebooks column + URLTiles column +} + +func (c arcgisAccountColumns) AsSlice() []column { + return []column{ + c.ID, c.Name, c.OrganizationID, c.URLFeatures, c.URLInsights, c.URLGeometry, c.URLNotebooks, c.URLTiles, + } +} + +type arcgisAccountIndexes struct { + AccountPkey index +} + +func (i arcgisAccountIndexes) AsSlice() []index { + return []index{ + i.AccountPkey, + } +} + +type arcgisAccountForeignKeys struct { + ArcgisAccountAccountOrganizationIDFkey foreignKey +} + +func (f arcgisAccountForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ArcgisAccountAccountOrganizationIDFkey, + } +} + +type arcgisAccountUniques struct{} + +func (u arcgisAccountUniques) AsSlice() []constraint { + return []constraint{} +} + +type arcgisAccountChecks struct{} + +func (c arcgisAccountChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/arcgis.layer.bob.go b/db/dbinfo/arcgis.layer.bob.go index 2c09a4d4..a5f2173b 100644 --- a/db/dbinfo/arcgis.layer.bob.go +++ b/db/dbinfo/arcgis.layer.bob.go @@ -79,7 +79,7 @@ var ArcgisLayers = Table[ Columns: []string{"feature_service_item_id"}, Comment: "", }, - ForeignTable: "arcgis.feature_service", + ForeignTable: "arcgis.service_feature", ForeignColumns: []string{"item_id"}, }, }, diff --git a/db/dbinfo/arcgis.oauth_token.bob.go b/db/dbinfo/arcgis.oauth_token.bob.go new file mode 100644 index 00000000..b7202fc3 --- /dev/null +++ b/db/dbinfo/arcgis.oauth_token.bob.go @@ -0,0 +1,227 @@ +// 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 ArcgisOauthTokens = Table[ + arcgisOauthTokenColumns, + arcgisOauthTokenIndexes, + arcgisOauthTokenForeignKeys, + arcgisOauthTokenUniques, + arcgisOauthTokenChecks, +]{ + Schema: "arcgis", + Name: "oauth_token", + Columns: arcgisOauthTokenColumns{ + AccessToken: column{ + Name: "access_token", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + AccessTokenExpires: column{ + Name: "access_token_expires", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ArcgisAccountID: column{ + Name: "arcgis_account_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + ArcgisID: column{ + Name: "arcgis_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + ArcgisLicenseTypeID: column{ + Name: "arcgis_license_type_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + Created: column{ + Name: "created", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ID: column{ + Name: "id", + DBType: "integer", + Default: "nextval('arcgis.oauth_token_id_seq'::regclass)", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + InvalidatedAt: column{ + Name: "invalidated_at", + DBType: "timestamp without time zone", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + RefreshToken: column{ + Name: "refresh_token", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + RefreshTokenExpires: column{ + Name: "refresh_token_expires", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + UserID: column{ + Name: "user_id", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Username: column{ + Name: "username", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: arcgisOauthTokenIndexes{ + OauthTokenPkey: index{ + Type: "btree", + Name: "oauth_token_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "oauth_token_pkey", + Columns: []string{"id"}, + Comment: "", + }, + ForeignKeys: arcgisOauthTokenForeignKeys{ + ArcgisOauthTokenOauthTokenArcgisAccountIDFkey: foreignKey{ + constraint: constraint{ + Name: "arcgis.oauth_token.oauth_token_arcgis_account_id_fkey", + Columns: []string{"arcgis_account_id"}, + Comment: "", + }, + ForeignTable: "arcgis.account", + ForeignColumns: []string{"id"}, + }, + ArcgisOauthTokenOauthTokenUserIDFkey: foreignKey{ + constraint: constraint{ + Name: "arcgis.oauth_token.oauth_token_user_id_fkey", + Columns: []string{"user_id"}, + Comment: "", + }, + ForeignTable: "user_", + ForeignColumns: []string{"id"}, + }, + }, + + Comment: "", +} + +type arcgisOauthTokenColumns struct { + AccessToken column + AccessTokenExpires column + ArcgisAccountID column + ArcgisID column + ArcgisLicenseTypeID column + Created column + ID column + InvalidatedAt column + RefreshToken column + RefreshTokenExpires column + UserID column + Username column +} + +func (c arcgisOauthTokenColumns) AsSlice() []column { + return []column{ + c.AccessToken, c.AccessTokenExpires, c.ArcgisAccountID, c.ArcgisID, c.ArcgisLicenseTypeID, c.Created, c.ID, c.InvalidatedAt, c.RefreshToken, c.RefreshTokenExpires, c.UserID, c.Username, + } +} + +type arcgisOauthTokenIndexes struct { + OauthTokenPkey index +} + +func (i arcgisOauthTokenIndexes) AsSlice() []index { + return []index{ + i.OauthTokenPkey, + } +} + +type arcgisOauthTokenForeignKeys struct { + ArcgisOauthTokenOauthTokenArcgisAccountIDFkey foreignKey + ArcgisOauthTokenOauthTokenUserIDFkey foreignKey +} + +func (f arcgisOauthTokenForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ArcgisOauthTokenOauthTokenArcgisAccountIDFkey, f.ArcgisOauthTokenOauthTokenUserIDFkey, + } +} + +type arcgisOauthTokenUniques struct{} + +func (u arcgisOauthTokenUniques) AsSlice() []constraint { + return []constraint{} +} + +type arcgisOauthTokenChecks struct{} + +func (c arcgisOauthTokenChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/arcgis.service_feature.bob.go b/db/dbinfo/arcgis.service_feature.bob.go new file mode 100644 index 00000000..96a3e142 --- /dev/null +++ b/db/dbinfo/arcgis.service_feature.bob.go @@ -0,0 +1,147 @@ +// 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 ArcgisServiceFeatures = Table[ + arcgisServiceFeatureColumns, + arcgisServiceFeatureIndexes, + arcgisServiceFeatureForeignKeys, + arcgisServiceFeatureUniques, + arcgisServiceFeatureChecks, +]{ + Schema: "arcgis", + Name: "service_feature", + Columns: arcgisServiceFeatureColumns{ + Extent: column{ + Name: "extent", + DBType: "box2d", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ItemID: column{ + Name: "item_id", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + SpatialReference: column{ + Name: "spatial_reference", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + URL: column{ + Name: "url", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + AccountID: column{ + Name: "account_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: arcgisServiceFeatureIndexes{ + FeatureServicePkey: index{ + Type: "btree", + Name: "feature_service_pkey", + Columns: []indexColumn{ + { + Name: "item_id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "feature_service_pkey", + Columns: []string{"item_id"}, + Comment: "", + }, + ForeignKeys: arcgisServiceFeatureForeignKeys{ + ArcgisServiceFeatureServiceFeatureAccountIDFkey: foreignKey{ + constraint: constraint{ + Name: "arcgis.service_feature.service_feature_account_id_fkey", + Columns: []string{"account_id"}, + Comment: "", + }, + ForeignTable: "arcgis.account", + ForeignColumns: []string{"id"}, + }, + }, + + Comment: "", +} + +type arcgisServiceFeatureColumns struct { + Extent column + ItemID column + SpatialReference column + URL column + AccountID column +} + +func (c arcgisServiceFeatureColumns) AsSlice() []column { + return []column{ + c.Extent, c.ItemID, c.SpatialReference, c.URL, c.AccountID, + } +} + +type arcgisServiceFeatureIndexes struct { + FeatureServicePkey index +} + +func (i arcgisServiceFeatureIndexes) AsSlice() []index { + return []index{ + i.FeatureServicePkey, + } +} + +type arcgisServiceFeatureForeignKeys struct { + ArcgisServiceFeatureServiceFeatureAccountIDFkey foreignKey +} + +func (f arcgisServiceFeatureForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ArcgisServiceFeatureServiceFeatureAccountIDFkey, + } +} + +type arcgisServiceFeatureUniques struct{} + +func (u arcgisServiceFeatureUniques) AsSlice() []constraint { + return []constraint{} +} + +type arcgisServiceFeatureChecks struct{} + +func (c arcgisServiceFeatureChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/arcgis.service_map.bob.go b/db/dbinfo/arcgis.service_map.bob.go new file mode 100644 index 00000000..911ca46c --- /dev/null +++ b/db/dbinfo/arcgis.service_map.bob.go @@ -0,0 +1,147 @@ +// 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 ArcgisServiceMaps = Table[ + arcgisServiceMapColumns, + arcgisServiceMapIndexes, + arcgisServiceMapForeignKeys, + arcgisServiceMapUniques, + arcgisServiceMapChecks, +]{ + Schema: "arcgis", + Name: "service_map", + Columns: arcgisServiceMapColumns{ + AccountID: column{ + Name: "account_id", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ArcgisID: column{ + Name: "arcgis_id", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Name: column{ + Name: "name", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Title: column{ + Name: "title", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + URL: column{ + Name: "url", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: arcgisServiceMapIndexes{ + ServiceMapPkey: index{ + Type: "btree", + Name: "service_map_pkey", + Columns: []indexColumn{ + { + Name: "arcgis_id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "service_map_pkey", + Columns: []string{"arcgis_id"}, + Comment: "", + }, + ForeignKeys: arcgisServiceMapForeignKeys{ + ArcgisServiceMapServiceMapAccountIDFkey: foreignKey{ + constraint: constraint{ + Name: "arcgis.service_map.service_map_account_id_fkey", + Columns: []string{"account_id"}, + Comment: "", + }, + ForeignTable: "arcgis.account", + ForeignColumns: []string{"id"}, + }, + }, + + Comment: "", +} + +type arcgisServiceMapColumns struct { + AccountID column + ArcgisID column + Name column + Title column + URL column +} + +func (c arcgisServiceMapColumns) AsSlice() []column { + return []column{ + c.AccountID, c.ArcgisID, c.Name, c.Title, c.URL, + } +} + +type arcgisServiceMapIndexes struct { + ServiceMapPkey index +} + +func (i arcgisServiceMapIndexes) AsSlice() []index { + return []index{ + i.ServiceMapPkey, + } +} + +type arcgisServiceMapForeignKeys struct { + ArcgisServiceMapServiceMapAccountIDFkey foreignKey +} + +func (f arcgisServiceMapForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ArcgisServiceMapServiceMapAccountIDFkey, + } +} + +type arcgisServiceMapUniques struct{} + +func (u arcgisServiceMapUniques) AsSlice() []constraint { + return []constraint{} +} + +type arcgisServiceMapChecks struct{} + +func (c arcgisServiceMapChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/comms.mailer.bob.go b/db/dbinfo/comms.mailer.bob.go new file mode 100644 index 00000000..a9c6cc56 --- /dev/null +++ b/db/dbinfo/comms.mailer.bob.go @@ -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 dbinfo + +import "github.com/aarondl/opt/null" + +var CommsMailers = Table[ + commsMailerColumns, + commsMailerIndexes, + commsMailerForeignKeys, + commsMailerUniques, + commsMailerChecks, +]{ + Schema: "comms", + Name: "mailer", + Columns: commsMailerColumns{ + Created: column{ + Name: "created", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ID: column{ + Name: "id", + DBType: "integer", + Default: "nextval('comms.mailer_id_seq'::regclass)", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Type: column{ + Name: "type_", + DBType: "comms.mailertype", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: commsMailerIndexes{ + MailerPkey: index{ + Type: "btree", + Name: "mailer_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "mailer_pkey", + Columns: []string{"id"}, + Comment: "", + }, + + Comment: "", +} + +type commsMailerColumns struct { + Created column + ID column + Type column +} + +func (c commsMailerColumns) AsSlice() []column { + return []column{ + c.Created, c.ID, c.Type, + } +} + +type commsMailerIndexes struct { + MailerPkey index +} + +func (i commsMailerIndexes) AsSlice() []index { + return []index{ + i.MailerPkey, + } +} + +type commsMailerForeignKeys struct{} + +func (f commsMailerForeignKeys) AsSlice() []foreignKey { + return []foreignKey{} +} + +type commsMailerUniques struct{} + +func (u commsMailerUniques) AsSlice() []constraint { + return []constraint{} +} + +type commsMailerChecks struct{} + +func (c commsMailerChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/compliance_report_request.bob.go b/db/dbinfo/compliance_report_request.bob.go new file mode 100644 index 00000000..4e13586d --- /dev/null +++ b/db/dbinfo/compliance_report_request.bob.go @@ -0,0 +1,196 @@ +// 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 ComplianceReportRequests = Table[ + complianceReportRequestColumns, + complianceReportRequestIndexes, + complianceReportRequestForeignKeys, + complianceReportRequestUniques, + complianceReportRequestChecks, +]{ + Schema: "", + Name: "compliance_report_request", + Columns: complianceReportRequestColumns{ + Created: column{ + Name: "created", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Creator: column{ + Name: "creator", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ID: column{ + Name: "id", + DBType: "integer", + Default: "nextval('compliance_report_request_id_seq'::regclass)", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + PublicID: column{ + Name: "public_id", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + SiteID: column{ + Name: "site_id", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + SiteVersion: column{ + Name: "site_version", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: complianceReportRequestIndexes{ + ComplianceReportRequestPkey: index{ + Type: "btree", + Name: "compliance_report_request_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + ComplianceReportRequestPublicIDKey: index{ + Type: "btree", + Name: "compliance_report_request_public_id_key", + Columns: []indexColumn{ + { + Name: "public_id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "compliance_report_request_pkey", + Columns: []string{"id"}, + Comment: "", + }, + ForeignKeys: complianceReportRequestForeignKeys{ + ComplianceReportRequestComplianceReportRequestCreatorFkey: foreignKey{ + constraint: constraint{ + Name: "compliance_report_request.compliance_report_request_creator_fkey", + Columns: []string{"creator"}, + Comment: "", + }, + ForeignTable: "user_", + ForeignColumns: []string{"id"}, + }, + ComplianceReportRequestComplianceReportRequestSiteIDSiteVersionFkey: foreignKey{ + constraint: constraint{ + Name: "compliance_report_request.compliance_report_request_site_id_site_version_fkey", + Columns: []string{"site_id", "site_version"}, + Comment: "", + }, + ForeignTable: "site", + ForeignColumns: []string{"id", "version"}, + }, + }, + Uniques: complianceReportRequestUniques{ + ComplianceReportRequestPublicIDKey: constraint{ + Name: "compliance_report_request_public_id_key", + Columns: []string{"public_id"}, + Comment: "", + }, + }, + + Comment: "", +} + +type complianceReportRequestColumns struct { + Created column + Creator column + ID column + PublicID column + SiteID column + SiteVersion column +} + +func (c complianceReportRequestColumns) AsSlice() []column { + return []column{ + c.Created, c.Creator, c.ID, c.PublicID, c.SiteID, c.SiteVersion, + } +} + +type complianceReportRequestIndexes struct { + ComplianceReportRequestPkey index + ComplianceReportRequestPublicIDKey index +} + +func (i complianceReportRequestIndexes) AsSlice() []index { + return []index{ + i.ComplianceReportRequestPkey, i.ComplianceReportRequestPublicIDKey, + } +} + +type complianceReportRequestForeignKeys struct { + ComplianceReportRequestComplianceReportRequestCreatorFkey foreignKey + ComplianceReportRequestComplianceReportRequestSiteIDSiteVersionFkey foreignKey +} + +func (f complianceReportRequestForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ComplianceReportRequestComplianceReportRequestCreatorFkey, f.ComplianceReportRequestComplianceReportRequestSiteIDSiteVersionFkey, + } +} + +type complianceReportRequestUniques struct { + ComplianceReportRequestPublicIDKey constraint +} + +func (u complianceReportRequestUniques) AsSlice() []constraint { + return []constraint{ + u.ComplianceReportRequestPublicIDKey, + } +} + +type complianceReportRequestChecks struct{} + +func (c complianceReportRequestChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/organization.bob.go b/db/dbinfo/organization.bob.go index e43b426f..51a1a352 100644 --- a/db/dbinfo/organization.bob.go +++ b/db/dbinfo/organization.bob.go @@ -33,33 +33,6 @@ var Organizations = Table[ Generated: false, AutoIncr: false, }, - ArcgisID: column{ - Name: "arcgis_id", - DBType: "text", - Default: "NULL", - Comment: "", - Nullable: true, - Generated: false, - AutoIncr: false, - }, - ArcgisName: column{ - Name: "arcgis_name", - DBType: "text", - Default: "NULL", - Comment: "", - Nullable: true, - Generated: false, - AutoIncr: false, - }, - FieldseekerURL: column{ - Name: "fieldseeker_url", - DBType: "text", - Default: "NULL", - Comment: "", - Nullable: true, - Generated: false, - AutoIncr: false, - }, ImportDistrictGid: column{ Name: "import_district_gid", DBType: "integer", @@ -276,6 +249,60 @@ var Organizations = Table[ Generated: true, AutoIncr: false, }, + MailingAddressCountry: column{ + Name: "mailing_address_country", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + MailingAddressState: column{ + Name: "mailing_address_state", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + OfficeAddressCountry: column{ + Name: "office_address_country", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + OfficeAddressState: column{ + Name: "office_address_state", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + ArcgisAccountID: column{ + Name: "arcgis_account_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + FieldseekerServiceFeatureItemID: column{ + Name: "fieldseeker_service_feature_item_id", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, }, Indexes: organizationIndexes{ OrganizationPkey: index{ @@ -336,6 +363,24 @@ var Organizations = Table[ Comment: "", }, ForeignKeys: organizationForeignKeys{ + OrganizationOrganizationArcgisAccountIDFkey: foreignKey{ + constraint: constraint{ + Name: "organization.organization_arcgis_account_id_fkey", + Columns: []string{"arcgis_account_id"}, + Comment: "", + }, + ForeignTable: "arcgis.account", + ForeignColumns: []string{"id"}, + }, + OrganizationOrganizationFieldseekerServiceFeatureItemIDFkey: foreignKey{ + constraint: constraint{ + Name: "organization.organization_fieldseeker_service_feature_item_id_fkey", + Columns: []string{"fieldseeker_service_feature_item_id"}, + Comment: "", + }, + ForeignTable: "arcgis.service_feature", + ForeignColumns: []string{"item_id"}, + }, OrganizationOrganizationImportDistrictGidFkey: foreignKey{ constraint: constraint{ Name: "organization.organization_import_district_gid_fkey", @@ -363,40 +408,43 @@ var Organizations = Table[ } type organizationColumns struct { - ID column - Name column - ArcgisID column - ArcgisName column - FieldseekerURL column - ImportDistrictGid column - Website column - LogoUUID column - Slug column - GeneralManagerName column - MailingAddressCity column - MailingAddressPostalCode column - MailingAddressStreet column - OfficeAddressCity column - OfficeAddressPostalCode column - OfficeAddressStreet column - ServiceAreaGeometry column - ServiceAreaSquareMeters column - ServiceAreaCentroid column - ServiceAreaExtent column - OfficeFax column - OfficePhone column - ServiceAreaXmin column - ServiceAreaYmin column - ServiceAreaXmax column - ServiceAreaYmax column - ServiceAreaCentroidGeojson column - ServiceAreaCentroidX column - ServiceAreaCentroidY column + ID column + Name column + ImportDistrictGid column + Website column + LogoUUID column + Slug column + GeneralManagerName column + MailingAddressCity column + MailingAddressPostalCode column + MailingAddressStreet column + OfficeAddressCity column + OfficeAddressPostalCode column + OfficeAddressStreet column + ServiceAreaGeometry column + ServiceAreaSquareMeters column + ServiceAreaCentroid column + ServiceAreaExtent column + OfficeFax column + OfficePhone column + ServiceAreaXmin column + ServiceAreaYmin column + ServiceAreaXmax column + ServiceAreaYmax column + ServiceAreaCentroidGeojson column + ServiceAreaCentroidX column + ServiceAreaCentroidY column + MailingAddressCountry column + MailingAddressState column + OfficeAddressCountry column + OfficeAddressState column + ArcgisAccountID column + FieldseekerServiceFeatureItemID column } func (c organizationColumns) AsSlice() []column { return []column{ - c.ID, c.Name, c.ArcgisID, c.ArcgisName, c.FieldseekerURL, c.ImportDistrictGid, c.Website, c.LogoUUID, c.Slug, c.GeneralManagerName, c.MailingAddressCity, c.MailingAddressPostalCode, c.MailingAddressStreet, c.OfficeAddressCity, c.OfficeAddressPostalCode, c.OfficeAddressStreet, c.ServiceAreaGeometry, c.ServiceAreaSquareMeters, c.ServiceAreaCentroid, c.ServiceAreaExtent, c.OfficeFax, c.OfficePhone, c.ServiceAreaXmin, c.ServiceAreaYmin, c.ServiceAreaXmax, c.ServiceAreaYmax, c.ServiceAreaCentroidGeojson, c.ServiceAreaCentroidX, c.ServiceAreaCentroidY, + c.ID, c.Name, c.ImportDistrictGid, c.Website, c.LogoUUID, c.Slug, c.GeneralManagerName, c.MailingAddressCity, c.MailingAddressPostalCode, c.MailingAddressStreet, c.OfficeAddressCity, c.OfficeAddressPostalCode, c.OfficeAddressStreet, c.ServiceAreaGeometry, c.ServiceAreaSquareMeters, c.ServiceAreaCentroid, c.ServiceAreaExtent, c.OfficeFax, c.OfficePhone, c.ServiceAreaXmin, c.ServiceAreaYmin, c.ServiceAreaXmax, c.ServiceAreaYmax, c.ServiceAreaCentroidGeojson, c.ServiceAreaCentroidX, c.ServiceAreaCentroidY, c.MailingAddressCountry, c.MailingAddressState, c.OfficeAddressCountry, c.OfficeAddressState, c.ArcgisAccountID, c.FieldseekerServiceFeatureItemID, } } @@ -413,12 +461,14 @@ func (i organizationIndexes) AsSlice() []index { } type organizationForeignKeys struct { - OrganizationOrganizationImportDistrictGidFkey foreignKey + OrganizationOrganizationArcgisAccountIDFkey foreignKey + OrganizationOrganizationFieldseekerServiceFeatureItemIDFkey foreignKey + OrganizationOrganizationImportDistrictGidFkey foreignKey } func (f organizationForeignKeys) AsSlice() []foreignKey { return []foreignKey{ - f.OrganizationOrganizationImportDistrictGidFkey, + f.OrganizationOrganizationArcgisAccountIDFkey, f.OrganizationOrganizationFieldseekerServiceFeatureItemIDFkey, f.OrganizationOrganizationImportDistrictGidFkey, } } diff --git a/db/dbinfo/parcel.bob.go b/db/dbinfo/parcel.bob.go index 845bece8..865941f9 100644 --- a/db/dbinfo/parcel.bob.go +++ b/db/dbinfo/parcel.bob.go @@ -18,18 +18,18 @@ var Parcels = Table[ Apn: column{ Name: "apn", DBType: "text", - Default: "", + Default: "NULL", Comment: "", - Nullable: false, + Nullable: true, Generated: false, AutoIncr: false, }, Description: column{ Name: "description", DBType: "text", - Default: "", + Default: "NULL", Comment: "", - Nullable: false, + Nullable: true, Generated: false, AutoIncr: false, }, diff --git a/db/dbinfo/pool.bob.go b/db/dbinfo/pool.bob.go index 149b10d2..3bdd31a6 100644 --- a/db/dbinfo/pool.bob.go +++ b/db/dbinfo/pool.bob.go @@ -54,9 +54,18 @@ var Pools = Table[ SiteID: column{ Name: "site_id", DBType: "integer", - Default: "NULL", + Default: "", Comment: "", - Nullable: true, + Nullable: false, + Generated: false, + AutoIncr: false, + }, + SiteVersion: column{ + Name: "site_version", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, Generated: false, AutoIncr: false, }, @@ -95,22 +104,32 @@ var Pools = Table[ ForeignTable: "user_", ForeignColumns: []string{"id"}, }, + PoolPoolSiteIDSiteVersionFkey: foreignKey{ + constraint: constraint{ + Name: "pool.pool_site_id_site_version_fkey", + Columns: []string{"site_id", "site_version"}, + Comment: "", + }, + ForeignTable: "site", + ForeignColumns: []string{"id", "version"}, + }, }, Comment: "", } type poolColumns struct { - Condition column - Created column - CreatorID column - ID column - SiteID column + Condition column + Created column + CreatorID column + ID column + SiteID column + SiteVersion column } func (c poolColumns) AsSlice() []column { return []column{ - c.Condition, c.Created, c.CreatorID, c.ID, c.SiteID, + c.Condition, c.Created, c.CreatorID, c.ID, c.SiteID, c.SiteVersion, } } @@ -125,12 +144,13 @@ func (i poolIndexes) AsSlice() []index { } type poolForeignKeys struct { - PoolPoolCreatorIDFkey foreignKey + PoolPoolCreatorIDFkey foreignKey + PoolPoolSiteIDSiteVersionFkey foreignKey } func (f poolForeignKeys) AsSlice() []foreignKey { return []foreignKey{ - f.PoolPoolCreatorIDFkey, + f.PoolPoolCreatorIDFkey, f.PoolPoolSiteIDSiteVersionFkey, } } diff --git a/db/dbinfo/resident.bob.go b/db/dbinfo/resident.bob.go new file mode 100644 index 00000000..2a1d097b --- /dev/null +++ b/db/dbinfo/resident.bob.go @@ -0,0 +1,207 @@ +// 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 Residents = Table[ + residentColumns, + residentIndexes, + residentForeignKeys, + residentUniques, + residentChecks, +]{ + Schema: "", + Name: "resident", + Columns: residentColumns{ + AddressID: column{ + Name: "address_id", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Created: column{ + Name: "created", + DBType: "timestamp without time zone", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Creator: column{ + Name: "creator", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + ID: column{ + Name: "id", + DBType: "integer", + Default: "nextval('resident_id_seq'::regclass)", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + Name: column{ + Name: "name", + DBType: "text", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + PhoneMobile: column{ + Name: "phone_mobile", + DBType: "text", + Default: "NULL", + Comment: "", + Nullable: true, + Generated: false, + AutoIncr: false, + }, + SiteID: column{ + Name: "site_id", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + SiteVersion: column{ + Name: "site_version", + DBType: "integer", + Default: "", + Comment: "", + Nullable: false, + Generated: false, + AutoIncr: false, + }, + }, + Indexes: residentIndexes{ + ResidentPkey: index{ + Type: "btree", + Name: "resident_pkey", + Columns: []indexColumn{ + { + Name: "id", + Desc: null.FromCond(false, true), + IsExpression: false, + }, + }, + Unique: true, + Comment: "", + NullsFirst: []bool{false}, + NullsDistinct: false, + Where: "", + Include: []string{}, + }, + }, + PrimaryKey: &constraint{ + Name: "resident_pkey", + Columns: []string{"id"}, + Comment: "", + }, + ForeignKeys: residentForeignKeys{ + ResidentResidentAddressIDFkey: foreignKey{ + constraint: constraint{ + Name: "resident.resident_address_id_fkey", + Columns: []string{"address_id"}, + Comment: "", + }, + ForeignTable: "address", + ForeignColumns: []string{"id"}, + }, + ResidentResidentCreatorFkey: foreignKey{ + constraint: constraint{ + Name: "resident.resident_creator_fkey", + Columns: []string{"creator"}, + Comment: "", + }, + ForeignTable: "user_", + ForeignColumns: []string{"id"}, + }, + ResidentResidentPhoneMobileFkey: foreignKey{ + constraint: constraint{ + Name: "resident.resident_phone_mobile_fkey", + Columns: []string{"phone_mobile"}, + Comment: "", + }, + ForeignTable: "comms.phone", + ForeignColumns: []string{"e164"}, + }, + ResidentResidentSiteIDSiteVersionFkey: foreignKey{ + constraint: constraint{ + Name: "resident.resident_site_id_site_version_fkey", + Columns: []string{"site_id", "site_version"}, + Comment: "", + }, + ForeignTable: "site", + ForeignColumns: []string{"id", "version"}, + }, + }, + + Comment: "", +} + +type residentColumns struct { + AddressID column + Created column + Creator column + ID column + Name column + PhoneMobile column + SiteID column + SiteVersion column +} + +func (c residentColumns) AsSlice() []column { + return []column{ + c.AddressID, c.Created, c.Creator, c.ID, c.Name, c.PhoneMobile, c.SiteID, c.SiteVersion, + } +} + +type residentIndexes struct { + ResidentPkey index +} + +func (i residentIndexes) AsSlice() []index { + return []index{ + i.ResidentPkey, + } +} + +type residentForeignKeys struct { + ResidentResidentAddressIDFkey foreignKey + ResidentResidentCreatorFkey foreignKey + ResidentResidentPhoneMobileFkey foreignKey + ResidentResidentSiteIDSiteVersionFkey foreignKey +} + +func (f residentForeignKeys) AsSlice() []foreignKey { + return []foreignKey{ + f.ResidentResidentAddressIDFkey, f.ResidentResidentCreatorFkey, f.ResidentResidentPhoneMobileFkey, f.ResidentResidentSiteIDSiteVersionFkey, + } +} + +type residentUniques struct{} + +func (u residentUniques) AsSlice() []constraint { + return []constraint{} +} + +type residentChecks struct{} + +func (c residentChecks) AsSlice() []check { + return []check{} +} diff --git a/db/dbinfo/site.bob.go b/db/dbinfo/site.bob.go index a0154cfb..f72d5827 100644 --- a/db/dbinfo/site.bob.go +++ b/db/dbinfo/site.bob.go @@ -96,18 +96,18 @@ var Sites = Table[ Generated: false, AutoIncr: false, }, - ResidentOwned: column{ - Name: "resident_owned", - DBType: "boolean", - Default: "NULL", + ParcelID: column{ + Name: "parcel_id", + DBType: "integer", + Default: "", Comment: "", - Nullable: true, + Nullable: false, Generated: false, AutoIncr: false, }, - ResidentPhoneE164: column{ - Name: "resident_phone_e164", - DBType: "text", + ResidentOwned: column{ + Name: "resident_owned", + DBType: "boolean", Default: "NULL", Comment: "", Nullable: true, @@ -207,6 +207,15 @@ var Sites = Table[ ForeignTable: "fileupload.file", ForeignColumns: []string{"id"}, }, + SiteSiteParcelIDFkey: foreignKey{ + constraint: constraint{ + Name: "site.site_parcel_id_fkey", + Columns: []string{"parcel_id"}, + Comment: "", + }, + ForeignTable: "parcel", + ForeignColumns: []string{"id"}, + }, }, Uniques: siteUniques{ SiteAddressIDKey: constraint{ @@ -220,24 +229,24 @@ var Sites = Table[ } type siteColumns struct { - AddressID column - Created column - CreatorID column - FileID column - ID column - Notes column - OrganizationID column - OwnerName column - OwnerPhoneE164 column - ResidentOwned column - ResidentPhoneE164 column - Tags column - Version column + AddressID column + Created column + CreatorID column + FileID column + ID column + Notes column + OrganizationID column + OwnerName column + OwnerPhoneE164 column + ParcelID column + ResidentOwned column + Tags column + Version column } func (c siteColumns) AsSlice() []column { return []column{ - c.AddressID, c.Created, c.CreatorID, c.FileID, c.ID, c.Notes, c.OrganizationID, c.OwnerName, c.OwnerPhoneE164, c.ResidentOwned, c.ResidentPhoneE164, c.Tags, c.Version, + c.AddressID, c.Created, c.CreatorID, c.FileID, c.ID, c.Notes, c.OrganizationID, c.OwnerName, c.OwnerPhoneE164, c.ParcelID, c.ResidentOwned, c.Tags, c.Version, } } @@ -256,11 +265,12 @@ type siteForeignKeys struct { SiteSiteAddressIDFkey foreignKey SiteSiteCreatorIDFkey foreignKey SiteSiteFileIDFkey foreignKey + SiteSiteParcelIDFkey foreignKey } func (f siteForeignKeys) AsSlice() []foreignKey { return []foreignKey{ - f.SiteSiteAddressIDFkey, f.SiteSiteCreatorIDFkey, f.SiteSiteFileIDFkey, + f.SiteSiteAddressIDFkey, f.SiteSiteCreatorIDFkey, f.SiteSiteFileIDFkey, f.SiteSiteParcelIDFkey, } } diff --git a/db/enums/enums.bob.go b/db/enums/enums.bob.go index ecb6cad5..9aee274d 100644 --- a/db/enums/enums.bob.go +++ b/db/enums/enums.bob.go @@ -457,6 +457,76 @@ func (e *Audiodatatype) Scan(value any) error { return nil } +// Enum values for CommsMailertype +const ( + CommsMailertypeGreenPool CommsMailertype = "green-pool" +) + +func AllCommsMailertype() []CommsMailertype { + return []CommsMailertype{ + CommsMailertypeGreenPool, + } +} + +type CommsMailertype string + +func (e CommsMailertype) String() string { + return string(e) +} + +func (e CommsMailertype) Valid() bool { + switch e { + case CommsMailertypeGreenPool: + return true + default: + return false + } +} + +// useful when testing in other packages +func (e CommsMailertype) All() []CommsMailertype { + return AllCommsMailertype() +} + +func (e CommsMailertype) MarshalText() ([]byte, error) { + return []byte(e), nil +} + +func (e *CommsMailertype) UnmarshalText(text []byte) error { + return e.Scan(text) +} + +func (e CommsMailertype) MarshalBinary() ([]byte, error) { + return []byte(e), nil +} + +func (e *CommsMailertype) UnmarshalBinary(data []byte) error { + return e.Scan(data) +} + +func (e CommsMailertype) Value() (driver.Value, error) { + return string(e), nil +} + +func (e *CommsMailertype) Scan(value any) error { + switch x := value.(type) { + case string: + *e = CommsMailertype(x) + case []byte: + *e = CommsMailertype(x) + case nil: + return fmt.Errorf("cannot nil into CommsMailertype") + default: + return fmt.Errorf("cannot scan type %T: %v", value, value) + } + + if !e.Valid() { + return fmt.Errorf("invalid CommsMailertype value: %s", *e) + } + + return nil +} + // Enum values for CommsMessagetypeemail const ( CommsMessagetypeemailInitialContact CommsMessagetypeemail = "initial-contact" diff --git a/db/factory/address.bob.go b/db/factory/address.bob.go index a12c7a49..893379b1 100644 --- a/db/factory/address.bob.go +++ b/db/factory/address.bob.go @@ -54,9 +54,14 @@ type AddressTemplate struct { } type addressR struct { - Site *addressRSiteR + Residents []*addressRResidentsR + Site *addressRSiteR } +type addressRResidentsR struct { + number int + o *ResidentTemplate +} type addressRSiteR struct { o *SiteTemplate } @@ -71,6 +76,19 @@ func (o *AddressTemplate) Apply(ctx context.Context, mods ...AddressMod) { // setModelRels creates and sets the relationships on *models.Address // according to the relationships in the template. Nothing is inserted into the db func (t AddressTemplate) setModelRels(o *models.Address) { + if t.r.Residents != nil { + rel := models.ResidentSlice{} + for _, r := range t.r.Residents { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.AddressID = o.ID // h2 + rel.R.Address = o + } + rel = append(rel, related...) + } + o.R.Residents = rel + } + if t.r.Site != nil { rel := t.r.Site.o.Build() rel.R.Address = o @@ -240,18 +258,38 @@ func ensureCreatableAddress(m *models.AddressSetter) { func (o *AddressTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Address) error { var err error + isResidentsDone, _ := addressRelResidentsCtx.Value(ctx) + if !isResidentsDone && o.r.Residents != nil { + ctx = addressRelResidentsCtx.WithValue(ctx, true) + for _, r := range o.r.Residents { + if r.o.alreadyPersisted { + m.R.Residents = append(m.R.Residents, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachResidents(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + isSiteDone, _ := addressRelSiteCtx.Value(ctx) if !isSiteDone && o.r.Site != nil { ctx = addressRelSiteCtx.WithValue(ctx, true) if o.r.Site.o.alreadyPersisted { m.R.Site = o.r.Site.o.Build() } else { - var rel0 *models.Site - rel0, err = o.r.Site.o.Create(ctx, exec) + var rel1 *models.Site + rel1, err = o.r.Site.o.Create(ctx, exec) if err != nil { return err } - err = m.AttachSite(ctx, exec, rel0) + err = m.AttachSite(ctx, exec, rel1) if err != nil { return err } @@ -717,3 +755,51 @@ func (m addressMods) WithoutSite() AddressMod { o.r.Site = nil }) } + +func (m addressMods) WithResidents(number int, related *ResidentTemplate) AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + o.r.Residents = []*addressRResidentsR{{ + number: number, + o: related, + }} + }) +} + +func (m addressMods) WithNewResidents(number int, mods ...ResidentMod) AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.WithResidents(number, related).Apply(ctx, o) + }) +} + +func (m addressMods) AddResidents(number int, related *ResidentTemplate) AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + o.r.Residents = append(o.r.Residents, &addressRResidentsR{ + number: number, + o: related, + }) + }) +} + +func (m addressMods) AddNewResidents(number int, mods ...ResidentMod) AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.AddResidents(number, related).Apply(ctx, o) + }) +} + +func (m addressMods) AddExistingResidents(existingModels ...*models.Resident) AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + for _, em := range existingModels { + o.r.Residents = append(o.r.Residents, &addressRResidentsR{ + o: o.f.FromExistingResident(em), + }) + } + }) +} + +func (m addressMods) WithoutResidents() AddressMod { + return AddressModFunc(func(ctx context.Context, o *AddressTemplate) { + o.r.Residents = nil + }) +} diff --git a/db/factory/arcgis.account.bob.go b/db/factory/arcgis.account.bob.go new file mode 100644 index 00000000..c985466c --- /dev/null +++ b/db/factory/arcgis.account.bob.go @@ -0,0 +1,1069 @@ +// 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 factory + +import ( + "context" + "testing" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/jaswdr/faker/v2" +) + +type ArcgisAccountMod interface { + Apply(context.Context, *ArcgisAccountTemplate) +} + +type ArcgisAccountModFunc func(context.Context, *ArcgisAccountTemplate) + +func (f ArcgisAccountModFunc) Apply(ctx context.Context, n *ArcgisAccountTemplate) { + f(ctx, n) +} + +type ArcgisAccountModSlice []ArcgisAccountMod + +func (mods ArcgisAccountModSlice) Apply(ctx context.Context, n *ArcgisAccountTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ArcgisAccountTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ArcgisAccountTemplate struct { + ID func() string + Name func() string + OrganizationID func() int32 + URLFeatures func() null.Val[string] + URLInsights func() null.Val[string] + URLGeometry func() null.Val[string] + URLNotebooks func() null.Val[string] + URLTiles func() null.Val[string] + + r arcgisAccountR + f *Factory + + alreadyPersisted bool +} + +type arcgisAccountR struct { + Organization *arcgisAccountROrganizationR + ArcgisAccountOauthTokens []*arcgisAccountRArcgisAccountOauthTokensR + ServiceFeatures []*arcgisAccountRServiceFeaturesR + ServiceMaps []*arcgisAccountRServiceMapsR + ArcgisAccountOrganizations []*arcgisAccountRArcgisAccountOrganizationsR +} + +type arcgisAccountROrganizationR struct { + o *OrganizationTemplate +} +type arcgisAccountRArcgisAccountOauthTokensR struct { + number int + o *ArcgisOauthTokenTemplate +} +type arcgisAccountRServiceFeaturesR struct { + number int + o *ArcgisServiceFeatureTemplate +} +type arcgisAccountRServiceMapsR struct { + number int + o *ArcgisServiceMapTemplate +} +type arcgisAccountRArcgisAccountOrganizationsR struct { + number int + o *OrganizationTemplate +} + +// Apply mods to the ArcgisAccountTemplate +func (o *ArcgisAccountTemplate) Apply(ctx context.Context, mods ...ArcgisAccountMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.ArcgisAccount +// according to the relationships in the template. Nothing is inserted into the db +func (t ArcgisAccountTemplate) setModelRels(o *models.ArcgisAccount) { + if t.r.Organization != nil { + rel := t.r.Organization.o.Build() + rel.R.Accounts = append(rel.R.Accounts, o) + o.OrganizationID = rel.ID // h2 + o.R.Organization = rel + } + + if t.r.ArcgisAccountOauthTokens != nil { + rel := models.ArcgisOauthTokenSlice{} + for _, r := range t.r.ArcgisAccountOauthTokens { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.ArcgisAccountID = null.From(o.ID) // h2 + rel.R.ArcgisAccountAccount = o + } + rel = append(rel, related...) + } + o.R.ArcgisAccountOauthTokens = rel + } + + if t.r.ServiceFeatures != nil { + rel := models.ArcgisServiceFeatureSlice{} + for _, r := range t.r.ServiceFeatures { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.AccountID = null.From(o.ID) // h2 + rel.R.Account = o + } + rel = append(rel, related...) + } + o.R.ServiceFeatures = rel + } + + if t.r.ServiceMaps != nil { + rel := models.ArcgisServiceMapSlice{} + for _, r := range t.r.ServiceMaps { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.AccountID = o.ID // h2 + rel.R.Account = o + } + rel = append(rel, related...) + } + o.R.ServiceMaps = rel + } + + if t.r.ArcgisAccountOrganizations != nil { + rel := models.OrganizationSlice{} + for _, r := range t.r.ArcgisAccountOrganizations { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.ArcgisAccountID = null.From(o.ID) // h2 + rel.R.ArcgisAccountAccount = o + } + rel = append(rel, related...) + } + o.R.ArcgisAccountOrganizations = rel + } +} + +// BuildSetter returns an *models.ArcgisAccountSetter +// this does nothing with the relationship templates +func (o ArcgisAccountTemplate) BuildSetter() *models.ArcgisAccountSetter { + m := &models.ArcgisAccountSetter{} + + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.Name != nil { + val := o.Name() + m.Name = omit.From(val) + } + if o.OrganizationID != nil { + val := o.OrganizationID() + m.OrganizationID = omit.From(val) + } + if o.URLFeatures != nil { + val := o.URLFeatures() + m.URLFeatures = omitnull.FromNull(val) + } + if o.URLInsights != nil { + val := o.URLInsights() + m.URLInsights = omitnull.FromNull(val) + } + if o.URLGeometry != nil { + val := o.URLGeometry() + m.URLGeometry = omitnull.FromNull(val) + } + if o.URLNotebooks != nil { + val := o.URLNotebooks() + m.URLNotebooks = omitnull.FromNull(val) + } + if o.URLTiles != nil { + val := o.URLTiles() + m.URLTiles = omitnull.FromNull(val) + } + + return m +} + +// BuildManySetter returns an []*models.ArcgisAccountSetter +// this does nothing with the relationship templates +func (o ArcgisAccountTemplate) BuildManySetter(number int) []*models.ArcgisAccountSetter { + m := make([]*models.ArcgisAccountSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.ArcgisAccount +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisAccountTemplate.Create +func (o ArcgisAccountTemplate) Build() *models.ArcgisAccount { + m := &models.ArcgisAccount{} + + if o.ID != nil { + m.ID = o.ID() + } + if o.Name != nil { + m.Name = o.Name() + } + if o.OrganizationID != nil { + m.OrganizationID = o.OrganizationID() + } + if o.URLFeatures != nil { + m.URLFeatures = o.URLFeatures() + } + if o.URLInsights != nil { + m.URLInsights = o.URLInsights() + } + if o.URLGeometry != nil { + m.URLGeometry = o.URLGeometry() + } + if o.URLNotebooks != nil { + m.URLNotebooks = o.URLNotebooks() + } + if o.URLTiles != nil { + m.URLTiles = o.URLTiles() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ArcgisAccountSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisAccountTemplate.CreateMany +func (o ArcgisAccountTemplate) BuildMany(number int) models.ArcgisAccountSlice { + m := make(models.ArcgisAccountSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableArcgisAccount(m *models.ArcgisAccountSetter) { + if !(m.ID.IsValue()) { + val := random_string(nil) + m.ID = omit.From(val) + } + if !(m.Name.IsValue()) { + val := random_string(nil) + m.Name = omit.From(val) + } + if !(m.OrganizationID.IsValue()) { + val := random_int32(nil) + m.OrganizationID = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.ArcgisAccount +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ArcgisAccountTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.ArcgisAccount) error { + var err error + + isArcgisAccountOauthTokensDone, _ := arcgisAccountRelArcgisAccountOauthTokensCtx.Value(ctx) + if !isArcgisAccountOauthTokensDone && o.r.ArcgisAccountOauthTokens != nil { + ctx = arcgisAccountRelArcgisAccountOauthTokensCtx.WithValue(ctx, true) + for _, r := range o.r.ArcgisAccountOauthTokens { + if r.o.alreadyPersisted { + m.R.ArcgisAccountOauthTokens = append(m.R.ArcgisAccountOauthTokens, r.o.Build()) + } else { + rel1, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachArcgisAccountOauthTokens(ctx, exec, rel1...) + if err != nil { + return err + } + } + } + } + + isServiceFeaturesDone, _ := arcgisAccountRelServiceFeaturesCtx.Value(ctx) + if !isServiceFeaturesDone && o.r.ServiceFeatures != nil { + ctx = arcgisAccountRelServiceFeaturesCtx.WithValue(ctx, true) + for _, r := range o.r.ServiceFeatures { + if r.o.alreadyPersisted { + m.R.ServiceFeatures = append(m.R.ServiceFeatures, r.o.Build()) + } else { + rel2, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachServiceFeatures(ctx, exec, rel2...) + if err != nil { + return err + } + } + } + } + + isServiceMapsDone, _ := arcgisAccountRelServiceMapsCtx.Value(ctx) + if !isServiceMapsDone && o.r.ServiceMaps != nil { + ctx = arcgisAccountRelServiceMapsCtx.WithValue(ctx, true) + for _, r := range o.r.ServiceMaps { + if r.o.alreadyPersisted { + m.R.ServiceMaps = append(m.R.ServiceMaps, r.o.Build()) + } else { + rel3, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachServiceMaps(ctx, exec, rel3...) + if err != nil { + return err + } + } + } + } + + isArcgisAccountOrganizationsDone, _ := arcgisAccountRelArcgisAccountOrganizationsCtx.Value(ctx) + if !isArcgisAccountOrganizationsDone && o.r.ArcgisAccountOrganizations != nil { + ctx = arcgisAccountRelArcgisAccountOrganizationsCtx.WithValue(ctx, true) + for _, r := range o.r.ArcgisAccountOrganizations { + if r.o.alreadyPersisted { + m.R.ArcgisAccountOrganizations = append(m.R.ArcgisAccountOrganizations, r.o.Build()) + } else { + rel4, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachArcgisAccountOrganizations(ctx, exec, rel4...) + if err != nil { + return err + } + } + } + } + + return err +} + +// Create builds a arcgisAccount and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ArcgisAccountTemplate) Create(ctx context.Context, exec bob.Executor) (*models.ArcgisAccount, error) { + var err error + opt := o.BuildSetter() + ensureCreatableArcgisAccount(opt) + + if o.r.Organization == nil { + ArcgisAccountMods.WithNewOrganization().Apply(ctx, o) + } + + var rel0 *models.Organization + + if o.r.Organization.o.alreadyPersisted { + rel0 = o.r.Organization.o.Build() + } else { + rel0, err = o.r.Organization.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.OrganizationID = omit.From(rel0.ID) + + m, err := models.ArcgisAccounts.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + m.R.Organization = rel0 + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a arcgisAccount and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ArcgisAccountTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.ArcgisAccount { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a arcgisAccount and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ArcgisAccountTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.ArcgisAccount { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple arcgisAccounts and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ArcgisAccountTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ArcgisAccountSlice, error) { + var err error + m := make(models.ArcgisAccountSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple arcgisAccounts and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ArcgisAccountTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ArcgisAccountSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple arcgisAccounts and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ArcgisAccountTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ArcgisAccountSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// ArcgisAccount has methods that act as mods for the ArcgisAccountTemplate +var ArcgisAccountMods arcgisAccountMods + +type arcgisAccountMods struct{} + +func (m arcgisAccountMods) RandomizeAllColumns(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModSlice{ + ArcgisAccountMods.RandomID(f), + ArcgisAccountMods.RandomName(f), + ArcgisAccountMods.RandomOrganizationID(f), + ArcgisAccountMods.RandomURLFeatures(f), + ArcgisAccountMods.RandomURLInsights(f), + ArcgisAccountMods.RandomURLGeometry(f), + ArcgisAccountMods.RandomURLNotebooks(f), + ArcgisAccountMods.RandomURLTiles(f), + } +} + +// Set the model columns to this value +func (m arcgisAccountMods) ID(val string) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.ID = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) IDFunc(f func() string) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetID() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisAccountMods) RandomID(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.ID = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) Name(val string) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.Name = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) NameFunc(f func() string) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.Name = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetName() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.Name = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisAccountMods) RandomName(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.Name = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) OrganizationID(val int32) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.OrganizationID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) OrganizationIDFunc(f func() int32) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.OrganizationID = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetOrganizationID() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.OrganizationID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisAccountMods) RandomOrganizationID(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.OrganizationID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) URLFeatures(val null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLFeatures = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) URLFeaturesFunc(f func() null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLFeatures = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetURLFeatures() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLFeatures = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisAccountMods) RandomURLFeatures(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLFeatures = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisAccountMods) RandomURLFeaturesNotNull(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLFeatures = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) URLInsights(val null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLInsights = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) URLInsightsFunc(f func() null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLInsights = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetURLInsights() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLInsights = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisAccountMods) RandomURLInsights(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLInsights = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisAccountMods) RandomURLInsightsNotNull(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLInsights = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) URLGeometry(val null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLGeometry = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) URLGeometryFunc(f func() null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLGeometry = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetURLGeometry() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLGeometry = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisAccountMods) RandomURLGeometry(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLGeometry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisAccountMods) RandomURLGeometryNotNull(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLGeometry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) URLNotebooks(val null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLNotebooks = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) URLNotebooksFunc(f func() null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLNotebooks = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetURLNotebooks() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLNotebooks = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisAccountMods) RandomURLNotebooks(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLNotebooks = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisAccountMods) RandomURLNotebooksNotNull(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLNotebooks = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisAccountMods) URLTiles(val null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLTiles = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisAccountMods) URLTilesFunc(f func() null.Val[string]) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLTiles = f + }) +} + +// Clear any values for the column +func (m arcgisAccountMods) UnsetURLTiles() ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLTiles = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisAccountMods) RandomURLTiles(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLTiles = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisAccountMods) RandomURLTilesNotNull(f *faker.Faker) ArcgisAccountMod { + return ArcgisAccountModFunc(func(_ context.Context, o *ArcgisAccountTemplate) { + o.URLTiles = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +func (m arcgisAccountMods) WithParentsCascading() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + if isDone, _ := arcgisAccountWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = arcgisAccountWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewOrganizationWithContext(ctx, OrganizationMods.WithParentsCascading()) + m.WithOrganization(related).Apply(ctx, o) + } + }) +} + +func (m arcgisAccountMods) WithOrganization(rel *OrganizationTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.Organization = &arcgisAccountROrganizationR{ + o: rel, + } + }) +} + +func (m arcgisAccountMods) WithNewOrganization(mods ...OrganizationMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewOrganizationWithContext(ctx, mods...) + + m.WithOrganization(related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) WithExistingOrganization(em *models.Organization) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.Organization = &arcgisAccountROrganizationR{ + o: o.f.FromExistingOrganization(em), + } + }) +} + +func (m arcgisAccountMods) WithoutOrganization() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.Organization = nil + }) +} + +func (m arcgisAccountMods) WithArcgisAccountOauthTokens(number int, related *ArcgisOauthTokenTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOauthTokens = []*arcgisAccountRArcgisAccountOauthTokensR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisAccountMods) WithNewArcgisAccountOauthTokens(number int, mods ...ArcgisOauthTokenMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisOauthTokenWithContext(ctx, mods...) + m.WithArcgisAccountOauthTokens(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddArcgisAccountOauthTokens(number int, related *ArcgisOauthTokenTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOauthTokens = append(o.r.ArcgisAccountOauthTokens, &arcgisAccountRArcgisAccountOauthTokensR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisAccountMods) AddNewArcgisAccountOauthTokens(number int, mods ...ArcgisOauthTokenMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisOauthTokenWithContext(ctx, mods...) + m.AddArcgisAccountOauthTokens(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddExistingArcgisAccountOauthTokens(existingModels ...*models.ArcgisOauthToken) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + for _, em := range existingModels { + o.r.ArcgisAccountOauthTokens = append(o.r.ArcgisAccountOauthTokens, &arcgisAccountRArcgisAccountOauthTokensR{ + o: o.f.FromExistingArcgisOauthToken(em), + }) + } + }) +} + +func (m arcgisAccountMods) WithoutArcgisAccountOauthTokens() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOauthTokens = nil + }) +} + +func (m arcgisAccountMods) WithServiceFeatures(number int, related *ArcgisServiceFeatureTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceFeatures = []*arcgisAccountRServiceFeaturesR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisAccountMods) WithNewServiceFeatures(number int, mods ...ArcgisServiceFeatureMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisServiceFeatureWithContext(ctx, mods...) + m.WithServiceFeatures(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddServiceFeatures(number int, related *ArcgisServiceFeatureTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceFeatures = append(o.r.ServiceFeatures, &arcgisAccountRServiceFeaturesR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisAccountMods) AddNewServiceFeatures(number int, mods ...ArcgisServiceFeatureMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisServiceFeatureWithContext(ctx, mods...) + m.AddServiceFeatures(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddExistingServiceFeatures(existingModels ...*models.ArcgisServiceFeature) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + for _, em := range existingModels { + o.r.ServiceFeatures = append(o.r.ServiceFeatures, &arcgisAccountRServiceFeaturesR{ + o: o.f.FromExistingArcgisServiceFeature(em), + }) + } + }) +} + +func (m arcgisAccountMods) WithoutServiceFeatures() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceFeatures = nil + }) +} + +func (m arcgisAccountMods) WithServiceMaps(number int, related *ArcgisServiceMapTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceMaps = []*arcgisAccountRServiceMapsR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisAccountMods) WithNewServiceMaps(number int, mods ...ArcgisServiceMapMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisServiceMapWithContext(ctx, mods...) + m.WithServiceMaps(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddServiceMaps(number int, related *ArcgisServiceMapTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceMaps = append(o.r.ServiceMaps, &arcgisAccountRServiceMapsR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisAccountMods) AddNewServiceMaps(number int, mods ...ArcgisServiceMapMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewArcgisServiceMapWithContext(ctx, mods...) + m.AddServiceMaps(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddExistingServiceMaps(existingModels ...*models.ArcgisServiceMap) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + for _, em := range existingModels { + o.r.ServiceMaps = append(o.r.ServiceMaps, &arcgisAccountRServiceMapsR{ + o: o.f.FromExistingArcgisServiceMap(em), + }) + } + }) +} + +func (m arcgisAccountMods) WithoutServiceMaps() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ServiceMaps = nil + }) +} + +func (m arcgisAccountMods) WithArcgisAccountOrganizations(number int, related *OrganizationTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOrganizations = []*arcgisAccountRArcgisAccountOrganizationsR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisAccountMods) WithNewArcgisAccountOrganizations(number int, mods ...OrganizationMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewOrganizationWithContext(ctx, mods...) + m.WithArcgisAccountOrganizations(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddArcgisAccountOrganizations(number int, related *OrganizationTemplate) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOrganizations = append(o.r.ArcgisAccountOrganizations, &arcgisAccountRArcgisAccountOrganizationsR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisAccountMods) AddNewArcgisAccountOrganizations(number int, mods ...OrganizationMod) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + related := o.f.NewOrganizationWithContext(ctx, mods...) + m.AddArcgisAccountOrganizations(number, related).Apply(ctx, o) + }) +} + +func (m arcgisAccountMods) AddExistingArcgisAccountOrganizations(existingModels ...*models.Organization) ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + for _, em := range existingModels { + o.r.ArcgisAccountOrganizations = append(o.r.ArcgisAccountOrganizations, &arcgisAccountRArcgisAccountOrganizationsR{ + o: o.f.FromExistingOrganization(em), + }) + } + }) +} + +func (m arcgisAccountMods) WithoutArcgisAccountOrganizations() ArcgisAccountMod { + return ArcgisAccountModFunc(func(ctx context.Context, o *ArcgisAccountTemplate) { + o.r.ArcgisAccountOrganizations = nil + }) +} diff --git a/db/factory/arcgis.layer.bob.go b/db/factory/arcgis.layer.bob.go index 33eb4d0f..8bd5332b 100644 --- a/db/factory/arcgis.layer.bob.go +++ b/db/factory/arcgis.layer.bob.go @@ -45,12 +45,12 @@ type ArcgisLayerTemplate struct { } type arcgisLayerR struct { - FeatureServiceItemFeatureService *arcgisLayerRFeatureServiceItemFeatureServiceR + FeatureServiceItemServiceFeature *arcgisLayerRFeatureServiceItemServiceFeatureR LayerFields []*arcgisLayerRLayerFieldsR } -type arcgisLayerRFeatureServiceItemFeatureServiceR struct { - o *ArcgisFeatureServiceTemplate +type arcgisLayerRFeatureServiceItemServiceFeatureR struct { + o *ArcgisServiceFeatureTemplate } type arcgisLayerRLayerFieldsR struct { number int @@ -67,11 +67,11 @@ func (o *ArcgisLayerTemplate) Apply(ctx context.Context, mods ...ArcgisLayerMod) // setModelRels creates and sets the relationships on *models.ArcgisLayer // according to the relationships in the template. Nothing is inserted into the db func (t ArcgisLayerTemplate) setModelRels(o *models.ArcgisLayer) { - if t.r.FeatureServiceItemFeatureService != nil { - rel := t.r.FeatureServiceItemFeatureService.o.Build() + if t.r.FeatureServiceItemServiceFeature != nil { + rel := t.r.FeatureServiceItemServiceFeature.o.Build() rel.R.FeatureServiceItemLayers = append(rel.R.FeatureServiceItemLayers, o) o.FeatureServiceItemID = rel.ItemID // h2 - o.R.FeatureServiceItemFeatureService = rel + o.R.FeatureServiceItemServiceFeature = rel } if t.r.LayerFields != nil { @@ -207,16 +207,16 @@ func (o *ArcgisLayerTemplate) Create(ctx context.Context, exec bob.Executor) (*m opt := o.BuildSetter() ensureCreatableArcgisLayer(opt) - if o.r.FeatureServiceItemFeatureService == nil { - ArcgisLayerMods.WithNewFeatureServiceItemFeatureService().Apply(ctx, o) + if o.r.FeatureServiceItemServiceFeature == nil { + ArcgisLayerMods.WithNewFeatureServiceItemServiceFeature().Apply(ctx, o) } - var rel0 *models.ArcgisFeatureService + var rel0 *models.ArcgisServiceFeature - if o.r.FeatureServiceItemFeatureService.o.alreadyPersisted { - rel0 = o.r.FeatureServiceItemFeatureService.o.Build() + if o.r.FeatureServiceItemServiceFeature.o.alreadyPersisted { + rel0 = o.r.FeatureServiceItemServiceFeature.o.Build() } else { - rel0, err = o.r.FeatureServiceItemFeatureService.o.Create(ctx, exec) + rel0, err = o.r.FeatureServiceItemServiceFeature.o.Create(ctx, exec) if err != nil { return nil, err } @@ -229,7 +229,7 @@ func (o *ArcgisLayerTemplate) Create(ctx context.Context, exec bob.Executor) (*m return nil, err } - m.R.FeatureServiceItemFeatureService = rel0 + m.R.FeatureServiceItemServiceFeature = rel0 if err := o.insertOptRels(ctx, exec, m); err != nil { return nil, err @@ -415,39 +415,39 @@ func (m arcgisLayerMods) WithParentsCascading() ArcgisLayerMod { ctx = arcgisLayerWithParentsCascadingCtx.WithValue(ctx, true) { - related := o.f.NewArcgisFeatureServiceWithContext(ctx, ArcgisFeatureServiceMods.WithParentsCascading()) - m.WithFeatureServiceItemFeatureService(related).Apply(ctx, o) + related := o.f.NewArcgisServiceFeatureWithContext(ctx, ArcgisServiceFeatureMods.WithParentsCascading()) + m.WithFeatureServiceItemServiceFeature(related).Apply(ctx, o) } }) } -func (m arcgisLayerMods) WithFeatureServiceItemFeatureService(rel *ArcgisFeatureServiceTemplate) ArcgisLayerMod { +func (m arcgisLayerMods) WithFeatureServiceItemServiceFeature(rel *ArcgisServiceFeatureTemplate) ArcgisLayerMod { return ArcgisLayerModFunc(func(ctx context.Context, o *ArcgisLayerTemplate) { - o.r.FeatureServiceItemFeatureService = &arcgisLayerRFeatureServiceItemFeatureServiceR{ + o.r.FeatureServiceItemServiceFeature = &arcgisLayerRFeatureServiceItemServiceFeatureR{ o: rel, } }) } -func (m arcgisLayerMods) WithNewFeatureServiceItemFeatureService(mods ...ArcgisFeatureServiceMod) ArcgisLayerMod { +func (m arcgisLayerMods) WithNewFeatureServiceItemServiceFeature(mods ...ArcgisServiceFeatureMod) ArcgisLayerMod { return ArcgisLayerModFunc(func(ctx context.Context, o *ArcgisLayerTemplate) { - related := o.f.NewArcgisFeatureServiceWithContext(ctx, mods...) + related := o.f.NewArcgisServiceFeatureWithContext(ctx, mods...) - m.WithFeatureServiceItemFeatureService(related).Apply(ctx, o) + m.WithFeatureServiceItemServiceFeature(related).Apply(ctx, o) }) } -func (m arcgisLayerMods) WithExistingFeatureServiceItemFeatureService(em *models.ArcgisFeatureService) ArcgisLayerMod { +func (m arcgisLayerMods) WithExistingFeatureServiceItemServiceFeature(em *models.ArcgisServiceFeature) ArcgisLayerMod { return ArcgisLayerModFunc(func(ctx context.Context, o *ArcgisLayerTemplate) { - o.r.FeatureServiceItemFeatureService = &arcgisLayerRFeatureServiceItemFeatureServiceR{ - o: o.f.FromExistingArcgisFeatureService(em), + o.r.FeatureServiceItemServiceFeature = &arcgisLayerRFeatureServiceItemServiceFeatureR{ + o: o.f.FromExistingArcgisServiceFeature(em), } }) } -func (m arcgisLayerMods) WithoutFeatureServiceItemFeatureService() ArcgisLayerMod { +func (m arcgisLayerMods) WithoutFeatureServiceItemServiceFeature() ArcgisLayerMod { return ArcgisLayerModFunc(func(ctx context.Context, o *ArcgisLayerTemplate) { - o.r.FeatureServiceItemFeatureService = nil + o.r.FeatureServiceItemServiceFeature = nil }) } diff --git a/db/factory/arcgis.oauth_token.bob.go b/db/factory/arcgis.oauth_token.bob.go new file mode 100644 index 00000000..afdb670f --- /dev/null +++ b/db/factory/arcgis.oauth_token.bob.go @@ -0,0 +1,945 @@ +// 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 factory + +import ( + "context" + "testing" + "time" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/jaswdr/faker/v2" +) + +type ArcgisOauthTokenMod interface { + Apply(context.Context, *ArcgisOauthTokenTemplate) +} + +type ArcgisOauthTokenModFunc func(context.Context, *ArcgisOauthTokenTemplate) + +func (f ArcgisOauthTokenModFunc) Apply(ctx context.Context, n *ArcgisOauthTokenTemplate) { + f(ctx, n) +} + +type ArcgisOauthTokenModSlice []ArcgisOauthTokenMod + +func (mods ArcgisOauthTokenModSlice) Apply(ctx context.Context, n *ArcgisOauthTokenTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ArcgisOauthTokenTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ArcgisOauthTokenTemplate struct { + AccessToken func() string + AccessTokenExpires func() time.Time + ArcgisAccountID func() null.Val[string] + ArcgisID func() null.Val[string] + ArcgisLicenseTypeID func() null.Val[string] + Created func() time.Time + ID func() int32 + InvalidatedAt func() null.Val[time.Time] + RefreshToken func() string + RefreshTokenExpires func() time.Time + UserID func() int32 + Username func() string + + r arcgisOauthTokenR + f *Factory + + alreadyPersisted bool +} + +type arcgisOauthTokenR struct { + ArcgisAccountAccount *arcgisOauthTokenRArcgisAccountAccountR + UserUser *arcgisOauthTokenRUserUserR +} + +type arcgisOauthTokenRArcgisAccountAccountR struct { + o *ArcgisAccountTemplate +} +type arcgisOauthTokenRUserUserR struct { + o *UserTemplate +} + +// Apply mods to the ArcgisOauthTokenTemplate +func (o *ArcgisOauthTokenTemplate) Apply(ctx context.Context, mods ...ArcgisOauthTokenMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.ArcgisOauthToken +// according to the relationships in the template. Nothing is inserted into the db +func (t ArcgisOauthTokenTemplate) setModelRels(o *models.ArcgisOauthToken) { + if t.r.ArcgisAccountAccount != nil { + rel := t.r.ArcgisAccountAccount.o.Build() + rel.R.ArcgisAccountOauthTokens = append(rel.R.ArcgisAccountOauthTokens, o) + o.ArcgisAccountID = null.From(rel.ID) // h2 + o.R.ArcgisAccountAccount = rel + } + + if t.r.UserUser != nil { + rel := t.r.UserUser.o.Build() + rel.R.UserOauthTokens = append(rel.R.UserOauthTokens, o) + o.UserID = rel.ID // h2 + o.R.UserUser = rel + } +} + +// BuildSetter returns an *models.ArcgisOauthTokenSetter +// this does nothing with the relationship templates +func (o ArcgisOauthTokenTemplate) BuildSetter() *models.ArcgisOauthTokenSetter { + m := &models.ArcgisOauthTokenSetter{} + + if o.AccessToken != nil { + val := o.AccessToken() + m.AccessToken = omit.From(val) + } + if o.AccessTokenExpires != nil { + val := o.AccessTokenExpires() + m.AccessTokenExpires = omit.From(val) + } + if o.ArcgisAccountID != nil { + val := o.ArcgisAccountID() + m.ArcgisAccountID = omitnull.FromNull(val) + } + if o.ArcgisID != nil { + val := o.ArcgisID() + m.ArcgisID = omitnull.FromNull(val) + } + if o.ArcgisLicenseTypeID != nil { + val := o.ArcgisLicenseTypeID() + m.ArcgisLicenseTypeID = omitnull.FromNull(val) + } + if o.Created != nil { + val := o.Created() + m.Created = omit.From(val) + } + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.InvalidatedAt != nil { + val := o.InvalidatedAt() + m.InvalidatedAt = omitnull.FromNull(val) + } + if o.RefreshToken != nil { + val := o.RefreshToken() + m.RefreshToken = omit.From(val) + } + if o.RefreshTokenExpires != nil { + val := o.RefreshTokenExpires() + m.RefreshTokenExpires = omit.From(val) + } + if o.UserID != nil { + val := o.UserID() + m.UserID = omit.From(val) + } + if o.Username != nil { + val := o.Username() + m.Username = omit.From(val) + } + + return m +} + +// BuildManySetter returns an []*models.ArcgisOauthTokenSetter +// this does nothing with the relationship templates +func (o ArcgisOauthTokenTemplate) BuildManySetter(number int) []*models.ArcgisOauthTokenSetter { + m := make([]*models.ArcgisOauthTokenSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.ArcgisOauthToken +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisOauthTokenTemplate.Create +func (o ArcgisOauthTokenTemplate) Build() *models.ArcgisOauthToken { + m := &models.ArcgisOauthToken{} + + if o.AccessToken != nil { + m.AccessToken = o.AccessToken() + } + if o.AccessTokenExpires != nil { + m.AccessTokenExpires = o.AccessTokenExpires() + } + if o.ArcgisAccountID != nil { + m.ArcgisAccountID = o.ArcgisAccountID() + } + if o.ArcgisID != nil { + m.ArcgisID = o.ArcgisID() + } + if o.ArcgisLicenseTypeID != nil { + m.ArcgisLicenseTypeID = o.ArcgisLicenseTypeID() + } + if o.Created != nil { + m.Created = o.Created() + } + if o.ID != nil { + m.ID = o.ID() + } + if o.InvalidatedAt != nil { + m.InvalidatedAt = o.InvalidatedAt() + } + if o.RefreshToken != nil { + m.RefreshToken = o.RefreshToken() + } + if o.RefreshTokenExpires != nil { + m.RefreshTokenExpires = o.RefreshTokenExpires() + } + if o.UserID != nil { + m.UserID = o.UserID() + } + if o.Username != nil { + m.Username = o.Username() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ArcgisOauthTokenSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisOauthTokenTemplate.CreateMany +func (o ArcgisOauthTokenTemplate) BuildMany(number int) models.ArcgisOauthTokenSlice { + m := make(models.ArcgisOauthTokenSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableArcgisOauthToken(m *models.ArcgisOauthTokenSetter) { + if !(m.AccessToken.IsValue()) { + val := random_string(nil) + m.AccessToken = omit.From(val) + } + if !(m.AccessTokenExpires.IsValue()) { + val := random_time_Time(nil) + m.AccessTokenExpires = omit.From(val) + } + if !(m.Created.IsValue()) { + val := random_time_Time(nil) + m.Created = omit.From(val) + } + if !(m.RefreshToken.IsValue()) { + val := random_string(nil) + m.RefreshToken = omit.From(val) + } + if !(m.RefreshTokenExpires.IsValue()) { + val := random_time_Time(nil) + m.RefreshTokenExpires = omit.From(val) + } + if !(m.UserID.IsValue()) { + val := random_int32(nil) + m.UserID = omit.From(val) + } + if !(m.Username.IsValue()) { + val := random_string(nil) + m.Username = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.ArcgisOauthToken +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ArcgisOauthTokenTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.ArcgisOauthToken) error { + var err error + + isArcgisAccountAccountDone, _ := arcgisOauthTokenRelArcgisAccountAccountCtx.Value(ctx) + if !isArcgisAccountAccountDone && o.r.ArcgisAccountAccount != nil { + ctx = arcgisOauthTokenRelArcgisAccountAccountCtx.WithValue(ctx, true) + if o.r.ArcgisAccountAccount.o.alreadyPersisted { + m.R.ArcgisAccountAccount = o.r.ArcgisAccountAccount.o.Build() + } else { + var rel0 *models.ArcgisAccount + rel0, err = o.r.ArcgisAccountAccount.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachArcgisAccountAccount(ctx, exec, rel0) + if err != nil { + return err + } + } + + } + + return err +} + +// Create builds a arcgisOauthToken and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ArcgisOauthTokenTemplate) Create(ctx context.Context, exec bob.Executor) (*models.ArcgisOauthToken, error) { + var err error + opt := o.BuildSetter() + ensureCreatableArcgisOauthToken(opt) + + if o.r.UserUser == nil { + ArcgisOauthTokenMods.WithNewUserUser().Apply(ctx, o) + } + + var rel1 *models.User + + if o.r.UserUser.o.alreadyPersisted { + rel1 = o.r.UserUser.o.Build() + } else { + rel1, err = o.r.UserUser.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.UserID = omit.From(rel1.ID) + + m, err := models.ArcgisOauthTokens.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + m.R.UserUser = rel1 + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a arcgisOauthToken and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ArcgisOauthTokenTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.ArcgisOauthToken { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a arcgisOauthToken and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ArcgisOauthTokenTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.ArcgisOauthToken { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple arcgisOauthTokens and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ArcgisOauthTokenTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ArcgisOauthTokenSlice, error) { + var err error + m := make(models.ArcgisOauthTokenSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple arcgisOauthTokens and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ArcgisOauthTokenTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ArcgisOauthTokenSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple arcgisOauthTokens and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ArcgisOauthTokenTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ArcgisOauthTokenSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// ArcgisOauthToken has methods that act as mods for the ArcgisOauthTokenTemplate +var ArcgisOauthTokenMods arcgisOauthTokenMods + +type arcgisOauthTokenMods struct{} + +func (m arcgisOauthTokenMods) RandomizeAllColumns(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModSlice{ + ArcgisOauthTokenMods.RandomAccessToken(f), + ArcgisOauthTokenMods.RandomAccessTokenExpires(f), + ArcgisOauthTokenMods.RandomArcgisAccountID(f), + ArcgisOauthTokenMods.RandomArcgisID(f), + ArcgisOauthTokenMods.RandomArcgisLicenseTypeID(f), + ArcgisOauthTokenMods.RandomCreated(f), + ArcgisOauthTokenMods.RandomID(f), + ArcgisOauthTokenMods.RandomInvalidatedAt(f), + ArcgisOauthTokenMods.RandomRefreshToken(f), + ArcgisOauthTokenMods.RandomRefreshTokenExpires(f), + ArcgisOauthTokenMods.RandomUserID(f), + ArcgisOauthTokenMods.RandomUsername(f), + } +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) AccessToken(val string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessToken = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) AccessTokenFunc(f func() string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessToken = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetAccessToken() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessToken = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomAccessToken(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessToken = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) AccessTokenExpires(val time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessTokenExpires = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) AccessTokenExpiresFunc(f func() time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessTokenExpires = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetAccessTokenExpires() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessTokenExpires = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomAccessTokenExpires(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.AccessTokenExpires = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) ArcgisAccountID(val null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisAccountID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) ArcgisAccountIDFunc(f func() null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisAccountID = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetArcgisAccountID() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisAccountID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisOauthTokenMods) RandomArcgisAccountID(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisAccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisOauthTokenMods) RandomArcgisAccountIDNotNull(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisAccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) ArcgisID(val null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) ArcgisIDFunc(f func() null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisID = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetArcgisID() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisOauthTokenMods) RandomArcgisID(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisOauthTokenMods) RandomArcgisIDNotNull(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) ArcgisLicenseTypeID(val null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisLicenseTypeID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) ArcgisLicenseTypeIDFunc(f func() null.Val[string]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisLicenseTypeID = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetArcgisLicenseTypeID() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisLicenseTypeID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisOauthTokenMods) RandomArcgisLicenseTypeID(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisLicenseTypeID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisOauthTokenMods) RandomArcgisLicenseTypeIDNotNull(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ArcgisLicenseTypeID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) Created(val time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Created = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) CreatedFunc(f func() time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Created = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetCreated() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Created = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomCreated(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Created = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) ID(val int32) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) IDFunc(f func() int32) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetID() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomID(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.ID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) InvalidatedAt(val null.Val[time.Time]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) InvalidatedAtFunc(f func() null.Val[time.Time]) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.InvalidatedAt = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetInvalidatedAt() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.InvalidatedAt = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisOauthTokenMods) RandomInvalidatedAt(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisOauthTokenMods) RandomInvalidatedAtNotNull(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.InvalidatedAt = func() null.Val[time.Time] { + if f == nil { + f = &defaultFaker + } + + val := random_time_Time(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) RefreshToken(val string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshToken = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) RefreshTokenFunc(f func() string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshToken = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetRefreshToken() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshToken = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomRefreshToken(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshToken = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) RefreshTokenExpires(val time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshTokenExpires = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) RefreshTokenExpiresFunc(f func() time.Time) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshTokenExpires = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetRefreshTokenExpires() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshTokenExpires = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomRefreshTokenExpires(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.RefreshTokenExpires = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) UserID(val int32) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.UserID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) UserIDFunc(f func() int32) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.UserID = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetUserID() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.UserID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomUserID(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.UserID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisOauthTokenMods) Username(val string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Username = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisOauthTokenMods) UsernameFunc(f func() string) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Username = f + }) +} + +// Clear any values for the column +func (m arcgisOauthTokenMods) UnsetUsername() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Username = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisOauthTokenMods) RandomUsername(f *faker.Faker) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(_ context.Context, o *ArcgisOauthTokenTemplate) { + o.Username = func() string { + return random_string(f) + } + }) +} + +func (m arcgisOauthTokenMods) WithParentsCascading() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + if isDone, _ := arcgisOauthTokenWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = arcgisOauthTokenWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewArcgisAccountWithContext(ctx, ArcgisAccountMods.WithParentsCascading()) + m.WithArcgisAccountAccount(related).Apply(ctx, o) + } + { + + related := o.f.NewUserWithContext(ctx, UserMods.WithParentsCascading()) + m.WithUserUser(related).Apply(ctx, o) + } + }) +} + +func (m arcgisOauthTokenMods) WithArcgisAccountAccount(rel *ArcgisAccountTemplate) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.ArcgisAccountAccount = &arcgisOauthTokenRArcgisAccountAccountR{ + o: rel, + } + }) +} + +func (m arcgisOauthTokenMods) WithNewArcgisAccountAccount(mods ...ArcgisAccountMod) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + + m.WithArcgisAccountAccount(related).Apply(ctx, o) + }) +} + +func (m arcgisOauthTokenMods) WithExistingArcgisAccountAccount(em *models.ArcgisAccount) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.ArcgisAccountAccount = &arcgisOauthTokenRArcgisAccountAccountR{ + o: o.f.FromExistingArcgisAccount(em), + } + }) +} + +func (m arcgisOauthTokenMods) WithoutArcgisAccountAccount() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.ArcgisAccountAccount = nil + }) +} + +func (m arcgisOauthTokenMods) WithUserUser(rel *UserTemplate) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.UserUser = &arcgisOauthTokenRUserUserR{ + o: rel, + } + }) +} + +func (m arcgisOauthTokenMods) WithNewUserUser(mods ...UserMod) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + related := o.f.NewUserWithContext(ctx, mods...) + + m.WithUserUser(related).Apply(ctx, o) + }) +} + +func (m arcgisOauthTokenMods) WithExistingUserUser(em *models.User) ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.UserUser = &arcgisOauthTokenRUserUserR{ + o: o.f.FromExistingUser(em), + } + }) +} + +func (m arcgisOauthTokenMods) WithoutUserUser() ArcgisOauthTokenMod { + return ArcgisOauthTokenModFunc(func(ctx context.Context, o *ArcgisOauthTokenTemplate) { + o.r.UserUser = nil + }) +} diff --git a/db/factory/arcgis.service_feature.bob.go b/db/factory/arcgis.service_feature.bob.go new file mode 100644 index 00000000..6541dec9 --- /dev/null +++ b/db/factory/arcgis.service_feature.bob.go @@ -0,0 +1,693 @@ +// 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 factory + +import ( + "context" + "testing" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/jaswdr/faker/v2" +) + +type ArcgisServiceFeatureMod interface { + Apply(context.Context, *ArcgisServiceFeatureTemplate) +} + +type ArcgisServiceFeatureModFunc func(context.Context, *ArcgisServiceFeatureTemplate) + +func (f ArcgisServiceFeatureModFunc) Apply(ctx context.Context, n *ArcgisServiceFeatureTemplate) { + f(ctx, n) +} + +type ArcgisServiceFeatureModSlice []ArcgisServiceFeatureMod + +func (mods ArcgisServiceFeatureModSlice) Apply(ctx context.Context, n *ArcgisServiceFeatureTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ArcgisServiceFeatureTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ArcgisServiceFeatureTemplate struct { + Extent func() string + ItemID func() string + SpatialReference func() int32 + URL func() string + AccountID func() null.Val[string] + + r arcgisServiceFeatureR + f *Factory + + alreadyPersisted bool +} + +type arcgisServiceFeatureR struct { + FeatureServiceItemLayers []*arcgisServiceFeatureRFeatureServiceItemLayersR + Account *arcgisServiceFeatureRAccountR + FieldseekerServiceFeatureItemOrganizations []*arcgisServiceFeatureRFieldseekerServiceFeatureItemOrganizationsR +} + +type arcgisServiceFeatureRFeatureServiceItemLayersR struct { + number int + o *ArcgisLayerTemplate +} +type arcgisServiceFeatureRAccountR struct { + o *ArcgisAccountTemplate +} +type arcgisServiceFeatureRFieldseekerServiceFeatureItemOrganizationsR struct { + number int + o *OrganizationTemplate +} + +// Apply mods to the ArcgisServiceFeatureTemplate +func (o *ArcgisServiceFeatureTemplate) Apply(ctx context.Context, mods ...ArcgisServiceFeatureMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.ArcgisServiceFeature +// according to the relationships in the template. Nothing is inserted into the db +func (t ArcgisServiceFeatureTemplate) setModelRels(o *models.ArcgisServiceFeature) { + if t.r.FeatureServiceItemLayers != nil { + rel := models.ArcgisLayerSlice{} + for _, r := range t.r.FeatureServiceItemLayers { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.FeatureServiceItemID = o.ItemID // h2 + rel.R.FeatureServiceItemServiceFeature = o + } + rel = append(rel, related...) + } + o.R.FeatureServiceItemLayers = rel + } + + if t.r.Account != nil { + rel := t.r.Account.o.Build() + rel.R.ServiceFeatures = append(rel.R.ServiceFeatures, o) + o.AccountID = null.From(rel.ID) // h2 + o.R.Account = rel + } + + if t.r.FieldseekerServiceFeatureItemOrganizations != nil { + rel := models.OrganizationSlice{} + for _, r := range t.r.FieldseekerServiceFeatureItemOrganizations { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.FieldseekerServiceFeatureItemID = null.From(o.ItemID) // h2 + rel.R.FieldseekerServiceFeatureItemServiceFeature = o + } + rel = append(rel, related...) + } + o.R.FieldseekerServiceFeatureItemOrganizations = rel + } +} + +// BuildSetter returns an *models.ArcgisServiceFeatureSetter +// this does nothing with the relationship templates +func (o ArcgisServiceFeatureTemplate) BuildSetter() *models.ArcgisServiceFeatureSetter { + m := &models.ArcgisServiceFeatureSetter{} + + if o.Extent != nil { + val := o.Extent() + m.Extent = omit.From(val) + } + if o.ItemID != nil { + val := o.ItemID() + m.ItemID = omit.From(val) + } + if o.SpatialReference != nil { + val := o.SpatialReference() + m.SpatialReference = omit.From(val) + } + if o.URL != nil { + val := o.URL() + m.URL = omit.From(val) + } + if o.AccountID != nil { + val := o.AccountID() + m.AccountID = omitnull.FromNull(val) + } + + return m +} + +// BuildManySetter returns an []*models.ArcgisServiceFeatureSetter +// this does nothing with the relationship templates +func (o ArcgisServiceFeatureTemplate) BuildManySetter(number int) []*models.ArcgisServiceFeatureSetter { + m := make([]*models.ArcgisServiceFeatureSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.ArcgisServiceFeature +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisServiceFeatureTemplate.Create +func (o ArcgisServiceFeatureTemplate) Build() *models.ArcgisServiceFeature { + m := &models.ArcgisServiceFeature{} + + if o.Extent != nil { + m.Extent = o.Extent() + } + if o.ItemID != nil { + m.ItemID = o.ItemID() + } + if o.SpatialReference != nil { + m.SpatialReference = o.SpatialReference() + } + if o.URL != nil { + m.URL = o.URL() + } + if o.AccountID != nil { + m.AccountID = o.AccountID() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ArcgisServiceFeatureSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisServiceFeatureTemplate.CreateMany +func (o ArcgisServiceFeatureTemplate) BuildMany(number int) models.ArcgisServiceFeatureSlice { + m := make(models.ArcgisServiceFeatureSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableArcgisServiceFeature(m *models.ArcgisServiceFeatureSetter) { + if !(m.Extent.IsValue()) { + val := random_string(nil) + m.Extent = omit.From(val) + } + if !(m.ItemID.IsValue()) { + val := random_string(nil) + m.ItemID = omit.From(val) + } + if !(m.SpatialReference.IsValue()) { + val := random_int32(nil) + m.SpatialReference = omit.From(val) + } + if !(m.URL.IsValue()) { + val := random_string(nil) + m.URL = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.ArcgisServiceFeature +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ArcgisServiceFeatureTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.ArcgisServiceFeature) error { + var err error + + isFeatureServiceItemLayersDone, _ := arcgisServiceFeatureRelFeatureServiceItemLayersCtx.Value(ctx) + if !isFeatureServiceItemLayersDone && o.r.FeatureServiceItemLayers != nil { + ctx = arcgisServiceFeatureRelFeatureServiceItemLayersCtx.WithValue(ctx, true) + for _, r := range o.r.FeatureServiceItemLayers { + if r.o.alreadyPersisted { + m.R.FeatureServiceItemLayers = append(m.R.FeatureServiceItemLayers, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachFeatureServiceItemLayers(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + + isAccountDone, _ := arcgisServiceFeatureRelAccountCtx.Value(ctx) + if !isAccountDone && o.r.Account != nil { + ctx = arcgisServiceFeatureRelAccountCtx.WithValue(ctx, true) + if o.r.Account.o.alreadyPersisted { + m.R.Account = o.r.Account.o.Build() + } else { + var rel1 *models.ArcgisAccount + rel1, err = o.r.Account.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachAccount(ctx, exec, rel1) + if err != nil { + return err + } + } + + } + + isFieldseekerServiceFeatureItemOrganizationsDone, _ := arcgisServiceFeatureRelFieldseekerServiceFeatureItemOrganizationsCtx.Value(ctx) + if !isFieldseekerServiceFeatureItemOrganizationsDone && o.r.FieldseekerServiceFeatureItemOrganizations != nil { + ctx = arcgisServiceFeatureRelFieldseekerServiceFeatureItemOrganizationsCtx.WithValue(ctx, true) + for _, r := range o.r.FieldseekerServiceFeatureItemOrganizations { + if r.o.alreadyPersisted { + m.R.FieldseekerServiceFeatureItemOrganizations = append(m.R.FieldseekerServiceFeatureItemOrganizations, r.o.Build()) + } else { + rel2, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachFieldseekerServiceFeatureItemOrganizations(ctx, exec, rel2...) + if err != nil { + return err + } + } + } + } + + return err +} + +// Create builds a arcgisServiceFeature and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ArcgisServiceFeatureTemplate) Create(ctx context.Context, exec bob.Executor) (*models.ArcgisServiceFeature, error) { + var err error + opt := o.BuildSetter() + ensureCreatableArcgisServiceFeature(opt) + + m, err := models.ArcgisServiceFeatures.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a arcgisServiceFeature and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ArcgisServiceFeatureTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.ArcgisServiceFeature { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a arcgisServiceFeature and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ArcgisServiceFeatureTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.ArcgisServiceFeature { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple arcgisServiceFeatures and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ArcgisServiceFeatureTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ArcgisServiceFeatureSlice, error) { + var err error + m := make(models.ArcgisServiceFeatureSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple arcgisServiceFeatures and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ArcgisServiceFeatureTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ArcgisServiceFeatureSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple arcgisServiceFeatures and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ArcgisServiceFeatureTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ArcgisServiceFeatureSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// ArcgisServiceFeature has methods that act as mods for the ArcgisServiceFeatureTemplate +var ArcgisServiceFeatureMods arcgisServiceFeatureMods + +type arcgisServiceFeatureMods struct{} + +func (m arcgisServiceFeatureMods) RandomizeAllColumns(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModSlice{ + ArcgisServiceFeatureMods.RandomExtent(f), + ArcgisServiceFeatureMods.RandomItemID(f), + ArcgisServiceFeatureMods.RandomSpatialReference(f), + ArcgisServiceFeatureMods.RandomURL(f), + ArcgisServiceFeatureMods.RandomAccountID(f), + } +} + +// Set the model columns to this value +func (m arcgisServiceFeatureMods) Extent(val string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.Extent = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceFeatureMods) ExtentFunc(f func() string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.Extent = f + }) +} + +// Clear any values for the column +func (m arcgisServiceFeatureMods) UnsetExtent() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.Extent = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceFeatureMods) RandomExtent(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.Extent = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceFeatureMods) ItemID(val string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.ItemID = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceFeatureMods) ItemIDFunc(f func() string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.ItemID = f + }) +} + +// Clear any values for the column +func (m arcgisServiceFeatureMods) UnsetItemID() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.ItemID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceFeatureMods) RandomItemID(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.ItemID = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceFeatureMods) SpatialReference(val int32) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.SpatialReference = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceFeatureMods) SpatialReferenceFunc(f func() int32) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.SpatialReference = f + }) +} + +// Clear any values for the column +func (m arcgisServiceFeatureMods) UnsetSpatialReference() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.SpatialReference = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceFeatureMods) RandomSpatialReference(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.SpatialReference = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceFeatureMods) URL(val string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.URL = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceFeatureMods) URLFunc(f func() string) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.URL = f + }) +} + +// Clear any values for the column +func (m arcgisServiceFeatureMods) UnsetURL() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.URL = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceFeatureMods) RandomURL(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.URL = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceFeatureMods) AccountID(val null.Val[string]) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.AccountID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceFeatureMods) AccountIDFunc(f func() null.Val[string]) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.AccountID = f + }) +} + +// Clear any values for the column +func (m arcgisServiceFeatureMods) UnsetAccountID() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.AccountID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m arcgisServiceFeatureMods) RandomAccountID(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.AccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m arcgisServiceFeatureMods) RandomAccountIDNotNull(f *faker.Faker) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(_ context.Context, o *ArcgisServiceFeatureTemplate) { + o.AccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +func (m arcgisServiceFeatureMods) WithParentsCascading() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + if isDone, _ := arcgisServiceFeatureWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = arcgisServiceFeatureWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewArcgisAccountWithContext(ctx, ArcgisAccountMods.WithParentsCascading()) + m.WithAccount(related).Apply(ctx, o) + } + }) +} + +func (m arcgisServiceFeatureMods) WithAccount(rel *ArcgisAccountTemplate) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.Account = &arcgisServiceFeatureRAccountR{ + o: rel, + } + }) +} + +func (m arcgisServiceFeatureMods) WithNewAccount(mods ...ArcgisAccountMod) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + + m.WithAccount(related).Apply(ctx, o) + }) +} + +func (m arcgisServiceFeatureMods) WithExistingAccount(em *models.ArcgisAccount) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.Account = &arcgisServiceFeatureRAccountR{ + o: o.f.FromExistingArcgisAccount(em), + } + }) +} + +func (m arcgisServiceFeatureMods) WithoutAccount() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.Account = nil + }) +} + +func (m arcgisServiceFeatureMods) WithFeatureServiceItemLayers(number int, related *ArcgisLayerTemplate) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FeatureServiceItemLayers = []*arcgisServiceFeatureRFeatureServiceItemLayersR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisServiceFeatureMods) WithNewFeatureServiceItemLayers(number int, mods ...ArcgisLayerMod) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + related := o.f.NewArcgisLayerWithContext(ctx, mods...) + m.WithFeatureServiceItemLayers(number, related).Apply(ctx, o) + }) +} + +func (m arcgisServiceFeatureMods) AddFeatureServiceItemLayers(number int, related *ArcgisLayerTemplate) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FeatureServiceItemLayers = append(o.r.FeatureServiceItemLayers, &arcgisServiceFeatureRFeatureServiceItemLayersR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisServiceFeatureMods) AddNewFeatureServiceItemLayers(number int, mods ...ArcgisLayerMod) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + related := o.f.NewArcgisLayerWithContext(ctx, mods...) + m.AddFeatureServiceItemLayers(number, related).Apply(ctx, o) + }) +} + +func (m arcgisServiceFeatureMods) AddExistingFeatureServiceItemLayers(existingModels ...*models.ArcgisLayer) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + for _, em := range existingModels { + o.r.FeatureServiceItemLayers = append(o.r.FeatureServiceItemLayers, &arcgisServiceFeatureRFeatureServiceItemLayersR{ + o: o.f.FromExistingArcgisLayer(em), + }) + } + }) +} + +func (m arcgisServiceFeatureMods) WithoutFeatureServiceItemLayers() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FeatureServiceItemLayers = nil + }) +} + +func (m arcgisServiceFeatureMods) WithFieldseekerServiceFeatureItemOrganizations(number int, related *OrganizationTemplate) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FieldseekerServiceFeatureItemOrganizations = []*arcgisServiceFeatureRFieldseekerServiceFeatureItemOrganizationsR{{ + number: number, + o: related, + }} + }) +} + +func (m arcgisServiceFeatureMods) WithNewFieldseekerServiceFeatureItemOrganizations(number int, mods ...OrganizationMod) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + related := o.f.NewOrganizationWithContext(ctx, mods...) + m.WithFieldseekerServiceFeatureItemOrganizations(number, related).Apply(ctx, o) + }) +} + +func (m arcgisServiceFeatureMods) AddFieldseekerServiceFeatureItemOrganizations(number int, related *OrganizationTemplate) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FieldseekerServiceFeatureItemOrganizations = append(o.r.FieldseekerServiceFeatureItemOrganizations, &arcgisServiceFeatureRFieldseekerServiceFeatureItemOrganizationsR{ + number: number, + o: related, + }) + }) +} + +func (m arcgisServiceFeatureMods) AddNewFieldseekerServiceFeatureItemOrganizations(number int, mods ...OrganizationMod) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + related := o.f.NewOrganizationWithContext(ctx, mods...) + m.AddFieldseekerServiceFeatureItemOrganizations(number, related).Apply(ctx, o) + }) +} + +func (m arcgisServiceFeatureMods) AddExistingFieldseekerServiceFeatureItemOrganizations(existingModels ...*models.Organization) ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + for _, em := range existingModels { + o.r.FieldseekerServiceFeatureItemOrganizations = append(o.r.FieldseekerServiceFeatureItemOrganizations, &arcgisServiceFeatureRFieldseekerServiceFeatureItemOrganizationsR{ + o: o.f.FromExistingOrganization(em), + }) + } + }) +} + +func (m arcgisServiceFeatureMods) WithoutFieldseekerServiceFeatureItemOrganizations() ArcgisServiceFeatureMod { + return ArcgisServiceFeatureModFunc(func(ctx context.Context, o *ArcgisServiceFeatureTemplate) { + o.r.FieldseekerServiceFeatureItemOrganizations = nil + }) +} diff --git a/db/factory/arcgis.service_map.bob.go b/db/factory/arcgis.service_map.bob.go new file mode 100644 index 00000000..843d707b --- /dev/null +++ b/db/factory/arcgis.service_map.bob.go @@ -0,0 +1,501 @@ +// 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 factory + +import ( + "context" + "testing" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/omit" + "github.com/jaswdr/faker/v2" +) + +type ArcgisServiceMapMod interface { + Apply(context.Context, *ArcgisServiceMapTemplate) +} + +type ArcgisServiceMapModFunc func(context.Context, *ArcgisServiceMapTemplate) + +func (f ArcgisServiceMapModFunc) Apply(ctx context.Context, n *ArcgisServiceMapTemplate) { + f(ctx, n) +} + +type ArcgisServiceMapModSlice []ArcgisServiceMapMod + +func (mods ArcgisServiceMapModSlice) Apply(ctx context.Context, n *ArcgisServiceMapTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ArcgisServiceMapTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ArcgisServiceMapTemplate struct { + AccountID func() string + ArcgisID func() string + Name func() string + Title func() string + URL func() string + + r arcgisServiceMapR + f *Factory + + alreadyPersisted bool +} + +type arcgisServiceMapR struct { + Account *arcgisServiceMapRAccountR +} + +type arcgisServiceMapRAccountR struct { + o *ArcgisAccountTemplate +} + +// Apply mods to the ArcgisServiceMapTemplate +func (o *ArcgisServiceMapTemplate) Apply(ctx context.Context, mods ...ArcgisServiceMapMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.ArcgisServiceMap +// according to the relationships in the template. Nothing is inserted into the db +func (t ArcgisServiceMapTemplate) setModelRels(o *models.ArcgisServiceMap) { + if t.r.Account != nil { + rel := t.r.Account.o.Build() + rel.R.ServiceMaps = append(rel.R.ServiceMaps, o) + o.AccountID = rel.ID // h2 + o.R.Account = rel + } +} + +// BuildSetter returns an *models.ArcgisServiceMapSetter +// this does nothing with the relationship templates +func (o ArcgisServiceMapTemplate) BuildSetter() *models.ArcgisServiceMapSetter { + m := &models.ArcgisServiceMapSetter{} + + if o.AccountID != nil { + val := o.AccountID() + m.AccountID = omit.From(val) + } + if o.ArcgisID != nil { + val := o.ArcgisID() + m.ArcgisID = omit.From(val) + } + if o.Name != nil { + val := o.Name() + m.Name = omit.From(val) + } + if o.Title != nil { + val := o.Title() + m.Title = omit.From(val) + } + if o.URL != nil { + val := o.URL() + m.URL = omit.From(val) + } + + return m +} + +// BuildManySetter returns an []*models.ArcgisServiceMapSetter +// this does nothing with the relationship templates +func (o ArcgisServiceMapTemplate) BuildManySetter(number int) []*models.ArcgisServiceMapSetter { + m := make([]*models.ArcgisServiceMapSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.ArcgisServiceMap +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisServiceMapTemplate.Create +func (o ArcgisServiceMapTemplate) Build() *models.ArcgisServiceMap { + m := &models.ArcgisServiceMap{} + + if o.AccountID != nil { + m.AccountID = o.AccountID() + } + if o.ArcgisID != nil { + m.ArcgisID = o.ArcgisID() + } + if o.Name != nil { + m.Name = o.Name() + } + if o.Title != nil { + m.Title = o.Title() + } + if o.URL != nil { + m.URL = o.URL() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ArcgisServiceMapSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ArcgisServiceMapTemplate.CreateMany +func (o ArcgisServiceMapTemplate) BuildMany(number int) models.ArcgisServiceMapSlice { + m := make(models.ArcgisServiceMapSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableArcgisServiceMap(m *models.ArcgisServiceMapSetter) { + if !(m.AccountID.IsValue()) { + val := random_string(nil) + m.AccountID = omit.From(val) + } + if !(m.ArcgisID.IsValue()) { + val := random_string(nil) + m.ArcgisID = omit.From(val) + } + if !(m.Name.IsValue()) { + val := random_string(nil) + m.Name = omit.From(val) + } + if !(m.Title.IsValue()) { + val := random_string(nil) + m.Title = omit.From(val) + } + if !(m.URL.IsValue()) { + val := random_string(nil) + m.URL = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.ArcgisServiceMap +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ArcgisServiceMapTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.ArcgisServiceMap) error { + var err error + + return err +} + +// Create builds a arcgisServiceMap and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ArcgisServiceMapTemplate) Create(ctx context.Context, exec bob.Executor) (*models.ArcgisServiceMap, error) { + var err error + opt := o.BuildSetter() + ensureCreatableArcgisServiceMap(opt) + + if o.r.Account == nil { + ArcgisServiceMapMods.WithNewAccount().Apply(ctx, o) + } + + var rel0 *models.ArcgisAccount + + if o.r.Account.o.alreadyPersisted { + rel0 = o.r.Account.o.Build() + } else { + rel0, err = o.r.Account.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.AccountID = omit.From(rel0.ID) + + m, err := models.ArcgisServiceMaps.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + m.R.Account = rel0 + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a arcgisServiceMap and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ArcgisServiceMapTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.ArcgisServiceMap { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a arcgisServiceMap and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ArcgisServiceMapTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.ArcgisServiceMap { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple arcgisServiceMaps and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ArcgisServiceMapTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ArcgisServiceMapSlice, error) { + var err error + m := make(models.ArcgisServiceMapSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple arcgisServiceMaps and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ArcgisServiceMapTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ArcgisServiceMapSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple arcgisServiceMaps and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ArcgisServiceMapTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ArcgisServiceMapSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// ArcgisServiceMap has methods that act as mods for the ArcgisServiceMapTemplate +var ArcgisServiceMapMods arcgisServiceMapMods + +type arcgisServiceMapMods struct{} + +func (m arcgisServiceMapMods) RandomizeAllColumns(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModSlice{ + ArcgisServiceMapMods.RandomAccountID(f), + ArcgisServiceMapMods.RandomArcgisID(f), + ArcgisServiceMapMods.RandomName(f), + ArcgisServiceMapMods.RandomTitle(f), + ArcgisServiceMapMods.RandomURL(f), + } +} + +// Set the model columns to this value +func (m arcgisServiceMapMods) AccountID(val string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.AccountID = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceMapMods) AccountIDFunc(f func() string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.AccountID = f + }) +} + +// Clear any values for the column +func (m arcgisServiceMapMods) UnsetAccountID() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.AccountID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceMapMods) RandomAccountID(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.AccountID = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceMapMods) ArcgisID(val string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.ArcgisID = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceMapMods) ArcgisIDFunc(f func() string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.ArcgisID = f + }) +} + +// Clear any values for the column +func (m arcgisServiceMapMods) UnsetArcgisID() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.ArcgisID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceMapMods) RandomArcgisID(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.ArcgisID = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceMapMods) Name(val string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Name = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceMapMods) NameFunc(f func() string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Name = f + }) +} + +// Clear any values for the column +func (m arcgisServiceMapMods) UnsetName() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Name = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceMapMods) RandomName(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Name = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceMapMods) Title(val string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Title = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceMapMods) TitleFunc(f func() string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Title = f + }) +} + +// Clear any values for the column +func (m arcgisServiceMapMods) UnsetTitle() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Title = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceMapMods) RandomTitle(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.Title = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m arcgisServiceMapMods) URL(val string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.URL = func() string { return val } + }) +} + +// Set the Column from the function +func (m arcgisServiceMapMods) URLFunc(f func() string) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.URL = f + }) +} + +// Clear any values for the column +func (m arcgisServiceMapMods) UnsetURL() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.URL = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m arcgisServiceMapMods) RandomURL(f *faker.Faker) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(_ context.Context, o *ArcgisServiceMapTemplate) { + o.URL = func() string { + return random_string(f) + } + }) +} + +func (m arcgisServiceMapMods) WithParentsCascading() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(ctx context.Context, o *ArcgisServiceMapTemplate) { + if isDone, _ := arcgisServiceMapWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = arcgisServiceMapWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewArcgisAccountWithContext(ctx, ArcgisAccountMods.WithParentsCascading()) + m.WithAccount(related).Apply(ctx, o) + } + }) +} + +func (m arcgisServiceMapMods) WithAccount(rel *ArcgisAccountTemplate) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(ctx context.Context, o *ArcgisServiceMapTemplate) { + o.r.Account = &arcgisServiceMapRAccountR{ + o: rel, + } + }) +} + +func (m arcgisServiceMapMods) WithNewAccount(mods ...ArcgisAccountMod) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(ctx context.Context, o *ArcgisServiceMapTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + + m.WithAccount(related).Apply(ctx, o) + }) +} + +func (m arcgisServiceMapMods) WithExistingAccount(em *models.ArcgisAccount) ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(ctx context.Context, o *ArcgisServiceMapTemplate) { + o.r.Account = &arcgisServiceMapRAccountR{ + o: o.f.FromExistingArcgisAccount(em), + } + }) +} + +func (m arcgisServiceMapMods) WithoutAccount() ArcgisServiceMapMod { + return ArcgisServiceMapModFunc(func(ctx context.Context, o *ArcgisServiceMapTemplate) { + o.r.Account = nil + }) +} diff --git a/db/factory/bobfactory_context.bob.go b/db/factory/bobfactory_context.bob.go index 4c3c2c7b..906dd5fd 100644 --- a/db/factory/bobfactory_context.bob.go +++ b/db/factory/bobfactory_context.bob.go @@ -10,20 +10,25 @@ type contextKey string var ( // Relationship Contexts for address addressWithParentsCascadingCtx = newContextual[bool]("addressWithParentsCascading") + addressRelResidentsCtx = newContextual[bool]("address.resident.resident.resident_address_id_fkey") addressRelSiteCtx = newContextual[bool]("address.site.site.site_address_id_fkey") + // Relationship Contexts for arcgis.account + arcgisAccountWithParentsCascadingCtx = newContextual[bool]("arcgisAccountWithParentsCascading") + arcgisAccountRelOrganizationCtx = newContextual[bool]("arcgis.account.organization.arcgis.account.account_organization_id_fkey") + arcgisAccountRelArcgisAccountOauthTokensCtx = newContextual[bool]("arcgis.account.arcgis.oauth_token.arcgis.oauth_token.oauth_token_arcgis_account_id_fkey") + arcgisAccountRelServiceFeaturesCtx = newContextual[bool]("arcgis.account.arcgis.service_feature.arcgis.service_feature.service_feature_account_id_fkey") + arcgisAccountRelServiceMapsCtx = newContextual[bool]("arcgis.account.arcgis.service_map.arcgis.service_map.service_map_account_id_fkey") + arcgisAccountRelArcgisAccountOrganizationsCtx = newContextual[bool]("arcgis.account.organization.organization.organization_arcgis_account_id_fkey") + // Relationship Contexts for arcgis.address_mapping arcgisAddressMappingWithParentsCascadingCtx = newContextual[bool]("arcgisAddressMappingWithParentsCascading") arcgisAddressMappingRelLayerFieldCtx = newContextual[bool]("arcgis.address_mapping.arcgis.layer_field.arcgis.address_mapping.address_mapping_layer_feature_service_item_id_layer_index__fkey") arcgisAddressMappingRelOrganizationCtx = newContextual[bool]("arcgis.address_mapping.organization.arcgis.address_mapping.address_mapping_organization_id_fkey") - // Relationship Contexts for arcgis.feature_service - arcgisFeatureServiceWithParentsCascadingCtx = newContextual[bool]("arcgisFeatureServiceWithParentsCascading") - arcgisFeatureServiceRelFeatureServiceItemLayersCtx = newContextual[bool]("arcgis.feature_service.arcgis.layer.arcgis.layer.layer_feature_service_item_id_fkey") - // Relationship Contexts for arcgis.layer arcgisLayerWithParentsCascadingCtx = newContextual[bool]("arcgisLayerWithParentsCascading") - arcgisLayerRelFeatureServiceItemFeatureServiceCtx = newContextual[bool]("arcgis.feature_service.arcgis.layer.arcgis.layer.layer_feature_service_item_id_fkey") + arcgisLayerRelFeatureServiceItemServiceFeatureCtx = newContextual[bool]("arcgis.layer.arcgis.service_feature.arcgis.layer.layer_feature_service_item_id_fkey") arcgisLayerRelLayerFieldsCtx = newContextual[bool]("arcgis.layer.arcgis.layer_field.arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey") // Relationship Contexts for arcgis.layer_field @@ -32,11 +37,26 @@ var ( arcgisLayerFieldRelLayerCtx = newContextual[bool]("arcgis.layer.arcgis.layer_field.arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey") arcgisLayerFieldRelParcelMappingsCtx = newContextual[bool]("arcgis.layer_field.arcgis.parcel_mapping.arcgis.parcel_mapping.parcel_mapping_layer_feature_service_item_id_layer_index_l_fkey") + // Relationship Contexts for arcgis.oauth_token + arcgisOauthTokenWithParentsCascadingCtx = newContextual[bool]("arcgisOauthTokenWithParentsCascading") + arcgisOauthTokenRelArcgisAccountAccountCtx = newContextual[bool]("arcgis.account.arcgis.oauth_token.arcgis.oauth_token.oauth_token_arcgis_account_id_fkey") + arcgisOauthTokenRelUserUserCtx = newContextual[bool]("arcgis.oauth_token.user_.arcgis.oauth_token.oauth_token_user_id_fkey") + // Relationship Contexts for arcgis.parcel_mapping arcgisParcelMappingWithParentsCascadingCtx = newContextual[bool]("arcgisParcelMappingWithParentsCascading") arcgisParcelMappingRelLayerFieldCtx = newContextual[bool]("arcgis.layer_field.arcgis.parcel_mapping.arcgis.parcel_mapping.parcel_mapping_layer_feature_service_item_id_layer_index_l_fkey") arcgisParcelMappingRelOrganizationCtx = newContextual[bool]("arcgis.parcel_mapping.organization.arcgis.parcel_mapping.parcel_mapping_organization_id_fkey") + // Relationship Contexts for arcgis.service_feature + arcgisServiceFeatureWithParentsCascadingCtx = newContextual[bool]("arcgisServiceFeatureWithParentsCascading") + arcgisServiceFeatureRelFeatureServiceItemLayersCtx = newContextual[bool]("arcgis.layer.arcgis.service_feature.arcgis.layer.layer_feature_service_item_id_fkey") + arcgisServiceFeatureRelAccountCtx = newContextual[bool]("arcgis.account.arcgis.service_feature.arcgis.service_feature.service_feature_account_id_fkey") + arcgisServiceFeatureRelFieldseekerServiceFeatureItemOrganizationsCtx = newContextual[bool]("arcgis.service_feature.organization.organization.organization_fieldseeker_service_feature_item_id_fkey") + + // Relationship Contexts for arcgis.service_map + arcgisServiceMapWithParentsCascadingCtx = newContextual[bool]("arcgisServiceMapWithParentsCascading") + arcgisServiceMapRelAccountCtx = newContextual[bool]("arcgis.account.arcgis.service_map.arcgis.service_map.service_map_account_id_fkey") + // Relationship Contexts for arcgis.user_ arcgisuserWithParentsCascadingCtx = newContextual[bool]("arcgisuserWithParentsCascading") arcgisuserRelPublicUserUserCtx = newContextual[bool]("arcgis.user_.user_.arcgis.user_.user__public_user_id_fkey") @@ -63,6 +83,9 @@ var ( commsEmailTemplateWithParentsCascadingCtx = newContextual[bool]("commsEmailTemplateWithParentsCascading") commsEmailTemplateRelTemplateEmailLogsCtx = newContextual[bool]("comms.email_log.comms.email_template.comms.email_log.email_log_template_id_fkey") + // Relationship Contexts for comms.mailer + commsMailerWithParentsCascadingCtx = newContextual[bool]("commsMailerWithParentsCascading") + // Relationship Contexts for comms.phone commsPhoneWithParentsCascadingCtx = newContextual[bool]("commsPhoneWithParentsCascading") commsPhoneRelDestinationTextJobsCtx = newContextual[bool]("comms.phone.comms.text_job.comms.text_job.text_job_destination_fkey") @@ -74,6 +97,7 @@ var ( commsPhoneRelPhoneE164NotifyPhoneNuisancesCtx = newContextual[bool]("comms.phone.publicreport.notify_phone_nuisance.publicreport.notify_phone_nuisance.notify_phone_nuisance_phone_e164_fkey") commsPhoneRelPhoneE164NotifyPhonePoolsCtx = newContextual[bool]("comms.phone.publicreport.notify_phone_pool.publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey") commsPhoneRelPhoneE164SubscribePhonesCtx = newContextual[bool]("comms.phone.publicreport.subscribe_phone.publicreport.subscribe_phone.subscribe_phone_phone_e164_fkey") + commsPhoneRelPhoneMobileResidentsCtx = newContextual[bool]("comms.phone.resident.resident.resident_phone_mobile_fkey") // Relationship Contexts for comms.text_job commsTextJobWithParentsCascadingCtx = newContextual[bool]("commsTextJobWithParentsCascading") @@ -84,6 +108,11 @@ var ( commsTextLogRelDestinationPhoneCtx = newContextual[bool]("comms.phone.comms.text_log.comms.text_log.text_log_destination_fkey") commsTextLogRelSourcePhoneCtx = newContextual[bool]("comms.phone.comms.text_log.comms.text_log.text_log_source_fkey") + // Relationship Contexts for compliance_report_request + complianceReportRequestWithParentsCascadingCtx = newContextual[bool]("complianceReportRequestWithParentsCascading") + complianceReportRequestRelCreatorUserCtx = newContextual[bool]("compliance_report_request.user_.compliance_report_request.compliance_report_request_creator_fkey") + complianceReportRequestRelSiteCtx = newContextual[bool]("compliance_report_request.site.compliance_report_request.compliance_report_request_site_id_site_version_fkey") + // Relationship Contexts for district_subscription_email districtSubscriptionEmailWithParentsCascadingCtx = newContextual[bool]("districtSubscriptionEmailWithParentsCascading") districtSubscriptionEmailRelEmailContactAddressEmailContactCtx = newContextual[bool]("comms.email_contact.district_subscription_email.district_subscription_email.district_subscription_email_email_contact_address_fkey") @@ -285,60 +314,61 @@ var ( notificationWithParentsCascadingCtx = newContextual[bool]("notificationWithParentsCascading") notificationRelUserUserCtx = newContextual[bool]("notification.user_.notification.notification_user_id_fkey") - // Relationship Contexts for oauth_token - oauthTokenWithParentsCascadingCtx = newContextual[bool]("oauthTokenWithParentsCascading") - oauthTokenRelUserUserCtx = newContextual[bool]("oauth_token.user_.oauth_token.oauth_token_user_id_fkey") - // Relationship Contexts for organization - organizationWithParentsCascadingCtx = newContextual[bool]("organizationWithParentsCascading") - organizationRelAddressMappingsCtx = newContextual[bool]("arcgis.address_mapping.organization.arcgis.address_mapping.address_mapping_organization_id_fkey") - organizationRelParcelMappingsCtx = newContextual[bool]("arcgis.parcel_mapping.organization.arcgis.parcel_mapping.parcel_mapping_organization_id_fkey") - organizationRelEmailContactsCtx = newContextual[bool]("comms.email_contact.organization.district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey") - organizationRelPhonesCtx = newContextual[bool]("comms.phone.organization.district_subscription_phone.district_subscription_phone_organization_id_fkeydistrict_subscription_phone.district_subscription_phone_phone_e164_fkey") - organizationRelContainerrelatesCtx = newContextual[bool]("fieldseeker.containerrelate.organization.fieldseeker.containerrelate.containerrelate_organization_id_fkey") - organizationRelFieldscoutinglogsCtx = newContextual[bool]("fieldseeker.fieldscoutinglog.organization.fieldseeker.fieldscoutinglog.fieldscoutinglog_organization_id_fkey") - organizationRelHabitatrelatesCtx = newContextual[bool]("fieldseeker.habitatrelate.organization.fieldseeker.habitatrelate.habitatrelate_organization_id_fkey") - organizationRelInspectionsamplesCtx = newContextual[bool]("fieldseeker.inspectionsample.organization.fieldseeker.inspectionsample.inspectionsample_organization_id_fkey") - organizationRelInspectionsampledetailsCtx = newContextual[bool]("fieldseeker.inspectionsampledetail.organization.fieldseeker.inspectionsampledetail.inspectionsampledetail_organization_id_fkey") - organizationRelLinelocationsCtx = newContextual[bool]("fieldseeker.linelocation.organization.fieldseeker.linelocation.linelocation_organization_id_fkey") - organizationRelLocationtrackingsCtx = newContextual[bool]("fieldseeker.locationtracking.organization.fieldseeker.locationtracking.locationtracking_organization_id_fkey") - organizationRelMosquitoinspectionsCtx = newContextual[bool]("fieldseeker.mosquitoinspection.organization.fieldseeker.mosquitoinspection.mosquitoinspection_organization_id_fkey") - organizationRelPointlocationsCtx = newContextual[bool]("fieldseeker.pointlocation.organization.fieldseeker.pointlocation.pointlocation_organization_id_fkey") - organizationRelPolygonlocationsCtx = newContextual[bool]("fieldseeker.polygonlocation.organization.fieldseeker.polygonlocation.polygonlocation_organization_id_fkey") - organizationRelFieldseekerPoolCtx = newContextual[bool]("fieldseeker.pool.organization.fieldseeker.pool.pool_organization_id_fkey") - organizationRelPooldetailsCtx = newContextual[bool]("fieldseeker.pooldetail.organization.fieldseeker.pooldetail.pooldetail_organization_id_fkey") - organizationRelProposedtreatmentareasCtx = newContextual[bool]("fieldseeker.proposedtreatmentarea.organization.fieldseeker.proposedtreatmentarea.proposedtreatmentarea_organization_id_fkey") - organizationRelQamosquitoinspectionsCtx = newContextual[bool]("fieldseeker.qamosquitoinspection.organization.fieldseeker.qamosquitoinspection.qamosquitoinspection_organization_id_fkey") - organizationRelRodentlocationsCtx = newContextual[bool]("fieldseeker.rodentlocation.organization.fieldseeker.rodentlocation.rodentlocation_organization_id_fkey") - organizationRelSamplecollectionsCtx = newContextual[bool]("fieldseeker.samplecollection.organization.fieldseeker.samplecollection.samplecollection_organization_id_fkey") - organizationRelSamplelocationsCtx = newContextual[bool]("fieldseeker.samplelocation.organization.fieldseeker.samplelocation.samplelocation_organization_id_fkey") - organizationRelServicerequestsCtx = newContextual[bool]("fieldseeker.servicerequest.organization.fieldseeker.servicerequest.servicerequest_organization_id_fkey") - organizationRelSpeciesabundancesCtx = newContextual[bool]("fieldseeker.speciesabundance.organization.fieldseeker.speciesabundance.speciesabundance_organization_id_fkey") - organizationRelStormdrainsCtx = newContextual[bool]("fieldseeker.stormdrain.organization.fieldseeker.stormdrain.stormdrain_organization_id_fkey") - organizationRelTimecardsCtx = newContextual[bool]("fieldseeker.timecard.organization.fieldseeker.timecard.timecard_organization_id_fkey") - organizationRelTrapdataCtx = newContextual[bool]("fieldseeker.trapdata.organization.fieldseeker.trapdata.trapdata_organization_id_fkey") - organizationRelTraplocationsCtx = newContextual[bool]("fieldseeker.traplocation.organization.fieldseeker.traplocation.traplocation_organization_id_fkey") - organizationRelTreatmentsCtx = newContextual[bool]("fieldseeker.treatment.organization.fieldseeker.treatment.treatment_organization_id_fkey") - organizationRelTreatmentareasCtx = newContextual[bool]("fieldseeker.treatmentarea.organization.fieldseeker.treatmentarea.treatmentarea_organization_id_fkey") - organizationRelZonesCtx = newContextual[bool]("fieldseeker.zones.organization.fieldseeker.zones.zones_organization_id_fkey") - organizationRelZones2sCtx = newContextual[bool]("fieldseeker.zones2.organization.fieldseeker.zones2.zones2_organization_id_fkey") - organizationRelFieldseekerSyncsCtx = newContextual[bool]("fieldseeker_sync.organization.fieldseeker_sync.fieldseeker_sync_organization_id_fkey") - organizationRelFilesCtx = newContextual[bool]("fileupload.file.organization.fileupload.file.file_organization_id_fkey") - organizationRelPoolsCtx = newContextual[bool]("fileupload.pool.organization.fileupload.pool.pool_organization_id_fkey") - organizationRelH3AggregationsCtx = newContextual[bool]("h3_aggregation.organization.h3_aggregation.h3_aggregation_organization_id_fkey") - organizationRelNoteAudiosCtx = newContextual[bool]("note_audio.organization.note_audio.note_audio_organization_id_fkey") - organizationRelNoteImagesCtx = newContextual[bool]("note_image.organization.note_image.note_image_organization_id_fkey") - organizationRelNuisancesCtx = newContextual[bool]("organization.publicreport.nuisance.publicreport.nuisance.nuisance_organization_id_fkey") - organizationRelPublicreportPoolCtx = newContextual[bool]("organization.publicreport.pool.publicreport.pool.pool_organization_id_fkey") - organizationRelQuicksCtx = newContextual[bool]("organization.publicreport.quick.publicreport.quick.quick_organization_id_fkey") - organizationRelUserCtx = newContextual[bool]("organization.user_.user_.user__organization_id_fkey") + organizationWithParentsCascadingCtx = newContextual[bool]("organizationWithParentsCascading") + organizationRelAccountsCtx = newContextual[bool]("arcgis.account.organization.arcgis.account.account_organization_id_fkey") + organizationRelAddressMappingsCtx = newContextual[bool]("arcgis.address_mapping.organization.arcgis.address_mapping.address_mapping_organization_id_fkey") + organizationRelParcelMappingsCtx = newContextual[bool]("arcgis.parcel_mapping.organization.arcgis.parcel_mapping.parcel_mapping_organization_id_fkey") + organizationRelEmailContactsCtx = newContextual[bool]("comms.email_contact.organization.district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey") + organizationRelPhonesCtx = newContextual[bool]("comms.phone.organization.district_subscription_phone.district_subscription_phone_organization_id_fkeydistrict_subscription_phone.district_subscription_phone_phone_e164_fkey") + organizationRelContainerrelatesCtx = newContextual[bool]("fieldseeker.containerrelate.organization.fieldseeker.containerrelate.containerrelate_organization_id_fkey") + organizationRelFieldscoutinglogsCtx = newContextual[bool]("fieldseeker.fieldscoutinglog.organization.fieldseeker.fieldscoutinglog.fieldscoutinglog_organization_id_fkey") + organizationRelHabitatrelatesCtx = newContextual[bool]("fieldseeker.habitatrelate.organization.fieldseeker.habitatrelate.habitatrelate_organization_id_fkey") + organizationRelInspectionsamplesCtx = newContextual[bool]("fieldseeker.inspectionsample.organization.fieldseeker.inspectionsample.inspectionsample_organization_id_fkey") + organizationRelInspectionsampledetailsCtx = newContextual[bool]("fieldseeker.inspectionsampledetail.organization.fieldseeker.inspectionsampledetail.inspectionsampledetail_organization_id_fkey") + organizationRelLinelocationsCtx = newContextual[bool]("fieldseeker.linelocation.organization.fieldseeker.linelocation.linelocation_organization_id_fkey") + organizationRelLocationtrackingsCtx = newContextual[bool]("fieldseeker.locationtracking.organization.fieldseeker.locationtracking.locationtracking_organization_id_fkey") + organizationRelMosquitoinspectionsCtx = newContextual[bool]("fieldseeker.mosquitoinspection.organization.fieldseeker.mosquitoinspection.mosquitoinspection_organization_id_fkey") + organizationRelPointlocationsCtx = newContextual[bool]("fieldseeker.pointlocation.organization.fieldseeker.pointlocation.pointlocation_organization_id_fkey") + organizationRelPolygonlocationsCtx = newContextual[bool]("fieldseeker.polygonlocation.organization.fieldseeker.polygonlocation.polygonlocation_organization_id_fkey") + organizationRelFieldseekerPoolCtx = newContextual[bool]("fieldseeker.pool.organization.fieldseeker.pool.pool_organization_id_fkey") + organizationRelPooldetailsCtx = newContextual[bool]("fieldseeker.pooldetail.organization.fieldseeker.pooldetail.pooldetail_organization_id_fkey") + organizationRelProposedtreatmentareasCtx = newContextual[bool]("fieldseeker.proposedtreatmentarea.organization.fieldseeker.proposedtreatmentarea.proposedtreatmentarea_organization_id_fkey") + organizationRelQamosquitoinspectionsCtx = newContextual[bool]("fieldseeker.qamosquitoinspection.organization.fieldseeker.qamosquitoinspection.qamosquitoinspection_organization_id_fkey") + organizationRelRodentlocationsCtx = newContextual[bool]("fieldseeker.rodentlocation.organization.fieldseeker.rodentlocation.rodentlocation_organization_id_fkey") + organizationRelSamplecollectionsCtx = newContextual[bool]("fieldseeker.samplecollection.organization.fieldseeker.samplecollection.samplecollection_organization_id_fkey") + organizationRelSamplelocationsCtx = newContextual[bool]("fieldseeker.samplelocation.organization.fieldseeker.samplelocation.samplelocation_organization_id_fkey") + organizationRelServicerequestsCtx = newContextual[bool]("fieldseeker.servicerequest.organization.fieldseeker.servicerequest.servicerequest_organization_id_fkey") + organizationRelSpeciesabundancesCtx = newContextual[bool]("fieldseeker.speciesabundance.organization.fieldseeker.speciesabundance.speciesabundance_organization_id_fkey") + organizationRelStormdrainsCtx = newContextual[bool]("fieldseeker.stormdrain.organization.fieldseeker.stormdrain.stormdrain_organization_id_fkey") + organizationRelTimecardsCtx = newContextual[bool]("fieldseeker.timecard.organization.fieldseeker.timecard.timecard_organization_id_fkey") + organizationRelTrapdataCtx = newContextual[bool]("fieldseeker.trapdata.organization.fieldseeker.trapdata.trapdata_organization_id_fkey") + organizationRelTraplocationsCtx = newContextual[bool]("fieldseeker.traplocation.organization.fieldseeker.traplocation.traplocation_organization_id_fkey") + organizationRelTreatmentsCtx = newContextual[bool]("fieldseeker.treatment.organization.fieldseeker.treatment.treatment_organization_id_fkey") + organizationRelTreatmentareasCtx = newContextual[bool]("fieldseeker.treatmentarea.organization.fieldseeker.treatmentarea.treatmentarea_organization_id_fkey") + organizationRelZonesCtx = newContextual[bool]("fieldseeker.zones.organization.fieldseeker.zones.zones_organization_id_fkey") + organizationRelZones2sCtx = newContextual[bool]("fieldseeker.zones2.organization.fieldseeker.zones2.zones2_organization_id_fkey") + organizationRelFieldseekerSyncsCtx = newContextual[bool]("fieldseeker_sync.organization.fieldseeker_sync.fieldseeker_sync_organization_id_fkey") + organizationRelFilesCtx = newContextual[bool]("fileupload.file.organization.fileupload.file.file_organization_id_fkey") + organizationRelPoolsCtx = newContextual[bool]("fileupload.pool.organization.fileupload.pool.pool_organization_id_fkey") + organizationRelH3AggregationsCtx = newContextual[bool]("h3_aggregation.organization.h3_aggregation.h3_aggregation_organization_id_fkey") + organizationRelNoteAudiosCtx = newContextual[bool]("note_audio.organization.note_audio.note_audio_organization_id_fkey") + organizationRelNoteImagesCtx = newContextual[bool]("note_image.organization.note_image.note_image_organization_id_fkey") + organizationRelArcgisAccountAccountCtx = newContextual[bool]("arcgis.account.organization.organization.organization_arcgis_account_id_fkey") + organizationRelFieldseekerServiceFeatureItemServiceFeatureCtx = newContextual[bool]("arcgis.service_feature.organization.organization.organization_fieldseeker_service_feature_item_id_fkey") + organizationRelNuisancesCtx = newContextual[bool]("organization.publicreport.nuisance.publicreport.nuisance.nuisance_organization_id_fkey") + organizationRelPublicreportPoolCtx = newContextual[bool]("organization.publicreport.pool.publicreport.pool.pool_organization_id_fkey") + organizationRelQuicksCtx = newContextual[bool]("organization.publicreport.quick.publicreport.quick.quick_organization_id_fkey") + organizationRelUserCtx = newContextual[bool]("organization.user_.user_.user__organization_id_fkey") // Relationship Contexts for parcel parcelWithParentsCascadingCtx = newContextual[bool]("parcelWithParentsCascading") + parcelRelSitesCtx = newContextual[bool]("parcel.site.site.site_parcel_id_fkey") // Relationship Contexts for pool poolWithParentsCascadingCtx = newContextual[bool]("poolWithParentsCascading") poolRelCreatorUserCtx = newContextual[bool]("pool.user_.pool.pool_creator_id_fkey") + poolRelSiteCtx = newContextual[bool]("pool.site.pool.pool_site_id_site_version_fkey") // Relationship Contexts for publicreport.image publicreportImageWithParentsCascadingCtx = newContextual[bool]("publicreportImageWithParentsCascading") @@ -422,32 +452,45 @@ var ( // Relationship Contexts for raster_overviews rasterOverviewWithParentsCascadingCtx = newContextual[bool]("rasterOverviewWithParentsCascading") + // Relationship Contexts for resident + residentWithParentsCascadingCtx = newContextual[bool]("residentWithParentsCascading") + residentRelAddressCtx = newContextual[bool]("address.resident.resident.resident_address_id_fkey") + residentRelCreatorUserCtx = newContextual[bool]("resident.user_.resident.resident_creator_fkey") + residentRelPhoneMobilePhoneCtx = newContextual[bool]("comms.phone.resident.resident.resident_phone_mobile_fkey") + residentRelSiteCtx = newContextual[bool]("resident.site.resident.resident_site_id_site_version_fkey") + // Relationship Contexts for sessions sessionWithParentsCascadingCtx = newContextual[bool]("sessionWithParentsCascading") // Relationship Contexts for site - siteWithParentsCascadingCtx = newContextual[bool]("siteWithParentsCascading") - siteRelAddressCtx = newContextual[bool]("address.site.site.site_address_id_fkey") - siteRelCreatorUserCtx = newContextual[bool]("site.user_.site.site_creator_id_fkey") - siteRelFileCtx = newContextual[bool]("fileupload.file.site.site.site_file_id_fkey") + siteWithParentsCascadingCtx = newContextual[bool]("siteWithParentsCascading") + siteRelComplianceReportRequestsCtx = newContextual[bool]("compliance_report_request.site.compliance_report_request.compliance_report_request_site_id_site_version_fkey") + siteRelPoolsCtx = newContextual[bool]("pool.site.pool.pool_site_id_site_version_fkey") + siteRelResidentsCtx = newContextual[bool]("resident.site.resident.resident_site_id_site_version_fkey") + siteRelAddressCtx = newContextual[bool]("address.site.site.site_address_id_fkey") + siteRelCreatorUserCtx = newContextual[bool]("site.user_.site.site_creator_id_fkey") + siteRelFileCtx = newContextual[bool]("fileupload.file.site.site.site_file_id_fkey") + siteRelParcelCtx = newContextual[bool]("parcel.site.site.site_parcel_id_fkey") // Relationship Contexts for spatial_ref_sys spatialRefSyWithParentsCascadingCtx = newContextual[bool]("spatialRefSyWithParentsCascading") // Relationship Contexts for user_ - userWithParentsCascadingCtx = newContextual[bool]("userWithParentsCascading") - userRelPublicUserUserCtx = newContextual[bool]("arcgis.user_.user_.arcgis.user_.user__public_user_id_fkey") - userRelCreatorFilesCtx = newContextual[bool]("fileupload.file.user_.fileupload.file.file_creator_id_fkey") - userRelFileuploadPoolCtx = newContextual[bool]("fileupload.pool.user_.fileupload.pool.pool_creator_id_fkey") - userRelCreatorNoteAudiosCtx = newContextual[bool]("note_audio.user_.note_audio.note_audio_creator_id_fkey") - userRelDeletorNoteAudiosCtx = newContextual[bool]("note_audio.user_.note_audio.note_audio_deletor_id_fkey") - userRelCreatorNoteImagesCtx = newContextual[bool]("note_image.user_.note_image.note_image_creator_id_fkey") - userRelDeletorNoteImagesCtx = newContextual[bool]("note_image.user_.note_image.note_image_deletor_id_fkey") - userRelUserNotificationsCtx = newContextual[bool]("notification.user_.notification.notification_user_id_fkey") - userRelUserOauthTokensCtx = newContextual[bool]("oauth_token.user_.oauth_token.oauth_token_user_id_fkey") - userRelCreatorPoolsCtx = newContextual[bool]("pool.user_.pool.pool_creator_id_fkey") - userRelCreatorSitesCtx = newContextual[bool]("site.user_.site.site_creator_id_fkey") - userRelOrganizationCtx = newContextual[bool]("organization.user_.user_.user__organization_id_fkey") + userWithParentsCascadingCtx = newContextual[bool]("userWithParentsCascading") + userRelUserOauthTokensCtx = newContextual[bool]("arcgis.oauth_token.user_.arcgis.oauth_token.oauth_token_user_id_fkey") + userRelPublicUserUserCtx = newContextual[bool]("arcgis.user_.user_.arcgis.user_.user__public_user_id_fkey") + userRelCreatorComplianceReportRequestsCtx = newContextual[bool]("compliance_report_request.user_.compliance_report_request.compliance_report_request_creator_fkey") + userRelCreatorFilesCtx = newContextual[bool]("fileupload.file.user_.fileupload.file.file_creator_id_fkey") + userRelFileuploadPoolCtx = newContextual[bool]("fileupload.pool.user_.fileupload.pool.pool_creator_id_fkey") + userRelCreatorNoteAudiosCtx = newContextual[bool]("note_audio.user_.note_audio.note_audio_creator_id_fkey") + userRelDeletorNoteAudiosCtx = newContextual[bool]("note_audio.user_.note_audio.note_audio_deletor_id_fkey") + userRelCreatorNoteImagesCtx = newContextual[bool]("note_image.user_.note_image.note_image_creator_id_fkey") + userRelDeletorNoteImagesCtx = newContextual[bool]("note_image.user_.note_image.note_image_deletor_id_fkey") + userRelUserNotificationsCtx = newContextual[bool]("notification.user_.notification.notification_user_id_fkey") + userRelCreatorPoolsCtx = newContextual[bool]("pool.user_.pool.pool_creator_id_fkey") + userRelCreatorResidentsCtx = newContextual[bool]("resident.user_.resident.resident_creator_fkey") + userRelCreatorSitesCtx = newContextual[bool]("site.user_.site.site_creator_id_fkey") + userRelOrganizationCtx = newContextual[bool]("organization.user_.user_.user__organization_id_fkey") ) // Contextual is a convienience wrapper around context.WithValue and context.Value diff --git a/db/factory/bobfactory_main.bob.go b/db/factory/bobfactory_main.bob.go index 95689998..44dcdcdc 100644 --- a/db/factory/bobfactory_main.bob.go +++ b/db/factory/bobfactory_main.bob.go @@ -20,19 +20,24 @@ import ( type Factory struct { baseAddressMods AddressModSlice + baseArcgisAccountMods ArcgisAccountModSlice baseArcgisAddressMappingMods ArcgisAddressMappingModSlice - baseArcgisFeatureServiceMods ArcgisFeatureServiceModSlice baseArcgisLayerMods ArcgisLayerModSlice baseArcgisLayerFieldMods ArcgisLayerFieldModSlice + baseArcgisOauthTokenMods ArcgisOauthTokenModSlice baseArcgisParcelMappingMods ArcgisParcelMappingModSlice + baseArcgisServiceFeatureMods ArcgisServiceFeatureModSlice + baseArcgisServiceMapMods ArcgisServiceMapModSlice baseArcgisUserMods ArcgisUserModSlice baseArcgisUserPrivilegeMods ArcgisUserPrivilegeModSlice baseCommsEmailContactMods CommsEmailContactModSlice baseCommsEmailLogMods CommsEmailLogModSlice baseCommsEmailTemplateMods CommsEmailTemplateModSlice + baseCommsMailerMods CommsMailerModSlice baseCommsPhoneMods CommsPhoneModSlice baseCommsTextJobMods CommsTextJobModSlice baseCommsTextLogMods CommsTextLogModSlice + baseComplianceReportRequestMods ComplianceReportRequestModSlice baseDistrictSubscriptionEmailMods DistrictSubscriptionEmailModSlice baseDistrictSubscriptionPhoneMods DistrictSubscriptionPhoneModSlice baseFieldseekerContainerrelateMods FieldseekerContainerrelateModSlice @@ -79,7 +84,6 @@ type Factory struct { baseNoteImageBreadcrumbMods NoteImageBreadcrumbModSlice baseNoteImageDatumMods NoteImageDatumModSlice baseNotificationMods NotificationModSlice - baseOauthTokenMods OauthTokenModSlice baseOrganizationMods OrganizationModSlice baseParcelMods ParcelModSlice basePoolMods PoolModSlice @@ -100,6 +104,7 @@ type Factory struct { basePublicreportSubscribePhoneMods PublicreportSubscribePhoneModSlice baseRasterColumnMods RasterColumnModSlice baseRasterOverviewMods RasterOverviewModSlice + baseResidentMods ResidentModSlice baseSessionMods SessionModSlice baseSiteMods SiteModSlice baseSpatialRefSyMods SpatialRefSyModSlice @@ -141,6 +146,9 @@ func (f *Factory) FromExistingAddress(m *models.Address) *AddressTemplate { o.Unit = func() string { return m.Unit } ctx := context.Background() + if len(m.R.Residents) > 0 { + AddressMods.AddExistingResidents(m.R.Residents...).Apply(ctx, o) + } if m.R.Site != nil { AddressMods.WithExistingSite(m.R.Site).Apply(ctx, o) } @@ -148,6 +156,54 @@ func (f *Factory) FromExistingAddress(m *models.Address) *AddressTemplate { return o } +func (f *Factory) NewArcgisAccount(mods ...ArcgisAccountMod) *ArcgisAccountTemplate { + return f.NewArcgisAccountWithContext(context.Background(), mods...) +} + +func (f *Factory) NewArcgisAccountWithContext(ctx context.Context, mods ...ArcgisAccountMod) *ArcgisAccountTemplate { + o := &ArcgisAccountTemplate{f: f} + + if f != nil { + f.baseArcgisAccountMods.Apply(ctx, o) + } + + ArcgisAccountModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingArcgisAccount(m *models.ArcgisAccount) *ArcgisAccountTemplate { + o := &ArcgisAccountTemplate{f: f, alreadyPersisted: true} + + o.ID = func() string { return m.ID } + o.Name = func() string { return m.Name } + o.OrganizationID = func() int32 { return m.OrganizationID } + o.URLFeatures = func() null.Val[string] { return m.URLFeatures } + o.URLInsights = func() null.Val[string] { return m.URLInsights } + o.URLGeometry = func() null.Val[string] { return m.URLGeometry } + o.URLNotebooks = func() null.Val[string] { return m.URLNotebooks } + o.URLTiles = func() null.Val[string] { return m.URLTiles } + + ctx := context.Background() + if m.R.Organization != nil { + ArcgisAccountMods.WithExistingOrganization(m.R.Organization).Apply(ctx, o) + } + if len(m.R.ArcgisAccountOauthTokens) > 0 { + ArcgisAccountMods.AddExistingArcgisAccountOauthTokens(m.R.ArcgisAccountOauthTokens...).Apply(ctx, o) + } + if len(m.R.ServiceFeatures) > 0 { + ArcgisAccountMods.AddExistingServiceFeatures(m.R.ServiceFeatures...).Apply(ctx, o) + } + if len(m.R.ServiceMaps) > 0 { + ArcgisAccountMods.AddExistingServiceMaps(m.R.ServiceMaps...).Apply(ctx, o) + } + if len(m.R.ArcgisAccountOrganizations) > 0 { + ArcgisAccountMods.AddExistingArcgisAccountOrganizations(m.R.ArcgisAccountOrganizations...).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewArcgisAddressMapping(mods ...ArcgisAddressMappingMod) *ArcgisAddressMappingTemplate { return f.NewArcgisAddressMappingWithContext(context.Background(), mods...) } @@ -184,38 +240,6 @@ func (f *Factory) FromExistingArcgisAddressMapping(m *models.ArcgisAddressMappin return o } -func (f *Factory) NewArcgisFeatureService(mods ...ArcgisFeatureServiceMod) *ArcgisFeatureServiceTemplate { - return f.NewArcgisFeatureServiceWithContext(context.Background(), mods...) -} - -func (f *Factory) NewArcgisFeatureServiceWithContext(ctx context.Context, mods ...ArcgisFeatureServiceMod) *ArcgisFeatureServiceTemplate { - o := &ArcgisFeatureServiceTemplate{f: f} - - if f != nil { - f.baseArcgisFeatureServiceMods.Apply(ctx, o) - } - - ArcgisFeatureServiceModSlice(mods).Apply(ctx, o) - - return o -} - -func (f *Factory) FromExistingArcgisFeatureService(m *models.ArcgisFeatureService) *ArcgisFeatureServiceTemplate { - o := &ArcgisFeatureServiceTemplate{f: f, alreadyPersisted: true} - - o.Extent = func() string { return m.Extent } - o.ItemID = func() string { return m.ItemID } - o.SpatialReference = func() int32 { return m.SpatialReference } - o.URL = func() string { return m.URL } - - ctx := context.Background() - if len(m.R.FeatureServiceItemLayers) > 0 { - ArcgisFeatureServiceMods.AddExistingFeatureServiceItemLayers(m.R.FeatureServiceItemLayers...).Apply(ctx, o) - } - - return o -} - func (f *Factory) NewArcgisLayer(mods ...ArcgisLayerMod) *ArcgisLayerTemplate { return f.NewArcgisLayerWithContext(context.Background(), mods...) } @@ -240,8 +264,8 @@ func (f *Factory) FromExistingArcgisLayer(m *models.ArcgisLayer) *ArcgisLayerTem o.Index = func() int32 { return m.Index } ctx := context.Background() - if m.R.FeatureServiceItemFeatureService != nil { - ArcgisLayerMods.WithExistingFeatureServiceItemFeatureService(m.R.FeatureServiceItemFeatureService).Apply(ctx, o) + if m.R.FeatureServiceItemServiceFeature != nil { + ArcgisLayerMods.WithExistingFeatureServiceItemServiceFeature(m.R.FeatureServiceItemServiceFeature).Apply(ctx, o) } if len(m.R.LayerFields) > 0 { ArcgisLayerMods.AddExistingLayerFields(m.R.LayerFields...).Apply(ctx, o) @@ -288,6 +312,49 @@ func (f *Factory) FromExistingArcgisLayerField(m *models.ArcgisLayerField) *Arcg return o } +func (f *Factory) NewArcgisOauthToken(mods ...ArcgisOauthTokenMod) *ArcgisOauthTokenTemplate { + return f.NewArcgisOauthTokenWithContext(context.Background(), mods...) +} + +func (f *Factory) NewArcgisOauthTokenWithContext(ctx context.Context, mods ...ArcgisOauthTokenMod) *ArcgisOauthTokenTemplate { + o := &ArcgisOauthTokenTemplate{f: f} + + if f != nil { + f.baseArcgisOauthTokenMods.Apply(ctx, o) + } + + ArcgisOauthTokenModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingArcgisOauthToken(m *models.ArcgisOauthToken) *ArcgisOauthTokenTemplate { + o := &ArcgisOauthTokenTemplate{f: f, alreadyPersisted: true} + + o.AccessToken = func() string { return m.AccessToken } + o.AccessTokenExpires = func() time.Time { return m.AccessTokenExpires } + o.ArcgisAccountID = func() null.Val[string] { return m.ArcgisAccountID } + o.ArcgisID = func() null.Val[string] { return m.ArcgisID } + o.ArcgisLicenseTypeID = func() null.Val[string] { return m.ArcgisLicenseTypeID } + o.Created = func() time.Time { return m.Created } + o.ID = func() int32 { return m.ID } + o.InvalidatedAt = func() null.Val[time.Time] { return m.InvalidatedAt } + o.RefreshToken = func() string { return m.RefreshToken } + o.RefreshTokenExpires = func() time.Time { return m.RefreshTokenExpires } + o.UserID = func() int32 { return m.UserID } + o.Username = func() string { return m.Username } + + ctx := context.Background() + if m.R.ArcgisAccountAccount != nil { + ArcgisOauthTokenMods.WithExistingArcgisAccountAccount(m.R.ArcgisAccountAccount).Apply(ctx, o) + } + if m.R.UserUser != nil { + ArcgisOauthTokenMods.WithExistingUserUser(m.R.UserUser).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewArcgisParcelMapping(mods ...ArcgisParcelMappingMod) *ArcgisParcelMappingTemplate { return f.NewArcgisParcelMappingWithContext(context.Background(), mods...) } @@ -324,6 +391,78 @@ func (f *Factory) FromExistingArcgisParcelMapping(m *models.ArcgisParcelMapping) return o } +func (f *Factory) NewArcgisServiceFeature(mods ...ArcgisServiceFeatureMod) *ArcgisServiceFeatureTemplate { + return f.NewArcgisServiceFeatureWithContext(context.Background(), mods...) +} + +func (f *Factory) NewArcgisServiceFeatureWithContext(ctx context.Context, mods ...ArcgisServiceFeatureMod) *ArcgisServiceFeatureTemplate { + o := &ArcgisServiceFeatureTemplate{f: f} + + if f != nil { + f.baseArcgisServiceFeatureMods.Apply(ctx, o) + } + + ArcgisServiceFeatureModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingArcgisServiceFeature(m *models.ArcgisServiceFeature) *ArcgisServiceFeatureTemplate { + o := &ArcgisServiceFeatureTemplate{f: f, alreadyPersisted: true} + + o.Extent = func() string { return m.Extent } + o.ItemID = func() string { return m.ItemID } + o.SpatialReference = func() int32 { return m.SpatialReference } + o.URL = func() string { return m.URL } + o.AccountID = func() null.Val[string] { return m.AccountID } + + ctx := context.Background() + if len(m.R.FeatureServiceItemLayers) > 0 { + ArcgisServiceFeatureMods.AddExistingFeatureServiceItemLayers(m.R.FeatureServiceItemLayers...).Apply(ctx, o) + } + if m.R.Account != nil { + ArcgisServiceFeatureMods.WithExistingAccount(m.R.Account).Apply(ctx, o) + } + if len(m.R.FieldseekerServiceFeatureItemOrganizations) > 0 { + ArcgisServiceFeatureMods.AddExistingFieldseekerServiceFeatureItemOrganizations(m.R.FieldseekerServiceFeatureItemOrganizations...).Apply(ctx, o) + } + + return o +} + +func (f *Factory) NewArcgisServiceMap(mods ...ArcgisServiceMapMod) *ArcgisServiceMapTemplate { + return f.NewArcgisServiceMapWithContext(context.Background(), mods...) +} + +func (f *Factory) NewArcgisServiceMapWithContext(ctx context.Context, mods ...ArcgisServiceMapMod) *ArcgisServiceMapTemplate { + o := &ArcgisServiceMapTemplate{f: f} + + if f != nil { + f.baseArcgisServiceMapMods.Apply(ctx, o) + } + + ArcgisServiceMapModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingArcgisServiceMap(m *models.ArcgisServiceMap) *ArcgisServiceMapTemplate { + o := &ArcgisServiceMapTemplate{f: f, alreadyPersisted: true} + + o.AccountID = func() string { return m.AccountID } + o.ArcgisID = func() string { return m.ArcgisID } + o.Name = func() string { return m.Name } + o.Title = func() string { return m.Title } + o.URL = func() string { return m.URL } + + ctx := context.Background() + if m.R.Account != nil { + ArcgisServiceMapMods.WithExistingAccount(m.R.Account).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewArcgisUser(mods ...ArcgisUserMod) *ArcgisUserTemplate { return f.NewArcgisUserWithContext(context.Background(), mods...) } @@ -521,6 +660,32 @@ func (f *Factory) FromExistingCommsEmailTemplate(m *models.CommsEmailTemplate) * return o } +func (f *Factory) NewCommsMailer(mods ...CommsMailerMod) *CommsMailerTemplate { + return f.NewCommsMailerWithContext(context.Background(), mods...) +} + +func (f *Factory) NewCommsMailerWithContext(ctx context.Context, mods ...CommsMailerMod) *CommsMailerTemplate { + o := &CommsMailerTemplate{f: f} + + if f != nil { + f.baseCommsMailerMods.Apply(ctx, o) + } + + CommsMailerModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingCommsMailer(m *models.CommsMailer) *CommsMailerTemplate { + o := &CommsMailerTemplate{f: f, alreadyPersisted: true} + + o.Created = func() time.Time { return m.Created } + o.ID = func() int32 { return m.ID } + o.Type = func() enums.CommsMailertype { return m.Type } + + return o +} + func (f *Factory) NewCommsPhone(mods ...CommsPhoneMod) *CommsPhoneTemplate { return f.NewCommsPhoneWithContext(context.Background(), mods...) } @@ -572,6 +737,9 @@ func (f *Factory) FromExistingCommsPhone(m *models.CommsPhone) *CommsPhoneTempla if len(m.R.PhoneE164SubscribePhones) > 0 { CommsPhoneMods.AddExistingPhoneE164SubscribePhones(m.R.PhoneE164SubscribePhones...).Apply(ctx, o) } + if len(m.R.PhoneMobileResidents) > 0 { + CommsPhoneMods.AddExistingPhoneMobileResidents(m.R.PhoneMobileResidents...).Apply(ctx, o) + } return o } @@ -652,6 +820,43 @@ func (f *Factory) FromExistingCommsTextLog(m *models.CommsTextLog) *CommsTextLog return o } +func (f *Factory) NewComplianceReportRequest(mods ...ComplianceReportRequestMod) *ComplianceReportRequestTemplate { + return f.NewComplianceReportRequestWithContext(context.Background(), mods...) +} + +func (f *Factory) NewComplianceReportRequestWithContext(ctx context.Context, mods ...ComplianceReportRequestMod) *ComplianceReportRequestTemplate { + o := &ComplianceReportRequestTemplate{f: f} + + if f != nil { + f.baseComplianceReportRequestMods.Apply(ctx, o) + } + + ComplianceReportRequestModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingComplianceReportRequest(m *models.ComplianceReportRequest) *ComplianceReportRequestTemplate { + o := &ComplianceReportRequestTemplate{f: f, alreadyPersisted: true} + + o.Created = func() time.Time { return m.Created } + o.Creator = func() int32 { return m.Creator } + o.ID = func() int32 { return m.ID } + o.PublicID = func() string { return m.PublicID } + o.SiteID = func() int32 { return m.SiteID } + o.SiteVersion = func() int32 { return m.SiteVersion } + + ctx := context.Background() + if m.R.CreatorUser != nil { + ComplianceReportRequestMods.WithExistingCreatorUser(m.R.CreatorUser).Apply(ctx, o) + } + if m.R.Site != nil { + ComplianceReportRequestMods.WithExistingSite(m.R.Site).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewDistrictSubscriptionEmail(mods ...DistrictSubscriptionEmailMod) *DistrictSubscriptionEmailTemplate { return f.NewDistrictSubscriptionEmailWithContext(context.Background(), mods...) } @@ -3070,45 +3275,6 @@ func (f *Factory) FromExistingNotification(m *models.Notification) *Notification return o } -func (f *Factory) NewOauthToken(mods ...OauthTokenMod) *OauthTokenTemplate { - return f.NewOauthTokenWithContext(context.Background(), mods...) -} - -func (f *Factory) NewOauthTokenWithContext(ctx context.Context, mods ...OauthTokenMod) *OauthTokenTemplate { - o := &OauthTokenTemplate{f: f} - - if f != nil { - f.baseOauthTokenMods.Apply(ctx, o) - } - - OauthTokenModSlice(mods).Apply(ctx, o) - - return o -} - -func (f *Factory) FromExistingOauthToken(m *models.OauthToken) *OauthTokenTemplate { - o := &OauthTokenTemplate{f: f, alreadyPersisted: true} - - o.ID = func() int32 { return m.ID } - o.AccessToken = func() string { return m.AccessToken } - o.AccessTokenExpires = func() time.Time { return m.AccessTokenExpires } - o.RefreshToken = func() string { return m.RefreshToken } - o.Username = func() string { return m.Username } - o.UserID = func() int32 { return m.UserID } - o.ArcgisID = func() null.Val[string] { return m.ArcgisID } - o.ArcgisLicenseTypeID = func() null.Val[string] { return m.ArcgisLicenseTypeID } - o.RefreshTokenExpires = func() time.Time { return m.RefreshTokenExpires } - o.InvalidatedAt = func() null.Val[time.Time] { return m.InvalidatedAt } - o.Created = func() time.Time { return m.Created } - - ctx := context.Background() - if m.R.UserUser != nil { - OauthTokenMods.WithExistingUserUser(m.R.UserUser).Apply(ctx, o) - } - - return o -} - func (f *Factory) NewOrganization(mods ...OrganizationMod) *OrganizationTemplate { return f.NewOrganizationWithContext(context.Background(), mods...) } @@ -3130,9 +3296,6 @@ func (f *Factory) FromExistingOrganization(m *models.Organization) *Organization o.ID = func() int32 { return m.ID } o.Name = func() string { return m.Name } - o.ArcgisID = func() null.Val[string] { return m.ArcgisID } - o.ArcgisName = func() null.Val[string] { return m.ArcgisName } - o.FieldseekerURL = func() null.Val[string] { return m.FieldseekerURL } o.ImportDistrictGid = func() null.Val[int32] { return m.ImportDistrictGid } o.Website = func() null.Val[string] { return m.Website } o.LogoUUID = func() null.Val[uuid.UUID] { return m.LogoUUID } @@ -3157,8 +3320,17 @@ func (f *Factory) FromExistingOrganization(m *models.Organization) *Organization o.ServiceAreaCentroidGeojson = func() null.Val[string] { return m.ServiceAreaCentroidGeojson } o.ServiceAreaCentroidX = func() null.Val[float64] { return m.ServiceAreaCentroidX } o.ServiceAreaCentroidY = func() null.Val[float64] { return m.ServiceAreaCentroidY } + o.MailingAddressCountry = func() null.Val[string] { return m.MailingAddressCountry } + o.MailingAddressState = func() null.Val[string] { return m.MailingAddressState } + o.OfficeAddressCountry = func() null.Val[string] { return m.OfficeAddressCountry } + o.OfficeAddressState = func() null.Val[string] { return m.OfficeAddressState } + o.ArcgisAccountID = func() null.Val[string] { return m.ArcgisAccountID } + o.FieldseekerServiceFeatureItemID = func() null.Val[string] { return m.FieldseekerServiceFeatureItemID } ctx := context.Background() + if len(m.R.Accounts) > 0 { + OrganizationMods.AddExistingAccounts(m.R.Accounts...).Apply(ctx, o) + } if len(m.R.AddressMappings) > 0 { OrganizationMods.AddExistingAddressMappings(m.R.AddressMappings...).Apply(ctx, o) } @@ -3270,6 +3442,12 @@ func (f *Factory) FromExistingOrganization(m *models.Organization) *Organization if len(m.R.NoteImages) > 0 { OrganizationMods.AddExistingNoteImages(m.R.NoteImages...).Apply(ctx, o) } + if m.R.ArcgisAccountAccount != nil { + OrganizationMods.WithExistingArcgisAccountAccount(m.R.ArcgisAccountAccount).Apply(ctx, o) + } + if m.R.FieldseekerServiceFeatureItemServiceFeature != nil { + OrganizationMods.WithExistingFieldseekerServiceFeatureItemServiceFeature(m.R.FieldseekerServiceFeatureItemServiceFeature).Apply(ctx, o) + } if len(m.R.Nuisances) > 0 { OrganizationMods.AddExistingNuisances(m.R.Nuisances...).Apply(ctx, o) } @@ -3305,11 +3483,16 @@ func (f *Factory) NewParcelWithContext(ctx context.Context, mods ...ParcelMod) * func (f *Factory) FromExistingParcel(m *models.Parcel) *ParcelTemplate { o := &ParcelTemplate{f: f, alreadyPersisted: true} - o.Apn = func() string { return m.Apn } - o.Description = func() string { return m.Description } + o.Apn = func() null.Val[string] { return m.Apn } + o.Description = func() null.Val[string] { return m.Description } o.ID = func() int32 { return m.ID } o.Geometry = func() string { return m.Geometry } + ctx := context.Background() + if len(m.R.Sites) > 0 { + ParcelMods.AddExistingSites(m.R.Sites...).Apply(ctx, o) + } + return o } @@ -3336,12 +3519,16 @@ func (f *Factory) FromExistingPool(m *models.Pool) *PoolTemplate { o.Created = func() time.Time { return m.Created } o.CreatorID = func() int32 { return m.CreatorID } o.ID = func() int32 { return m.ID } - o.SiteID = func() null.Val[int32] { return m.SiteID } + o.SiteID = func() int32 { return m.SiteID } + o.SiteVersion = func() int32 { return m.SiteVersion } ctx := context.Background() if m.R.CreatorUser != nil { PoolMods.WithExistingCreatorUser(m.R.CreatorUser).Apply(ctx, o) } + if m.R.Site != nil { + PoolMods.WithExistingSite(m.R.Site).Apply(ctx, o) + } return o } @@ -4013,6 +4200,51 @@ func (f *Factory) FromExistingRasterOverview(m *models.RasterOverview) *RasterOv return o } +func (f *Factory) NewResident(mods ...ResidentMod) *ResidentTemplate { + return f.NewResidentWithContext(context.Background(), mods...) +} + +func (f *Factory) NewResidentWithContext(ctx context.Context, mods ...ResidentMod) *ResidentTemplate { + o := &ResidentTemplate{f: f} + + if f != nil { + f.baseResidentMods.Apply(ctx, o) + } + + ResidentModSlice(mods).Apply(ctx, o) + + return o +} + +func (f *Factory) FromExistingResident(m *models.Resident) *ResidentTemplate { + o := &ResidentTemplate{f: f, alreadyPersisted: true} + + o.AddressID = func() int32 { return m.AddressID } + o.Created = func() time.Time { return m.Created } + o.Creator = func() int32 { return m.Creator } + o.ID = func() int32 { return m.ID } + o.Name = func() string { return m.Name } + o.PhoneMobile = func() null.Val[string] { return m.PhoneMobile } + o.SiteID = func() int32 { return m.SiteID } + o.SiteVersion = func() int32 { return m.SiteVersion } + + ctx := context.Background() + if m.R.Address != nil { + ResidentMods.WithExistingAddress(m.R.Address).Apply(ctx, o) + } + if m.R.CreatorUser != nil { + ResidentMods.WithExistingCreatorUser(m.R.CreatorUser).Apply(ctx, o) + } + if m.R.PhoneMobilePhone != nil { + ResidentMods.WithExistingPhoneMobilePhone(m.R.PhoneMobilePhone).Apply(ctx, o) + } + if m.R.Site != nil { + ResidentMods.WithExistingSite(m.R.Site).Apply(ctx, o) + } + + return o +} + func (f *Factory) NewSession(mods ...SessionMod) *SessionTemplate { return f.NewSessionWithContext(context.Background(), mods...) } @@ -4067,12 +4299,21 @@ func (f *Factory) FromExistingSite(m *models.Site) *SiteTemplate { o.OrganizationID = func() int32 { return m.OrganizationID } o.OwnerName = func() string { return m.OwnerName } o.OwnerPhoneE164 = func() null.Val[string] { return m.OwnerPhoneE164 } + o.ParcelID = func() int32 { return m.ParcelID } o.ResidentOwned = func() null.Val[bool] { return m.ResidentOwned } - o.ResidentPhoneE164 = func() null.Val[string] { return m.ResidentPhoneE164 } o.Tags = func() pgtypes.HStore { return m.Tags } o.Version = func() int32 { return m.Version } ctx := context.Background() + if len(m.R.ComplianceReportRequests) > 0 { + SiteMods.AddExistingComplianceReportRequests(m.R.ComplianceReportRequests...).Apply(ctx, o) + } + if len(m.R.Pools) > 0 { + SiteMods.AddExistingPools(m.R.Pools...).Apply(ctx, o) + } + if len(m.R.Residents) > 0 { + SiteMods.AddExistingResidents(m.R.Residents...).Apply(ctx, o) + } if m.R.Address != nil { SiteMods.WithExistingAddress(m.R.Address).Apply(ctx, o) } @@ -4082,6 +4323,9 @@ func (f *Factory) FromExistingSite(m *models.Site) *SiteTemplate { if m.R.File != nil { SiteMods.WithExistingFile(m.R.File).Apply(ctx, o) } + if m.R.Parcel != nil { + SiteMods.WithExistingParcel(m.R.Parcel).Apply(ctx, o) + } return o } @@ -4148,9 +4392,15 @@ func (f *Factory) FromExistingUser(m *models.User) *UserTemplate { o.Role = func() enums.Userrole { return m.Role } ctx := context.Background() + if len(m.R.UserOauthTokens) > 0 { + UserMods.AddExistingUserOauthTokens(m.R.UserOauthTokens...).Apply(ctx, o) + } if len(m.R.PublicUserUser) > 0 { UserMods.AddExistingPublicUserUser(m.R.PublicUserUser...).Apply(ctx, o) } + if len(m.R.CreatorComplianceReportRequests) > 0 { + UserMods.AddExistingCreatorComplianceReportRequests(m.R.CreatorComplianceReportRequests...).Apply(ctx, o) + } if len(m.R.CreatorFiles) > 0 { UserMods.AddExistingCreatorFiles(m.R.CreatorFiles...).Apply(ctx, o) } @@ -4172,12 +4422,12 @@ func (f *Factory) FromExistingUser(m *models.User) *UserTemplate { if len(m.R.UserNotifications) > 0 { UserMods.AddExistingUserNotifications(m.R.UserNotifications...).Apply(ctx, o) } - if len(m.R.UserOauthTokens) > 0 { - UserMods.AddExistingUserOauthTokens(m.R.UserOauthTokens...).Apply(ctx, o) - } if len(m.R.CreatorPools) > 0 { UserMods.AddExistingCreatorPools(m.R.CreatorPools...).Apply(ctx, o) } + if len(m.R.CreatorResidents) > 0 { + UserMods.AddExistingCreatorResidents(m.R.CreatorResidents...).Apply(ctx, o) + } if len(m.R.CreatorSites) > 0 { UserMods.AddExistingCreatorSites(m.R.CreatorSites...).Apply(ctx, o) } @@ -4196,6 +4446,14 @@ func (f *Factory) AddBaseAddressMod(mods ...AddressMod) { f.baseAddressMods = append(f.baseAddressMods, mods...) } +func (f *Factory) ClearBaseArcgisAccountMods() { + f.baseArcgisAccountMods = nil +} + +func (f *Factory) AddBaseArcgisAccountMod(mods ...ArcgisAccountMod) { + f.baseArcgisAccountMods = append(f.baseArcgisAccountMods, mods...) +} + func (f *Factory) ClearBaseArcgisAddressMappingMods() { f.baseArcgisAddressMappingMods = nil } @@ -4204,14 +4462,6 @@ func (f *Factory) AddBaseArcgisAddressMappingMod(mods ...ArcgisAddressMappingMod f.baseArcgisAddressMappingMods = append(f.baseArcgisAddressMappingMods, mods...) } -func (f *Factory) ClearBaseArcgisFeatureServiceMods() { - f.baseArcgisFeatureServiceMods = nil -} - -func (f *Factory) AddBaseArcgisFeatureServiceMod(mods ...ArcgisFeatureServiceMod) { - f.baseArcgisFeatureServiceMods = append(f.baseArcgisFeatureServiceMods, mods...) -} - func (f *Factory) ClearBaseArcgisLayerMods() { f.baseArcgisLayerMods = nil } @@ -4228,6 +4478,14 @@ func (f *Factory) AddBaseArcgisLayerFieldMod(mods ...ArcgisLayerFieldMod) { f.baseArcgisLayerFieldMods = append(f.baseArcgisLayerFieldMods, mods...) } +func (f *Factory) ClearBaseArcgisOauthTokenMods() { + f.baseArcgisOauthTokenMods = nil +} + +func (f *Factory) AddBaseArcgisOauthTokenMod(mods ...ArcgisOauthTokenMod) { + f.baseArcgisOauthTokenMods = append(f.baseArcgisOauthTokenMods, mods...) +} + func (f *Factory) ClearBaseArcgisParcelMappingMods() { f.baseArcgisParcelMappingMods = nil } @@ -4236,6 +4494,22 @@ func (f *Factory) AddBaseArcgisParcelMappingMod(mods ...ArcgisParcelMappingMod) f.baseArcgisParcelMappingMods = append(f.baseArcgisParcelMappingMods, mods...) } +func (f *Factory) ClearBaseArcgisServiceFeatureMods() { + f.baseArcgisServiceFeatureMods = nil +} + +func (f *Factory) AddBaseArcgisServiceFeatureMod(mods ...ArcgisServiceFeatureMod) { + f.baseArcgisServiceFeatureMods = append(f.baseArcgisServiceFeatureMods, mods...) +} + +func (f *Factory) ClearBaseArcgisServiceMapMods() { + f.baseArcgisServiceMapMods = nil +} + +func (f *Factory) AddBaseArcgisServiceMapMod(mods ...ArcgisServiceMapMod) { + f.baseArcgisServiceMapMods = append(f.baseArcgisServiceMapMods, mods...) +} + func (f *Factory) ClearBaseArcgisUserMods() { f.baseArcgisUserMods = nil } @@ -4276,6 +4550,14 @@ func (f *Factory) AddBaseCommsEmailTemplateMod(mods ...CommsEmailTemplateMod) { f.baseCommsEmailTemplateMods = append(f.baseCommsEmailTemplateMods, mods...) } +func (f *Factory) ClearBaseCommsMailerMods() { + f.baseCommsMailerMods = nil +} + +func (f *Factory) AddBaseCommsMailerMod(mods ...CommsMailerMod) { + f.baseCommsMailerMods = append(f.baseCommsMailerMods, mods...) +} + func (f *Factory) ClearBaseCommsPhoneMods() { f.baseCommsPhoneMods = nil } @@ -4300,6 +4582,14 @@ func (f *Factory) AddBaseCommsTextLogMod(mods ...CommsTextLogMod) { f.baseCommsTextLogMods = append(f.baseCommsTextLogMods, mods...) } +func (f *Factory) ClearBaseComplianceReportRequestMods() { + f.baseComplianceReportRequestMods = nil +} + +func (f *Factory) AddBaseComplianceReportRequestMod(mods ...ComplianceReportRequestMod) { + f.baseComplianceReportRequestMods = append(f.baseComplianceReportRequestMods, mods...) +} + func (f *Factory) ClearBaseDistrictSubscriptionEmailMods() { f.baseDistrictSubscriptionEmailMods = nil } @@ -4668,14 +4958,6 @@ func (f *Factory) AddBaseNotificationMod(mods ...NotificationMod) { f.baseNotificationMods = append(f.baseNotificationMods, mods...) } -func (f *Factory) ClearBaseOauthTokenMods() { - f.baseOauthTokenMods = nil -} - -func (f *Factory) AddBaseOauthTokenMod(mods ...OauthTokenMod) { - f.baseOauthTokenMods = append(f.baseOauthTokenMods, mods...) -} - func (f *Factory) ClearBaseOrganizationMods() { f.baseOrganizationMods = nil } @@ -4836,6 +5118,14 @@ func (f *Factory) AddBaseRasterOverviewMod(mods ...RasterOverviewMod) { f.baseRasterOverviewMods = append(f.baseRasterOverviewMods, mods...) } +func (f *Factory) ClearBaseResidentMods() { + f.baseResidentMods = nil +} + +func (f *Factory) AddBaseResidentMod(mods ...ResidentMod) { + f.baseResidentMods = append(f.baseResidentMods, mods...) +} + func (f *Factory) ClearBaseSessionMods() { f.baseSessionMods = nil } diff --git a/db/factory/bobfactory_random.bob.go b/db/factory/bobfactory_random.bob.go index 427dbbe6..2f6f2bdb 100644 --- a/db/factory/bobfactory_random.bob.go +++ b/db/factory/bobfactory_random.bob.go @@ -121,6 +121,16 @@ func random_enums_Audiodatatype(f *faker.Faker, limits ...string) enums.Audiodat return all[f.IntBetween(0, len(all)-1)] } +func random_enums_CommsMailertype(f *faker.Faker, limits ...string) enums.CommsMailertype { + if f == nil { + f = &defaultFaker + } + + var e enums.CommsMailertype + all := e.All() + return all[f.IntBetween(0, len(all)-1)] +} + func random_enums_CommsMessagetypeemail(f *faker.Faker, limits ...string) enums.CommsMessagetypeemail { if f == nil { f = &defaultFaker diff --git a/db/factory/comms.mailer.bob.go b/db/factory/comms.mailer.bob.go new file mode 100644 index 00000000..f5edc457 --- /dev/null +++ b/db/factory/comms.mailer.bob.go @@ -0,0 +1,341 @@ +// 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 factory + +import ( + "context" + "testing" + "time" + + "github.com/Gleipnir-Technology/bob" + enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/omit" + "github.com/jaswdr/faker/v2" +) + +type CommsMailerMod interface { + Apply(context.Context, *CommsMailerTemplate) +} + +type CommsMailerModFunc func(context.Context, *CommsMailerTemplate) + +func (f CommsMailerModFunc) Apply(ctx context.Context, n *CommsMailerTemplate) { + f(ctx, n) +} + +type CommsMailerModSlice []CommsMailerMod + +func (mods CommsMailerModSlice) Apply(ctx context.Context, n *CommsMailerTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// CommsMailerTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type CommsMailerTemplate struct { + Created func() time.Time + ID func() int32 + Type func() enums.CommsMailertype + + f *Factory + + alreadyPersisted bool +} + +// Apply mods to the CommsMailerTemplate +func (o *CommsMailerTemplate) Apply(ctx context.Context, mods ...CommsMailerMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.CommsMailer +// according to the relationships in the template. Nothing is inserted into the db +func (t CommsMailerTemplate) setModelRels(o *models.CommsMailer) {} + +// BuildSetter returns an *models.CommsMailerSetter +// this does nothing with the relationship templates +func (o CommsMailerTemplate) BuildSetter() *models.CommsMailerSetter { + m := &models.CommsMailerSetter{} + + if o.Created != nil { + val := o.Created() + m.Created = omit.From(val) + } + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.Type != nil { + val := o.Type() + m.Type = omit.From(val) + } + + return m +} + +// BuildManySetter returns an []*models.CommsMailerSetter +// this does nothing with the relationship templates +func (o CommsMailerTemplate) BuildManySetter(number int) []*models.CommsMailerSetter { + m := make([]*models.CommsMailerSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.CommsMailer +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use CommsMailerTemplate.Create +func (o CommsMailerTemplate) Build() *models.CommsMailer { + m := &models.CommsMailer{} + + if o.Created != nil { + m.Created = o.Created() + } + if o.ID != nil { + m.ID = o.ID() + } + if o.Type != nil { + m.Type = o.Type() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.CommsMailerSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use CommsMailerTemplate.CreateMany +func (o CommsMailerTemplate) BuildMany(number int) models.CommsMailerSlice { + m := make(models.CommsMailerSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableCommsMailer(m *models.CommsMailerSetter) { + if !(m.Created.IsValue()) { + val := random_time_Time(nil) + m.Created = omit.From(val) + } + if !(m.Type.IsValue()) { + val := random_enums_CommsMailertype(nil) + m.Type = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.CommsMailer +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *CommsMailerTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.CommsMailer) error { + var err error + + return err +} + +// Create builds a commsMailer and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *CommsMailerTemplate) Create(ctx context.Context, exec bob.Executor) (*models.CommsMailer, error) { + var err error + opt := o.BuildSetter() + ensureCreatableCommsMailer(opt) + + m, err := models.CommsMailers.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a commsMailer and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *CommsMailerTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.CommsMailer { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a commsMailer and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *CommsMailerTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.CommsMailer { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple commsMailers and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o CommsMailerTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.CommsMailerSlice, error) { + var err error + m := make(models.CommsMailerSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple commsMailers and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o CommsMailerTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.CommsMailerSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple commsMailers and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o CommsMailerTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.CommsMailerSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CommsMailer has methods that act as mods for the CommsMailerTemplate +var CommsMailerMods commsMailerMods + +type commsMailerMods struct{} + +func (m commsMailerMods) RandomizeAllColumns(f *faker.Faker) CommsMailerMod { + return CommsMailerModSlice{ + CommsMailerMods.RandomCreated(f), + CommsMailerMods.RandomID(f), + CommsMailerMods.RandomType(f), + } +} + +// Set the model columns to this value +func (m commsMailerMods) Created(val time.Time) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Created = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m commsMailerMods) CreatedFunc(f func() time.Time) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Created = f + }) +} + +// Clear any values for the column +func (m commsMailerMods) UnsetCreated() CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Created = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m commsMailerMods) RandomCreated(f *faker.Faker) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Created = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m commsMailerMods) ID(val int32) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.ID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m commsMailerMods) IDFunc(f func() int32) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m commsMailerMods) UnsetID() CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m commsMailerMods) RandomID(f *faker.Faker) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.ID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m commsMailerMods) Type(val enums.CommsMailertype) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Type = func() enums.CommsMailertype { return val } + }) +} + +// Set the Column from the function +func (m commsMailerMods) TypeFunc(f func() enums.CommsMailertype) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Type = f + }) +} + +// Clear any values for the column +func (m commsMailerMods) UnsetType() CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Type = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m commsMailerMods) RandomType(f *faker.Faker) CommsMailerMod { + return CommsMailerModFunc(func(_ context.Context, o *CommsMailerTemplate) { + o.Type = func() enums.CommsMailertype { + return random_enums_CommsMailertype(f) + } + }) +} + +func (m commsMailerMods) WithParentsCascading() CommsMailerMod { + return CommsMailerModFunc(func(ctx context.Context, o *CommsMailerTemplate) { + if isDone, _ := commsMailerWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = commsMailerWithParentsCascadingCtx.WithValue(ctx, true) + }) +} diff --git a/db/factory/comms.phone.bob.go b/db/factory/comms.phone.bob.go index b2d5ff6e..5250ce18 100644 --- a/db/factory/comms.phone.bob.go +++ b/db/factory/comms.phone.bob.go @@ -56,6 +56,7 @@ type commsPhoneR struct { PhoneE164NotifyPhoneNuisances []*commsPhoneRPhoneE164NotifyPhoneNuisancesR PhoneE164NotifyPhonePools []*commsPhoneRPhoneE164NotifyPhonePoolsR PhoneE164SubscribePhones []*commsPhoneRPhoneE164SubscribePhonesR + PhoneMobileResidents []*commsPhoneRPhoneMobileResidentsR } type commsPhoneRDestinationTextJobsR struct { @@ -94,6 +95,10 @@ type commsPhoneRPhoneE164SubscribePhonesR struct { number int o *PublicreportSubscribePhoneTemplate } +type commsPhoneRPhoneMobileResidentsR struct { + number int + o *ResidentTemplate +} // Apply mods to the CommsPhoneTemplate func (o *CommsPhoneTemplate) Apply(ctx context.Context, mods ...CommsPhoneMod) { @@ -220,6 +225,19 @@ func (t CommsPhoneTemplate) setModelRels(o *models.CommsPhone) { } o.R.PhoneE164SubscribePhones = rel } + + if t.r.PhoneMobileResidents != nil { + rel := models.ResidentSlice{} + for _, r := range t.r.PhoneMobileResidents { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.PhoneMobile = null.From(o.E164) // h2 + rel.R.PhoneMobilePhone = o + } + rel = append(rel, related...) + } + o.R.PhoneMobileResidents = rel + } } // BuildSetter returns an *models.CommsPhoneSetter @@ -490,6 +508,26 @@ func (o *CommsPhoneTemplate) insertOptRels(ctx context.Context, exec bob.Executo } } + isPhoneMobileResidentsDone, _ := commsPhoneRelPhoneMobileResidentsCtx.Value(ctx) + if !isPhoneMobileResidentsDone && o.r.PhoneMobileResidents != nil { + ctx = commsPhoneRelPhoneMobileResidentsCtx.WithValue(ctx, true) + for _, r := range o.r.PhoneMobileResidents { + if r.o.alreadyPersisted { + m.R.PhoneMobileResidents = append(m.R.PhoneMobileResidents, r.o.Build()) + } else { + rel9, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachPhoneMobileResidents(ctx, exec, rel9...) + if err != nil { + return err + } + } + } + } + return err } @@ -1121,3 +1159,51 @@ func (m commsPhoneMods) WithoutPhoneE164SubscribePhones() CommsPhoneMod { o.r.PhoneE164SubscribePhones = nil }) } + +func (m commsPhoneMods) WithPhoneMobileResidents(number int, related *ResidentTemplate) CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + o.r.PhoneMobileResidents = []*commsPhoneRPhoneMobileResidentsR{{ + number: number, + o: related, + }} + }) +} + +func (m commsPhoneMods) WithNewPhoneMobileResidents(number int, mods ...ResidentMod) CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.WithPhoneMobileResidents(number, related).Apply(ctx, o) + }) +} + +func (m commsPhoneMods) AddPhoneMobileResidents(number int, related *ResidentTemplate) CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + o.r.PhoneMobileResidents = append(o.r.PhoneMobileResidents, &commsPhoneRPhoneMobileResidentsR{ + number: number, + o: related, + }) + }) +} + +func (m commsPhoneMods) AddNewPhoneMobileResidents(number int, mods ...ResidentMod) CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.AddPhoneMobileResidents(number, related).Apply(ctx, o) + }) +} + +func (m commsPhoneMods) AddExistingPhoneMobileResidents(existingModels ...*models.Resident) CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + for _, em := range existingModels { + o.r.PhoneMobileResidents = append(o.r.PhoneMobileResidents, &commsPhoneRPhoneMobileResidentsR{ + o: o.f.FromExistingResident(em), + }) + } + }) +} + +func (m commsPhoneMods) WithoutPhoneMobileResidents() CommsPhoneMod { + return CommsPhoneModFunc(func(ctx context.Context, o *CommsPhoneTemplate) { + o.r.PhoneMobileResidents = nil + }) +} diff --git a/db/factory/compliance_report_request.bob.go b/db/factory/compliance_report_request.bob.go new file mode 100644 index 00000000..a5ff35e6 --- /dev/null +++ b/db/factory/compliance_report_request.bob.go @@ -0,0 +1,608 @@ +// 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 factory + +import ( + "context" + "testing" + "time" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/omit" + "github.com/jaswdr/faker/v2" +) + +type ComplianceReportRequestMod interface { + Apply(context.Context, *ComplianceReportRequestTemplate) +} + +type ComplianceReportRequestModFunc func(context.Context, *ComplianceReportRequestTemplate) + +func (f ComplianceReportRequestModFunc) Apply(ctx context.Context, n *ComplianceReportRequestTemplate) { + f(ctx, n) +} + +type ComplianceReportRequestModSlice []ComplianceReportRequestMod + +func (mods ComplianceReportRequestModSlice) Apply(ctx context.Context, n *ComplianceReportRequestTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ComplianceReportRequestTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ComplianceReportRequestTemplate struct { + Created func() time.Time + Creator func() int32 + ID func() int32 + PublicID func() string + SiteID func() int32 + SiteVersion func() int32 + + r complianceReportRequestR + f *Factory + + alreadyPersisted bool +} + +type complianceReportRequestR struct { + CreatorUser *complianceReportRequestRCreatorUserR + Site *complianceReportRequestRSiteR +} + +type complianceReportRequestRCreatorUserR struct { + o *UserTemplate +} +type complianceReportRequestRSiteR struct { + o *SiteTemplate +} + +// Apply mods to the ComplianceReportRequestTemplate +func (o *ComplianceReportRequestTemplate) Apply(ctx context.Context, mods ...ComplianceReportRequestMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.ComplianceReportRequest +// according to the relationships in the template. Nothing is inserted into the db +func (t ComplianceReportRequestTemplate) setModelRels(o *models.ComplianceReportRequest) { + if t.r.CreatorUser != nil { + rel := t.r.CreatorUser.o.Build() + rel.R.CreatorComplianceReportRequests = append(rel.R.CreatorComplianceReportRequests, o) + o.Creator = rel.ID // h2 + o.R.CreatorUser = rel + } + + if t.r.Site != nil { + rel := t.r.Site.o.Build() + rel.R.ComplianceReportRequests = append(rel.R.ComplianceReportRequests, o) + o.SiteID = rel.ID // h2 + o.SiteVersion = rel.Version // h2 + o.R.Site = rel + } +} + +// BuildSetter returns an *models.ComplianceReportRequestSetter +// this does nothing with the relationship templates +func (o ComplianceReportRequestTemplate) BuildSetter() *models.ComplianceReportRequestSetter { + m := &models.ComplianceReportRequestSetter{} + + if o.Created != nil { + val := o.Created() + m.Created = omit.From(val) + } + if o.Creator != nil { + val := o.Creator() + m.Creator = omit.From(val) + } + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.PublicID != nil { + val := o.PublicID() + m.PublicID = omit.From(val) + } + if o.SiteID != nil { + val := o.SiteID() + m.SiteID = omit.From(val) + } + if o.SiteVersion != nil { + val := o.SiteVersion() + m.SiteVersion = omit.From(val) + } + + return m +} + +// BuildManySetter returns an []*models.ComplianceReportRequestSetter +// this does nothing with the relationship templates +func (o ComplianceReportRequestTemplate) BuildManySetter(number int) []*models.ComplianceReportRequestSetter { + m := make([]*models.ComplianceReportRequestSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.ComplianceReportRequest +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ComplianceReportRequestTemplate.Create +func (o ComplianceReportRequestTemplate) Build() *models.ComplianceReportRequest { + m := &models.ComplianceReportRequest{} + + if o.Created != nil { + m.Created = o.Created() + } + if o.Creator != nil { + m.Creator = o.Creator() + } + if o.ID != nil { + m.ID = o.ID() + } + if o.PublicID != nil { + m.PublicID = o.PublicID() + } + if o.SiteID != nil { + m.SiteID = o.SiteID() + } + if o.SiteVersion != nil { + m.SiteVersion = o.SiteVersion() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ComplianceReportRequestSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ComplianceReportRequestTemplate.CreateMany +func (o ComplianceReportRequestTemplate) BuildMany(number int) models.ComplianceReportRequestSlice { + m := make(models.ComplianceReportRequestSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableComplianceReportRequest(m *models.ComplianceReportRequestSetter) { + if !(m.Created.IsValue()) { + val := random_time_Time(nil) + m.Created = omit.From(val) + } + if !(m.Creator.IsValue()) { + val := random_int32(nil) + m.Creator = omit.From(val) + } + if !(m.PublicID.IsValue()) { + val := random_string(nil) + m.PublicID = omit.From(val) + } + if !(m.SiteID.IsValue()) { + val := random_int32(nil) + m.SiteID = omit.From(val) + } + if !(m.SiteVersion.IsValue()) { + val := random_int32(nil) + m.SiteVersion = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.ComplianceReportRequest +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ComplianceReportRequestTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.ComplianceReportRequest) error { + var err error + + return err +} + +// Create builds a complianceReportRequest and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ComplianceReportRequestTemplate) Create(ctx context.Context, exec bob.Executor) (*models.ComplianceReportRequest, error) { + var err error + opt := o.BuildSetter() + ensureCreatableComplianceReportRequest(opt) + + if o.r.CreatorUser == nil { + ComplianceReportRequestMods.WithNewCreatorUser().Apply(ctx, o) + } + + var rel0 *models.User + + if o.r.CreatorUser.o.alreadyPersisted { + rel0 = o.r.CreatorUser.o.Build() + } else { + rel0, err = o.r.CreatorUser.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.Creator = omit.From(rel0.ID) + + if o.r.Site == nil { + ComplianceReportRequestMods.WithNewSite().Apply(ctx, o) + } + + var rel1 *models.Site + + if o.r.Site.o.alreadyPersisted { + rel1 = o.r.Site.o.Build() + } else { + rel1, err = o.r.Site.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.SiteID = omit.From(rel1.ID) + opt.SiteVersion = omit.From(rel1.Version) + + m, err := models.ComplianceReportRequests.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + m.R.CreatorUser = rel0 + m.R.Site = rel1 + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a complianceReportRequest and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ComplianceReportRequestTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.ComplianceReportRequest { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a complianceReportRequest and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ComplianceReportRequestTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.ComplianceReportRequest { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple complianceReportRequests and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ComplianceReportRequestTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ComplianceReportRequestSlice, error) { + var err error + m := make(models.ComplianceReportRequestSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple complianceReportRequests and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ComplianceReportRequestTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ComplianceReportRequestSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple complianceReportRequests and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ComplianceReportRequestTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ComplianceReportRequestSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// ComplianceReportRequest has methods that act as mods for the ComplianceReportRequestTemplate +var ComplianceReportRequestMods complianceReportRequestMods + +type complianceReportRequestMods struct{} + +func (m complianceReportRequestMods) RandomizeAllColumns(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModSlice{ + ComplianceReportRequestMods.RandomCreated(f), + ComplianceReportRequestMods.RandomCreator(f), + ComplianceReportRequestMods.RandomID(f), + ComplianceReportRequestMods.RandomPublicID(f), + ComplianceReportRequestMods.RandomSiteID(f), + ComplianceReportRequestMods.RandomSiteVersion(f), + } +} + +// Set the model columns to this value +func (m complianceReportRequestMods) Created(val time.Time) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Created = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) CreatedFunc(f func() time.Time) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Created = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetCreated() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Created = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomCreated(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Created = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m complianceReportRequestMods) Creator(val int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Creator = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) CreatorFunc(f func() int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Creator = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetCreator() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Creator = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomCreator(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.Creator = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m complianceReportRequestMods) ID(val int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.ID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) IDFunc(f func() int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetID() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomID(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.ID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m complianceReportRequestMods) PublicID(val string) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.PublicID = func() string { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) PublicIDFunc(f func() string) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.PublicID = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetPublicID() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.PublicID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomPublicID(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.PublicID = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m complianceReportRequestMods) SiteID(val int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) SiteIDFunc(f func() int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteID = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetSiteID() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomSiteID(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m complianceReportRequestMods) SiteVersion(val int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteVersion = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m complianceReportRequestMods) SiteVersionFunc(f func() int32) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteVersion = f + }) +} + +// Clear any values for the column +func (m complianceReportRequestMods) UnsetSiteVersion() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteVersion = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m complianceReportRequestMods) RandomSiteVersion(f *faker.Faker) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(_ context.Context, o *ComplianceReportRequestTemplate) { + o.SiteVersion = func() int32 { + return random_int32(f) + } + }) +} + +func (m complianceReportRequestMods) WithParentsCascading() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + if isDone, _ := complianceReportRequestWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = complianceReportRequestWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewUserWithContext(ctx, UserMods.WithParentsCascading()) + m.WithCreatorUser(related).Apply(ctx, o) + } + { + + related := o.f.NewSiteWithContext(ctx, SiteMods.WithParentsCascading()) + m.WithSite(related).Apply(ctx, o) + } + }) +} + +func (m complianceReportRequestMods) WithCreatorUser(rel *UserTemplate) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.CreatorUser = &complianceReportRequestRCreatorUserR{ + o: rel, + } + }) +} + +func (m complianceReportRequestMods) WithNewCreatorUser(mods ...UserMod) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + related := o.f.NewUserWithContext(ctx, mods...) + + m.WithCreatorUser(related).Apply(ctx, o) + }) +} + +func (m complianceReportRequestMods) WithExistingCreatorUser(em *models.User) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.CreatorUser = &complianceReportRequestRCreatorUserR{ + o: o.f.FromExistingUser(em), + } + }) +} + +func (m complianceReportRequestMods) WithoutCreatorUser() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.CreatorUser = nil + }) +} + +func (m complianceReportRequestMods) WithSite(rel *SiteTemplate) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.Site = &complianceReportRequestRSiteR{ + o: rel, + } + }) +} + +func (m complianceReportRequestMods) WithNewSite(mods ...SiteMod) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + related := o.f.NewSiteWithContext(ctx, mods...) + + m.WithSite(related).Apply(ctx, o) + }) +} + +func (m complianceReportRequestMods) WithExistingSite(em *models.Site) ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.Site = &complianceReportRequestRSiteR{ + o: o.f.FromExistingSite(em), + } + }) +} + +func (m complianceReportRequestMods) WithoutSite() ComplianceReportRequestMod { + return ComplianceReportRequestModFunc(func(ctx context.Context, o *ComplianceReportRequestTemplate) { + o.r.Site = nil + }) +} diff --git a/db/factory/organization.bob.go b/db/factory/organization.bob.go index 2e40bcda..e92fc48f 100644 --- a/db/factory/organization.bob.go +++ b/db/factory/organization.bob.go @@ -38,35 +38,38 @@ func (mods OrganizationModSlice) Apply(ctx context.Context, n *OrganizationTempl // OrganizationTemplate is an object representing the database table. // all columns are optional and should be set by mods type OrganizationTemplate struct { - ID func() int32 - Name func() string - ArcgisID func() null.Val[string] - ArcgisName func() null.Val[string] - FieldseekerURL func() null.Val[string] - ImportDistrictGid func() null.Val[int32] - Website func() null.Val[string] - LogoUUID func() null.Val[uuid.UUID] - Slug func() null.Val[string] - GeneralManagerName func() null.Val[string] - MailingAddressCity func() null.Val[string] - MailingAddressPostalCode func() null.Val[string] - MailingAddressStreet func() null.Val[string] - OfficeAddressCity func() null.Val[string] - OfficeAddressPostalCode func() null.Val[string] - OfficeAddressStreet func() null.Val[string] - ServiceAreaGeometry func() null.Val[string] - ServiceAreaSquareMeters func() null.Val[decimal.Decimal] - ServiceAreaCentroid func() null.Val[string] - ServiceAreaExtent func() null.Val[string] - OfficeFax func() null.Val[string] - OfficePhone func() null.Val[string] - ServiceAreaXmin func() null.Val[float64] - ServiceAreaYmin func() null.Val[float64] - ServiceAreaXmax func() null.Val[float64] - ServiceAreaYmax func() null.Val[float64] - ServiceAreaCentroidGeojson func() null.Val[string] - ServiceAreaCentroidX func() null.Val[float64] - ServiceAreaCentroidY func() null.Val[float64] + ID func() int32 + Name func() string + ImportDistrictGid func() null.Val[int32] + Website func() null.Val[string] + LogoUUID func() null.Val[uuid.UUID] + Slug func() null.Val[string] + GeneralManagerName func() null.Val[string] + MailingAddressCity func() null.Val[string] + MailingAddressPostalCode func() null.Val[string] + MailingAddressStreet func() null.Val[string] + OfficeAddressCity func() null.Val[string] + OfficeAddressPostalCode func() null.Val[string] + OfficeAddressStreet func() null.Val[string] + ServiceAreaGeometry func() null.Val[string] + ServiceAreaSquareMeters func() null.Val[decimal.Decimal] + ServiceAreaCentroid func() null.Val[string] + ServiceAreaExtent func() null.Val[string] + OfficeFax func() null.Val[string] + OfficePhone func() null.Val[string] + ServiceAreaXmin func() null.Val[float64] + ServiceAreaYmin func() null.Val[float64] + ServiceAreaXmax func() null.Val[float64] + ServiceAreaYmax func() null.Val[float64] + ServiceAreaCentroidGeojson func() null.Val[string] + ServiceAreaCentroidX func() null.Val[float64] + ServiceAreaCentroidY func() null.Val[float64] + MailingAddressCountry func() null.Val[string] + MailingAddressState func() null.Val[string] + OfficeAddressCountry func() null.Val[string] + OfficeAddressState func() null.Val[string] + ArcgisAccountID func() null.Val[string] + FieldseekerServiceFeatureItemID func() null.Val[string] r organizationR f *Factory @@ -75,49 +78,56 @@ type OrganizationTemplate struct { } type organizationR struct { - AddressMappings []*organizationRAddressMappingsR - ParcelMappings []*organizationRParcelMappingsR - EmailContacts []*organizationREmailContactsR - Phones []*organizationRPhonesR - Containerrelates []*organizationRContainerrelatesR - Fieldscoutinglogs []*organizationRFieldscoutinglogsR - Habitatrelates []*organizationRHabitatrelatesR - Inspectionsamples []*organizationRInspectionsamplesR - Inspectionsampledetails []*organizationRInspectionsampledetailsR - Linelocations []*organizationRLinelocationsR - Locationtrackings []*organizationRLocationtrackingsR - Mosquitoinspections []*organizationRMosquitoinspectionsR - Pointlocations []*organizationRPointlocationsR - Polygonlocations []*organizationRPolygonlocationsR - FieldseekerPool []*organizationRFieldseekerPoolR - Pooldetails []*organizationRPooldetailsR - Proposedtreatmentareas []*organizationRProposedtreatmentareasR - Qamosquitoinspections []*organizationRQamosquitoinspectionsR - Rodentlocations []*organizationRRodentlocationsR - Samplecollections []*organizationRSamplecollectionsR - Samplelocations []*organizationRSamplelocationsR - Servicerequests []*organizationRServicerequestsR - Speciesabundances []*organizationRSpeciesabundancesR - Stormdrains []*organizationRStormdrainsR - Timecards []*organizationRTimecardsR - Trapdata []*organizationRTrapdataR - Traplocations []*organizationRTraplocationsR - Treatments []*organizationRTreatmentsR - Treatmentareas []*organizationRTreatmentareasR - Zones []*organizationRZonesR - Zones2s []*organizationRZones2sR - FieldseekerSyncs []*organizationRFieldseekerSyncsR - Files []*organizationRFilesR - Pools []*organizationRPoolsR - H3Aggregations []*organizationRH3AggregationsR - NoteAudios []*organizationRNoteAudiosR - NoteImages []*organizationRNoteImagesR - Nuisances []*organizationRNuisancesR - PublicreportPool []*organizationRPublicreportPoolR - Quicks []*organizationRQuicksR - User []*organizationRUserR + Accounts []*organizationRAccountsR + AddressMappings []*organizationRAddressMappingsR + ParcelMappings []*organizationRParcelMappingsR + EmailContacts []*organizationREmailContactsR + Phones []*organizationRPhonesR + Containerrelates []*organizationRContainerrelatesR + Fieldscoutinglogs []*organizationRFieldscoutinglogsR + Habitatrelates []*organizationRHabitatrelatesR + Inspectionsamples []*organizationRInspectionsamplesR + Inspectionsampledetails []*organizationRInspectionsampledetailsR + Linelocations []*organizationRLinelocationsR + Locationtrackings []*organizationRLocationtrackingsR + Mosquitoinspections []*organizationRMosquitoinspectionsR + Pointlocations []*organizationRPointlocationsR + Polygonlocations []*organizationRPolygonlocationsR + FieldseekerPool []*organizationRFieldseekerPoolR + Pooldetails []*organizationRPooldetailsR + Proposedtreatmentareas []*organizationRProposedtreatmentareasR + Qamosquitoinspections []*organizationRQamosquitoinspectionsR + Rodentlocations []*organizationRRodentlocationsR + Samplecollections []*organizationRSamplecollectionsR + Samplelocations []*organizationRSamplelocationsR + Servicerequests []*organizationRServicerequestsR + Speciesabundances []*organizationRSpeciesabundancesR + Stormdrains []*organizationRStormdrainsR + Timecards []*organizationRTimecardsR + Trapdata []*organizationRTrapdataR + Traplocations []*organizationRTraplocationsR + Treatments []*organizationRTreatmentsR + Treatmentareas []*organizationRTreatmentareasR + Zones []*organizationRZonesR + Zones2s []*organizationRZones2sR + FieldseekerSyncs []*organizationRFieldseekerSyncsR + Files []*organizationRFilesR + Pools []*organizationRPoolsR + H3Aggregations []*organizationRH3AggregationsR + NoteAudios []*organizationRNoteAudiosR + NoteImages []*organizationRNoteImagesR + ArcgisAccountAccount *organizationRArcgisAccountAccountR + FieldseekerServiceFeatureItemServiceFeature *organizationRFieldseekerServiceFeatureItemServiceFeatureR + Nuisances []*organizationRNuisancesR + PublicreportPool []*organizationRPublicreportPoolR + Quicks []*organizationRQuicksR + User []*organizationRUserR } +type organizationRAccountsR struct { + number int + o *ArcgisAccountTemplate +} type organizationRAddressMappingsR struct { number int o *ArcgisAddressMappingTemplate @@ -266,6 +276,12 @@ type organizationRNoteImagesR struct { number int o *NoteImageTemplate } +type organizationRArcgisAccountAccountR struct { + o *ArcgisAccountTemplate +} +type organizationRFieldseekerServiceFeatureItemServiceFeatureR struct { + o *ArcgisServiceFeatureTemplate +} type organizationRNuisancesR struct { number int o *PublicreportNuisanceTemplate @@ -293,6 +309,19 @@ func (o *OrganizationTemplate) Apply(ctx context.Context, mods ...OrganizationMo // setModelRels creates and sets the relationships on *models.Organization // according to the relationships in the template. Nothing is inserted into the db func (t OrganizationTemplate) setModelRels(o *models.Organization) { + if t.r.Accounts != nil { + rel := models.ArcgisAccountSlice{} + for _, r := range t.r.Accounts { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.OrganizationID = o.ID // h2 + rel.R.Organization = o + } + rel = append(rel, related...) + } + o.R.Accounts = rel + } + if t.r.AddressMappings != nil { rel := models.ArcgisAddressMappingSlice{} for _, r := range t.r.AddressMappings { @@ -772,6 +801,20 @@ func (t OrganizationTemplate) setModelRels(o *models.Organization) { o.R.NoteImages = rel } + if t.r.ArcgisAccountAccount != nil { + rel := t.r.ArcgisAccountAccount.o.Build() + rel.R.ArcgisAccountOrganizations = append(rel.R.ArcgisAccountOrganizations, o) + o.ArcgisAccountID = null.From(rel.ID) // h2 + o.R.ArcgisAccountAccount = rel + } + + if t.r.FieldseekerServiceFeatureItemServiceFeature != nil { + rel := t.r.FieldseekerServiceFeatureItemServiceFeature.o.Build() + rel.R.FieldseekerServiceFeatureItemOrganizations = append(rel.R.FieldseekerServiceFeatureItemOrganizations, o) + o.FieldseekerServiceFeatureItemID = null.From(rel.ItemID) // h2 + o.R.FieldseekerServiceFeatureItemServiceFeature = rel + } + if t.r.Nuisances != nil { rel := models.PublicreportNuisanceSlice{} for _, r := range t.r.Nuisances { @@ -838,18 +881,6 @@ func (o OrganizationTemplate) BuildSetter() *models.OrganizationSetter { val := o.Name() m.Name = omit.From(val) } - if o.ArcgisID != nil { - val := o.ArcgisID() - m.ArcgisID = omitnull.FromNull(val) - } - if o.ArcgisName != nil { - val := o.ArcgisName() - m.ArcgisName = omitnull.FromNull(val) - } - if o.FieldseekerURL != nil { - val := o.FieldseekerURL() - m.FieldseekerURL = omitnull.FromNull(val) - } if o.ImportDistrictGid != nil { val := o.ImportDistrictGid() m.ImportDistrictGid = omitnull.FromNull(val) @@ -906,6 +937,30 @@ func (o OrganizationTemplate) BuildSetter() *models.OrganizationSetter { val := o.OfficePhone() m.OfficePhone = omitnull.FromNull(val) } + if o.MailingAddressCountry != nil { + val := o.MailingAddressCountry() + m.MailingAddressCountry = omitnull.FromNull(val) + } + if o.MailingAddressState != nil { + val := o.MailingAddressState() + m.MailingAddressState = omitnull.FromNull(val) + } + if o.OfficeAddressCountry != nil { + val := o.OfficeAddressCountry() + m.OfficeAddressCountry = omitnull.FromNull(val) + } + if o.OfficeAddressState != nil { + val := o.OfficeAddressState() + m.OfficeAddressState = omitnull.FromNull(val) + } + if o.ArcgisAccountID != nil { + val := o.ArcgisAccountID() + m.ArcgisAccountID = omitnull.FromNull(val) + } + if o.FieldseekerServiceFeatureItemID != nil { + val := o.FieldseekerServiceFeatureItemID() + m.FieldseekerServiceFeatureItemID = omitnull.FromNull(val) + } return m } @@ -934,15 +989,6 @@ func (o OrganizationTemplate) Build() *models.Organization { if o.Name != nil { m.Name = o.Name() } - if o.ArcgisID != nil { - m.ArcgisID = o.ArcgisID() - } - if o.ArcgisName != nil { - m.ArcgisName = o.ArcgisName() - } - if o.FieldseekerURL != nil { - m.FieldseekerURL = o.FieldseekerURL() - } if o.ImportDistrictGid != nil { m.ImportDistrictGid = o.ImportDistrictGid() } @@ -1015,6 +1061,24 @@ func (o OrganizationTemplate) Build() *models.Organization { if o.ServiceAreaCentroidY != nil { m.ServiceAreaCentroidY = o.ServiceAreaCentroidY() } + if o.MailingAddressCountry != nil { + m.MailingAddressCountry = o.MailingAddressCountry() + } + if o.MailingAddressState != nil { + m.MailingAddressState = o.MailingAddressState() + } + if o.OfficeAddressCountry != nil { + m.OfficeAddressCountry = o.OfficeAddressCountry() + } + if o.OfficeAddressState != nil { + m.OfficeAddressState = o.OfficeAddressState() + } + if o.ArcgisAccountID != nil { + m.ArcgisAccountID = o.ArcgisAccountID() + } + if o.FieldseekerServiceFeatureItemID != nil { + m.FieldseekerServiceFeatureItemID = o.FieldseekerServiceFeatureItemID() + } o.setModelRels(m) @@ -1047,6 +1111,26 @@ func ensureCreatableOrganization(m *models.OrganizationSetter) { func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Organization) error { var err error + isAccountsDone, _ := organizationRelAccountsCtx.Value(ctx) + if !isAccountsDone && o.r.Accounts != nil { + ctx = organizationRelAccountsCtx.WithValue(ctx, true) + for _, r := range o.r.Accounts { + if r.o.alreadyPersisted { + m.R.Accounts = append(m.R.Accounts, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachAccounts(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + isAddressMappingsDone, _ := organizationRelAddressMappingsCtx.Value(ctx) if !isAddressMappingsDone && o.r.AddressMappings != nil { ctx = organizationRelAddressMappingsCtx.WithValue(ctx, true) @@ -1054,12 +1138,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.AddressMappings = append(m.R.AddressMappings, r.o.Build()) } else { - rel0, err := r.o.CreateMany(ctx, exec, r.number) + rel1, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachAddressMappings(ctx, exec, rel0...) + err = m.AttachAddressMappings(ctx, exec, rel1...) if err != nil { return err } @@ -1074,12 +1158,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.ParcelMappings = append(m.R.ParcelMappings, r.o.Build()) } else { - rel1, err := r.o.CreateMany(ctx, exec, r.number) + rel2, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachParcelMappings(ctx, exec, rel1...) + err = m.AttachParcelMappings(ctx, exec, rel2...) if err != nil { return err } @@ -1094,12 +1178,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.EmailContacts = append(m.R.EmailContacts, r.o.Build()) } else { - rel2, err := r.o.CreateMany(ctx, exec, r.number) + rel3, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachEmailContacts(ctx, exec, rel2...) + err = m.AttachEmailContacts(ctx, exec, rel3...) if err != nil { return err } @@ -1114,12 +1198,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Phones = append(m.R.Phones, r.o.Build()) } else { - rel3, err := r.o.CreateMany(ctx, exec, r.number) + rel4, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPhones(ctx, exec, rel3...) + err = m.AttachPhones(ctx, exec, rel4...) if err != nil { return err } @@ -1134,12 +1218,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Containerrelates = append(m.R.Containerrelates, r.o.Build()) } else { - rel4, err := r.o.CreateMany(ctx, exec, r.number) + rel5, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachContainerrelates(ctx, exec, rel4...) + err = m.AttachContainerrelates(ctx, exec, rel5...) if err != nil { return err } @@ -1154,12 +1238,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Fieldscoutinglogs = append(m.R.Fieldscoutinglogs, r.o.Build()) } else { - rel5, err := r.o.CreateMany(ctx, exec, r.number) + rel6, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachFieldscoutinglogs(ctx, exec, rel5...) + err = m.AttachFieldscoutinglogs(ctx, exec, rel6...) if err != nil { return err } @@ -1174,12 +1258,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Habitatrelates = append(m.R.Habitatrelates, r.o.Build()) } else { - rel6, err := r.o.CreateMany(ctx, exec, r.number) + rel7, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachHabitatrelates(ctx, exec, rel6...) + err = m.AttachHabitatrelates(ctx, exec, rel7...) if err != nil { return err } @@ -1194,12 +1278,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Inspectionsamples = append(m.R.Inspectionsamples, r.o.Build()) } else { - rel7, err := r.o.CreateMany(ctx, exec, r.number) + rel8, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachInspectionsamples(ctx, exec, rel7...) + err = m.AttachInspectionsamples(ctx, exec, rel8...) if err != nil { return err } @@ -1214,12 +1298,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Inspectionsampledetails = append(m.R.Inspectionsampledetails, r.o.Build()) } else { - rel8, err := r.o.CreateMany(ctx, exec, r.number) + rel9, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachInspectionsampledetails(ctx, exec, rel8...) + err = m.AttachInspectionsampledetails(ctx, exec, rel9...) if err != nil { return err } @@ -1234,12 +1318,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Linelocations = append(m.R.Linelocations, r.o.Build()) } else { - rel9, err := r.o.CreateMany(ctx, exec, r.number) + rel10, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachLinelocations(ctx, exec, rel9...) + err = m.AttachLinelocations(ctx, exec, rel10...) if err != nil { return err } @@ -1254,12 +1338,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Locationtrackings = append(m.R.Locationtrackings, r.o.Build()) } else { - rel10, err := r.o.CreateMany(ctx, exec, r.number) + rel11, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachLocationtrackings(ctx, exec, rel10...) + err = m.AttachLocationtrackings(ctx, exec, rel11...) if err != nil { return err } @@ -1274,12 +1358,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Mosquitoinspections = append(m.R.Mosquitoinspections, r.o.Build()) } else { - rel11, err := r.o.CreateMany(ctx, exec, r.number) + rel12, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachMosquitoinspections(ctx, exec, rel11...) + err = m.AttachMosquitoinspections(ctx, exec, rel12...) if err != nil { return err } @@ -1294,12 +1378,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Pointlocations = append(m.R.Pointlocations, r.o.Build()) } else { - rel12, err := r.o.CreateMany(ctx, exec, r.number) + rel13, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPointlocations(ctx, exec, rel12...) + err = m.AttachPointlocations(ctx, exec, rel13...) if err != nil { return err } @@ -1314,12 +1398,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Polygonlocations = append(m.R.Polygonlocations, r.o.Build()) } else { - rel13, err := r.o.CreateMany(ctx, exec, r.number) + rel14, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPolygonlocations(ctx, exec, rel13...) + err = m.AttachPolygonlocations(ctx, exec, rel14...) if err != nil { return err } @@ -1334,12 +1418,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.FieldseekerPool = append(m.R.FieldseekerPool, r.o.Build()) } else { - rel14, err := r.o.CreateMany(ctx, exec, r.number) + rel15, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachFieldseekerPool(ctx, exec, rel14...) + err = m.AttachFieldseekerPool(ctx, exec, rel15...) if err != nil { return err } @@ -1354,12 +1438,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Pooldetails = append(m.R.Pooldetails, r.o.Build()) } else { - rel15, err := r.o.CreateMany(ctx, exec, r.number) + rel16, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPooldetails(ctx, exec, rel15...) + err = m.AttachPooldetails(ctx, exec, rel16...) if err != nil { return err } @@ -1374,12 +1458,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Proposedtreatmentareas = append(m.R.Proposedtreatmentareas, r.o.Build()) } else { - rel16, err := r.o.CreateMany(ctx, exec, r.number) + rel17, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachProposedtreatmentareas(ctx, exec, rel16...) + err = m.AttachProposedtreatmentareas(ctx, exec, rel17...) if err != nil { return err } @@ -1394,12 +1478,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Qamosquitoinspections = append(m.R.Qamosquitoinspections, r.o.Build()) } else { - rel17, err := r.o.CreateMany(ctx, exec, r.number) + rel18, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachQamosquitoinspections(ctx, exec, rel17...) + err = m.AttachQamosquitoinspections(ctx, exec, rel18...) if err != nil { return err } @@ -1414,12 +1498,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Rodentlocations = append(m.R.Rodentlocations, r.o.Build()) } else { - rel18, err := r.o.CreateMany(ctx, exec, r.number) + rel19, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachRodentlocations(ctx, exec, rel18...) + err = m.AttachRodentlocations(ctx, exec, rel19...) if err != nil { return err } @@ -1434,12 +1518,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Samplecollections = append(m.R.Samplecollections, r.o.Build()) } else { - rel19, err := r.o.CreateMany(ctx, exec, r.number) + rel20, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachSamplecollections(ctx, exec, rel19...) + err = m.AttachSamplecollections(ctx, exec, rel20...) if err != nil { return err } @@ -1454,12 +1538,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Samplelocations = append(m.R.Samplelocations, r.o.Build()) } else { - rel20, err := r.o.CreateMany(ctx, exec, r.number) + rel21, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachSamplelocations(ctx, exec, rel20...) + err = m.AttachSamplelocations(ctx, exec, rel21...) if err != nil { return err } @@ -1474,12 +1558,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Servicerequests = append(m.R.Servicerequests, r.o.Build()) } else { - rel21, err := r.o.CreateMany(ctx, exec, r.number) + rel22, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachServicerequests(ctx, exec, rel21...) + err = m.AttachServicerequests(ctx, exec, rel22...) if err != nil { return err } @@ -1494,12 +1578,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Speciesabundances = append(m.R.Speciesabundances, r.o.Build()) } else { - rel22, err := r.o.CreateMany(ctx, exec, r.number) + rel23, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachSpeciesabundances(ctx, exec, rel22...) + err = m.AttachSpeciesabundances(ctx, exec, rel23...) if err != nil { return err } @@ -1514,12 +1598,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Stormdrains = append(m.R.Stormdrains, r.o.Build()) } else { - rel23, err := r.o.CreateMany(ctx, exec, r.number) + rel24, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachStormdrains(ctx, exec, rel23...) + err = m.AttachStormdrains(ctx, exec, rel24...) if err != nil { return err } @@ -1534,12 +1618,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Timecards = append(m.R.Timecards, r.o.Build()) } else { - rel24, err := r.o.CreateMany(ctx, exec, r.number) + rel25, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachTimecards(ctx, exec, rel24...) + err = m.AttachTimecards(ctx, exec, rel25...) if err != nil { return err } @@ -1554,12 +1638,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Trapdata = append(m.R.Trapdata, r.o.Build()) } else { - rel25, err := r.o.CreateMany(ctx, exec, r.number) + rel26, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachTrapdata(ctx, exec, rel25...) + err = m.AttachTrapdata(ctx, exec, rel26...) if err != nil { return err } @@ -1574,12 +1658,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Traplocations = append(m.R.Traplocations, r.o.Build()) } else { - rel26, err := r.o.CreateMany(ctx, exec, r.number) + rel27, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachTraplocations(ctx, exec, rel26...) + err = m.AttachTraplocations(ctx, exec, rel27...) if err != nil { return err } @@ -1594,12 +1678,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Treatments = append(m.R.Treatments, r.o.Build()) } else { - rel27, err := r.o.CreateMany(ctx, exec, r.number) + rel28, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachTreatments(ctx, exec, rel27...) + err = m.AttachTreatments(ctx, exec, rel28...) if err != nil { return err } @@ -1614,12 +1698,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Treatmentareas = append(m.R.Treatmentareas, r.o.Build()) } else { - rel28, err := r.o.CreateMany(ctx, exec, r.number) + rel29, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachTreatmentareas(ctx, exec, rel28...) + err = m.AttachTreatmentareas(ctx, exec, rel29...) if err != nil { return err } @@ -1634,12 +1718,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Zones = append(m.R.Zones, r.o.Build()) } else { - rel29, err := r.o.CreateMany(ctx, exec, r.number) + rel30, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachZones(ctx, exec, rel29...) + err = m.AttachZones(ctx, exec, rel30...) if err != nil { return err } @@ -1654,12 +1738,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Zones2s = append(m.R.Zones2s, r.o.Build()) } else { - rel30, err := r.o.CreateMany(ctx, exec, r.number) + rel31, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachZones2s(ctx, exec, rel30...) + err = m.AttachZones2s(ctx, exec, rel31...) if err != nil { return err } @@ -1674,12 +1758,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.FieldseekerSyncs = append(m.R.FieldseekerSyncs, r.o.Build()) } else { - rel31, err := r.o.CreateMany(ctx, exec, r.number) + rel32, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachFieldseekerSyncs(ctx, exec, rel31...) + err = m.AttachFieldseekerSyncs(ctx, exec, rel32...) if err != nil { return err } @@ -1694,12 +1778,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Files = append(m.R.Files, r.o.Build()) } else { - rel32, err := r.o.CreateMany(ctx, exec, r.number) + rel33, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachFiles(ctx, exec, rel32...) + err = m.AttachFiles(ctx, exec, rel33...) if err != nil { return err } @@ -1714,12 +1798,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Pools = append(m.R.Pools, r.o.Build()) } else { - rel33, err := r.o.CreateMany(ctx, exec, r.number) + rel34, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPools(ctx, exec, rel33...) + err = m.AttachPools(ctx, exec, rel34...) if err != nil { return err } @@ -1734,12 +1818,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.H3Aggregations = append(m.R.H3Aggregations, r.o.Build()) } else { - rel34, err := r.o.CreateMany(ctx, exec, r.number) + rel35, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachH3Aggregations(ctx, exec, rel34...) + err = m.AttachH3Aggregations(ctx, exec, rel35...) if err != nil { return err } @@ -1754,12 +1838,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.NoteAudios = append(m.R.NoteAudios, r.o.Build()) } else { - rel35, err := r.o.CreateMany(ctx, exec, r.number) + rel36, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachNoteAudios(ctx, exec, rel35...) + err = m.AttachNoteAudios(ctx, exec, rel36...) if err != nil { return err } @@ -1774,12 +1858,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.NoteImages = append(m.R.NoteImages, r.o.Build()) } else { - rel36, err := r.o.CreateMany(ctx, exec, r.number) + rel37, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachNoteImages(ctx, exec, rel36...) + err = m.AttachNoteImages(ctx, exec, rel37...) if err != nil { return err } @@ -1787,6 +1871,44 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu } } + isArcgisAccountAccountDone, _ := organizationRelArcgisAccountAccountCtx.Value(ctx) + if !isArcgisAccountAccountDone && o.r.ArcgisAccountAccount != nil { + ctx = organizationRelArcgisAccountAccountCtx.WithValue(ctx, true) + if o.r.ArcgisAccountAccount.o.alreadyPersisted { + m.R.ArcgisAccountAccount = o.r.ArcgisAccountAccount.o.Build() + } else { + var rel38 *models.ArcgisAccount + rel38, err = o.r.ArcgisAccountAccount.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachArcgisAccountAccount(ctx, exec, rel38) + if err != nil { + return err + } + } + + } + + isFieldseekerServiceFeatureItemServiceFeatureDone, _ := organizationRelFieldseekerServiceFeatureItemServiceFeatureCtx.Value(ctx) + if !isFieldseekerServiceFeatureItemServiceFeatureDone && o.r.FieldseekerServiceFeatureItemServiceFeature != nil { + ctx = organizationRelFieldseekerServiceFeatureItemServiceFeatureCtx.WithValue(ctx, true) + if o.r.FieldseekerServiceFeatureItemServiceFeature.o.alreadyPersisted { + m.R.FieldseekerServiceFeatureItemServiceFeature = o.r.FieldseekerServiceFeatureItemServiceFeature.o.Build() + } else { + var rel39 *models.ArcgisServiceFeature + rel39, err = o.r.FieldseekerServiceFeatureItemServiceFeature.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachFieldseekerServiceFeatureItemServiceFeature(ctx, exec, rel39) + if err != nil { + return err + } + } + + } + isNuisancesDone, _ := organizationRelNuisancesCtx.Value(ctx) if !isNuisancesDone && o.r.Nuisances != nil { ctx = organizationRelNuisancesCtx.WithValue(ctx, true) @@ -1794,12 +1916,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Nuisances = append(m.R.Nuisances, r.o.Build()) } else { - rel37, err := r.o.CreateMany(ctx, exec, r.number) + rel40, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachNuisances(ctx, exec, rel37...) + err = m.AttachNuisances(ctx, exec, rel40...) if err != nil { return err } @@ -1814,12 +1936,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.PublicreportPool = append(m.R.PublicreportPool, r.o.Build()) } else { - rel38, err := r.o.CreateMany(ctx, exec, r.number) + rel41, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPublicreportPool(ctx, exec, rel38...) + err = m.AttachPublicreportPool(ctx, exec, rel41...) if err != nil { return err } @@ -1834,12 +1956,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.Quicks = append(m.R.Quicks, r.o.Build()) } else { - rel39, err := r.o.CreateMany(ctx, exec, r.number) + rel42, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachQuicks(ctx, exec, rel39...) + err = m.AttachQuicks(ctx, exec, rel42...) if err != nil { return err } @@ -1854,12 +1976,12 @@ func (o *OrganizationTemplate) insertOptRels(ctx context.Context, exec bob.Execu if r.o.alreadyPersisted { m.R.User = append(m.R.User, r.o.Build()) } else { - rel40, err := r.o.CreateMany(ctx, exec, r.number) + rel43, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachUser(ctx, exec, rel40...) + err = m.AttachUser(ctx, exec, rel43...) if err != nil { return err } @@ -1961,9 +2083,6 @@ func (m organizationMods) RandomizeAllColumns(f *faker.Faker) OrganizationMod { return OrganizationModSlice{ OrganizationMods.RandomID(f), OrganizationMods.RandomName(f), - OrganizationMods.RandomArcgisID(f), - OrganizationMods.RandomArcgisName(f), - OrganizationMods.RandomFieldseekerURL(f), OrganizationMods.RandomImportDistrictGid(f), OrganizationMods.RandomWebsite(f), OrganizationMods.RandomLogoUUID(f), @@ -1988,6 +2107,12 @@ func (m organizationMods) RandomizeAllColumns(f *faker.Faker) OrganizationMod { OrganizationMods.RandomServiceAreaCentroidGeojson(f), OrganizationMods.RandomServiceAreaCentroidX(f), OrganizationMods.RandomServiceAreaCentroidY(f), + OrganizationMods.RandomMailingAddressCountry(f), + OrganizationMods.RandomMailingAddressState(f), + OrganizationMods.RandomOfficeAddressCountry(f), + OrganizationMods.RandomOfficeAddressState(f), + OrganizationMods.RandomArcgisAccountID(f), + OrganizationMods.RandomFieldseekerServiceFeatureItemID(f), } } @@ -2053,165 +2178,6 @@ func (m organizationMods) RandomName(f *faker.Faker) OrganizationMod { }) } -// Set the model columns to this value -func (m organizationMods) ArcgisID(val null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisID = func() null.Val[string] { return val } - }) -} - -// Set the Column from the function -func (m organizationMods) ArcgisIDFunc(f func() null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisID = f - }) -} - -// Clear any values for the column -func (m organizationMods) UnsetArcgisID() OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisID = nil - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is sometimes null -func (m organizationMods) RandomArcgisID(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisID = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is never null -func (m organizationMods) RandomArcgisIDNotNull(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisID = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Set the model columns to this value -func (m organizationMods) ArcgisName(val null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisName = func() null.Val[string] { return val } - }) -} - -// Set the Column from the function -func (m organizationMods) ArcgisNameFunc(f func() null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisName = f - }) -} - -// Clear any values for the column -func (m organizationMods) UnsetArcgisName() OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisName = nil - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is sometimes null -func (m organizationMods) RandomArcgisName(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisName = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is never null -func (m organizationMods) RandomArcgisNameNotNull(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.ArcgisName = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Set the model columns to this value -func (m organizationMods) FieldseekerURL(val null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.FieldseekerURL = func() null.Val[string] { return val } - }) -} - -// Set the Column from the function -func (m organizationMods) FieldseekerURLFunc(f func() null.Val[string]) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.FieldseekerURL = f - }) -} - -// Clear any values for the column -func (m organizationMods) UnsetFieldseekerURL() OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.FieldseekerURL = nil - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is sometimes null -func (m organizationMods) RandomFieldseekerURL(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.FieldseekerURL = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is never null -func (m organizationMods) RandomFieldseekerURLNotNull(f *faker.Faker) OrganizationMod { - return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { - o.FieldseekerURL = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - // Set the model columns to this value func (m organizationMods) ImportDistrictGid(val null.Val[int32]) OrganizationMod { return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { @@ -3484,12 +3450,448 @@ func (m organizationMods) RandomServiceAreaCentroidYNotNull(f *faker.Faker) Orga }) } +// Set the model columns to this value +func (m organizationMods) MailingAddressCountry(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressCountry = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) MailingAddressCountryFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressCountry = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetMailingAddressCountry() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressCountry = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomMailingAddressCountry(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressCountry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomMailingAddressCountryNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressCountry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m organizationMods) MailingAddressState(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressState = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) MailingAddressStateFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressState = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetMailingAddressState() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressState = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomMailingAddressState(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressState = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomMailingAddressStateNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.MailingAddressState = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m organizationMods) OfficeAddressCountry(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressCountry = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) OfficeAddressCountryFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressCountry = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetOfficeAddressCountry() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressCountry = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomOfficeAddressCountry(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressCountry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomOfficeAddressCountryNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressCountry = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m organizationMods) OfficeAddressState(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressState = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) OfficeAddressStateFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressState = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetOfficeAddressState() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressState = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomOfficeAddressState(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressState = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomOfficeAddressStateNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.OfficeAddressState = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m organizationMods) ArcgisAccountID(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.ArcgisAccountID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) ArcgisAccountIDFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.ArcgisAccountID = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetArcgisAccountID() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.ArcgisAccountID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomArcgisAccountID(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.ArcgisAccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomArcgisAccountIDNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.ArcgisAccountID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m organizationMods) FieldseekerServiceFeatureItemID(val null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.FieldseekerServiceFeatureItemID = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m organizationMods) FieldseekerServiceFeatureItemIDFunc(f func() null.Val[string]) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.FieldseekerServiceFeatureItemID = f + }) +} + +// Clear any values for the column +func (m organizationMods) UnsetFieldseekerServiceFeatureItemID() OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.FieldseekerServiceFeatureItemID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m organizationMods) RandomFieldseekerServiceFeatureItemID(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.FieldseekerServiceFeatureItemID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m organizationMods) RandomFieldseekerServiceFeatureItemIDNotNull(f *faker.Faker) OrganizationMod { + return OrganizationModFunc(func(_ context.Context, o *OrganizationTemplate) { + o.FieldseekerServiceFeatureItemID = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + func (m organizationMods) WithParentsCascading() OrganizationMod { return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { if isDone, _ := organizationWithParentsCascadingCtx.Value(ctx); isDone { return } ctx = organizationWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewArcgisAccountWithContext(ctx, ArcgisAccountMods.WithParentsCascading()) + m.WithArcgisAccountAccount(related).Apply(ctx, o) + } + { + + related := o.f.NewArcgisServiceFeatureWithContext(ctx, ArcgisServiceFeatureMods.WithParentsCascading()) + m.WithFieldseekerServiceFeatureItemServiceFeature(related).Apply(ctx, o) + } + }) +} + +func (m organizationMods) WithArcgisAccountAccount(rel *ArcgisAccountTemplate) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.ArcgisAccountAccount = &organizationRArcgisAccountAccountR{ + o: rel, + } + }) +} + +func (m organizationMods) WithNewArcgisAccountAccount(mods ...ArcgisAccountMod) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + + m.WithArcgisAccountAccount(related).Apply(ctx, o) + }) +} + +func (m organizationMods) WithExistingArcgisAccountAccount(em *models.ArcgisAccount) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.ArcgisAccountAccount = &organizationRArcgisAccountAccountR{ + o: o.f.FromExistingArcgisAccount(em), + } + }) +} + +func (m organizationMods) WithoutArcgisAccountAccount() OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.ArcgisAccountAccount = nil + }) +} + +func (m organizationMods) WithFieldseekerServiceFeatureItemServiceFeature(rel *ArcgisServiceFeatureTemplate) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.FieldseekerServiceFeatureItemServiceFeature = &organizationRFieldseekerServiceFeatureItemServiceFeatureR{ + o: rel, + } + }) +} + +func (m organizationMods) WithNewFieldseekerServiceFeatureItemServiceFeature(mods ...ArcgisServiceFeatureMod) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + related := o.f.NewArcgisServiceFeatureWithContext(ctx, mods...) + + m.WithFieldseekerServiceFeatureItemServiceFeature(related).Apply(ctx, o) + }) +} + +func (m organizationMods) WithExistingFieldseekerServiceFeatureItemServiceFeature(em *models.ArcgisServiceFeature) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.FieldseekerServiceFeatureItemServiceFeature = &organizationRFieldseekerServiceFeatureItemServiceFeatureR{ + o: o.f.FromExistingArcgisServiceFeature(em), + } + }) +} + +func (m organizationMods) WithoutFieldseekerServiceFeatureItemServiceFeature() OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.FieldseekerServiceFeatureItemServiceFeature = nil + }) +} + +func (m organizationMods) WithAccounts(number int, related *ArcgisAccountTemplate) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.Accounts = []*organizationRAccountsR{{ + number: number, + o: related, + }} + }) +} + +func (m organizationMods) WithNewAccounts(number int, mods ...ArcgisAccountMod) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + m.WithAccounts(number, related).Apply(ctx, o) + }) +} + +func (m organizationMods) AddAccounts(number int, related *ArcgisAccountTemplate) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.Accounts = append(o.r.Accounts, &organizationRAccountsR{ + number: number, + o: related, + }) + }) +} + +func (m organizationMods) AddNewAccounts(number int, mods ...ArcgisAccountMod) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + related := o.f.NewArcgisAccountWithContext(ctx, mods...) + m.AddAccounts(number, related).Apply(ctx, o) + }) +} + +func (m organizationMods) AddExistingAccounts(existingModels ...*models.ArcgisAccount) OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + for _, em := range existingModels { + o.r.Accounts = append(o.r.Accounts, &organizationRAccountsR{ + o: o.f.FromExistingArcgisAccount(em), + }) + } + }) +} + +func (m organizationMods) WithoutAccounts() OrganizationMod { + return OrganizationModFunc(func(ctx context.Context, o *OrganizationTemplate) { + o.r.Accounts = nil }) } diff --git a/db/factory/parcel.bob.go b/db/factory/parcel.bob.go index 92e0b050..eb3bee7a 100644 --- a/db/factory/parcel.bob.go +++ b/db/factory/parcel.bob.go @@ -9,7 +9,9 @@ import ( "github.com/Gleipnir-Technology/bob" models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" "github.com/jaswdr/faker/v2" ) @@ -34,16 +36,26 @@ func (mods ParcelModSlice) Apply(ctx context.Context, n *ParcelTemplate) { // ParcelTemplate is an object representing the database table. // all columns are optional and should be set by mods type ParcelTemplate struct { - Apn func() string - Description func() string + Apn func() null.Val[string] + Description func() null.Val[string] ID func() int32 Geometry func() string + r parcelR f *Factory alreadyPersisted bool } +type parcelR struct { + Sites []*parcelRSitesR +} + +type parcelRSitesR struct { + number int + o *SiteTemplate +} + // Apply mods to the ParcelTemplate func (o *ParcelTemplate) Apply(ctx context.Context, mods ...ParcelMod) { for _, mod := range mods { @@ -53,7 +65,20 @@ func (o *ParcelTemplate) Apply(ctx context.Context, mods ...ParcelMod) { // setModelRels creates and sets the relationships on *models.Parcel // according to the relationships in the template. Nothing is inserted into the db -func (t ParcelTemplate) setModelRels(o *models.Parcel) {} +func (t ParcelTemplate) setModelRels(o *models.Parcel) { + if t.r.Sites != nil { + rel := models.SiteSlice{} + for _, r := range t.r.Sites { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.ParcelID = o.ID // h2 + rel.R.Parcel = o + } + rel = append(rel, related...) + } + o.R.Sites = rel + } +} // BuildSetter returns an *models.ParcelSetter // this does nothing with the relationship templates @@ -62,11 +87,11 @@ func (o ParcelTemplate) BuildSetter() *models.ParcelSetter { if o.Apn != nil { val := o.Apn() - m.Apn = omit.From(val) + m.Apn = omitnull.FromNull(val) } if o.Description != nil { val := o.Description() - m.Description = omit.From(val) + m.Description = omitnull.FromNull(val) } if o.ID != nil { val := o.ID() @@ -130,14 +155,6 @@ func (o ParcelTemplate) BuildMany(number int) models.ParcelSlice { } func ensureCreatableParcel(m *models.ParcelSetter) { - if !(m.Apn.IsValue()) { - val := random_string(nil) - m.Apn = omit.From(val) - } - if !(m.Description.IsValue()) { - val := random_string(nil) - m.Description = omit.From(val) - } if !(m.Geometry.IsValue()) { val := random_string(nil) m.Geometry = omit.From(val) @@ -150,6 +167,26 @@ func ensureCreatableParcel(m *models.ParcelSetter) { func (o *ParcelTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Parcel) error { var err error + isSitesDone, _ := parcelRelSitesCtx.Value(ctx) + if !isSitesDone && o.r.Sites != nil { + ctx = parcelRelSitesCtx.WithValue(ctx, true) + for _, r := range o.r.Sites { + if r.o.alreadyPersisted { + m.R.Sites = append(m.R.Sites, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachSites(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + return err } @@ -250,14 +287,14 @@ func (m parcelMods) RandomizeAllColumns(f *faker.Faker) ParcelMod { } // Set the model columns to this value -func (m parcelMods) Apn(val string) ParcelMod { +func (m parcelMods) Apn(val null.Val[string]) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { - o.Apn = func() string { return val } + o.Apn = func() null.Val[string] { return val } }) } // Set the Column from the function -func (m parcelMods) ApnFunc(f func() string) ParcelMod { +func (m parcelMods) ApnFunc(f func() null.Val[string]) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { o.Apn = f }) @@ -272,23 +309,45 @@ func (m parcelMods) UnsetApn() ParcelMod { // Generates a random value for the column using the given faker // if faker is nil, a default faker is used +// The generated value is sometimes null func (m parcelMods) RandomApn(f *faker.Faker) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { - o.Apn = func() string { - return random_string(f) + o.Apn = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m parcelMods) RandomApnNotNull(f *faker.Faker) ParcelMod { + return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { + o.Apn = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) } }) } // Set the model columns to this value -func (m parcelMods) Description(val string) ParcelMod { +func (m parcelMods) Description(val null.Val[string]) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { - o.Description = func() string { return val } + o.Description = func() null.Val[string] { return val } }) } // Set the Column from the function -func (m parcelMods) DescriptionFunc(f func() string) ParcelMod { +func (m parcelMods) DescriptionFunc(f func() null.Val[string]) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { o.Description = f }) @@ -303,10 +362,32 @@ func (m parcelMods) UnsetDescription() ParcelMod { // Generates a random value for the column using the given faker // if faker is nil, a default faker is used +// The generated value is sometimes null func (m parcelMods) RandomDescription(f *faker.Faker) ParcelMod { return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { - o.Description = func() string { - return random_string(f) + o.Description = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m parcelMods) RandomDescriptionNotNull(f *faker.Faker) ParcelMod { + return ParcelModFunc(func(_ context.Context, o *ParcelTemplate) { + o.Description = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) } }) } @@ -381,3 +462,51 @@ func (m parcelMods) WithParentsCascading() ParcelMod { ctx = parcelWithParentsCascadingCtx.WithValue(ctx, true) }) } + +func (m parcelMods) WithSites(number int, related *SiteTemplate) ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + o.r.Sites = []*parcelRSitesR{{ + number: number, + o: related, + }} + }) +} + +func (m parcelMods) WithNewSites(number int, mods ...SiteMod) ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + related := o.f.NewSiteWithContext(ctx, mods...) + m.WithSites(number, related).Apply(ctx, o) + }) +} + +func (m parcelMods) AddSites(number int, related *SiteTemplate) ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + o.r.Sites = append(o.r.Sites, &parcelRSitesR{ + number: number, + o: related, + }) + }) +} + +func (m parcelMods) AddNewSites(number int, mods ...SiteMod) ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + related := o.f.NewSiteWithContext(ctx, mods...) + m.AddSites(number, related).Apply(ctx, o) + }) +} + +func (m parcelMods) AddExistingSites(existingModels ...*models.Site) ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + for _, em := range existingModels { + o.r.Sites = append(o.r.Sites, &parcelRSitesR{ + o: o.f.FromExistingSite(em), + }) + } + }) +} + +func (m parcelMods) WithoutSites() ParcelMod { + return ParcelModFunc(func(ctx context.Context, o *ParcelTemplate) { + o.r.Sites = nil + }) +} diff --git a/db/factory/pool.bob.go b/db/factory/pool.bob.go index 667dbb89..07c5ad91 100644 --- a/db/factory/pool.bob.go +++ b/db/factory/pool.bob.go @@ -11,9 +11,7 @@ import ( "github.com/Gleipnir-Technology/bob" enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" models "github.com/Gleipnir-Technology/nidus-sync/db/models" - "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" "github.com/jaswdr/faker/v2" ) @@ -38,11 +36,12 @@ func (mods PoolModSlice) Apply(ctx context.Context, n *PoolTemplate) { // PoolTemplate is an object representing the database table. // all columns are optional and should be set by mods type PoolTemplate struct { - Condition func() enums.Poolconditiontype - Created func() time.Time - CreatorID func() int32 - ID func() int32 - SiteID func() null.Val[int32] + Condition func() enums.Poolconditiontype + Created func() time.Time + CreatorID func() int32 + ID func() int32 + SiteID func() int32 + SiteVersion func() int32 r poolR f *Factory @@ -52,11 +51,15 @@ type PoolTemplate struct { type poolR struct { CreatorUser *poolRCreatorUserR + Site *poolRSiteR } type poolRCreatorUserR struct { o *UserTemplate } +type poolRSiteR struct { + o *SiteTemplate +} // Apply mods to the PoolTemplate func (o *PoolTemplate) Apply(ctx context.Context, mods ...PoolMod) { @@ -74,6 +77,14 @@ func (t PoolTemplate) setModelRels(o *models.Pool) { o.CreatorID = rel.ID // h2 o.R.CreatorUser = rel } + + if t.r.Site != nil { + rel := t.r.Site.o.Build() + rel.R.Pools = append(rel.R.Pools, o) + o.SiteID = rel.ID // h2 + o.SiteVersion = rel.Version // h2 + o.R.Site = rel + } } // BuildSetter returns an *models.PoolSetter @@ -99,7 +110,11 @@ func (o PoolTemplate) BuildSetter() *models.PoolSetter { } if o.SiteID != nil { val := o.SiteID() - m.SiteID = omitnull.FromNull(val) + m.SiteID = omit.From(val) + } + if o.SiteVersion != nil { + val := o.SiteVersion() + m.SiteVersion = omit.From(val) } return m @@ -138,6 +153,9 @@ func (o PoolTemplate) Build() *models.Pool { if o.SiteID != nil { m.SiteID = o.SiteID() } + if o.SiteVersion != nil { + m.SiteVersion = o.SiteVersion() + } o.setModelRels(m) @@ -170,6 +188,14 @@ func ensureCreatablePool(m *models.PoolSetter) { val := random_int32(nil) m.CreatorID = omit.From(val) } + if !(m.SiteID.IsValue()) { + val := random_int32(nil) + m.SiteID = omit.From(val) + } + if !(m.SiteVersion.IsValue()) { + val := random_int32(nil) + m.SiteVersion = omit.From(val) + } } // insertOptRels creates and inserts any optional the relationships on *models.Pool @@ -205,12 +231,31 @@ func (o *PoolTemplate) Create(ctx context.Context, exec bob.Executor) (*models.P opt.CreatorID = omit.From(rel0.ID) + if o.r.Site == nil { + PoolMods.WithNewSite().Apply(ctx, o) + } + + var rel1 *models.Site + + if o.r.Site.o.alreadyPersisted { + rel1 = o.r.Site.o.Build() + } else { + rel1, err = o.r.Site.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.SiteID = omit.From(rel1.ID) + opt.SiteVersion = omit.From(rel1.Version) + m, err := models.Pools.Insert(opt).One(ctx, exec) if err != nil { return nil, err } m.R.CreatorUser = rel0 + m.R.Site = rel1 if err := o.insertOptRels(ctx, exec, m); err != nil { return nil, err @@ -294,6 +339,7 @@ func (m poolMods) RandomizeAllColumns(f *faker.Faker) PoolMod { PoolMods.RandomCreatorID(f), PoolMods.RandomID(f), PoolMods.RandomSiteID(f), + PoolMods.RandomSiteVersion(f), } } @@ -422,14 +468,14 @@ func (m poolMods) RandomID(f *faker.Faker) PoolMod { } // Set the model columns to this value -func (m poolMods) SiteID(val null.Val[int32]) PoolMod { +func (m poolMods) SiteID(val int32) PoolMod { return PoolModFunc(func(_ context.Context, o *PoolTemplate) { - o.SiteID = func() null.Val[int32] { return val } + o.SiteID = func() int32 { return val } }) } // Set the Column from the function -func (m poolMods) SiteIDFunc(f func() null.Val[int32]) PoolMod { +func (m poolMods) SiteIDFunc(f func() int32) PoolMod { return PoolModFunc(func(_ context.Context, o *PoolTemplate) { o.SiteID = f }) @@ -444,32 +490,41 @@ func (m poolMods) UnsetSiteID() PoolMod { // Generates a random value for the column using the given faker // if faker is nil, a default faker is used -// The generated value is sometimes null func (m poolMods) RandomSiteID(f *faker.Faker) PoolMod { return PoolModFunc(func(_ context.Context, o *PoolTemplate) { - o.SiteID = func() null.Val[int32] { - if f == nil { - f = &defaultFaker - } - - val := random_int32(f) - return null.From(val) + o.SiteID = func() int32 { + return random_int32(f) } }) } +// Set the model columns to this value +func (m poolMods) SiteVersion(val int32) PoolMod { + return PoolModFunc(func(_ context.Context, o *PoolTemplate) { + o.SiteVersion = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m poolMods) SiteVersionFunc(f func() int32) PoolMod { + return PoolModFunc(func(_ context.Context, o *PoolTemplate) { + o.SiteVersion = f + }) +} + +// Clear any values for the column +func (m poolMods) UnsetSiteVersion() PoolMod { + return PoolModFunc(func(_ context.Context, o *PoolTemplate) { + o.SiteVersion = nil + }) +} + // Generates a random value for the column using the given faker // if faker is nil, a default faker is used -// The generated value is never null -func (m poolMods) RandomSiteIDNotNull(f *faker.Faker) PoolMod { +func (m poolMods) RandomSiteVersion(f *faker.Faker) PoolMod { return PoolModFunc(func(_ context.Context, o *PoolTemplate) { - o.SiteID = func() null.Val[int32] { - if f == nil { - f = &defaultFaker - } - - val := random_int32(f) - return null.From(val) + o.SiteVersion = func() int32 { + return random_int32(f) } }) } @@ -485,6 +540,11 @@ func (m poolMods) WithParentsCascading() PoolMod { related := o.f.NewUserWithContext(ctx, UserMods.WithParentsCascading()) m.WithCreatorUser(related).Apply(ctx, o) } + { + + related := o.f.NewSiteWithContext(ctx, SiteMods.WithParentsCascading()) + m.WithSite(related).Apply(ctx, o) + } }) } @@ -517,3 +577,33 @@ func (m poolMods) WithoutCreatorUser() PoolMod { o.r.CreatorUser = nil }) } + +func (m poolMods) WithSite(rel *SiteTemplate) PoolMod { + return PoolModFunc(func(ctx context.Context, o *PoolTemplate) { + o.r.Site = &poolRSiteR{ + o: rel, + } + }) +} + +func (m poolMods) WithNewSite(mods ...SiteMod) PoolMod { + return PoolModFunc(func(ctx context.Context, o *PoolTemplate) { + related := o.f.NewSiteWithContext(ctx, mods...) + + m.WithSite(related).Apply(ctx, o) + }) +} + +func (m poolMods) WithExistingSite(em *models.Site) PoolMod { + return PoolModFunc(func(ctx context.Context, o *PoolTemplate) { + o.r.Site = &poolRSiteR{ + o: o.f.FromExistingSite(em), + } + }) +} + +func (m poolMods) WithoutSite() PoolMod { + return PoolModFunc(func(ctx context.Context, o *PoolTemplate) { + o.r.Site = nil + }) +} diff --git a/db/factory/resident.bob.go b/db/factory/resident.bob.go new file mode 100644 index 00000000..094a7d20 --- /dev/null +++ b/db/factory/resident.bob.go @@ -0,0 +1,845 @@ +// 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 factory + +import ( + "context" + "testing" + "time" + + "github.com/Gleipnir-Technology/bob" + models "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/aarondl/opt/null" + "github.com/aarondl/opt/omit" + "github.com/aarondl/opt/omitnull" + "github.com/jaswdr/faker/v2" +) + +type ResidentMod interface { + Apply(context.Context, *ResidentTemplate) +} + +type ResidentModFunc func(context.Context, *ResidentTemplate) + +func (f ResidentModFunc) Apply(ctx context.Context, n *ResidentTemplate) { + f(ctx, n) +} + +type ResidentModSlice []ResidentMod + +func (mods ResidentModSlice) Apply(ctx context.Context, n *ResidentTemplate) { + for _, f := range mods { + f.Apply(ctx, n) + } +} + +// ResidentTemplate is an object representing the database table. +// all columns are optional and should be set by mods +type ResidentTemplate struct { + AddressID func() int32 + Created func() time.Time + Creator func() int32 + ID func() int32 + Name func() string + PhoneMobile func() null.Val[string] + SiteID func() int32 + SiteVersion func() int32 + + r residentR + f *Factory + + alreadyPersisted bool +} + +type residentR struct { + Address *residentRAddressR + CreatorUser *residentRCreatorUserR + PhoneMobilePhone *residentRPhoneMobilePhoneR + Site *residentRSiteR +} + +type residentRAddressR struct { + o *AddressTemplate +} +type residentRCreatorUserR struct { + o *UserTemplate +} +type residentRPhoneMobilePhoneR struct { + o *CommsPhoneTemplate +} +type residentRSiteR struct { + o *SiteTemplate +} + +// Apply mods to the ResidentTemplate +func (o *ResidentTemplate) Apply(ctx context.Context, mods ...ResidentMod) { + for _, mod := range mods { + mod.Apply(ctx, o) + } +} + +// setModelRels creates and sets the relationships on *models.Resident +// according to the relationships in the template. Nothing is inserted into the db +func (t ResidentTemplate) setModelRels(o *models.Resident) { + if t.r.Address != nil { + rel := t.r.Address.o.Build() + rel.R.Residents = append(rel.R.Residents, o) + o.AddressID = rel.ID // h2 + o.R.Address = rel + } + + if t.r.CreatorUser != nil { + rel := t.r.CreatorUser.o.Build() + rel.R.CreatorResidents = append(rel.R.CreatorResidents, o) + o.Creator = rel.ID // h2 + o.R.CreatorUser = rel + } + + if t.r.PhoneMobilePhone != nil { + rel := t.r.PhoneMobilePhone.o.Build() + rel.R.PhoneMobileResidents = append(rel.R.PhoneMobileResidents, o) + o.PhoneMobile = null.From(rel.E164) // h2 + o.R.PhoneMobilePhone = rel + } + + if t.r.Site != nil { + rel := t.r.Site.o.Build() + rel.R.Residents = append(rel.R.Residents, o) + o.SiteID = rel.ID // h2 + o.SiteVersion = rel.Version // h2 + o.R.Site = rel + } +} + +// BuildSetter returns an *models.ResidentSetter +// this does nothing with the relationship templates +func (o ResidentTemplate) BuildSetter() *models.ResidentSetter { + m := &models.ResidentSetter{} + + if o.AddressID != nil { + val := o.AddressID() + m.AddressID = omit.From(val) + } + if o.Created != nil { + val := o.Created() + m.Created = omit.From(val) + } + if o.Creator != nil { + val := o.Creator() + m.Creator = omit.From(val) + } + if o.ID != nil { + val := o.ID() + m.ID = omit.From(val) + } + if o.Name != nil { + val := o.Name() + m.Name = omit.From(val) + } + if o.PhoneMobile != nil { + val := o.PhoneMobile() + m.PhoneMobile = omitnull.FromNull(val) + } + if o.SiteID != nil { + val := o.SiteID() + m.SiteID = omit.From(val) + } + if o.SiteVersion != nil { + val := o.SiteVersion() + m.SiteVersion = omit.From(val) + } + + return m +} + +// BuildManySetter returns an []*models.ResidentSetter +// this does nothing with the relationship templates +func (o ResidentTemplate) BuildManySetter(number int) []*models.ResidentSetter { + m := make([]*models.ResidentSetter, number) + + for i := range m { + m[i] = o.BuildSetter() + } + + return m +} + +// Build returns an *models.Resident +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ResidentTemplate.Create +func (o ResidentTemplate) Build() *models.Resident { + m := &models.Resident{} + + if o.AddressID != nil { + m.AddressID = o.AddressID() + } + if o.Created != nil { + m.Created = o.Created() + } + if o.Creator != nil { + m.Creator = o.Creator() + } + if o.ID != nil { + m.ID = o.ID() + } + if o.Name != nil { + m.Name = o.Name() + } + if o.PhoneMobile != nil { + m.PhoneMobile = o.PhoneMobile() + } + if o.SiteID != nil { + m.SiteID = o.SiteID() + } + if o.SiteVersion != nil { + m.SiteVersion = o.SiteVersion() + } + + o.setModelRels(m) + + return m +} + +// BuildMany returns an models.ResidentSlice +// Related objects are also created and placed in the .R field +// NOTE: Objects are not inserted into the database. Use ResidentTemplate.CreateMany +func (o ResidentTemplate) BuildMany(number int) models.ResidentSlice { + m := make(models.ResidentSlice, number) + + for i := range m { + m[i] = o.Build() + } + + return m +} + +func ensureCreatableResident(m *models.ResidentSetter) { + if !(m.AddressID.IsValue()) { + val := random_int32(nil) + m.AddressID = omit.From(val) + } + if !(m.Created.IsValue()) { + val := random_time_Time(nil) + m.Created = omit.From(val) + } + if !(m.Creator.IsValue()) { + val := random_int32(nil) + m.Creator = omit.From(val) + } + if !(m.Name.IsValue()) { + val := random_string(nil) + m.Name = omit.From(val) + } + if !(m.SiteID.IsValue()) { + val := random_int32(nil) + m.SiteID = omit.From(val) + } + if !(m.SiteVersion.IsValue()) { + val := random_int32(nil) + m.SiteVersion = omit.From(val) + } +} + +// insertOptRels creates and inserts any optional the relationships on *models.Resident +// according to the relationships in the template. +// any required relationship should have already exist on the model +func (o *ResidentTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Resident) error { + var err error + + isPhoneMobilePhoneDone, _ := residentRelPhoneMobilePhoneCtx.Value(ctx) + if !isPhoneMobilePhoneDone && o.r.PhoneMobilePhone != nil { + ctx = residentRelPhoneMobilePhoneCtx.WithValue(ctx, true) + if o.r.PhoneMobilePhone.o.alreadyPersisted { + m.R.PhoneMobilePhone = o.r.PhoneMobilePhone.o.Build() + } else { + var rel2 *models.CommsPhone + rel2, err = o.r.PhoneMobilePhone.o.Create(ctx, exec) + if err != nil { + return err + } + err = m.AttachPhoneMobilePhone(ctx, exec, rel2) + if err != nil { + return err + } + } + + } + + return err +} + +// Create builds a resident and inserts it into the database +// Relations objects are also inserted and placed in the .R field +func (o *ResidentTemplate) Create(ctx context.Context, exec bob.Executor) (*models.Resident, error) { + var err error + opt := o.BuildSetter() + ensureCreatableResident(opt) + + if o.r.Address == nil { + ResidentMods.WithNewAddress().Apply(ctx, o) + } + + var rel0 *models.Address + + if o.r.Address.o.alreadyPersisted { + rel0 = o.r.Address.o.Build() + } else { + rel0, err = o.r.Address.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.AddressID = omit.From(rel0.ID) + + if o.r.CreatorUser == nil { + ResidentMods.WithNewCreatorUser().Apply(ctx, o) + } + + var rel1 *models.User + + if o.r.CreatorUser.o.alreadyPersisted { + rel1 = o.r.CreatorUser.o.Build() + } else { + rel1, err = o.r.CreatorUser.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.Creator = omit.From(rel1.ID) + + if o.r.Site == nil { + ResidentMods.WithNewSite().Apply(ctx, o) + } + + var rel3 *models.Site + + if o.r.Site.o.alreadyPersisted { + rel3 = o.r.Site.o.Build() + } else { + rel3, err = o.r.Site.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.SiteID = omit.From(rel3.ID) + opt.SiteVersion = omit.From(rel3.Version) + + m, err := models.Residents.Insert(opt).One(ctx, exec) + if err != nil { + return nil, err + } + + m.R.Address = rel0 + m.R.CreatorUser = rel1 + m.R.Site = rel3 + + if err := o.insertOptRels(ctx, exec, m); err != nil { + return nil, err + } + return m, err +} + +// MustCreate builds a resident and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o *ResidentTemplate) MustCreate(ctx context.Context, exec bob.Executor) *models.Resident { + m, err := o.Create(ctx, exec) + if err != nil { + panic(err) + } + return m +} + +// CreateOrFail builds a resident and inserts it into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o *ResidentTemplate) CreateOrFail(ctx context.Context, tb testing.TB, exec bob.Executor) *models.Resident { + tb.Helper() + m, err := o.Create(ctx, exec) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// CreateMany builds multiple residents and inserts them into the database +// Relations objects are also inserted and placed in the .R field +func (o ResidentTemplate) CreateMany(ctx context.Context, exec bob.Executor, number int) (models.ResidentSlice, error) { + var err error + m := make(models.ResidentSlice, number) + + for i := range m { + m[i], err = o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + return m, nil +} + +// MustCreateMany builds multiple residents and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// panics if an error occurs +func (o ResidentTemplate) MustCreateMany(ctx context.Context, exec bob.Executor, number int) models.ResidentSlice { + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + panic(err) + } + return m +} + +// CreateManyOrFail builds multiple residents and inserts them into the database +// Relations objects are also inserted and placed in the .R field +// It calls `tb.Fatal(err)` on the test/benchmark if an error occurs +func (o ResidentTemplate) CreateManyOrFail(ctx context.Context, tb testing.TB, exec bob.Executor, number int) models.ResidentSlice { + tb.Helper() + m, err := o.CreateMany(ctx, exec, number) + if err != nil { + tb.Fatal(err) + return nil + } + return m +} + +// Resident has methods that act as mods for the ResidentTemplate +var ResidentMods residentMods + +type residentMods struct{} + +func (m residentMods) RandomizeAllColumns(f *faker.Faker) ResidentMod { + return ResidentModSlice{ + ResidentMods.RandomAddressID(f), + ResidentMods.RandomCreated(f), + ResidentMods.RandomCreator(f), + ResidentMods.RandomID(f), + ResidentMods.RandomName(f), + ResidentMods.RandomPhoneMobile(f), + ResidentMods.RandomSiteID(f), + ResidentMods.RandomSiteVersion(f), + } +} + +// Set the model columns to this value +func (m residentMods) AddressID(val int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.AddressID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m residentMods) AddressIDFunc(f func() int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.AddressID = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetAddressID() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.AddressID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomAddressID(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.AddressID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) Created(val time.Time) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Created = func() time.Time { return val } + }) +} + +// Set the Column from the function +func (m residentMods) CreatedFunc(f func() time.Time) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Created = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetCreated() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Created = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomCreated(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Created = func() time.Time { + return random_time_Time(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) Creator(val int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Creator = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m residentMods) CreatorFunc(f func() int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Creator = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetCreator() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Creator = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomCreator(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Creator = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) ID(val int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.ID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m residentMods) IDFunc(f func() int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.ID = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetID() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.ID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomID(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.ID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) Name(val string) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Name = func() string { return val } + }) +} + +// Set the Column from the function +func (m residentMods) NameFunc(f func() string) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Name = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetName() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Name = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomName(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.Name = func() string { + return random_string(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) PhoneMobile(val null.Val[string]) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.PhoneMobile = func() null.Val[string] { return val } + }) +} + +// Set the Column from the function +func (m residentMods) PhoneMobileFunc(f func() null.Val[string]) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.PhoneMobile = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetPhoneMobile() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.PhoneMobile = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is sometimes null +func (m residentMods) RandomPhoneMobile(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.PhoneMobile = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +// The generated value is never null +func (m residentMods) RandomPhoneMobileNotNull(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.PhoneMobile = func() null.Val[string] { + if f == nil { + f = &defaultFaker + } + + val := random_string(f) + return null.From(val) + } + }) +} + +// Set the model columns to this value +func (m residentMods) SiteID(val int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m residentMods) SiteIDFunc(f func() int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteID = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetSiteID() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomSiteID(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteID = func() int32 { + return random_int32(f) + } + }) +} + +// Set the model columns to this value +func (m residentMods) SiteVersion(val int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteVersion = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m residentMods) SiteVersionFunc(f func() int32) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteVersion = f + }) +} + +// Clear any values for the column +func (m residentMods) UnsetSiteVersion() ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteVersion = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m residentMods) RandomSiteVersion(f *faker.Faker) ResidentMod { + return ResidentModFunc(func(_ context.Context, o *ResidentTemplate) { + o.SiteVersion = func() int32 { + return random_int32(f) + } + }) +} + +func (m residentMods) WithParentsCascading() ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + if isDone, _ := residentWithParentsCascadingCtx.Value(ctx); isDone { + return + } + ctx = residentWithParentsCascadingCtx.WithValue(ctx, true) + { + + related := o.f.NewAddressWithContext(ctx, AddressMods.WithParentsCascading()) + m.WithAddress(related).Apply(ctx, o) + } + { + + related := o.f.NewUserWithContext(ctx, UserMods.WithParentsCascading()) + m.WithCreatorUser(related).Apply(ctx, o) + } + { + + related := o.f.NewCommsPhoneWithContext(ctx, CommsPhoneMods.WithParentsCascading()) + m.WithPhoneMobilePhone(related).Apply(ctx, o) + } + { + + related := o.f.NewSiteWithContext(ctx, SiteMods.WithParentsCascading()) + m.WithSite(related).Apply(ctx, o) + } + }) +} + +func (m residentMods) WithAddress(rel *AddressTemplate) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Address = &residentRAddressR{ + o: rel, + } + }) +} + +func (m residentMods) WithNewAddress(mods ...AddressMod) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + related := o.f.NewAddressWithContext(ctx, mods...) + + m.WithAddress(related).Apply(ctx, o) + }) +} + +func (m residentMods) WithExistingAddress(em *models.Address) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Address = &residentRAddressR{ + o: o.f.FromExistingAddress(em), + } + }) +} + +func (m residentMods) WithoutAddress() ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Address = nil + }) +} + +func (m residentMods) WithCreatorUser(rel *UserTemplate) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.CreatorUser = &residentRCreatorUserR{ + o: rel, + } + }) +} + +func (m residentMods) WithNewCreatorUser(mods ...UserMod) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + related := o.f.NewUserWithContext(ctx, mods...) + + m.WithCreatorUser(related).Apply(ctx, o) + }) +} + +func (m residentMods) WithExistingCreatorUser(em *models.User) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.CreatorUser = &residentRCreatorUserR{ + o: o.f.FromExistingUser(em), + } + }) +} + +func (m residentMods) WithoutCreatorUser() ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.CreatorUser = nil + }) +} + +func (m residentMods) WithPhoneMobilePhone(rel *CommsPhoneTemplate) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.PhoneMobilePhone = &residentRPhoneMobilePhoneR{ + o: rel, + } + }) +} + +func (m residentMods) WithNewPhoneMobilePhone(mods ...CommsPhoneMod) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + related := o.f.NewCommsPhoneWithContext(ctx, mods...) + + m.WithPhoneMobilePhone(related).Apply(ctx, o) + }) +} + +func (m residentMods) WithExistingPhoneMobilePhone(em *models.CommsPhone) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.PhoneMobilePhone = &residentRPhoneMobilePhoneR{ + o: o.f.FromExistingCommsPhone(em), + } + }) +} + +func (m residentMods) WithoutPhoneMobilePhone() ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.PhoneMobilePhone = nil + }) +} + +func (m residentMods) WithSite(rel *SiteTemplate) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Site = &residentRSiteR{ + o: rel, + } + }) +} + +func (m residentMods) WithNewSite(mods ...SiteMod) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + related := o.f.NewSiteWithContext(ctx, mods...) + + m.WithSite(related).Apply(ctx, o) + }) +} + +func (m residentMods) WithExistingSite(em *models.Site) ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Site = &residentRSiteR{ + o: o.f.FromExistingSite(em), + } + }) +} + +func (m residentMods) WithoutSite() ResidentMod { + return ResidentModFunc(func(ctx context.Context, o *ResidentTemplate) { + o.r.Site = nil + }) +} diff --git a/db/factory/site.bob.go b/db/factory/site.bob.go index c9733f9e..ddaad081 100644 --- a/db/factory/site.bob.go +++ b/db/factory/site.bob.go @@ -38,19 +38,19 @@ func (mods SiteModSlice) Apply(ctx context.Context, n *SiteTemplate) { // SiteTemplate is an object representing the database table. // all columns are optional and should be set by mods type SiteTemplate struct { - AddressID func() int32 - Created func() time.Time - CreatorID func() int32 - FileID func() null.Val[int32] - ID func() int32 - Notes func() string - OrganizationID func() int32 - OwnerName func() string - OwnerPhoneE164 func() null.Val[string] - ResidentOwned func() null.Val[bool] - ResidentPhoneE164 func() null.Val[string] - Tags func() pgtypes.HStore - Version func() int32 + AddressID func() int32 + Created func() time.Time + CreatorID func() int32 + FileID func() null.Val[int32] + ID func() int32 + Notes func() string + OrganizationID func() int32 + OwnerName func() string + OwnerPhoneE164 func() null.Val[string] + ParcelID func() int32 + ResidentOwned func() null.Val[bool] + Tags func() pgtypes.HStore + Version func() int32 r siteR f *Factory @@ -59,11 +59,27 @@ type SiteTemplate struct { } type siteR struct { - Address *siteRAddressR - CreatorUser *siteRCreatorUserR - File *siteRFileR + ComplianceReportRequests []*siteRComplianceReportRequestsR + Pools []*siteRPoolsR + Residents []*siteRResidentsR + Address *siteRAddressR + CreatorUser *siteRCreatorUserR + File *siteRFileR + Parcel *siteRParcelR } +type siteRComplianceReportRequestsR struct { + number int + o *ComplianceReportRequestTemplate +} +type siteRPoolsR struct { + number int + o *PoolTemplate +} +type siteRResidentsR struct { + number int + o *ResidentTemplate +} type siteRAddressR struct { o *AddressTemplate } @@ -73,6 +89,9 @@ type siteRCreatorUserR struct { type siteRFileR struct { o *FileuploadFileTemplate } +type siteRParcelR struct { + o *ParcelTemplate +} // Apply mods to the SiteTemplate func (o *SiteTemplate) Apply(ctx context.Context, mods ...SiteMod) { @@ -84,6 +103,48 @@ func (o *SiteTemplate) Apply(ctx context.Context, mods ...SiteMod) { // setModelRels creates and sets the relationships on *models.Site // according to the relationships in the template. Nothing is inserted into the db func (t SiteTemplate) setModelRels(o *models.Site) { + if t.r.ComplianceReportRequests != nil { + rel := models.ComplianceReportRequestSlice{} + for _, r := range t.r.ComplianceReportRequests { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.SiteID = o.ID // h2 + rel.SiteVersion = o.Version // h2 + rel.R.Site = o + } + rel = append(rel, related...) + } + o.R.ComplianceReportRequests = rel + } + + if t.r.Pools != nil { + rel := models.PoolSlice{} + for _, r := range t.r.Pools { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.SiteID = o.ID // h2 + rel.SiteVersion = o.Version // h2 + rel.R.Site = o + } + rel = append(rel, related...) + } + o.R.Pools = rel + } + + if t.r.Residents != nil { + rel := models.ResidentSlice{} + for _, r := range t.r.Residents { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.SiteID = o.ID // h2 + rel.SiteVersion = o.Version // h2 + rel.R.Site = o + } + rel = append(rel, related...) + } + o.R.Residents = rel + } + if t.r.Address != nil { rel := t.r.Address.o.Build() rel.R.Site = o @@ -104,6 +165,13 @@ func (t SiteTemplate) setModelRels(o *models.Site) { o.FileID = null.From(rel.ID) // h2 o.R.File = rel } + + if t.r.Parcel != nil { + rel := t.r.Parcel.o.Build() + rel.R.Sites = append(rel.R.Sites, o) + o.ParcelID = rel.ID // h2 + o.R.Parcel = rel + } } // BuildSetter returns an *models.SiteSetter @@ -147,14 +215,14 @@ func (o SiteTemplate) BuildSetter() *models.SiteSetter { val := o.OwnerPhoneE164() m.OwnerPhoneE164 = omitnull.FromNull(val) } + if o.ParcelID != nil { + val := o.ParcelID() + m.ParcelID = omit.From(val) + } if o.ResidentOwned != nil { val := o.ResidentOwned() m.ResidentOwned = omitnull.FromNull(val) } - if o.ResidentPhoneE164 != nil { - val := o.ResidentPhoneE164() - m.ResidentPhoneE164 = omitnull.FromNull(val) - } if o.Tags != nil { val := o.Tags() m.Tags = omit.From(val) @@ -212,12 +280,12 @@ func (o SiteTemplate) Build() *models.Site { if o.OwnerPhoneE164 != nil { m.OwnerPhoneE164 = o.OwnerPhoneE164() } + if o.ParcelID != nil { + m.ParcelID = o.ParcelID() + } if o.ResidentOwned != nil { m.ResidentOwned = o.ResidentOwned() } - if o.ResidentPhoneE164 != nil { - m.ResidentPhoneE164 = o.ResidentPhoneE164() - } if o.Tags != nil { m.Tags = o.Tags() } @@ -268,6 +336,10 @@ func ensureCreatableSite(m *models.SiteSetter) { val := random_string(nil) m.OwnerName = omit.From(val) } + if !(m.ParcelID.IsValue()) { + val := random_int32(nil) + m.ParcelID = omit.From(val) + } if !(m.Tags.IsValue()) { val := random_pgtypes_HStore(nil) m.Tags = omit.From(val) @@ -284,18 +356,78 @@ func ensureCreatableSite(m *models.SiteSetter) { func (o *SiteTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.Site) error { var err error + isComplianceReportRequestsDone, _ := siteRelComplianceReportRequestsCtx.Value(ctx) + if !isComplianceReportRequestsDone && o.r.ComplianceReportRequests != nil { + ctx = siteRelComplianceReportRequestsCtx.WithValue(ctx, true) + for _, r := range o.r.ComplianceReportRequests { + if r.o.alreadyPersisted { + m.R.ComplianceReportRequests = append(m.R.ComplianceReportRequests, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachComplianceReportRequests(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + + isPoolsDone, _ := siteRelPoolsCtx.Value(ctx) + if !isPoolsDone && o.r.Pools != nil { + ctx = siteRelPoolsCtx.WithValue(ctx, true) + for _, r := range o.r.Pools { + if r.o.alreadyPersisted { + m.R.Pools = append(m.R.Pools, r.o.Build()) + } else { + rel1, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachPools(ctx, exec, rel1...) + if err != nil { + return err + } + } + } + } + + isResidentsDone, _ := siteRelResidentsCtx.Value(ctx) + if !isResidentsDone && o.r.Residents != nil { + ctx = siteRelResidentsCtx.WithValue(ctx, true) + for _, r := range o.r.Residents { + if r.o.alreadyPersisted { + m.R.Residents = append(m.R.Residents, r.o.Build()) + } else { + rel2, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachResidents(ctx, exec, rel2...) + if err != nil { + return err + } + } + } + } + isFileDone, _ := siteRelFileCtx.Value(ctx) if !isFileDone && o.r.File != nil { ctx = siteRelFileCtx.WithValue(ctx, true) if o.r.File.o.alreadyPersisted { m.R.File = o.r.File.o.Build() } else { - var rel2 *models.FileuploadFile - rel2, err = o.r.File.o.Create(ctx, exec) + var rel5 *models.FileuploadFile + rel5, err = o.r.File.o.Create(ctx, exec) if err != nil { return err } - err = m.AttachFile(ctx, exec, rel2) + err = m.AttachFile(ctx, exec, rel5) if err != nil { return err } @@ -317,43 +449,61 @@ func (o *SiteTemplate) Create(ctx context.Context, exec bob.Executor) (*models.S SiteMods.WithNewAddress().Apply(ctx, o) } - var rel0 *models.Address + var rel3 *models.Address if o.r.Address.o.alreadyPersisted { - rel0 = o.r.Address.o.Build() + rel3 = o.r.Address.o.Build() } else { - rel0, err = o.r.Address.o.Create(ctx, exec) + rel3, err = o.r.Address.o.Create(ctx, exec) if err != nil { return nil, err } } - opt.AddressID = omit.From(rel0.ID) + opt.AddressID = omit.From(rel3.ID) if o.r.CreatorUser == nil { SiteMods.WithNewCreatorUser().Apply(ctx, o) } - var rel1 *models.User + var rel4 *models.User if o.r.CreatorUser.o.alreadyPersisted { - rel1 = o.r.CreatorUser.o.Build() + rel4 = o.r.CreatorUser.o.Build() } else { - rel1, err = o.r.CreatorUser.o.Create(ctx, exec) + rel4, err = o.r.CreatorUser.o.Create(ctx, exec) if err != nil { return nil, err } } - opt.CreatorID = omit.From(rel1.ID) + opt.CreatorID = omit.From(rel4.ID) + + if o.r.Parcel == nil { + SiteMods.WithNewParcel().Apply(ctx, o) + } + + var rel6 *models.Parcel + + if o.r.Parcel.o.alreadyPersisted { + rel6 = o.r.Parcel.o.Build() + } else { + rel6, err = o.r.Parcel.o.Create(ctx, exec) + if err != nil { + return nil, err + } + } + + opt.ParcelID = omit.From(rel6.ID) m, err := models.Sites.Insert(opt).One(ctx, exec) if err != nil { return nil, err } - m.R.Address = rel0 - m.R.CreatorUser = rel1 + m.R.Address = rel3 + m.R.CreatorUser = rel4 + m.R.Parcel = rel6 if err := o.insertOptRels(ctx, exec, m); err != nil { return nil, err @@ -441,8 +591,8 @@ func (m siteMods) RandomizeAllColumns(f *faker.Faker) SiteMod { SiteMods.RandomOrganizationID(f), SiteMods.RandomOwnerName(f), SiteMods.RandomOwnerPhoneE164(f), + SiteMods.RandomParcelID(f), SiteMods.RandomResidentOwned(f), - SiteMods.RandomResidentPhoneE164(f), SiteMods.RandomTags(f), SiteMods.RandomVersion(f), } @@ -771,6 +921,37 @@ func (m siteMods) RandomOwnerPhoneE164NotNull(f *faker.Faker) SiteMod { }) } +// Set the model columns to this value +func (m siteMods) ParcelID(val int32) SiteMod { + return SiteModFunc(func(_ context.Context, o *SiteTemplate) { + o.ParcelID = func() int32 { return val } + }) +} + +// Set the Column from the function +func (m siteMods) ParcelIDFunc(f func() int32) SiteMod { + return SiteModFunc(func(_ context.Context, o *SiteTemplate) { + o.ParcelID = f + }) +} + +// Clear any values for the column +func (m siteMods) UnsetParcelID() SiteMod { + return SiteModFunc(func(_ context.Context, o *SiteTemplate) { + o.ParcelID = nil + }) +} + +// Generates a random value for the column using the given faker +// if faker is nil, a default faker is used +func (m siteMods) RandomParcelID(f *faker.Faker) SiteMod { + return SiteModFunc(func(_ context.Context, o *SiteTemplate) { + o.ParcelID = func() int32 { + return random_int32(f) + } + }) +} + // Set the model columns to this value func (m siteMods) ResidentOwned(val null.Val[bool]) SiteMod { return SiteModFunc(func(_ context.Context, o *SiteTemplate) { @@ -824,59 +1005,6 @@ func (m siteMods) RandomResidentOwnedNotNull(f *faker.Faker) SiteMod { }) } -// Set the model columns to this value -func (m siteMods) ResidentPhoneE164(val null.Val[string]) SiteMod { - return SiteModFunc(func(_ context.Context, o *SiteTemplate) { - o.ResidentPhoneE164 = func() null.Val[string] { return val } - }) -} - -// Set the Column from the function -func (m siteMods) ResidentPhoneE164Func(f func() null.Val[string]) SiteMod { - return SiteModFunc(func(_ context.Context, o *SiteTemplate) { - o.ResidentPhoneE164 = f - }) -} - -// Clear any values for the column -func (m siteMods) UnsetResidentPhoneE164() SiteMod { - return SiteModFunc(func(_ context.Context, o *SiteTemplate) { - o.ResidentPhoneE164 = nil - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is sometimes null -func (m siteMods) RandomResidentPhoneE164(f *faker.Faker) SiteMod { - return SiteModFunc(func(_ context.Context, o *SiteTemplate) { - o.ResidentPhoneE164 = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - -// Generates a random value for the column using the given faker -// if faker is nil, a default faker is used -// The generated value is never null -func (m siteMods) RandomResidentPhoneE164NotNull(f *faker.Faker) SiteMod { - return SiteModFunc(func(_ context.Context, o *SiteTemplate) { - o.ResidentPhoneE164 = func() null.Val[string] { - if f == nil { - f = &defaultFaker - } - - val := random_string(f) - return null.From(val) - } - }) -} - // Set the model columns to this value func (m siteMods) Tags(val pgtypes.HStore) SiteMod { return SiteModFunc(func(_ context.Context, o *SiteTemplate) { @@ -960,6 +1088,11 @@ func (m siteMods) WithParentsCascading() SiteMod { related := o.f.NewFileuploadFileWithContext(ctx, FileuploadFileMods.WithParentsCascading()) m.WithFile(related).Apply(ctx, o) } + { + + related := o.f.NewParcelWithContext(ctx, ParcelMods.WithParentsCascading()) + m.WithParcel(related).Apply(ctx, o) + } }) } @@ -1052,3 +1185,177 @@ func (m siteMods) WithoutFile() SiteMod { o.r.File = nil }) } + +func (m siteMods) WithParcel(rel *ParcelTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Parcel = &siteRParcelR{ + o: rel, + } + }) +} + +func (m siteMods) WithNewParcel(mods ...ParcelMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewParcelWithContext(ctx, mods...) + + m.WithParcel(related).Apply(ctx, o) + }) +} + +func (m siteMods) WithExistingParcel(em *models.Parcel) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Parcel = &siteRParcelR{ + o: o.f.FromExistingParcel(em), + } + }) +} + +func (m siteMods) WithoutParcel() SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Parcel = nil + }) +} + +func (m siteMods) WithComplianceReportRequests(number int, related *ComplianceReportRequestTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.ComplianceReportRequests = []*siteRComplianceReportRequestsR{{ + number: number, + o: related, + }} + }) +} + +func (m siteMods) WithNewComplianceReportRequests(number int, mods ...ComplianceReportRequestMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewComplianceReportRequestWithContext(ctx, mods...) + m.WithComplianceReportRequests(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddComplianceReportRequests(number int, related *ComplianceReportRequestTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.ComplianceReportRequests = append(o.r.ComplianceReportRequests, &siteRComplianceReportRequestsR{ + number: number, + o: related, + }) + }) +} + +func (m siteMods) AddNewComplianceReportRequests(number int, mods ...ComplianceReportRequestMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewComplianceReportRequestWithContext(ctx, mods...) + m.AddComplianceReportRequests(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddExistingComplianceReportRequests(existingModels ...*models.ComplianceReportRequest) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + for _, em := range existingModels { + o.r.ComplianceReportRequests = append(o.r.ComplianceReportRequests, &siteRComplianceReportRequestsR{ + o: o.f.FromExistingComplianceReportRequest(em), + }) + } + }) +} + +func (m siteMods) WithoutComplianceReportRequests() SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.ComplianceReportRequests = nil + }) +} + +func (m siteMods) WithPools(number int, related *PoolTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Pools = []*siteRPoolsR{{ + number: number, + o: related, + }} + }) +} + +func (m siteMods) WithNewPools(number int, mods ...PoolMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewPoolWithContext(ctx, mods...) + m.WithPools(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddPools(number int, related *PoolTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Pools = append(o.r.Pools, &siteRPoolsR{ + number: number, + o: related, + }) + }) +} + +func (m siteMods) AddNewPools(number int, mods ...PoolMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewPoolWithContext(ctx, mods...) + m.AddPools(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddExistingPools(existingModels ...*models.Pool) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + for _, em := range existingModels { + o.r.Pools = append(o.r.Pools, &siteRPoolsR{ + o: o.f.FromExistingPool(em), + }) + } + }) +} + +func (m siteMods) WithoutPools() SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Pools = nil + }) +} + +func (m siteMods) WithResidents(number int, related *ResidentTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Residents = []*siteRResidentsR{{ + number: number, + o: related, + }} + }) +} + +func (m siteMods) WithNewResidents(number int, mods ...ResidentMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.WithResidents(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddResidents(number int, related *ResidentTemplate) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Residents = append(o.r.Residents, &siteRResidentsR{ + number: number, + o: related, + }) + }) +} + +func (m siteMods) AddNewResidents(number int, mods ...ResidentMod) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.AddResidents(number, related).Apply(ctx, o) + }) +} + +func (m siteMods) AddExistingResidents(existingModels ...*models.Resident) SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + for _, em := range existingModels { + o.r.Residents = append(o.r.Residents, &siteRResidentsR{ + o: o.f.FromExistingResident(em), + }) + } + }) +} + +func (m siteMods) WithoutResidents() SiteMod { + return SiteModFunc(func(ctx context.Context, o *SiteTemplate) { + o.r.Residents = nil + }) +} diff --git a/db/factory/user_.bob.go b/db/factory/user_.bob.go index 87bcc9cf..22d66a94 100644 --- a/db/factory/user_.bob.go +++ b/db/factory/user_.bob.go @@ -59,24 +59,34 @@ type UserTemplate struct { } type userR struct { - PublicUserUser []*userRPublicUserUserR - CreatorFiles []*userRCreatorFilesR - FileuploadPool []*userRFileuploadPoolR - CreatorNoteAudios []*userRCreatorNoteAudiosR - DeletorNoteAudios []*userRDeletorNoteAudiosR - CreatorNoteImages []*userRCreatorNoteImagesR - DeletorNoteImages []*userRDeletorNoteImagesR - UserNotifications []*userRUserNotificationsR - UserOauthTokens []*userRUserOauthTokensR - CreatorPools []*userRCreatorPoolsR - CreatorSites []*userRCreatorSitesR - Organization *userROrganizationR + UserOauthTokens []*userRUserOauthTokensR + PublicUserUser []*userRPublicUserUserR + CreatorComplianceReportRequests []*userRCreatorComplianceReportRequestsR + CreatorFiles []*userRCreatorFilesR + FileuploadPool []*userRFileuploadPoolR + CreatorNoteAudios []*userRCreatorNoteAudiosR + DeletorNoteAudios []*userRDeletorNoteAudiosR + CreatorNoteImages []*userRCreatorNoteImagesR + DeletorNoteImages []*userRDeletorNoteImagesR + UserNotifications []*userRUserNotificationsR + CreatorPools []*userRCreatorPoolsR + CreatorResidents []*userRCreatorResidentsR + CreatorSites []*userRCreatorSitesR + Organization *userROrganizationR } +type userRUserOauthTokensR struct { + number int + o *ArcgisOauthTokenTemplate +} type userRPublicUserUserR struct { number int o *ArcgisUserTemplate } +type userRCreatorComplianceReportRequestsR struct { + number int + o *ComplianceReportRequestTemplate +} type userRCreatorFilesR struct { number int o *FileuploadFileTemplate @@ -105,14 +115,14 @@ type userRUserNotificationsR struct { number int o *NotificationTemplate } -type userRUserOauthTokensR struct { - number int - o *OauthTokenTemplate -} type userRCreatorPoolsR struct { number int o *PoolTemplate } +type userRCreatorResidentsR struct { + number int + o *ResidentTemplate +} type userRCreatorSitesR struct { number int o *SiteTemplate @@ -131,6 +141,19 @@ func (o *UserTemplate) Apply(ctx context.Context, mods ...UserMod) { // setModelRels creates and sets the relationships on *models.User // according to the relationships in the template. Nothing is inserted into the db func (t UserTemplate) setModelRels(o *models.User) { + if t.r.UserOauthTokens != nil { + rel := models.ArcgisOauthTokenSlice{} + for _, r := range t.r.UserOauthTokens { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.UserID = o.ID // h2 + rel.R.UserUser = o + } + rel = append(rel, related...) + } + o.R.UserOauthTokens = rel + } + if t.r.PublicUserUser != nil { rel := models.ArcgisUserSlice{} for _, r := range t.r.PublicUserUser { @@ -144,6 +167,19 @@ func (t UserTemplate) setModelRels(o *models.User) { o.R.PublicUserUser = rel } + if t.r.CreatorComplianceReportRequests != nil { + rel := models.ComplianceReportRequestSlice{} + for _, r := range t.r.CreatorComplianceReportRequests { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.Creator = o.ID // h2 + rel.R.CreatorUser = o + } + rel = append(rel, related...) + } + o.R.CreatorComplianceReportRequests = rel + } + if t.r.CreatorFiles != nil { rel := models.FileuploadFileSlice{} for _, r := range t.r.CreatorFiles { @@ -235,19 +271,6 @@ func (t UserTemplate) setModelRels(o *models.User) { o.R.UserNotifications = rel } - if t.r.UserOauthTokens != nil { - rel := models.OauthTokenSlice{} - for _, r := range t.r.UserOauthTokens { - related := r.o.BuildMany(r.number) - for _, rel := range related { - rel.UserID = o.ID // h2 - rel.R.UserUser = o - } - rel = append(rel, related...) - } - o.R.UserOauthTokens = rel - } - if t.r.CreatorPools != nil { rel := models.PoolSlice{} for _, r := range t.r.CreatorPools { @@ -261,6 +284,19 @@ func (t UserTemplate) setModelRels(o *models.User) { o.R.CreatorPools = rel } + if t.r.CreatorResidents != nil { + rel := models.ResidentSlice{} + for _, r := range t.r.CreatorResidents { + related := r.o.BuildMany(r.number) + for _, rel := range related { + rel.Creator = o.ID // h2 + rel.R.CreatorUser = o + } + rel = append(rel, related...) + } + o.R.CreatorResidents = rel + } + if t.r.CreatorSites != nil { rel := models.SiteSlice{} for _, r := range t.r.CreatorSites { @@ -452,6 +488,26 @@ func ensureCreatableUser(m *models.UserSetter) { func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m *models.User) error { var err error + isUserOauthTokensDone, _ := userRelUserOauthTokensCtx.Value(ctx) + if !isUserOauthTokensDone && o.r.UserOauthTokens != nil { + ctx = userRelUserOauthTokensCtx.WithValue(ctx, true) + for _, r := range o.r.UserOauthTokens { + if r.o.alreadyPersisted { + m.R.UserOauthTokens = append(m.R.UserOauthTokens, r.o.Build()) + } else { + rel0, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachUserOauthTokens(ctx, exec, rel0...) + if err != nil { + return err + } + } + } + } + isPublicUserUserDone, _ := userRelPublicUserUserCtx.Value(ctx) if !isPublicUserUserDone && o.r.PublicUserUser != nil { ctx = userRelPublicUserUserCtx.WithValue(ctx, true) @@ -459,12 +515,32 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.PublicUserUser = append(m.R.PublicUserUser, r.o.Build()) } else { - rel0, err := r.o.CreateMany(ctx, exec, r.number) + rel1, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachPublicUserUser(ctx, exec, rel0...) + err = m.AttachPublicUserUser(ctx, exec, rel1...) + if err != nil { + return err + } + } + } + } + + isCreatorComplianceReportRequestsDone, _ := userRelCreatorComplianceReportRequestsCtx.Value(ctx) + if !isCreatorComplianceReportRequestsDone && o.r.CreatorComplianceReportRequests != nil { + ctx = userRelCreatorComplianceReportRequestsCtx.WithValue(ctx, true) + for _, r := range o.r.CreatorComplianceReportRequests { + if r.o.alreadyPersisted { + m.R.CreatorComplianceReportRequests = append(m.R.CreatorComplianceReportRequests, r.o.Build()) + } else { + rel2, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachCreatorComplianceReportRequests(ctx, exec, rel2...) if err != nil { return err } @@ -479,12 +555,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.CreatorFiles = append(m.R.CreatorFiles, r.o.Build()) } else { - rel1, err := r.o.CreateMany(ctx, exec, r.number) + rel3, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachCreatorFiles(ctx, exec, rel1...) + err = m.AttachCreatorFiles(ctx, exec, rel3...) if err != nil { return err } @@ -499,12 +575,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.FileuploadPool = append(m.R.FileuploadPool, r.o.Build()) } else { - rel2, err := r.o.CreateMany(ctx, exec, r.number) + rel4, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachFileuploadPool(ctx, exec, rel2...) + err = m.AttachFileuploadPool(ctx, exec, rel4...) if err != nil { return err } @@ -519,12 +595,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.CreatorNoteAudios = append(m.R.CreatorNoteAudios, r.o.Build()) } else { - rel3, err := r.o.CreateMany(ctx, exec, r.number) + rel5, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachCreatorNoteAudios(ctx, exec, rel3...) + err = m.AttachCreatorNoteAudios(ctx, exec, rel5...) if err != nil { return err } @@ -539,12 +615,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.DeletorNoteAudios = append(m.R.DeletorNoteAudios, r.o.Build()) } else { - rel4, err := r.o.CreateMany(ctx, exec, r.number) + rel6, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachDeletorNoteAudios(ctx, exec, rel4...) + err = m.AttachDeletorNoteAudios(ctx, exec, rel6...) if err != nil { return err } @@ -559,12 +635,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.CreatorNoteImages = append(m.R.CreatorNoteImages, r.o.Build()) } else { - rel5, err := r.o.CreateMany(ctx, exec, r.number) + rel7, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachCreatorNoteImages(ctx, exec, rel5...) + err = m.AttachCreatorNoteImages(ctx, exec, rel7...) if err != nil { return err } @@ -579,12 +655,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.DeletorNoteImages = append(m.R.DeletorNoteImages, r.o.Build()) } else { - rel6, err := r.o.CreateMany(ctx, exec, r.number) + rel8, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachDeletorNoteImages(ctx, exec, rel6...) + err = m.AttachDeletorNoteImages(ctx, exec, rel8...) if err != nil { return err } @@ -599,32 +675,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.UserNotifications = append(m.R.UserNotifications, r.o.Build()) } else { - rel7, err := r.o.CreateMany(ctx, exec, r.number) + rel9, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachUserNotifications(ctx, exec, rel7...) - if err != nil { - return err - } - } - } - } - - isUserOauthTokensDone, _ := userRelUserOauthTokensCtx.Value(ctx) - if !isUserOauthTokensDone && o.r.UserOauthTokens != nil { - ctx = userRelUserOauthTokensCtx.WithValue(ctx, true) - for _, r := range o.r.UserOauthTokens { - if r.o.alreadyPersisted { - m.R.UserOauthTokens = append(m.R.UserOauthTokens, r.o.Build()) - } else { - rel8, err := r.o.CreateMany(ctx, exec, r.number) - if err != nil { - return err - } - - err = m.AttachUserOauthTokens(ctx, exec, rel8...) + err = m.AttachUserNotifications(ctx, exec, rel9...) if err != nil { return err } @@ -639,12 +695,32 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.CreatorPools = append(m.R.CreatorPools, r.o.Build()) } else { - rel9, err := r.o.CreateMany(ctx, exec, r.number) + rel10, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachCreatorPools(ctx, exec, rel9...) + err = m.AttachCreatorPools(ctx, exec, rel10...) + if err != nil { + return err + } + } + } + } + + isCreatorResidentsDone, _ := userRelCreatorResidentsCtx.Value(ctx) + if !isCreatorResidentsDone && o.r.CreatorResidents != nil { + ctx = userRelCreatorResidentsCtx.WithValue(ctx, true) + for _, r := range o.r.CreatorResidents { + if r.o.alreadyPersisted { + m.R.CreatorResidents = append(m.R.CreatorResidents, r.o.Build()) + } else { + rel11, err := r.o.CreateMany(ctx, exec, r.number) + if err != nil { + return err + } + + err = m.AttachCreatorResidents(ctx, exec, rel11...) if err != nil { return err } @@ -659,12 +735,12 @@ func (o *UserTemplate) insertOptRels(ctx context.Context, exec bob.Executor, m * if r.o.alreadyPersisted { m.R.CreatorSites = append(m.R.CreatorSites, r.o.Build()) } else { - rel10, err := r.o.CreateMany(ctx, exec, r.number) + rel12, err := r.o.CreateMany(ctx, exec, r.number) if err != nil { return err } - err = m.AttachCreatorSites(ctx, exec, rel10...) + err = m.AttachCreatorSites(ctx, exec, rel12...) if err != nil { return err } @@ -686,25 +762,25 @@ func (o *UserTemplate) Create(ctx context.Context, exec bob.Executor) (*models.U UserMods.WithNewOrganization().Apply(ctx, o) } - var rel11 *models.Organization + var rel13 *models.Organization if o.r.Organization.o.alreadyPersisted { - rel11 = o.r.Organization.o.Build() + rel13 = o.r.Organization.o.Build() } else { - rel11, err = o.r.Organization.o.Create(ctx, exec) + rel13, err = o.r.Organization.o.Create(ctx, exec) if err != nil { return nil, err } } - opt.OrganizationID = omit.From(rel11.ID) + opt.OrganizationID = omit.From(rel13.ID) m, err := models.Users.Insert(opt).One(ctx, exec) if err != nil { return nil, err } - m.R.Organization = rel11 + m.R.Organization = rel13 if err := o.insertOptRels(ctx, exec, m); err != nil { return nil, err @@ -1378,6 +1454,54 @@ func (m userMods) WithoutOrganization() UserMod { }) } +func (m userMods) WithUserOauthTokens(number int, related *ArcgisOauthTokenTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserOauthTokens = []*userRUserOauthTokensR{{ + number: number, + o: related, + }} + }) +} + +func (m userMods) WithNewUserOauthTokens(number int, mods ...ArcgisOauthTokenMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewArcgisOauthTokenWithContext(ctx, mods...) + m.WithUserOauthTokens(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddUserOauthTokens(number int, related *ArcgisOauthTokenTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserOauthTokens = append(o.r.UserOauthTokens, &userRUserOauthTokensR{ + number: number, + o: related, + }) + }) +} + +func (m userMods) AddNewUserOauthTokens(number int, mods ...ArcgisOauthTokenMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewArcgisOauthTokenWithContext(ctx, mods...) + m.AddUserOauthTokens(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddExistingUserOauthTokens(existingModels ...*models.ArcgisOauthToken) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + for _, em := range existingModels { + o.r.UserOauthTokens = append(o.r.UserOauthTokens, &userRUserOauthTokensR{ + o: o.f.FromExistingArcgisOauthToken(em), + }) + } + }) +} + +func (m userMods) WithoutUserOauthTokens() UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.UserOauthTokens = nil + }) +} + func (m userMods) WithPublicUserUser(number int, related *ArcgisUserTemplate) UserMod { return UserModFunc(func(ctx context.Context, o *UserTemplate) { o.r.PublicUserUser = []*userRPublicUserUserR{{ @@ -1426,6 +1550,54 @@ func (m userMods) WithoutPublicUserUser() UserMod { }) } +func (m userMods) WithCreatorComplianceReportRequests(number int, related *ComplianceReportRequestTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorComplianceReportRequests = []*userRCreatorComplianceReportRequestsR{{ + number: number, + o: related, + }} + }) +} + +func (m userMods) WithNewCreatorComplianceReportRequests(number int, mods ...ComplianceReportRequestMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewComplianceReportRequestWithContext(ctx, mods...) + m.WithCreatorComplianceReportRequests(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddCreatorComplianceReportRequests(number int, related *ComplianceReportRequestTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorComplianceReportRequests = append(o.r.CreatorComplianceReportRequests, &userRCreatorComplianceReportRequestsR{ + number: number, + o: related, + }) + }) +} + +func (m userMods) AddNewCreatorComplianceReportRequests(number int, mods ...ComplianceReportRequestMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewComplianceReportRequestWithContext(ctx, mods...) + m.AddCreatorComplianceReportRequests(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddExistingCreatorComplianceReportRequests(existingModels ...*models.ComplianceReportRequest) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + for _, em := range existingModels { + o.r.CreatorComplianceReportRequests = append(o.r.CreatorComplianceReportRequests, &userRCreatorComplianceReportRequestsR{ + o: o.f.FromExistingComplianceReportRequest(em), + }) + } + }) +} + +func (m userMods) WithoutCreatorComplianceReportRequests() UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorComplianceReportRequests = nil + }) +} + func (m userMods) WithCreatorFiles(number int, related *FileuploadFileTemplate) UserMod { return UserModFunc(func(ctx context.Context, o *UserTemplate) { o.r.CreatorFiles = []*userRCreatorFilesR{{ @@ -1762,54 +1934,6 @@ func (m userMods) WithoutUserNotifications() UserMod { }) } -func (m userMods) WithUserOauthTokens(number int, related *OauthTokenTemplate) UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - o.r.UserOauthTokens = []*userRUserOauthTokensR{{ - number: number, - o: related, - }} - }) -} - -func (m userMods) WithNewUserOauthTokens(number int, mods ...OauthTokenMod) UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - related := o.f.NewOauthTokenWithContext(ctx, mods...) - m.WithUserOauthTokens(number, related).Apply(ctx, o) - }) -} - -func (m userMods) AddUserOauthTokens(number int, related *OauthTokenTemplate) UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - o.r.UserOauthTokens = append(o.r.UserOauthTokens, &userRUserOauthTokensR{ - number: number, - o: related, - }) - }) -} - -func (m userMods) AddNewUserOauthTokens(number int, mods ...OauthTokenMod) UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - related := o.f.NewOauthTokenWithContext(ctx, mods...) - m.AddUserOauthTokens(number, related).Apply(ctx, o) - }) -} - -func (m userMods) AddExistingUserOauthTokens(existingModels ...*models.OauthToken) UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - for _, em := range existingModels { - o.r.UserOauthTokens = append(o.r.UserOauthTokens, &userRUserOauthTokensR{ - o: o.f.FromExistingOauthToken(em), - }) - } - }) -} - -func (m userMods) WithoutUserOauthTokens() UserMod { - return UserModFunc(func(ctx context.Context, o *UserTemplate) { - o.r.UserOauthTokens = nil - }) -} - func (m userMods) WithCreatorPools(number int, related *PoolTemplate) UserMod { return UserModFunc(func(ctx context.Context, o *UserTemplate) { o.r.CreatorPools = []*userRCreatorPoolsR{{ @@ -1858,6 +1982,54 @@ func (m userMods) WithoutCreatorPools() UserMod { }) } +func (m userMods) WithCreatorResidents(number int, related *ResidentTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorResidents = []*userRCreatorResidentsR{{ + number: number, + o: related, + }} + }) +} + +func (m userMods) WithNewCreatorResidents(number int, mods ...ResidentMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.WithCreatorResidents(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddCreatorResidents(number int, related *ResidentTemplate) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorResidents = append(o.r.CreatorResidents, &userRCreatorResidentsR{ + number: number, + o: related, + }) + }) +} + +func (m userMods) AddNewCreatorResidents(number int, mods ...ResidentMod) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + related := o.f.NewResidentWithContext(ctx, mods...) + m.AddCreatorResidents(number, related).Apply(ctx, o) + }) +} + +func (m userMods) AddExistingCreatorResidents(existingModels ...*models.Resident) UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + for _, em := range existingModels { + o.r.CreatorResidents = append(o.r.CreatorResidents, &userRCreatorResidentsR{ + o: o.f.FromExistingResident(em), + }) + } + }) +} + +func (m userMods) WithoutCreatorResidents() UserMod { + return UserModFunc(func(ctx context.Context, o *UserTemplate) { + o.r.CreatorResidents = nil + }) +} + func (m userMods) WithCreatorSites(number int, related *SiteTemplate) UserMod { return UserModFunc(func(ctx context.Context, o *UserTemplate) { o.r.CreatorSites = []*userRCreatorSitesR{{ diff --git a/db/migrations/00068_site.sql b/db/migrations/00068_site.sql index 0a1c1574..1106a91a 100644 --- a/db/migrations/00068_site.sql +++ b/db/migrations/00068_site.sql @@ -14,9 +14,15 @@ CREATE TABLE address ( street TEXT NOT NULL, unit TEXT NOT NULL, PRIMARY KEY(id), - UNIQUE(country, locality, number_, street) + UNIQUE(country, locality, unit, number_, street) +); +CREATE TABLE parcel ( + apn TEXT, + description TEXT, + id SERIAL NOT NULL, + geometry geometry(MultiPolygon, 4326) NOT NULL, + PRIMARY KEY(id) ); - CREATE TABLE site ( address_id INTEGER REFERENCES address(id) NOT NULL, created TIMESTAMP WITHOUT TIME ZONE NOT NULL, @@ -27,13 +33,26 @@ CREATE TABLE site ( organization_id INTEGER NOT NULL, owner_name TEXT NOT NULL, owner_phone_e164 TEXT, + parcel_id INTEGER REFERENCES parcel(id) NOT NULL, resident_owned BOOLEAN, - resident_phone_e164 TEXT, tags HSTORE NOT NULL, version INTEGER NOT NULL, PRIMARY KEY(id, version), UNIQUE(address_id) ); +CREATE TABLE resident ( + address_id INTEGER REFERENCES address(id) NOT NULL, + created TIMESTAMP WITHOUT TIME ZONE NOT NULL, + creator INTEGER REFERENCES user_(id) NOT NULL, + id SERIAL NOT NULL, + name TEXT NOT NULL, + phone_mobile TEXT REFERENCES comms.phone(e164), + site_id INTEGER NOT NULL, + site_version INTEGER NOT NULL, + PRIMARY KEY(id), + FOREIGN KEY(site_id, site_version) REFERENCES site(id, version) +); + CREATE TYPE PoolConditionType AS ENUM ( 'blue', @@ -47,6 +66,16 @@ CREATE TABLE pool ( created TIMESTAMP WITHOUT TIME ZONE NOT NULL, creator_id INTEGER REFERENCES user_(id) NOT NULL, id SERIAL NOT NULL, - site_id INTEGER, - PRIMARY KEY(id) + site_id INTEGER NOT NULL, + site_version INTEGER NOT NULL, + PRIMARY KEY(id), + FOREIGN KEY(site_id, site_version) REFERENCES site(id, version) ); +-- +goose Down +DROP TABLE pool; +DROP TYPE PoolConditionType; +DROP TABLE resident; +DROP TABLE site; +DROP TABLE parcel; +DROP TABLE address; +DROP TYPE CountryType; diff --git a/db/migrations/00069_arcgis_layer.sql b/db/migrations/00069_arcgis_layer.sql index e223dc3e..5ef4e8ee 100644 --- a/db/migrations/00069_arcgis_layer.sql +++ b/db/migrations/00069_arcgis_layer.sql @@ -66,10 +66,12 @@ CREATE TABLE arcgis.address_mapping ( FOREIGN KEY(layer_feature_service_item_id, layer_index, layer_field_name) REFERENCES arcgis.layer_field(layer_feature_service_item_id, layer_index, name), PRIMARY KEY(organization_id, destination) ); -CREATE TABLE parcel ( - apn TEXT NOT NULL, - description TEXT NOT NULL, - id SERIAL NOT NULL, - geometry geometry(Polygon, 4326) NOT NULL, - PRIMARY KEY(id) -); +-- +goose Down +DROP TABLE arcgis.address_mapping; +DROP TYPE arcgis.MappingDestinationAddress; +DROP TABLE arcgis.parcel_mapping; +DROP TYPE arcgis.MappingDestinationParcel; +DROP TABLE arcgis.layer_field; +DROP TYPE arcgis.FieldType; +DROP TABLE arcgis.layer; +DROP TABLE arcgis.feature_service; diff --git a/db/migrations/00070_geojsontogeom.sql b/db/migrations/00070_geojsontogeom.sql new file mode 100644 index 00000000..69d0aa72 --- /dev/null +++ b/db/migrations/00070_geojsontogeom.sql @@ -0,0 +1,23 @@ +-- +goose Up +-- Hat tip to https://jesseamundsen.github.io/2025-11-02-geojsontogeom/ +-- +goose StatementBegin +create function public.geojsontogeom(geojson jsonb) +returns table (geometrytype text, properties jsonb, geom geometry) +language plpgsql +as $function$ +begin + return query + select f.features -> 'geometry' ->> 'type' geometrytype + ,f.features -> 'properties' properties + ,st_setsrid(st_geomfromgeojson(f.features ->> 'geometry'),4326) geometry + from ( + select jsonb_array_elements(case + when lower(geojson ->> 'type')='featurecollection' then geojson -> 'features' + when lower(geojson ->> 'type')='feature' then jsonb_build_array(geojson) + else jsonb_build_array(jsonb_build_object('type','Feature','geometry',geojson)) end) features + ) f; +end +$function$; +-- +goose StatementEnd +-- +goose Down +DROP FUNCTION public.geojsontogeom; diff --git a/db/migrations/00071_org_state.sql b/db/migrations/00071_org_state.sql new file mode 100644 index 00000000..139713ba --- /dev/null +++ b/db/migrations/00071_org_state.sql @@ -0,0 +1,23 @@ +-- +goose Up +ALTER TABLE organization ADD COLUMN mailing_address_country TEXT; +ALTER TABLE organization ADD COLUMN mailing_address_state TEXT; +ALTER TABLE organization ADD COLUMN office_address_country TEXT; +ALTER TABLE organization ADD COLUMN office_address_state TEXT; + +UPDATE organization SET mailing_address_country = 'USA'; +UPDATE organization SET mailing_address_state = 'CA'; +UPDATE organization SET office_address_country = 'USA'; +UPDATE organization SET office_address_state = 'CA'; + +UPDATE organization +SET office_address_postal_code = split_part(office_address_postal_code, '.', 1) +WHERE office_address_postal_code LIKE '%.%'; + +UPDATE organization +SET mailing_address_postal_code = split_part(mailing_address_postal_code, '.', 1) +WHERE mailing_address_postal_code LIKE '%.%'; +-- +goose Down +ALTER TABLE organization DROP COLUMN mailing_address_country; +ALTER TABLE organization DROP COLUMN mailing_address_state; +ALTER TABLE organization DROP COLUMN office_address_country; +ALTER TABLE organization DROP COLUMN office_address_state; diff --git a/db/migrations/00072_mailer.sql b/db/migrations/00072_mailer.sql new file mode 100644 index 00000000..884c09d7 --- /dev/null +++ b/db/migrations/00072_mailer.sql @@ -0,0 +1,26 @@ +-- +goose Up +CREATE TYPE comms.MailerType AS ENUM ( + 'green-pool' +); +CREATE TABLE comms.mailer ( + created TIMESTAMP WITHOUT TIME ZONE NOT NULL, + id SERIAL NOT NULL, + type_ comms.MailerType NOT NULL, + PRIMARY KEY(id) +); + +CREATE TABLE compliance_report_request ( + created TIMESTAMP WITHOUT TIME ZONE NOT NULL, + creator INTEGER REFERENCES user_(id) NOT NULL, + id SERIAL NOT NULL, + public_id TEXT NOT NULL UNIQUE, + site_id INTEGER NOT NULL, + site_version INTEGER NOT NULL, + PRIMARY KEY(id), + FOREIGN KEY(site_id, site_version) REFERENCES site(id, version) +); +-- +goose Down +DROP TABLE compliance_report_request; +DROP TABLE comms.mailer; +DROP TYPE comms.MailerType; + diff --git a/db/migrations/00073_arcgis_mapping_service.sql b/db/migrations/00073_arcgis_mapping_service.sql new file mode 100644 index 00000000..e5c3261b --- /dev/null +++ b/db/migrations/00073_arcgis_mapping_service.sql @@ -0,0 +1,72 @@ +-- +goose Up +CREATE TABLE arcgis.account ( + id TEXT NOT NULL, + name TEXT NOT NULL, + organization_id INTEGER NOT NULL REFERENCES organization(id), + + url_features TEXT, + url_insights TEXT, + url_geometry TEXT, + url_notebooks TEXT, + url_tiles TEXT, + PRIMARY KEY(id) +); +CREATE TABLE arcgis.service_map ( + account_id TEXT NOT NULL REFERENCES arcgis.account(id), + arcgis_id TEXT NOT NULL, + name TEXT NOT NULL, + title TEXT NOT NULL, + url TEXT NOT NULL, + PRIMARY KEY(arcgis_id) +); +ALTER TABLE arcgis.feature_service RENAME TO service_feature; +ALTER TABLE arcgis.service_feature ADD COLUMN account_id TEXT REFERENCES arcgis.account(id); +CREATE TABLE arcgis.oauth_token ( + access_token TEXT NOT NULL, + access_token_expires TIMESTAMP WITHOUT TIME ZONE NOT NULL, + arcgis_account_id TEXT REFERENCES arcgis.account(id), + arcgis_id TEXT, + arcgis_license_type_id TEXT, + created TIMESTAMP WITHOUT TIME ZONE NOT NULL, + id SERIAL NOT NULL, + invalidated_at TIMESTAMP WITHOUT TIME ZONE, + refresh_token TEXT NOT NULL, + refresh_token_expires TIMESTAMP WITHOUT TIME ZONE NOT NULL, + user_id INTEGER NOT NULL REFERENCES user_(id), + username TEXT NOT NULL, + PRIMARY KEY (id) +); + + +ALTER TABLE organization ADD COLUMN arcgis_account_id TEXT REFERENCES arcgis.account(id); +ALTER TABLE organization ADD COLUMN fieldseeker_service_feature_item_id TEXT REFERENCES arcgis.service_feature(item_id); +ALTER TABLE organization DROP COLUMN arcgis_id; +ALTER TABLE organization DROP COLUMN arcgis_name; +ALTER TABLE organization DROP COLUMN fieldseeker_url; +DROP TABLE oauth_token; +-- +goose Down +CREATE TABLE oauth_token ( + access_token TEXT NOT NULL, + access_token_expires TIMESTAMP WITHOUT TIME ZONE NOT NULL, + -- arcgis_account_id INTEGER REFERENCES arcgis.account(id), + arcgis_id TEXT, + arcgis_license_type_id TEXT, + created TIMESTAMP WITHOUT TIME ZONE, + id SERIAL NOT NULL, + invalidated_at TIMESTAMP WITHOUT TIME ZONE, + refresh_token TEXT NOT NULL, + refresh_token_expires TIMESTAMP WITHOUT TIME ZONE NOT NULL, + user_id INTEGER NOT NULL REFERENCES user_(id), + username TEXT NOT NULL, + PRIMARY KEY (id) +); +ALTER TABLE organization ADD COLUMN fieldseeker_url TEXT; +ALTER TABLE organization ADD COLUMN arcgis_name TEXT; +ALTER TABLE organization ADD COLUMN arcgis_id TEXT; +ALTER TABLE organization DROP COLUMN fieldseeker_service_feature_item_id; +ALTER TABLE organization DROP COLUMN arcgis_account_id; +DROP TABLE arcgis.oauth_token; +ALTER TABLE arcgis.service_feature DROP COLUMN account_id; +ALTER TABLE arcgis.service_feature RENAME TO feature_service; +DROP TABLE arcgis.service_map; +DROP TABLE arcgis.account; diff --git a/db/models/address.bob.go b/db/models/address.bob.go index c4413e7c..bb6e8338 100644 --- a/db/models/address.bob.go +++ b/db/models/address.bob.go @@ -37,6 +37,8 @@ type Address struct { Unit string `db:"unit" ` R addressR `db:"-" ` + + C addressC `db:"-" ` } // AddressSlice is an alias for a slice of pointers to Address. @@ -51,7 +53,8 @@ type AddressesQuery = *psql.ViewQuery[*Address, AddressSlice] // addressR is where relationships are stored. type addressR struct { - Site *Site // site.site_address_id_fkey + Residents ResidentSlice // resident.resident_address_id_fkey + Site *Site // site.site_address_id_fkey } func buildAddressColumns(alias string) addressColumns { @@ -554,6 +557,30 @@ func (o AddressSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { return nil } +// Residents starts a query for related objects on resident +func (o *Address) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + return Residents.Query(append(mods, + sm.Where(Residents.Columns.AddressID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os AddressSlice) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + 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 Residents.Query(append(mods, + sm.Where(psql.Group(Residents.Columns.AddressID).OP("IN", PKArgExpr)), + )...) +} + // Site starts a query for related objects on site func (o *Address) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { return Sites.Query(append(mods, @@ -578,6 +605,74 @@ func (os AddressSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { )...) } +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) + } + + ret, err := Residents.Insert(bob.ToMods(residents1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertAddressResidents0: %w", err) + } + + return ret, nil +} + +func attachAddressResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, address0 *Address) (ResidentSlice, error) { + setter := &ResidentSetter{ + AddressID: omit.From(address0.ID), + } + + err := residents1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachAddressResidents0: %w", err) + } + + return residents1, nil +} + +func (address0 *Address) InsertResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + residents1, err := insertAddressResidents0(ctx, exec, related, address0) + if err != nil { + return err + } + + address0.R.Residents = append(address0.R.Residents, residents1...) + + for _, rel := range residents1 { + rel.R.Address = address0 + } + return nil +} + +func (address0 *Address) AttachResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error { + if len(related) == 0 { + return nil + } + + var err error + residents1 := ResidentSlice(related) + + _, err = attachAddressResidents0(ctx, exec, len(related), residents1, address0) + if err != nil { + return err + } + + address0.R.Residents = append(address0.R.Residents, residents1...) + + for _, rel := range related { + rel.R.Address = address0 + } + + return nil +} + func insertAddressSite0(ctx context.Context, exec bob.Executor, site1 *SiteSetter, address0 *Address) (*Site, error) { site1.AddressID = omit.From(address0.ID) @@ -670,6 +765,20 @@ func (o *Address) Preload(name string, retrieved any) error { } switch name { + case "Residents": + rels, ok := retrieved.(ResidentSlice) + if !ok { + return fmt.Errorf("address cannot load %T as %q", retrieved, name) + } + + o.R.Residents = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Address = o + } + } + return nil case "Site": rel, ok := retrieved.(*Site) if !ok { @@ -710,15 +819,25 @@ func buildAddressPreloader() addressPreloader { } type addressThenLoader[Q orm.Loadable] struct { - Site 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] } func buildAddressThenLoader[Q orm.Loadable]() addressThenLoader[Q] { + type ResidentsLoadInterface interface { + LoadResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type SiteLoadInterface interface { LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } return addressThenLoader[Q]{ + Residents: thenLoadBuilder[Q]( + "Residents", + func(ctx context.Context, exec bob.Executor, retrieved ResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadResidents(ctx, exec, mods...) + }, + ), Site: thenLoadBuilder[Q]( "Site", func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -728,6 +847,67 @@ func buildAddressThenLoader[Q orm.Loadable]() addressThenLoader[Q] { } } +// 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 { + return nil + } + + // Reset the relationship + o.R.Residents = nil + + related, err := o.Residents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Address = o + } + + o.R.Residents = related + return nil +} + +// LoadResidents loads the address's Residents into the .R struct +func (os AddressSlice) LoadResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + residents, err := os.Residents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.Residents = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range residents { + + if !(o.ID == rel.AddressID) { + continue + } + + rel.R.Address = o + + o.R.Residents = append(o.R.Residents, rel) + } + } + + return nil +} + // LoadSite loads the address's Site into the .R struct func (o *Address) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -780,9 +960,103 @@ func (os AddressSlice) LoadSite(ctx context.Context, exec bob.Executor, mods ... return nil } +// addressC is where relationship counts are stored. +type addressC struct { + Residents *int64 +} + +// PreloadCount sets a count in the C struct by name +func (o *Address) PreloadCount(name string, count int64) error { + if o == nil { + return nil + } + + switch name { + case "Residents": + o.C.Residents = &count + } + return nil +} + +type addressCountPreloader struct { + Residents func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader +} + +func buildAddressCountPreloader() addressCountPreloader { + return addressCountPreloader{ + Residents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Address]("Residents", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Addresses.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Residents.Name()), + sm.Where(psql.Quote(Residents.Alias(), "address_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + } +} + +type addressCountThenLoader[Q orm.Loadable] struct { + Residents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildAddressCountThenLoader[Q orm.Loadable]() addressCountThenLoader[Q] { + type ResidentsCountInterface interface { + LoadCountResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return addressCountThenLoader[Q]{ + Residents: countThenLoadBuilder[Q]( + "Residents", + func(ctx context.Context, exec bob.Executor, retrieved ResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountResidents(ctx, exec, mods...) + }, + ), + } +} + +// LoadCountResidents loads the count of Residents into the C struct +func (o *Address) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.Residents(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.Residents = &count + return nil +} + +// LoadCountResidents loads the count of Residents for a slice +func (os AddressSlice) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountResidents(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + type addressJoins[Q dialect.Joinable] struct { - typ string - Site modAs[Q, siteColumns] + typ string + Residents modAs[Q, residentColumns] + Site modAs[Q, siteColumns] } func (j addressJoins[Q]) aliasedAs(alias string) addressJoins[Q] { @@ -792,6 +1066,20 @@ func (j addressJoins[Q]) aliasedAs(alias string) addressJoins[Q] { func buildAddressJoins[Q dialect.Joinable](cols addressColumns, typ string) addressJoins[Q] { return addressJoins[Q]{ typ: typ, + Residents: modAs[Q, residentColumns]{ + c: Residents.Columns, + f: func(to residentColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Residents.Name().As(to.Alias())).On( + to.AddressID.EQ(cols.ID), + )) + } + + return mods + }, + }, Site: modAs[Q, siteColumns]{ c: Sites.Columns, f: func(to siteColumns) bob.Mod[Q] { diff --git a/db/models/arcgis.account.bob.go b/db/models/arcgis.account.bob.go new file mode 100644 index 00000000..64b2d08b --- /dev/null +++ b/db/models/arcgis.account.bob.go @@ -0,0 +1,1813 @@ +// 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/mods" + "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" +) + +// ArcgisAccount is an object representing the database table. +type ArcgisAccount struct { + ID string `db:"id,pk" ` + Name string `db:"name" ` + OrganizationID int32 `db:"organization_id" ` + URLFeatures null.Val[string] `db:"url_features" ` + URLInsights null.Val[string] `db:"url_insights" ` + URLGeometry null.Val[string] `db:"url_geometry" ` + URLNotebooks null.Val[string] `db:"url_notebooks" ` + URLTiles null.Val[string] `db:"url_tiles" ` + + R arcgisAccountR `db:"-" ` + + C arcgisAccountC `db:"-" ` +} + +// ArcgisAccountSlice is an alias for a slice of pointers to ArcgisAccount. +// This should almost always be used instead of []*ArcgisAccount. +type ArcgisAccountSlice []*ArcgisAccount + +// ArcgisAccounts contains methods to work with the account table +var ArcgisAccounts = psql.NewTablex[*ArcgisAccount, ArcgisAccountSlice, *ArcgisAccountSetter]("arcgis", "account", buildArcgisAccountColumns("arcgis.account")) + +// ArcgisAccountsQuery is a query on the account table +type ArcgisAccountsQuery = *psql.ViewQuery[*ArcgisAccount, ArcgisAccountSlice] + +// arcgisAccountR is where relationships are stored. +type arcgisAccountR struct { + Organization *Organization // arcgis.account.account_organization_id_fkey + ArcgisAccountOauthTokens ArcgisOauthTokenSlice // arcgis.oauth_token.oauth_token_arcgis_account_id_fkey + ServiceFeatures ArcgisServiceFeatureSlice // arcgis.service_feature.service_feature_account_id_fkey + ServiceMaps ArcgisServiceMapSlice // arcgis.service_map.service_map_account_id_fkey + ArcgisAccountOrganizations OrganizationSlice // organization.organization_arcgis_account_id_fkey +} + +func buildArcgisAccountColumns(alias string) arcgisAccountColumns { + return arcgisAccountColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "id", "name", "organization_id", "url_features", "url_insights", "url_geometry", "url_notebooks", "url_tiles", + ).WithParent("arcgis.account"), + tableAlias: alias, + ID: psql.Quote(alias, "id"), + Name: psql.Quote(alias, "name"), + OrganizationID: psql.Quote(alias, "organization_id"), + URLFeatures: psql.Quote(alias, "url_features"), + URLInsights: psql.Quote(alias, "url_insights"), + URLGeometry: psql.Quote(alias, "url_geometry"), + URLNotebooks: psql.Quote(alias, "url_notebooks"), + URLTiles: psql.Quote(alias, "url_tiles"), + } +} + +type arcgisAccountColumns struct { + expr.ColumnsExpr + tableAlias string + ID psql.Expression + Name psql.Expression + OrganizationID psql.Expression + URLFeatures psql.Expression + URLInsights psql.Expression + URLGeometry psql.Expression + URLNotebooks psql.Expression + URLTiles psql.Expression +} + +func (c arcgisAccountColumns) Alias() string { + return c.tableAlias +} + +func (arcgisAccountColumns) AliasedAs(alias string) arcgisAccountColumns { + return buildArcgisAccountColumns(alias) +} + +// ArcgisAccountSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ArcgisAccountSetter struct { + ID omit.Val[string] `db:"id,pk" ` + Name omit.Val[string] `db:"name" ` + OrganizationID omit.Val[int32] `db:"organization_id" ` + URLFeatures omitnull.Val[string] `db:"url_features" ` + URLInsights omitnull.Val[string] `db:"url_insights" ` + URLGeometry omitnull.Val[string] `db:"url_geometry" ` + URLNotebooks omitnull.Val[string] `db:"url_notebooks" ` + URLTiles omitnull.Val[string] `db:"url_tiles" ` +} + +func (s ArcgisAccountSetter) SetColumns() []string { + vals := make([]string, 0, 8) + if s.ID.IsValue() { + vals = append(vals, "id") + } + if s.Name.IsValue() { + vals = append(vals, "name") + } + if s.OrganizationID.IsValue() { + vals = append(vals, "organization_id") + } + if !s.URLFeatures.IsUnset() { + vals = append(vals, "url_features") + } + if !s.URLInsights.IsUnset() { + vals = append(vals, "url_insights") + } + if !s.URLGeometry.IsUnset() { + vals = append(vals, "url_geometry") + } + if !s.URLNotebooks.IsUnset() { + vals = append(vals, "url_notebooks") + } + if !s.URLTiles.IsUnset() { + vals = append(vals, "url_tiles") + } + return vals +} + +func (s ArcgisAccountSetter) Overwrite(t *ArcgisAccount) { + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if s.Name.IsValue() { + t.Name = s.Name.MustGet() + } + if s.OrganizationID.IsValue() { + t.OrganizationID = s.OrganizationID.MustGet() + } + if !s.URLFeatures.IsUnset() { + t.URLFeatures = s.URLFeatures.MustGetNull() + } + if !s.URLInsights.IsUnset() { + t.URLInsights = s.URLInsights.MustGetNull() + } + if !s.URLGeometry.IsUnset() { + t.URLGeometry = s.URLGeometry.MustGetNull() + } + if !s.URLNotebooks.IsUnset() { + t.URLNotebooks = s.URLNotebooks.MustGetNull() + } + if !s.URLTiles.IsUnset() { + t.URLTiles = s.URLTiles.MustGetNull() + } +} + +func (s *ArcgisAccountSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return ArcgisAccounts.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, 8) + if s.ID.IsValue() { + vals[0] = psql.Arg(s.ID.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.Name.IsValue() { + vals[1] = psql.Arg(s.Name.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.OrganizationID.IsValue() { + vals[2] = psql.Arg(s.OrganizationID.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if !s.URLFeatures.IsUnset() { + vals[3] = psql.Arg(s.URLFeatures.MustGetNull()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if !s.URLInsights.IsUnset() { + vals[4] = psql.Arg(s.URLInsights.MustGetNull()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + if !s.URLGeometry.IsUnset() { + vals[5] = psql.Arg(s.URLGeometry.MustGetNull()) + } else { + vals[5] = psql.Raw("DEFAULT") + } + + if !s.URLNotebooks.IsUnset() { + vals[6] = psql.Arg(s.URLNotebooks.MustGetNull()) + } else { + vals[6] = psql.Raw("DEFAULT") + } + + if !s.URLTiles.IsUnset() { + vals[7] = psql.Arg(s.URLTiles.MustGetNull()) + } else { + vals[7] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ArcgisAccountSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ArcgisAccountSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 8) + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if s.Name.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "name")...), + psql.Arg(s.Name), + }}) + } + + if s.OrganizationID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "organization_id")...), + psql.Arg(s.OrganizationID), + }}) + } + + if !s.URLFeatures.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url_features")...), + psql.Arg(s.URLFeatures), + }}) + } + + if !s.URLInsights.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url_insights")...), + psql.Arg(s.URLInsights), + }}) + } + + if !s.URLGeometry.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url_geometry")...), + psql.Arg(s.URLGeometry), + }}) + } + + if !s.URLNotebooks.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url_notebooks")...), + psql.Arg(s.URLNotebooks), + }}) + } + + if !s.URLTiles.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url_tiles")...), + psql.Arg(s.URLTiles), + }}) + } + + return exprs +} + +// FindArcgisAccount retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindArcgisAccount(ctx context.Context, exec bob.Executor, IDPK string, cols ...string) (*ArcgisAccount, error) { + if len(cols) == 0 { + return ArcgisAccounts.Query( + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return ArcgisAccounts.Query( + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(ArcgisAccounts.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ArcgisAccountExists checks the presence of a single record by primary key +func ArcgisAccountExists(ctx context.Context, exec bob.Executor, IDPK string) (bool, error) { + return ArcgisAccounts.Query( + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after ArcgisAccount is retrieved from the database +func (o *ArcgisAccount) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisAccounts.AfterSelectHooks.RunHooks(ctx, exec, ArcgisAccountSlice{o}) + case bob.QueryTypeInsert: + ctx, err = ArcgisAccounts.AfterInsertHooks.RunHooks(ctx, exec, ArcgisAccountSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = ArcgisAccounts.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisAccountSlice{o}) + case bob.QueryTypeDelete: + ctx, err = ArcgisAccounts.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisAccountSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the ArcgisAccount +func (o *ArcgisAccount) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *ArcgisAccount) pkEQ() dialect.Expression { + return psql.Quote("arcgis.account", "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 ArcgisAccount +func (o *ArcgisAccount) Update(ctx context.Context, exec bob.Executor, s *ArcgisAccountSetter) error { + v, err := ArcgisAccounts.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 ArcgisAccount record with an executor +func (o *ArcgisAccount) Delete(ctx context.Context, exec bob.Executor) error { + _, err := ArcgisAccounts.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the ArcgisAccount using the executor +func (o *ArcgisAccount) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := ArcgisAccounts.Query( + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ArcgisAccountSlice is retrieved from the database +func (o ArcgisAccountSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisAccounts.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = ArcgisAccounts.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = ArcgisAccounts.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = ArcgisAccounts.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ArcgisAccountSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("arcgis.account", "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 ArcgisAccountSlice) copyMatchingRows(from ...*ArcgisAccount) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ArcgisAccountSlice) 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 ArcgisAccounts.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 *ArcgisAccount: + o.copyMatchingRows(retrieved) + case []*ArcgisAccount: + o.copyMatchingRows(retrieved...) + case ArcgisAccountSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisAccount or a slice of ArcgisAccount + // then run the AfterUpdateHooks on the slice + _, err = ArcgisAccounts.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ArcgisAccountSlice) 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 ArcgisAccounts.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 *ArcgisAccount: + o.copyMatchingRows(retrieved) + case []*ArcgisAccount: + o.copyMatchingRows(retrieved...) + case ArcgisAccountSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisAccount or a slice of ArcgisAccount + // then run the AfterDeleteHooks on the slice + _, err = ArcgisAccounts.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ArcgisAccountSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisAccountSetter) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisAccounts.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ArcgisAccountSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisAccounts.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ArcgisAccountSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := ArcgisAccounts.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// Organization starts a query for related objects on organization +func (o *ArcgisAccount) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + return Organizations.Query(append(mods, + sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))), + )...) +} + +func (os ArcgisAccountSlice) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + pkOrganizationID := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkOrganizationID = append(pkOrganizationID, o.OrganizationID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkOrganizationID), "integer[]")), + )) + + return Organizations.Query(append(mods, + sm.Where(psql.Group(Organizations.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// ArcgisAccountOauthTokens starts a query for related objects on arcgis.oauth_token +func (o *ArcgisAccount) ArcgisAccountOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisOauthTokensQuery { + return ArcgisOauthTokens.Query(append(mods, + sm.Where(ArcgisOauthTokens.Columns.ArcgisAccountID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os ArcgisAccountSlice) ArcgisAccountOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisOauthTokensQuery { + pkID := make(pgtypes.Array[string], 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), "text[]")), + )) + + return ArcgisOauthTokens.Query(append(mods, + sm.Where(psql.Group(ArcgisOauthTokens.Columns.ArcgisAccountID).OP("IN", PKArgExpr)), + )...) +} + +// ServiceFeatures starts a query for related objects on arcgis.service_feature +func (o *ArcgisAccount) ServiceFeatures(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(ArcgisServiceFeatures.Columns.AccountID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os ArcgisAccountSlice) ServiceFeatures(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { + pkID := make(pgtypes.Array[string], 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), "text[]")), + )) + + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(psql.Group(ArcgisServiceFeatures.Columns.AccountID).OP("IN", PKArgExpr)), + )...) +} + +// ServiceMaps starts a query for related objects on arcgis.service_map +func (o *ArcgisAccount) ServiceMaps(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { + return ArcgisServiceMaps.Query(append(mods, + sm.Where(ArcgisServiceMaps.Columns.AccountID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os ArcgisAccountSlice) ServiceMaps(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { + pkID := make(pgtypes.Array[string], 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), "text[]")), + )) + + return ArcgisServiceMaps.Query(append(mods, + sm.Where(psql.Group(ArcgisServiceMaps.Columns.AccountID).OP("IN", PKArgExpr)), + )...) +} + +// ArcgisAccountOrganizations starts a query for related objects on organization +func (o *ArcgisAccount) ArcgisAccountOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + return Organizations.Query(append(mods, + sm.Where(Organizations.Columns.ArcgisAccountID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os ArcgisAccountSlice) ArcgisAccountOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + pkID := make(pgtypes.Array[string], 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), "text[]")), + )) + + return Organizations.Query(append(mods, + sm.Where(psql.Group(Organizations.Columns.ArcgisAccountID).OP("IN", PKArgExpr)), + )...) +} + +func attachArcgisAccountOrganization0(ctx context.Context, exec bob.Executor, count int, arcgisAccount0 *ArcgisAccount, organization1 *Organization) (*ArcgisAccount, error) { + setter := &ArcgisAccountSetter{ + OrganizationID: omit.From(organization1.ID), + } + + err := arcgisAccount0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisAccountOrganization0: %w", err) + } + + return arcgisAccount0, nil +} + +func (arcgisAccount0 *ArcgisAccount) InsertOrganization(ctx context.Context, exec bob.Executor, related *OrganizationSetter) error { + var err error + + organization1, err := Organizations.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachArcgisAccountOrganization0(ctx, exec, 1, arcgisAccount0, organization1) + if err != nil { + return err + } + + arcgisAccount0.R.Organization = organization1 + + organization1.R.Accounts = append(organization1.R.Accounts, arcgisAccount0) + + return nil +} + +func (arcgisAccount0 *ArcgisAccount) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error { + var err error + + _, err = attachArcgisAccountOrganization0(ctx, exec, 1, arcgisAccount0, organization1) + if err != nil { + return err + } + + arcgisAccount0.R.Organization = organization1 + + organization1.R.Accounts = append(organization1.R.Accounts, arcgisAccount0) + + return nil +} + +func insertArcgisAccountArcgisAccountOauthTokens0(ctx context.Context, exec bob.Executor, arcgisOauthTokens1 []*ArcgisOauthTokenSetter, arcgisAccount0 *ArcgisAccount) (ArcgisOauthTokenSlice, error) { + for i := range arcgisOauthTokens1 { + arcgisOauthTokens1[i].ArcgisAccountID = omitnull.From(arcgisAccount0.ID) + } + + ret, err := ArcgisOauthTokens.Insert(bob.ToMods(arcgisOauthTokens1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisAccountArcgisAccountOauthTokens0: %w", err) + } + + return ret, nil +} + +func attachArcgisAccountArcgisAccountOauthTokens0(ctx context.Context, exec bob.Executor, count int, arcgisOauthTokens1 ArcgisOauthTokenSlice, arcgisAccount0 *ArcgisAccount) (ArcgisOauthTokenSlice, error) { + setter := &ArcgisOauthTokenSetter{ + ArcgisAccountID: omitnull.From(arcgisAccount0.ID), + } + + err := arcgisOauthTokens1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisAccountArcgisAccountOauthTokens0: %w", err) + } + + return arcgisOauthTokens1, nil +} + +func (arcgisAccount0 *ArcgisAccount) InsertArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthTokenSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisOauthTokens1, err := insertArcgisAccountArcgisAccountOauthTokens0(ctx, exec, related, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ArcgisAccountOauthTokens = append(arcgisAccount0.R.ArcgisAccountOauthTokens, arcgisOauthTokens1...) + + for _, rel := range arcgisOauthTokens1 { + rel.R.ArcgisAccountAccount = arcgisAccount0 + } + return nil +} + +func (arcgisAccount0 *ArcgisAccount) AttachArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthToken) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisOauthTokens1 := ArcgisOauthTokenSlice(related) + + _, err = attachArcgisAccountArcgisAccountOauthTokens0(ctx, exec, len(related), arcgisOauthTokens1, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ArcgisAccountOauthTokens = append(arcgisAccount0.R.ArcgisAccountOauthTokens, arcgisOauthTokens1...) + + for _, rel := range related { + rel.R.ArcgisAccountAccount = arcgisAccount0 + } + + return nil +} + +func insertArcgisAccountServiceFeatures0(ctx context.Context, exec bob.Executor, arcgisServiceFeatures1 []*ArcgisServiceFeatureSetter, arcgisAccount0 *ArcgisAccount) (ArcgisServiceFeatureSlice, error) { + for i := range arcgisServiceFeatures1 { + arcgisServiceFeatures1[i].AccountID = omitnull.From(arcgisAccount0.ID) + } + + ret, err := ArcgisServiceFeatures.Insert(bob.ToMods(arcgisServiceFeatures1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisAccountServiceFeatures0: %w", err) + } + + return ret, nil +} + +func attachArcgisAccountServiceFeatures0(ctx context.Context, exec bob.Executor, count int, arcgisServiceFeatures1 ArcgisServiceFeatureSlice, arcgisAccount0 *ArcgisAccount) (ArcgisServiceFeatureSlice, error) { + setter := &ArcgisServiceFeatureSetter{ + AccountID: omitnull.From(arcgisAccount0.ID), + } + + err := arcgisServiceFeatures1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisAccountServiceFeatures0: %w", err) + } + + return arcgisServiceFeatures1, nil +} + +func (arcgisAccount0 *ArcgisAccount) InsertServiceFeatures(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceFeatureSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisServiceFeatures1, err := insertArcgisAccountServiceFeatures0(ctx, exec, related, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ServiceFeatures = append(arcgisAccount0.R.ServiceFeatures, arcgisServiceFeatures1...) + + for _, rel := range arcgisServiceFeatures1 { + rel.R.Account = arcgisAccount0 + } + return nil +} + +func (arcgisAccount0 *ArcgisAccount) AttachServiceFeatures(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceFeature) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisServiceFeatures1 := ArcgisServiceFeatureSlice(related) + + _, err = attachArcgisAccountServiceFeatures0(ctx, exec, len(related), arcgisServiceFeatures1, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ServiceFeatures = append(arcgisAccount0.R.ServiceFeatures, arcgisServiceFeatures1...) + + for _, rel := range related { + rel.R.Account = arcgisAccount0 + } + + return nil +} + +func insertArcgisAccountServiceMaps0(ctx context.Context, exec bob.Executor, arcgisServiceMaps1 []*ArcgisServiceMapSetter, arcgisAccount0 *ArcgisAccount) (ArcgisServiceMapSlice, error) { + for i := range arcgisServiceMaps1 { + arcgisServiceMaps1[i].AccountID = omit.From(arcgisAccount0.ID) + } + + ret, err := ArcgisServiceMaps.Insert(bob.ToMods(arcgisServiceMaps1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisAccountServiceMaps0: %w", err) + } + + return ret, nil +} + +func attachArcgisAccountServiceMaps0(ctx context.Context, exec bob.Executor, count int, arcgisServiceMaps1 ArcgisServiceMapSlice, arcgisAccount0 *ArcgisAccount) (ArcgisServiceMapSlice, error) { + setter := &ArcgisServiceMapSetter{ + AccountID: omit.From(arcgisAccount0.ID), + } + + err := arcgisServiceMaps1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisAccountServiceMaps0: %w", err) + } + + return arcgisServiceMaps1, nil +} + +func (arcgisAccount0 *ArcgisAccount) InsertServiceMaps(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceMapSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisServiceMaps1, err := insertArcgisAccountServiceMaps0(ctx, exec, related, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ServiceMaps = append(arcgisAccount0.R.ServiceMaps, arcgisServiceMaps1...) + + for _, rel := range arcgisServiceMaps1 { + rel.R.Account = arcgisAccount0 + } + return nil +} + +func (arcgisAccount0 *ArcgisAccount) AttachServiceMaps(ctx context.Context, exec bob.Executor, related ...*ArcgisServiceMap) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisServiceMaps1 := ArcgisServiceMapSlice(related) + + _, err = attachArcgisAccountServiceMaps0(ctx, exec, len(related), arcgisServiceMaps1, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ServiceMaps = append(arcgisAccount0.R.ServiceMaps, arcgisServiceMaps1...) + + for _, rel := range related { + rel.R.Account = arcgisAccount0 + } + + return nil +} + +func insertArcgisAccountArcgisAccountOrganizations0(ctx context.Context, exec bob.Executor, organizations1 []*OrganizationSetter, arcgisAccount0 *ArcgisAccount) (OrganizationSlice, error) { + for i := range organizations1 { + organizations1[i].ArcgisAccountID = omitnull.From(arcgisAccount0.ID) + } + + ret, err := Organizations.Insert(bob.ToMods(organizations1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisAccountArcgisAccountOrganizations0: %w", err) + } + + return ret, nil +} + +func attachArcgisAccountArcgisAccountOrganizations0(ctx context.Context, exec bob.Executor, count int, organizations1 OrganizationSlice, arcgisAccount0 *ArcgisAccount) (OrganizationSlice, error) { + setter := &OrganizationSetter{ + ArcgisAccountID: omitnull.From(arcgisAccount0.ID), + } + + err := organizations1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisAccountArcgisAccountOrganizations0: %w", err) + } + + return organizations1, nil +} + +func (arcgisAccount0 *ArcgisAccount) InsertArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + organizations1, err := insertArcgisAccountArcgisAccountOrganizations0(ctx, exec, related, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ArcgisAccountOrganizations = append(arcgisAccount0.R.ArcgisAccountOrganizations, organizations1...) + + for _, rel := range organizations1 { + rel.R.ArcgisAccountAccount = arcgisAccount0 + } + return nil +} + +func (arcgisAccount0 *ArcgisAccount) AttachArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error { + if len(related) == 0 { + return nil + } + + var err error + organizations1 := OrganizationSlice(related) + + _, err = attachArcgisAccountArcgisAccountOrganizations0(ctx, exec, len(related), organizations1, arcgisAccount0) + if err != nil { + return err + } + + arcgisAccount0.R.ArcgisAccountOrganizations = append(arcgisAccount0.R.ArcgisAccountOrganizations, organizations1...) + + for _, rel := range related { + rel.R.ArcgisAccountAccount = arcgisAccount0 + } + + return nil +} + +type arcgisAccountWhere[Q psql.Filterable] struct { + ID psql.WhereMod[Q, string] + Name psql.WhereMod[Q, string] + OrganizationID psql.WhereMod[Q, int32] + URLFeatures psql.WhereNullMod[Q, string] + URLInsights psql.WhereNullMod[Q, string] + URLGeometry psql.WhereNullMod[Q, string] + URLNotebooks psql.WhereNullMod[Q, string] + URLTiles psql.WhereNullMod[Q, string] +} + +func (arcgisAccountWhere[Q]) AliasedAs(alias string) arcgisAccountWhere[Q] { + return buildArcgisAccountWhere[Q](buildArcgisAccountColumns(alias)) +} + +func buildArcgisAccountWhere[Q psql.Filterable](cols arcgisAccountColumns) arcgisAccountWhere[Q] { + return arcgisAccountWhere[Q]{ + ID: psql.Where[Q, string](cols.ID), + Name: psql.Where[Q, string](cols.Name), + OrganizationID: psql.Where[Q, int32](cols.OrganizationID), + URLFeatures: psql.WhereNull[Q, string](cols.URLFeatures), + URLInsights: psql.WhereNull[Q, string](cols.URLInsights), + URLGeometry: psql.WhereNull[Q, string](cols.URLGeometry), + URLNotebooks: psql.WhereNull[Q, string](cols.URLNotebooks), + URLTiles: psql.WhereNull[Q, string](cols.URLTiles), + } +} + +func (o *ArcgisAccount) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "Organization": + rel, ok := retrieved.(*Organization) + if !ok { + return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name) + } + + o.R.Organization = rel + + if rel != nil { + rel.R.Accounts = ArcgisAccountSlice{o} + } + return nil + case "ArcgisAccountOauthTokens": + rels, ok := retrieved.(ArcgisOauthTokenSlice) + if !ok { + return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name) + } + + o.R.ArcgisAccountOauthTokens = rels + + for _, rel := range rels { + if rel != nil { + rel.R.ArcgisAccountAccount = o + } + } + return nil + case "ServiceFeatures": + rels, ok := retrieved.(ArcgisServiceFeatureSlice) + if !ok { + return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name) + } + + o.R.ServiceFeatures = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Account = o + } + } + return nil + case "ServiceMaps": + rels, ok := retrieved.(ArcgisServiceMapSlice) + if !ok { + return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name) + } + + o.R.ServiceMaps = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Account = o + } + } + return nil + case "ArcgisAccountOrganizations": + rels, ok := retrieved.(OrganizationSlice) + if !ok { + return fmt.Errorf("arcgisAccount cannot load %T as %q", retrieved, name) + } + + o.R.ArcgisAccountOrganizations = rels + + for _, rel := range rels { + if rel != nil { + rel.R.ArcgisAccountAccount = o + } + } + return nil + default: + return fmt.Errorf("arcgisAccount has no relationship %q", name) + } +} + +type arcgisAccountPreloader struct { + Organization func(...psql.PreloadOption) psql.Preloader +} + +func buildArcgisAccountPreloader() arcgisAccountPreloader { + return arcgisAccountPreloader{ + Organization: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{ + Name: "Organization", + Sides: []psql.PreloadSide{ + { + From: ArcgisAccounts, + To: Organizations, + FromColumns: []string{"organization_id"}, + ToColumns: []string{"id"}, + }, + }, + }, Organizations.Columns.Names(), opts...) + }, + } +} + +type arcgisAccountThenLoader[Q orm.Loadable] struct { + Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ArcgisAccountOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ServiceFeatures func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ServiceMaps func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ArcgisAccountOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisAccountThenLoader[Q orm.Loadable]() arcgisAccountThenLoader[Q] { + type OrganizationLoadInterface interface { + LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ArcgisAccountOauthTokensLoadInterface interface { + LoadArcgisAccountOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ServiceFeaturesLoadInterface interface { + LoadServiceFeatures(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ServiceMapsLoadInterface interface { + LoadServiceMaps(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ArcgisAccountOrganizationsLoadInterface interface { + LoadArcgisAccountOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisAccountThenLoader[Q]{ + Organization: thenLoadBuilder[Q]( + "Organization", + func(ctx context.Context, exec bob.Executor, retrieved OrganizationLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadOrganization(ctx, exec, mods...) + }, + ), + ArcgisAccountOauthTokens: thenLoadBuilder[Q]( + "ArcgisAccountOauthTokens", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOauthTokensLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadArcgisAccountOauthTokens(ctx, exec, mods...) + }, + ), + ServiceFeatures: thenLoadBuilder[Q]( + "ServiceFeatures", + func(ctx context.Context, exec bob.Executor, retrieved ServiceFeaturesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadServiceFeatures(ctx, exec, mods...) + }, + ), + ServiceMaps: thenLoadBuilder[Q]( + "ServiceMaps", + func(ctx context.Context, exec bob.Executor, retrieved ServiceMapsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadServiceMaps(ctx, exec, mods...) + }, + ), + ArcgisAccountOrganizations: thenLoadBuilder[Q]( + "ArcgisAccountOrganizations", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadArcgisAccountOrganizations(ctx, exec, mods...) + }, + ), + } +} + +// LoadOrganization loads the arcgisAccount's Organization into the .R struct +func (o *ArcgisAccount) LoadOrganization(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Organization = nil + + related, err := o.Organization(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.Accounts = ArcgisAccountSlice{o} + + o.R.Organization = related + return nil +} + +// LoadOrganization loads the arcgisAccount's Organization into the .R struct +func (os ArcgisAccountSlice) LoadOrganization(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + organizations, err := os.Organization(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range organizations { + + if !(o.OrganizationID == rel.ID) { + continue + } + + rel.R.Accounts = append(rel.R.Accounts, o) + + o.R.Organization = rel + break + } + } + + return nil +} + +// LoadArcgisAccountOauthTokens loads the arcgisAccount's ArcgisAccountOauthTokens into the .R struct +func (o *ArcgisAccount) LoadArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ArcgisAccountOauthTokens = nil + + related, err := o.ArcgisAccountOauthTokens(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.ArcgisAccountAccount = o + } + + o.R.ArcgisAccountOauthTokens = related + return nil +} + +// LoadArcgisAccountOauthTokens loads the arcgisAccount's ArcgisAccountOauthTokens into the .R struct +func (os ArcgisAccountSlice) LoadArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisOauthTokens, err := os.ArcgisAccountOauthTokens(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.ArcgisAccountOauthTokens = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisOauthTokens { + + if !rel.ArcgisAccountID.IsValue() { + continue + } + if !(rel.ArcgisAccountID.IsValue() && o.ID == rel.ArcgisAccountID.MustGet()) { + continue + } + + rel.R.ArcgisAccountAccount = o + + o.R.ArcgisAccountOauthTokens = append(o.R.ArcgisAccountOauthTokens, rel) + } + } + + return nil +} + +// LoadServiceFeatures loads the arcgisAccount's ServiceFeatures into the .R struct +func (o *ArcgisAccount) LoadServiceFeatures(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ServiceFeatures = nil + + related, err := o.ServiceFeatures(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Account = o + } + + o.R.ServiceFeatures = related + return nil +} + +// LoadServiceFeatures loads the arcgisAccount's ServiceFeatures into the .R struct +func (os ArcgisAccountSlice) LoadServiceFeatures(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisServiceFeatures, err := os.ServiceFeatures(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.ServiceFeatures = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisServiceFeatures { + + if !rel.AccountID.IsValue() { + continue + } + if !(rel.AccountID.IsValue() && o.ID == rel.AccountID.MustGet()) { + continue + } + + rel.R.Account = o + + o.R.ServiceFeatures = append(o.R.ServiceFeatures, rel) + } + } + + return nil +} + +// LoadServiceMaps loads the arcgisAccount's ServiceMaps into the .R struct +func (o *ArcgisAccount) LoadServiceMaps(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ServiceMaps = nil + + related, err := o.ServiceMaps(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Account = o + } + + o.R.ServiceMaps = related + return nil +} + +// LoadServiceMaps loads the arcgisAccount's ServiceMaps into the .R struct +func (os ArcgisAccountSlice) LoadServiceMaps(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisServiceMaps, err := os.ServiceMaps(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.ServiceMaps = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisServiceMaps { + + if !(o.ID == rel.AccountID) { + continue + } + + rel.R.Account = o + + o.R.ServiceMaps = append(o.R.ServiceMaps, rel) + } + } + + return nil +} + +// LoadArcgisAccountOrganizations loads the arcgisAccount's ArcgisAccountOrganizations into the .R struct +func (o *ArcgisAccount) LoadArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ArcgisAccountOrganizations = nil + + related, err := o.ArcgisAccountOrganizations(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.ArcgisAccountAccount = o + } + + o.R.ArcgisAccountOrganizations = related + return nil +} + +// LoadArcgisAccountOrganizations loads the arcgisAccount's ArcgisAccountOrganizations into the .R struct +func (os ArcgisAccountSlice) LoadArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + organizations, err := os.ArcgisAccountOrganizations(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.ArcgisAccountOrganizations = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range organizations { + + if !rel.ArcgisAccountID.IsValue() { + continue + } + if !(rel.ArcgisAccountID.IsValue() && o.ID == rel.ArcgisAccountID.MustGet()) { + continue + } + + rel.R.ArcgisAccountAccount = o + + o.R.ArcgisAccountOrganizations = append(o.R.ArcgisAccountOrganizations, rel) + } + } + + return nil +} + +// arcgisAccountC is where relationship counts are stored. +type arcgisAccountC struct { + ArcgisAccountOauthTokens *int64 + ServiceFeatures *int64 + ServiceMaps *int64 + ArcgisAccountOrganizations *int64 +} + +// PreloadCount sets a count in the C struct by name +func (o *ArcgisAccount) PreloadCount(name string, count int64) error { + if o == nil { + return nil + } + + switch name { + case "ArcgisAccountOauthTokens": + o.C.ArcgisAccountOauthTokens = &count + case "ServiceFeatures": + o.C.ServiceFeatures = &count + case "ServiceMaps": + o.C.ServiceMaps = &count + case "ArcgisAccountOrganizations": + o.C.ArcgisAccountOrganizations = &count + } + return nil +} + +type arcgisAccountCountPreloader struct { + ArcgisAccountOauthTokens func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + ServiceFeatures func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + ServiceMaps func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + ArcgisAccountOrganizations func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader +} + +func buildArcgisAccountCountPreloader() arcgisAccountCountPreloader { + return arcgisAccountCountPreloader{ + ArcgisAccountOauthTokens: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisAccount]("ArcgisAccountOauthTokens", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisAccounts.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisOauthTokens.Name()), + sm.Where(psql.Quote(ArcgisOauthTokens.Alias(), "arcgis_account_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + ServiceFeatures: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisAccount]("ServiceFeatures", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisAccounts.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisServiceFeatures.Name()), + sm.Where(psql.Quote(ArcgisServiceFeatures.Alias(), "account_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + ServiceMaps: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisAccount]("ServiceMaps", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisAccounts.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisServiceMaps.Name()), + sm.Where(psql.Quote(ArcgisServiceMaps.Alias(), "account_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + ArcgisAccountOrganizations: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisAccount]("ArcgisAccountOrganizations", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisAccounts.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Organizations.Name()), + sm.Where(psql.Quote(Organizations.Alias(), "arcgis_account_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + } +} + +type arcgisAccountCountThenLoader[Q orm.Loadable] struct { + ArcgisAccountOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ServiceFeatures func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ServiceMaps func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ArcgisAccountOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisAccountCountThenLoader[Q orm.Loadable]() arcgisAccountCountThenLoader[Q] { + type ArcgisAccountOauthTokensCountInterface interface { + LoadCountArcgisAccountOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ServiceFeaturesCountInterface interface { + LoadCountServiceFeatures(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ServiceMapsCountInterface interface { + LoadCountServiceMaps(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ArcgisAccountOrganizationsCountInterface interface { + LoadCountArcgisAccountOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisAccountCountThenLoader[Q]{ + ArcgisAccountOauthTokens: countThenLoadBuilder[Q]( + "ArcgisAccountOauthTokens", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOauthTokensCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountArcgisAccountOauthTokens(ctx, exec, mods...) + }, + ), + ServiceFeatures: countThenLoadBuilder[Q]( + "ServiceFeatures", + func(ctx context.Context, exec bob.Executor, retrieved ServiceFeaturesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountServiceFeatures(ctx, exec, mods...) + }, + ), + ServiceMaps: countThenLoadBuilder[Q]( + "ServiceMaps", + func(ctx context.Context, exec bob.Executor, retrieved ServiceMapsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountServiceMaps(ctx, exec, mods...) + }, + ), + ArcgisAccountOrganizations: countThenLoadBuilder[Q]( + "ArcgisAccountOrganizations", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountOrganizationsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountArcgisAccountOrganizations(ctx, exec, mods...) + }, + ), + } +} + +// LoadCountArcgisAccountOauthTokens loads the count of ArcgisAccountOauthTokens into the C struct +func (o *ArcgisAccount) LoadCountArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.ArcgisAccountOauthTokens(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.ArcgisAccountOauthTokens = &count + return nil +} + +// LoadCountArcgisAccountOauthTokens loads the count of ArcgisAccountOauthTokens for a slice +func (os ArcgisAccountSlice) LoadCountArcgisAccountOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountArcgisAccountOauthTokens(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountServiceFeatures loads the count of ServiceFeatures into the C struct +func (o *ArcgisAccount) LoadCountServiceFeatures(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.ServiceFeatures(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.ServiceFeatures = &count + return nil +} + +// LoadCountServiceFeatures loads the count of ServiceFeatures for a slice +func (os ArcgisAccountSlice) LoadCountServiceFeatures(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountServiceFeatures(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountServiceMaps loads the count of ServiceMaps into the C struct +func (o *ArcgisAccount) LoadCountServiceMaps(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.ServiceMaps(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.ServiceMaps = &count + return nil +} + +// LoadCountServiceMaps loads the count of ServiceMaps for a slice +func (os ArcgisAccountSlice) LoadCountServiceMaps(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountServiceMaps(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountArcgisAccountOrganizations loads the count of ArcgisAccountOrganizations into the C struct +func (o *ArcgisAccount) LoadCountArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.ArcgisAccountOrganizations(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.ArcgisAccountOrganizations = &count + return nil +} + +// LoadCountArcgisAccountOrganizations loads the count of ArcgisAccountOrganizations for a slice +func (os ArcgisAccountSlice) LoadCountArcgisAccountOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountArcgisAccountOrganizations(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +type arcgisAccountJoins[Q dialect.Joinable] struct { + typ string + Organization modAs[Q, organizationColumns] + ArcgisAccountOauthTokens modAs[Q, arcgisOauthTokenColumns] + ServiceFeatures modAs[Q, arcgisServiceFeatureColumns] + ServiceMaps modAs[Q, arcgisServiceMapColumns] + ArcgisAccountOrganizations modAs[Q, organizationColumns] +} + +func (j arcgisAccountJoins[Q]) aliasedAs(alias string) arcgisAccountJoins[Q] { + return buildArcgisAccountJoins[Q](buildArcgisAccountColumns(alias), j.typ) +} + +func buildArcgisAccountJoins[Q dialect.Joinable](cols arcgisAccountColumns, typ string) arcgisAccountJoins[Q] { + return arcgisAccountJoins[Q]{ + typ: typ, + Organization: modAs[Q, organizationColumns]{ + c: Organizations.Columns, + f: func(to organizationColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On( + to.ID.EQ(cols.OrganizationID), + )) + } + + return mods + }, + }, + ArcgisAccountOauthTokens: modAs[Q, arcgisOauthTokenColumns]{ + c: ArcgisOauthTokens.Columns, + f: func(to arcgisOauthTokenColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisOauthTokens.Name().As(to.Alias())).On( + to.ArcgisAccountID.EQ(cols.ID), + )) + } + + return mods + }, + }, + ServiceFeatures: modAs[Q, arcgisServiceFeatureColumns]{ + c: ArcgisServiceFeatures.Columns, + f: func(to arcgisServiceFeatureColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisServiceFeatures.Name().As(to.Alias())).On( + to.AccountID.EQ(cols.ID), + )) + } + + return mods + }, + }, + ServiceMaps: modAs[Q, arcgisServiceMapColumns]{ + c: ArcgisServiceMaps.Columns, + f: func(to arcgisServiceMapColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisServiceMaps.Name().As(to.Alias())).On( + to.AccountID.EQ(cols.ID), + )) + } + + return mods + }, + }, + ArcgisAccountOrganizations: modAs[Q, organizationColumns]{ + c: Organizations.Columns, + f: func(to organizationColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On( + to.ArcgisAccountID.EQ(cols.ID), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/arcgis.layer.bob.go b/db/models/arcgis.layer.bob.go index aec268f1..0aa7ee5c 100644 --- a/db/models/arcgis.layer.bob.go +++ b/db/models/arcgis.layer.bob.go @@ -44,7 +44,7 @@ type ArcgisLayersQuery = *psql.ViewQuery[*ArcgisLayer, ArcgisLayerSlice] // arcgisLayerR is where relationships are stored. type arcgisLayerR struct { - FeatureServiceItemFeatureService *ArcgisFeatureService // arcgis.layer.layer_feature_service_item_id_fkey + FeatureServiceItemServiceFeature *ArcgisServiceFeature // arcgis.layer.layer_feature_service_item_id_fkey LayerFields ArcgisLayerFieldSlice // arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey } @@ -404,14 +404,14 @@ func (o ArcgisLayerSlice) ReloadAll(ctx context.Context, exec bob.Executor) erro return nil } -// FeatureServiceItemFeatureService starts a query for related objects on arcgis.feature_service -func (o *ArcgisLayer) FeatureServiceItemFeatureService(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisFeatureServicesQuery { - return ArcgisFeatureServices.Query(append(mods, - sm.Where(ArcgisFeatureServices.Columns.ItemID.EQ(psql.Arg(o.FeatureServiceItemID))), +// FeatureServiceItemServiceFeature starts a query for related objects on arcgis.service_feature +func (o *ArcgisLayer) FeatureServiceItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(o.FeatureServiceItemID))), )...) } -func (os ArcgisLayerSlice) FeatureServiceItemFeatureService(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisFeatureServicesQuery { +func (os ArcgisLayerSlice) FeatureServiceItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { pkFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) for _, o := range os { if o == nil { @@ -423,8 +423,8 @@ func (os ArcgisLayerSlice) FeatureServiceItemFeatureService(mods ...bob.Mod[*dia psql.F("unnest", psql.Cast(psql.Arg(pkFeatureServiceItemID), "text[]")), )) - return ArcgisFeatureServices.Query(append(mods, - sm.Where(psql.Group(ArcgisFeatureServices.Columns.ItemID).OP("IN", PKArgExpr)), + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(psql.Group(ArcgisServiceFeatures.Columns.ItemID).OP("IN", PKArgExpr)), )...) } @@ -456,50 +456,50 @@ func (os ArcgisLayerSlice) LayerFields(mods ...bob.Mod[*dialect.SelectQuery]) Ar )...) } -func attachArcgisLayerFeatureServiceItemFeatureService0(ctx context.Context, exec bob.Executor, count int, arcgisLayer0 *ArcgisLayer, arcgisFeatureService1 *ArcgisFeatureService) (*ArcgisLayer, error) { +func attachArcgisLayerFeatureServiceItemServiceFeature0(ctx context.Context, exec bob.Executor, count int, arcgisLayer0 *ArcgisLayer, arcgisServiceFeature1 *ArcgisServiceFeature) (*ArcgisLayer, error) { setter := &ArcgisLayerSetter{ - FeatureServiceItemID: omit.From(arcgisFeatureService1.ItemID), + FeatureServiceItemID: omit.From(arcgisServiceFeature1.ItemID), } err := arcgisLayer0.Update(ctx, exec, setter) if err != nil { - return nil, fmt.Errorf("attachArcgisLayerFeatureServiceItemFeatureService0: %w", err) + return nil, fmt.Errorf("attachArcgisLayerFeatureServiceItemServiceFeature0: %w", err) } return arcgisLayer0, nil } -func (arcgisLayer0 *ArcgisLayer) InsertFeatureServiceItemFeatureService(ctx context.Context, exec bob.Executor, related *ArcgisFeatureServiceSetter) error { +func (arcgisLayer0 *ArcgisLayer) InsertFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, related *ArcgisServiceFeatureSetter) error { var err error - arcgisFeatureService1, err := ArcgisFeatureServices.Insert(related).One(ctx, exec) + arcgisServiceFeature1, err := ArcgisServiceFeatures.Insert(related).One(ctx, exec) if err != nil { return fmt.Errorf("inserting related objects: %w", err) } - _, err = attachArcgisLayerFeatureServiceItemFeatureService0(ctx, exec, 1, arcgisLayer0, arcgisFeatureService1) + _, err = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1) if err != nil { return err } - arcgisLayer0.R.FeatureServiceItemFeatureService = arcgisFeatureService1 + arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1 - arcgisFeatureService1.R.FeatureServiceItemLayers = append(arcgisFeatureService1.R.FeatureServiceItemLayers, arcgisLayer0) + arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0) return nil } -func (arcgisLayer0 *ArcgisLayer) AttachFeatureServiceItemFeatureService(ctx context.Context, exec bob.Executor, arcgisFeatureService1 *ArcgisFeatureService) error { +func (arcgisLayer0 *ArcgisLayer) AttachFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, arcgisServiceFeature1 *ArcgisServiceFeature) error { var err error - _, err = attachArcgisLayerFeatureServiceItemFeatureService0(ctx, exec, 1, arcgisLayer0, arcgisFeatureService1) + _, err = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1) if err != nil { return err } - arcgisLayer0.R.FeatureServiceItemFeatureService = arcgisFeatureService1 + arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1 - arcgisFeatureService1.R.FeatureServiceItemLayers = append(arcgisFeatureService1.R.FeatureServiceItemLayers, arcgisLayer0) + arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0) return nil } @@ -598,13 +598,13 @@ func (o *ArcgisLayer) Preload(name string, retrieved any) error { } switch name { - case "FeatureServiceItemFeatureService": - rel, ok := retrieved.(*ArcgisFeatureService) + case "FeatureServiceItemServiceFeature": + rel, ok := retrieved.(*ArcgisServiceFeature) if !ok { return fmt.Errorf("arcgisLayer cannot load %T as %q", retrieved, name) } - o.R.FeatureServiceItemFeatureService = rel + o.R.FeatureServiceItemServiceFeature = rel if rel != nil { rel.R.FeatureServiceItemLayers = ArcgisLayerSlice{o} @@ -630,45 +630,45 @@ func (o *ArcgisLayer) Preload(name string, retrieved any) error { } type arcgisLayerPreloader struct { - FeatureServiceItemFeatureService func(...psql.PreloadOption) psql.Preloader + FeatureServiceItemServiceFeature func(...psql.PreloadOption) psql.Preloader } func buildArcgisLayerPreloader() arcgisLayerPreloader { return arcgisLayerPreloader{ - FeatureServiceItemFeatureService: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisFeatureService, ArcgisFeatureServiceSlice](psql.PreloadRel{ - Name: "FeatureServiceItemFeatureService", + FeatureServiceItemServiceFeature: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisServiceFeature, ArcgisServiceFeatureSlice](psql.PreloadRel{ + Name: "FeatureServiceItemServiceFeature", Sides: []psql.PreloadSide{ { From: ArcgisLayers, - To: ArcgisFeatureServices, + To: ArcgisServiceFeatures, FromColumns: []string{"feature_service_item_id"}, ToColumns: []string{"item_id"}, }, }, - }, ArcgisFeatureServices.Columns.Names(), opts...) + }, ArcgisServiceFeatures.Columns.Names(), opts...) }, } } type arcgisLayerThenLoader[Q orm.Loadable] struct { - FeatureServiceItemFeatureService func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FeatureServiceItemServiceFeature func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] LayerFields func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildArcgisLayerThenLoader[Q orm.Loadable]() arcgisLayerThenLoader[Q] { - type FeatureServiceItemFeatureServiceLoadInterface interface { - LoadFeatureServiceItemFeatureService(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + type FeatureServiceItemServiceFeatureLoadInterface interface { + LoadFeatureServiceItemServiceFeature(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } type LayerFieldsLoadInterface interface { LoadLayerFields(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } return arcgisLayerThenLoader[Q]{ - FeatureServiceItemFeatureService: thenLoadBuilder[Q]( - "FeatureServiceItemFeatureService", - func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemFeatureServiceLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadFeatureServiceItemFeatureService(ctx, exec, mods...) + FeatureServiceItemServiceFeature: thenLoadBuilder[Q]( + "FeatureServiceItemServiceFeature", + func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemServiceFeatureLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadFeatureServiceItemServiceFeature(ctx, exec, mods...) }, ), LayerFields: thenLoadBuilder[Q]( @@ -680,33 +680,33 @@ func buildArcgisLayerThenLoader[Q orm.Loadable]() arcgisLayerThenLoader[Q] { } } -// LoadFeatureServiceItemFeatureService loads the arcgisLayer's FeatureServiceItemFeatureService into the .R struct -func (o *ArcgisLayer) LoadFeatureServiceItemFeatureService(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { +// LoadFeatureServiceItemServiceFeature loads the arcgisLayer's FeatureServiceItemServiceFeature into the .R struct +func (o *ArcgisLayer) LoadFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { return nil } // Reset the relationship - o.R.FeatureServiceItemFeatureService = nil + o.R.FeatureServiceItemServiceFeature = nil - related, err := o.FeatureServiceItemFeatureService(mods...).One(ctx, exec) + related, err := o.FeatureServiceItemServiceFeature(mods...).One(ctx, exec) if err != nil { return err } related.R.FeatureServiceItemLayers = ArcgisLayerSlice{o} - o.R.FeatureServiceItemFeatureService = related + o.R.FeatureServiceItemServiceFeature = related return nil } -// LoadFeatureServiceItemFeatureService loads the arcgisLayer's FeatureServiceItemFeatureService into the .R struct -func (os ArcgisLayerSlice) LoadFeatureServiceItemFeatureService(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { +// LoadFeatureServiceItemServiceFeature loads the arcgisLayer's FeatureServiceItemServiceFeature into the .R struct +func (os ArcgisLayerSlice) LoadFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if len(os) == 0 { return nil } - arcgisFeatureServices, err := os.FeatureServiceItemFeatureService(mods...).All(ctx, exec) + arcgisServiceFeatures, err := os.FeatureServiceItemServiceFeature(mods...).All(ctx, exec) if err != nil { return err } @@ -716,7 +716,7 @@ func (os ArcgisLayerSlice) LoadFeatureServiceItemFeatureService(ctx context.Cont continue } - for _, rel := range arcgisFeatureServices { + for _, rel := range arcgisServiceFeatures { if !(o.FeatureServiceItemID == rel.ItemID) { continue @@ -724,7 +724,7 @@ func (os ArcgisLayerSlice) LoadFeatureServiceItemFeatureService(ctx context.Cont rel.R.FeatureServiceItemLayers = append(rel.R.FeatureServiceItemLayers, o) - o.R.FeatureServiceItemFeatureService = rel + o.R.FeatureServiceItemServiceFeature = rel break } } @@ -893,7 +893,7 @@ func (os ArcgisLayerSlice) LoadCountLayerFields(ctx context.Context, exec bob.Ex type arcgisLayerJoins[Q dialect.Joinable] struct { typ string - FeatureServiceItemFeatureService modAs[Q, arcgisFeatureServiceColumns] + FeatureServiceItemServiceFeature modAs[Q, arcgisServiceFeatureColumns] LayerFields modAs[Q, arcgisLayerFieldColumns] } @@ -904,13 +904,13 @@ func (j arcgisLayerJoins[Q]) aliasedAs(alias string) arcgisLayerJoins[Q] { func buildArcgisLayerJoins[Q dialect.Joinable](cols arcgisLayerColumns, typ string) arcgisLayerJoins[Q] { return arcgisLayerJoins[Q]{ typ: typ, - FeatureServiceItemFeatureService: modAs[Q, arcgisFeatureServiceColumns]{ - c: ArcgisFeatureServices.Columns, - f: func(to arcgisFeatureServiceColumns) bob.Mod[Q] { + FeatureServiceItemServiceFeature: modAs[Q, arcgisServiceFeatureColumns]{ + c: ArcgisServiceFeatures.Columns, + f: func(to arcgisServiceFeatureColumns) bob.Mod[Q] { mods := make(mods.QueryMods[Q], 0, 1) { - mods = append(mods, dialect.Join[Q](typ, ArcgisFeatureServices.Name().As(to.Alias())).On( + mods = append(mods, dialect.Join[Q](typ, ArcgisServiceFeatures.Name().As(to.Alias())).On( to.ItemID.EQ(cols.FeatureServiceItemID), )) } diff --git a/db/models/arcgis.oauth_token.bob.go b/db/models/arcgis.oauth_token.bob.go new file mode 100644 index 00000000..564686a2 --- /dev/null +++ b/db/models/arcgis.oauth_token.bob.go @@ -0,0 +1,1034 @@ +// 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/mods" + "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" +) + +// ArcgisOauthToken is an object representing the database table. +type ArcgisOauthToken struct { + AccessToken string `db:"access_token" ` + AccessTokenExpires time.Time `db:"access_token_expires" ` + ArcgisAccountID null.Val[string] `db:"arcgis_account_id" ` + ArcgisID null.Val[string] `db:"arcgis_id" ` + ArcgisLicenseTypeID null.Val[string] `db:"arcgis_license_type_id" ` + Created time.Time `db:"created" ` + ID int32 `db:"id,pk" ` + InvalidatedAt null.Val[time.Time] `db:"invalidated_at" ` + RefreshToken string `db:"refresh_token" ` + RefreshTokenExpires time.Time `db:"refresh_token_expires" ` + UserID int32 `db:"user_id" ` + Username string `db:"username" ` + + R arcgisOauthTokenR `db:"-" ` +} + +// ArcgisOauthTokenSlice is an alias for a slice of pointers to ArcgisOauthToken. +// This should almost always be used instead of []*ArcgisOauthToken. +type ArcgisOauthTokenSlice []*ArcgisOauthToken + +// ArcgisOauthTokens contains methods to work with the oauth_token table +var ArcgisOauthTokens = psql.NewTablex[*ArcgisOauthToken, ArcgisOauthTokenSlice, *ArcgisOauthTokenSetter]("arcgis", "oauth_token", buildArcgisOauthTokenColumns("arcgis.oauth_token")) + +// ArcgisOauthTokensQuery is a query on the oauth_token table +type ArcgisOauthTokensQuery = *psql.ViewQuery[*ArcgisOauthToken, ArcgisOauthTokenSlice] + +// arcgisOauthTokenR is where relationships are stored. +type arcgisOauthTokenR struct { + ArcgisAccountAccount *ArcgisAccount // arcgis.oauth_token.oauth_token_arcgis_account_id_fkey + UserUser *User // arcgis.oauth_token.oauth_token_user_id_fkey +} + +func buildArcgisOauthTokenColumns(alias string) arcgisOauthTokenColumns { + return arcgisOauthTokenColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "access_token", "access_token_expires", "arcgis_account_id", "arcgis_id", "arcgis_license_type_id", "created", "id", "invalidated_at", "refresh_token", "refresh_token_expires", "user_id", "username", + ).WithParent("arcgis.oauth_token"), + tableAlias: alias, + AccessToken: psql.Quote(alias, "access_token"), + AccessTokenExpires: psql.Quote(alias, "access_token_expires"), + ArcgisAccountID: psql.Quote(alias, "arcgis_account_id"), + ArcgisID: psql.Quote(alias, "arcgis_id"), + ArcgisLicenseTypeID: psql.Quote(alias, "arcgis_license_type_id"), + Created: psql.Quote(alias, "created"), + ID: psql.Quote(alias, "id"), + InvalidatedAt: psql.Quote(alias, "invalidated_at"), + RefreshToken: psql.Quote(alias, "refresh_token"), + RefreshTokenExpires: psql.Quote(alias, "refresh_token_expires"), + UserID: psql.Quote(alias, "user_id"), + Username: psql.Quote(alias, "username"), + } +} + +type arcgisOauthTokenColumns struct { + expr.ColumnsExpr + tableAlias string + AccessToken psql.Expression + AccessTokenExpires psql.Expression + ArcgisAccountID psql.Expression + ArcgisID psql.Expression + ArcgisLicenseTypeID psql.Expression + Created psql.Expression + ID psql.Expression + InvalidatedAt psql.Expression + RefreshToken psql.Expression + RefreshTokenExpires psql.Expression + UserID psql.Expression + Username psql.Expression +} + +func (c arcgisOauthTokenColumns) Alias() string { + return c.tableAlias +} + +func (arcgisOauthTokenColumns) AliasedAs(alias string) arcgisOauthTokenColumns { + return buildArcgisOauthTokenColumns(alias) +} + +// ArcgisOauthTokenSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ArcgisOauthTokenSetter struct { + AccessToken omit.Val[string] `db:"access_token" ` + AccessTokenExpires omit.Val[time.Time] `db:"access_token_expires" ` + ArcgisAccountID omitnull.Val[string] `db:"arcgis_account_id" ` + ArcgisID omitnull.Val[string] `db:"arcgis_id" ` + ArcgisLicenseTypeID omitnull.Val[string] `db:"arcgis_license_type_id" ` + Created omit.Val[time.Time] `db:"created" ` + ID omit.Val[int32] `db:"id,pk" ` + InvalidatedAt omitnull.Val[time.Time] `db:"invalidated_at" ` + RefreshToken omit.Val[string] `db:"refresh_token" ` + RefreshTokenExpires omit.Val[time.Time] `db:"refresh_token_expires" ` + UserID omit.Val[int32] `db:"user_id" ` + Username omit.Val[string] `db:"username" ` +} + +func (s ArcgisOauthTokenSetter) SetColumns() []string { + vals := make([]string, 0, 12) + if s.AccessToken.IsValue() { + vals = append(vals, "access_token") + } + if s.AccessTokenExpires.IsValue() { + vals = append(vals, "access_token_expires") + } + if !s.ArcgisAccountID.IsUnset() { + vals = append(vals, "arcgis_account_id") + } + if !s.ArcgisID.IsUnset() { + vals = append(vals, "arcgis_id") + } + if !s.ArcgisLicenseTypeID.IsUnset() { + vals = append(vals, "arcgis_license_type_id") + } + if s.Created.IsValue() { + vals = append(vals, "created") + } + if s.ID.IsValue() { + vals = append(vals, "id") + } + if !s.InvalidatedAt.IsUnset() { + vals = append(vals, "invalidated_at") + } + if s.RefreshToken.IsValue() { + vals = append(vals, "refresh_token") + } + if s.RefreshTokenExpires.IsValue() { + vals = append(vals, "refresh_token_expires") + } + if s.UserID.IsValue() { + vals = append(vals, "user_id") + } + if s.Username.IsValue() { + vals = append(vals, "username") + } + return vals +} + +func (s ArcgisOauthTokenSetter) Overwrite(t *ArcgisOauthToken) { + if s.AccessToken.IsValue() { + t.AccessToken = s.AccessToken.MustGet() + } + if s.AccessTokenExpires.IsValue() { + t.AccessTokenExpires = s.AccessTokenExpires.MustGet() + } + if !s.ArcgisAccountID.IsUnset() { + t.ArcgisAccountID = s.ArcgisAccountID.MustGetNull() + } + if !s.ArcgisID.IsUnset() { + t.ArcgisID = s.ArcgisID.MustGetNull() + } + if !s.ArcgisLicenseTypeID.IsUnset() { + t.ArcgisLicenseTypeID = s.ArcgisLicenseTypeID.MustGetNull() + } + if s.Created.IsValue() { + t.Created = s.Created.MustGet() + } + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if !s.InvalidatedAt.IsUnset() { + t.InvalidatedAt = s.InvalidatedAt.MustGetNull() + } + if s.RefreshToken.IsValue() { + t.RefreshToken = s.RefreshToken.MustGet() + } + if s.RefreshTokenExpires.IsValue() { + t.RefreshTokenExpires = s.RefreshTokenExpires.MustGet() + } + if s.UserID.IsValue() { + t.UserID = s.UserID.MustGet() + } + if s.Username.IsValue() { + t.Username = s.Username.MustGet() + } +} + +func (s *ArcgisOauthTokenSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return ArcgisOauthTokens.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, 12) + if s.AccessToken.IsValue() { + vals[0] = psql.Arg(s.AccessToken.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.AccessTokenExpires.IsValue() { + vals[1] = psql.Arg(s.AccessTokenExpires.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if !s.ArcgisAccountID.IsUnset() { + vals[2] = psql.Arg(s.ArcgisAccountID.MustGetNull()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if !s.ArcgisID.IsUnset() { + vals[3] = psql.Arg(s.ArcgisID.MustGetNull()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if !s.ArcgisLicenseTypeID.IsUnset() { + vals[4] = psql.Arg(s.ArcgisLicenseTypeID.MustGetNull()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + if s.Created.IsValue() { + vals[5] = psql.Arg(s.Created.MustGet()) + } else { + vals[5] = psql.Raw("DEFAULT") + } + + if s.ID.IsValue() { + vals[6] = psql.Arg(s.ID.MustGet()) + } else { + vals[6] = psql.Raw("DEFAULT") + } + + if !s.InvalidatedAt.IsUnset() { + vals[7] = psql.Arg(s.InvalidatedAt.MustGetNull()) + } else { + vals[7] = psql.Raw("DEFAULT") + } + + if s.RefreshToken.IsValue() { + vals[8] = psql.Arg(s.RefreshToken.MustGet()) + } else { + vals[8] = psql.Raw("DEFAULT") + } + + if s.RefreshTokenExpires.IsValue() { + vals[9] = psql.Arg(s.RefreshTokenExpires.MustGet()) + } else { + vals[9] = psql.Raw("DEFAULT") + } + + if s.UserID.IsValue() { + vals[10] = psql.Arg(s.UserID.MustGet()) + } else { + vals[10] = psql.Raw("DEFAULT") + } + + if s.Username.IsValue() { + vals[11] = psql.Arg(s.Username.MustGet()) + } else { + vals[11] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ArcgisOauthTokenSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ArcgisOauthTokenSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 12) + + if s.AccessToken.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "access_token")...), + psql.Arg(s.AccessToken), + }}) + } + + if s.AccessTokenExpires.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "access_token_expires")...), + psql.Arg(s.AccessTokenExpires), + }}) + } + + if !s.ArcgisAccountID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "arcgis_account_id")...), + psql.Arg(s.ArcgisAccountID), + }}) + } + + if !s.ArcgisID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "arcgis_id")...), + psql.Arg(s.ArcgisID), + }}) + } + + if !s.ArcgisLicenseTypeID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "arcgis_license_type_id")...), + psql.Arg(s.ArcgisLicenseTypeID), + }}) + } + + if s.Created.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "created")...), + psql.Arg(s.Created), + }}) + } + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if !s.InvalidatedAt.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "invalidated_at")...), + psql.Arg(s.InvalidatedAt), + }}) + } + + if s.RefreshToken.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "refresh_token")...), + psql.Arg(s.RefreshToken), + }}) + } + + if s.RefreshTokenExpires.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "refresh_token_expires")...), + psql.Arg(s.RefreshTokenExpires), + }}) + } + + if s.UserID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "user_id")...), + psql.Arg(s.UserID), + }}) + } + + if s.Username.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "username")...), + psql.Arg(s.Username), + }}) + } + + return exprs +} + +// FindArcgisOauthToken retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindArcgisOauthToken(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*ArcgisOauthToken, error) { + if len(cols) == 0 { + return ArcgisOauthTokens.Query( + sm.Where(ArcgisOauthTokens.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return ArcgisOauthTokens.Query( + sm.Where(ArcgisOauthTokens.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(ArcgisOauthTokens.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ArcgisOauthTokenExists checks the presence of a single record by primary key +func ArcgisOauthTokenExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) { + return ArcgisOauthTokens.Query( + sm.Where(ArcgisOauthTokens.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after ArcgisOauthToken is retrieved from the database +func (o *ArcgisOauthToken) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisOauthTokens.AfterSelectHooks.RunHooks(ctx, exec, ArcgisOauthTokenSlice{o}) + case bob.QueryTypeInsert: + ctx, err = ArcgisOauthTokens.AfterInsertHooks.RunHooks(ctx, exec, ArcgisOauthTokenSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = ArcgisOauthTokens.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisOauthTokenSlice{o}) + case bob.QueryTypeDelete: + ctx, err = ArcgisOauthTokens.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisOauthTokenSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the ArcgisOauthToken +func (o *ArcgisOauthToken) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *ArcgisOauthToken) pkEQ() dialect.Expression { + return psql.Quote("arcgis.oauth_token", "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 ArcgisOauthToken +func (o *ArcgisOauthToken) Update(ctx context.Context, exec bob.Executor, s *ArcgisOauthTokenSetter) error { + v, err := ArcgisOauthTokens.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 ArcgisOauthToken record with an executor +func (o *ArcgisOauthToken) Delete(ctx context.Context, exec bob.Executor) error { + _, err := ArcgisOauthTokens.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the ArcgisOauthToken using the executor +func (o *ArcgisOauthToken) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := ArcgisOauthTokens.Query( + sm.Where(ArcgisOauthTokens.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ArcgisOauthTokenSlice is retrieved from the database +func (o ArcgisOauthTokenSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisOauthTokens.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = ArcgisOauthTokens.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = ArcgisOauthTokens.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = ArcgisOauthTokens.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ArcgisOauthTokenSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("arcgis.oauth_token", "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 ArcgisOauthTokenSlice) copyMatchingRows(from ...*ArcgisOauthToken) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ArcgisOauthTokenSlice) 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 ArcgisOauthTokens.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 *ArcgisOauthToken: + o.copyMatchingRows(retrieved) + case []*ArcgisOauthToken: + o.copyMatchingRows(retrieved...) + case ArcgisOauthTokenSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisOauthToken or a slice of ArcgisOauthToken + // then run the AfterUpdateHooks on the slice + _, err = ArcgisOauthTokens.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ArcgisOauthTokenSlice) 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 ArcgisOauthTokens.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 *ArcgisOauthToken: + o.copyMatchingRows(retrieved) + case []*ArcgisOauthToken: + o.copyMatchingRows(retrieved...) + case ArcgisOauthTokenSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisOauthToken or a slice of ArcgisOauthToken + // then run the AfterDeleteHooks on the slice + _, err = ArcgisOauthTokens.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ArcgisOauthTokenSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisOauthTokenSetter) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisOauthTokens.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ArcgisOauthTokenSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisOauthTokens.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ArcgisOauthTokenSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := ArcgisOauthTokens.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// ArcgisAccountAccount starts a query for related objects on arcgis.account +func (o *ArcgisOauthToken) ArcgisAccountAccount(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + return ArcgisAccounts.Query(append(mods, + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.ArcgisAccountID))), + )...) +} + +func (os ArcgisOauthTokenSlice) ArcgisAccountAccount(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + pkArcgisAccountID := make(pgtypes.Array[null.Val[string]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkArcgisAccountID = append(pkArcgisAccountID, o.ArcgisAccountID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkArcgisAccountID), "text[]")), + )) + + return ArcgisAccounts.Query(append(mods, + sm.Where(psql.Group(ArcgisAccounts.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// UserUser starts a query for related objects on user_ +func (o *ArcgisOauthToken) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + return Users.Query(append(mods, + sm.Where(Users.Columns.ID.EQ(psql.Arg(o.UserID))), + )...) +} + +func (os ArcgisOauthTokenSlice) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + pkUserID := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkUserID = append(pkUserID, o.UserID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkUserID), "integer[]")), + )) + + return Users.Query(append(mods, + sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +func attachArcgisOauthTokenArcgisAccountAccount0(ctx context.Context, exec bob.Executor, count int, arcgisOauthToken0 *ArcgisOauthToken, arcgisAccount1 *ArcgisAccount) (*ArcgisOauthToken, error) { + setter := &ArcgisOauthTokenSetter{ + ArcgisAccountID: omitnull.From(arcgisAccount1.ID), + } + + err := arcgisOauthToken0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisOauthTokenArcgisAccountAccount0: %w", err) + } + + return arcgisOauthToken0, nil +} + +func (arcgisOauthToken0 *ArcgisOauthToken) InsertArcgisAccountAccount(ctx context.Context, exec bob.Executor, related *ArcgisAccountSetter) error { + var err error + + arcgisAccount1, err := ArcgisAccounts.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachArcgisOauthTokenArcgisAccountAccount0(ctx, exec, 1, arcgisOauthToken0, arcgisAccount1) + if err != nil { + return err + } + + arcgisOauthToken0.R.ArcgisAccountAccount = arcgisAccount1 + + arcgisAccount1.R.ArcgisAccountOauthTokens = append(arcgisAccount1.R.ArcgisAccountOauthTokens, arcgisOauthToken0) + + return nil +} + +func (arcgisOauthToken0 *ArcgisOauthToken) AttachArcgisAccountAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error { + var err error + + _, err = attachArcgisOauthTokenArcgisAccountAccount0(ctx, exec, 1, arcgisOauthToken0, arcgisAccount1) + if err != nil { + return err + } + + arcgisOauthToken0.R.ArcgisAccountAccount = arcgisAccount1 + + arcgisAccount1.R.ArcgisAccountOauthTokens = append(arcgisAccount1.R.ArcgisAccountOauthTokens, arcgisOauthToken0) + + return nil +} + +func attachArcgisOauthTokenUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisOauthToken0 *ArcgisOauthToken, user1 *User) (*ArcgisOauthToken, error) { + setter := &ArcgisOauthTokenSetter{ + UserID: omit.From(user1.ID), + } + + err := arcgisOauthToken0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisOauthTokenUserUser0: %w", err) + } + + return arcgisOauthToken0, nil +} + +func (arcgisOauthToken0 *ArcgisOauthToken) InsertUserUser(ctx context.Context, exec bob.Executor, related *UserSetter) error { + var err error + + user1, err := Users.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachArcgisOauthTokenUserUser0(ctx, exec, 1, arcgisOauthToken0, user1) + if err != nil { + return err + } + + arcgisOauthToken0.R.UserUser = user1 + + user1.R.UserOauthTokens = append(user1.R.UserOauthTokens, arcgisOauthToken0) + + return nil +} + +func (arcgisOauthToken0 *ArcgisOauthToken) AttachUserUser(ctx context.Context, exec bob.Executor, user1 *User) error { + var err error + + _, err = attachArcgisOauthTokenUserUser0(ctx, exec, 1, arcgisOauthToken0, user1) + if err != nil { + return err + } + + arcgisOauthToken0.R.UserUser = user1 + + user1.R.UserOauthTokens = append(user1.R.UserOauthTokens, arcgisOauthToken0) + + return nil +} + +type arcgisOauthTokenWhere[Q psql.Filterable] struct { + AccessToken psql.WhereMod[Q, string] + AccessTokenExpires psql.WhereMod[Q, time.Time] + ArcgisAccountID psql.WhereNullMod[Q, string] + ArcgisID psql.WhereNullMod[Q, string] + ArcgisLicenseTypeID psql.WhereNullMod[Q, string] + Created psql.WhereMod[Q, time.Time] + ID psql.WhereMod[Q, int32] + InvalidatedAt psql.WhereNullMod[Q, time.Time] + RefreshToken psql.WhereMod[Q, string] + RefreshTokenExpires psql.WhereMod[Q, time.Time] + UserID psql.WhereMod[Q, int32] + Username psql.WhereMod[Q, string] +} + +func (arcgisOauthTokenWhere[Q]) AliasedAs(alias string) arcgisOauthTokenWhere[Q] { + return buildArcgisOauthTokenWhere[Q](buildArcgisOauthTokenColumns(alias)) +} + +func buildArcgisOauthTokenWhere[Q psql.Filterable](cols arcgisOauthTokenColumns) arcgisOauthTokenWhere[Q] { + return arcgisOauthTokenWhere[Q]{ + AccessToken: psql.Where[Q, string](cols.AccessToken), + AccessTokenExpires: psql.Where[Q, time.Time](cols.AccessTokenExpires), + ArcgisAccountID: psql.WhereNull[Q, string](cols.ArcgisAccountID), + ArcgisID: psql.WhereNull[Q, string](cols.ArcgisID), + ArcgisLicenseTypeID: psql.WhereNull[Q, string](cols.ArcgisLicenseTypeID), + Created: psql.Where[Q, time.Time](cols.Created), + ID: psql.Where[Q, int32](cols.ID), + InvalidatedAt: psql.WhereNull[Q, time.Time](cols.InvalidatedAt), + RefreshToken: psql.Where[Q, string](cols.RefreshToken), + RefreshTokenExpires: psql.Where[Q, time.Time](cols.RefreshTokenExpires), + UserID: psql.Where[Q, int32](cols.UserID), + Username: psql.Where[Q, string](cols.Username), + } +} + +func (o *ArcgisOauthToken) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "ArcgisAccountAccount": + rel, ok := retrieved.(*ArcgisAccount) + if !ok { + return fmt.Errorf("arcgisOauthToken cannot load %T as %q", retrieved, name) + } + + o.R.ArcgisAccountAccount = rel + + if rel != nil { + rel.R.ArcgisAccountOauthTokens = ArcgisOauthTokenSlice{o} + } + return nil + case "UserUser": + rel, ok := retrieved.(*User) + if !ok { + return fmt.Errorf("arcgisOauthToken cannot load %T as %q", retrieved, name) + } + + o.R.UserUser = rel + + if rel != nil { + rel.R.UserOauthTokens = ArcgisOauthTokenSlice{o} + } + return nil + default: + return fmt.Errorf("arcgisOauthToken has no relationship %q", name) + } +} + +type arcgisOauthTokenPreloader struct { + ArcgisAccountAccount func(...psql.PreloadOption) psql.Preloader + UserUser func(...psql.PreloadOption) psql.Preloader +} + +func buildArcgisOauthTokenPreloader() arcgisOauthTokenPreloader { + return arcgisOauthTokenPreloader{ + ArcgisAccountAccount: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{ + Name: "ArcgisAccountAccount", + Sides: []psql.PreloadSide{ + { + From: ArcgisOauthTokens, + To: ArcgisAccounts, + FromColumns: []string{"arcgis_account_id"}, + ToColumns: []string{"id"}, + }, + }, + }, ArcgisAccounts.Columns.Names(), opts...) + }, + UserUser: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*User, UserSlice](psql.PreloadRel{ + Name: "UserUser", + Sides: []psql.PreloadSide{ + { + From: ArcgisOauthTokens, + To: Users, + FromColumns: []string{"user_id"}, + ToColumns: []string{"id"}, + }, + }, + }, Users.Columns.Names(), opts...) + }, + } +} + +type arcgisOauthTokenThenLoader[Q orm.Loadable] struct { + ArcgisAccountAccount func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisOauthTokenThenLoader[Q orm.Loadable]() arcgisOauthTokenThenLoader[Q] { + type ArcgisAccountAccountLoadInterface interface { + LoadArcgisAccountAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type UserUserLoadInterface interface { + LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisOauthTokenThenLoader[Q]{ + ArcgisAccountAccount: thenLoadBuilder[Q]( + "ArcgisAccountAccount", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountAccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadArcgisAccountAccount(ctx, exec, mods...) + }, + ), + UserUser: thenLoadBuilder[Q]( + "UserUser", + func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadUserUser(ctx, exec, mods...) + }, + ), + } +} + +// LoadArcgisAccountAccount loads the arcgisOauthToken's ArcgisAccountAccount into the .R struct +func (o *ArcgisOauthToken) LoadArcgisAccountAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ArcgisAccountAccount = nil + + related, err := o.ArcgisAccountAccount(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.ArcgisAccountOauthTokens = ArcgisOauthTokenSlice{o} + + o.R.ArcgisAccountAccount = related + return nil +} + +// LoadArcgisAccountAccount loads the arcgisOauthToken's ArcgisAccountAccount into the .R struct +func (os ArcgisOauthTokenSlice) LoadArcgisAccountAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisAccounts, err := os.ArcgisAccountAccount(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisAccounts { + if !o.ArcgisAccountID.IsValue() { + continue + } + + if !(o.ArcgisAccountID.IsValue() && o.ArcgisAccountID.MustGet() == rel.ID) { + continue + } + + rel.R.ArcgisAccountOauthTokens = append(rel.R.ArcgisAccountOauthTokens, o) + + o.R.ArcgisAccountAccount = rel + break + } + } + + return nil +} + +// LoadUserUser loads the arcgisOauthToken's UserUser into the .R struct +func (o *ArcgisOauthToken) LoadUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.UserUser = nil + + related, err := o.UserUser(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.UserOauthTokens = ArcgisOauthTokenSlice{o} + + o.R.UserUser = related + return nil +} + +// LoadUserUser loads the arcgisOauthToken's UserUser into the .R struct +func (os ArcgisOauthTokenSlice) LoadUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + users, err := os.UserUser(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range users { + + if !(o.UserID == rel.ID) { + continue + } + + rel.R.UserOauthTokens = append(rel.R.UserOauthTokens, o) + + o.R.UserUser = rel + break + } + } + + return nil +} + +type arcgisOauthTokenJoins[Q dialect.Joinable] struct { + typ string + ArcgisAccountAccount modAs[Q, arcgisAccountColumns] + UserUser modAs[Q, userColumns] +} + +func (j arcgisOauthTokenJoins[Q]) aliasedAs(alias string) arcgisOauthTokenJoins[Q] { + return buildArcgisOauthTokenJoins[Q](buildArcgisOauthTokenColumns(alias), j.typ) +} + +func buildArcgisOauthTokenJoins[Q dialect.Joinable](cols arcgisOauthTokenColumns, typ string) arcgisOauthTokenJoins[Q] { + return arcgisOauthTokenJoins[Q]{ + typ: typ, + ArcgisAccountAccount: modAs[Q, arcgisAccountColumns]{ + c: ArcgisAccounts.Columns, + f: func(to arcgisAccountColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On( + to.ID.EQ(cols.ArcgisAccountID), + )) + } + + return mods + }, + }, + UserUser: modAs[Q, userColumns]{ + c: Users.Columns, + f: func(to userColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Users.Name().As(to.Alias())).On( + to.ID.EQ(cols.UserID), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/arcgis.service_feature.bob.go b/db/models/arcgis.service_feature.bob.go new file mode 100644 index 00000000..7bf06f66 --- /dev/null +++ b/db/models/arcgis.service_feature.bob.go @@ -0,0 +1,1227 @@ +// 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/mods" + "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" +) + +// ArcgisServiceFeature is an object representing the database table. +type ArcgisServiceFeature struct { + Extent string `db:"extent" ` + ItemID string `db:"item_id,pk" ` + SpatialReference int32 `db:"spatial_reference" ` + URL string `db:"url" ` + AccountID null.Val[string] `db:"account_id" ` + + R arcgisServiceFeatureR `db:"-" ` + + C arcgisServiceFeatureC `db:"-" ` +} + +// ArcgisServiceFeatureSlice is an alias for a slice of pointers to ArcgisServiceFeature. +// This should almost always be used instead of []*ArcgisServiceFeature. +type ArcgisServiceFeatureSlice []*ArcgisServiceFeature + +// ArcgisServiceFeatures contains methods to work with the service_feature table +var ArcgisServiceFeatures = psql.NewTablex[*ArcgisServiceFeature, ArcgisServiceFeatureSlice, *ArcgisServiceFeatureSetter]("arcgis", "service_feature", buildArcgisServiceFeatureColumns("arcgis.service_feature")) + +// ArcgisServiceFeaturesQuery is a query on the service_feature table +type ArcgisServiceFeaturesQuery = *psql.ViewQuery[*ArcgisServiceFeature, ArcgisServiceFeatureSlice] + +// arcgisServiceFeatureR is where relationships are stored. +type arcgisServiceFeatureR struct { + FeatureServiceItemLayers ArcgisLayerSlice // arcgis.layer.layer_feature_service_item_id_fkey + Account *ArcgisAccount // arcgis.service_feature.service_feature_account_id_fkey + FieldseekerServiceFeatureItemOrganizations OrganizationSlice // organization.organization_fieldseeker_service_feature_item_id_fkey +} + +func buildArcgisServiceFeatureColumns(alias string) arcgisServiceFeatureColumns { + return arcgisServiceFeatureColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "extent", "item_id", "spatial_reference", "url", "account_id", + ).WithParent("arcgis.service_feature"), + tableAlias: alias, + Extent: psql.Quote(alias, "extent"), + ItemID: psql.Quote(alias, "item_id"), + SpatialReference: psql.Quote(alias, "spatial_reference"), + URL: psql.Quote(alias, "url"), + AccountID: psql.Quote(alias, "account_id"), + } +} + +type arcgisServiceFeatureColumns struct { + expr.ColumnsExpr + tableAlias string + Extent psql.Expression + ItemID psql.Expression + SpatialReference psql.Expression + URL psql.Expression + AccountID psql.Expression +} + +func (c arcgisServiceFeatureColumns) Alias() string { + return c.tableAlias +} + +func (arcgisServiceFeatureColumns) AliasedAs(alias string) arcgisServiceFeatureColumns { + return buildArcgisServiceFeatureColumns(alias) +} + +// ArcgisServiceFeatureSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ArcgisServiceFeatureSetter struct { + Extent omit.Val[string] `db:"extent" ` + ItemID omit.Val[string] `db:"item_id,pk" ` + SpatialReference omit.Val[int32] `db:"spatial_reference" ` + URL omit.Val[string] `db:"url" ` + AccountID omitnull.Val[string] `db:"account_id" ` +} + +func (s ArcgisServiceFeatureSetter) SetColumns() []string { + vals := make([]string, 0, 5) + if s.Extent.IsValue() { + vals = append(vals, "extent") + } + if s.ItemID.IsValue() { + vals = append(vals, "item_id") + } + if s.SpatialReference.IsValue() { + vals = append(vals, "spatial_reference") + } + if s.URL.IsValue() { + vals = append(vals, "url") + } + if !s.AccountID.IsUnset() { + vals = append(vals, "account_id") + } + return vals +} + +func (s ArcgisServiceFeatureSetter) Overwrite(t *ArcgisServiceFeature) { + if s.Extent.IsValue() { + t.Extent = s.Extent.MustGet() + } + if s.ItemID.IsValue() { + t.ItemID = s.ItemID.MustGet() + } + if s.SpatialReference.IsValue() { + t.SpatialReference = s.SpatialReference.MustGet() + } + if s.URL.IsValue() { + t.URL = s.URL.MustGet() + } + if !s.AccountID.IsUnset() { + t.AccountID = s.AccountID.MustGetNull() + } +} + +func (s *ArcgisServiceFeatureSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return ArcgisServiceFeatures.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, 5) + if s.Extent.IsValue() { + vals[0] = psql.Arg(s.Extent.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.ItemID.IsValue() { + vals[1] = psql.Arg(s.ItemID.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.SpatialReference.IsValue() { + vals[2] = psql.Arg(s.SpatialReference.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if s.URL.IsValue() { + vals[3] = psql.Arg(s.URL.MustGet()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if !s.AccountID.IsUnset() { + vals[4] = psql.Arg(s.AccountID.MustGetNull()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ArcgisServiceFeatureSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ArcgisServiceFeatureSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 5) + + if s.Extent.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "extent")...), + psql.Arg(s.Extent), + }}) + } + + if s.ItemID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "item_id")...), + psql.Arg(s.ItemID), + }}) + } + + if s.SpatialReference.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "spatial_reference")...), + psql.Arg(s.SpatialReference), + }}) + } + + if s.URL.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url")...), + psql.Arg(s.URL), + }}) + } + + if !s.AccountID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "account_id")...), + psql.Arg(s.AccountID), + }}) + } + + return exprs +} + +// FindArcgisServiceFeature retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindArcgisServiceFeature(ctx context.Context, exec bob.Executor, ItemIDPK string, cols ...string) (*ArcgisServiceFeature, error) { + if len(cols) == 0 { + return ArcgisServiceFeatures.Query( + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(ItemIDPK))), + ).One(ctx, exec) + } + + return ArcgisServiceFeatures.Query( + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(ItemIDPK))), + sm.Columns(ArcgisServiceFeatures.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ArcgisServiceFeatureExists checks the presence of a single record by primary key +func ArcgisServiceFeatureExists(ctx context.Context, exec bob.Executor, ItemIDPK string) (bool, error) { + return ArcgisServiceFeatures.Query( + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(ItemIDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after ArcgisServiceFeature is retrieved from the database +func (o *ArcgisServiceFeature) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisServiceFeatures.AfterSelectHooks.RunHooks(ctx, exec, ArcgisServiceFeatureSlice{o}) + case bob.QueryTypeInsert: + ctx, err = ArcgisServiceFeatures.AfterInsertHooks.RunHooks(ctx, exec, ArcgisServiceFeatureSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = ArcgisServiceFeatures.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisServiceFeatureSlice{o}) + case bob.QueryTypeDelete: + ctx, err = ArcgisServiceFeatures.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisServiceFeatureSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the ArcgisServiceFeature +func (o *ArcgisServiceFeature) primaryKeyVals() bob.Expression { + return psql.Arg(o.ItemID) +} + +func (o *ArcgisServiceFeature) pkEQ() dialect.Expression { + return psql.Quote("arcgis.service_feature", "item_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 ArcgisServiceFeature +func (o *ArcgisServiceFeature) Update(ctx context.Context, exec bob.Executor, s *ArcgisServiceFeatureSetter) error { + v, err := ArcgisServiceFeatures.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 ArcgisServiceFeature record with an executor +func (o *ArcgisServiceFeature) Delete(ctx context.Context, exec bob.Executor) error { + _, err := ArcgisServiceFeatures.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the ArcgisServiceFeature using the executor +func (o *ArcgisServiceFeature) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := ArcgisServiceFeatures.Query( + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(o.ItemID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ArcgisServiceFeatureSlice is retrieved from the database +func (o ArcgisServiceFeatureSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisServiceFeatures.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = ArcgisServiceFeatures.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = ArcgisServiceFeatures.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = ArcgisServiceFeatures.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ArcgisServiceFeatureSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("arcgis.service_feature", "item_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 ArcgisServiceFeatureSlice) copyMatchingRows(from ...*ArcgisServiceFeature) { + for i, old := range o { + for _, new := range from { + if new.ItemID != old.ItemID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ArcgisServiceFeatureSlice) 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 ArcgisServiceFeatures.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 *ArcgisServiceFeature: + o.copyMatchingRows(retrieved) + case []*ArcgisServiceFeature: + o.copyMatchingRows(retrieved...) + case ArcgisServiceFeatureSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisServiceFeature or a slice of ArcgisServiceFeature + // then run the AfterUpdateHooks on the slice + _, err = ArcgisServiceFeatures.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ArcgisServiceFeatureSlice) 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 ArcgisServiceFeatures.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 *ArcgisServiceFeature: + o.copyMatchingRows(retrieved) + case []*ArcgisServiceFeature: + o.copyMatchingRows(retrieved...) + case ArcgisServiceFeatureSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisServiceFeature or a slice of ArcgisServiceFeature + // then run the AfterDeleteHooks on the slice + _, err = ArcgisServiceFeatures.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ArcgisServiceFeatureSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisServiceFeatureSetter) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisServiceFeatures.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ArcgisServiceFeatureSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisServiceFeatures.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ArcgisServiceFeatureSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := ArcgisServiceFeatures.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// FeatureServiceItemLayers starts a query for related objects on arcgis.layer +func (o *ArcgisServiceFeature) FeatureServiceItemLayers(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayersQuery { + return ArcgisLayers.Query(append(mods, + sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(o.ItemID))), + )...) +} + +func (os ArcgisServiceFeatureSlice) FeatureServiceItemLayers(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayersQuery { + pkItemID := make(pgtypes.Array[string], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkItemID = append(pkItemID, o.ItemID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkItemID), "text[]")), + )) + + return ArcgisLayers.Query(append(mods, + sm.Where(psql.Group(ArcgisLayers.Columns.FeatureServiceItemID).OP("IN", PKArgExpr)), + )...) +} + +// Account starts a query for related objects on arcgis.account +func (o *ArcgisServiceFeature) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + return ArcgisAccounts.Query(append(mods, + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.AccountID))), + )...) +} + +func (os ArcgisServiceFeatureSlice) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + pkAccountID := make(pgtypes.Array[null.Val[string]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkAccountID = append(pkAccountID, o.AccountID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkAccountID), "text[]")), + )) + + return ArcgisAccounts.Query(append(mods, + sm.Where(psql.Group(ArcgisAccounts.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// FieldseekerServiceFeatureItemOrganizations starts a query for related objects on organization +func (o *ArcgisServiceFeature) FieldseekerServiceFeatureItemOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + return Organizations.Query(append(mods, + sm.Where(Organizations.Columns.FieldseekerServiceFeatureItemID.EQ(psql.Arg(o.ItemID))), + )...) +} + +func (os ArcgisServiceFeatureSlice) FieldseekerServiceFeatureItemOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { + pkItemID := make(pgtypes.Array[string], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkItemID = append(pkItemID, o.ItemID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkItemID), "text[]")), + )) + + return Organizations.Query(append(mods, + sm.Where(psql.Group(Organizations.Columns.FieldseekerServiceFeatureItemID).OP("IN", PKArgExpr)), + )...) +} + +func insertArcgisServiceFeatureFeatureServiceItemLayers0(ctx context.Context, exec bob.Executor, arcgisLayers1 []*ArcgisLayerSetter, arcgisServiceFeature0 *ArcgisServiceFeature) (ArcgisLayerSlice, error) { + for i := range arcgisLayers1 { + arcgisLayers1[i].FeatureServiceItemID = omit.From(arcgisServiceFeature0.ItemID) + } + + ret, err := ArcgisLayers.Insert(bob.ToMods(arcgisLayers1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisServiceFeatureFeatureServiceItemLayers0: %w", err) + } + + return ret, nil +} + +func attachArcgisServiceFeatureFeatureServiceItemLayers0(ctx context.Context, exec bob.Executor, count int, arcgisLayers1 ArcgisLayerSlice, arcgisServiceFeature0 *ArcgisServiceFeature) (ArcgisLayerSlice, error) { + setter := &ArcgisLayerSetter{ + FeatureServiceItemID: omit.From(arcgisServiceFeature0.ItemID), + } + + err := arcgisLayers1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisServiceFeatureFeatureServiceItemLayers0: %w", err) + } + + return arcgisLayers1, nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisLayers1, err := insertArcgisServiceFeatureFeatureServiceItemLayers0(ctx, exec, related, arcgisServiceFeature0) + if err != nil { + return err + } + + arcgisServiceFeature0.R.FeatureServiceItemLayers = append(arcgisServiceFeature0.R.FeatureServiceItemLayers, arcgisLayers1...) + + for _, rel := range arcgisLayers1 { + rel.R.FeatureServiceItemServiceFeature = arcgisServiceFeature0 + } + return nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, related ...*ArcgisLayer) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisLayers1 := ArcgisLayerSlice(related) + + _, err = attachArcgisServiceFeatureFeatureServiceItemLayers0(ctx, exec, len(related), arcgisLayers1, arcgisServiceFeature0) + if err != nil { + return err + } + + arcgisServiceFeature0.R.FeatureServiceItemLayers = append(arcgisServiceFeature0.R.FeatureServiceItemLayers, arcgisLayers1...) + + for _, rel := range related { + rel.R.FeatureServiceItemServiceFeature = arcgisServiceFeature0 + } + + return nil +} + +func attachArcgisServiceFeatureAccount0(ctx context.Context, exec bob.Executor, count int, arcgisServiceFeature0 *ArcgisServiceFeature, arcgisAccount1 *ArcgisAccount) (*ArcgisServiceFeature, error) { + setter := &ArcgisServiceFeatureSetter{ + AccountID: omitnull.From(arcgisAccount1.ID), + } + + err := arcgisServiceFeature0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisServiceFeatureAccount0: %w", err) + } + + return arcgisServiceFeature0, nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertAccount(ctx context.Context, exec bob.Executor, related *ArcgisAccountSetter) error { + var err error + + arcgisAccount1, err := ArcgisAccounts.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachArcgisServiceFeatureAccount0(ctx, exec, 1, arcgisServiceFeature0, arcgisAccount1) + if err != nil { + return err + } + + arcgisServiceFeature0.R.Account = arcgisAccount1 + + arcgisAccount1.R.ServiceFeatures = append(arcgisAccount1.R.ServiceFeatures, arcgisServiceFeature0) + + return nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error { + var err error + + _, err = attachArcgisServiceFeatureAccount0(ctx, exec, 1, arcgisServiceFeature0, arcgisAccount1) + if err != nil { + return err + } + + arcgisServiceFeature0.R.Account = arcgisAccount1 + + arcgisAccount1.R.ServiceFeatures = append(arcgisAccount1.R.ServiceFeatures, arcgisServiceFeature0) + + return nil +} + +func insertArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx context.Context, exec bob.Executor, organizations1 []*OrganizationSetter, arcgisServiceFeature0 *ArcgisServiceFeature) (OrganizationSlice, error) { + for i := range organizations1 { + organizations1[i].FieldseekerServiceFeatureItemID = omitnull.From(arcgisServiceFeature0.ItemID) + } + + ret, err := Organizations.Insert(bob.ToMods(organizations1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0: %w", err) + } + + return ret, nil +} + +func attachArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx context.Context, exec bob.Executor, count int, organizations1 OrganizationSlice, arcgisServiceFeature0 *ArcgisServiceFeature) (OrganizationSlice, error) { + setter := &OrganizationSetter{ + FieldseekerServiceFeatureItemID: omitnull.From(arcgisServiceFeature0.ItemID), + } + + err := organizations1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0: %w", err) + } + + return organizations1, nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) InsertFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + organizations1, err := insertArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx, exec, related, arcgisServiceFeature0) + if err != nil { + return err + } + + arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations, organizations1...) + + for _, rel := range organizations1 { + rel.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature0 + } + return nil +} + +func (arcgisServiceFeature0 *ArcgisServiceFeature) AttachFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error { + if len(related) == 0 { + return nil + } + + var err error + organizations1 := OrganizationSlice(related) + + _, err = attachArcgisServiceFeatureFieldseekerServiceFeatureItemOrganizations0(ctx, exec, len(related), organizations1, arcgisServiceFeature0) + if err != nil { + return err + } + + arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature0.R.FieldseekerServiceFeatureItemOrganizations, organizations1...) + + for _, rel := range related { + rel.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature0 + } + + return nil +} + +type arcgisServiceFeatureWhere[Q psql.Filterable] struct { + Extent psql.WhereMod[Q, string] + ItemID psql.WhereMod[Q, string] + SpatialReference psql.WhereMod[Q, int32] + URL psql.WhereMod[Q, string] + AccountID psql.WhereNullMod[Q, string] +} + +func (arcgisServiceFeatureWhere[Q]) AliasedAs(alias string) arcgisServiceFeatureWhere[Q] { + return buildArcgisServiceFeatureWhere[Q](buildArcgisServiceFeatureColumns(alias)) +} + +func buildArcgisServiceFeatureWhere[Q psql.Filterable](cols arcgisServiceFeatureColumns) arcgisServiceFeatureWhere[Q] { + return arcgisServiceFeatureWhere[Q]{ + Extent: psql.Where[Q, string](cols.Extent), + ItemID: psql.Where[Q, string](cols.ItemID), + SpatialReference: psql.Where[Q, int32](cols.SpatialReference), + URL: psql.Where[Q, string](cols.URL), + AccountID: psql.WhereNull[Q, string](cols.AccountID), + } +} + +func (o *ArcgisServiceFeature) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "FeatureServiceItemLayers": + rels, ok := retrieved.(ArcgisLayerSlice) + if !ok { + return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name) + } + + o.R.FeatureServiceItemLayers = rels + + for _, rel := range rels { + if rel != nil { + rel.R.FeatureServiceItemServiceFeature = o + } + } + return nil + case "Account": + rel, ok := retrieved.(*ArcgisAccount) + if !ok { + return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name) + } + + o.R.Account = rel + + if rel != nil { + rel.R.ServiceFeatures = ArcgisServiceFeatureSlice{o} + } + return nil + case "FieldseekerServiceFeatureItemOrganizations": + rels, ok := retrieved.(OrganizationSlice) + if !ok { + return fmt.Errorf("arcgisServiceFeature cannot load %T as %q", retrieved, name) + } + + o.R.FieldseekerServiceFeatureItemOrganizations = rels + + for _, rel := range rels { + if rel != nil { + rel.R.FieldseekerServiceFeatureItemServiceFeature = o + } + } + return nil + default: + return fmt.Errorf("arcgisServiceFeature has no relationship %q", name) + } +} + +type arcgisServiceFeaturePreloader struct { + Account func(...psql.PreloadOption) psql.Preloader +} + +func buildArcgisServiceFeaturePreloader() arcgisServiceFeaturePreloader { + return arcgisServiceFeaturePreloader{ + Account: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{ + Name: "Account", + Sides: []psql.PreloadSide{ + { + From: ArcgisServiceFeatures, + To: ArcgisAccounts, + FromColumns: []string{"account_id"}, + ToColumns: []string{"id"}, + }, + }, + }, ArcgisAccounts.Columns.Names(), opts...) + }, + } +} + +type arcgisServiceFeatureThenLoader[Q orm.Loadable] struct { + FeatureServiceItemLayers func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Account func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisServiceFeatureThenLoader[Q orm.Loadable]() arcgisServiceFeatureThenLoader[Q] { + type FeatureServiceItemLayersLoadInterface interface { + LoadFeatureServiceItemLayers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type AccountLoadInterface interface { + LoadAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type FieldseekerServiceFeatureItemOrganizationsLoadInterface interface { + LoadFieldseekerServiceFeatureItemOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisServiceFeatureThenLoader[Q]{ + FeatureServiceItemLayers: thenLoadBuilder[Q]( + "FeatureServiceItemLayers", + func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemLayersLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadFeatureServiceItemLayers(ctx, exec, mods...) + }, + ), + Account: thenLoadBuilder[Q]( + "Account", + func(ctx context.Context, exec bob.Executor, retrieved AccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadAccount(ctx, exec, mods...) + }, + ), + FieldseekerServiceFeatureItemOrganizations: thenLoadBuilder[Q]( + "FieldseekerServiceFeatureItemOrganizations", + func(ctx context.Context, exec bob.Executor, retrieved FieldseekerServiceFeatureItemOrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...) + }, + ), + } +} + +// LoadFeatureServiceItemLayers loads the arcgisServiceFeature's FeatureServiceItemLayers into the .R struct +func (o *ArcgisServiceFeature) LoadFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.FeatureServiceItemLayers = nil + + related, err := o.FeatureServiceItemLayers(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.FeatureServiceItemServiceFeature = o + } + + o.R.FeatureServiceItemLayers = related + return nil +} + +// LoadFeatureServiceItemLayers loads the arcgisServiceFeature's FeatureServiceItemLayers into the .R struct +func (os ArcgisServiceFeatureSlice) LoadFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisLayers, err := os.FeatureServiceItemLayers(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.FeatureServiceItemLayers = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisLayers { + + if !(o.ItemID == rel.FeatureServiceItemID) { + continue + } + + rel.R.FeatureServiceItemServiceFeature = o + + o.R.FeatureServiceItemLayers = append(o.R.FeatureServiceItemLayers, rel) + } + } + + return nil +} + +// LoadAccount loads the arcgisServiceFeature's Account into the .R struct +func (o *ArcgisServiceFeature) LoadAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Account = nil + + related, err := o.Account(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.ServiceFeatures = ArcgisServiceFeatureSlice{o} + + o.R.Account = related + return nil +} + +// LoadAccount loads the arcgisServiceFeature's Account into the .R struct +func (os ArcgisServiceFeatureSlice) LoadAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisAccounts, err := os.Account(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisAccounts { + if !o.AccountID.IsValue() { + continue + } + + if !(o.AccountID.IsValue() && o.AccountID.MustGet() == rel.ID) { + continue + } + + rel.R.ServiceFeatures = append(rel.R.ServiceFeatures, o) + + o.R.Account = rel + break + } + } + + return nil +} + +// LoadFieldseekerServiceFeatureItemOrganizations loads the arcgisServiceFeature's FieldseekerServiceFeatureItemOrganizations into the .R struct +func (o *ArcgisServiceFeature) LoadFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.FieldseekerServiceFeatureItemOrganizations = nil + + related, err := o.FieldseekerServiceFeatureItemOrganizations(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.FieldseekerServiceFeatureItemServiceFeature = o + } + + o.R.FieldseekerServiceFeatureItemOrganizations = related + return nil +} + +// LoadFieldseekerServiceFeatureItemOrganizations loads the arcgisServiceFeature's FieldseekerServiceFeatureItemOrganizations into the .R struct +func (os ArcgisServiceFeatureSlice) LoadFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + organizations, err := os.FieldseekerServiceFeatureItemOrganizations(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.FieldseekerServiceFeatureItemOrganizations = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range organizations { + + if !rel.FieldseekerServiceFeatureItemID.IsValue() { + continue + } + if !(rel.FieldseekerServiceFeatureItemID.IsValue() && o.ItemID == rel.FieldseekerServiceFeatureItemID.MustGet()) { + continue + } + + rel.R.FieldseekerServiceFeatureItemServiceFeature = o + + o.R.FieldseekerServiceFeatureItemOrganizations = append(o.R.FieldseekerServiceFeatureItemOrganizations, rel) + } + } + + return nil +} + +// arcgisServiceFeatureC is where relationship counts are stored. +type arcgisServiceFeatureC struct { + FeatureServiceItemLayers *int64 + FieldseekerServiceFeatureItemOrganizations *int64 +} + +// PreloadCount sets a count in the C struct by name +func (o *ArcgisServiceFeature) PreloadCount(name string, count int64) error { + if o == nil { + return nil + } + + switch name { + case "FeatureServiceItemLayers": + o.C.FeatureServiceItemLayers = &count + case "FieldseekerServiceFeatureItemOrganizations": + o.C.FieldseekerServiceFeatureItemOrganizations = &count + } + return nil +} + +type arcgisServiceFeatureCountPreloader struct { + FeatureServiceItemLayers func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader +} + +func buildArcgisServiceFeatureCountPreloader() arcgisServiceFeatureCountPreloader { + return arcgisServiceFeatureCountPreloader{ + FeatureServiceItemLayers: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisServiceFeature]("FeatureServiceItemLayers", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisServiceFeatures.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisLayers.Name()), + sm.Where(psql.Quote(ArcgisLayers.Alias(), "feature_service_item_id").EQ(psql.Quote(parent, "item_id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + FieldseekerServiceFeatureItemOrganizations: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*ArcgisServiceFeature]("FieldseekerServiceFeatureItemOrganizations", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = ArcgisServiceFeatures.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Organizations.Name()), + sm.Where(psql.Quote(Organizations.Alias(), "fieldseeker_service_feature_item_id").EQ(psql.Quote(parent, "item_id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + } +} + +type arcgisServiceFeatureCountThenLoader[Q orm.Loadable] struct { + FeatureServiceItemLayers func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FieldseekerServiceFeatureItemOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisServiceFeatureCountThenLoader[Q orm.Loadable]() arcgisServiceFeatureCountThenLoader[Q] { + type FeatureServiceItemLayersCountInterface interface { + LoadCountFeatureServiceItemLayers(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type FieldseekerServiceFeatureItemOrganizationsCountInterface interface { + LoadCountFieldseekerServiceFeatureItemOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisServiceFeatureCountThenLoader[Q]{ + FeatureServiceItemLayers: countThenLoadBuilder[Q]( + "FeatureServiceItemLayers", + func(ctx context.Context, exec bob.Executor, retrieved FeatureServiceItemLayersCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountFeatureServiceItemLayers(ctx, exec, mods...) + }, + ), + FieldseekerServiceFeatureItemOrganizations: countThenLoadBuilder[Q]( + "FieldseekerServiceFeatureItemOrganizations", + func(ctx context.Context, exec bob.Executor, retrieved FieldseekerServiceFeatureItemOrganizationsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...) + }, + ), + } +} + +// LoadCountFeatureServiceItemLayers loads the count of FeatureServiceItemLayers into the C struct +func (o *ArcgisServiceFeature) LoadCountFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.FeatureServiceItemLayers(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.FeatureServiceItemLayers = &count + return nil +} + +// LoadCountFeatureServiceItemLayers loads the count of FeatureServiceItemLayers for a slice +func (os ArcgisServiceFeatureSlice) LoadCountFeatureServiceItemLayers(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountFeatureServiceItemLayers(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountFieldseekerServiceFeatureItemOrganizations loads the count of FieldseekerServiceFeatureItemOrganizations into the C struct +func (o *ArcgisServiceFeature) LoadCountFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.FieldseekerServiceFeatureItemOrganizations(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.FieldseekerServiceFeatureItemOrganizations = &count + return nil +} + +// LoadCountFieldseekerServiceFeatureItemOrganizations loads the count of FieldseekerServiceFeatureItemOrganizations for a slice +func (os ArcgisServiceFeatureSlice) LoadCountFieldseekerServiceFeatureItemOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountFieldseekerServiceFeatureItemOrganizations(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +type arcgisServiceFeatureJoins[Q dialect.Joinable] struct { + typ string + FeatureServiceItemLayers modAs[Q, arcgisLayerColumns] + Account modAs[Q, arcgisAccountColumns] + FieldseekerServiceFeatureItemOrganizations modAs[Q, organizationColumns] +} + +func (j arcgisServiceFeatureJoins[Q]) aliasedAs(alias string) arcgisServiceFeatureJoins[Q] { + return buildArcgisServiceFeatureJoins[Q](buildArcgisServiceFeatureColumns(alias), j.typ) +} + +func buildArcgisServiceFeatureJoins[Q dialect.Joinable](cols arcgisServiceFeatureColumns, typ string) arcgisServiceFeatureJoins[Q] { + return arcgisServiceFeatureJoins[Q]{ + typ: typ, + FeatureServiceItemLayers: modAs[Q, arcgisLayerColumns]{ + c: ArcgisLayers.Columns, + f: func(to arcgisLayerColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisLayers.Name().As(to.Alias())).On( + to.FeatureServiceItemID.EQ(cols.ItemID), + )) + } + + return mods + }, + }, + Account: modAs[Q, arcgisAccountColumns]{ + c: ArcgisAccounts.Columns, + f: func(to arcgisAccountColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On( + to.ID.EQ(cols.AccountID), + )) + } + + return mods + }, + }, + FieldseekerServiceFeatureItemOrganizations: modAs[Q, organizationColumns]{ + c: Organizations.Columns, + f: func(to organizationColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Organizations.Name().As(to.Alias())).On( + to.FieldseekerServiceFeatureItemID.EQ(cols.ItemID), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/arcgis.service_map.bob.go b/db/models/arcgis.service_map.bob.go new file mode 100644 index 00000000..2f64922a --- /dev/null +++ b/db/models/arcgis.service_map.bob.go @@ -0,0 +1,677 @@ +// 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/mods" + "github.com/Gleipnir-Technology/bob/orm" + "github.com/Gleipnir-Technology/bob/types/pgtypes" + "github.com/aarondl/opt/omit" +) + +// ArcgisServiceMap is an object representing the database table. +type ArcgisServiceMap struct { + AccountID string `db:"account_id" ` + ArcgisID string `db:"arcgis_id,pk" ` + Name string `db:"name" ` + Title string `db:"title" ` + URL string `db:"url" ` + + R arcgisServiceMapR `db:"-" ` +} + +// ArcgisServiceMapSlice is an alias for a slice of pointers to ArcgisServiceMap. +// This should almost always be used instead of []*ArcgisServiceMap. +type ArcgisServiceMapSlice []*ArcgisServiceMap + +// ArcgisServiceMaps contains methods to work with the service_map table +var ArcgisServiceMaps = psql.NewTablex[*ArcgisServiceMap, ArcgisServiceMapSlice, *ArcgisServiceMapSetter]("arcgis", "service_map", buildArcgisServiceMapColumns("arcgis.service_map")) + +// ArcgisServiceMapsQuery is a query on the service_map table +type ArcgisServiceMapsQuery = *psql.ViewQuery[*ArcgisServiceMap, ArcgisServiceMapSlice] + +// arcgisServiceMapR is where relationships are stored. +type arcgisServiceMapR struct { + Account *ArcgisAccount // arcgis.service_map.service_map_account_id_fkey +} + +func buildArcgisServiceMapColumns(alias string) arcgisServiceMapColumns { + return arcgisServiceMapColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "account_id", "arcgis_id", "name", "title", "url", + ).WithParent("arcgis.service_map"), + tableAlias: alias, + AccountID: psql.Quote(alias, "account_id"), + ArcgisID: psql.Quote(alias, "arcgis_id"), + Name: psql.Quote(alias, "name"), + Title: psql.Quote(alias, "title"), + URL: psql.Quote(alias, "url"), + } +} + +type arcgisServiceMapColumns struct { + expr.ColumnsExpr + tableAlias string + AccountID psql.Expression + ArcgisID psql.Expression + Name psql.Expression + Title psql.Expression + URL psql.Expression +} + +func (c arcgisServiceMapColumns) Alias() string { + return c.tableAlias +} + +func (arcgisServiceMapColumns) AliasedAs(alias string) arcgisServiceMapColumns { + return buildArcgisServiceMapColumns(alias) +} + +// ArcgisServiceMapSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ArcgisServiceMapSetter struct { + AccountID omit.Val[string] `db:"account_id" ` + ArcgisID omit.Val[string] `db:"arcgis_id,pk" ` + Name omit.Val[string] `db:"name" ` + Title omit.Val[string] `db:"title" ` + URL omit.Val[string] `db:"url" ` +} + +func (s ArcgisServiceMapSetter) SetColumns() []string { + vals := make([]string, 0, 5) + if s.AccountID.IsValue() { + vals = append(vals, "account_id") + } + if s.ArcgisID.IsValue() { + vals = append(vals, "arcgis_id") + } + if s.Name.IsValue() { + vals = append(vals, "name") + } + if s.Title.IsValue() { + vals = append(vals, "title") + } + if s.URL.IsValue() { + vals = append(vals, "url") + } + return vals +} + +func (s ArcgisServiceMapSetter) Overwrite(t *ArcgisServiceMap) { + if s.AccountID.IsValue() { + t.AccountID = s.AccountID.MustGet() + } + if s.ArcgisID.IsValue() { + t.ArcgisID = s.ArcgisID.MustGet() + } + if s.Name.IsValue() { + t.Name = s.Name.MustGet() + } + if s.Title.IsValue() { + t.Title = s.Title.MustGet() + } + if s.URL.IsValue() { + t.URL = s.URL.MustGet() + } +} + +func (s *ArcgisServiceMapSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return ArcgisServiceMaps.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, 5) + if s.AccountID.IsValue() { + vals[0] = psql.Arg(s.AccountID.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.ArcgisID.IsValue() { + vals[1] = psql.Arg(s.ArcgisID.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.Name.IsValue() { + vals[2] = psql.Arg(s.Name.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if s.Title.IsValue() { + vals[3] = psql.Arg(s.Title.MustGet()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if s.URL.IsValue() { + vals[4] = psql.Arg(s.URL.MustGet()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ArcgisServiceMapSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ArcgisServiceMapSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 5) + + if s.AccountID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "account_id")...), + psql.Arg(s.AccountID), + }}) + } + + if s.ArcgisID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "arcgis_id")...), + psql.Arg(s.ArcgisID), + }}) + } + + if s.Name.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "name")...), + psql.Arg(s.Name), + }}) + } + + if s.Title.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "title")...), + psql.Arg(s.Title), + }}) + } + + if s.URL.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "url")...), + psql.Arg(s.URL), + }}) + } + + return exprs +} + +// FindArcgisServiceMap retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindArcgisServiceMap(ctx context.Context, exec bob.Executor, ArcgisIDPK string, cols ...string) (*ArcgisServiceMap, error) { + if len(cols) == 0 { + return ArcgisServiceMaps.Query( + sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(ArcgisIDPK))), + ).One(ctx, exec) + } + + return ArcgisServiceMaps.Query( + sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(ArcgisIDPK))), + sm.Columns(ArcgisServiceMaps.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ArcgisServiceMapExists checks the presence of a single record by primary key +func ArcgisServiceMapExists(ctx context.Context, exec bob.Executor, ArcgisIDPK string) (bool, error) { + return ArcgisServiceMaps.Query( + sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(ArcgisIDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after ArcgisServiceMap is retrieved from the database +func (o *ArcgisServiceMap) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisServiceMaps.AfterSelectHooks.RunHooks(ctx, exec, ArcgisServiceMapSlice{o}) + case bob.QueryTypeInsert: + ctx, err = ArcgisServiceMaps.AfterInsertHooks.RunHooks(ctx, exec, ArcgisServiceMapSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = ArcgisServiceMaps.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisServiceMapSlice{o}) + case bob.QueryTypeDelete: + ctx, err = ArcgisServiceMaps.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisServiceMapSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the ArcgisServiceMap +func (o *ArcgisServiceMap) primaryKeyVals() bob.Expression { + return psql.Arg(o.ArcgisID) +} + +func (o *ArcgisServiceMap) pkEQ() dialect.Expression { + return psql.Quote("arcgis.service_map", "arcgis_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 ArcgisServiceMap +func (o *ArcgisServiceMap) Update(ctx context.Context, exec bob.Executor, s *ArcgisServiceMapSetter) error { + v, err := ArcgisServiceMaps.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 ArcgisServiceMap record with an executor +func (o *ArcgisServiceMap) Delete(ctx context.Context, exec bob.Executor) error { + _, err := ArcgisServiceMaps.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the ArcgisServiceMap using the executor +func (o *ArcgisServiceMap) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := ArcgisServiceMaps.Query( + sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(o.ArcgisID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ArcgisServiceMapSlice is retrieved from the database +func (o ArcgisServiceMapSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ArcgisServiceMaps.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = ArcgisServiceMaps.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = ArcgisServiceMaps.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = ArcgisServiceMaps.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ArcgisServiceMapSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("arcgis.service_map", "arcgis_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 ArcgisServiceMapSlice) copyMatchingRows(from ...*ArcgisServiceMap) { + for i, old := range o { + for _, new := range from { + if new.ArcgisID != old.ArcgisID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ArcgisServiceMapSlice) 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 ArcgisServiceMaps.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 *ArcgisServiceMap: + o.copyMatchingRows(retrieved) + case []*ArcgisServiceMap: + o.copyMatchingRows(retrieved...) + case ArcgisServiceMapSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisServiceMap or a slice of ArcgisServiceMap + // then run the AfterUpdateHooks on the slice + _, err = ArcgisServiceMaps.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ArcgisServiceMapSlice) 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 ArcgisServiceMaps.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 *ArcgisServiceMap: + o.copyMatchingRows(retrieved) + case []*ArcgisServiceMap: + o.copyMatchingRows(retrieved...) + case ArcgisServiceMapSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ArcgisServiceMap or a slice of ArcgisServiceMap + // then run the AfterDeleteHooks on the slice + _, err = ArcgisServiceMaps.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ArcgisServiceMapSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisServiceMapSetter) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisServiceMaps.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ArcgisServiceMapSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := ArcgisServiceMaps.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ArcgisServiceMapSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := ArcgisServiceMaps.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// Account starts a query for related objects on arcgis.account +func (o *ArcgisServiceMap) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + return ArcgisAccounts.Query(append(mods, + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.AccountID))), + )...) +} + +func (os ArcgisServiceMapSlice) Account(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + pkAccountID := make(pgtypes.Array[string], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkAccountID = append(pkAccountID, o.AccountID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkAccountID), "text[]")), + )) + + return ArcgisAccounts.Query(append(mods, + sm.Where(psql.Group(ArcgisAccounts.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +func attachArcgisServiceMapAccount0(ctx context.Context, exec bob.Executor, count int, arcgisServiceMap0 *ArcgisServiceMap, arcgisAccount1 *ArcgisAccount) (*ArcgisServiceMap, error) { + setter := &ArcgisServiceMapSetter{ + AccountID: omit.From(arcgisAccount1.ID), + } + + err := arcgisServiceMap0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachArcgisServiceMapAccount0: %w", err) + } + + return arcgisServiceMap0, nil +} + +func (arcgisServiceMap0 *ArcgisServiceMap) InsertAccount(ctx context.Context, exec bob.Executor, related *ArcgisAccountSetter) error { + var err error + + arcgisAccount1, err := ArcgisAccounts.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachArcgisServiceMapAccount0(ctx, exec, 1, arcgisServiceMap0, arcgisAccount1) + if err != nil { + return err + } + + arcgisServiceMap0.R.Account = arcgisAccount1 + + arcgisAccount1.R.ServiceMaps = append(arcgisAccount1.R.ServiceMaps, arcgisServiceMap0) + + return nil +} + +func (arcgisServiceMap0 *ArcgisServiceMap) AttachAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error { + var err error + + _, err = attachArcgisServiceMapAccount0(ctx, exec, 1, arcgisServiceMap0, arcgisAccount1) + if err != nil { + return err + } + + arcgisServiceMap0.R.Account = arcgisAccount1 + + arcgisAccount1.R.ServiceMaps = append(arcgisAccount1.R.ServiceMaps, arcgisServiceMap0) + + return nil +} + +type arcgisServiceMapWhere[Q psql.Filterable] struct { + AccountID psql.WhereMod[Q, string] + ArcgisID psql.WhereMod[Q, string] + Name psql.WhereMod[Q, string] + Title psql.WhereMod[Q, string] + URL psql.WhereMod[Q, string] +} + +func (arcgisServiceMapWhere[Q]) AliasedAs(alias string) arcgisServiceMapWhere[Q] { + return buildArcgisServiceMapWhere[Q](buildArcgisServiceMapColumns(alias)) +} + +func buildArcgisServiceMapWhere[Q psql.Filterable](cols arcgisServiceMapColumns) arcgisServiceMapWhere[Q] { + return arcgisServiceMapWhere[Q]{ + AccountID: psql.Where[Q, string](cols.AccountID), + ArcgisID: psql.Where[Q, string](cols.ArcgisID), + Name: psql.Where[Q, string](cols.Name), + Title: psql.Where[Q, string](cols.Title), + URL: psql.Where[Q, string](cols.URL), + } +} + +func (o *ArcgisServiceMap) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "Account": + rel, ok := retrieved.(*ArcgisAccount) + if !ok { + return fmt.Errorf("arcgisServiceMap cannot load %T as %q", retrieved, name) + } + + o.R.Account = rel + + if rel != nil { + rel.R.ServiceMaps = ArcgisServiceMapSlice{o} + } + return nil + default: + return fmt.Errorf("arcgisServiceMap has no relationship %q", name) + } +} + +type arcgisServiceMapPreloader struct { + Account func(...psql.PreloadOption) psql.Preloader +} + +func buildArcgisServiceMapPreloader() arcgisServiceMapPreloader { + return arcgisServiceMapPreloader{ + Account: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{ + Name: "Account", + Sides: []psql.PreloadSide{ + { + From: ArcgisServiceMaps, + To: ArcgisAccounts, + FromColumns: []string{"account_id"}, + ToColumns: []string{"id"}, + }, + }, + }, ArcgisAccounts.Columns.Names(), opts...) + }, + } +} + +type arcgisServiceMapThenLoader[Q orm.Loadable] struct { + Account func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildArcgisServiceMapThenLoader[Q orm.Loadable]() arcgisServiceMapThenLoader[Q] { + type AccountLoadInterface interface { + LoadAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return arcgisServiceMapThenLoader[Q]{ + Account: thenLoadBuilder[Q]( + "Account", + func(ctx context.Context, exec bob.Executor, retrieved AccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadAccount(ctx, exec, mods...) + }, + ), + } +} + +// LoadAccount loads the arcgisServiceMap's Account into the .R struct +func (o *ArcgisServiceMap) LoadAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Account = nil + + related, err := o.Account(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.ServiceMaps = ArcgisServiceMapSlice{o} + + o.R.Account = related + return nil +} + +// LoadAccount loads the arcgisServiceMap's Account into the .R struct +func (os ArcgisServiceMapSlice) LoadAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisAccounts, err := os.Account(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisAccounts { + + if !(o.AccountID == rel.ID) { + continue + } + + rel.R.ServiceMaps = append(rel.R.ServiceMaps, o) + + o.R.Account = rel + break + } + } + + return nil +} + +type arcgisServiceMapJoins[Q dialect.Joinable] struct { + typ string + Account modAs[Q, arcgisAccountColumns] +} + +func (j arcgisServiceMapJoins[Q]) aliasedAs(alias string) arcgisServiceMapJoins[Q] { + return buildArcgisServiceMapJoins[Q](buildArcgisServiceMapColumns(alias), j.typ) +} + +func buildArcgisServiceMapJoins[Q dialect.Joinable](cols arcgisServiceMapColumns, typ string) arcgisServiceMapJoins[Q] { + return arcgisServiceMapJoins[Q]{ + typ: typ, + Account: modAs[Q, arcgisAccountColumns]{ + c: ArcgisAccounts.Columns, + f: func(to arcgisAccountColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On( + to.ID.EQ(cols.AccountID), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/bob_counts.bob.go b/db/models/bob_counts.bob.go index 5f015649..096c80f1 100644 --- a/db/models/bob_counts.bob.go +++ b/db/models/bob_counts.bob.go @@ -21,9 +21,11 @@ var ( ) type preloadCounts struct { - ArcgisFeatureService arcgisFeatureServiceCountPreloader + Address addressCountPreloader + ArcgisAccount arcgisAccountCountPreloader ArcgisLayer arcgisLayerCountPreloader ArcgisLayerField arcgisLayerFieldCountPreloader + ArcgisServiceFeature arcgisServiceFeatureCountPreloader ArcgisUser arcgisuserCountPreloader CommsEmailContact commsEmailContactCountPreloader CommsEmailTemplate commsEmailTemplateCountPreloader @@ -33,18 +35,22 @@ type preloadCounts struct { NoteAudio noteAudioCountPreloader NoteImage noteImageCountPreloader Organization organizationCountPreloader + Parcel parcelCountPreloader PublicreportImage publicreportImageCountPreloader PublicreportNuisance publicreportNuisanceCountPreloader PublicreportPool publicreportPoolCountPreloader PublicreportQuick publicreportQuickCountPreloader + Site siteCountPreloader User userCountPreloader } func getPreloadCount() preloadCounts { return preloadCounts{ - ArcgisFeatureService: buildArcgisFeatureServiceCountPreloader(), + Address: buildAddressCountPreloader(), + ArcgisAccount: buildArcgisAccountCountPreloader(), ArcgisLayer: buildArcgisLayerCountPreloader(), ArcgisLayerField: buildArcgisLayerFieldCountPreloader(), + ArcgisServiceFeature: buildArcgisServiceFeatureCountPreloader(), ArcgisUser: buildArcgisUserCountPreloader(), CommsEmailContact: buildCommsEmailContactCountPreloader(), CommsEmailTemplate: buildCommsEmailTemplateCountPreloader(), @@ -54,18 +60,22 @@ func getPreloadCount() preloadCounts { NoteAudio: buildNoteAudioCountPreloader(), NoteImage: buildNoteImageCountPreloader(), Organization: buildOrganizationCountPreloader(), + Parcel: buildParcelCountPreloader(), PublicreportImage: buildPublicreportImageCountPreloader(), PublicreportNuisance: buildPublicreportNuisanceCountPreloader(), PublicreportPool: buildPublicreportPoolCountPreloader(), PublicreportQuick: buildPublicreportQuickCountPreloader(), + Site: buildSiteCountPreloader(), User: buildUserCountPreloader(), } } type thenLoadCounts[Q orm.Loadable] struct { - ArcgisFeatureService arcgisFeatureServiceCountThenLoader[Q] + Address addressCountThenLoader[Q] + ArcgisAccount arcgisAccountCountThenLoader[Q] ArcgisLayer arcgisLayerCountThenLoader[Q] ArcgisLayerField arcgisLayerFieldCountThenLoader[Q] + ArcgisServiceFeature arcgisServiceFeatureCountThenLoader[Q] ArcgisUser arcgisuserCountThenLoader[Q] CommsEmailContact commsEmailContactCountThenLoader[Q] CommsEmailTemplate commsEmailTemplateCountThenLoader[Q] @@ -75,18 +85,22 @@ type thenLoadCounts[Q orm.Loadable] struct { NoteAudio noteAudioCountThenLoader[Q] NoteImage noteImageCountThenLoader[Q] Organization organizationCountThenLoader[Q] + Parcel parcelCountThenLoader[Q] PublicreportImage publicreportImageCountThenLoader[Q] PublicreportNuisance publicreportNuisanceCountThenLoader[Q] PublicreportPool publicreportPoolCountThenLoader[Q] PublicreportQuick publicreportQuickCountThenLoader[Q] + Site siteCountThenLoader[Q] User userCountThenLoader[Q] } func getThenLoadCount[Q orm.Loadable]() thenLoadCounts[Q] { return thenLoadCounts[Q]{ - ArcgisFeatureService: buildArcgisFeatureServiceCountThenLoader[Q](), + Address: buildAddressCountThenLoader[Q](), + ArcgisAccount: buildArcgisAccountCountThenLoader[Q](), ArcgisLayer: buildArcgisLayerCountThenLoader[Q](), ArcgisLayerField: buildArcgisLayerFieldCountThenLoader[Q](), + ArcgisServiceFeature: buildArcgisServiceFeatureCountThenLoader[Q](), ArcgisUser: buildArcgisUserCountThenLoader[Q](), CommsEmailContact: buildCommsEmailContactCountThenLoader[Q](), CommsEmailTemplate: buildCommsEmailTemplateCountThenLoader[Q](), @@ -96,10 +110,12 @@ func getThenLoadCount[Q orm.Loadable]() thenLoadCounts[Q] { NoteAudio: buildNoteAudioCountThenLoader[Q](), NoteImage: buildNoteImageCountThenLoader[Q](), Organization: buildOrganizationCountThenLoader[Q](), + Parcel: buildParcelCountThenLoader[Q](), PublicreportImage: buildPublicreportImageCountThenLoader[Q](), PublicreportNuisance: buildPublicreportNuisanceCountThenLoader[Q](), PublicreportPool: buildPublicreportPoolCountThenLoader[Q](), PublicreportQuick: buildPublicreportQuickCountThenLoader[Q](), + Site: buildSiteCountThenLoader[Q](), User: buildUserCountThenLoader[Q](), } } diff --git a/db/models/bob_joins.bob.go b/db/models/bob_joins.bob.go index 3ae21741..32de2dbc 100644 --- a/db/models/bob_joins.bob.go +++ b/db/models/bob_joins.bob.go @@ -33,11 +33,14 @@ func (j joinSet[Q]) AliasedAs(alias string) joinSet[Q] { type joins[Q dialect.Joinable] struct { Addresses joinSet[addressJoins[Q]] + ArcgisAccounts joinSet[arcgisAccountJoins[Q]] ArcgisAddressMappings joinSet[arcgisAddressMappingJoins[Q]] - ArcgisFeatureServices joinSet[arcgisFeatureServiceJoins[Q]] ArcgisLayers joinSet[arcgisLayerJoins[Q]] ArcgisLayerFields joinSet[arcgisLayerFieldJoins[Q]] + ArcgisOauthTokens joinSet[arcgisOauthTokenJoins[Q]] ArcgisParcelMappings joinSet[arcgisParcelMappingJoins[Q]] + ArcgisServiceFeatures joinSet[arcgisServiceFeatureJoins[Q]] + ArcgisServiceMaps joinSet[arcgisServiceMapJoins[Q]] ArcgisUsers joinSet[arcgisuserJoins[Q]] ArcgisUserPrivileges joinSet[arcgisUserPrivilegeJoins[Q]] CommsEmailContacts joinSet[commsEmailContactJoins[Q]] @@ -46,6 +49,7 @@ type joins[Q dialect.Joinable] struct { CommsPhones joinSet[commsPhoneJoins[Q]] CommsTextJobs joinSet[commsTextJobJoins[Q]] CommsTextLogs joinSet[commsTextLogJoins[Q]] + ComplianceReportRequests joinSet[complianceReportRequestJoins[Q]] DistrictSubscriptionEmails joinSet[districtSubscriptionEmailJoins[Q]] DistrictSubscriptionPhones joinSet[districtSubscriptionPhoneJoins[Q]] FieldseekerContainerrelates joinSet[fieldseekerContainerrelateJoins[Q]] @@ -89,8 +93,8 @@ type joins[Q dialect.Joinable] struct { NoteImageBreadcrumbs joinSet[noteImageBreadcrumbJoins[Q]] NoteImageData joinSet[noteImageDatumJoins[Q]] Notifications joinSet[notificationJoins[Q]] - OauthTokens joinSet[oauthTokenJoins[Q]] Organizations joinSet[organizationJoins[Q]] + Parcels joinSet[parcelJoins[Q]] Pools joinSet[poolJoins[Q]] PublicreportImages joinSet[publicreportImageJoins[Q]] PublicreportImageExifs joinSet[publicreportImageExifJoins[Q]] @@ -106,6 +110,7 @@ type joins[Q dialect.Joinable] struct { PublicreportQuickImages joinSet[publicreportQuickImageJoins[Q]] PublicreportSubscribeEmails joinSet[publicreportSubscribeEmailJoins[Q]] PublicreportSubscribePhones joinSet[publicreportSubscribePhoneJoins[Q]] + Residents joinSet[residentJoins[Q]] Sites joinSet[siteJoins[Q]] Users joinSet[userJoins[Q]] } @@ -121,11 +126,14 @@ func buildJoinSet[Q interface{ aliasedAs(string) Q }, C any, F func(C, string) Q func getJoins[Q dialect.Joinable]() joins[Q] { return joins[Q]{ Addresses: buildJoinSet[addressJoins[Q]](Addresses.Columns, buildAddressJoins), + ArcgisAccounts: buildJoinSet[arcgisAccountJoins[Q]](ArcgisAccounts.Columns, buildArcgisAccountJoins), ArcgisAddressMappings: buildJoinSet[arcgisAddressMappingJoins[Q]](ArcgisAddressMappings.Columns, buildArcgisAddressMappingJoins), - ArcgisFeatureServices: buildJoinSet[arcgisFeatureServiceJoins[Q]](ArcgisFeatureServices.Columns, buildArcgisFeatureServiceJoins), ArcgisLayers: buildJoinSet[arcgisLayerJoins[Q]](ArcgisLayers.Columns, buildArcgisLayerJoins), ArcgisLayerFields: buildJoinSet[arcgisLayerFieldJoins[Q]](ArcgisLayerFields.Columns, buildArcgisLayerFieldJoins), + ArcgisOauthTokens: buildJoinSet[arcgisOauthTokenJoins[Q]](ArcgisOauthTokens.Columns, buildArcgisOauthTokenJoins), ArcgisParcelMappings: buildJoinSet[arcgisParcelMappingJoins[Q]](ArcgisParcelMappings.Columns, buildArcgisParcelMappingJoins), + ArcgisServiceFeatures: buildJoinSet[arcgisServiceFeatureJoins[Q]](ArcgisServiceFeatures.Columns, buildArcgisServiceFeatureJoins), + ArcgisServiceMaps: buildJoinSet[arcgisServiceMapJoins[Q]](ArcgisServiceMaps.Columns, buildArcgisServiceMapJoins), ArcgisUsers: buildJoinSet[arcgisuserJoins[Q]](ArcgisUsers.Columns, buildArcgisUserJoins), ArcgisUserPrivileges: buildJoinSet[arcgisUserPrivilegeJoins[Q]](ArcgisUserPrivileges.Columns, buildArcgisUserPrivilegeJoins), CommsEmailContacts: buildJoinSet[commsEmailContactJoins[Q]](CommsEmailContacts.Columns, buildCommsEmailContactJoins), @@ -134,6 +142,7 @@ func getJoins[Q dialect.Joinable]() joins[Q] { CommsPhones: buildJoinSet[commsPhoneJoins[Q]](CommsPhones.Columns, buildCommsPhoneJoins), CommsTextJobs: buildJoinSet[commsTextJobJoins[Q]](CommsTextJobs.Columns, buildCommsTextJobJoins), CommsTextLogs: buildJoinSet[commsTextLogJoins[Q]](CommsTextLogs.Columns, buildCommsTextLogJoins), + ComplianceReportRequests: buildJoinSet[complianceReportRequestJoins[Q]](ComplianceReportRequests.Columns, buildComplianceReportRequestJoins), DistrictSubscriptionEmails: buildJoinSet[districtSubscriptionEmailJoins[Q]](DistrictSubscriptionEmails.Columns, buildDistrictSubscriptionEmailJoins), DistrictSubscriptionPhones: buildJoinSet[districtSubscriptionPhoneJoins[Q]](DistrictSubscriptionPhones.Columns, buildDistrictSubscriptionPhoneJoins), FieldseekerContainerrelates: buildJoinSet[fieldseekerContainerrelateJoins[Q]](FieldseekerContainerrelates.Columns, buildFieldseekerContainerrelateJoins), @@ -177,8 +186,8 @@ func getJoins[Q dialect.Joinable]() joins[Q] { NoteImageBreadcrumbs: buildJoinSet[noteImageBreadcrumbJoins[Q]](NoteImageBreadcrumbs.Columns, buildNoteImageBreadcrumbJoins), NoteImageData: buildJoinSet[noteImageDatumJoins[Q]](NoteImageData.Columns, buildNoteImageDatumJoins), Notifications: buildJoinSet[notificationJoins[Q]](Notifications.Columns, buildNotificationJoins), - OauthTokens: buildJoinSet[oauthTokenJoins[Q]](OauthTokens.Columns, buildOauthTokenJoins), Organizations: buildJoinSet[organizationJoins[Q]](Organizations.Columns, buildOrganizationJoins), + Parcels: buildJoinSet[parcelJoins[Q]](Parcels.Columns, buildParcelJoins), Pools: buildJoinSet[poolJoins[Q]](Pools.Columns, buildPoolJoins), PublicreportImages: buildJoinSet[publicreportImageJoins[Q]](PublicreportImages.Columns, buildPublicreportImageJoins), PublicreportImageExifs: buildJoinSet[publicreportImageExifJoins[Q]](PublicreportImageExifs.Columns, buildPublicreportImageExifJoins), @@ -194,6 +203,7 @@ func getJoins[Q dialect.Joinable]() joins[Q] { PublicreportQuickImages: buildJoinSet[publicreportQuickImageJoins[Q]](PublicreportQuickImages.Columns, buildPublicreportQuickImageJoins), PublicreportSubscribeEmails: buildJoinSet[publicreportSubscribeEmailJoins[Q]](PublicreportSubscribeEmails.Columns, buildPublicreportSubscribeEmailJoins), PublicreportSubscribePhones: buildJoinSet[publicreportSubscribePhoneJoins[Q]](PublicreportSubscribePhones.Columns, buildPublicreportSubscribePhoneJoins), + Residents: buildJoinSet[residentJoins[Q]](Residents.Columns, buildResidentJoins), Sites: buildJoinSet[siteJoins[Q]](Sites.Columns, buildSiteJoins), Users: buildJoinSet[userJoins[Q]](Users.Columns, buildUserJoins), } diff --git a/db/models/bob_loaders.bob.go b/db/models/bob_loaders.bob.go index ab8cae6f..fd26aa43 100644 --- a/db/models/bob_loaders.bob.go +++ b/db/models/bob_loaders.bob.go @@ -18,11 +18,14 @@ var Preload = getPreloaders() type preloaders struct { Address addressPreloader + ArcgisAccount arcgisAccountPreloader ArcgisAddressMapping arcgisAddressMappingPreloader - ArcgisFeatureService arcgisFeatureServicePreloader ArcgisLayer arcgisLayerPreloader ArcgisLayerField arcgisLayerFieldPreloader + ArcgisOauthToken arcgisOauthTokenPreloader ArcgisParcelMapping arcgisParcelMappingPreloader + ArcgisServiceFeature arcgisServiceFeaturePreloader + ArcgisServiceMap arcgisServiceMapPreloader ArcgisUser arcgisuserPreloader ArcgisUserPrivilege arcgisUserPrivilegePreloader CommsEmailContact commsEmailContactPreloader @@ -31,6 +34,7 @@ type preloaders struct { CommsPhone commsPhonePreloader CommsTextJob commsTextJobPreloader CommsTextLog commsTextLogPreloader + ComplianceReportRequest complianceReportRequestPreloader DistrictSubscriptionEmail districtSubscriptionEmailPreloader DistrictSubscriptionPhone districtSubscriptionPhonePreloader FieldseekerContainerrelate fieldseekerContainerrelatePreloader @@ -74,8 +78,8 @@ type preloaders struct { NoteImageBreadcrumb noteImageBreadcrumbPreloader NoteImageDatum noteImageDatumPreloader Notification notificationPreloader - OauthToken oauthTokenPreloader Organization organizationPreloader + Parcel parcelPreloader Pool poolPreloader PublicreportImage publicreportImagePreloader PublicreportImageExif publicreportImageExifPreloader @@ -91,6 +95,7 @@ type preloaders struct { PublicreportQuickImage publicreportQuickImagePreloader PublicreportSubscribeEmail publicreportSubscribeEmailPreloader PublicreportSubscribePhone publicreportSubscribePhonePreloader + Resident residentPreloader Site sitePreloader User userPreloader } @@ -98,11 +103,14 @@ type preloaders struct { func getPreloaders() preloaders { return preloaders{ Address: buildAddressPreloader(), + ArcgisAccount: buildArcgisAccountPreloader(), ArcgisAddressMapping: buildArcgisAddressMappingPreloader(), - ArcgisFeatureService: buildArcgisFeatureServicePreloader(), ArcgisLayer: buildArcgisLayerPreloader(), ArcgisLayerField: buildArcgisLayerFieldPreloader(), + ArcgisOauthToken: buildArcgisOauthTokenPreloader(), ArcgisParcelMapping: buildArcgisParcelMappingPreloader(), + ArcgisServiceFeature: buildArcgisServiceFeaturePreloader(), + ArcgisServiceMap: buildArcgisServiceMapPreloader(), ArcgisUser: buildArcgisUserPreloader(), ArcgisUserPrivilege: buildArcgisUserPrivilegePreloader(), CommsEmailContact: buildCommsEmailContactPreloader(), @@ -111,6 +119,7 @@ func getPreloaders() preloaders { CommsPhone: buildCommsPhonePreloader(), CommsTextJob: buildCommsTextJobPreloader(), CommsTextLog: buildCommsTextLogPreloader(), + ComplianceReportRequest: buildComplianceReportRequestPreloader(), DistrictSubscriptionEmail: buildDistrictSubscriptionEmailPreloader(), DistrictSubscriptionPhone: buildDistrictSubscriptionPhonePreloader(), FieldseekerContainerrelate: buildFieldseekerContainerrelatePreloader(), @@ -154,8 +163,8 @@ func getPreloaders() preloaders { NoteImageBreadcrumb: buildNoteImageBreadcrumbPreloader(), NoteImageDatum: buildNoteImageDatumPreloader(), Notification: buildNotificationPreloader(), - OauthToken: buildOauthTokenPreloader(), Organization: buildOrganizationPreloader(), + Parcel: buildParcelPreloader(), Pool: buildPoolPreloader(), PublicreportImage: buildPublicreportImagePreloader(), PublicreportImageExif: buildPublicreportImageExifPreloader(), @@ -171,6 +180,7 @@ func getPreloaders() preloaders { PublicreportQuickImage: buildPublicreportQuickImagePreloader(), PublicreportSubscribeEmail: buildPublicreportSubscribeEmailPreloader(), PublicreportSubscribePhone: buildPublicreportSubscribePhonePreloader(), + Resident: buildResidentPreloader(), Site: buildSitePreloader(), User: buildUserPreloader(), } @@ -184,11 +194,14 @@ var ( type thenLoaders[Q orm.Loadable] struct { Address addressThenLoader[Q] + ArcgisAccount arcgisAccountThenLoader[Q] ArcgisAddressMapping arcgisAddressMappingThenLoader[Q] - ArcgisFeatureService arcgisFeatureServiceThenLoader[Q] ArcgisLayer arcgisLayerThenLoader[Q] ArcgisLayerField arcgisLayerFieldThenLoader[Q] + ArcgisOauthToken arcgisOauthTokenThenLoader[Q] ArcgisParcelMapping arcgisParcelMappingThenLoader[Q] + ArcgisServiceFeature arcgisServiceFeatureThenLoader[Q] + ArcgisServiceMap arcgisServiceMapThenLoader[Q] ArcgisUser arcgisuserThenLoader[Q] ArcgisUserPrivilege arcgisUserPrivilegeThenLoader[Q] CommsEmailContact commsEmailContactThenLoader[Q] @@ -197,6 +210,7 @@ type thenLoaders[Q orm.Loadable] struct { CommsPhone commsPhoneThenLoader[Q] CommsTextJob commsTextJobThenLoader[Q] CommsTextLog commsTextLogThenLoader[Q] + ComplianceReportRequest complianceReportRequestThenLoader[Q] DistrictSubscriptionEmail districtSubscriptionEmailThenLoader[Q] DistrictSubscriptionPhone districtSubscriptionPhoneThenLoader[Q] FieldseekerContainerrelate fieldseekerContainerrelateThenLoader[Q] @@ -240,8 +254,8 @@ type thenLoaders[Q orm.Loadable] struct { NoteImageBreadcrumb noteImageBreadcrumbThenLoader[Q] NoteImageDatum noteImageDatumThenLoader[Q] Notification notificationThenLoader[Q] - OauthToken oauthTokenThenLoader[Q] Organization organizationThenLoader[Q] + Parcel parcelThenLoader[Q] Pool poolThenLoader[Q] PublicreportImage publicreportImageThenLoader[Q] PublicreportImageExif publicreportImageExifThenLoader[Q] @@ -257,6 +271,7 @@ type thenLoaders[Q orm.Loadable] struct { PublicreportQuickImage publicreportQuickImageThenLoader[Q] PublicreportSubscribeEmail publicreportSubscribeEmailThenLoader[Q] PublicreportSubscribePhone publicreportSubscribePhoneThenLoader[Q] + Resident residentThenLoader[Q] Site siteThenLoader[Q] User userThenLoader[Q] } @@ -264,11 +279,14 @@ type thenLoaders[Q orm.Loadable] struct { func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] { return thenLoaders[Q]{ Address: buildAddressThenLoader[Q](), + ArcgisAccount: buildArcgisAccountThenLoader[Q](), ArcgisAddressMapping: buildArcgisAddressMappingThenLoader[Q](), - ArcgisFeatureService: buildArcgisFeatureServiceThenLoader[Q](), ArcgisLayer: buildArcgisLayerThenLoader[Q](), ArcgisLayerField: buildArcgisLayerFieldThenLoader[Q](), + ArcgisOauthToken: buildArcgisOauthTokenThenLoader[Q](), ArcgisParcelMapping: buildArcgisParcelMappingThenLoader[Q](), + ArcgisServiceFeature: buildArcgisServiceFeatureThenLoader[Q](), + ArcgisServiceMap: buildArcgisServiceMapThenLoader[Q](), ArcgisUser: buildArcgisUserThenLoader[Q](), ArcgisUserPrivilege: buildArcgisUserPrivilegeThenLoader[Q](), CommsEmailContact: buildCommsEmailContactThenLoader[Q](), @@ -277,6 +295,7 @@ func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] { CommsPhone: buildCommsPhoneThenLoader[Q](), CommsTextJob: buildCommsTextJobThenLoader[Q](), CommsTextLog: buildCommsTextLogThenLoader[Q](), + ComplianceReportRequest: buildComplianceReportRequestThenLoader[Q](), DistrictSubscriptionEmail: buildDistrictSubscriptionEmailThenLoader[Q](), DistrictSubscriptionPhone: buildDistrictSubscriptionPhoneThenLoader[Q](), FieldseekerContainerrelate: buildFieldseekerContainerrelateThenLoader[Q](), @@ -320,8 +339,8 @@ func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] { NoteImageBreadcrumb: buildNoteImageBreadcrumbThenLoader[Q](), NoteImageDatum: buildNoteImageDatumThenLoader[Q](), Notification: buildNotificationThenLoader[Q](), - OauthToken: buildOauthTokenThenLoader[Q](), Organization: buildOrganizationThenLoader[Q](), + Parcel: buildParcelThenLoader[Q](), Pool: buildPoolThenLoader[Q](), PublicreportImage: buildPublicreportImageThenLoader[Q](), PublicreportImageExif: buildPublicreportImageExifThenLoader[Q](), @@ -337,6 +356,7 @@ func getThenLoaders[Q orm.Loadable]() thenLoaders[Q] { PublicreportQuickImage: buildPublicreportQuickImageThenLoader[Q](), PublicreportSubscribeEmail: buildPublicreportSubscribeEmailThenLoader[Q](), PublicreportSubscribePhone: buildPublicreportSubscribePhoneThenLoader[Q](), + Resident: buildResidentThenLoader[Q](), Site: buildSiteThenLoader[Q](), User: buildUserThenLoader[Q](), } diff --git a/db/models/bob_where.bob.go b/db/models/bob_where.bob.go index 1c80ddd9..0312394e 100644 --- a/db/models/bob_where.bob.go +++ b/db/models/bob_where.bob.go @@ -18,19 +18,24 @@ var ( func Where[Q psql.Filterable]() struct { Addresses addressWhere[Q] + ArcgisAccounts arcgisAccountWhere[Q] ArcgisAddressMappings arcgisAddressMappingWhere[Q] - ArcgisFeatureServices arcgisFeatureServiceWhere[Q] ArcgisLayers arcgisLayerWhere[Q] ArcgisLayerFields arcgisLayerFieldWhere[Q] + ArcgisOauthTokens arcgisOauthTokenWhere[Q] ArcgisParcelMappings arcgisParcelMappingWhere[Q] + ArcgisServiceFeatures arcgisServiceFeatureWhere[Q] + ArcgisServiceMaps arcgisServiceMapWhere[Q] ArcgisUsers arcgisuserWhere[Q] ArcgisUserPrivileges arcgisUserPrivilegeWhere[Q] CommsEmailContacts commsEmailContactWhere[Q] CommsEmailLogs commsEmailLogWhere[Q] CommsEmailTemplates commsEmailTemplateWhere[Q] + CommsMailers commsMailerWhere[Q] CommsPhones commsPhoneWhere[Q] CommsTextJobs commsTextJobWhere[Q] CommsTextLogs commsTextLogWhere[Q] + ComplianceReportRequests complianceReportRequestWhere[Q] DistrictSubscriptionEmails districtSubscriptionEmailWhere[Q] DistrictSubscriptionPhones districtSubscriptionPhoneWhere[Q] FieldseekerContainerrelates fieldseekerContainerrelateWhere[Q] @@ -77,7 +82,6 @@ func Where[Q psql.Filterable]() struct { NoteImageBreadcrumbs noteImageBreadcrumbWhere[Q] NoteImageData noteImageDatumWhere[Q] Notifications notificationWhere[Q] - OauthTokens oauthTokenWhere[Q] Organizations organizationWhere[Q] Parcels parcelWhere[Q] Pools poolWhere[Q] @@ -98,6 +102,7 @@ func Where[Q psql.Filterable]() struct { PublicreportSubscribePhones publicreportSubscribePhoneWhere[Q] RasterColumns rasterColumnWhere[Q] RasterOverviews rasterOverviewWhere[Q] + Residents residentWhere[Q] Sessions sessionWhere[Q] Sites siteWhere[Q] SpatialRefSys spatialRefSyWhere[Q] @@ -105,19 +110,24 @@ func Where[Q psql.Filterable]() struct { } { return struct { Addresses addressWhere[Q] + ArcgisAccounts arcgisAccountWhere[Q] ArcgisAddressMappings arcgisAddressMappingWhere[Q] - ArcgisFeatureServices arcgisFeatureServiceWhere[Q] ArcgisLayers arcgisLayerWhere[Q] ArcgisLayerFields arcgisLayerFieldWhere[Q] + ArcgisOauthTokens arcgisOauthTokenWhere[Q] ArcgisParcelMappings arcgisParcelMappingWhere[Q] + ArcgisServiceFeatures arcgisServiceFeatureWhere[Q] + ArcgisServiceMaps arcgisServiceMapWhere[Q] ArcgisUsers arcgisuserWhere[Q] ArcgisUserPrivileges arcgisUserPrivilegeWhere[Q] CommsEmailContacts commsEmailContactWhere[Q] CommsEmailLogs commsEmailLogWhere[Q] CommsEmailTemplates commsEmailTemplateWhere[Q] + CommsMailers commsMailerWhere[Q] CommsPhones commsPhoneWhere[Q] CommsTextJobs commsTextJobWhere[Q] CommsTextLogs commsTextLogWhere[Q] + ComplianceReportRequests complianceReportRequestWhere[Q] DistrictSubscriptionEmails districtSubscriptionEmailWhere[Q] DistrictSubscriptionPhones districtSubscriptionPhoneWhere[Q] FieldseekerContainerrelates fieldseekerContainerrelateWhere[Q] @@ -164,7 +174,6 @@ func Where[Q psql.Filterable]() struct { NoteImageBreadcrumbs noteImageBreadcrumbWhere[Q] NoteImageData noteImageDatumWhere[Q] Notifications notificationWhere[Q] - OauthTokens oauthTokenWhere[Q] Organizations organizationWhere[Q] Parcels parcelWhere[Q] Pools poolWhere[Q] @@ -185,25 +194,31 @@ func Where[Q psql.Filterable]() struct { PublicreportSubscribePhones publicreportSubscribePhoneWhere[Q] RasterColumns rasterColumnWhere[Q] RasterOverviews rasterOverviewWhere[Q] + Residents residentWhere[Q] Sessions sessionWhere[Q] Sites siteWhere[Q] SpatialRefSys spatialRefSyWhere[Q] Users userWhere[Q] }{ Addresses: buildAddressWhere[Q](Addresses.Columns), + ArcgisAccounts: buildArcgisAccountWhere[Q](ArcgisAccounts.Columns), ArcgisAddressMappings: buildArcgisAddressMappingWhere[Q](ArcgisAddressMappings.Columns), - ArcgisFeatureServices: buildArcgisFeatureServiceWhere[Q](ArcgisFeatureServices.Columns), ArcgisLayers: buildArcgisLayerWhere[Q](ArcgisLayers.Columns), ArcgisLayerFields: buildArcgisLayerFieldWhere[Q](ArcgisLayerFields.Columns), + ArcgisOauthTokens: buildArcgisOauthTokenWhere[Q](ArcgisOauthTokens.Columns), ArcgisParcelMappings: buildArcgisParcelMappingWhere[Q](ArcgisParcelMappings.Columns), + ArcgisServiceFeatures: buildArcgisServiceFeatureWhere[Q](ArcgisServiceFeatures.Columns), + ArcgisServiceMaps: buildArcgisServiceMapWhere[Q](ArcgisServiceMaps.Columns), ArcgisUsers: buildArcgisUserWhere[Q](ArcgisUsers.Columns), ArcgisUserPrivileges: buildArcgisUserPrivilegeWhere[Q](ArcgisUserPrivileges.Columns), CommsEmailContacts: buildCommsEmailContactWhere[Q](CommsEmailContacts.Columns), CommsEmailLogs: buildCommsEmailLogWhere[Q](CommsEmailLogs.Columns), CommsEmailTemplates: buildCommsEmailTemplateWhere[Q](CommsEmailTemplates.Columns), + CommsMailers: buildCommsMailerWhere[Q](CommsMailers.Columns), CommsPhones: buildCommsPhoneWhere[Q](CommsPhones.Columns), CommsTextJobs: buildCommsTextJobWhere[Q](CommsTextJobs.Columns), CommsTextLogs: buildCommsTextLogWhere[Q](CommsTextLogs.Columns), + ComplianceReportRequests: buildComplianceReportRequestWhere[Q](ComplianceReportRequests.Columns), DistrictSubscriptionEmails: buildDistrictSubscriptionEmailWhere[Q](DistrictSubscriptionEmails.Columns), DistrictSubscriptionPhones: buildDistrictSubscriptionPhoneWhere[Q](DistrictSubscriptionPhones.Columns), FieldseekerContainerrelates: buildFieldseekerContainerrelateWhere[Q](FieldseekerContainerrelates.Columns), @@ -250,7 +265,6 @@ func Where[Q psql.Filterable]() struct { NoteImageBreadcrumbs: buildNoteImageBreadcrumbWhere[Q](NoteImageBreadcrumbs.Columns), NoteImageData: buildNoteImageDatumWhere[Q](NoteImageData.Columns), Notifications: buildNotificationWhere[Q](Notifications.Columns), - OauthTokens: buildOauthTokenWhere[Q](OauthTokens.Columns), Organizations: buildOrganizationWhere[Q](Organizations.Columns), Parcels: buildParcelWhere[Q](Parcels.Columns), Pools: buildPoolWhere[Q](Pools.Columns), @@ -271,6 +285,7 @@ func Where[Q psql.Filterable]() struct { PublicreportSubscribePhones: buildPublicreportSubscribePhoneWhere[Q](PublicreportSubscribePhones.Columns), RasterColumns: buildRasterColumnWhere[Q](RasterColumns.Columns), RasterOverviews: buildRasterOverviewWhere[Q](RasterOverviews.Columns), + Residents: buildResidentWhere[Q](Residents.Columns), Sessions: buildSessionWhere[Q](Sessions.Columns), Sites: buildSiteWhere[Q](Sites.Columns), SpatialRefSys: buildSpatialRefSyWhere[Q](SpatialRefSys.Columns), diff --git a/db/models/comms.mailer.bob.go b/db/models/comms.mailer.bob.go new file mode 100644 index 00000000..1a87ca57 --- /dev/null +++ b/db/models/comms.mailer.bob.go @@ -0,0 +1,400 @@ +// 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" + "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" + enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" + "github.com/aarondl/opt/omit" +) + +// CommsMailer is an object representing the database table. +type CommsMailer struct { + Created time.Time `db:"created" ` + ID int32 `db:"id,pk" ` + Type enums.CommsMailertype `db:"type_" ` +} + +// CommsMailerSlice is an alias for a slice of pointers to CommsMailer. +// This should almost always be used instead of []*CommsMailer. +type CommsMailerSlice []*CommsMailer + +// CommsMailers contains methods to work with the mailer table +var CommsMailers = psql.NewTablex[*CommsMailer, CommsMailerSlice, *CommsMailerSetter]("comms", "mailer", buildCommsMailerColumns("comms.mailer")) + +// CommsMailersQuery is a query on the mailer table +type CommsMailersQuery = *psql.ViewQuery[*CommsMailer, CommsMailerSlice] + +func buildCommsMailerColumns(alias string) commsMailerColumns { + return commsMailerColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "created", "id", "type_", + ).WithParent("comms.mailer"), + tableAlias: alias, + Created: psql.Quote(alias, "created"), + ID: psql.Quote(alias, "id"), + Type: psql.Quote(alias, "type_"), + } +} + +type commsMailerColumns struct { + expr.ColumnsExpr + tableAlias string + Created psql.Expression + ID psql.Expression + Type psql.Expression +} + +func (c commsMailerColumns) Alias() string { + return c.tableAlias +} + +func (commsMailerColumns) AliasedAs(alias string) commsMailerColumns { + return buildCommsMailerColumns(alias) +} + +// CommsMailerSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type CommsMailerSetter struct { + Created omit.Val[time.Time] `db:"created" ` + ID omit.Val[int32] `db:"id,pk" ` + Type omit.Val[enums.CommsMailertype] `db:"type_" ` +} + +func (s CommsMailerSetter) SetColumns() []string { + vals := make([]string, 0, 3) + if s.Created.IsValue() { + vals = append(vals, "created") + } + if s.ID.IsValue() { + vals = append(vals, "id") + } + if s.Type.IsValue() { + vals = append(vals, "type_") + } + return vals +} + +func (s CommsMailerSetter) Overwrite(t *CommsMailer) { + if s.Created.IsValue() { + t.Created = s.Created.MustGet() + } + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if s.Type.IsValue() { + t.Type = s.Type.MustGet() + } +} + +func (s *CommsMailerSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return CommsMailers.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, 3) + if s.Created.IsValue() { + vals[0] = psql.Arg(s.Created.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.ID.IsValue() { + vals[1] = psql.Arg(s.ID.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.Type.IsValue() { + vals[2] = psql.Arg(s.Type.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s CommsMailerSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s CommsMailerSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 3) + + if s.Created.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "created")...), + psql.Arg(s.Created), + }}) + } + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if s.Type.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "type_")...), + psql.Arg(s.Type), + }}) + } + + return exprs +} + +// FindCommsMailer retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindCommsMailer(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*CommsMailer, error) { + if len(cols) == 0 { + return CommsMailers.Query( + sm.Where(CommsMailers.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return CommsMailers.Query( + sm.Where(CommsMailers.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(CommsMailers.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// CommsMailerExists checks the presence of a single record by primary key +func CommsMailerExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) { + return CommsMailers.Query( + sm.Where(CommsMailers.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after CommsMailer is retrieved from the database +func (o *CommsMailer) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = CommsMailers.AfterSelectHooks.RunHooks(ctx, exec, CommsMailerSlice{o}) + case bob.QueryTypeInsert: + ctx, err = CommsMailers.AfterInsertHooks.RunHooks(ctx, exec, CommsMailerSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = CommsMailers.AfterUpdateHooks.RunHooks(ctx, exec, CommsMailerSlice{o}) + case bob.QueryTypeDelete: + ctx, err = CommsMailers.AfterDeleteHooks.RunHooks(ctx, exec, CommsMailerSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the CommsMailer +func (o *CommsMailer) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *CommsMailer) pkEQ() dialect.Expression { + return psql.Quote("comms.mailer", "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 CommsMailer +func (o *CommsMailer) Update(ctx context.Context, exec bob.Executor, s *CommsMailerSetter) error { + v, err := CommsMailers.Update(s.UpdateMod(), um.Where(o.pkEQ())).One(ctx, exec) + if err != nil { + return err + } + + *o = *v + + return nil +} + +// Delete deletes a single CommsMailer record with an executor +func (o *CommsMailer) Delete(ctx context.Context, exec bob.Executor) error { + _, err := CommsMailers.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the CommsMailer using the executor +func (o *CommsMailer) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := CommsMailers.Query( + sm.Where(CommsMailers.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + + *o = *o2 + + return nil +} + +// AfterQueryHook is called after CommsMailerSlice is retrieved from the database +func (o CommsMailerSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = CommsMailers.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = CommsMailers.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = CommsMailers.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = CommsMailers.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o CommsMailerSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("comms.mailer", "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 CommsMailerSlice) copyMatchingRows(from ...*CommsMailer) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o CommsMailerSlice) 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 CommsMailers.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 *CommsMailer: + o.copyMatchingRows(retrieved) + case []*CommsMailer: + o.copyMatchingRows(retrieved...) + case CommsMailerSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a CommsMailer or a slice of CommsMailer + // then run the AfterUpdateHooks on the slice + _, err = CommsMailers.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o CommsMailerSlice) 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 CommsMailers.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 *CommsMailer: + o.copyMatchingRows(retrieved) + case []*CommsMailer: + o.copyMatchingRows(retrieved...) + case CommsMailerSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a CommsMailer or a slice of CommsMailer + // then run the AfterDeleteHooks on the slice + _, err = CommsMailers.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o CommsMailerSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals CommsMailerSetter) error { + if len(o) == 0 { + return nil + } + + _, err := CommsMailers.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o CommsMailerSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := CommsMailers.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o CommsMailerSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := CommsMailers.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +type commsMailerWhere[Q psql.Filterable] struct { + Created psql.WhereMod[Q, time.Time] + ID psql.WhereMod[Q, int32] + Type psql.WhereMod[Q, enums.CommsMailertype] +} + +func (commsMailerWhere[Q]) AliasedAs(alias string) commsMailerWhere[Q] { + return buildCommsMailerWhere[Q](buildCommsMailerColumns(alias)) +} + +func buildCommsMailerWhere[Q psql.Filterable](cols commsMailerColumns) commsMailerWhere[Q] { + return commsMailerWhere[Q]{ + Created: psql.Where[Q, time.Time](cols.Created), + ID: psql.Where[Q, int32](cols.ID), + Type: psql.Where[Q, enums.CommsMailertype](cols.Type), + } +} diff --git a/db/models/comms.phone.bob.go b/db/models/comms.phone.bob.go index de5be9b7..97aaacdd 100644 --- a/db/models/comms.phone.bob.go +++ b/db/models/comms.phone.bob.go @@ -57,6 +57,7 @@ type commsPhoneR struct { PhoneE164NotifyPhoneNuisances PublicreportNotifyPhoneNuisanceSlice // publicreport.notify_phone_nuisance.notify_phone_nuisance_phone_e164_fkey PhoneE164NotifyPhonePools PublicreportNotifyPhonePoolSlice // publicreport.notify_phone_pool.notify_phone_pool_phone_e164_fkey PhoneE164SubscribePhones PublicreportSubscribePhoneSlice // publicreport.subscribe_phone.subscribe_phone_phone_e164_fkey + PhoneMobileResidents ResidentSlice // resident.resident_phone_mobile_fkey } func buildCommsPhoneColumns(alias string) commsPhoneColumns { @@ -626,6 +627,30 @@ func (os CommsPhoneSlice) PhoneE164SubscribePhones(mods ...bob.Mod[*dialect.Sele )...) } +// PhoneMobileResidents starts a query for related objects on resident +func (o *CommsPhone) PhoneMobileResidents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + return Residents.Query(append(mods, + sm.Where(Residents.Columns.PhoneMobile.EQ(psql.Arg(o.E164))), + )...) +} + +func (os CommsPhoneSlice) PhoneMobileResidents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + pkE164 := make(pgtypes.Array[string], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkE164 = append(pkE164, o.E164) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkE164), "text[]")), + )) + + return Residents.Query(append(mods, + sm.Where(psql.Group(Residents.Columns.PhoneMobile).OP("IN", PKArgExpr)), + )...) +} + func insertCommsPhoneDestinationTextJobs0(ctx context.Context, exec bob.Executor, commsTextJobs1 []*CommsTextJobSetter, commsPhone0 *CommsPhone) (CommsTextJobSlice, error) { for i := range commsTextJobs1 { commsTextJobs1[i].Destination = omit.From(commsPhone0.E164) @@ -1235,6 +1260,74 @@ func (commsPhone0 *CommsPhone) AttachPhoneE164SubscribePhones(ctx context.Contex return nil } +func insertCommsPhonePhoneMobileResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, commsPhone0 *CommsPhone) (ResidentSlice, error) { + for i := range residents1 { + residents1[i].PhoneMobile = omitnull.From(commsPhone0.E164) + } + + ret, err := Residents.Insert(bob.ToMods(residents1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertCommsPhonePhoneMobileResidents0: %w", err) + } + + return ret, nil +} + +func attachCommsPhonePhoneMobileResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, commsPhone0 *CommsPhone) (ResidentSlice, error) { + setter := &ResidentSetter{ + PhoneMobile: omitnull.From(commsPhone0.E164), + } + + err := residents1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachCommsPhonePhoneMobileResidents0: %w", err) + } + + return residents1, nil +} + +func (commsPhone0 *CommsPhone) InsertPhoneMobileResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + residents1, err := insertCommsPhonePhoneMobileResidents0(ctx, exec, related, commsPhone0) + if err != nil { + return err + } + + commsPhone0.R.PhoneMobileResidents = append(commsPhone0.R.PhoneMobileResidents, residents1...) + + for _, rel := range residents1 { + rel.R.PhoneMobilePhone = commsPhone0 + } + return nil +} + +func (commsPhone0 *CommsPhone) AttachPhoneMobileResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error { + if len(related) == 0 { + return nil + } + + var err error + residents1 := ResidentSlice(related) + + _, err = attachCommsPhonePhoneMobileResidents0(ctx, exec, len(related), residents1, commsPhone0) + if err != nil { + return err + } + + commsPhone0.R.PhoneMobileResidents = append(commsPhone0.R.PhoneMobileResidents, residents1...) + + for _, rel := range related { + rel.R.PhoneMobilePhone = commsPhone0 + } + + return nil +} + type commsPhoneWhere[Q psql.Filterable] struct { E164 psql.WhereMod[Q, string] IsSubscribed psql.WhereMod[Q, bool] @@ -1385,6 +1478,20 @@ func (o *CommsPhone) Preload(name string, retrieved any) error { } } return nil + case "PhoneMobileResidents": + rels, ok := retrieved.(ResidentSlice) + if !ok { + return fmt.Errorf("commsPhone cannot load %T as %q", retrieved, name) + } + + o.R.PhoneMobileResidents = rels + + for _, rel := range rels { + if rel != nil { + rel.R.PhoneMobilePhone = o + } + } + return nil default: return fmt.Errorf("commsPhone has no relationship %q", name) } @@ -1406,6 +1513,7 @@ type commsPhoneThenLoader[Q orm.Loadable] struct { PhoneE164NotifyPhoneNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] PhoneE164NotifyPhonePools 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] } func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] { @@ -1436,6 +1544,9 @@ func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] { type PhoneE164SubscribePhonesLoadInterface interface { LoadPhoneE164SubscribePhones(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type PhoneMobileResidentsLoadInterface interface { + LoadPhoneMobileResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } return commsPhoneThenLoader[Q]{ DestinationTextJobs: thenLoadBuilder[Q]( @@ -1492,6 +1603,12 @@ func buildCommsPhoneThenLoader[Q orm.Loadable]() commsPhoneThenLoader[Q] { return retrieved.LoadPhoneE164SubscribePhones(ctx, exec, mods...) }, ), + PhoneMobileResidents: thenLoadBuilder[Q]( + "PhoneMobileResidents", + func(ctx context.Context, exec bob.Executor, retrieved PhoneMobileResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadPhoneMobileResidents(ctx, exec, mods...) + }, + ), } } @@ -2070,6 +2187,70 @@ func (os CommsPhoneSlice) LoadPhoneE164SubscribePhones(ctx context.Context, exec return nil } +// LoadPhoneMobileResidents loads the commsPhone's PhoneMobileResidents into the .R struct +func (o *CommsPhone) LoadPhoneMobileResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.PhoneMobileResidents = nil + + related, err := o.PhoneMobileResidents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.PhoneMobilePhone = o + } + + o.R.PhoneMobileResidents = related + return nil +} + +// LoadPhoneMobileResidents loads the commsPhone's PhoneMobileResidents into the .R struct +func (os CommsPhoneSlice) LoadPhoneMobileResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + residents, err := os.PhoneMobileResidents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.PhoneMobileResidents = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range residents { + + if !rel.PhoneMobile.IsValue() { + continue + } + if !(rel.PhoneMobile.IsValue() && o.E164 == rel.PhoneMobile.MustGet()) { + continue + } + + rel.R.PhoneMobilePhone = o + + o.R.PhoneMobileResidents = append(o.R.PhoneMobileResidents, rel) + } + } + + return nil +} + // commsPhoneC is where relationship counts are stored. type commsPhoneC struct { DestinationTextJobs *int64 @@ -2081,6 +2262,7 @@ type commsPhoneC struct { PhoneE164NotifyPhoneNuisances *int64 PhoneE164NotifyPhonePools *int64 PhoneE164SubscribePhones *int64 + PhoneMobileResidents *int64 } // PreloadCount sets a count in the C struct by name @@ -2108,6 +2290,8 @@ func (o *CommsPhone) PreloadCount(name string, count int64) error { o.C.PhoneE164NotifyPhonePools = &count case "PhoneE164SubscribePhones": o.C.PhoneE164SubscribePhones = &count + case "PhoneMobileResidents": + o.C.PhoneMobileResidents = &count } return nil } @@ -2122,6 +2306,7 @@ type commsPhoneCountPreloader struct { PhoneE164NotifyPhoneNuisances func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader PhoneE164NotifyPhonePools func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader PhoneE164SubscribePhones func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + PhoneMobileResidents func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader } func buildCommsPhoneCountPreloader() commsPhoneCountPreloader { @@ -2282,6 +2467,23 @@ func buildCommsPhoneCountPreloader() commsPhoneCountPreloader { return psql.Group(psql.Select(subqueryMods...).Expression) }) }, + PhoneMobileResidents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*CommsPhone]("PhoneMobileResidents", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = CommsPhones.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Residents.Name()), + sm.Where(psql.Quote(Residents.Alias(), "phone_mobile").EQ(psql.Quote(parent, "e164"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, } } @@ -2295,6 +2497,7 @@ type commsPhoneCountThenLoader[Q orm.Loadable] struct { PhoneE164NotifyPhoneNuisances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] PhoneE164NotifyPhonePools 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] } func buildCommsPhoneCountThenLoader[Q orm.Loadable]() commsPhoneCountThenLoader[Q] { @@ -2325,6 +2528,9 @@ func buildCommsPhoneCountThenLoader[Q orm.Loadable]() commsPhoneCountThenLoader[ type PhoneE164SubscribePhonesCountInterface interface { LoadCountPhoneE164SubscribePhones(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type PhoneMobileResidentsCountInterface interface { + LoadCountPhoneMobileResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } return commsPhoneCountThenLoader[Q]{ DestinationTextJobs: countThenLoadBuilder[Q]( @@ -2381,6 +2587,12 @@ func buildCommsPhoneCountThenLoader[Q orm.Loadable]() commsPhoneCountThenLoader[ return retrieved.LoadCountPhoneE164SubscribePhones(ctx, exec, mods...) }, ), + PhoneMobileResidents: countThenLoadBuilder[Q]( + "PhoneMobileResidents", + func(ctx context.Context, exec bob.Executor, retrieved PhoneMobileResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountPhoneMobileResidents(ctx, exec, mods...) + }, + ), } } @@ -2654,6 +2866,36 @@ func (os CommsPhoneSlice) LoadCountPhoneE164SubscribePhones(ctx context.Context, return nil } +// LoadCountPhoneMobileResidents loads the count of PhoneMobileResidents into the C struct +func (o *CommsPhone) LoadCountPhoneMobileResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.PhoneMobileResidents(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.PhoneMobileResidents = &count + return nil +} + +// LoadCountPhoneMobileResidents loads the count of PhoneMobileResidents for a slice +func (os CommsPhoneSlice) LoadCountPhoneMobileResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountPhoneMobileResidents(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + type commsPhoneJoins[Q dialect.Joinable] struct { typ string DestinationTextJobs modAs[Q, commsTextJobColumns] @@ -2665,6 +2907,7 @@ type commsPhoneJoins[Q dialect.Joinable] struct { PhoneE164NotifyPhoneNuisances modAs[Q, publicreportNotifyPhoneNuisanceColumns] PhoneE164NotifyPhonePools modAs[Q, publicreportNotifyPhonePoolColumns] PhoneE164SubscribePhones modAs[Q, publicreportSubscribePhoneColumns] + PhoneMobileResidents modAs[Q, residentColumns] } func (j commsPhoneJoins[Q]) aliasedAs(alias string) commsPhoneJoins[Q] { @@ -2805,6 +3048,20 @@ func buildCommsPhoneJoins[Q dialect.Joinable](cols commsPhoneColumns, typ string )) } + return mods + }, + }, + PhoneMobileResidents: modAs[Q, residentColumns]{ + c: Residents.Columns, + f: func(to residentColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Residents.Name().As(to.Alias())).On( + to.PhoneMobile.EQ(cols.E164), + )) + } + return mods }, }, diff --git a/db/models/compliance_report_request.bob.go b/db/models/compliance_report_request.bob.go new file mode 100644 index 00000000..2cfbb510 --- /dev/null +++ b/db/models/compliance_report_request.bob.go @@ -0,0 +1,888 @@ +// 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/mods" + "github.com/Gleipnir-Technology/bob/orm" + "github.com/Gleipnir-Technology/bob/types/pgtypes" + "github.com/aarondl/opt/omit" +) + +// ComplianceReportRequest is an object representing the database table. +type ComplianceReportRequest struct { + Created time.Time `db:"created" ` + Creator int32 `db:"creator" ` + ID int32 `db:"id,pk" ` + PublicID string `db:"public_id" ` + SiteID int32 `db:"site_id" ` + SiteVersion int32 `db:"site_version" ` + + R complianceReportRequestR `db:"-" ` +} + +// ComplianceReportRequestSlice is an alias for a slice of pointers to ComplianceReportRequest. +// This should almost always be used instead of []*ComplianceReportRequest. +type ComplianceReportRequestSlice []*ComplianceReportRequest + +// ComplianceReportRequests contains methods to work with the compliance_report_request table +var ComplianceReportRequests = psql.NewTablex[*ComplianceReportRequest, ComplianceReportRequestSlice, *ComplianceReportRequestSetter]("", "compliance_report_request", buildComplianceReportRequestColumns("compliance_report_request")) + +// ComplianceReportRequestsQuery is a query on the compliance_report_request table +type ComplianceReportRequestsQuery = *psql.ViewQuery[*ComplianceReportRequest, ComplianceReportRequestSlice] + +// complianceReportRequestR is where relationships are stored. +type complianceReportRequestR struct { + CreatorUser *User // compliance_report_request.compliance_report_request_creator_fkey + Site *Site // compliance_report_request.compliance_report_request_site_id_site_version_fkey +} + +func buildComplianceReportRequestColumns(alias string) complianceReportRequestColumns { + return complianceReportRequestColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "created", "creator", "id", "public_id", "site_id", "site_version", + ).WithParent("compliance_report_request"), + tableAlias: alias, + Created: psql.Quote(alias, "created"), + Creator: psql.Quote(alias, "creator"), + ID: psql.Quote(alias, "id"), + PublicID: psql.Quote(alias, "public_id"), + SiteID: psql.Quote(alias, "site_id"), + SiteVersion: psql.Quote(alias, "site_version"), + } +} + +type complianceReportRequestColumns struct { + expr.ColumnsExpr + tableAlias string + Created psql.Expression + Creator psql.Expression + ID psql.Expression + PublicID psql.Expression + SiteID psql.Expression + SiteVersion psql.Expression +} + +func (c complianceReportRequestColumns) Alias() string { + return c.tableAlias +} + +func (complianceReportRequestColumns) AliasedAs(alias string) complianceReportRequestColumns { + return buildComplianceReportRequestColumns(alias) +} + +// ComplianceReportRequestSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ComplianceReportRequestSetter struct { + Created omit.Val[time.Time] `db:"created" ` + Creator omit.Val[int32] `db:"creator" ` + ID omit.Val[int32] `db:"id,pk" ` + PublicID omit.Val[string] `db:"public_id" ` + SiteID omit.Val[int32] `db:"site_id" ` + SiteVersion omit.Val[int32] `db:"site_version" ` +} + +func (s ComplianceReportRequestSetter) SetColumns() []string { + vals := make([]string, 0, 6) + if s.Created.IsValue() { + vals = append(vals, "created") + } + if s.Creator.IsValue() { + vals = append(vals, "creator") + } + if s.ID.IsValue() { + vals = append(vals, "id") + } + if s.PublicID.IsValue() { + vals = append(vals, "public_id") + } + if s.SiteID.IsValue() { + vals = append(vals, "site_id") + } + if s.SiteVersion.IsValue() { + vals = append(vals, "site_version") + } + return vals +} + +func (s ComplianceReportRequestSetter) Overwrite(t *ComplianceReportRequest) { + if s.Created.IsValue() { + t.Created = s.Created.MustGet() + } + if s.Creator.IsValue() { + t.Creator = s.Creator.MustGet() + } + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if s.PublicID.IsValue() { + t.PublicID = s.PublicID.MustGet() + } + if s.SiteID.IsValue() { + t.SiteID = s.SiteID.MustGet() + } + if s.SiteVersion.IsValue() { + t.SiteVersion = s.SiteVersion.MustGet() + } +} + +func (s *ComplianceReportRequestSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return ComplianceReportRequests.BeforeInsertHooks.RunHooks(ctx, exec, s) + }) + + q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) { + vals := make([]bob.Expression, 6) + if s.Created.IsValue() { + vals[0] = psql.Arg(s.Created.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.Creator.IsValue() { + vals[1] = psql.Arg(s.Creator.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.ID.IsValue() { + vals[2] = psql.Arg(s.ID.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if s.PublicID.IsValue() { + vals[3] = psql.Arg(s.PublicID.MustGet()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if s.SiteID.IsValue() { + vals[4] = psql.Arg(s.SiteID.MustGet()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + if s.SiteVersion.IsValue() { + vals[5] = psql.Arg(s.SiteVersion.MustGet()) + } else { + vals[5] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ComplianceReportRequestSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ComplianceReportRequestSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 6) + + if s.Created.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "created")...), + psql.Arg(s.Created), + }}) + } + + if s.Creator.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "creator")...), + psql.Arg(s.Creator), + }}) + } + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if s.PublicID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "public_id")...), + psql.Arg(s.PublicID), + }}) + } + + if s.SiteID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "site_id")...), + psql.Arg(s.SiteID), + }}) + } + + if s.SiteVersion.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "site_version")...), + psql.Arg(s.SiteVersion), + }}) + } + + return exprs +} + +// FindComplianceReportRequest retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindComplianceReportRequest(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*ComplianceReportRequest, error) { + if len(cols) == 0 { + return ComplianceReportRequests.Query( + sm.Where(ComplianceReportRequests.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return ComplianceReportRequests.Query( + sm.Where(ComplianceReportRequests.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(ComplianceReportRequests.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ComplianceReportRequestExists checks the presence of a single record by primary key +func ComplianceReportRequestExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) { + return ComplianceReportRequests.Query( + sm.Where(ComplianceReportRequests.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after ComplianceReportRequest is retrieved from the database +func (o *ComplianceReportRequest) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ComplianceReportRequests.AfterSelectHooks.RunHooks(ctx, exec, ComplianceReportRequestSlice{o}) + case bob.QueryTypeInsert: + ctx, err = ComplianceReportRequests.AfterInsertHooks.RunHooks(ctx, exec, ComplianceReportRequestSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = ComplianceReportRequests.AfterUpdateHooks.RunHooks(ctx, exec, ComplianceReportRequestSlice{o}) + case bob.QueryTypeDelete: + ctx, err = ComplianceReportRequests.AfterDeleteHooks.RunHooks(ctx, exec, ComplianceReportRequestSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the ComplianceReportRequest +func (o *ComplianceReportRequest) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *ComplianceReportRequest) pkEQ() dialect.Expression { + return psql.Quote("compliance_report_request", "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 ComplianceReportRequest +func (o *ComplianceReportRequest) Update(ctx context.Context, exec bob.Executor, s *ComplianceReportRequestSetter) error { + v, err := ComplianceReportRequests.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 ComplianceReportRequest record with an executor +func (o *ComplianceReportRequest) Delete(ctx context.Context, exec bob.Executor) error { + _, err := ComplianceReportRequests.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the ComplianceReportRequest using the executor +func (o *ComplianceReportRequest) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := ComplianceReportRequests.Query( + sm.Where(ComplianceReportRequests.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ComplianceReportRequestSlice is retrieved from the database +func (o ComplianceReportRequestSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = ComplianceReportRequests.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = ComplianceReportRequests.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = ComplianceReportRequests.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = ComplianceReportRequests.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ComplianceReportRequestSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("compliance_report_request", "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 ComplianceReportRequestSlice) copyMatchingRows(from ...*ComplianceReportRequest) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ComplianceReportRequestSlice) 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 ComplianceReportRequests.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 *ComplianceReportRequest: + o.copyMatchingRows(retrieved) + case []*ComplianceReportRequest: + o.copyMatchingRows(retrieved...) + case ComplianceReportRequestSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ComplianceReportRequest or a slice of ComplianceReportRequest + // then run the AfterUpdateHooks on the slice + _, err = ComplianceReportRequests.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ComplianceReportRequestSlice) 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 ComplianceReportRequests.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 *ComplianceReportRequest: + o.copyMatchingRows(retrieved) + case []*ComplianceReportRequest: + o.copyMatchingRows(retrieved...) + case ComplianceReportRequestSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a ComplianceReportRequest or a slice of ComplianceReportRequest + // then run the AfterDeleteHooks on the slice + _, err = ComplianceReportRequests.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ComplianceReportRequestSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ComplianceReportRequestSetter) error { + if len(o) == 0 { + return nil + } + + _, err := ComplianceReportRequests.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ComplianceReportRequestSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := ComplianceReportRequests.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ComplianceReportRequestSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := ComplianceReportRequests.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// CreatorUser starts a query for related objects on user_ +func (o *ComplianceReportRequest) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + return Users.Query(append(mods, + sm.Where(Users.Columns.ID.EQ(psql.Arg(o.Creator))), + )...) +} + +func (os ComplianceReportRequestSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + pkCreator := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkCreator = append(pkCreator, o.Creator) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkCreator), "integer[]")), + )) + + return Users.Query(append(mods, + sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// Site starts a query for related objects on site +func (o *ComplianceReportRequest) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + return Sites.Query(append(mods, + sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))), sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.SiteVersion))), + )...) +} + +func (os ComplianceReportRequestSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + pkSiteID := make(pgtypes.Array[int32], 0, len(os)) + + pkSiteVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkSiteID = append(pkSiteID, o.SiteID) + pkSiteVersion = append(pkSiteVersion, o.SiteVersion) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkSiteID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkSiteVersion), "integer[]")), + )) + + return Sites.Query(append(mods, + sm.Where(psql.Group(Sites.Columns.ID, Sites.Columns.Version).OP("IN", PKArgExpr)), + )...) +} + +func attachComplianceReportRequestCreatorUser0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, user1 *User) (*ComplianceReportRequest, error) { + setter := &ComplianceReportRequestSetter{ + Creator: omit.From(user1.ID), + } + + err := complianceReportRequest0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachComplianceReportRequestCreatorUser0: %w", err) + } + + return complianceReportRequest0, nil +} + +func (complianceReportRequest0 *ComplianceReportRequest) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error { + var err error + + user1, err := Users.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachComplianceReportRequestCreatorUser0(ctx, exec, 1, complianceReportRequest0, user1) + if err != nil { + return err + } + + complianceReportRequest0.R.CreatorUser = user1 + + user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0) + + return nil +} + +func (complianceReportRequest0 *ComplianceReportRequest) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error { + var err error + + _, err = attachComplianceReportRequestCreatorUser0(ctx, exec, 1, complianceReportRequest0, user1) + if err != nil { + return err + } + + complianceReportRequest0.R.CreatorUser = user1 + + user1.R.CreatorComplianceReportRequests = append(user1.R.CreatorComplianceReportRequests, complianceReportRequest0) + + return nil +} + +func attachComplianceReportRequestSite0(ctx context.Context, exec bob.Executor, count int, complianceReportRequest0 *ComplianceReportRequest, site1 *Site) (*ComplianceReportRequest, error) { + setter := &ComplianceReportRequestSetter{ + SiteID: omit.From(site1.ID), + SiteVersion: omit.From(site1.Version), + } + + err := complianceReportRequest0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachComplianceReportRequestSite0: %w", err) + } + + return complianceReportRequest0, nil +} + +func (complianceReportRequest0 *ComplianceReportRequest) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error { + var err error + + site1, err := Sites.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachComplianceReportRequestSite0(ctx, exec, 1, complianceReportRequest0, site1) + if err != nil { + return err + } + + complianceReportRequest0.R.Site = site1 + + site1.R.ComplianceReportRequests = append(site1.R.ComplianceReportRequests, complianceReportRequest0) + + return nil +} + +func (complianceReportRequest0 *ComplianceReportRequest) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error { + var err error + + _, err = attachComplianceReportRequestSite0(ctx, exec, 1, complianceReportRequest0, site1) + if err != nil { + return err + } + + complianceReportRequest0.R.Site = site1 + + site1.R.ComplianceReportRequests = append(site1.R.ComplianceReportRequests, complianceReportRequest0) + + return nil +} + +type complianceReportRequestWhere[Q psql.Filterable] struct { + Created psql.WhereMod[Q, time.Time] + Creator psql.WhereMod[Q, int32] + ID psql.WhereMod[Q, int32] + PublicID psql.WhereMod[Q, string] + SiteID psql.WhereMod[Q, int32] + SiteVersion psql.WhereMod[Q, int32] +} + +func (complianceReportRequestWhere[Q]) AliasedAs(alias string) complianceReportRequestWhere[Q] { + return buildComplianceReportRequestWhere[Q](buildComplianceReportRequestColumns(alias)) +} + +func buildComplianceReportRequestWhere[Q psql.Filterable](cols complianceReportRequestColumns) complianceReportRequestWhere[Q] { + return complianceReportRequestWhere[Q]{ + Created: psql.Where[Q, time.Time](cols.Created), + Creator: psql.Where[Q, int32](cols.Creator), + ID: psql.Where[Q, int32](cols.ID), + PublicID: psql.Where[Q, string](cols.PublicID), + SiteID: psql.Where[Q, int32](cols.SiteID), + SiteVersion: psql.Where[Q, int32](cols.SiteVersion), + } +} + +func (o *ComplianceReportRequest) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "CreatorUser": + rel, ok := retrieved.(*User) + if !ok { + return fmt.Errorf("complianceReportRequest cannot load %T as %q", retrieved, name) + } + + o.R.CreatorUser = rel + + if rel != nil { + rel.R.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o} + } + return nil + case "Site": + rel, ok := retrieved.(*Site) + if !ok { + return fmt.Errorf("complianceReportRequest cannot load %T as %q", retrieved, name) + } + + o.R.Site = rel + + if rel != nil { + rel.R.ComplianceReportRequests = ComplianceReportRequestSlice{o} + } + return nil + default: + return fmt.Errorf("complianceReportRequest has no relationship %q", name) + } +} + +type complianceReportRequestPreloader struct { + CreatorUser func(...psql.PreloadOption) psql.Preloader + Site func(...psql.PreloadOption) psql.Preloader +} + +func buildComplianceReportRequestPreloader() complianceReportRequestPreloader { + return complianceReportRequestPreloader{ + CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*User, UserSlice](psql.PreloadRel{ + Name: "CreatorUser", + Sides: []psql.PreloadSide{ + { + From: ComplianceReportRequests, + To: Users, + FromColumns: []string{"creator"}, + ToColumns: []string{"id"}, + }, + }, + }, Users.Columns.Names(), opts...) + }, + Site: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Site, SiteSlice](psql.PreloadRel{ + Name: "Site", + Sides: []psql.PreloadSide{ + { + From: ComplianceReportRequests, + To: Sites, + FromColumns: []string{"site_id", "site_version"}, + ToColumns: []string{"id", "version"}, + }, + }, + }, Sites.Columns.Names(), opts...) + }, + } +} + +type complianceReportRequestThenLoader[Q orm.Loadable] struct { + CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Site func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildComplianceReportRequestThenLoader[Q orm.Loadable]() complianceReportRequestThenLoader[Q] { + type CreatorUserLoadInterface interface { + LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type SiteLoadInterface interface { + LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return complianceReportRequestThenLoader[Q]{ + CreatorUser: thenLoadBuilder[Q]( + "CreatorUser", + func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCreatorUser(ctx, exec, mods...) + }, + ), + Site: thenLoadBuilder[Q]( + "Site", + func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadSite(ctx, exec, mods...) + }, + ), + } +} + +// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct +func (o *ComplianceReportRequest) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.CreatorUser = nil + + related, err := o.CreatorUser(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.CreatorComplianceReportRequests = ComplianceReportRequestSlice{o} + + o.R.CreatorUser = related + return nil +} + +// LoadCreatorUser loads the complianceReportRequest's CreatorUser into the .R struct +func (os ComplianceReportRequestSlice) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + users, err := os.CreatorUser(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range users { + + if !(o.Creator == rel.ID) { + continue + } + + rel.R.CreatorComplianceReportRequests = append(rel.R.CreatorComplianceReportRequests, o) + + o.R.CreatorUser = rel + break + } + } + + return nil +} + +// LoadSite loads the complianceReportRequest's Site into the .R struct +func (o *ComplianceReportRequest) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Site = nil + + related, err := o.Site(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.ComplianceReportRequests = ComplianceReportRequestSlice{o} + + o.R.Site = related + return nil +} + +// LoadSite loads the complianceReportRequest's Site into the .R struct +func (os ComplianceReportRequestSlice) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + sites, err := os.Site(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range sites { + + if !(o.SiteID == rel.ID) { + continue + } + + if !(o.SiteVersion == rel.Version) { + continue + } + + rel.R.ComplianceReportRequests = append(rel.R.ComplianceReportRequests, o) + + o.R.Site = rel + break + } + } + + return nil +} + +type complianceReportRequestJoins[Q dialect.Joinable] struct { + typ string + CreatorUser modAs[Q, userColumns] + Site modAs[Q, siteColumns] +} + +func (j complianceReportRequestJoins[Q]) aliasedAs(alias string) complianceReportRequestJoins[Q] { + return buildComplianceReportRequestJoins[Q](buildComplianceReportRequestColumns(alias), j.typ) +} + +func buildComplianceReportRequestJoins[Q dialect.Joinable](cols complianceReportRequestColumns, typ string) complianceReportRequestJoins[Q] { + return complianceReportRequestJoins[Q]{ + typ: typ, + CreatorUser: modAs[Q, userColumns]{ + c: Users.Columns, + f: func(to userColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Users.Name().As(to.Alias())).On( + to.ID.EQ(cols.Creator), + )) + } + + return mods + }, + }, + Site: modAs[Q, siteColumns]{ + c: Sites.Columns, + f: func(to siteColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On( + to.ID.EQ(cols.SiteID), to.Version.EQ(cols.SiteVersion), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/organization.bob.go b/db/models/organization.bob.go index 2243b8ff..2e8d436b 100644 --- a/db/models/organization.bob.go +++ b/db/models/organization.bob.go @@ -29,35 +29,38 @@ import ( // Organization is an object representing the database table. type Organization struct { - ID int32 `db:"id,pk" ` - Name string `db:"name" ` - ArcgisID null.Val[string] `db:"arcgis_id" ` - ArcgisName null.Val[string] `db:"arcgis_name" ` - FieldseekerURL null.Val[string] `db:"fieldseeker_url" ` - ImportDistrictGid null.Val[int32] `db:"import_district_gid" ` - Website null.Val[string] `db:"website" ` - LogoUUID null.Val[uuid.UUID] `db:"logo_uuid" ` - Slug null.Val[string] `db:"slug" ` - GeneralManagerName null.Val[string] `db:"general_manager_name" ` - MailingAddressCity null.Val[string] `db:"mailing_address_city" ` - MailingAddressPostalCode null.Val[string] `db:"mailing_address_postal_code" ` - MailingAddressStreet null.Val[string] `db:"mailing_address_street" ` - OfficeAddressCity null.Val[string] `db:"office_address_city" ` - OfficeAddressPostalCode null.Val[string] `db:"office_address_postal_code" ` - OfficeAddressStreet null.Val[string] `db:"office_address_street" ` - ServiceAreaGeometry null.Val[string] `db:"service_area_geometry" ` - ServiceAreaSquareMeters null.Val[decimal.Decimal] `db:"service_area_square_meters,generated" ` - ServiceAreaCentroid null.Val[string] `db:"service_area_centroid,generated" ` - ServiceAreaExtent null.Val[string] `db:"service_area_extent,generated" ` - OfficeFax null.Val[string] `db:"office_fax" ` - OfficePhone null.Val[string] `db:"office_phone" ` - ServiceAreaXmin null.Val[float64] `db:"service_area_xmin,generated" ` - ServiceAreaYmin null.Val[float64] `db:"service_area_ymin,generated" ` - ServiceAreaXmax null.Val[float64] `db:"service_area_xmax,generated" ` - ServiceAreaYmax null.Val[float64] `db:"service_area_ymax,generated" ` - ServiceAreaCentroidGeojson null.Val[string] `db:"service_area_centroid_geojson,generated" ` - ServiceAreaCentroidX null.Val[float64] `db:"service_area_centroid_x,generated" ` - ServiceAreaCentroidY null.Val[float64] `db:"service_area_centroid_y,generated" ` + ID int32 `db:"id,pk" ` + Name string `db:"name" ` + ImportDistrictGid null.Val[int32] `db:"import_district_gid" ` + Website null.Val[string] `db:"website" ` + LogoUUID null.Val[uuid.UUID] `db:"logo_uuid" ` + Slug null.Val[string] `db:"slug" ` + GeneralManagerName null.Val[string] `db:"general_manager_name" ` + MailingAddressCity null.Val[string] `db:"mailing_address_city" ` + MailingAddressPostalCode null.Val[string] `db:"mailing_address_postal_code" ` + MailingAddressStreet null.Val[string] `db:"mailing_address_street" ` + OfficeAddressCity null.Val[string] `db:"office_address_city" ` + OfficeAddressPostalCode null.Val[string] `db:"office_address_postal_code" ` + OfficeAddressStreet null.Val[string] `db:"office_address_street" ` + ServiceAreaGeometry null.Val[string] `db:"service_area_geometry" ` + ServiceAreaSquareMeters null.Val[decimal.Decimal] `db:"service_area_square_meters,generated" ` + ServiceAreaCentroid null.Val[string] `db:"service_area_centroid,generated" ` + ServiceAreaExtent null.Val[string] `db:"service_area_extent,generated" ` + OfficeFax null.Val[string] `db:"office_fax" ` + OfficePhone null.Val[string] `db:"office_phone" ` + ServiceAreaXmin null.Val[float64] `db:"service_area_xmin,generated" ` + ServiceAreaYmin null.Val[float64] `db:"service_area_ymin,generated" ` + ServiceAreaXmax null.Val[float64] `db:"service_area_xmax,generated" ` + ServiceAreaYmax null.Val[float64] `db:"service_area_ymax,generated" ` + ServiceAreaCentroidGeojson null.Val[string] `db:"service_area_centroid_geojson,generated" ` + ServiceAreaCentroidX null.Val[float64] `db:"service_area_centroid_x,generated" ` + ServiceAreaCentroidY null.Val[float64] `db:"service_area_centroid_y,generated" ` + MailingAddressCountry null.Val[string] `db:"mailing_address_country" ` + MailingAddressState null.Val[string] `db:"mailing_address_state" ` + OfficeAddressCountry null.Val[string] `db:"office_address_country" ` + OfficeAddressState null.Val[string] `db:"office_address_state" ` + ArcgisAccountID null.Val[string] `db:"arcgis_account_id" ` + FieldseekerServiceFeatureItemID null.Val[string] `db:"fieldseeker_service_feature_item_id" ` R organizationR `db:"-" ` @@ -76,119 +79,128 @@ type OrganizationsQuery = *psql.ViewQuery[*Organization, OrganizationSlice] // organizationR is where relationships are stored. type organizationR struct { - AddressMappings ArcgisAddressMappingSlice // arcgis.address_mapping.address_mapping_organization_id_fkey - ParcelMappings ArcgisParcelMappingSlice // arcgis.parcel_mapping.parcel_mapping_organization_id_fkey - EmailContacts CommsEmailContactSlice // district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey - Phones CommsPhoneSlice // district_subscription_phone.district_subscription_phone_organization_id_fkeydistrict_subscription_phone.district_subscription_phone_phone_e164_fkey - Containerrelates FieldseekerContainerrelateSlice // fieldseeker.containerrelate.containerrelate_organization_id_fkey - Fieldscoutinglogs FieldseekerFieldscoutinglogSlice // fieldseeker.fieldscoutinglog.fieldscoutinglog_organization_id_fkey - Habitatrelates FieldseekerHabitatrelateSlice // fieldseeker.habitatrelate.habitatrelate_organization_id_fkey - Inspectionsamples FieldseekerInspectionsampleSlice // fieldseeker.inspectionsample.inspectionsample_organization_id_fkey - Inspectionsampledetails FieldseekerInspectionsampledetailSlice // fieldseeker.inspectionsampledetail.inspectionsampledetail_organization_id_fkey - Linelocations FieldseekerLinelocationSlice // fieldseeker.linelocation.linelocation_organization_id_fkey - Locationtrackings FieldseekerLocationtrackingSlice // fieldseeker.locationtracking.locationtracking_organization_id_fkey - Mosquitoinspections FieldseekerMosquitoinspectionSlice // fieldseeker.mosquitoinspection.mosquitoinspection_organization_id_fkey - Pointlocations FieldseekerPointlocationSlice // fieldseeker.pointlocation.pointlocation_organization_id_fkey - Polygonlocations FieldseekerPolygonlocationSlice // fieldseeker.polygonlocation.polygonlocation_organization_id_fkey - FieldseekerPool FieldseekerPoolSlice // fieldseeker.pool.pool_organization_id_fkey - Pooldetails FieldseekerPooldetailSlice // fieldseeker.pooldetail.pooldetail_organization_id_fkey - Proposedtreatmentareas FieldseekerProposedtreatmentareaSlice // fieldseeker.proposedtreatmentarea.proposedtreatmentarea_organization_id_fkey - Qamosquitoinspections FieldseekerQamosquitoinspectionSlice // fieldseeker.qamosquitoinspection.qamosquitoinspection_organization_id_fkey - Rodentlocations FieldseekerRodentlocationSlice // fieldseeker.rodentlocation.rodentlocation_organization_id_fkey - Samplecollections FieldseekerSamplecollectionSlice // fieldseeker.samplecollection.samplecollection_organization_id_fkey - Samplelocations FieldseekerSamplelocationSlice // fieldseeker.samplelocation.samplelocation_organization_id_fkey - Servicerequests FieldseekerServicerequestSlice // fieldseeker.servicerequest.servicerequest_organization_id_fkey - Speciesabundances FieldseekerSpeciesabundanceSlice // fieldseeker.speciesabundance.speciesabundance_organization_id_fkey - Stormdrains FieldseekerStormdrainSlice // fieldseeker.stormdrain.stormdrain_organization_id_fkey - Timecards FieldseekerTimecardSlice // fieldseeker.timecard.timecard_organization_id_fkey - Trapdata FieldseekerTrapdatumSlice // fieldseeker.trapdata.trapdata_organization_id_fkey - Traplocations FieldseekerTraplocationSlice // fieldseeker.traplocation.traplocation_organization_id_fkey - Treatments FieldseekerTreatmentSlice // fieldseeker.treatment.treatment_organization_id_fkey - Treatmentareas FieldseekerTreatmentareaSlice // fieldseeker.treatmentarea.treatmentarea_organization_id_fkey - Zones FieldseekerZoneSlice // fieldseeker.zones.zones_organization_id_fkey - Zones2s FieldseekerZones2Slice // fieldseeker.zones2.zones2_organization_id_fkey - FieldseekerSyncs FieldseekerSyncSlice // fieldseeker_sync.fieldseeker_sync_organization_id_fkey - Files FileuploadFileSlice // fileupload.file.file_organization_id_fkey - Pools FileuploadPoolSlice // fileupload.pool.pool_organization_id_fkey - H3Aggregations H3AggregationSlice // h3_aggregation.h3_aggregation_organization_id_fkey - NoteAudios NoteAudioSlice // note_audio.note_audio_organization_id_fkey - NoteImages NoteImageSlice // note_image.note_image_organization_id_fkey - Nuisances PublicreportNuisanceSlice // publicreport.nuisance.nuisance_organization_id_fkey - PublicreportPool PublicreportPoolSlice // publicreport.pool.pool_organization_id_fkey - Quicks PublicreportQuickSlice // publicreport.quick.quick_organization_id_fkey - User UserSlice // user_.user__organization_id_fkey + Accounts ArcgisAccountSlice // arcgis.account.account_organization_id_fkey + AddressMappings ArcgisAddressMappingSlice // arcgis.address_mapping.address_mapping_organization_id_fkey + ParcelMappings ArcgisParcelMappingSlice // arcgis.parcel_mapping.parcel_mapping_organization_id_fkey + EmailContacts CommsEmailContactSlice // district_subscription_email.district_subscription_email_email_contact_address_fkeydistrict_subscription_email.district_subscription_email_organization_id_fkey + Phones CommsPhoneSlice // district_subscription_phone.district_subscription_phone_organization_id_fkeydistrict_subscription_phone.district_subscription_phone_phone_e164_fkey + Containerrelates FieldseekerContainerrelateSlice // fieldseeker.containerrelate.containerrelate_organization_id_fkey + Fieldscoutinglogs FieldseekerFieldscoutinglogSlice // fieldseeker.fieldscoutinglog.fieldscoutinglog_organization_id_fkey + Habitatrelates FieldseekerHabitatrelateSlice // fieldseeker.habitatrelate.habitatrelate_organization_id_fkey + Inspectionsamples FieldseekerInspectionsampleSlice // fieldseeker.inspectionsample.inspectionsample_organization_id_fkey + Inspectionsampledetails FieldseekerInspectionsampledetailSlice // fieldseeker.inspectionsampledetail.inspectionsampledetail_organization_id_fkey + Linelocations FieldseekerLinelocationSlice // fieldseeker.linelocation.linelocation_organization_id_fkey + Locationtrackings FieldseekerLocationtrackingSlice // fieldseeker.locationtracking.locationtracking_organization_id_fkey + Mosquitoinspections FieldseekerMosquitoinspectionSlice // fieldseeker.mosquitoinspection.mosquitoinspection_organization_id_fkey + Pointlocations FieldseekerPointlocationSlice // fieldseeker.pointlocation.pointlocation_organization_id_fkey + Polygonlocations FieldseekerPolygonlocationSlice // fieldseeker.polygonlocation.polygonlocation_organization_id_fkey + FieldseekerPool FieldseekerPoolSlice // fieldseeker.pool.pool_organization_id_fkey + Pooldetails FieldseekerPooldetailSlice // fieldseeker.pooldetail.pooldetail_organization_id_fkey + Proposedtreatmentareas FieldseekerProposedtreatmentareaSlice // fieldseeker.proposedtreatmentarea.proposedtreatmentarea_organization_id_fkey + Qamosquitoinspections FieldseekerQamosquitoinspectionSlice // fieldseeker.qamosquitoinspection.qamosquitoinspection_organization_id_fkey + Rodentlocations FieldseekerRodentlocationSlice // fieldseeker.rodentlocation.rodentlocation_organization_id_fkey + Samplecollections FieldseekerSamplecollectionSlice // fieldseeker.samplecollection.samplecollection_organization_id_fkey + Samplelocations FieldseekerSamplelocationSlice // fieldseeker.samplelocation.samplelocation_organization_id_fkey + Servicerequests FieldseekerServicerequestSlice // fieldseeker.servicerequest.servicerequest_organization_id_fkey + Speciesabundances FieldseekerSpeciesabundanceSlice // fieldseeker.speciesabundance.speciesabundance_organization_id_fkey + Stormdrains FieldseekerStormdrainSlice // fieldseeker.stormdrain.stormdrain_organization_id_fkey + Timecards FieldseekerTimecardSlice // fieldseeker.timecard.timecard_organization_id_fkey + Trapdata FieldseekerTrapdatumSlice // fieldseeker.trapdata.trapdata_organization_id_fkey + Traplocations FieldseekerTraplocationSlice // fieldseeker.traplocation.traplocation_organization_id_fkey + Treatments FieldseekerTreatmentSlice // fieldseeker.treatment.treatment_organization_id_fkey + Treatmentareas FieldseekerTreatmentareaSlice // fieldseeker.treatmentarea.treatmentarea_organization_id_fkey + Zones FieldseekerZoneSlice // fieldseeker.zones.zones_organization_id_fkey + Zones2s FieldseekerZones2Slice // fieldseeker.zones2.zones2_organization_id_fkey + FieldseekerSyncs FieldseekerSyncSlice // fieldseeker_sync.fieldseeker_sync_organization_id_fkey + Files FileuploadFileSlice // fileupload.file.file_organization_id_fkey + Pools FileuploadPoolSlice // fileupload.pool.pool_organization_id_fkey + H3Aggregations H3AggregationSlice // h3_aggregation.h3_aggregation_organization_id_fkey + NoteAudios NoteAudioSlice // note_audio.note_audio_organization_id_fkey + NoteImages NoteImageSlice // note_image.note_image_organization_id_fkey + ArcgisAccountAccount *ArcgisAccount // organization.organization_arcgis_account_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 + Quicks PublicreportQuickSlice // publicreport.quick.quick_organization_id_fkey + User UserSlice // user_.user__organization_id_fkey } func buildOrganizationColumns(alias string) organizationColumns { return organizationColumns{ ColumnsExpr: expr.NewColumnsExpr( - "id", "name", "arcgis_id", "arcgis_name", "fieldseeker_url", "import_district_gid", "website", "logo_uuid", "slug", "general_manager_name", "mailing_address_city", "mailing_address_postal_code", "mailing_address_street", "office_address_city", "office_address_postal_code", "office_address_street", "service_area_geometry", "service_area_square_meters", "service_area_centroid", "service_area_extent", "office_fax", "office_phone", "service_area_xmin", "service_area_ymin", "service_area_xmax", "service_area_ymax", "service_area_centroid_geojson", "service_area_centroid_x", "service_area_centroid_y", + "id", "name", "import_district_gid", "website", "logo_uuid", "slug", "general_manager_name", "mailing_address_city", "mailing_address_postal_code", "mailing_address_street", "office_address_city", "office_address_postal_code", "office_address_street", "service_area_geometry", "service_area_square_meters", "service_area_centroid", "service_area_extent", "office_fax", "office_phone", "service_area_xmin", "service_area_ymin", "service_area_xmax", "service_area_ymax", "service_area_centroid_geojson", "service_area_centroid_x", "service_area_centroid_y", "mailing_address_country", "mailing_address_state", "office_address_country", "office_address_state", "arcgis_account_id", "fieldseeker_service_feature_item_id", ).WithParent("organization"), - tableAlias: alias, - ID: psql.Quote(alias, "id"), - Name: psql.Quote(alias, "name"), - ArcgisID: psql.Quote(alias, "arcgis_id"), - ArcgisName: psql.Quote(alias, "arcgis_name"), - FieldseekerURL: psql.Quote(alias, "fieldseeker_url"), - ImportDistrictGid: psql.Quote(alias, "import_district_gid"), - Website: psql.Quote(alias, "website"), - LogoUUID: psql.Quote(alias, "logo_uuid"), - Slug: psql.Quote(alias, "slug"), - GeneralManagerName: psql.Quote(alias, "general_manager_name"), - MailingAddressCity: psql.Quote(alias, "mailing_address_city"), - MailingAddressPostalCode: psql.Quote(alias, "mailing_address_postal_code"), - MailingAddressStreet: psql.Quote(alias, "mailing_address_street"), - OfficeAddressCity: psql.Quote(alias, "office_address_city"), - OfficeAddressPostalCode: psql.Quote(alias, "office_address_postal_code"), - OfficeAddressStreet: psql.Quote(alias, "office_address_street"), - ServiceAreaGeometry: psql.Quote(alias, "service_area_geometry"), - ServiceAreaSquareMeters: psql.Quote(alias, "service_area_square_meters"), - ServiceAreaCentroid: psql.Quote(alias, "service_area_centroid"), - ServiceAreaExtent: psql.Quote(alias, "service_area_extent"), - OfficeFax: psql.Quote(alias, "office_fax"), - OfficePhone: psql.Quote(alias, "office_phone"), - ServiceAreaXmin: psql.Quote(alias, "service_area_xmin"), - ServiceAreaYmin: psql.Quote(alias, "service_area_ymin"), - ServiceAreaXmax: psql.Quote(alias, "service_area_xmax"), - ServiceAreaYmax: psql.Quote(alias, "service_area_ymax"), - ServiceAreaCentroidGeojson: psql.Quote(alias, "service_area_centroid_geojson"), - ServiceAreaCentroidX: psql.Quote(alias, "service_area_centroid_x"), - ServiceAreaCentroidY: psql.Quote(alias, "service_area_centroid_y"), + tableAlias: alias, + ID: psql.Quote(alias, "id"), + Name: psql.Quote(alias, "name"), + ImportDistrictGid: psql.Quote(alias, "import_district_gid"), + Website: psql.Quote(alias, "website"), + LogoUUID: psql.Quote(alias, "logo_uuid"), + Slug: psql.Quote(alias, "slug"), + GeneralManagerName: psql.Quote(alias, "general_manager_name"), + MailingAddressCity: psql.Quote(alias, "mailing_address_city"), + MailingAddressPostalCode: psql.Quote(alias, "mailing_address_postal_code"), + MailingAddressStreet: psql.Quote(alias, "mailing_address_street"), + OfficeAddressCity: psql.Quote(alias, "office_address_city"), + OfficeAddressPostalCode: psql.Quote(alias, "office_address_postal_code"), + OfficeAddressStreet: psql.Quote(alias, "office_address_street"), + ServiceAreaGeometry: psql.Quote(alias, "service_area_geometry"), + ServiceAreaSquareMeters: psql.Quote(alias, "service_area_square_meters"), + ServiceAreaCentroid: psql.Quote(alias, "service_area_centroid"), + ServiceAreaExtent: psql.Quote(alias, "service_area_extent"), + OfficeFax: psql.Quote(alias, "office_fax"), + OfficePhone: psql.Quote(alias, "office_phone"), + ServiceAreaXmin: psql.Quote(alias, "service_area_xmin"), + ServiceAreaYmin: psql.Quote(alias, "service_area_ymin"), + ServiceAreaXmax: psql.Quote(alias, "service_area_xmax"), + ServiceAreaYmax: psql.Quote(alias, "service_area_ymax"), + ServiceAreaCentroidGeojson: psql.Quote(alias, "service_area_centroid_geojson"), + ServiceAreaCentroidX: psql.Quote(alias, "service_area_centroid_x"), + ServiceAreaCentroidY: psql.Quote(alias, "service_area_centroid_y"), + MailingAddressCountry: psql.Quote(alias, "mailing_address_country"), + MailingAddressState: psql.Quote(alias, "mailing_address_state"), + OfficeAddressCountry: psql.Quote(alias, "office_address_country"), + OfficeAddressState: psql.Quote(alias, "office_address_state"), + ArcgisAccountID: psql.Quote(alias, "arcgis_account_id"), + FieldseekerServiceFeatureItemID: psql.Quote(alias, "fieldseeker_service_feature_item_id"), } } type organizationColumns struct { expr.ColumnsExpr - tableAlias string - ID psql.Expression - Name psql.Expression - ArcgisID psql.Expression - ArcgisName psql.Expression - FieldseekerURL psql.Expression - ImportDistrictGid psql.Expression - Website psql.Expression - LogoUUID psql.Expression - Slug psql.Expression - GeneralManagerName psql.Expression - MailingAddressCity psql.Expression - MailingAddressPostalCode psql.Expression - MailingAddressStreet psql.Expression - OfficeAddressCity psql.Expression - OfficeAddressPostalCode psql.Expression - OfficeAddressStreet psql.Expression - ServiceAreaGeometry psql.Expression - ServiceAreaSquareMeters psql.Expression - ServiceAreaCentroid psql.Expression - ServiceAreaExtent psql.Expression - OfficeFax psql.Expression - OfficePhone psql.Expression - ServiceAreaXmin psql.Expression - ServiceAreaYmin psql.Expression - ServiceAreaXmax psql.Expression - ServiceAreaYmax psql.Expression - ServiceAreaCentroidGeojson psql.Expression - ServiceAreaCentroidX psql.Expression - ServiceAreaCentroidY psql.Expression + tableAlias string + ID psql.Expression + Name psql.Expression + ImportDistrictGid psql.Expression + Website psql.Expression + LogoUUID psql.Expression + Slug psql.Expression + GeneralManagerName psql.Expression + MailingAddressCity psql.Expression + MailingAddressPostalCode psql.Expression + MailingAddressStreet psql.Expression + OfficeAddressCity psql.Expression + OfficeAddressPostalCode psql.Expression + OfficeAddressStreet psql.Expression + ServiceAreaGeometry psql.Expression + ServiceAreaSquareMeters psql.Expression + ServiceAreaCentroid psql.Expression + ServiceAreaExtent psql.Expression + OfficeFax psql.Expression + OfficePhone psql.Expression + ServiceAreaXmin psql.Expression + ServiceAreaYmin psql.Expression + ServiceAreaXmax psql.Expression + ServiceAreaYmax psql.Expression + ServiceAreaCentroidGeojson psql.Expression + ServiceAreaCentroidX psql.Expression + ServiceAreaCentroidY psql.Expression + MailingAddressCountry psql.Expression + MailingAddressState psql.Expression + OfficeAddressCountry psql.Expression + OfficeAddressState psql.Expression + ArcgisAccountID psql.Expression + FieldseekerServiceFeatureItemID psql.Expression } func (c organizationColumns) Alias() string { @@ -203,44 +215,38 @@ func (organizationColumns) AliasedAs(alias string) organizationColumns { // All values are optional, and do not have to be set // Generated columns are not included type OrganizationSetter struct { - ID omit.Val[int32] `db:"id,pk" ` - Name omit.Val[string] `db:"name" ` - ArcgisID omitnull.Val[string] `db:"arcgis_id" ` - ArcgisName omitnull.Val[string] `db:"arcgis_name" ` - FieldseekerURL omitnull.Val[string] `db:"fieldseeker_url" ` - ImportDistrictGid omitnull.Val[int32] `db:"import_district_gid" ` - Website omitnull.Val[string] `db:"website" ` - LogoUUID omitnull.Val[uuid.UUID] `db:"logo_uuid" ` - Slug omitnull.Val[string] `db:"slug" ` - GeneralManagerName omitnull.Val[string] `db:"general_manager_name" ` - MailingAddressCity omitnull.Val[string] `db:"mailing_address_city" ` - MailingAddressPostalCode omitnull.Val[string] `db:"mailing_address_postal_code" ` - MailingAddressStreet omitnull.Val[string] `db:"mailing_address_street" ` - OfficeAddressCity omitnull.Val[string] `db:"office_address_city" ` - OfficeAddressPostalCode omitnull.Val[string] `db:"office_address_postal_code" ` - OfficeAddressStreet omitnull.Val[string] `db:"office_address_street" ` - ServiceAreaGeometry omitnull.Val[string] `db:"service_area_geometry" ` - OfficeFax omitnull.Val[string] `db:"office_fax" ` - OfficePhone omitnull.Val[string] `db:"office_phone" ` + ID omit.Val[int32] `db:"id,pk" ` + Name omit.Val[string] `db:"name" ` + ImportDistrictGid omitnull.Val[int32] `db:"import_district_gid" ` + Website omitnull.Val[string] `db:"website" ` + LogoUUID omitnull.Val[uuid.UUID] `db:"logo_uuid" ` + Slug omitnull.Val[string] `db:"slug" ` + GeneralManagerName omitnull.Val[string] `db:"general_manager_name" ` + MailingAddressCity omitnull.Val[string] `db:"mailing_address_city" ` + MailingAddressPostalCode omitnull.Val[string] `db:"mailing_address_postal_code" ` + MailingAddressStreet omitnull.Val[string] `db:"mailing_address_street" ` + OfficeAddressCity omitnull.Val[string] `db:"office_address_city" ` + OfficeAddressPostalCode omitnull.Val[string] `db:"office_address_postal_code" ` + OfficeAddressStreet omitnull.Val[string] `db:"office_address_street" ` + ServiceAreaGeometry omitnull.Val[string] `db:"service_area_geometry" ` + OfficeFax omitnull.Val[string] `db:"office_fax" ` + OfficePhone omitnull.Val[string] `db:"office_phone" ` + MailingAddressCountry omitnull.Val[string] `db:"mailing_address_country" ` + MailingAddressState omitnull.Val[string] `db:"mailing_address_state" ` + OfficeAddressCountry omitnull.Val[string] `db:"office_address_country" ` + OfficeAddressState omitnull.Val[string] `db:"office_address_state" ` + ArcgisAccountID omitnull.Val[string] `db:"arcgis_account_id" ` + FieldseekerServiceFeatureItemID omitnull.Val[string] `db:"fieldseeker_service_feature_item_id" ` } func (s OrganizationSetter) SetColumns() []string { - vals := make([]string, 0, 19) + vals := make([]string, 0, 22) if s.ID.IsValue() { vals = append(vals, "id") } if s.Name.IsValue() { vals = append(vals, "name") } - if !s.ArcgisID.IsUnset() { - vals = append(vals, "arcgis_id") - } - if !s.ArcgisName.IsUnset() { - vals = append(vals, "arcgis_name") - } - if !s.FieldseekerURL.IsUnset() { - vals = append(vals, "fieldseeker_url") - } if !s.ImportDistrictGid.IsUnset() { vals = append(vals, "import_district_gid") } @@ -283,6 +289,24 @@ func (s OrganizationSetter) SetColumns() []string { if !s.OfficePhone.IsUnset() { vals = append(vals, "office_phone") } + if !s.MailingAddressCountry.IsUnset() { + vals = append(vals, "mailing_address_country") + } + if !s.MailingAddressState.IsUnset() { + vals = append(vals, "mailing_address_state") + } + if !s.OfficeAddressCountry.IsUnset() { + vals = append(vals, "office_address_country") + } + if !s.OfficeAddressState.IsUnset() { + vals = append(vals, "office_address_state") + } + if !s.ArcgisAccountID.IsUnset() { + vals = append(vals, "arcgis_account_id") + } + if !s.FieldseekerServiceFeatureItemID.IsUnset() { + vals = append(vals, "fieldseeker_service_feature_item_id") + } return vals } @@ -293,15 +317,6 @@ func (s OrganizationSetter) Overwrite(t *Organization) { if s.Name.IsValue() { t.Name = s.Name.MustGet() } - if !s.ArcgisID.IsUnset() { - t.ArcgisID = s.ArcgisID.MustGetNull() - } - if !s.ArcgisName.IsUnset() { - t.ArcgisName = s.ArcgisName.MustGetNull() - } - if !s.FieldseekerURL.IsUnset() { - t.FieldseekerURL = s.FieldseekerURL.MustGetNull() - } if !s.ImportDistrictGid.IsUnset() { t.ImportDistrictGid = s.ImportDistrictGid.MustGetNull() } @@ -344,6 +359,24 @@ func (s OrganizationSetter) Overwrite(t *Organization) { if !s.OfficePhone.IsUnset() { t.OfficePhone = s.OfficePhone.MustGetNull() } + if !s.MailingAddressCountry.IsUnset() { + t.MailingAddressCountry = s.MailingAddressCountry.MustGetNull() + } + if !s.MailingAddressState.IsUnset() { + t.MailingAddressState = s.MailingAddressState.MustGetNull() + } + if !s.OfficeAddressCountry.IsUnset() { + t.OfficeAddressCountry = s.OfficeAddressCountry.MustGetNull() + } + if !s.OfficeAddressState.IsUnset() { + t.OfficeAddressState = s.OfficeAddressState.MustGetNull() + } + if !s.ArcgisAccountID.IsUnset() { + t.ArcgisAccountID = s.ArcgisAccountID.MustGetNull() + } + if !s.FieldseekerServiceFeatureItemID.IsUnset() { + t.FieldseekerServiceFeatureItemID = s.FieldseekerServiceFeatureItemID.MustGetNull() + } } func (s *OrganizationSetter) Apply(q *dialect.InsertQuery) { @@ -352,7 +385,7 @@ func (s *OrganizationSetter) 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, 19) + vals := make([]bob.Expression, 22) if s.ID.IsValue() { vals[0] = psql.Arg(s.ID.MustGet()) } else { @@ -365,108 +398,126 @@ func (s *OrganizationSetter) Apply(q *dialect.InsertQuery) { vals[1] = psql.Raw("DEFAULT") } - if !s.ArcgisID.IsUnset() { - vals[2] = psql.Arg(s.ArcgisID.MustGetNull()) + if !s.ImportDistrictGid.IsUnset() { + vals[2] = psql.Arg(s.ImportDistrictGid.MustGetNull()) } else { vals[2] = psql.Raw("DEFAULT") } - if !s.ArcgisName.IsUnset() { - vals[3] = psql.Arg(s.ArcgisName.MustGetNull()) + if !s.Website.IsUnset() { + vals[3] = psql.Arg(s.Website.MustGetNull()) } else { vals[3] = psql.Raw("DEFAULT") } - if !s.FieldseekerURL.IsUnset() { - vals[4] = psql.Arg(s.FieldseekerURL.MustGetNull()) + if !s.LogoUUID.IsUnset() { + vals[4] = psql.Arg(s.LogoUUID.MustGetNull()) } else { vals[4] = psql.Raw("DEFAULT") } - if !s.ImportDistrictGid.IsUnset() { - vals[5] = psql.Arg(s.ImportDistrictGid.MustGetNull()) + if !s.Slug.IsUnset() { + vals[5] = psql.Arg(s.Slug.MustGetNull()) } else { vals[5] = psql.Raw("DEFAULT") } - if !s.Website.IsUnset() { - vals[6] = psql.Arg(s.Website.MustGetNull()) + if !s.GeneralManagerName.IsUnset() { + vals[6] = psql.Arg(s.GeneralManagerName.MustGetNull()) } else { vals[6] = psql.Raw("DEFAULT") } - if !s.LogoUUID.IsUnset() { - vals[7] = psql.Arg(s.LogoUUID.MustGetNull()) + if !s.MailingAddressCity.IsUnset() { + vals[7] = psql.Arg(s.MailingAddressCity.MustGetNull()) } else { vals[7] = psql.Raw("DEFAULT") } - if !s.Slug.IsUnset() { - vals[8] = psql.Arg(s.Slug.MustGetNull()) + if !s.MailingAddressPostalCode.IsUnset() { + vals[8] = psql.Arg(s.MailingAddressPostalCode.MustGetNull()) } else { vals[8] = psql.Raw("DEFAULT") } - if !s.GeneralManagerName.IsUnset() { - vals[9] = psql.Arg(s.GeneralManagerName.MustGetNull()) + if !s.MailingAddressStreet.IsUnset() { + vals[9] = psql.Arg(s.MailingAddressStreet.MustGetNull()) } else { vals[9] = psql.Raw("DEFAULT") } - if !s.MailingAddressCity.IsUnset() { - vals[10] = psql.Arg(s.MailingAddressCity.MustGetNull()) + if !s.OfficeAddressCity.IsUnset() { + vals[10] = psql.Arg(s.OfficeAddressCity.MustGetNull()) } else { vals[10] = psql.Raw("DEFAULT") } - if !s.MailingAddressPostalCode.IsUnset() { - vals[11] = psql.Arg(s.MailingAddressPostalCode.MustGetNull()) + if !s.OfficeAddressPostalCode.IsUnset() { + vals[11] = psql.Arg(s.OfficeAddressPostalCode.MustGetNull()) } else { vals[11] = psql.Raw("DEFAULT") } - if !s.MailingAddressStreet.IsUnset() { - vals[12] = psql.Arg(s.MailingAddressStreet.MustGetNull()) + if !s.OfficeAddressStreet.IsUnset() { + vals[12] = psql.Arg(s.OfficeAddressStreet.MustGetNull()) } else { vals[12] = psql.Raw("DEFAULT") } - if !s.OfficeAddressCity.IsUnset() { - vals[13] = psql.Arg(s.OfficeAddressCity.MustGetNull()) + if !s.ServiceAreaGeometry.IsUnset() { + vals[13] = psql.Arg(s.ServiceAreaGeometry.MustGetNull()) } else { vals[13] = psql.Raw("DEFAULT") } - if !s.OfficeAddressPostalCode.IsUnset() { - vals[14] = psql.Arg(s.OfficeAddressPostalCode.MustGetNull()) + if !s.OfficeFax.IsUnset() { + vals[14] = psql.Arg(s.OfficeFax.MustGetNull()) } else { vals[14] = psql.Raw("DEFAULT") } - if !s.OfficeAddressStreet.IsUnset() { - vals[15] = psql.Arg(s.OfficeAddressStreet.MustGetNull()) + if !s.OfficePhone.IsUnset() { + vals[15] = psql.Arg(s.OfficePhone.MustGetNull()) } else { vals[15] = psql.Raw("DEFAULT") } - if !s.ServiceAreaGeometry.IsUnset() { - vals[16] = psql.Arg(s.ServiceAreaGeometry.MustGetNull()) + if !s.MailingAddressCountry.IsUnset() { + vals[16] = psql.Arg(s.MailingAddressCountry.MustGetNull()) } else { vals[16] = psql.Raw("DEFAULT") } - if !s.OfficeFax.IsUnset() { - vals[17] = psql.Arg(s.OfficeFax.MustGetNull()) + if !s.MailingAddressState.IsUnset() { + vals[17] = psql.Arg(s.MailingAddressState.MustGetNull()) } else { vals[17] = psql.Raw("DEFAULT") } - if !s.OfficePhone.IsUnset() { - vals[18] = psql.Arg(s.OfficePhone.MustGetNull()) + if !s.OfficeAddressCountry.IsUnset() { + vals[18] = psql.Arg(s.OfficeAddressCountry.MustGetNull()) } else { vals[18] = psql.Raw("DEFAULT") } + if !s.OfficeAddressState.IsUnset() { + vals[19] = psql.Arg(s.OfficeAddressState.MustGetNull()) + } else { + vals[19] = psql.Raw("DEFAULT") + } + + if !s.ArcgisAccountID.IsUnset() { + vals[20] = psql.Arg(s.ArcgisAccountID.MustGetNull()) + } else { + vals[20] = psql.Raw("DEFAULT") + } + + if !s.FieldseekerServiceFeatureItemID.IsUnset() { + vals[21] = psql.Arg(s.FieldseekerServiceFeatureItemID.MustGetNull()) + } else { + vals[21] = psql.Raw("DEFAULT") + } + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") })) } @@ -476,7 +527,7 @@ func (s OrganizationSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { } func (s OrganizationSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 19) + exprs := make([]bob.Expression, 0, 22) if s.ID.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ @@ -492,27 +543,6 @@ func (s OrganizationSetter) Expressions(prefix ...string) []bob.Expression { }}) } - if !s.ArcgisID.IsUnset() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "arcgis_id")...), - psql.Arg(s.ArcgisID), - }}) - } - - if !s.ArcgisName.IsUnset() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "arcgis_name")...), - psql.Arg(s.ArcgisName), - }}) - } - - if !s.FieldseekerURL.IsUnset() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "fieldseeker_url")...), - psql.Arg(s.FieldseekerURL), - }}) - } - if !s.ImportDistrictGid.IsUnset() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "import_district_gid")...), @@ -611,6 +641,48 @@ func (s OrganizationSetter) Expressions(prefix ...string) []bob.Expression { }}) } + if !s.MailingAddressCountry.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "mailing_address_country")...), + psql.Arg(s.MailingAddressCountry), + }}) + } + + if !s.MailingAddressState.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "mailing_address_state")...), + psql.Arg(s.MailingAddressState), + }}) + } + + if !s.OfficeAddressCountry.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "office_address_country")...), + psql.Arg(s.OfficeAddressCountry), + }}) + } + + if !s.OfficeAddressState.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "office_address_state")...), + psql.Arg(s.OfficeAddressState), + }}) + } + + if !s.ArcgisAccountID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "arcgis_account_id")...), + psql.Arg(s.ArcgisAccountID), + }}) + } + + if !s.FieldseekerServiceFeatureItemID.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "fieldseeker_service_feature_item_id")...), + psql.Arg(s.FieldseekerServiceFeatureItemID), + }}) + } + return exprs } @@ -837,6 +909,30 @@ func (o OrganizationSlice) ReloadAll(ctx context.Context, exec bob.Executor) err return nil } +// Accounts starts a query for related objects on arcgis.account +func (o *Organization) Accounts(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + return ArcgisAccounts.Query(append(mods, + sm.Where(ArcgisAccounts.Columns.OrganizationID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os OrganizationSlice) Accounts(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + 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 ArcgisAccounts.Query(append(mods, + sm.Where(psql.Group(ArcgisAccounts.Columns.OrganizationID).OP("IN", PKArgExpr)), + )...) +} + // AddressMappings starts a query for related objects on arcgis.address_mapping func (o *Organization) AddressMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAddressMappingsQuery { return ArcgisAddressMappings.Query(append(mods, @@ -1735,6 +1831,54 @@ func (os OrganizationSlice) NoteImages(mods ...bob.Mod[*dialect.SelectQuery]) No )...) } +// ArcgisAccountAccount starts a query for related objects on arcgis.account +func (o *Organization) ArcgisAccountAccount(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + return ArcgisAccounts.Query(append(mods, + sm.Where(ArcgisAccounts.Columns.ID.EQ(psql.Arg(o.ArcgisAccountID))), + )...) +} + +func (os OrganizationSlice) ArcgisAccountAccount(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAccountsQuery { + pkArcgisAccountID := make(pgtypes.Array[null.Val[string]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkArcgisAccountID = append(pkArcgisAccountID, o.ArcgisAccountID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkArcgisAccountID), "text[]")), + )) + + return ArcgisAccounts.Query(append(mods, + sm.Where(psql.Group(ArcgisAccounts.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// FieldseekerServiceFeatureItemServiceFeature starts a query for related objects on arcgis.service_feature +func (o *Organization) FieldseekerServiceFeatureItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(ArcgisServiceFeatures.Columns.ItemID.EQ(psql.Arg(o.FieldseekerServiceFeatureItemID))), + )...) +} + +func (os OrganizationSlice) FieldseekerServiceFeatureItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { + pkFieldseekerServiceFeatureItemID := make(pgtypes.Array[null.Val[string]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkFieldseekerServiceFeatureItemID = append(pkFieldseekerServiceFeatureItemID, o.FieldseekerServiceFeatureItemID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkFieldseekerServiceFeatureItemID), "text[]")), + )) + + return ArcgisServiceFeatures.Query(append(mods, + sm.Where(psql.Group(ArcgisServiceFeatures.Columns.ItemID).OP("IN", PKArgExpr)), + )...) +} + // Nuisances starts a query for related objects on publicreport.nuisance func (o *Organization) Nuisances(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisancesQuery { return PublicreportNuisances.Query(append(mods, @@ -1831,6 +1975,74 @@ func (os OrganizationSlice) User(mods ...bob.Mod[*dialect.SelectQuery]) UsersQue )...) } +func insertOrganizationAccounts0(ctx context.Context, exec bob.Executor, arcgisAccounts1 []*ArcgisAccountSetter, organization0 *Organization) (ArcgisAccountSlice, error) { + for i := range arcgisAccounts1 { + arcgisAccounts1[i].OrganizationID = omit.From(organization0.ID) + } + + ret, err := ArcgisAccounts.Insert(bob.ToMods(arcgisAccounts1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertOrganizationAccounts0: %w", err) + } + + return ret, nil +} + +func attachOrganizationAccounts0(ctx context.Context, exec bob.Executor, count int, arcgisAccounts1 ArcgisAccountSlice, organization0 *Organization) (ArcgisAccountSlice, error) { + setter := &ArcgisAccountSetter{ + OrganizationID: omit.From(organization0.ID), + } + + err := arcgisAccounts1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachOrganizationAccounts0: %w", err) + } + + return arcgisAccounts1, nil +} + +func (organization0 *Organization) InsertAccounts(ctx context.Context, exec bob.Executor, related ...*ArcgisAccountSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisAccounts1, err := insertOrganizationAccounts0(ctx, exec, related, organization0) + if err != nil { + return err + } + + organization0.R.Accounts = append(organization0.R.Accounts, arcgisAccounts1...) + + for _, rel := range arcgisAccounts1 { + rel.R.Organization = organization0 + } + return nil +} + +func (organization0 *Organization) AttachAccounts(ctx context.Context, exec bob.Executor, related ...*ArcgisAccount) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisAccounts1 := ArcgisAccountSlice(related) + + _, err = attachOrganizationAccounts0(ctx, exec, len(related), arcgisAccounts1, organization0) + if err != nil { + return err + } + + organization0.R.Accounts = append(organization0.R.Accounts, arcgisAccounts1...) + + for _, rel := range related { + rel.R.Organization = organization0 + } + + return nil +} + func insertOrganizationAddressMappings0(ctx context.Context, exec bob.Executor, arcgisAddressMappings1 []*ArcgisAddressMappingSetter, organization0 *Organization) (ArcgisAddressMappingSlice, error) { for i := range arcgisAddressMappings1 { arcgisAddressMappings1[i].OrganizationID = omit.From(organization0.ID) @@ -4341,6 +4553,102 @@ func (organization0 *Organization) AttachNoteImages(ctx context.Context, exec bo return nil } +func attachOrganizationArcgisAccountAccount0(ctx context.Context, exec bob.Executor, count int, organization0 *Organization, arcgisAccount1 *ArcgisAccount) (*Organization, error) { + setter := &OrganizationSetter{ + ArcgisAccountID: omitnull.From(arcgisAccount1.ID), + } + + err := organization0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachOrganizationArcgisAccountAccount0: %w", err) + } + + return organization0, nil +} + +func (organization0 *Organization) InsertArcgisAccountAccount(ctx context.Context, exec bob.Executor, related *ArcgisAccountSetter) error { + var err error + + arcgisAccount1, err := ArcgisAccounts.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachOrganizationArcgisAccountAccount0(ctx, exec, 1, organization0, arcgisAccount1) + if err != nil { + return err + } + + organization0.R.ArcgisAccountAccount = arcgisAccount1 + + arcgisAccount1.R.ArcgisAccountOrganizations = append(arcgisAccount1.R.ArcgisAccountOrganizations, organization0) + + return nil +} + +func (organization0 *Organization) AttachArcgisAccountAccount(ctx context.Context, exec bob.Executor, arcgisAccount1 *ArcgisAccount) error { + var err error + + _, err = attachOrganizationArcgisAccountAccount0(ctx, exec, 1, organization0, arcgisAccount1) + if err != nil { + return err + } + + organization0.R.ArcgisAccountAccount = arcgisAccount1 + + arcgisAccount1.R.ArcgisAccountOrganizations = append(arcgisAccount1.R.ArcgisAccountOrganizations, organization0) + + return nil +} + +func attachOrganizationFieldseekerServiceFeatureItemServiceFeature0(ctx context.Context, exec bob.Executor, count int, organization0 *Organization, arcgisServiceFeature1 *ArcgisServiceFeature) (*Organization, error) { + setter := &OrganizationSetter{ + FieldseekerServiceFeatureItemID: omitnull.From(arcgisServiceFeature1.ItemID), + } + + err := organization0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachOrganizationFieldseekerServiceFeatureItemServiceFeature0: %w", err) + } + + return organization0, nil +} + +func (organization0 *Organization) InsertFieldseekerServiceFeatureItemServiceFeature(ctx context.Context, exec bob.Executor, related *ArcgisServiceFeatureSetter) error { + var err error + + arcgisServiceFeature1, err := ArcgisServiceFeatures.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachOrganizationFieldseekerServiceFeatureItemServiceFeature0(ctx, exec, 1, organization0, arcgisServiceFeature1) + if err != nil { + return err + } + + organization0.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature1 + + arcgisServiceFeature1.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature1.R.FieldseekerServiceFeatureItemOrganizations, organization0) + + return nil +} + +func (organization0 *Organization) AttachFieldseekerServiceFeatureItemServiceFeature(ctx context.Context, exec bob.Executor, arcgisServiceFeature1 *ArcgisServiceFeature) error { + var err error + + _, err = attachOrganizationFieldseekerServiceFeatureItemServiceFeature0(ctx, exec, 1, organization0, arcgisServiceFeature1) + if err != nil { + return err + } + + organization0.R.FieldseekerServiceFeatureItemServiceFeature = arcgisServiceFeature1 + + arcgisServiceFeature1.R.FieldseekerServiceFeatureItemOrganizations = append(arcgisServiceFeature1.R.FieldseekerServiceFeatureItemOrganizations, organization0) + + return nil +} + func insertOrganizationNuisances0(ctx context.Context, exec bob.Executor, publicreportNuisances1 []*PublicreportNuisanceSetter, organization0 *Organization) (PublicreportNuisanceSlice, error) { for i := range publicreportNuisances1 { publicreportNuisances1[i].OrganizationID = omitnull.From(organization0.ID) @@ -4614,35 +4922,38 @@ func (organization0 *Organization) AttachUser(ctx context.Context, exec bob.Exec } type organizationWhere[Q psql.Filterable] struct { - ID psql.WhereMod[Q, int32] - Name psql.WhereMod[Q, string] - ArcgisID psql.WhereNullMod[Q, string] - ArcgisName psql.WhereNullMod[Q, string] - FieldseekerURL psql.WhereNullMod[Q, string] - ImportDistrictGid psql.WhereNullMod[Q, int32] - Website psql.WhereNullMod[Q, string] - LogoUUID psql.WhereNullMod[Q, uuid.UUID] - Slug psql.WhereNullMod[Q, string] - GeneralManagerName psql.WhereNullMod[Q, string] - MailingAddressCity psql.WhereNullMod[Q, string] - MailingAddressPostalCode psql.WhereNullMod[Q, string] - MailingAddressStreet psql.WhereNullMod[Q, string] - OfficeAddressCity psql.WhereNullMod[Q, string] - OfficeAddressPostalCode psql.WhereNullMod[Q, string] - OfficeAddressStreet psql.WhereNullMod[Q, string] - ServiceAreaGeometry psql.WhereNullMod[Q, string] - ServiceAreaSquareMeters psql.WhereNullMod[Q, decimal.Decimal] - ServiceAreaCentroid psql.WhereNullMod[Q, string] - ServiceAreaExtent psql.WhereNullMod[Q, string] - OfficeFax psql.WhereNullMod[Q, string] - OfficePhone psql.WhereNullMod[Q, string] - ServiceAreaXmin psql.WhereNullMod[Q, float64] - ServiceAreaYmin psql.WhereNullMod[Q, float64] - ServiceAreaXmax psql.WhereNullMod[Q, float64] - ServiceAreaYmax psql.WhereNullMod[Q, float64] - ServiceAreaCentroidGeojson psql.WhereNullMod[Q, string] - ServiceAreaCentroidX psql.WhereNullMod[Q, float64] - ServiceAreaCentroidY psql.WhereNullMod[Q, float64] + ID psql.WhereMod[Q, int32] + Name psql.WhereMod[Q, string] + ImportDistrictGid psql.WhereNullMod[Q, int32] + Website psql.WhereNullMod[Q, string] + LogoUUID psql.WhereNullMod[Q, uuid.UUID] + Slug psql.WhereNullMod[Q, string] + GeneralManagerName psql.WhereNullMod[Q, string] + MailingAddressCity psql.WhereNullMod[Q, string] + MailingAddressPostalCode psql.WhereNullMod[Q, string] + MailingAddressStreet psql.WhereNullMod[Q, string] + OfficeAddressCity psql.WhereNullMod[Q, string] + OfficeAddressPostalCode psql.WhereNullMod[Q, string] + OfficeAddressStreet psql.WhereNullMod[Q, string] + ServiceAreaGeometry psql.WhereNullMod[Q, string] + ServiceAreaSquareMeters psql.WhereNullMod[Q, decimal.Decimal] + ServiceAreaCentroid psql.WhereNullMod[Q, string] + ServiceAreaExtent psql.WhereNullMod[Q, string] + OfficeFax psql.WhereNullMod[Q, string] + OfficePhone psql.WhereNullMod[Q, string] + ServiceAreaXmin psql.WhereNullMod[Q, float64] + ServiceAreaYmin psql.WhereNullMod[Q, float64] + ServiceAreaXmax psql.WhereNullMod[Q, float64] + ServiceAreaYmax psql.WhereNullMod[Q, float64] + ServiceAreaCentroidGeojson psql.WhereNullMod[Q, string] + ServiceAreaCentroidX psql.WhereNullMod[Q, float64] + ServiceAreaCentroidY psql.WhereNullMod[Q, float64] + MailingAddressCountry psql.WhereNullMod[Q, string] + MailingAddressState psql.WhereNullMod[Q, string] + OfficeAddressCountry psql.WhereNullMod[Q, string] + OfficeAddressState psql.WhereNullMod[Q, string] + ArcgisAccountID psql.WhereNullMod[Q, string] + FieldseekerServiceFeatureItemID psql.WhereNullMod[Q, string] } func (organizationWhere[Q]) AliasedAs(alias string) organizationWhere[Q] { @@ -4651,35 +4962,38 @@ func (organizationWhere[Q]) AliasedAs(alias string) organizationWhere[Q] { func buildOrganizationWhere[Q psql.Filterable](cols organizationColumns) organizationWhere[Q] { return organizationWhere[Q]{ - ID: psql.Where[Q, int32](cols.ID), - Name: psql.Where[Q, string](cols.Name), - ArcgisID: psql.WhereNull[Q, string](cols.ArcgisID), - ArcgisName: psql.WhereNull[Q, string](cols.ArcgisName), - FieldseekerURL: psql.WhereNull[Q, string](cols.FieldseekerURL), - ImportDistrictGid: psql.WhereNull[Q, int32](cols.ImportDistrictGid), - Website: psql.WhereNull[Q, string](cols.Website), - LogoUUID: psql.WhereNull[Q, uuid.UUID](cols.LogoUUID), - Slug: psql.WhereNull[Q, string](cols.Slug), - GeneralManagerName: psql.WhereNull[Q, string](cols.GeneralManagerName), - MailingAddressCity: psql.WhereNull[Q, string](cols.MailingAddressCity), - MailingAddressPostalCode: psql.WhereNull[Q, string](cols.MailingAddressPostalCode), - MailingAddressStreet: psql.WhereNull[Q, string](cols.MailingAddressStreet), - OfficeAddressCity: psql.WhereNull[Q, string](cols.OfficeAddressCity), - OfficeAddressPostalCode: psql.WhereNull[Q, string](cols.OfficeAddressPostalCode), - OfficeAddressStreet: psql.WhereNull[Q, string](cols.OfficeAddressStreet), - ServiceAreaGeometry: psql.WhereNull[Q, string](cols.ServiceAreaGeometry), - ServiceAreaSquareMeters: psql.WhereNull[Q, decimal.Decimal](cols.ServiceAreaSquareMeters), - ServiceAreaCentroid: psql.WhereNull[Q, string](cols.ServiceAreaCentroid), - ServiceAreaExtent: psql.WhereNull[Q, string](cols.ServiceAreaExtent), - OfficeFax: psql.WhereNull[Q, string](cols.OfficeFax), - OfficePhone: psql.WhereNull[Q, string](cols.OfficePhone), - ServiceAreaXmin: psql.WhereNull[Q, float64](cols.ServiceAreaXmin), - ServiceAreaYmin: psql.WhereNull[Q, float64](cols.ServiceAreaYmin), - ServiceAreaXmax: psql.WhereNull[Q, float64](cols.ServiceAreaXmax), - ServiceAreaYmax: psql.WhereNull[Q, float64](cols.ServiceAreaYmax), - ServiceAreaCentroidGeojson: psql.WhereNull[Q, string](cols.ServiceAreaCentroidGeojson), - ServiceAreaCentroidX: psql.WhereNull[Q, float64](cols.ServiceAreaCentroidX), - ServiceAreaCentroidY: psql.WhereNull[Q, float64](cols.ServiceAreaCentroidY), + ID: psql.Where[Q, int32](cols.ID), + Name: psql.Where[Q, string](cols.Name), + ImportDistrictGid: psql.WhereNull[Q, int32](cols.ImportDistrictGid), + Website: psql.WhereNull[Q, string](cols.Website), + LogoUUID: psql.WhereNull[Q, uuid.UUID](cols.LogoUUID), + Slug: psql.WhereNull[Q, string](cols.Slug), + GeneralManagerName: psql.WhereNull[Q, string](cols.GeneralManagerName), + MailingAddressCity: psql.WhereNull[Q, string](cols.MailingAddressCity), + MailingAddressPostalCode: psql.WhereNull[Q, string](cols.MailingAddressPostalCode), + MailingAddressStreet: psql.WhereNull[Q, string](cols.MailingAddressStreet), + OfficeAddressCity: psql.WhereNull[Q, string](cols.OfficeAddressCity), + OfficeAddressPostalCode: psql.WhereNull[Q, string](cols.OfficeAddressPostalCode), + OfficeAddressStreet: psql.WhereNull[Q, string](cols.OfficeAddressStreet), + ServiceAreaGeometry: psql.WhereNull[Q, string](cols.ServiceAreaGeometry), + ServiceAreaSquareMeters: psql.WhereNull[Q, decimal.Decimal](cols.ServiceAreaSquareMeters), + ServiceAreaCentroid: psql.WhereNull[Q, string](cols.ServiceAreaCentroid), + ServiceAreaExtent: psql.WhereNull[Q, string](cols.ServiceAreaExtent), + OfficeFax: psql.WhereNull[Q, string](cols.OfficeFax), + OfficePhone: psql.WhereNull[Q, string](cols.OfficePhone), + ServiceAreaXmin: psql.WhereNull[Q, float64](cols.ServiceAreaXmin), + ServiceAreaYmin: psql.WhereNull[Q, float64](cols.ServiceAreaYmin), + ServiceAreaXmax: psql.WhereNull[Q, float64](cols.ServiceAreaXmax), + ServiceAreaYmax: psql.WhereNull[Q, float64](cols.ServiceAreaYmax), + ServiceAreaCentroidGeojson: psql.WhereNull[Q, string](cols.ServiceAreaCentroidGeojson), + ServiceAreaCentroidX: psql.WhereNull[Q, float64](cols.ServiceAreaCentroidX), + ServiceAreaCentroidY: psql.WhereNull[Q, float64](cols.ServiceAreaCentroidY), + MailingAddressCountry: psql.WhereNull[Q, string](cols.MailingAddressCountry), + MailingAddressState: psql.WhereNull[Q, string](cols.MailingAddressState), + OfficeAddressCountry: psql.WhereNull[Q, string](cols.OfficeAddressCountry), + OfficeAddressState: psql.WhereNull[Q, string](cols.OfficeAddressState), + ArcgisAccountID: psql.WhereNull[Q, string](cols.ArcgisAccountID), + FieldseekerServiceFeatureItemID: psql.WhereNull[Q, string](cols.FieldseekerServiceFeatureItemID), } } @@ -4689,6 +5003,20 @@ func (o *Organization) Preload(name string, retrieved any) error { } switch name { + case "Accounts": + rels, ok := retrieved.(ArcgisAccountSlice) + if !ok { + return fmt.Errorf("organization cannot load %T as %q", retrieved, name) + } + + o.R.Accounts = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Organization = o + } + } + return nil case "AddressMappings": rels, ok := retrieved.(ArcgisAddressMappingSlice) if !ok { @@ -5207,6 +5535,30 @@ func (o *Organization) Preload(name string, retrieved any) error { } } return nil + case "ArcgisAccountAccount": + rel, ok := retrieved.(*ArcgisAccount) + if !ok { + return fmt.Errorf("organization cannot load %T as %q", retrieved, name) + } + + o.R.ArcgisAccountAccount = rel + + if rel != nil { + rel.R.ArcgisAccountOrganizations = OrganizationSlice{o} + } + return nil + case "FieldseekerServiceFeatureItemServiceFeature": + rel, ok := retrieved.(*ArcgisServiceFeature) + if !ok { + return fmt.Errorf("organization cannot load %T as %q", retrieved, name) + } + + o.R.FieldseekerServiceFeatureItemServiceFeature = rel + + if rel != nil { + rel.R.FieldseekerServiceFeatureItemOrganizations = OrganizationSlice{o} + } + return nil case "Nuisances": rels, ok := retrieved.(PublicreportNuisanceSlice) if !ok { @@ -5268,57 +5620,93 @@ func (o *Organization) Preload(name string, retrieved any) error { } } -type organizationPreloader struct{} +type organizationPreloader struct { + ArcgisAccountAccount func(...psql.PreloadOption) psql.Preloader + FieldseekerServiceFeatureItemServiceFeature func(...psql.PreloadOption) psql.Preloader +} func buildOrganizationPreloader() organizationPreloader { - return organizationPreloader{} + return organizationPreloader{ + ArcgisAccountAccount: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisAccount, ArcgisAccountSlice](psql.PreloadRel{ + Name: "ArcgisAccountAccount", + Sides: []psql.PreloadSide{ + { + From: Organizations, + To: ArcgisAccounts, + FromColumns: []string{"arcgis_account_id"}, + ToColumns: []string{"id"}, + }, + }, + }, ArcgisAccounts.Columns.Names(), opts...) + }, + FieldseekerServiceFeatureItemServiceFeature: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*ArcgisServiceFeature, ArcgisServiceFeatureSlice](psql.PreloadRel{ + Name: "FieldseekerServiceFeatureItemServiceFeature", + Sides: []psql.PreloadSide{ + { + From: Organizations, + To: ArcgisServiceFeatures, + FromColumns: []string{"fieldseeker_service_feature_item_id"}, + ToColumns: []string{"item_id"}, + }, + }, + }, ArcgisServiceFeatures.Columns.Names(), opts...) + }, + } } type organizationThenLoader[Q orm.Loadable] struct { - AddressMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - ParcelMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - EmailContacts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Phones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Containerrelates func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Fieldscoutinglogs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Habitatrelates func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Inspectionsamples func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Inspectionsampledetails func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Linelocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Locationtrackings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Mosquitoinspections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Pointlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Polygonlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - FieldseekerPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Pooldetails func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Proposedtreatmentareas func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Qamosquitoinspections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Rodentlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Samplecollections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Samplelocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Servicerequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Speciesabundances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Stormdrains func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Timecards func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Trapdata func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Traplocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Treatments func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Treatmentareas func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Zones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Zones2s func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - FieldseekerSyncs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Files func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - H3Aggregations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - NoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - NoteImages 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] - Quicks func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - User func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Accounts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + AddressMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ParcelMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + EmailContacts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Phones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Containerrelates func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Fieldscoutinglogs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Habitatrelates func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Inspectionsamples func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Inspectionsampledetails func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Linelocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Locationtrackings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Mosquitoinspections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Pointlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Polygonlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FieldseekerPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Pooldetails func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Proposedtreatmentareas func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Qamosquitoinspections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Rodentlocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Samplecollections func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Samplelocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Servicerequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Speciesabundances func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Stormdrains func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Timecards func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Trapdata func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Traplocations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Treatments func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Treatmentareas func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Zones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Zones2s func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FieldseekerSyncs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Files func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + H3Aggregations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + NoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + NoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ArcgisAccountAccount 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] + Quicks func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + User func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] { + type AccountsLoadInterface interface { + LoadAccounts(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type AddressMappingsLoadInterface interface { LoadAddressMappings(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -5430,6 +5818,12 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] { type NoteImagesLoadInterface interface { LoadNoteImages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type ArcgisAccountAccountLoadInterface interface { + LoadArcgisAccountAccount(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type FieldseekerServiceFeatureItemServiceFeatureLoadInterface interface { + LoadFieldseekerServiceFeatureItemServiceFeature(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type NuisancesLoadInterface interface { LoadNuisances(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -5444,6 +5838,12 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] { } return organizationThenLoader[Q]{ + Accounts: thenLoadBuilder[Q]( + "Accounts", + func(ctx context.Context, exec bob.Executor, retrieved AccountsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadAccounts(ctx, exec, mods...) + }, + ), AddressMappings: thenLoadBuilder[Q]( "AddressMappings", func(ctx context.Context, exec bob.Executor, retrieved AddressMappingsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -5666,6 +6066,18 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] { return retrieved.LoadNoteImages(ctx, exec, mods...) }, ), + ArcgisAccountAccount: thenLoadBuilder[Q]( + "ArcgisAccountAccount", + func(ctx context.Context, exec bob.Executor, retrieved ArcgisAccountAccountLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadArcgisAccountAccount(ctx, exec, mods...) + }, + ), + FieldseekerServiceFeatureItemServiceFeature: thenLoadBuilder[Q]( + "FieldseekerServiceFeatureItemServiceFeature", + func(ctx context.Context, exec bob.Executor, retrieved FieldseekerServiceFeatureItemServiceFeatureLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadFieldseekerServiceFeatureItemServiceFeature(ctx, exec, mods...) + }, + ), Nuisances: thenLoadBuilder[Q]( "Nuisances", func(ctx context.Context, exec bob.Executor, retrieved NuisancesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -5693,6 +6105,67 @@ func buildOrganizationThenLoader[Q orm.Loadable]() organizationThenLoader[Q] { } } +// LoadAccounts loads the organization's Accounts into the .R struct +func (o *Organization) LoadAccounts(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Accounts = nil + + related, err := o.Accounts(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Organization = o + } + + o.R.Accounts = related + return nil +} + +// LoadAccounts loads the organization's Accounts into the .R struct +func (os OrganizationSlice) LoadAccounts(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisAccounts, err := os.Accounts(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.Accounts = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisAccounts { + + if !(o.ID == rel.OrganizationID) { + continue + } + + rel.R.Organization = o + + o.R.Accounts = append(o.R.Accounts, rel) + } + } + + return nil +} + // LoadAddressMappings loads the organization's AddressMappings into the .R struct func (o *Organization) LoadAddressMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -7990,6 +8463,116 @@ func (os OrganizationSlice) LoadNoteImages(ctx context.Context, exec bob.Executo return nil } +// LoadArcgisAccountAccount loads the organization's ArcgisAccountAccount into the .R struct +func (o *Organization) LoadArcgisAccountAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ArcgisAccountAccount = nil + + related, err := o.ArcgisAccountAccount(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.ArcgisAccountOrganizations = OrganizationSlice{o} + + o.R.ArcgisAccountAccount = related + return nil +} + +// LoadArcgisAccountAccount loads the organization's ArcgisAccountAccount into the .R struct +func (os OrganizationSlice) LoadArcgisAccountAccount(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisAccounts, err := os.ArcgisAccountAccount(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisAccounts { + if !o.ArcgisAccountID.IsValue() { + continue + } + + if !(o.ArcgisAccountID.IsValue() && o.ArcgisAccountID.MustGet() == rel.ID) { + continue + } + + rel.R.ArcgisAccountOrganizations = append(rel.R.ArcgisAccountOrganizations, o) + + o.R.ArcgisAccountAccount = rel + break + } + } + + return nil +} + +// LoadFieldseekerServiceFeatureItemServiceFeature loads the organization's FieldseekerServiceFeatureItemServiceFeature into the .R struct +func (o *Organization) LoadFieldseekerServiceFeatureItemServiceFeature(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.FieldseekerServiceFeatureItemServiceFeature = nil + + related, err := o.FieldseekerServiceFeatureItemServiceFeature(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.FieldseekerServiceFeatureItemOrganizations = OrganizationSlice{o} + + o.R.FieldseekerServiceFeatureItemServiceFeature = related + return nil +} + +// LoadFieldseekerServiceFeatureItemServiceFeature loads the organization's FieldseekerServiceFeatureItemServiceFeature into the .R struct +func (os OrganizationSlice) LoadFieldseekerServiceFeatureItemServiceFeature(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisServiceFeatures, err := os.FieldseekerServiceFeatureItemServiceFeature(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisServiceFeatures { + if !o.FieldseekerServiceFeatureItemID.IsValue() { + continue + } + + if !(o.FieldseekerServiceFeatureItemID.IsValue() && o.FieldseekerServiceFeatureItemID.MustGet() == rel.ItemID) { + continue + } + + rel.R.FieldseekerServiceFeatureItemOrganizations = append(rel.R.FieldseekerServiceFeatureItemOrganizations, o) + + o.R.FieldseekerServiceFeatureItemServiceFeature = rel + break + } + } + + return nil +} + // LoadNuisances loads the organization's Nuisances into the .R struct func (o *Organization) LoadNuisances(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -8245,6 +8828,7 @@ func (os OrganizationSlice) LoadUser(ctx context.Context, exec bob.Executor, mod // organizationC is where relationship counts are stored. type organizationC struct { + Accounts *int64 AddressMappings *int64 ParcelMappings *int64 EmailContacts *int64 @@ -8295,6 +8879,8 @@ func (o *Organization) PreloadCount(name string, count int64) error { } switch name { + case "Accounts": + o.C.Accounts = &count case "AddressMappings": o.C.AddressMappings = &count case "ParcelMappings": @@ -8382,6 +8968,7 @@ func (o *Organization) PreloadCount(name string, count int64) error { } type organizationCountPreloader struct { + Accounts func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader AddressMappings func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader ParcelMappings func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader EmailContacts func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader @@ -8427,6 +9014,23 @@ type organizationCountPreloader struct { func buildOrganizationCountPreloader() organizationCountPreloader { return organizationCountPreloader{ + Accounts: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Organization]("Accounts", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Organizations.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisAccounts.Name()), + sm.Where(psql.Quote(ArcgisAccounts.Alias(), "organization_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, AddressMappings: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { return countPreloader[*Organization]("AddressMappings", func(parent string) bob.Expression { // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) @@ -9134,6 +9738,7 @@ func buildOrganizationCountPreloader() organizationCountPreloader { } type organizationCountThenLoader[Q orm.Loadable] struct { + Accounts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] AddressMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] ParcelMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] EmailContacts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] @@ -9178,6 +9783,9 @@ type organizationCountThenLoader[Q orm.Loadable] struct { } func buildOrganizationCountThenLoader[Q orm.Loadable]() organizationCountThenLoader[Q] { + type AccountsCountInterface interface { + LoadCountAccounts(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type AddressMappingsCountInterface interface { LoadCountAddressMappings(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -9303,6 +9911,12 @@ func buildOrganizationCountThenLoader[Q orm.Loadable]() organizationCountThenLoa } return organizationCountThenLoader[Q]{ + Accounts: countThenLoadBuilder[Q]( + "Accounts", + func(ctx context.Context, exec bob.Executor, retrieved AccountsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountAccounts(ctx, exec, mods...) + }, + ), AddressMappings: countThenLoadBuilder[Q]( "AddressMappings", func(ctx context.Context, exec bob.Executor, retrieved AddressMappingsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -9552,6 +10166,36 @@ func buildOrganizationCountThenLoader[Q orm.Loadable]() organizationCountThenLoa } } +// LoadCountAccounts loads the count of Accounts into the C struct +func (o *Organization) LoadCountAccounts(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.Accounts(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.Accounts = &count + return nil +} + +// LoadCountAccounts loads the count of Accounts for a slice +func (os OrganizationSlice) LoadCountAccounts(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountAccounts(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + // LoadCountAddressMappings loads the count of AddressMappings into the C struct func (o *Organization) LoadCountAddressMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -10783,48 +11427,51 @@ func (os OrganizationSlice) LoadCountUser(ctx context.Context, exec bob.Executor } type organizationJoins[Q dialect.Joinable] struct { - typ string - AddressMappings modAs[Q, arcgisAddressMappingColumns] - ParcelMappings modAs[Q, arcgisParcelMappingColumns] - EmailContacts modAs[Q, commsEmailContactColumns] - Phones modAs[Q, commsPhoneColumns] - Containerrelates modAs[Q, fieldseekerContainerrelateColumns] - Fieldscoutinglogs modAs[Q, fieldseekerFieldscoutinglogColumns] - Habitatrelates modAs[Q, fieldseekerHabitatrelateColumns] - Inspectionsamples modAs[Q, fieldseekerInspectionsampleColumns] - Inspectionsampledetails modAs[Q, fieldseekerInspectionsampledetailColumns] - Linelocations modAs[Q, fieldseekerLinelocationColumns] - Locationtrackings modAs[Q, fieldseekerLocationtrackingColumns] - Mosquitoinspections modAs[Q, fieldseekerMosquitoinspectionColumns] - Pointlocations modAs[Q, fieldseekerPointlocationColumns] - Polygonlocations modAs[Q, fieldseekerPolygonlocationColumns] - FieldseekerPool modAs[Q, fieldseekerPoolColumns] - Pooldetails modAs[Q, fieldseekerPooldetailColumns] - Proposedtreatmentareas modAs[Q, fieldseekerProposedtreatmentareaColumns] - Qamosquitoinspections modAs[Q, fieldseekerQamosquitoinspectionColumns] - Rodentlocations modAs[Q, fieldseekerRodentlocationColumns] - Samplecollections modAs[Q, fieldseekerSamplecollectionColumns] - Samplelocations modAs[Q, fieldseekerSamplelocationColumns] - Servicerequests modAs[Q, fieldseekerServicerequestColumns] - Speciesabundances modAs[Q, fieldseekerSpeciesabundanceColumns] - Stormdrains modAs[Q, fieldseekerStormdrainColumns] - Timecards modAs[Q, fieldseekerTimecardColumns] - Trapdata modAs[Q, fieldseekerTrapdatumColumns] - Traplocations modAs[Q, fieldseekerTraplocationColumns] - Treatments modAs[Q, fieldseekerTreatmentColumns] - Treatmentareas modAs[Q, fieldseekerTreatmentareaColumns] - Zones modAs[Q, fieldseekerZoneColumns] - Zones2s modAs[Q, fieldseekerZones2Columns] - FieldseekerSyncs modAs[Q, fieldseekerSyncColumns] - Files modAs[Q, fileuploadFileColumns] - Pools modAs[Q, fileuploadPoolColumns] - H3Aggregations modAs[Q, h3AggregationColumns] - NoteAudios modAs[Q, noteAudioColumns] - NoteImages modAs[Q, noteImageColumns] - Nuisances modAs[Q, publicreportNuisanceColumns] - PublicreportPool modAs[Q, publicreportPoolColumns] - Quicks modAs[Q, publicreportQuickColumns] - User modAs[Q, userColumns] + typ string + Accounts modAs[Q, arcgisAccountColumns] + AddressMappings modAs[Q, arcgisAddressMappingColumns] + ParcelMappings modAs[Q, arcgisParcelMappingColumns] + EmailContacts modAs[Q, commsEmailContactColumns] + Phones modAs[Q, commsPhoneColumns] + Containerrelates modAs[Q, fieldseekerContainerrelateColumns] + Fieldscoutinglogs modAs[Q, fieldseekerFieldscoutinglogColumns] + Habitatrelates modAs[Q, fieldseekerHabitatrelateColumns] + Inspectionsamples modAs[Q, fieldseekerInspectionsampleColumns] + Inspectionsampledetails modAs[Q, fieldseekerInspectionsampledetailColumns] + Linelocations modAs[Q, fieldseekerLinelocationColumns] + Locationtrackings modAs[Q, fieldseekerLocationtrackingColumns] + Mosquitoinspections modAs[Q, fieldseekerMosquitoinspectionColumns] + Pointlocations modAs[Q, fieldseekerPointlocationColumns] + Polygonlocations modAs[Q, fieldseekerPolygonlocationColumns] + FieldseekerPool modAs[Q, fieldseekerPoolColumns] + Pooldetails modAs[Q, fieldseekerPooldetailColumns] + Proposedtreatmentareas modAs[Q, fieldseekerProposedtreatmentareaColumns] + Qamosquitoinspections modAs[Q, fieldseekerQamosquitoinspectionColumns] + Rodentlocations modAs[Q, fieldseekerRodentlocationColumns] + Samplecollections modAs[Q, fieldseekerSamplecollectionColumns] + Samplelocations modAs[Q, fieldseekerSamplelocationColumns] + Servicerequests modAs[Q, fieldseekerServicerequestColumns] + Speciesabundances modAs[Q, fieldseekerSpeciesabundanceColumns] + Stormdrains modAs[Q, fieldseekerStormdrainColumns] + Timecards modAs[Q, fieldseekerTimecardColumns] + Trapdata modAs[Q, fieldseekerTrapdatumColumns] + Traplocations modAs[Q, fieldseekerTraplocationColumns] + Treatments modAs[Q, fieldseekerTreatmentColumns] + Treatmentareas modAs[Q, fieldseekerTreatmentareaColumns] + Zones modAs[Q, fieldseekerZoneColumns] + Zones2s modAs[Q, fieldseekerZones2Columns] + FieldseekerSyncs modAs[Q, fieldseekerSyncColumns] + Files modAs[Q, fileuploadFileColumns] + Pools modAs[Q, fileuploadPoolColumns] + H3Aggregations modAs[Q, h3AggregationColumns] + NoteAudios modAs[Q, noteAudioColumns] + NoteImages modAs[Q, noteImageColumns] + ArcgisAccountAccount modAs[Q, arcgisAccountColumns] + FieldseekerServiceFeatureItemServiceFeature modAs[Q, arcgisServiceFeatureColumns] + Nuisances modAs[Q, publicreportNuisanceColumns] + PublicreportPool modAs[Q, publicreportPoolColumns] + Quicks modAs[Q, publicreportQuickColumns] + User modAs[Q, userColumns] } func (j organizationJoins[Q]) aliasedAs(alias string) organizationJoins[Q] { @@ -10834,6 +11481,20 @@ func (j organizationJoins[Q]) aliasedAs(alias string) organizationJoins[Q] { func buildOrganizationJoins[Q dialect.Joinable](cols organizationColumns, typ string) organizationJoins[Q] { return organizationJoins[Q]{ typ: typ, + Accounts: modAs[Q, arcgisAccountColumns]{ + c: ArcgisAccounts.Columns, + f: func(to arcgisAccountColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On( + to.OrganizationID.EQ(cols.ID), + )) + } + + return mods + }, + }, AddressMappings: modAs[Q, arcgisAddressMappingColumns]{ c: ArcgisAddressMappings.Columns, f: func(to arcgisAddressMappingColumns) bob.Mod[Q] { @@ -11368,6 +12029,34 @@ func buildOrganizationJoins[Q dialect.Joinable](cols organizationColumns, typ st return mods }, }, + ArcgisAccountAccount: modAs[Q, arcgisAccountColumns]{ + c: ArcgisAccounts.Columns, + f: func(to arcgisAccountColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisAccounts.Name().As(to.Alias())).On( + to.ID.EQ(cols.ArcgisAccountID), + )) + } + + return mods + }, + }, + FieldseekerServiceFeatureItemServiceFeature: modAs[Q, arcgisServiceFeatureColumns]{ + c: ArcgisServiceFeatures.Columns, + f: func(to arcgisServiceFeatureColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisServiceFeatures.Name().As(to.Alias())).On( + to.ItemID.EQ(cols.FieldseekerServiceFeatureItemID), + )) + } + + return mods + }, + }, Nuisances: modAs[Q, publicreportNuisanceColumns]{ c: PublicreportNuisances.Columns, f: func(to publicreportNuisanceColumns) bob.Mod[Q] { diff --git a/db/models/parcel.bob.go b/db/models/parcel.bob.go index 41f92cc1..dc1d0c97 100644 --- a/db/models/parcel.bob.go +++ b/db/models/parcel.bob.go @@ -5,6 +5,7 @@ package models import ( "context" + "fmt" "io" "github.com/Gleipnir-Technology/bob" @@ -14,15 +15,24 @@ import ( "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/mods" + "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" ) // Parcel is an object representing the database table. type Parcel struct { - Apn string `db:"apn" ` - Description string `db:"description" ` - ID int32 `db:"id,pk" ` - Geometry string `db:"geometry" ` + Apn null.Val[string] `db:"apn" ` + Description null.Val[string] `db:"description" ` + ID int32 `db:"id,pk" ` + Geometry string `db:"geometry" ` + + R parcelR `db:"-" ` + + C parcelC `db:"-" ` } // ParcelSlice is an alias for a slice of pointers to Parcel. @@ -35,6 +45,11 @@ var Parcels = psql.NewTablex[*Parcel, ParcelSlice, *ParcelSetter]("", "parcel", // ParcelsQuery is a query on the parcel table type ParcelsQuery = *psql.ViewQuery[*Parcel, ParcelSlice] +// parcelR is where relationships are stored. +type parcelR struct { + Sites SiteSlice // site.site_parcel_id_fkey +} + func buildParcelColumns(alias string) parcelColumns { return parcelColumns{ ColumnsExpr: expr.NewColumnsExpr( @@ -69,18 +84,18 @@ func (parcelColumns) AliasedAs(alias string) parcelColumns { // All values are optional, and do not have to be set // Generated columns are not included type ParcelSetter struct { - Apn omit.Val[string] `db:"apn" ` - Description omit.Val[string] `db:"description" ` - ID omit.Val[int32] `db:"id,pk" ` - Geometry omit.Val[string] `db:"geometry" ` + Apn omitnull.Val[string] `db:"apn" ` + Description omitnull.Val[string] `db:"description" ` + ID omit.Val[int32] `db:"id,pk" ` + Geometry omit.Val[string] `db:"geometry" ` } func (s ParcelSetter) SetColumns() []string { vals := make([]string, 0, 4) - if s.Apn.IsValue() { + if !s.Apn.IsUnset() { vals = append(vals, "apn") } - if s.Description.IsValue() { + if !s.Description.IsUnset() { vals = append(vals, "description") } if s.ID.IsValue() { @@ -93,11 +108,11 @@ func (s ParcelSetter) SetColumns() []string { } func (s ParcelSetter) Overwrite(t *Parcel) { - if s.Apn.IsValue() { - t.Apn = s.Apn.MustGet() + if !s.Apn.IsUnset() { + t.Apn = s.Apn.MustGetNull() } - if s.Description.IsValue() { - t.Description = s.Description.MustGet() + if !s.Description.IsUnset() { + t.Description = s.Description.MustGetNull() } if s.ID.IsValue() { t.ID = s.ID.MustGet() @@ -114,14 +129,14 @@ func (s *ParcelSetter) 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, 4) - if s.Apn.IsValue() { - vals[0] = psql.Arg(s.Apn.MustGet()) + if !s.Apn.IsUnset() { + vals[0] = psql.Arg(s.Apn.MustGetNull()) } else { vals[0] = psql.Raw("DEFAULT") } - if s.Description.IsValue() { - vals[1] = psql.Arg(s.Description.MustGet()) + if !s.Description.IsUnset() { + vals[1] = psql.Arg(s.Description.MustGetNull()) } else { vals[1] = psql.Raw("DEFAULT") } @@ -149,14 +164,14 @@ func (s ParcelSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { func (s ParcelSetter) Expressions(prefix ...string) []bob.Expression { exprs := make([]bob.Expression, 0, 4) - if s.Apn.IsValue() { + if !s.Apn.IsUnset() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "apn")...), psql.Arg(s.Apn), }}) } - if s.Description.IsValue() { + if !s.Description.IsUnset() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "description")...), psql.Arg(s.Description), @@ -238,6 +253,7 @@ func (o *Parcel) Update(ctx context.Context, exec bob.Executor, s *ParcelSetter) return err } + o.R = v.R *o = *v return nil @@ -257,7 +273,7 @@ func (o *Parcel) Reload(ctx context.Context, exec bob.Executor) error { if err != nil { return err } - + o2.R = o.R *o = *o2 return nil @@ -304,7 +320,7 @@ func (o ParcelSlice) copyMatchingRows(from ...*Parcel) { if new.ID != old.ID { continue } - + new.R = old.R o[i] = new break } @@ -402,9 +418,101 @@ func (o ParcelSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { return nil } +// Sites starts a query for related objects on site +func (o *Parcel) Sites(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + return Sites.Query(append(mods, + sm.Where(Sites.Columns.ParcelID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os ParcelSlice) Sites(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + 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 Sites.Query(append(mods, + sm.Where(psql.Group(Sites.Columns.ParcelID).OP("IN", PKArgExpr)), + )...) +} + +func insertParcelSites0(ctx context.Context, exec bob.Executor, sites1 []*SiteSetter, parcel0 *Parcel) (SiteSlice, error) { + for i := range sites1 { + sites1[i].ParcelID = omit.From(parcel0.ID) + } + + ret, err := Sites.Insert(bob.ToMods(sites1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertParcelSites0: %w", err) + } + + return ret, nil +} + +func attachParcelSites0(ctx context.Context, exec bob.Executor, count int, sites1 SiteSlice, parcel0 *Parcel) (SiteSlice, error) { + setter := &SiteSetter{ + ParcelID: omit.From(parcel0.ID), + } + + err := sites1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachParcelSites0: %w", err) + } + + return sites1, nil +} + +func (parcel0 *Parcel) InsertSites(ctx context.Context, exec bob.Executor, related ...*SiteSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + sites1, err := insertParcelSites0(ctx, exec, related, parcel0) + if err != nil { + return err + } + + parcel0.R.Sites = append(parcel0.R.Sites, sites1...) + + for _, rel := range sites1 { + rel.R.Parcel = parcel0 + } + return nil +} + +func (parcel0 *Parcel) AttachSites(ctx context.Context, exec bob.Executor, related ...*Site) error { + if len(related) == 0 { + return nil + } + + var err error + sites1 := SiteSlice(related) + + _, err = attachParcelSites0(ctx, exec, len(related), sites1, parcel0) + if err != nil { + return err + } + + parcel0.R.Sites = append(parcel0.R.Sites, sites1...) + + for _, rel := range related { + rel.R.Parcel = parcel0 + } + + return nil +} + type parcelWhere[Q psql.Filterable] struct { - Apn psql.WhereMod[Q, string] - Description psql.WhereMod[Q, string] + Apn psql.WhereNullMod[Q, string] + Description psql.WhereNullMod[Q, string] ID psql.WhereMod[Q, int32] Geometry psql.WhereMod[Q, string] } @@ -415,9 +523,242 @@ func (parcelWhere[Q]) AliasedAs(alias string) parcelWhere[Q] { func buildParcelWhere[Q psql.Filterable](cols parcelColumns) parcelWhere[Q] { return parcelWhere[Q]{ - Apn: psql.Where[Q, string](cols.Apn), - Description: psql.Where[Q, string](cols.Description), + Apn: psql.WhereNull[Q, string](cols.Apn), + Description: psql.WhereNull[Q, string](cols.Description), ID: psql.Where[Q, int32](cols.ID), Geometry: psql.Where[Q, string](cols.Geometry), } } + +func (o *Parcel) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "Sites": + rels, ok := retrieved.(SiteSlice) + if !ok { + return fmt.Errorf("parcel cannot load %T as %q", retrieved, name) + } + + o.R.Sites = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Parcel = o + } + } + return nil + default: + return fmt.Errorf("parcel has no relationship %q", name) + } +} + +type parcelPreloader struct{} + +func buildParcelPreloader() parcelPreloader { + return parcelPreloader{} +} + +type parcelThenLoader[Q orm.Loadable] struct { + Sites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildParcelThenLoader[Q orm.Loadable]() parcelThenLoader[Q] { + type SitesLoadInterface interface { + LoadSites(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return parcelThenLoader[Q]{ + Sites: thenLoadBuilder[Q]( + "Sites", + func(ctx context.Context, exec bob.Executor, retrieved SitesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadSites(ctx, exec, mods...) + }, + ), + } +} + +// LoadSites loads the parcel's Sites into the .R struct +func (o *Parcel) LoadSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Sites = nil + + related, err := o.Sites(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Parcel = o + } + + o.R.Sites = related + return nil +} + +// LoadSites loads the parcel's Sites into the .R struct +func (os ParcelSlice) LoadSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + sites, err := os.Sites(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.Sites = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range sites { + + if !(o.ID == rel.ParcelID) { + continue + } + + rel.R.Parcel = o + + o.R.Sites = append(o.R.Sites, rel) + } + } + + return nil +} + +// parcelC is where relationship counts are stored. +type parcelC struct { + Sites *int64 +} + +// PreloadCount sets a count in the C struct by name +func (o *Parcel) PreloadCount(name string, count int64) error { + if o == nil { + return nil + } + + switch name { + case "Sites": + o.C.Sites = &count + } + return nil +} + +type parcelCountPreloader struct { + Sites func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader +} + +func buildParcelCountPreloader() parcelCountPreloader { + return parcelCountPreloader{ + Sites: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Parcel]("Sites", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Parcels.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Sites.Name()), + sm.Where(psql.Quote(Sites.Alias(), "parcel_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + } +} + +type parcelCountThenLoader[Q orm.Loadable] struct { + Sites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildParcelCountThenLoader[Q orm.Loadable]() parcelCountThenLoader[Q] { + type SitesCountInterface interface { + LoadCountSites(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return parcelCountThenLoader[Q]{ + Sites: countThenLoadBuilder[Q]( + "Sites", + func(ctx context.Context, exec bob.Executor, retrieved SitesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountSites(ctx, exec, mods...) + }, + ), + } +} + +// LoadCountSites loads the count of Sites into the C struct +func (o *Parcel) LoadCountSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.Sites(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.Sites = &count + return nil +} + +// LoadCountSites loads the count of Sites for a slice +func (os ParcelSlice) LoadCountSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountSites(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +type parcelJoins[Q dialect.Joinable] struct { + typ string + Sites modAs[Q, siteColumns] +} + +func (j parcelJoins[Q]) aliasedAs(alias string) parcelJoins[Q] { + return buildParcelJoins[Q](buildParcelColumns(alias), j.typ) +} + +func buildParcelJoins[Q dialect.Joinable](cols parcelColumns, typ string) parcelJoins[Q] { + return parcelJoins[Q]{ + typ: typ, + Sites: modAs[Q, siteColumns]{ + c: Sites.Columns, + f: func(to siteColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On( + to.ParcelID.EQ(cols.ID), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/pool.bob.go b/db/models/pool.bob.go index 105aad34..9888aaad 100644 --- a/db/models/pool.bob.go +++ b/db/models/pool.bob.go @@ -20,18 +20,17 @@ import ( "github.com/Gleipnir-Technology/bob/orm" "github.com/Gleipnir-Technology/bob/types/pgtypes" enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" - "github.com/aarondl/opt/null" "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" ) // Pool is an object representing the database table. type Pool struct { - Condition enums.Poolconditiontype `db:"condition" ` - Created time.Time `db:"created" ` - CreatorID int32 `db:"creator_id" ` - ID int32 `db:"id,pk" ` - SiteID null.Val[int32] `db:"site_id" ` + Condition enums.Poolconditiontype `db:"condition" ` + Created time.Time `db:"created" ` + CreatorID int32 `db:"creator_id" ` + ID int32 `db:"id,pk" ` + SiteID int32 `db:"site_id" ` + SiteVersion int32 `db:"site_version" ` R poolR `db:"-" ` } @@ -49,30 +48,33 @@ type PoolsQuery = *psql.ViewQuery[*Pool, PoolSlice] // poolR is where relationships are stored. type poolR struct { CreatorUser *User // pool.pool_creator_id_fkey + Site *Site // pool.pool_site_id_site_version_fkey } func buildPoolColumns(alias string) poolColumns { return poolColumns{ ColumnsExpr: expr.NewColumnsExpr( - "condition", "created", "creator_id", "id", "site_id", + "condition", "created", "creator_id", "id", "site_id", "site_version", ).WithParent("pool"), - tableAlias: alias, - Condition: psql.Quote(alias, "condition"), - Created: psql.Quote(alias, "created"), - CreatorID: psql.Quote(alias, "creator_id"), - ID: psql.Quote(alias, "id"), - SiteID: psql.Quote(alias, "site_id"), + tableAlias: alias, + Condition: psql.Quote(alias, "condition"), + Created: psql.Quote(alias, "created"), + CreatorID: psql.Quote(alias, "creator_id"), + ID: psql.Quote(alias, "id"), + SiteID: psql.Quote(alias, "site_id"), + SiteVersion: psql.Quote(alias, "site_version"), } } type poolColumns struct { expr.ColumnsExpr - tableAlias string - Condition psql.Expression - Created psql.Expression - CreatorID psql.Expression - ID psql.Expression - SiteID psql.Expression + tableAlias string + Condition psql.Expression + Created psql.Expression + CreatorID psql.Expression + ID psql.Expression + SiteID psql.Expression + SiteVersion psql.Expression } func (c poolColumns) Alias() string { @@ -87,15 +89,16 @@ func (poolColumns) AliasedAs(alias string) poolColumns { // All values are optional, and do not have to be set // Generated columns are not included type PoolSetter struct { - Condition omit.Val[enums.Poolconditiontype] `db:"condition" ` - Created omit.Val[time.Time] `db:"created" ` - CreatorID omit.Val[int32] `db:"creator_id" ` - ID omit.Val[int32] `db:"id,pk" ` - SiteID omitnull.Val[int32] `db:"site_id" ` + Condition omit.Val[enums.Poolconditiontype] `db:"condition" ` + Created omit.Val[time.Time] `db:"created" ` + CreatorID omit.Val[int32] `db:"creator_id" ` + ID omit.Val[int32] `db:"id,pk" ` + SiteID omit.Val[int32] `db:"site_id" ` + SiteVersion omit.Val[int32] `db:"site_version" ` } func (s PoolSetter) SetColumns() []string { - vals := make([]string, 0, 5) + vals := make([]string, 0, 6) if s.Condition.IsValue() { vals = append(vals, "condition") } @@ -108,9 +111,12 @@ func (s PoolSetter) SetColumns() []string { if s.ID.IsValue() { vals = append(vals, "id") } - if !s.SiteID.IsUnset() { + if s.SiteID.IsValue() { vals = append(vals, "site_id") } + if s.SiteVersion.IsValue() { + vals = append(vals, "site_version") + } return vals } @@ -127,8 +133,11 @@ func (s PoolSetter) Overwrite(t *Pool) { if s.ID.IsValue() { t.ID = s.ID.MustGet() } - if !s.SiteID.IsUnset() { - t.SiteID = s.SiteID.MustGetNull() + if s.SiteID.IsValue() { + t.SiteID = s.SiteID.MustGet() + } + if s.SiteVersion.IsValue() { + t.SiteVersion = s.SiteVersion.MustGet() } } @@ -138,7 +147,7 @@ func (s *PoolSetter) 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, 5) + vals := make([]bob.Expression, 6) if s.Condition.IsValue() { vals[0] = psql.Arg(s.Condition.MustGet()) } else { @@ -163,12 +172,18 @@ func (s *PoolSetter) Apply(q *dialect.InsertQuery) { vals[3] = psql.Raw("DEFAULT") } - if !s.SiteID.IsUnset() { - vals[4] = psql.Arg(s.SiteID.MustGetNull()) + if s.SiteID.IsValue() { + vals[4] = psql.Arg(s.SiteID.MustGet()) } else { vals[4] = psql.Raw("DEFAULT") } + if s.SiteVersion.IsValue() { + vals[5] = psql.Arg(s.SiteVersion.MustGet()) + } else { + vals[5] = psql.Raw("DEFAULT") + } + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") })) } @@ -178,7 +193,7 @@ func (s PoolSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { } func (s PoolSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 5) + exprs := make([]bob.Expression, 0, 6) if s.Condition.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ @@ -208,13 +223,20 @@ func (s PoolSetter) Expressions(prefix ...string) []bob.Expression { }}) } - if !s.SiteID.IsUnset() { + if s.SiteID.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "site_id")...), psql.Arg(s.SiteID), }}) } + if s.SiteVersion.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "site_version")...), + psql.Arg(s.SiteVersion), + }}) + } + return exprs } @@ -465,6 +487,34 @@ func (os PoolSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuer )...) } +// Site starts a query for related objects on site +func (o *Pool) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + return Sites.Query(append(mods, + sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))), sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.SiteVersion))), + )...) +} + +func (os PoolSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + pkSiteID := make(pgtypes.Array[int32], 0, len(os)) + + pkSiteVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkSiteID = append(pkSiteID, o.SiteID) + pkSiteVersion = append(pkSiteVersion, o.SiteVersion) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkSiteID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkSiteVersion), "integer[]")), + )) + + return Sites.Query(append(mods, + sm.Where(psql.Group(Sites.Columns.ID, Sites.Columns.Version).OP("IN", PKArgExpr)), + )...) +} + func attachPoolCreatorUser0(ctx context.Context, exec bob.Executor, count int, pool0 *Pool, user1 *User) (*Pool, error) { setter := &PoolSetter{ CreatorID: omit.From(user1.ID), @@ -513,12 +563,62 @@ func (pool0 *Pool) AttachCreatorUser(ctx context.Context, exec bob.Executor, use return nil } +func attachPoolSite0(ctx context.Context, exec bob.Executor, count int, pool0 *Pool, site1 *Site) (*Pool, error) { + setter := &PoolSetter{ + SiteID: omit.From(site1.ID), + SiteVersion: omit.From(site1.Version), + } + + err := pool0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachPoolSite0: %w", err) + } + + return pool0, nil +} + +func (pool0 *Pool) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error { + var err error + + site1, err := Sites.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachPoolSite0(ctx, exec, 1, pool0, site1) + if err != nil { + return err + } + + pool0.R.Site = site1 + + site1.R.Pools = append(site1.R.Pools, pool0) + + return nil +} + +func (pool0 *Pool) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error { + var err error + + _, err = attachPoolSite0(ctx, exec, 1, pool0, site1) + if err != nil { + return err + } + + pool0.R.Site = site1 + + site1.R.Pools = append(site1.R.Pools, pool0) + + return nil +} + type poolWhere[Q psql.Filterable] struct { - Condition psql.WhereMod[Q, enums.Poolconditiontype] - Created psql.WhereMod[Q, time.Time] - CreatorID psql.WhereMod[Q, int32] - ID psql.WhereMod[Q, int32] - SiteID psql.WhereNullMod[Q, int32] + Condition psql.WhereMod[Q, enums.Poolconditiontype] + Created psql.WhereMod[Q, time.Time] + CreatorID psql.WhereMod[Q, int32] + ID psql.WhereMod[Q, int32] + SiteID psql.WhereMod[Q, int32] + SiteVersion psql.WhereMod[Q, int32] } func (poolWhere[Q]) AliasedAs(alias string) poolWhere[Q] { @@ -527,11 +627,12 @@ func (poolWhere[Q]) AliasedAs(alias string) poolWhere[Q] { func buildPoolWhere[Q psql.Filterable](cols poolColumns) poolWhere[Q] { return poolWhere[Q]{ - Condition: psql.Where[Q, enums.Poolconditiontype](cols.Condition), - Created: psql.Where[Q, time.Time](cols.Created), - CreatorID: psql.Where[Q, int32](cols.CreatorID), - ID: psql.Where[Q, int32](cols.ID), - SiteID: psql.WhereNull[Q, int32](cols.SiteID), + Condition: psql.Where[Q, enums.Poolconditiontype](cols.Condition), + Created: psql.Where[Q, time.Time](cols.Created), + CreatorID: psql.Where[Q, int32](cols.CreatorID), + ID: psql.Where[Q, int32](cols.ID), + SiteID: psql.Where[Q, int32](cols.SiteID), + SiteVersion: psql.Where[Q, int32](cols.SiteVersion), } } @@ -553,6 +654,18 @@ func (o *Pool) Preload(name string, retrieved any) error { rel.R.CreatorPools = PoolSlice{o} } return nil + case "Site": + rel, ok := retrieved.(*Site) + if !ok { + return fmt.Errorf("pool cannot load %T as %q", retrieved, name) + } + + o.R.Site = rel + + if rel != nil { + rel.R.Pools = PoolSlice{o} + } + return nil default: return fmt.Errorf("pool has no relationship %q", name) } @@ -560,6 +673,7 @@ func (o *Pool) Preload(name string, retrieved any) error { type poolPreloader struct { CreatorUser func(...psql.PreloadOption) psql.Preloader + Site func(...psql.PreloadOption) psql.Preloader } func buildPoolPreloader() poolPreloader { @@ -577,17 +691,34 @@ func buildPoolPreloader() poolPreloader { }, }, Users.Columns.Names(), opts...) }, + Site: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Site, SiteSlice](psql.PreloadRel{ + Name: "Site", + Sides: []psql.PreloadSide{ + { + From: Pools, + To: Sites, + FromColumns: []string{"site_id", "site_version"}, + ToColumns: []string{"id", "version"}, + }, + }, + }, Sites.Columns.Names(), opts...) + }, } } type poolThenLoader[Q orm.Loadable] struct { CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Site func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildPoolThenLoader[Q orm.Loadable]() poolThenLoader[Q] { type CreatorUserLoadInterface interface { LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type SiteLoadInterface interface { + LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } return poolThenLoader[Q]{ CreatorUser: thenLoadBuilder[Q]( @@ -596,6 +727,12 @@ func buildPoolThenLoader[Q orm.Loadable]() poolThenLoader[Q] { return retrieved.LoadCreatorUser(ctx, exec, mods...) }, ), + Site: thenLoadBuilder[Q]( + "Site", + func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadSite(ctx, exec, mods...) + }, + ), } } @@ -651,9 +788,66 @@ func (os PoolSlice) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods return nil } +// LoadSite loads the pool's Site into the .R struct +func (o *Pool) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Site = nil + + related, err := o.Site(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.Pools = PoolSlice{o} + + o.R.Site = related + return nil +} + +// LoadSite loads the pool's Site into the .R struct +func (os PoolSlice) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + sites, err := os.Site(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range sites { + + if !(o.SiteID == rel.ID) { + continue + } + + if !(o.SiteVersion == rel.Version) { + continue + } + + rel.R.Pools = append(rel.R.Pools, o) + + o.R.Site = rel + break + } + } + + return nil +} + type poolJoins[Q dialect.Joinable] struct { typ string CreatorUser modAs[Q, userColumns] + Site modAs[Q, siteColumns] } func (j poolJoins[Q]) aliasedAs(alias string) poolJoins[Q] { @@ -674,6 +868,20 @@ func buildPoolJoins[Q dialect.Joinable](cols poolColumns, typ string) poolJoins[ )) } + return mods + }, + }, + Site: modAs[Q, siteColumns]{ + c: Sites.Columns, + f: func(to siteColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On( + to.ID.EQ(cols.SiteID), to.Version.EQ(cols.SiteVersion), + )) + } + return mods }, }, diff --git a/db/models/resident.bob.go b/db/models/resident.bob.go new file mode 100644 index 00000000..919d2877 --- /dev/null +++ b/db/models/resident.bob.go @@ -0,0 +1,1295 @@ +// 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/mods" + "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" +) + +// Resident is an object representing the database table. +type Resident struct { + AddressID int32 `db:"address_id" ` + Created time.Time `db:"created" ` + Creator int32 `db:"creator" ` + ID int32 `db:"id,pk" ` + Name string `db:"name" ` + PhoneMobile null.Val[string] `db:"phone_mobile" ` + SiteID int32 `db:"site_id" ` + SiteVersion int32 `db:"site_version" ` + + R residentR `db:"-" ` +} + +// ResidentSlice is an alias for a slice of pointers to Resident. +// This should almost always be used instead of []*Resident. +type ResidentSlice []*Resident + +// Residents contains methods to work with the resident table +var Residents = psql.NewTablex[*Resident, ResidentSlice, *ResidentSetter]("", "resident", buildResidentColumns("resident")) + +// ResidentsQuery is a query on the resident table +type ResidentsQuery = *psql.ViewQuery[*Resident, ResidentSlice] + +// residentR is where relationships are stored. +type residentR struct { + Address *Address // resident.resident_address_id_fkey + CreatorUser *User // resident.resident_creator_fkey + PhoneMobilePhone *CommsPhone // resident.resident_phone_mobile_fkey + Site *Site // resident.resident_site_id_site_version_fkey +} + +func buildResidentColumns(alias string) residentColumns { + return residentColumns{ + ColumnsExpr: expr.NewColumnsExpr( + "address_id", "created", "creator", "id", "name", "phone_mobile", "site_id", "site_version", + ).WithParent("resident"), + tableAlias: alias, + AddressID: psql.Quote(alias, "address_id"), + Created: psql.Quote(alias, "created"), + Creator: psql.Quote(alias, "creator"), + ID: psql.Quote(alias, "id"), + Name: psql.Quote(alias, "name"), + PhoneMobile: psql.Quote(alias, "phone_mobile"), + SiteID: psql.Quote(alias, "site_id"), + SiteVersion: psql.Quote(alias, "site_version"), + } +} + +type residentColumns struct { + expr.ColumnsExpr + tableAlias string + AddressID psql.Expression + Created psql.Expression + Creator psql.Expression + ID psql.Expression + Name psql.Expression + PhoneMobile psql.Expression + SiteID psql.Expression + SiteVersion psql.Expression +} + +func (c residentColumns) Alias() string { + return c.tableAlias +} + +func (residentColumns) AliasedAs(alias string) residentColumns { + return buildResidentColumns(alias) +} + +// ResidentSetter is used for insert/upsert/update operations +// All values are optional, and do not have to be set +// Generated columns are not included +type ResidentSetter struct { + AddressID omit.Val[int32] `db:"address_id" ` + Created omit.Val[time.Time] `db:"created" ` + Creator omit.Val[int32] `db:"creator" ` + ID omit.Val[int32] `db:"id,pk" ` + Name omit.Val[string] `db:"name" ` + PhoneMobile omitnull.Val[string] `db:"phone_mobile" ` + SiteID omit.Val[int32] `db:"site_id" ` + SiteVersion omit.Val[int32] `db:"site_version" ` +} + +func (s ResidentSetter) SetColumns() []string { + vals := make([]string, 0, 8) + if s.AddressID.IsValue() { + vals = append(vals, "address_id") + } + if s.Created.IsValue() { + vals = append(vals, "created") + } + if s.Creator.IsValue() { + vals = append(vals, "creator") + } + if s.ID.IsValue() { + vals = append(vals, "id") + } + if s.Name.IsValue() { + vals = append(vals, "name") + } + if !s.PhoneMobile.IsUnset() { + vals = append(vals, "phone_mobile") + } + if s.SiteID.IsValue() { + vals = append(vals, "site_id") + } + if s.SiteVersion.IsValue() { + vals = append(vals, "site_version") + } + return vals +} + +func (s ResidentSetter) Overwrite(t *Resident) { + if s.AddressID.IsValue() { + t.AddressID = s.AddressID.MustGet() + } + if s.Created.IsValue() { + t.Created = s.Created.MustGet() + } + if s.Creator.IsValue() { + t.Creator = s.Creator.MustGet() + } + if s.ID.IsValue() { + t.ID = s.ID.MustGet() + } + if s.Name.IsValue() { + t.Name = s.Name.MustGet() + } + if !s.PhoneMobile.IsUnset() { + t.PhoneMobile = s.PhoneMobile.MustGetNull() + } + if s.SiteID.IsValue() { + t.SiteID = s.SiteID.MustGet() + } + if s.SiteVersion.IsValue() { + t.SiteVersion = s.SiteVersion.MustGet() + } +} + +func (s *ResidentSetter) Apply(q *dialect.InsertQuery) { + q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { + return Residents.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, 8) + if s.AddressID.IsValue() { + vals[0] = psql.Arg(s.AddressID.MustGet()) + } else { + vals[0] = psql.Raw("DEFAULT") + } + + if s.Created.IsValue() { + vals[1] = psql.Arg(s.Created.MustGet()) + } else { + vals[1] = psql.Raw("DEFAULT") + } + + if s.Creator.IsValue() { + vals[2] = psql.Arg(s.Creator.MustGet()) + } else { + vals[2] = psql.Raw("DEFAULT") + } + + if s.ID.IsValue() { + vals[3] = psql.Arg(s.ID.MustGet()) + } else { + vals[3] = psql.Raw("DEFAULT") + } + + if s.Name.IsValue() { + vals[4] = psql.Arg(s.Name.MustGet()) + } else { + vals[4] = psql.Raw("DEFAULT") + } + + if !s.PhoneMobile.IsUnset() { + vals[5] = psql.Arg(s.PhoneMobile.MustGetNull()) + } else { + vals[5] = psql.Raw("DEFAULT") + } + + if s.SiteID.IsValue() { + vals[6] = psql.Arg(s.SiteID.MustGet()) + } else { + vals[6] = psql.Raw("DEFAULT") + } + + if s.SiteVersion.IsValue() { + vals[7] = psql.Arg(s.SiteVersion.MustGet()) + } else { + vals[7] = psql.Raw("DEFAULT") + } + + return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") + })) +} + +func (s ResidentSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { + return um.Set(s.Expressions()...) +} + +func (s ResidentSetter) Expressions(prefix ...string) []bob.Expression { + exprs := make([]bob.Expression, 0, 8) + + if s.AddressID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "address_id")...), + psql.Arg(s.AddressID), + }}) + } + + if s.Created.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "created")...), + psql.Arg(s.Created), + }}) + } + + if s.Creator.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "creator")...), + psql.Arg(s.Creator), + }}) + } + + if s.ID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "id")...), + psql.Arg(s.ID), + }}) + } + + if s.Name.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "name")...), + psql.Arg(s.Name), + }}) + } + + if !s.PhoneMobile.IsUnset() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "phone_mobile")...), + psql.Arg(s.PhoneMobile), + }}) + } + + if s.SiteID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "site_id")...), + psql.Arg(s.SiteID), + }}) + } + + if s.SiteVersion.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "site_version")...), + psql.Arg(s.SiteVersion), + }}) + } + + return exprs +} + +// FindResident retrieves a single record by primary key +// If cols is empty Find will return all columns. +func FindResident(ctx context.Context, exec bob.Executor, IDPK int32, cols ...string) (*Resident, error) { + if len(cols) == 0 { + return Residents.Query( + sm.Where(Residents.Columns.ID.EQ(psql.Arg(IDPK))), + ).One(ctx, exec) + } + + return Residents.Query( + sm.Where(Residents.Columns.ID.EQ(psql.Arg(IDPK))), + sm.Columns(Residents.Columns.Only(cols...)), + ).One(ctx, exec) +} + +// ResidentExists checks the presence of a single record by primary key +func ResidentExists(ctx context.Context, exec bob.Executor, IDPK int32) (bool, error) { + return Residents.Query( + sm.Where(Residents.Columns.ID.EQ(psql.Arg(IDPK))), + ).Exists(ctx, exec) +} + +// AfterQueryHook is called after Resident is retrieved from the database +func (o *Resident) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = Residents.AfterSelectHooks.RunHooks(ctx, exec, ResidentSlice{o}) + case bob.QueryTypeInsert: + ctx, err = Residents.AfterInsertHooks.RunHooks(ctx, exec, ResidentSlice{o}) + case bob.QueryTypeUpdate: + ctx, err = Residents.AfterUpdateHooks.RunHooks(ctx, exec, ResidentSlice{o}) + case bob.QueryTypeDelete: + ctx, err = Residents.AfterDeleteHooks.RunHooks(ctx, exec, ResidentSlice{o}) + } + + return err +} + +// primaryKeyVals returns the primary key values of the Resident +func (o *Resident) primaryKeyVals() bob.Expression { + return psql.Arg(o.ID) +} + +func (o *Resident) pkEQ() dialect.Expression { + return psql.Quote("resident", "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 Resident +func (o *Resident) Update(ctx context.Context, exec bob.Executor, s *ResidentSetter) error { + v, err := Residents.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 Resident record with an executor +func (o *Resident) Delete(ctx context.Context, exec bob.Executor) error { + _, err := Residents.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) + return err +} + +// Reload refreshes the Resident using the executor +func (o *Resident) Reload(ctx context.Context, exec bob.Executor) error { + o2, err := Residents.Query( + sm.Where(Residents.Columns.ID.EQ(psql.Arg(o.ID))), + ).One(ctx, exec) + if err != nil { + return err + } + o2.R = o.R + *o = *o2 + + return nil +} + +// AfterQueryHook is called after ResidentSlice is retrieved from the database +func (o ResidentSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { + var err error + + switch queryType { + case bob.QueryTypeSelect: + ctx, err = Residents.AfterSelectHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeInsert: + ctx, err = Residents.AfterInsertHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeUpdate: + ctx, err = Residents.AfterUpdateHooks.RunHooks(ctx, exec, o) + case bob.QueryTypeDelete: + ctx, err = Residents.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err +} + +func (o ResidentSlice) pkIN() dialect.Expression { + if len(o) == 0 { + return psql.Raw("NULL") + } + + return psql.Quote("resident", "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 ResidentSlice) copyMatchingRows(from ...*Resident) { + for i, old := range o { + for _, new := range from { + if new.ID != old.ID { + continue + } + new.R = old.R + o[i] = new + break + } + } +} + +// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" +func (o ResidentSlice) 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 Residents.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 *Resident: + o.copyMatchingRows(retrieved) + case []*Resident: + o.copyMatchingRows(retrieved...) + case ResidentSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a Resident or a slice of Resident + // then run the AfterUpdateHooks on the slice + _, err = Residents.AfterUpdateHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" +func (o ResidentSlice) 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 Residents.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 *Resident: + o.copyMatchingRows(retrieved) + case []*Resident: + o.copyMatchingRows(retrieved...) + case ResidentSlice: + o.copyMatchingRows(retrieved...) + default: + // If the retrieved value is not a Resident or a slice of Resident + // then run the AfterDeleteHooks on the slice + _, err = Residents.AfterDeleteHooks.RunHooks(ctx, exec, o) + } + + return err + })) + + q.AppendWhere(o.pkIN()) + }) +} + +func (o ResidentSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ResidentSetter) error { + if len(o) == 0 { + return nil + } + + _, err := Residents.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) + return err +} + +func (o ResidentSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + _, err := Residents.Delete(o.DeleteMod()).Exec(ctx, exec) + return err +} + +func (o ResidentSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { + if len(o) == 0 { + return nil + } + + o2, err := Residents.Query(sm.Where(o.pkIN())).All(ctx, exec) + if err != nil { + return err + } + + o.copyMatchingRows(o2...) + + return nil +} + +// Address starts a query for related objects on address +func (o *Resident) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery { + return Addresses.Query(append(mods, + sm.Where(Addresses.Columns.ID.EQ(psql.Arg(o.AddressID))), + )...) +} + +func (os ResidentSlice) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery { + pkAddressID := make(pgtypes.Array[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)), + )...) +} + +// CreatorUser starts a query for related objects on user_ +func (o *Resident) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + return Users.Query(append(mods, + sm.Where(Users.Columns.ID.EQ(psql.Arg(o.Creator))), + )...) +} + +func (os ResidentSlice) CreatorUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { + pkCreator := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkCreator = append(pkCreator, o.Creator) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkCreator), "integer[]")), + )) + + return Users.Query(append(mods, + sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +// PhoneMobilePhone starts a query for related objects on comms.phone +func (o *Resident) PhoneMobilePhone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery { + return CommsPhones.Query(append(mods, + sm.Where(CommsPhones.Columns.E164.EQ(psql.Arg(o.PhoneMobile))), + )...) +} + +func (os ResidentSlice) PhoneMobilePhone(mods ...bob.Mod[*dialect.SelectQuery]) CommsPhonesQuery { + pkPhoneMobile := make(pgtypes.Array[null.Val[string]], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkPhoneMobile = append(pkPhoneMobile, o.PhoneMobile) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkPhoneMobile), "text[]")), + )) + + return CommsPhones.Query(append(mods, + sm.Where(psql.Group(CommsPhones.Columns.E164).OP("IN", PKArgExpr)), + )...) +} + +// Site starts a query for related objects on site +func (o *Resident) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + return Sites.Query(append(mods, + sm.Where(Sites.Columns.ID.EQ(psql.Arg(o.SiteID))), sm.Where(Sites.Columns.Version.EQ(psql.Arg(o.SiteVersion))), + )...) +} + +func (os ResidentSlice) Site(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { + pkSiteID := make(pgtypes.Array[int32], 0, len(os)) + + pkSiteVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkSiteID = append(pkSiteID, o.SiteID) + pkSiteVersion = append(pkSiteVersion, o.SiteVersion) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkSiteID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkSiteVersion), "integer[]")), + )) + + return Sites.Query(append(mods, + sm.Where(psql.Group(Sites.Columns.ID, Sites.Columns.Version).OP("IN", PKArgExpr)), + )...) +} + +func attachResidentAddress0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, address1 *Address) (*Resident, error) { + setter := &ResidentSetter{ + AddressID: omit.From(address1.ID), + } + + err := resident0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachResidentAddress0: %w", err) + } + + return resident0, nil +} + +func (resident0 *Resident) 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 = attachResidentAddress0(ctx, exec, 1, resident0, address1) + if err != nil { + return err + } + + resident0.R.Address = address1 + + address1.R.Residents = append(address1.R.Residents, resident0) + + return nil +} + +func (resident0 *Resident) AttachAddress(ctx context.Context, exec bob.Executor, address1 *Address) error { + var err error + + _, err = attachResidentAddress0(ctx, exec, 1, resident0, address1) + if err != nil { + return err + } + + resident0.R.Address = address1 + + address1.R.Residents = append(address1.R.Residents, resident0) + + return nil +} + +func attachResidentCreatorUser0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, user1 *User) (*Resident, error) { + setter := &ResidentSetter{ + Creator: omit.From(user1.ID), + } + + err := resident0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachResidentCreatorUser0: %w", err) + } + + return resident0, nil +} + +func (resident0 *Resident) InsertCreatorUser(ctx context.Context, exec bob.Executor, related *UserSetter) error { + var err error + + user1, err := Users.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachResidentCreatorUser0(ctx, exec, 1, resident0, user1) + if err != nil { + return err + } + + resident0.R.CreatorUser = user1 + + user1.R.CreatorResidents = append(user1.R.CreatorResidents, resident0) + + return nil +} + +func (resident0 *Resident) AttachCreatorUser(ctx context.Context, exec bob.Executor, user1 *User) error { + var err error + + _, err = attachResidentCreatorUser0(ctx, exec, 1, resident0, user1) + if err != nil { + return err + } + + resident0.R.CreatorUser = user1 + + user1.R.CreatorResidents = append(user1.R.CreatorResidents, resident0) + + return nil +} + +func attachResidentPhoneMobilePhone0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, commsPhone1 *CommsPhone) (*Resident, error) { + setter := &ResidentSetter{ + PhoneMobile: omitnull.From(commsPhone1.E164), + } + + err := resident0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachResidentPhoneMobilePhone0: %w", err) + } + + return resident0, nil +} + +func (resident0 *Resident) InsertPhoneMobilePhone(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 = attachResidentPhoneMobilePhone0(ctx, exec, 1, resident0, commsPhone1) + if err != nil { + return err + } + + resident0.R.PhoneMobilePhone = commsPhone1 + + commsPhone1.R.PhoneMobileResidents = append(commsPhone1.R.PhoneMobileResidents, resident0) + + return nil +} + +func (resident0 *Resident) AttachPhoneMobilePhone(ctx context.Context, exec bob.Executor, commsPhone1 *CommsPhone) error { + var err error + + _, err = attachResidentPhoneMobilePhone0(ctx, exec, 1, resident0, commsPhone1) + if err != nil { + return err + } + + resident0.R.PhoneMobilePhone = commsPhone1 + + commsPhone1.R.PhoneMobileResidents = append(commsPhone1.R.PhoneMobileResidents, resident0) + + return nil +} + +func attachResidentSite0(ctx context.Context, exec bob.Executor, count int, resident0 *Resident, site1 *Site) (*Resident, error) { + setter := &ResidentSetter{ + SiteID: omit.From(site1.ID), + SiteVersion: omit.From(site1.Version), + } + + err := resident0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachResidentSite0: %w", err) + } + + return resident0, nil +} + +func (resident0 *Resident) InsertSite(ctx context.Context, exec bob.Executor, related *SiteSetter) error { + var err error + + site1, err := Sites.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachResidentSite0(ctx, exec, 1, resident0, site1) + if err != nil { + return err + } + + resident0.R.Site = site1 + + site1.R.Residents = append(site1.R.Residents, resident0) + + return nil +} + +func (resident0 *Resident) AttachSite(ctx context.Context, exec bob.Executor, site1 *Site) error { + var err error + + _, err = attachResidentSite0(ctx, exec, 1, resident0, site1) + if err != nil { + return err + } + + resident0.R.Site = site1 + + site1.R.Residents = append(site1.R.Residents, resident0) + + return nil +} + +type residentWhere[Q psql.Filterable] struct { + AddressID psql.WhereMod[Q, int32] + Created psql.WhereMod[Q, time.Time] + Creator psql.WhereMod[Q, int32] + ID psql.WhereMod[Q, int32] + Name psql.WhereMod[Q, string] + PhoneMobile psql.WhereNullMod[Q, string] + SiteID psql.WhereMod[Q, int32] + SiteVersion psql.WhereMod[Q, int32] +} + +func (residentWhere[Q]) AliasedAs(alias string) residentWhere[Q] { + return buildResidentWhere[Q](buildResidentColumns(alias)) +} + +func buildResidentWhere[Q psql.Filterable](cols residentColumns) residentWhere[Q] { + return residentWhere[Q]{ + AddressID: psql.Where[Q, int32](cols.AddressID), + Created: psql.Where[Q, time.Time](cols.Created), + Creator: psql.Where[Q, int32](cols.Creator), + ID: psql.Where[Q, int32](cols.ID), + Name: psql.Where[Q, string](cols.Name), + PhoneMobile: psql.WhereNull[Q, string](cols.PhoneMobile), + SiteID: psql.Where[Q, int32](cols.SiteID), + SiteVersion: psql.Where[Q, int32](cols.SiteVersion), + } +} + +func (o *Resident) Preload(name string, retrieved any) error { + if o == nil { + return nil + } + + switch name { + case "Address": + rel, ok := retrieved.(*Address) + if !ok { + return fmt.Errorf("resident cannot load %T as %q", retrieved, name) + } + + o.R.Address = rel + + if rel != nil { + rel.R.Residents = ResidentSlice{o} + } + return nil + case "CreatorUser": + rel, ok := retrieved.(*User) + if !ok { + return fmt.Errorf("resident cannot load %T as %q", retrieved, name) + } + + o.R.CreatorUser = rel + + if rel != nil { + rel.R.CreatorResidents = ResidentSlice{o} + } + return nil + case "PhoneMobilePhone": + rel, ok := retrieved.(*CommsPhone) + if !ok { + return fmt.Errorf("resident cannot load %T as %q", retrieved, name) + } + + o.R.PhoneMobilePhone = rel + + if rel != nil { + rel.R.PhoneMobileResidents = ResidentSlice{o} + } + return nil + case "Site": + rel, ok := retrieved.(*Site) + if !ok { + return fmt.Errorf("resident cannot load %T as %q", retrieved, name) + } + + o.R.Site = rel + + if rel != nil { + rel.R.Residents = ResidentSlice{o} + } + return nil + default: + return fmt.Errorf("resident has no relationship %q", name) + } +} + +type residentPreloader struct { + Address func(...psql.PreloadOption) psql.Preloader + CreatorUser func(...psql.PreloadOption) psql.Preloader + PhoneMobilePhone func(...psql.PreloadOption) psql.Preloader + Site func(...psql.PreloadOption) psql.Preloader +} + +func buildResidentPreloader() residentPreloader { + return residentPreloader{ + Address: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Address, AddressSlice](psql.PreloadRel{ + Name: "Address", + Sides: []psql.PreloadSide{ + { + From: Residents, + To: Addresses, + FromColumns: []string{"address_id"}, + ToColumns: []string{"id"}, + }, + }, + }, Addresses.Columns.Names(), opts...) + }, + CreatorUser: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*User, UserSlice](psql.PreloadRel{ + Name: "CreatorUser", + Sides: []psql.PreloadSide{ + { + From: Residents, + To: Users, + FromColumns: []string{"creator"}, + ToColumns: []string{"id"}, + }, + }, + }, Users.Columns.Names(), opts...) + }, + PhoneMobilePhone: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*CommsPhone, CommsPhoneSlice](psql.PreloadRel{ + Name: "PhoneMobilePhone", + Sides: []psql.PreloadSide{ + { + From: Residents, + To: CommsPhones, + FromColumns: []string{"phone_mobile"}, + ToColumns: []string{"e164"}, + }, + }, + }, CommsPhones.Columns.Names(), opts...) + }, + Site: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Site, SiteSlice](psql.PreloadRel{ + Name: "Site", + Sides: []psql.PreloadSide{ + { + From: Residents, + To: Sites, + FromColumns: []string{"site_id", "site_version"}, + ToColumns: []string{"id", "version"}, + }, + }, + }, Sites.Columns.Names(), opts...) + }, + } +} + +type residentThenLoader[Q orm.Loadable] struct { + Address func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + PhoneMobilePhone func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Site func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildResidentThenLoader[Q orm.Loadable]() residentThenLoader[Q] { + type AddressLoadInterface interface { + LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type CreatorUserLoadInterface interface { + LoadCreatorUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type PhoneMobilePhoneLoadInterface interface { + LoadPhoneMobilePhone(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type SiteLoadInterface interface { + LoadSite(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return residentThenLoader[Q]{ + 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...) + }, + ), + CreatorUser: thenLoadBuilder[Q]( + "CreatorUser", + func(ctx context.Context, exec bob.Executor, retrieved CreatorUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCreatorUser(ctx, exec, mods...) + }, + ), + PhoneMobilePhone: thenLoadBuilder[Q]( + "PhoneMobilePhone", + func(ctx context.Context, exec bob.Executor, retrieved PhoneMobilePhoneLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadPhoneMobilePhone(ctx, exec, mods...) + }, + ), + Site: thenLoadBuilder[Q]( + "Site", + func(ctx context.Context, exec bob.Executor, retrieved SiteLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadSite(ctx, exec, mods...) + }, + ), + } +} + +// LoadAddress loads the resident's Address into the .R struct +func (o *Resident) 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.Residents = ResidentSlice{o} + + o.R.Address = related + return nil +} + +// LoadAddress loads the resident's Address into the .R struct +func (os ResidentSlice) 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 == rel.ID) { + continue + } + + rel.R.Residents = append(rel.R.Residents, o) + + o.R.Address = rel + break + } + } + + return nil +} + +// LoadCreatorUser loads the resident's CreatorUser into the .R struct +func (o *Resident) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.CreatorUser = nil + + related, err := o.CreatorUser(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.CreatorResidents = ResidentSlice{o} + + o.R.CreatorUser = related + return nil +} + +// LoadCreatorUser loads the resident's CreatorUser into the .R struct +func (os ResidentSlice) LoadCreatorUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + users, err := os.CreatorUser(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range users { + + if !(o.Creator == rel.ID) { + continue + } + + rel.R.CreatorResidents = append(rel.R.CreatorResidents, o) + + o.R.CreatorUser = rel + break + } + } + + return nil +} + +// LoadPhoneMobilePhone loads the resident's PhoneMobilePhone into the .R struct +func (o *Resident) LoadPhoneMobilePhone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.PhoneMobilePhone = nil + + related, err := o.PhoneMobilePhone(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.PhoneMobileResidents = ResidentSlice{o} + + o.R.PhoneMobilePhone = related + return nil +} + +// LoadPhoneMobilePhone loads the resident's PhoneMobilePhone into the .R struct +func (os ResidentSlice) LoadPhoneMobilePhone(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + commsPhones, err := os.PhoneMobilePhone(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range commsPhones { + if !o.PhoneMobile.IsValue() { + continue + } + + if !(o.PhoneMobile.IsValue() && o.PhoneMobile.MustGet() == rel.E164) { + continue + } + + rel.R.PhoneMobileResidents = append(rel.R.PhoneMobileResidents, o) + + o.R.PhoneMobilePhone = rel + break + } + } + + return nil +} + +// LoadSite loads the resident's Site into the .R struct +func (o *Resident) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Site = nil + + related, err := o.Site(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.Residents = ResidentSlice{o} + + o.R.Site = related + return nil +} + +// LoadSite loads the resident's Site into the .R struct +func (os ResidentSlice) LoadSite(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + sites, err := os.Site(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range sites { + + if !(o.SiteID == rel.ID) { + continue + } + + if !(o.SiteVersion == rel.Version) { + continue + } + + rel.R.Residents = append(rel.R.Residents, o) + + o.R.Site = rel + break + } + } + + return nil +} + +type residentJoins[Q dialect.Joinable] struct { + typ string + Address modAs[Q, addressColumns] + CreatorUser modAs[Q, userColumns] + PhoneMobilePhone modAs[Q, commsPhoneColumns] + Site modAs[Q, siteColumns] +} + +func (j residentJoins[Q]) aliasedAs(alias string) residentJoins[Q] { + return buildResidentJoins[Q](buildResidentColumns(alias), j.typ) +} + +func buildResidentJoins[Q dialect.Joinable](cols residentColumns, typ string) residentJoins[Q] { + return residentJoins[Q]{ + typ: typ, + Address: modAs[Q, addressColumns]{ + c: Addresses.Columns, + f: func(to addressColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Addresses.Name().As(to.Alias())).On( + to.ID.EQ(cols.AddressID), + )) + } + + return mods + }, + }, + CreatorUser: modAs[Q, userColumns]{ + c: Users.Columns, + f: func(to userColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Users.Name().As(to.Alias())).On( + to.ID.EQ(cols.Creator), + )) + } + + return mods + }, + }, + PhoneMobilePhone: modAs[Q, commsPhoneColumns]{ + c: CommsPhones.Columns, + f: func(to commsPhoneColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, CommsPhones.Name().As(to.Alias())).On( + to.E164.EQ(cols.PhoneMobile), + )) + } + + return mods + }, + }, + Site: modAs[Q, siteColumns]{ + c: Sites.Columns, + f: func(to siteColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Sites.Name().As(to.Alias())).On( + to.ID.EQ(cols.SiteID), to.Version.EQ(cols.SiteVersion), + )) + } + + return mods + }, + }, + } +} diff --git a/db/models/site.bob.go b/db/models/site.bob.go index 5651ec7b..fe08a033 100644 --- a/db/models/site.bob.go +++ b/db/models/site.bob.go @@ -26,21 +26,23 @@ import ( // Site is an object representing the database table. type Site struct { - AddressID int32 `db:"address_id" ` - Created time.Time `db:"created" ` - CreatorID int32 `db:"creator_id" ` - FileID null.Val[int32] `db:"file_id" ` - ID int32 `db:"id,pk" ` - Notes string `db:"notes" ` - OrganizationID int32 `db:"organization_id" ` - OwnerName string `db:"owner_name" ` - OwnerPhoneE164 null.Val[string] `db:"owner_phone_e164" ` - ResidentOwned null.Val[bool] `db:"resident_owned" ` - ResidentPhoneE164 null.Val[string] `db:"resident_phone_e164" ` - Tags pgtypes.HStore `db:"tags" ` - Version int32 `db:"version,pk" ` + AddressID int32 `db:"address_id" ` + Created time.Time `db:"created" ` + CreatorID int32 `db:"creator_id" ` + FileID null.Val[int32] `db:"file_id" ` + ID int32 `db:"id,pk" ` + Notes string `db:"notes" ` + OrganizationID int32 `db:"organization_id" ` + OwnerName string `db:"owner_name" ` + OwnerPhoneE164 null.Val[string] `db:"owner_phone_e164" ` + ParcelID int32 `db:"parcel_id" ` + ResidentOwned null.Val[bool] `db:"resident_owned" ` + Tags pgtypes.HStore `db:"tags" ` + Version int32 `db:"version,pk" ` R siteR `db:"-" ` + + C siteC `db:"-" ` } // SiteSlice is an alias for a slice of pointers to Site. @@ -55,49 +57,53 @@ type SitesQuery = *psql.ViewQuery[*Site, SiteSlice] // siteR is where relationships are stored. type siteR struct { - Address *Address // site.site_address_id_fkey - CreatorUser *User // site.site_creator_id_fkey - File *FileuploadFile // site.site_file_id_fkey + ComplianceReportRequests ComplianceReportRequestSlice // compliance_report_request.compliance_report_request_site_id_site_version_fkey + Pools PoolSlice // pool.pool_site_id_site_version_fkey + Residents ResidentSlice // resident.resident_site_id_site_version_fkey + Address *Address // site.site_address_id_fkey + CreatorUser *User // site.site_creator_id_fkey + File *FileuploadFile // site.site_file_id_fkey + Parcel *Parcel // site.site_parcel_id_fkey } func buildSiteColumns(alias string) siteColumns { return siteColumns{ ColumnsExpr: expr.NewColumnsExpr( - "address_id", "created", "creator_id", "file_id", "id", "notes", "organization_id", "owner_name", "owner_phone_e164", "resident_owned", "resident_phone_e164", "tags", "version", + "address_id", "created", "creator_id", "file_id", "id", "notes", "organization_id", "owner_name", "owner_phone_e164", "parcel_id", "resident_owned", "tags", "version", ).WithParent("site"), - tableAlias: alias, - AddressID: psql.Quote(alias, "address_id"), - Created: psql.Quote(alias, "created"), - CreatorID: psql.Quote(alias, "creator_id"), - FileID: psql.Quote(alias, "file_id"), - ID: psql.Quote(alias, "id"), - Notes: psql.Quote(alias, "notes"), - OrganizationID: psql.Quote(alias, "organization_id"), - OwnerName: psql.Quote(alias, "owner_name"), - OwnerPhoneE164: psql.Quote(alias, "owner_phone_e164"), - ResidentOwned: psql.Quote(alias, "resident_owned"), - ResidentPhoneE164: psql.Quote(alias, "resident_phone_e164"), - Tags: psql.Quote(alias, "tags"), - Version: psql.Quote(alias, "version"), + tableAlias: alias, + AddressID: psql.Quote(alias, "address_id"), + Created: psql.Quote(alias, "created"), + CreatorID: psql.Quote(alias, "creator_id"), + FileID: psql.Quote(alias, "file_id"), + ID: psql.Quote(alias, "id"), + Notes: psql.Quote(alias, "notes"), + OrganizationID: psql.Quote(alias, "organization_id"), + OwnerName: psql.Quote(alias, "owner_name"), + OwnerPhoneE164: psql.Quote(alias, "owner_phone_e164"), + ParcelID: psql.Quote(alias, "parcel_id"), + ResidentOwned: psql.Quote(alias, "resident_owned"), + Tags: psql.Quote(alias, "tags"), + Version: psql.Quote(alias, "version"), } } type siteColumns struct { expr.ColumnsExpr - tableAlias string - AddressID psql.Expression - Created psql.Expression - CreatorID psql.Expression - FileID psql.Expression - ID psql.Expression - Notes psql.Expression - OrganizationID psql.Expression - OwnerName psql.Expression - OwnerPhoneE164 psql.Expression - ResidentOwned psql.Expression - ResidentPhoneE164 psql.Expression - Tags psql.Expression - Version psql.Expression + tableAlias string + AddressID psql.Expression + Created psql.Expression + CreatorID psql.Expression + FileID psql.Expression + ID psql.Expression + Notes psql.Expression + OrganizationID psql.Expression + OwnerName psql.Expression + OwnerPhoneE164 psql.Expression + ParcelID psql.Expression + ResidentOwned psql.Expression + Tags psql.Expression + Version psql.Expression } func (c siteColumns) Alias() string { @@ -112,19 +118,19 @@ func (siteColumns) AliasedAs(alias string) siteColumns { // All values are optional, and do not have to be set // Generated columns are not included type SiteSetter struct { - AddressID omit.Val[int32] `db:"address_id" ` - Created omit.Val[time.Time] `db:"created" ` - CreatorID omit.Val[int32] `db:"creator_id" ` - FileID omitnull.Val[int32] `db:"file_id" ` - ID omit.Val[int32] `db:"id,pk" ` - Notes omit.Val[string] `db:"notes" ` - OrganizationID omit.Val[int32] `db:"organization_id" ` - OwnerName omit.Val[string] `db:"owner_name" ` - OwnerPhoneE164 omitnull.Val[string] `db:"owner_phone_e164" ` - ResidentOwned omitnull.Val[bool] `db:"resident_owned" ` - ResidentPhoneE164 omitnull.Val[string] `db:"resident_phone_e164" ` - Tags omit.Val[pgtypes.HStore] `db:"tags" ` - Version omit.Val[int32] `db:"version,pk" ` + AddressID omit.Val[int32] `db:"address_id" ` + Created omit.Val[time.Time] `db:"created" ` + CreatorID omit.Val[int32] `db:"creator_id" ` + FileID omitnull.Val[int32] `db:"file_id" ` + ID omit.Val[int32] `db:"id,pk" ` + Notes omit.Val[string] `db:"notes" ` + OrganizationID omit.Val[int32] `db:"organization_id" ` + OwnerName omit.Val[string] `db:"owner_name" ` + OwnerPhoneE164 omitnull.Val[string] `db:"owner_phone_e164" ` + ParcelID omit.Val[int32] `db:"parcel_id" ` + ResidentOwned omitnull.Val[bool] `db:"resident_owned" ` + Tags omit.Val[pgtypes.HStore] `db:"tags" ` + Version omit.Val[int32] `db:"version,pk" ` } func (s SiteSetter) SetColumns() []string { @@ -156,12 +162,12 @@ func (s SiteSetter) SetColumns() []string { if !s.OwnerPhoneE164.IsUnset() { vals = append(vals, "owner_phone_e164") } + if s.ParcelID.IsValue() { + vals = append(vals, "parcel_id") + } if !s.ResidentOwned.IsUnset() { vals = append(vals, "resident_owned") } - if !s.ResidentPhoneE164.IsUnset() { - vals = append(vals, "resident_phone_e164") - } if s.Tags.IsValue() { vals = append(vals, "tags") } @@ -199,12 +205,12 @@ func (s SiteSetter) Overwrite(t *Site) { if !s.OwnerPhoneE164.IsUnset() { t.OwnerPhoneE164 = s.OwnerPhoneE164.MustGetNull() } + if s.ParcelID.IsValue() { + t.ParcelID = s.ParcelID.MustGet() + } if !s.ResidentOwned.IsUnset() { t.ResidentOwned = s.ResidentOwned.MustGetNull() } - if !s.ResidentPhoneE164.IsUnset() { - t.ResidentPhoneE164 = s.ResidentPhoneE164.MustGetNull() - } if s.Tags.IsValue() { t.Tags = s.Tags.MustGet() } @@ -274,14 +280,14 @@ func (s *SiteSetter) Apply(q *dialect.InsertQuery) { vals[8] = psql.Raw("DEFAULT") } - if !s.ResidentOwned.IsUnset() { - vals[9] = psql.Arg(s.ResidentOwned.MustGetNull()) + if s.ParcelID.IsValue() { + vals[9] = psql.Arg(s.ParcelID.MustGet()) } else { vals[9] = psql.Raw("DEFAULT") } - if !s.ResidentPhoneE164.IsUnset() { - vals[10] = psql.Arg(s.ResidentPhoneE164.MustGetNull()) + if !s.ResidentOwned.IsUnset() { + vals[10] = psql.Arg(s.ResidentOwned.MustGetNull()) } else { vals[10] = psql.Raw("DEFAULT") } @@ -372,6 +378,13 @@ func (s SiteSetter) Expressions(prefix ...string) []bob.Expression { }}) } + if s.ParcelID.IsValue() { + exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ + psql.Quote(append(prefix, "parcel_id")...), + psql.Arg(s.ParcelID), + }}) + } + if !s.ResidentOwned.IsUnset() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "resident_owned")...), @@ -379,13 +392,6 @@ func (s SiteSetter) Expressions(prefix ...string) []bob.Expression { }}) } - if !s.ResidentPhoneE164.IsUnset() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "resident_phone_e164")...), - psql.Arg(s.ResidentPhoneE164), - }}) - } - if s.Tags.IsValue() { exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ psql.Quote(append(prefix, "tags")...), @@ -636,6 +642,90 @@ func (o SiteSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { return nil } +// ComplianceReportRequests starts a query for related objects on compliance_report_request +func (o *Site) ComplianceReportRequests(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery { + return ComplianceReportRequests.Query(append(mods, + sm.Where(ComplianceReportRequests.Columns.SiteID.EQ(psql.Arg(o.ID))), sm.Where(ComplianceReportRequests.Columns.SiteVersion.EQ(psql.Arg(o.Version))), + )...) +} + +func (os SiteSlice) ComplianceReportRequests(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery { + pkID := make(pgtypes.Array[int32], 0, len(os)) + + pkVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkID = append(pkID, o.ID) + pkVersion = append(pkVersion, o.Version) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkVersion), "integer[]")), + )) + + return ComplianceReportRequests.Query(append(mods, + sm.Where(psql.Group(ComplianceReportRequests.Columns.SiteID, ComplianceReportRequests.Columns.SiteVersion).OP("IN", PKArgExpr)), + )...) +} + +// Pools starts a query for related objects on pool +func (o *Site) Pools(mods ...bob.Mod[*dialect.SelectQuery]) PoolsQuery { + return Pools.Query(append(mods, + sm.Where(Pools.Columns.SiteID.EQ(psql.Arg(o.ID))), sm.Where(Pools.Columns.SiteVersion.EQ(psql.Arg(o.Version))), + )...) +} + +func (os SiteSlice) Pools(mods ...bob.Mod[*dialect.SelectQuery]) PoolsQuery { + pkID := make(pgtypes.Array[int32], 0, len(os)) + + pkVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkID = append(pkID, o.ID) + pkVersion = append(pkVersion, o.Version) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkVersion), "integer[]")), + )) + + return Pools.Query(append(mods, + sm.Where(psql.Group(Pools.Columns.SiteID, Pools.Columns.SiteVersion).OP("IN", PKArgExpr)), + )...) +} + +// Residents starts a query for related objects on resident +func (o *Site) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + return Residents.Query(append(mods, + sm.Where(Residents.Columns.SiteID.EQ(psql.Arg(o.ID))), sm.Where(Residents.Columns.SiteVersion.EQ(psql.Arg(o.Version))), + )...) +} + +func (os SiteSlice) Residents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + pkID := make(pgtypes.Array[int32], 0, len(os)) + + pkVersion := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkID = append(pkID, o.ID) + pkVersion = append(pkVersion, o.Version) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkID), "integer[]")), + psql.F("unnest", psql.Cast(psql.Arg(pkVersion), "integer[]")), + )) + + return Residents.Query(append(mods, + sm.Where(psql.Group(Residents.Columns.SiteID, Residents.Columns.SiteVersion).OP("IN", PKArgExpr)), + )...) +} + // Address starts a query for related objects on address func (o *Site) Address(mods ...bob.Mod[*dialect.SelectQuery]) AddressesQuery { return Addresses.Query(append(mods, @@ -708,6 +798,240 @@ func (os SiteSlice) File(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadFilesQ )...) } +// Parcel starts a query for related objects on parcel +func (o *Site) Parcel(mods ...bob.Mod[*dialect.SelectQuery]) ParcelsQuery { + return Parcels.Query(append(mods, + sm.Where(Parcels.Columns.ID.EQ(psql.Arg(o.ParcelID))), + )...) +} + +func (os SiteSlice) Parcel(mods ...bob.Mod[*dialect.SelectQuery]) ParcelsQuery { + pkParcelID := make(pgtypes.Array[int32], 0, len(os)) + for _, o := range os { + if o == nil { + continue + } + pkParcelID = append(pkParcelID, o.ParcelID) + } + PKArgExpr := psql.Select(sm.Columns( + psql.F("unnest", psql.Cast(psql.Arg(pkParcelID), "integer[]")), + )) + + return Parcels.Query(append(mods, + sm.Where(psql.Group(Parcels.Columns.ID).OP("IN", PKArgExpr)), + )...) +} + +func insertSiteComplianceReportRequests0(ctx context.Context, exec bob.Executor, complianceReportRequests1 []*ComplianceReportRequestSetter, site0 *Site) (ComplianceReportRequestSlice, error) { + for i := range complianceReportRequests1 { + complianceReportRequests1[i].SiteID = omit.From(site0.ID) + complianceReportRequests1[i].SiteVersion = omit.From(site0.Version) + } + + ret, err := ComplianceReportRequests.Insert(bob.ToMods(complianceReportRequests1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertSiteComplianceReportRequests0: %w", err) + } + + return ret, nil +} + +func attachSiteComplianceReportRequests0(ctx context.Context, exec bob.Executor, count int, complianceReportRequests1 ComplianceReportRequestSlice, site0 *Site) (ComplianceReportRequestSlice, error) { + setter := &ComplianceReportRequestSetter{ + SiteID: omit.From(site0.ID), + SiteVersion: omit.From(site0.Version), + } + + err := complianceReportRequests1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachSiteComplianceReportRequests0: %w", err) + } + + return complianceReportRequests1, nil +} + +func (site0 *Site) InsertComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + complianceReportRequests1, err := insertSiteComplianceReportRequests0(ctx, exec, related, site0) + if err != nil { + return err + } + + site0.R.ComplianceReportRequests = append(site0.R.ComplianceReportRequests, complianceReportRequests1...) + + for _, rel := range complianceReportRequests1 { + rel.R.Site = site0 + } + return nil +} + +func (site0 *Site) AttachComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequest) error { + if len(related) == 0 { + return nil + } + + var err error + complianceReportRequests1 := ComplianceReportRequestSlice(related) + + _, err = attachSiteComplianceReportRequests0(ctx, exec, len(related), complianceReportRequests1, site0) + if err != nil { + return err + } + + site0.R.ComplianceReportRequests = append(site0.R.ComplianceReportRequests, complianceReportRequests1...) + + for _, rel := range related { + rel.R.Site = site0 + } + + return nil +} + +func insertSitePools0(ctx context.Context, exec bob.Executor, pools1 []*PoolSetter, site0 *Site) (PoolSlice, error) { + for i := range pools1 { + pools1[i].SiteID = omit.From(site0.ID) + pools1[i].SiteVersion = omit.From(site0.Version) + } + + ret, err := Pools.Insert(bob.ToMods(pools1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertSitePools0: %w", err) + } + + return ret, nil +} + +func attachSitePools0(ctx context.Context, exec bob.Executor, count int, pools1 PoolSlice, site0 *Site) (PoolSlice, error) { + setter := &PoolSetter{ + SiteID: omit.From(site0.ID), + SiteVersion: omit.From(site0.Version), + } + + err := pools1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachSitePools0: %w", err) + } + + return pools1, nil +} + +func (site0 *Site) InsertPools(ctx context.Context, exec bob.Executor, related ...*PoolSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + pools1, err := insertSitePools0(ctx, exec, related, site0) + if err != nil { + return err + } + + site0.R.Pools = append(site0.R.Pools, pools1...) + + for _, rel := range pools1 { + rel.R.Site = site0 + } + return nil +} + +func (site0 *Site) AttachPools(ctx context.Context, exec bob.Executor, related ...*Pool) error { + if len(related) == 0 { + return nil + } + + var err error + pools1 := PoolSlice(related) + + _, err = attachSitePools0(ctx, exec, len(related), pools1, site0) + if err != nil { + return err + } + + site0.R.Pools = append(site0.R.Pools, pools1...) + + for _, rel := range related { + rel.R.Site = site0 + } + + return nil +} + +func insertSiteResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, site0 *Site) (ResidentSlice, error) { + for i := range residents1 { + residents1[i].SiteID = omit.From(site0.ID) + residents1[i].SiteVersion = omit.From(site0.Version) + } + + ret, err := Residents.Insert(bob.ToMods(residents1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertSiteResidents0: %w", err) + } + + return ret, nil +} + +func attachSiteResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, site0 *Site) (ResidentSlice, error) { + setter := &ResidentSetter{ + SiteID: omit.From(site0.ID), + SiteVersion: omit.From(site0.Version), + } + + err := residents1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachSiteResidents0: %w", err) + } + + return residents1, nil +} + +func (site0 *Site) InsertResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + residents1, err := insertSiteResidents0(ctx, exec, related, site0) + if err != nil { + return err + } + + site0.R.Residents = append(site0.R.Residents, residents1...) + + for _, rel := range residents1 { + rel.R.Site = site0 + } + return nil +} + +func (site0 *Site) AttachResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error { + if len(related) == 0 { + return nil + } + + var err error + residents1 := ResidentSlice(related) + + _, err = attachSiteResidents0(ctx, exec, len(related), residents1, site0) + if err != nil { + return err + } + + site0.R.Residents = append(site0.R.Residents, residents1...) + + for _, rel := range related { + rel.R.Site = site0 + } + + return nil +} + func attachSiteAddress0(ctx context.Context, exec bob.Executor, count int, site0 *Site, address1 *Address) (*Site, error) { setter := &SiteSetter{ AddressID: omit.From(address1.ID), @@ -852,20 +1176,68 @@ func (site0 *Site) AttachFile(ctx context.Context, exec bob.Executor, fileupload return nil } +func attachSiteParcel0(ctx context.Context, exec bob.Executor, count int, site0 *Site, parcel1 *Parcel) (*Site, error) { + setter := &SiteSetter{ + ParcelID: omit.From(parcel1.ID), + } + + err := site0.Update(ctx, exec, setter) + if err != nil { + return nil, fmt.Errorf("attachSiteParcel0: %w", err) + } + + return site0, nil +} + +func (site0 *Site) InsertParcel(ctx context.Context, exec bob.Executor, related *ParcelSetter) error { + var err error + + parcel1, err := Parcels.Insert(related).One(ctx, exec) + if err != nil { + return fmt.Errorf("inserting related objects: %w", err) + } + + _, err = attachSiteParcel0(ctx, exec, 1, site0, parcel1) + if err != nil { + return err + } + + site0.R.Parcel = parcel1 + + parcel1.R.Sites = append(parcel1.R.Sites, site0) + + return nil +} + +func (site0 *Site) AttachParcel(ctx context.Context, exec bob.Executor, parcel1 *Parcel) error { + var err error + + _, err = attachSiteParcel0(ctx, exec, 1, site0, parcel1) + if err != nil { + return err + } + + site0.R.Parcel = parcel1 + + parcel1.R.Sites = append(parcel1.R.Sites, site0) + + return nil +} + type siteWhere[Q psql.Filterable] struct { - AddressID psql.WhereMod[Q, int32] - Created psql.WhereMod[Q, time.Time] - CreatorID psql.WhereMod[Q, int32] - FileID psql.WhereNullMod[Q, int32] - ID psql.WhereMod[Q, int32] - Notes psql.WhereMod[Q, string] - OrganizationID psql.WhereMod[Q, int32] - OwnerName psql.WhereMod[Q, string] - OwnerPhoneE164 psql.WhereNullMod[Q, string] - ResidentOwned psql.WhereNullMod[Q, bool] - ResidentPhoneE164 psql.WhereNullMod[Q, string] - Tags psql.WhereMod[Q, pgtypes.HStore] - Version psql.WhereMod[Q, int32] + AddressID psql.WhereMod[Q, int32] + Created psql.WhereMod[Q, time.Time] + CreatorID psql.WhereMod[Q, int32] + FileID psql.WhereNullMod[Q, int32] + ID psql.WhereMod[Q, int32] + Notes psql.WhereMod[Q, string] + OrganizationID psql.WhereMod[Q, int32] + OwnerName psql.WhereMod[Q, string] + OwnerPhoneE164 psql.WhereNullMod[Q, string] + ParcelID psql.WhereMod[Q, int32] + ResidentOwned psql.WhereNullMod[Q, bool] + Tags psql.WhereMod[Q, pgtypes.HStore] + Version psql.WhereMod[Q, int32] } func (siteWhere[Q]) AliasedAs(alias string) siteWhere[Q] { @@ -874,19 +1246,19 @@ func (siteWhere[Q]) AliasedAs(alias string) siteWhere[Q] { func buildSiteWhere[Q psql.Filterable](cols siteColumns) siteWhere[Q] { return siteWhere[Q]{ - AddressID: psql.Where[Q, int32](cols.AddressID), - Created: psql.Where[Q, time.Time](cols.Created), - CreatorID: psql.Where[Q, int32](cols.CreatorID), - FileID: psql.WhereNull[Q, int32](cols.FileID), - ID: psql.Where[Q, int32](cols.ID), - Notes: psql.Where[Q, string](cols.Notes), - OrganizationID: psql.Where[Q, int32](cols.OrganizationID), - OwnerName: psql.Where[Q, string](cols.OwnerName), - OwnerPhoneE164: psql.WhereNull[Q, string](cols.OwnerPhoneE164), - ResidentOwned: psql.WhereNull[Q, bool](cols.ResidentOwned), - ResidentPhoneE164: psql.WhereNull[Q, string](cols.ResidentPhoneE164), - Tags: psql.Where[Q, pgtypes.HStore](cols.Tags), - Version: psql.Where[Q, int32](cols.Version), + AddressID: psql.Where[Q, int32](cols.AddressID), + Created: psql.Where[Q, time.Time](cols.Created), + CreatorID: psql.Where[Q, int32](cols.CreatorID), + FileID: psql.WhereNull[Q, int32](cols.FileID), + ID: psql.Where[Q, int32](cols.ID), + Notes: psql.Where[Q, string](cols.Notes), + OrganizationID: psql.Where[Q, int32](cols.OrganizationID), + OwnerName: psql.Where[Q, string](cols.OwnerName), + OwnerPhoneE164: psql.WhereNull[Q, string](cols.OwnerPhoneE164), + ParcelID: psql.Where[Q, int32](cols.ParcelID), + ResidentOwned: psql.WhereNull[Q, bool](cols.ResidentOwned), + Tags: psql.Where[Q, pgtypes.HStore](cols.Tags), + Version: psql.Where[Q, int32](cols.Version), } } @@ -896,6 +1268,48 @@ func (o *Site) Preload(name string, retrieved any) error { } switch name { + case "ComplianceReportRequests": + rels, ok := retrieved.(ComplianceReportRequestSlice) + if !ok { + return fmt.Errorf("site cannot load %T as %q", retrieved, name) + } + + o.R.ComplianceReportRequests = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Site = o + } + } + return nil + case "Pools": + rels, ok := retrieved.(PoolSlice) + if !ok { + return fmt.Errorf("site cannot load %T as %q", retrieved, name) + } + + o.R.Pools = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Site = o + } + } + return nil + case "Residents": + rels, ok := retrieved.(ResidentSlice) + if !ok { + return fmt.Errorf("site cannot load %T as %q", retrieved, name) + } + + o.R.Residents = rels + + for _, rel := range rels { + if rel != nil { + rel.R.Site = o + } + } + return nil case "Address": rel, ok := retrieved.(*Address) if !ok { @@ -928,6 +1342,18 @@ func (o *Site) Preload(name string, retrieved any) error { o.R.File = rel + if rel != nil { + rel.R.Sites = SiteSlice{o} + } + return nil + case "Parcel": + rel, ok := retrieved.(*Parcel) + if !ok { + return fmt.Errorf("site cannot load %T as %q", retrieved, name) + } + + o.R.Parcel = rel + if rel != nil { rel.R.Sites = SiteSlice{o} } @@ -941,6 +1367,7 @@ type sitePreloader struct { Address func(...psql.PreloadOption) psql.Preloader CreatorUser func(...psql.PreloadOption) psql.Preloader File func(...psql.PreloadOption) psql.Preloader + Parcel func(...psql.PreloadOption) psql.Preloader } func buildSitePreloader() sitePreloader { @@ -984,16 +1411,42 @@ func buildSitePreloader() sitePreloader { }, }, FileuploadFiles.Columns.Names(), opts...) }, + Parcel: func(opts ...psql.PreloadOption) psql.Preloader { + return psql.Preload[*Parcel, ParcelSlice](psql.PreloadRel{ + Name: "Parcel", + Sides: []psql.PreloadSide{ + { + From: Sites, + To: Parcels, + FromColumns: []string{"parcel_id"}, + ToColumns: []string{"id"}, + }, + }, + }, Parcels.Columns.Names(), opts...) + }, } } type siteThenLoader[Q orm.Loadable] struct { - Address func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - File func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Residents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Address func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + File func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Parcel func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildSiteThenLoader[Q orm.Loadable]() siteThenLoader[Q] { + type ComplianceReportRequestsLoadInterface interface { + LoadComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type PoolsLoadInterface interface { + LoadPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ResidentsLoadInterface interface { + LoadResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type AddressLoadInterface interface { LoadAddress(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -1003,8 +1456,29 @@ func buildSiteThenLoader[Q orm.Loadable]() siteThenLoader[Q] { type FileLoadInterface interface { LoadFile(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type ParcelLoadInterface interface { + LoadParcel(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } return siteThenLoader[Q]{ + ComplianceReportRequests: thenLoadBuilder[Q]( + "ComplianceReportRequests", + func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadComplianceReportRequests(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...) + }, + ), + Residents: thenLoadBuilder[Q]( + "Residents", + func(ctx context.Context, exec bob.Executor, retrieved ResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadResidents(ctx, exec, mods...) + }, + ), Address: thenLoadBuilder[Q]( "Address", func(ctx context.Context, exec bob.Executor, retrieved AddressLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -1023,9 +1497,210 @@ func buildSiteThenLoader[Q orm.Loadable]() siteThenLoader[Q] { return retrieved.LoadFile(ctx, exec, mods...) }, ), + Parcel: thenLoadBuilder[Q]( + "Parcel", + func(ctx context.Context, exec bob.Executor, retrieved ParcelLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadParcel(ctx, exec, mods...) + }, + ), } } +// LoadComplianceReportRequests loads the site's ComplianceReportRequests into the .R struct +func (o *Site) LoadComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.ComplianceReportRequests = nil + + related, err := o.ComplianceReportRequests(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Site = o + } + + o.R.ComplianceReportRequests = related + return nil +} + +// LoadComplianceReportRequests loads the site's ComplianceReportRequests into the .R struct +func (os SiteSlice) LoadComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + complianceReportRequests, err := os.ComplianceReportRequests(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.ComplianceReportRequests = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range complianceReportRequests { + + if !(o.ID == rel.SiteID) { + continue + } + + if !(o.Version == rel.SiteVersion) { + continue + } + + rel.R.Site = o + + o.R.ComplianceReportRequests = append(o.R.ComplianceReportRequests, rel) + } + } + + return nil +} + +// LoadPools loads the site's Pools into the .R struct +func (o *Site) LoadPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Pools = nil + + related, err := o.Pools(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Site = o + } + + o.R.Pools = related + return nil +} + +// LoadPools loads the site's Pools into the .R struct +func (os SiteSlice) LoadPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + pools, err := os.Pools(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.Pools = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range pools { + + if !(o.ID == rel.SiteID) { + continue + } + + if !(o.Version == rel.SiteVersion) { + continue + } + + rel.R.Site = o + + o.R.Pools = append(o.R.Pools, rel) + } + } + + return nil +} + +// LoadResidents loads the site's Residents into the .R struct +func (o *Site) LoadResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Residents = nil + + related, err := o.Residents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.Site = o + } + + o.R.Residents = related + return nil +} + +// LoadResidents loads the site's Residents into the .R struct +func (os SiteSlice) LoadResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + residents, err := os.Residents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.Residents = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range residents { + + if !(o.ID == rel.SiteID) { + continue + } + + if !(o.Version == rel.SiteVersion) { + continue + } + + rel.R.Site = o + + o.R.Residents = append(o.R.Residents, rel) + } + } + + return nil +} + // LoadAddress loads the site's Address into the .R struct func (o *Site) LoadAddress(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -1185,11 +1860,285 @@ func (os SiteSlice) LoadFile(ctx context.Context, exec bob.Executor, mods ...bob return nil } +// LoadParcel loads the site's Parcel into the .R struct +func (o *Site) LoadParcel(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.Parcel = nil + + related, err := o.Parcel(mods...).One(ctx, exec) + if err != nil { + return err + } + + related.R.Sites = SiteSlice{o} + + o.R.Parcel = related + return nil +} + +// LoadParcel loads the site's Parcel into the .R struct +func (os SiteSlice) LoadParcel(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + parcels, err := os.Parcel(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range parcels { + + if !(o.ParcelID == rel.ID) { + continue + } + + rel.R.Sites = append(rel.R.Sites, o) + + o.R.Parcel = rel + break + } + } + + return nil +} + +// siteC is where relationship counts are stored. +type siteC struct { + ComplianceReportRequests *int64 + Pools *int64 + Residents *int64 +} + +// PreloadCount sets a count in the C struct by name +func (o *Site) PreloadCount(name string, count int64) error { + if o == nil { + return nil + } + + switch name { + case "ComplianceReportRequests": + o.C.ComplianceReportRequests = &count + case "Pools": + o.C.Pools = &count + case "Residents": + o.C.Residents = &count + } + return nil +} + +type siteCountPreloader struct { + ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + Pools func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + Residents func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader +} + +func buildSiteCountPreloader() siteCountPreloader { + return siteCountPreloader{ + ComplianceReportRequests: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Site]("ComplianceReportRequests", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Sites.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ComplianceReportRequests.Name()), + sm.Where(psql.Quote(ComplianceReportRequests.Alias(), "site_id").EQ(psql.Quote(parent, "id"))), + sm.Where(psql.Quote(ComplianceReportRequests.Alias(), "site_version").EQ(psql.Quote(parent, "version"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + Pools: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Site]("Pools", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Sites.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Pools.Name()), + sm.Where(psql.Quote(Pools.Alias(), "site_id").EQ(psql.Quote(parent, "id"))), + sm.Where(psql.Quote(Pools.Alias(), "site_version").EQ(psql.Quote(parent, "version"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + Residents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*Site]("Residents", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Sites.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Residents.Name()), + sm.Where(psql.Quote(Residents.Alias(), "site_id").EQ(psql.Quote(parent, "id"))), + sm.Where(psql.Quote(Residents.Alias(), "site_version").EQ(psql.Quote(parent, "version"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, + } +} + +type siteCountThenLoader[Q orm.Loadable] struct { + ComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Pools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Residents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] +} + +func buildSiteCountThenLoader[Q orm.Loadable]() siteCountThenLoader[Q] { + type ComplianceReportRequestsCountInterface interface { + LoadCountComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type PoolsCountInterface interface { + LoadCountPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + type ResidentsCountInterface interface { + LoadCountResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } + + return siteCountThenLoader[Q]{ + ComplianceReportRequests: countThenLoadBuilder[Q]( + "ComplianceReportRequests", + func(ctx context.Context, exec bob.Executor, retrieved ComplianceReportRequestsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountComplianceReportRequests(ctx, exec, mods...) + }, + ), + Pools: countThenLoadBuilder[Q]( + "Pools", + func(ctx context.Context, exec bob.Executor, retrieved PoolsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountPools(ctx, exec, mods...) + }, + ), + Residents: countThenLoadBuilder[Q]( + "Residents", + func(ctx context.Context, exec bob.Executor, retrieved ResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountResidents(ctx, exec, mods...) + }, + ), + } +} + +// LoadCountComplianceReportRequests loads the count of ComplianceReportRequests into the C struct +func (o *Site) LoadCountComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.ComplianceReportRequests(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.ComplianceReportRequests = &count + return nil +} + +// LoadCountComplianceReportRequests loads the count of ComplianceReportRequests for a slice +func (os SiteSlice) LoadCountComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountComplianceReportRequests(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountPools loads the count of Pools into the C struct +func (o *Site) LoadCountPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.Pools(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.Pools = &count + return nil +} + +// LoadCountPools loads the count of Pools for a slice +func (os SiteSlice) LoadCountPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountPools(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + +// LoadCountResidents loads the count of Residents into the C struct +func (o *Site) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.Residents(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.Residents = &count + return nil +} + +// LoadCountResidents loads the count of Residents for a slice +func (os SiteSlice) LoadCountResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountResidents(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + type siteJoins[Q dialect.Joinable] struct { - typ string - Address modAs[Q, addressColumns] - CreatorUser modAs[Q, userColumns] - File modAs[Q, fileuploadFileColumns] + typ string + ComplianceReportRequests modAs[Q, complianceReportRequestColumns] + Pools modAs[Q, poolColumns] + Residents modAs[Q, residentColumns] + Address modAs[Q, addressColumns] + CreatorUser modAs[Q, userColumns] + File modAs[Q, fileuploadFileColumns] + Parcel modAs[Q, parcelColumns] } func (j siteJoins[Q]) aliasedAs(alias string) siteJoins[Q] { @@ -1199,6 +2148,48 @@ func (j siteJoins[Q]) aliasedAs(alias string) siteJoins[Q] { func buildSiteJoins[Q dialect.Joinable](cols siteColumns, typ string) siteJoins[Q] { return siteJoins[Q]{ typ: typ, + ComplianceReportRequests: modAs[Q, complianceReportRequestColumns]{ + c: ComplianceReportRequests.Columns, + f: func(to complianceReportRequestColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ComplianceReportRequests.Name().As(to.Alias())).On( + to.SiteID.EQ(cols.ID), to.SiteVersion.EQ(cols.Version), + )) + } + + return mods + }, + }, + Pools: modAs[Q, poolColumns]{ + c: Pools.Columns, + f: func(to poolColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Pools.Name().As(to.Alias())).On( + to.SiteID.EQ(cols.ID), to.SiteVersion.EQ(cols.Version), + )) + } + + return mods + }, + }, + Residents: modAs[Q, residentColumns]{ + c: Residents.Columns, + f: func(to residentColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Residents.Name().As(to.Alias())).On( + to.SiteID.EQ(cols.ID), to.SiteVersion.EQ(cols.Version), + )) + } + + return mods + }, + }, Address: modAs[Q, addressColumns]{ c: Addresses.Columns, f: func(to addressColumns) bob.Mod[Q] { @@ -1238,6 +2229,20 @@ func buildSiteJoins[Q dialect.Joinable](cols siteColumns, typ string) siteJoins[ )) } + return mods + }, + }, + Parcel: modAs[Q, parcelColumns]{ + c: Parcels.Columns, + f: func(to parcelColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Parcels.Name().As(to.Alias())).On( + to.ID.EQ(cols.ParcelID), + )) + } + return mods }, }, diff --git a/db/models/user_.bob.go b/db/models/user_.bob.go index a9452cb2..bc742c07 100644 --- a/db/models/user_.bob.go +++ b/db/models/user_.bob.go @@ -58,18 +58,20 @@ type UsersQuery = *psql.ViewQuery[*User, UserSlice] // userR is where relationships are stored. type userR struct { - PublicUserUser ArcgisUserSlice // arcgis.user_.user__public_user_id_fkey - CreatorFiles FileuploadFileSlice // fileupload.file.file_creator_id_fkey - FileuploadPool FileuploadPoolSlice // fileupload.pool.pool_creator_id_fkey - CreatorNoteAudios NoteAudioSlice // note_audio.note_audio_creator_id_fkey - DeletorNoteAudios NoteAudioSlice // note_audio.note_audio_deletor_id_fkey - CreatorNoteImages NoteImageSlice // note_image.note_image_creator_id_fkey - DeletorNoteImages NoteImageSlice // note_image.note_image_deletor_id_fkey - UserNotifications NotificationSlice // notification.notification_user_id_fkey - UserOauthTokens OauthTokenSlice // oauth_token.oauth_token_user_id_fkey - CreatorPools PoolSlice // pool.pool_creator_id_fkey - CreatorSites SiteSlice // site.site_creator_id_fkey - Organization *Organization // user_.user__organization_id_fkey + UserOauthTokens ArcgisOauthTokenSlice // arcgis.oauth_token.oauth_token_user_id_fkey + PublicUserUser ArcgisUserSlice // arcgis.user_.user__public_user_id_fkey + CreatorComplianceReportRequests ComplianceReportRequestSlice // compliance_report_request.compliance_report_request_creator_fkey + CreatorFiles FileuploadFileSlice // fileupload.file.file_creator_id_fkey + FileuploadPool FileuploadPoolSlice // fileupload.pool.pool_creator_id_fkey + CreatorNoteAudios NoteAudioSlice // note_audio.note_audio_creator_id_fkey + DeletorNoteAudios NoteAudioSlice // note_audio.note_audio_deletor_id_fkey + CreatorNoteImages NoteImageSlice // note_image.note_image_creator_id_fkey + DeletorNoteImages NoteImageSlice // note_image.note_image_deletor_id_fkey + UserNotifications NotificationSlice // notification.notification_user_id_fkey + CreatorPools PoolSlice // pool.pool_creator_id_fkey + CreatorResidents ResidentSlice // resident.resident_creator_fkey + CreatorSites SiteSlice // site.site_creator_id_fkey + Organization *Organization // user_.user__organization_id_fkey } func buildUserColumns(alias string) userColumns { @@ -638,6 +640,30 @@ func (o UserSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { return nil } +// UserOauthTokens starts a query for related objects on arcgis.oauth_token +func (o *User) UserOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisOauthTokensQuery { + return ArcgisOauthTokens.Query(append(mods, + sm.Where(ArcgisOauthTokens.Columns.UserID.EQ(psql.Arg(o.ID))), + )...) +} + +func (os UserSlice) UserOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisOauthTokensQuery { + 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 ArcgisOauthTokens.Query(append(mods, + sm.Where(psql.Group(ArcgisOauthTokens.Columns.UserID).OP("IN", PKArgExpr)), + )...) +} + // PublicUserUser starts a query for related objects on arcgis.user_ func (o *User) PublicUserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery { return ArcgisUsers.Query(append(mods, @@ -662,6 +688,30 @@ func (os UserSlice) PublicUserUser(mods ...bob.Mod[*dialect.SelectQuery]) Arcgis )...) } +// CreatorComplianceReportRequests starts a query for related objects on compliance_report_request +func (o *User) CreatorComplianceReportRequests(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery { + return ComplianceReportRequests.Query(append(mods, + sm.Where(ComplianceReportRequests.Columns.Creator.EQ(psql.Arg(o.ID))), + )...) +} + +func (os UserSlice) CreatorComplianceReportRequests(mods ...bob.Mod[*dialect.SelectQuery]) ComplianceReportRequestsQuery { + 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 ComplianceReportRequests.Query(append(mods, + sm.Where(psql.Group(ComplianceReportRequests.Columns.Creator).OP("IN", PKArgExpr)), + )...) +} + // CreatorFiles starts a query for related objects on fileupload.file func (o *User) CreatorFiles(mods ...bob.Mod[*dialect.SelectQuery]) FileuploadFilesQuery { return FileuploadFiles.Query(append(mods, @@ -830,30 +880,6 @@ func (os UserSlice) UserNotifications(mods ...bob.Mod[*dialect.SelectQuery]) Not )...) } -// UserOauthTokens starts a query for related objects on oauth_token -func (o *User) UserOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) OauthTokensQuery { - return OauthTokens.Query(append(mods, - sm.Where(OauthTokens.Columns.UserID.EQ(psql.Arg(o.ID))), - )...) -} - -func (os UserSlice) UserOauthTokens(mods ...bob.Mod[*dialect.SelectQuery]) OauthTokensQuery { - 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 OauthTokens.Query(append(mods, - sm.Where(psql.Group(OauthTokens.Columns.UserID).OP("IN", PKArgExpr)), - )...) -} - // CreatorPools starts a query for related objects on pool func (o *User) CreatorPools(mods ...bob.Mod[*dialect.SelectQuery]) PoolsQuery { return Pools.Query(append(mods, @@ -878,6 +904,30 @@ func (os UserSlice) CreatorPools(mods ...bob.Mod[*dialect.SelectQuery]) PoolsQue )...) } +// CreatorResidents starts a query for related objects on resident +func (o *User) CreatorResidents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + return Residents.Query(append(mods, + sm.Where(Residents.Columns.Creator.EQ(psql.Arg(o.ID))), + )...) +} + +func (os UserSlice) CreatorResidents(mods ...bob.Mod[*dialect.SelectQuery]) ResidentsQuery { + 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 Residents.Query(append(mods, + sm.Where(psql.Group(Residents.Columns.Creator).OP("IN", PKArgExpr)), + )...) +} + // CreatorSites starts a query for related objects on site func (o *User) CreatorSites(mods ...bob.Mod[*dialect.SelectQuery]) SitesQuery { return Sites.Query(append(mods, @@ -926,6 +976,74 @@ func (os UserSlice) Organization(mods ...bob.Mod[*dialect.SelectQuery]) Organiza )...) } +func insertUserUserOauthTokens0(ctx context.Context, exec bob.Executor, arcgisOauthTokens1 []*ArcgisOauthTokenSetter, user0 *User) (ArcgisOauthTokenSlice, error) { + for i := range arcgisOauthTokens1 { + arcgisOauthTokens1[i].UserID = omit.From(user0.ID) + } + + ret, err := ArcgisOauthTokens.Insert(bob.ToMods(arcgisOauthTokens1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertUserUserOauthTokens0: %w", err) + } + + return ret, nil +} + +func attachUserUserOauthTokens0(ctx context.Context, exec bob.Executor, count int, arcgisOauthTokens1 ArcgisOauthTokenSlice, user0 *User) (ArcgisOauthTokenSlice, error) { + setter := &ArcgisOauthTokenSetter{ + UserID: omit.From(user0.ID), + } + + err := arcgisOauthTokens1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachUserUserOauthTokens0: %w", err) + } + + return arcgisOauthTokens1, nil +} + +func (user0 *User) InsertUserOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthTokenSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + arcgisOauthTokens1, err := insertUserUserOauthTokens0(ctx, exec, related, user0) + if err != nil { + return err + } + + user0.R.UserOauthTokens = append(user0.R.UserOauthTokens, arcgisOauthTokens1...) + + for _, rel := range arcgisOauthTokens1 { + rel.R.UserUser = user0 + } + return nil +} + +func (user0 *User) AttachUserOauthTokens(ctx context.Context, exec bob.Executor, related ...*ArcgisOauthToken) error { + if len(related) == 0 { + return nil + } + + var err error + arcgisOauthTokens1 := ArcgisOauthTokenSlice(related) + + _, err = attachUserUserOauthTokens0(ctx, exec, len(related), arcgisOauthTokens1, user0) + if err != nil { + return err + } + + user0.R.UserOauthTokens = append(user0.R.UserOauthTokens, arcgisOauthTokens1...) + + for _, rel := range related { + rel.R.UserUser = user0 + } + + return nil +} + func insertUserPublicUserUser0(ctx context.Context, exec bob.Executor, arcgisusers1 []*ArcgisUserSetter, user0 *User) (ArcgisUserSlice, error) { for i := range arcgisusers1 { arcgisusers1[i].PublicUserID = omit.From(user0.ID) @@ -994,6 +1112,74 @@ func (user0 *User) AttachPublicUserUser(ctx context.Context, exec bob.Executor, return nil } +func insertUserCreatorComplianceReportRequests0(ctx context.Context, exec bob.Executor, complianceReportRequests1 []*ComplianceReportRequestSetter, user0 *User) (ComplianceReportRequestSlice, error) { + for i := range complianceReportRequests1 { + complianceReportRequests1[i].Creator = omit.From(user0.ID) + } + + ret, err := ComplianceReportRequests.Insert(bob.ToMods(complianceReportRequests1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertUserCreatorComplianceReportRequests0: %w", err) + } + + return ret, nil +} + +func attachUserCreatorComplianceReportRequests0(ctx context.Context, exec bob.Executor, count int, complianceReportRequests1 ComplianceReportRequestSlice, user0 *User) (ComplianceReportRequestSlice, error) { + setter := &ComplianceReportRequestSetter{ + Creator: omit.From(user0.ID), + } + + err := complianceReportRequests1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachUserCreatorComplianceReportRequests0: %w", err) + } + + return complianceReportRequests1, nil +} + +func (user0 *User) InsertCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequestSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + complianceReportRequests1, err := insertUserCreatorComplianceReportRequests0(ctx, exec, related, user0) + if err != nil { + return err + } + + user0.R.CreatorComplianceReportRequests = append(user0.R.CreatorComplianceReportRequests, complianceReportRequests1...) + + for _, rel := range complianceReportRequests1 { + rel.R.CreatorUser = user0 + } + return nil +} + +func (user0 *User) AttachCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, related ...*ComplianceReportRequest) error { + if len(related) == 0 { + return nil + } + + var err error + complianceReportRequests1 := ComplianceReportRequestSlice(related) + + _, err = attachUserCreatorComplianceReportRequests0(ctx, exec, len(related), complianceReportRequests1, user0) + if err != nil { + return err + } + + user0.R.CreatorComplianceReportRequests = append(user0.R.CreatorComplianceReportRequests, complianceReportRequests1...) + + for _, rel := range related { + rel.R.CreatorUser = user0 + } + + return nil +} + func insertUserCreatorFiles0(ctx context.Context, exec bob.Executor, fileuploadFiles1 []*FileuploadFileSetter, user0 *User) (FileuploadFileSlice, error) { for i := range fileuploadFiles1 { fileuploadFiles1[i].CreatorID = omit.From(user0.ID) @@ -1470,74 +1656,6 @@ func (user0 *User) AttachUserNotifications(ctx context.Context, exec bob.Executo return nil } -func insertUserUserOauthTokens0(ctx context.Context, exec bob.Executor, oauthTokens1 []*OauthTokenSetter, user0 *User) (OauthTokenSlice, error) { - for i := range oauthTokens1 { - oauthTokens1[i].UserID = omit.From(user0.ID) - } - - ret, err := OauthTokens.Insert(bob.ToMods(oauthTokens1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertUserUserOauthTokens0: %w", err) - } - - return ret, nil -} - -func attachUserUserOauthTokens0(ctx context.Context, exec bob.Executor, count int, oauthTokens1 OauthTokenSlice, user0 *User) (OauthTokenSlice, error) { - setter := &OauthTokenSetter{ - UserID: omit.From(user0.ID), - } - - err := oauthTokens1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachUserUserOauthTokens0: %w", err) - } - - return oauthTokens1, nil -} - -func (user0 *User) InsertUserOauthTokens(ctx context.Context, exec bob.Executor, related ...*OauthTokenSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - oauthTokens1, err := insertUserUserOauthTokens0(ctx, exec, related, user0) - if err != nil { - return err - } - - user0.R.UserOauthTokens = append(user0.R.UserOauthTokens, oauthTokens1...) - - for _, rel := range oauthTokens1 { - rel.R.UserUser = user0 - } - return nil -} - -func (user0 *User) AttachUserOauthTokens(ctx context.Context, exec bob.Executor, related ...*OauthToken) error { - if len(related) == 0 { - return nil - } - - var err error - oauthTokens1 := OauthTokenSlice(related) - - _, err = attachUserUserOauthTokens0(ctx, exec, len(related), oauthTokens1, user0) - if err != nil { - return err - } - - user0.R.UserOauthTokens = append(user0.R.UserOauthTokens, oauthTokens1...) - - for _, rel := range related { - rel.R.UserUser = user0 - } - - return nil -} - func insertUserCreatorPools0(ctx context.Context, exec bob.Executor, pools1 []*PoolSetter, user0 *User) (PoolSlice, error) { for i := range pools1 { pools1[i].CreatorID = omit.From(user0.ID) @@ -1606,6 +1724,74 @@ func (user0 *User) AttachCreatorPools(ctx context.Context, exec bob.Executor, re return nil } +func insertUserCreatorResidents0(ctx context.Context, exec bob.Executor, residents1 []*ResidentSetter, user0 *User) (ResidentSlice, error) { + for i := range residents1 { + residents1[i].Creator = omit.From(user0.ID) + } + + ret, err := Residents.Insert(bob.ToMods(residents1...)).All(ctx, exec) + if err != nil { + return ret, fmt.Errorf("insertUserCreatorResidents0: %w", err) + } + + return ret, nil +} + +func attachUserCreatorResidents0(ctx context.Context, exec bob.Executor, count int, residents1 ResidentSlice, user0 *User) (ResidentSlice, error) { + setter := &ResidentSetter{ + Creator: omit.From(user0.ID), + } + + err := residents1.UpdateAll(ctx, exec, *setter) + if err != nil { + return nil, fmt.Errorf("attachUserCreatorResidents0: %w", err) + } + + return residents1, nil +} + +func (user0 *User) InsertCreatorResidents(ctx context.Context, exec bob.Executor, related ...*ResidentSetter) error { + if len(related) == 0 { + return nil + } + + var err error + + residents1, err := insertUserCreatorResidents0(ctx, exec, related, user0) + if err != nil { + return err + } + + user0.R.CreatorResidents = append(user0.R.CreatorResidents, residents1...) + + for _, rel := range residents1 { + rel.R.CreatorUser = user0 + } + return nil +} + +func (user0 *User) AttachCreatorResidents(ctx context.Context, exec bob.Executor, related ...*Resident) error { + if len(related) == 0 { + return nil + } + + var err error + residents1 := ResidentSlice(related) + + _, err = attachUserCreatorResidents0(ctx, exec, len(related), residents1, user0) + if err != nil { + return err + } + + user0.R.CreatorResidents = append(user0.R.CreatorResidents, residents1...) + + for _, rel := range related { + rel.R.CreatorUser = user0 + } + + return nil +} + func insertUserCreatorSites0(ctx context.Context, exec bob.Executor, sites1 []*SiteSetter, user0 *User) (SiteSlice, error) { for i := range sites1 { sites1[i].CreatorID = omit.From(user0.ID) @@ -1766,6 +1952,20 @@ func (o *User) Preload(name string, retrieved any) error { } switch name { + case "UserOauthTokens": + rels, ok := retrieved.(ArcgisOauthTokenSlice) + if !ok { + return fmt.Errorf("user cannot load %T as %q", retrieved, name) + } + + o.R.UserOauthTokens = rels + + for _, rel := range rels { + if rel != nil { + rel.R.UserUser = o + } + } + return nil case "PublicUserUser": rels, ok := retrieved.(ArcgisUserSlice) if !ok { @@ -1780,6 +1980,20 @@ func (o *User) Preload(name string, retrieved any) error { } } return nil + case "CreatorComplianceReportRequests": + rels, ok := retrieved.(ComplianceReportRequestSlice) + if !ok { + return fmt.Errorf("user cannot load %T as %q", retrieved, name) + } + + o.R.CreatorComplianceReportRequests = rels + + for _, rel := range rels { + if rel != nil { + rel.R.CreatorUser = o + } + } + return nil case "CreatorFiles": rels, ok := retrieved.(FileuploadFileSlice) if !ok { @@ -1872,20 +2086,6 @@ func (o *User) Preload(name string, retrieved any) error { o.R.UserNotifications = rels - for _, rel := range rels { - if rel != nil { - rel.R.UserUser = o - } - } - return nil - case "UserOauthTokens": - rels, ok := retrieved.(OauthTokenSlice) - if !ok { - return fmt.Errorf("user cannot load %T as %q", retrieved, name) - } - - o.R.UserOauthTokens = rels - for _, rel := range rels { if rel != nil { rel.R.UserUser = o @@ -1900,6 +2100,20 @@ func (o *User) Preload(name string, retrieved any) error { o.R.CreatorPools = rels + for _, rel := range rels { + if rel != nil { + rel.R.CreatorUser = o + } + } + return nil + case "CreatorResidents": + rels, ok := retrieved.(ResidentSlice) + if !ok { + return fmt.Errorf("user cannot load %T as %q", retrieved, name) + } + + o.R.CreatorResidents = rels + for _, rel := range rels { if rel != nil { rel.R.CreatorUser = o @@ -1960,24 +2174,32 @@ func buildUserPreloader() userPreloader { } type userThenLoader[Q orm.Loadable] struct { - PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - UserNotifications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorPools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorSites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserNotifications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorPools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorResidents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorSites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { + type UserOauthTokensLoadInterface interface { + LoadUserOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type PublicUserUserLoadInterface interface { LoadPublicUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type CreatorComplianceReportRequestsLoadInterface interface { + LoadCreatorComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type CreatorFilesLoadInterface interface { LoadCreatorFiles(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -1999,12 +2221,12 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { type UserNotificationsLoadInterface interface { LoadUserNotifications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } - type UserOauthTokensLoadInterface interface { - LoadUserOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } type CreatorPoolsLoadInterface interface { LoadCreatorPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type CreatorResidentsLoadInterface interface { + LoadCreatorResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type CreatorSitesLoadInterface interface { LoadCreatorSites(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -2013,12 +2235,24 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { } return userThenLoader[Q]{ + UserOauthTokens: thenLoadBuilder[Q]( + "UserOauthTokens", + func(ctx context.Context, exec bob.Executor, retrieved UserOauthTokensLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadUserOauthTokens(ctx, exec, mods...) + }, + ), PublicUserUser: thenLoadBuilder[Q]( "PublicUserUser", func(ctx context.Context, exec bob.Executor, retrieved PublicUserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { return retrieved.LoadPublicUserUser(ctx, exec, mods...) }, ), + CreatorComplianceReportRequests: thenLoadBuilder[Q]( + "CreatorComplianceReportRequests", + func(ctx context.Context, exec bob.Executor, retrieved CreatorComplianceReportRequestsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCreatorComplianceReportRequests(ctx, exec, mods...) + }, + ), CreatorFiles: thenLoadBuilder[Q]( "CreatorFiles", func(ctx context.Context, exec bob.Executor, retrieved CreatorFilesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -2061,18 +2295,18 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { return retrieved.LoadUserNotifications(ctx, exec, mods...) }, ), - UserOauthTokens: thenLoadBuilder[Q]( - "UserOauthTokens", - func(ctx context.Context, exec bob.Executor, retrieved UserOauthTokensLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadUserOauthTokens(ctx, exec, mods...) - }, - ), CreatorPools: thenLoadBuilder[Q]( "CreatorPools", func(ctx context.Context, exec bob.Executor, retrieved CreatorPoolsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { return retrieved.LoadCreatorPools(ctx, exec, mods...) }, ), + CreatorResidents: thenLoadBuilder[Q]( + "CreatorResidents", + func(ctx context.Context, exec bob.Executor, retrieved CreatorResidentsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCreatorResidents(ctx, exec, mods...) + }, + ), CreatorSites: thenLoadBuilder[Q]( "CreatorSites", func(ctx context.Context, exec bob.Executor, retrieved CreatorSitesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -2088,6 +2322,67 @@ func buildUserThenLoader[Q orm.Loadable]() userThenLoader[Q] { } } +// LoadUserOauthTokens loads the user's UserOauthTokens into the .R struct +func (o *User) LoadUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.UserOauthTokens = nil + + related, err := o.UserOauthTokens(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.UserUser = o + } + + o.R.UserOauthTokens = related + return nil +} + +// LoadUserOauthTokens loads the user's UserOauthTokens into the .R struct +func (os UserSlice) LoadUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + arcgisOauthTokens, err := os.UserOauthTokens(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.UserOauthTokens = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range arcgisOauthTokens { + + if !(o.ID == rel.UserID) { + continue + } + + rel.R.UserUser = o + + o.R.UserOauthTokens = append(o.R.UserOauthTokens, rel) + } + } + + return nil +} + // LoadPublicUserUser loads the user's PublicUserUser into the .R struct func (o *User) LoadPublicUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -2149,6 +2444,67 @@ func (os UserSlice) LoadPublicUserUser(ctx context.Context, exec bob.Executor, m return nil } +// LoadCreatorComplianceReportRequests loads the user's CreatorComplianceReportRequests into the .R struct +func (o *User) LoadCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.CreatorComplianceReportRequests = nil + + related, err := o.CreatorComplianceReportRequests(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.CreatorUser = o + } + + o.R.CreatorComplianceReportRequests = related + return nil +} + +// LoadCreatorComplianceReportRequests loads the user's CreatorComplianceReportRequests into the .R struct +func (os UserSlice) LoadCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + complianceReportRequests, err := os.CreatorComplianceReportRequests(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.CreatorComplianceReportRequests = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range complianceReportRequests { + + if !(o.ID == rel.Creator) { + continue + } + + rel.R.CreatorUser = o + + o.R.CreatorComplianceReportRequests = append(o.R.CreatorComplianceReportRequests, rel) + } + } + + return nil +} + // LoadCreatorFiles loads the user's CreatorFiles into the .R struct func (o *User) LoadCreatorFiles(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -2582,67 +2938,6 @@ func (os UserSlice) LoadUserNotifications(ctx context.Context, exec bob.Executor return nil } -// LoadUserOauthTokens loads the user's UserOauthTokens into the .R struct -func (o *User) LoadUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.UserOauthTokens = nil - - related, err := o.UserOauthTokens(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.UserUser = o - } - - o.R.UserOauthTokens = related - return nil -} - -// LoadUserOauthTokens loads the user's UserOauthTokens into the .R struct -func (os UserSlice) LoadUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - oauthTokens, err := os.UserOauthTokens(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.UserOauthTokens = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range oauthTokens { - - if !(o.ID == rel.UserID) { - continue - } - - rel.R.UserUser = o - - o.R.UserOauthTokens = append(o.R.UserOauthTokens, rel) - } - } - - return nil -} - // LoadCreatorPools loads the user's CreatorPools into the .R struct func (o *User) LoadCreatorPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -2704,6 +2999,67 @@ func (os UserSlice) LoadCreatorPools(ctx context.Context, exec bob.Executor, mod return nil } +// LoadCreatorResidents loads the user's CreatorResidents into the .R struct +func (o *User) LoadCreatorResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + // Reset the relationship + o.R.CreatorResidents = nil + + related, err := o.CreatorResidents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, rel := range related { + rel.R.CreatorUser = o + } + + o.R.CreatorResidents = related + return nil +} + +// LoadCreatorResidents loads the user's CreatorResidents into the .R struct +func (os UserSlice) LoadCreatorResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + residents, err := os.CreatorResidents(mods...).All(ctx, exec) + if err != nil { + return err + } + + for _, o := range os { + if o == nil { + continue + } + + o.R.CreatorResidents = nil + } + + for _, o := range os { + if o == nil { + continue + } + + for _, rel := range residents { + + if !(o.ID == rel.Creator) { + continue + } + + rel.R.CreatorUser = o + + o.R.CreatorResidents = append(o.R.CreatorResidents, rel) + } + } + + return nil +} + // LoadCreatorSites loads the user's CreatorSites into the .R struct func (o *User) LoadCreatorSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -2819,17 +3175,19 @@ func (os UserSlice) LoadOrganization(ctx context.Context, exec bob.Executor, mod // userC is where relationship counts are stored. type userC struct { - PublicUserUser *int64 - CreatorFiles *int64 - FileuploadPool *int64 - CreatorNoteAudios *int64 - DeletorNoteAudios *int64 - CreatorNoteImages *int64 - DeletorNoteImages *int64 - UserNotifications *int64 - UserOauthTokens *int64 - CreatorPools *int64 - CreatorSites *int64 + UserOauthTokens *int64 + PublicUserUser *int64 + CreatorComplianceReportRequests *int64 + CreatorFiles *int64 + FileuploadPool *int64 + CreatorNoteAudios *int64 + DeletorNoteAudios *int64 + CreatorNoteImages *int64 + DeletorNoteImages *int64 + UserNotifications *int64 + CreatorPools *int64 + CreatorResidents *int64 + CreatorSites *int64 } // PreloadCount sets a count in the C struct by name @@ -2839,8 +3197,12 @@ func (o *User) PreloadCount(name string, count int64) error { } switch name { + case "UserOauthTokens": + o.C.UserOauthTokens = &count case "PublicUserUser": o.C.PublicUserUser = &count + case "CreatorComplianceReportRequests": + o.C.CreatorComplianceReportRequests = &count case "CreatorFiles": o.C.CreatorFiles = &count case "FileuploadPool": @@ -2855,10 +3217,10 @@ func (o *User) PreloadCount(name string, count int64) error { o.C.DeletorNoteImages = &count case "UserNotifications": o.C.UserNotifications = &count - case "UserOauthTokens": - o.C.UserOauthTokens = &count case "CreatorPools": o.C.CreatorPools = &count + case "CreatorResidents": + o.C.CreatorResidents = &count case "CreatorSites": o.C.CreatorSites = &count } @@ -2866,21 +3228,40 @@ func (o *User) PreloadCount(name string, count int64) error { } type userCountPreloader struct { - PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - UserNotifications func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - CreatorPools func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader - CreatorSites func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + UserNotifications func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorPools func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorResidents func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader + CreatorSites func(...bob.Mod[*dialect.SelectQuery]) psql.Preloader } func buildUserCountPreloader() userCountPreloader { return userCountPreloader{ + UserOauthTokens: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*User]("UserOauthTokens", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Users.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ArcgisOauthTokens.Name()), + sm.Where(psql.Quote(ArcgisOauthTokens.Alias(), "user_id").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, PublicUserUser: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { return countPreloader[*User]("PublicUserUser", func(parent string) bob.Expression { // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) @@ -2898,6 +3279,23 @@ func buildUserCountPreloader() userCountPreloader { return psql.Group(psql.Select(subqueryMods...).Expression) }) }, + CreatorComplianceReportRequests: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*User]("CreatorComplianceReportRequests", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Users.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(ComplianceReportRequests.Name()), + sm.Where(psql.Quote(ComplianceReportRequests.Alias(), "creator").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, CreatorFiles: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { return countPreloader[*User]("CreatorFiles", func(parent string) bob.Expression { // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) @@ -3017,23 +3415,6 @@ func buildUserCountPreloader() userCountPreloader { return psql.Group(psql.Select(subqueryMods...).Expression) }) }, - UserOauthTokens: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { - return countPreloader[*User]("UserOauthTokens", func(parent string) bob.Expression { - // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) - if parent == "" { - parent = Users.Alias() - } - - subqueryMods := []bob.Mod[*dialect.SelectQuery]{ - sm.Columns(psql.Raw("count(*)")), - - sm.From(OauthTokens.Name()), - sm.Where(psql.Quote(OauthTokens.Alias(), "user_id").EQ(psql.Quote(parent, "id"))), - } - subqueryMods = append(subqueryMods, mods...) - return psql.Group(psql.Select(subqueryMods...).Expression) - }) - }, CreatorPools: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { return countPreloader[*User]("CreatorPools", func(parent string) bob.Expression { // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) @@ -3051,6 +3432,23 @@ func buildUserCountPreloader() userCountPreloader { return psql.Group(psql.Select(subqueryMods...).Expression) }) }, + CreatorResidents: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { + return countPreloader[*User]("CreatorResidents", func(parent string) bob.Expression { + // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) + if parent == "" { + parent = Users.Alias() + } + + subqueryMods := []bob.Mod[*dialect.SelectQuery]{ + sm.Columns(psql.Raw("count(*)")), + + sm.From(Residents.Name()), + sm.Where(psql.Quote(Residents.Alias(), "creator").EQ(psql.Quote(parent, "id"))), + } + subqueryMods = append(subqueryMods, mods...) + return psql.Group(psql.Select(subqueryMods...).Expression) + }) + }, CreatorSites: func(mods ...bob.Mod[*dialect.SelectQuery]) psql.Preloader { return countPreloader[*User]("CreatorSites", func(parent string) bob.Expression { // Build a correlated subquery: (SELECT COUNT(*) FROM related WHERE fk = parent.pk) @@ -3072,23 +3470,31 @@ func buildUserCountPreloader() userCountPreloader { } type userCountThenLoader[Q orm.Loadable] struct { - PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - UserNotifications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorPools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - CreatorSites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorComplianceReportRequests func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorFiles func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + FileuploadPool func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + DeletorNoteAudios func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + DeletorNoteImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + UserNotifications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorPools func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorResidents func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CreatorSites func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildUserCountThenLoader[Q orm.Loadable]() userCountThenLoader[Q] { + type UserOauthTokensCountInterface interface { + LoadCountUserOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type PublicUserUserCountInterface interface { LoadCountPublicUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type CreatorComplianceReportRequestsCountInterface interface { + LoadCountCreatorComplianceReportRequests(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type CreatorFilesCountInterface interface { LoadCountCreatorFiles(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -3110,23 +3516,35 @@ func buildUserCountThenLoader[Q orm.Loadable]() userCountThenLoader[Q] { type UserNotificationsCountInterface interface { LoadCountUserNotifications(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } - type UserOauthTokensCountInterface interface { - LoadCountUserOauthTokens(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } type CreatorPoolsCountInterface interface { LoadCountCreatorPools(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } + type CreatorResidentsCountInterface interface { + LoadCountCreatorResidents(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error + } type CreatorSitesCountInterface interface { LoadCountCreatorSites(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } return userCountThenLoader[Q]{ + UserOauthTokens: countThenLoadBuilder[Q]( + "UserOauthTokens", + func(ctx context.Context, exec bob.Executor, retrieved UserOauthTokensCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountUserOauthTokens(ctx, exec, mods...) + }, + ), PublicUserUser: countThenLoadBuilder[Q]( "PublicUserUser", func(ctx context.Context, exec bob.Executor, retrieved PublicUserUserCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { return retrieved.LoadCountPublicUserUser(ctx, exec, mods...) }, ), + CreatorComplianceReportRequests: countThenLoadBuilder[Q]( + "CreatorComplianceReportRequests", + func(ctx context.Context, exec bob.Executor, retrieved CreatorComplianceReportRequestsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountCreatorComplianceReportRequests(ctx, exec, mods...) + }, + ), CreatorFiles: countThenLoadBuilder[Q]( "CreatorFiles", func(ctx context.Context, exec bob.Executor, retrieved CreatorFilesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -3169,18 +3587,18 @@ func buildUserCountThenLoader[Q orm.Loadable]() userCountThenLoader[Q] { return retrieved.LoadCountUserNotifications(ctx, exec, mods...) }, ), - UserOauthTokens: countThenLoadBuilder[Q]( - "UserOauthTokens", - func(ctx context.Context, exec bob.Executor, retrieved UserOauthTokensCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadCountUserOauthTokens(ctx, exec, mods...) - }, - ), CreatorPools: countThenLoadBuilder[Q]( "CreatorPools", func(ctx context.Context, exec bob.Executor, retrieved CreatorPoolsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { return retrieved.LoadCountCreatorPools(ctx, exec, mods...) }, ), + CreatorResidents: countThenLoadBuilder[Q]( + "CreatorResidents", + func(ctx context.Context, exec bob.Executor, retrieved CreatorResidentsCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { + return retrieved.LoadCountCreatorResidents(ctx, exec, mods...) + }, + ), CreatorSites: countThenLoadBuilder[Q]( "CreatorSites", func(ctx context.Context, exec bob.Executor, retrieved CreatorSitesCountInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -3190,6 +3608,36 @@ func buildUserCountThenLoader[Q orm.Loadable]() userCountThenLoader[Q] { } } +// LoadCountUserOauthTokens loads the count of UserOauthTokens into the C struct +func (o *User) LoadCountUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.UserOauthTokens(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.UserOauthTokens = &count + return nil +} + +// LoadCountUserOauthTokens loads the count of UserOauthTokens for a slice +func (os UserSlice) LoadCountUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountUserOauthTokens(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + // LoadCountPublicUserUser loads the count of PublicUserUser into the C struct func (o *User) LoadCountPublicUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -3220,6 +3668,36 @@ func (os UserSlice) LoadCountPublicUserUser(ctx context.Context, exec bob.Execut return nil } +// LoadCountCreatorComplianceReportRequests loads the count of CreatorComplianceReportRequests into the C struct +func (o *User) LoadCountCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.CreatorComplianceReportRequests(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.CreatorComplianceReportRequests = &count + return nil +} + +// LoadCountCreatorComplianceReportRequests loads the count of CreatorComplianceReportRequests for a slice +func (os UserSlice) LoadCountCreatorComplianceReportRequests(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountCreatorComplianceReportRequests(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + // LoadCountCreatorFiles loads the count of CreatorFiles into the C struct func (o *User) LoadCountCreatorFiles(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -3430,36 +3908,6 @@ func (os UserSlice) LoadCountUserNotifications(ctx context.Context, exec bob.Exe return nil } -// LoadCountUserOauthTokens loads the count of UserOauthTokens into the C struct -func (o *User) LoadCountUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - count, err := o.UserOauthTokens(mods...).Count(ctx, exec) - if err != nil { - return err - } - - o.C.UserOauthTokens = &count - return nil -} - -// LoadCountUserOauthTokens loads the count of UserOauthTokens for a slice -func (os UserSlice) LoadCountUserOauthTokens(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - for _, o := range os { - if err := o.LoadCountUserOauthTokens(ctx, exec, mods...); err != nil { - return err - } - } - - return nil -} - // LoadCountCreatorPools loads the count of CreatorPools into the C struct func (o *User) LoadCountCreatorPools(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -3490,6 +3938,36 @@ func (os UserSlice) LoadCountCreatorPools(ctx context.Context, exec bob.Executor return nil } +// LoadCountCreatorResidents loads the count of CreatorResidents into the C struct +func (o *User) LoadCountCreatorResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if o == nil { + return nil + } + + count, err := o.CreatorResidents(mods...).Count(ctx, exec) + if err != nil { + return err + } + + o.C.CreatorResidents = &count + return nil +} + +// LoadCountCreatorResidents loads the count of CreatorResidents for a slice +func (os UserSlice) LoadCountCreatorResidents(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { + if len(os) == 0 { + return nil + } + + for _, o := range os { + if err := o.LoadCountCreatorResidents(ctx, exec, mods...); err != nil { + return err + } + } + + return nil +} + // LoadCountCreatorSites loads the count of CreatorSites into the C struct func (o *User) LoadCountCreatorSites(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -3521,19 +3999,21 @@ func (os UserSlice) LoadCountCreatorSites(ctx context.Context, exec bob.Executor } type userJoins[Q dialect.Joinable] struct { - typ string - PublicUserUser modAs[Q, arcgisuserColumns] - CreatorFiles modAs[Q, fileuploadFileColumns] - FileuploadPool modAs[Q, fileuploadPoolColumns] - CreatorNoteAudios modAs[Q, noteAudioColumns] - DeletorNoteAudios modAs[Q, noteAudioColumns] - CreatorNoteImages modAs[Q, noteImageColumns] - DeletorNoteImages modAs[Q, noteImageColumns] - UserNotifications modAs[Q, notificationColumns] - UserOauthTokens modAs[Q, oauthTokenColumns] - CreatorPools modAs[Q, poolColumns] - CreatorSites modAs[Q, siteColumns] - Organization modAs[Q, organizationColumns] + typ string + UserOauthTokens modAs[Q, arcgisOauthTokenColumns] + PublicUserUser modAs[Q, arcgisuserColumns] + CreatorComplianceReportRequests modAs[Q, complianceReportRequestColumns] + CreatorFiles modAs[Q, fileuploadFileColumns] + FileuploadPool modAs[Q, fileuploadPoolColumns] + CreatorNoteAudios modAs[Q, noteAudioColumns] + DeletorNoteAudios modAs[Q, noteAudioColumns] + CreatorNoteImages modAs[Q, noteImageColumns] + DeletorNoteImages modAs[Q, noteImageColumns] + UserNotifications modAs[Q, notificationColumns] + CreatorPools modAs[Q, poolColumns] + CreatorResidents modAs[Q, residentColumns] + CreatorSites modAs[Q, siteColumns] + Organization modAs[Q, organizationColumns] } func (j userJoins[Q]) aliasedAs(alias string) userJoins[Q] { @@ -3543,6 +4023,20 @@ func (j userJoins[Q]) aliasedAs(alias string) userJoins[Q] { func buildUserJoins[Q dialect.Joinable](cols userColumns, typ string) userJoins[Q] { return userJoins[Q]{ typ: typ, + UserOauthTokens: modAs[Q, arcgisOauthTokenColumns]{ + c: ArcgisOauthTokens.Columns, + f: func(to arcgisOauthTokenColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ArcgisOauthTokens.Name().As(to.Alias())).On( + to.UserID.EQ(cols.ID), + )) + } + + return mods + }, + }, PublicUserUser: modAs[Q, arcgisuserColumns]{ c: ArcgisUsers.Columns, f: func(to arcgisuserColumns) bob.Mod[Q] { @@ -3557,6 +4051,20 @@ func buildUserJoins[Q dialect.Joinable](cols userColumns, typ string) userJoins[ return mods }, }, + CreatorComplianceReportRequests: modAs[Q, complianceReportRequestColumns]{ + c: ComplianceReportRequests.Columns, + f: func(to complianceReportRequestColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, ComplianceReportRequests.Name().As(to.Alias())).On( + to.Creator.EQ(cols.ID), + )) + } + + return mods + }, + }, CreatorFiles: modAs[Q, fileuploadFileColumns]{ c: FileuploadFiles.Columns, f: func(to fileuploadFileColumns) bob.Mod[Q] { @@ -3655,20 +4163,6 @@ func buildUserJoins[Q dialect.Joinable](cols userColumns, typ string) userJoins[ return mods }, }, - UserOauthTokens: modAs[Q, oauthTokenColumns]{ - c: OauthTokens.Columns, - f: func(to oauthTokenColumns) bob.Mod[Q] { - mods := make(mods.QueryMods[Q], 0, 1) - - { - mods = append(mods, dialect.Join[Q](typ, OauthTokens.Name().As(to.Alias())).On( - to.UserID.EQ(cols.ID), - )) - } - - return mods - }, - }, CreatorPools: modAs[Q, poolColumns]{ c: Pools.Columns, f: func(to poolColumns) bob.Mod[Q] { @@ -3683,6 +4177,20 @@ func buildUserJoins[Q dialect.Joinable](cols userColumns, typ string) userJoins[ return mods }, }, + CreatorResidents: modAs[Q, residentColumns]{ + c: Residents.Columns, + f: func(to residentColumns) bob.Mod[Q] { + mods := make(mods.QueryMods[Q], 0, 1) + + { + mods = append(mods, dialect.Join[Q](typ, Residents.Name().As(to.Alias())).On( + to.Creator.EQ(cols.ID), + )) + } + + return mods + }, + }, CreatorSites: modAs[Q, siteColumns]{ c: Sites.Columns, f: func(to siteColumns) bob.Mod[Q] { diff --git a/db/sql/org_by_oauth_id.bob.go b/db/sql/org_by_oauth_id.bob.go index e780eaed..9a2f84fa 100644 --- a/db/sql/org_by_oauth_id.bob.go +++ b/db/sql/org_by_oauth_id.bob.go @@ -13,14 +13,13 @@ import ( "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/stephenafamo/scan" ) //go:embed org_by_oauth_id.bob.sql var formattedQueries_org_by_oauth_id string -var orgByOauthIdSQL = formattedQueries_org_by_oauth_id[150:363] +var orgByOauthIdSQL = formattedQueries_org_by_oauth_id[150:495] type OrgByOauthIdQuery = orm.ModQuery[*dialect.SelectQuery, orgByOauthId, OrgByOauthIdRow, []OrgByOauthIdRow, orgByOauthIdTransformer] @@ -51,17 +50,17 @@ func OrgByOauthId(ID int32) *OrgByOauthIdQuery { }, }, Mod: bob.ModFunc[*dialect.SelectQuery](func(q *dialect.SelectQuery) { - q.AppendSelect(expressionTypArgs.subExpr(7, 94)) - q.SetTable(expressionTypArgs.subExpr(100, 196)) - q.AppendWhere(expressionTypArgs.subExpr(203, 213)) + q.AppendSelect(expressionTypArgs.subExpr(7, 78)) + q.SetTable(expressionTypArgs.subExpr(84, 328)) + q.AppendWhere(expressionTypArgs.subExpr(335, 345)) }), } } type OrgByOauthIdRow = struct { - OrganizationID int32 `db:"organization_id"` - ArcgisID null.Val[string] `db:"arcgis_id"` - FieldseekerURL null.Val[string] `db:"fieldseeker_url"` + OrganizationID int32 `db:"organization_id"` + ArcgisID string `db:"arcgis_id"` + FieldseekerURL string `db:"fieldseeker_url"` } type orgByOauthIdTransformer = bob.SliceTransformer[OrgByOauthIdRow, []OrgByOauthIdRow] @@ -74,8 +73,8 @@ func (o orgByOauthId) args() iter.Seq[orm.ArgWithPosition] { return func(yield func(arg orm.ArgWithPosition) bool) { if !yield(orm.ArgWithPosition{ Name: "id", - Start: 211, - Stop: 213, + Start: 343, + Stop: 345, Expression: o.ID, }) { return diff --git a/db/sql/update_oauth_org.bob.go b/db/sql/update_oauth_org.bob.go deleted file mode 100644 index 85591579..00000000 --- a/db/sql/update_oauth_org.bob.go +++ /dev/null @@ -1,95 +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" - - "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" -) - -//go:embed update_oauth_org.bob.sql -var formattedQueries_update_oauth_org string - -var updateOauthTokenOrgSQL = formattedQueries_update_oauth_org[157:249] - -type UpdateOauthTokenOrgQuery = orm.ModExecQuery[*dialect.UpdateQuery, updateOauthTokenOrg] - -func UpdateOauthTokenOrg(ArcgisID string, ArcgisLicenseTypeID string, RefreshToken string) *UpdateOauthTokenOrgQuery { - var expressionTypArgs updateOauthTokenOrg - - expressionTypArgs.ArcgisID = psql.Arg(ArcgisID) - expressionTypArgs.ArcgisLicenseTypeID = psql.Arg(ArcgisLicenseTypeID) - expressionTypArgs.RefreshToken = psql.Arg(RefreshToken) - - return &UpdateOauthTokenOrgQuery{ - ExecQuery: orm.ExecQuery[updateOauthTokenOrg]{ - BaseQuery: bob.BaseQuery[updateOauthTokenOrg]{ - Expression: expressionTypArgs, - Dialect: dialect.Dialect, - QueryType: bob.QueryTypeUpdate, - }, - }, - Mod: bob.ModFunc[*dialect.UpdateQuery](func(q *dialect.UpdateQuery) { - q.Table.Expression = expressionTypArgs.subExpr(7, 18) - q.AppendSet(expressionTypArgs.subExpr(23, 66)) - q.AppendWhere(expressionTypArgs.subExpr(74, 92)) - }), - } -} - -type updateOauthTokenOrg struct { - ArcgisID bob.Expression - ArcgisLicenseTypeID bob.Expression - RefreshToken bob.Expression -} - -func (o updateOauthTokenOrg) args() iter.Seq[orm.ArgWithPosition] { - return func(yield func(arg orm.ArgWithPosition) bool) { - if !yield(orm.ArgWithPosition{ - Name: "arcgisID", - Start: 35, - Stop: 37, - Expression: o.ArcgisID, - }) { - return - } - - if !yield(orm.ArgWithPosition{ - Name: "arcgisLicenseTypeID", - Start: 64, - Stop: 66, - Expression: o.ArcgisLicenseTypeID, - }) { - return - } - - if !yield(orm.ArgWithPosition{ - Name: "refreshToken", - Start: 90, - Stop: 92, - Expression: o.RefreshToken, - }) { - return - } - } -} - -func (o updateOauthTokenOrg) raw(from, to int) string { - return updateOauthTokenOrgSQL[from:to] -} - -func (o updateOauthTokenOrg) subExpr(from, to int) bob.Expression { - return orm.ArgsToExpression(updateOauthTokenOrgSQL, from, to, o.args()) -} - -func (o updateOauthTokenOrg) WriteSQL(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) { - return o.subExpr(0, len(updateOauthTokenOrgSQL)).WriteSQL(ctx, w, d, start) -} diff --git a/db/sql/update_oauth_org.bob.sql b/db/sql/update_oauth_org.bob.sql deleted file mode 100644 index 37337db6..00000000 --- a/db/sql/update_oauth_org.bob.sql +++ /dev/null @@ -1,6 +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. - --- UpdateOauthTokenOrg -UPDATE oauth_token SET arcgis_id = $1, arcgis_license_type_id = $2 - WHERE refresh_token = $3; diff --git a/db/sql/update_oauth_org.sql b/db/sql/update_oauth_org.sql deleted file mode 100644 index db26f4f4..00000000 --- a/db/sql/update_oauth_org.sql +++ /dev/null @@ -1,3 +0,0 @@ --- UpdateOauthTokenOrg -UPDATE oauth_token SET arcgis_id = $1, arcgis_license_type_id = $2 - WHERE refresh_token = $3;