diff --git a/api/configuration.go b/api/configuration.go index 7bfddf2d..49e6c4d5 100644 --- a/api/configuration.go +++ b/api/configuration.go @@ -7,7 +7,8 @@ import ( "github.com/Gleipnir-Technology/bob/dialect/psql" "github.com/Gleipnir-Technology/bob/dialect/psql/um" "github.com/Gleipnir-Technology/nidus-sync/db" - "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + queryarcgis "github.com/Gleipnir-Technology/nidus-sync/db/query/arcgis" "github.com/Gleipnir-Technology/nidus-sync/html" nhttp "github.com/Gleipnir-Technology/nidus-sync/http" "github.com/Gleipnir-Technology/nidus-sync/platform" @@ -25,9 +26,9 @@ type contentSettingOrganization struct { } type contentSettingIntegration struct { - ArcGISAccount *models.ArcgisAccount - ArcGISOAuth *models.ArcgisOauthToken - ServiceMaps []*models.ArcgisServiceMap + ArcGISAccount *model.Account + ArcGISOAuth *model.OAuthToken + ServiceMaps []*model.ServiceMap } func getConfigurationOrganization(ctx context.Context, r *http.Request, u platform.User) (*html.Response[contentSettingOrganization], *nhttp.ErrorWithStatus) { @@ -82,17 +83,15 @@ func getConfigurationIntegrationArcgis(ctx context.Context, r *http.Request, u p if err != nil { return nil, nhttp.NewError("Failed to get oauth: %w", err) } - var account *models.ArcgisAccount - var service_maps []*models.ArcgisServiceMap + var account *model.Account + var service_maps []*model.ServiceMap account_id := u.Organization.ArcgisAccountID() if account_id != "" { - account, err = models.FindArcgisAccount(ctx, db.PGInstance.BobDB, account_id) + account, err = queryarcgis.AccountFromID(ctx, account_id) if err != nil { return nil, nhttp.NewError("Failed to get arcgis: %w", err) } - service_maps, err = models.ArcgisServiceMaps.Query( - models.SelectWhere.ArcgisServiceMaps.AccountID.EQ(account.ID), - ).All(ctx, db.PGInstance.BobDB) + service_maps, err = queryarcgis.ServiceMapsFromAccountID(ctx, account.ID) if err != nil { return nil, nhttp.NewError("Failed to get map services: %w", err) } diff --git a/db/connection.go b/db/connection.go index 1f1ee186..b8a72df9 100644 --- a/db/connection.go +++ b/db/connection.go @@ -18,6 +18,7 @@ import ( "github.com/jackc/pgx/v5/stdlib" "github.com/pressly/goose/v3" "github.com/rs/zerolog/log" + "github.com/stephenafamo/scan" ) //go:embed migrations/*.sql @@ -33,13 +34,41 @@ var ( pgOnce sync.Once ) -func Execute[T any](ctx context.Context, stmt postgres.Statement) (*T, error) { +func ExecuteNone(ctx context.Context, stmt postgres.Statement) error { query, args := stmt.Sql() - row, _ := PGInstance.PGXPool.Query(ctx, query, args...) - data, err := pgx.CollectOneRow(row, pgx.RowToAddrOfStructByPos[T]) + _, err := PGInstance.PGXPool.Query(ctx, query, args...) + return err +} +func ExecuteNoneTx(ctx context.Context, txn bob.Tx, stmt postgres.Statement) error { + query, args := stmt.Sql() - return data, err + _, err := txn.QueryContext(ctx, query, args...) + return err +} +func ExecuteOne[T any](ctx context.Context, stmt postgres.Statement) (*T, error) { + query, args := stmt.Sql() + + row, err := PGInstance.PGXPool.Query(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("execute query: %w", err) + } + return pgx.CollectOneRow(row, pgx.RowToAddrOfStructByPos[T]) +} +func ExecuteOneTx[T any](ctx context.Context, txn bob.Tx, stmt postgres.Statement) (*T, error) { + query, args := stmt.Sql() + + result, err := scan.One(ctx, txn, scan.StructMapper[T](), query, args...) + return &result, err +} +func ExecuteMany[T any](ctx context.Context, stmt postgres.Statement) ([]*T, error) { + query, args := stmt.Sql() + + rows, err := PGInstance.PGXPool.Query(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("execute query: %w", err) + } + return pgx.CollectRows(rows, pgx.RowToAddrOfStructByPos[T]) } func doMigrations(connection_string string) error { log.Debug().Str("dsn", connection_string).Msg("Connecting to database") diff --git a/db/dberrors/arcgis.account.bob.go b/db/dberrors/arcgis.account.bob.go deleted file mode 100644 index dbd59c6b..00000000 --- a/db/dberrors/arcgis.account.bob.go +++ /dev/null @@ -1,17 +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 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.address_mapping.bob.go b/db/dberrors/arcgis.address_mapping.bob.go deleted file mode 100644 index 530221b6..00000000 --- a/db/dberrors/arcgis.address_mapping.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisAddressMappingErrors = &arcgisAddressMappingErrors{ - ErrUniqueAddressMappingPkey: &UniqueConstraintError{ - schema: "arcgis", - table: "address_mapping", - columns: []string{"organization_id", "destination"}, - s: "address_mapping_pkey", - }, -} - -type arcgisAddressMappingErrors struct { - ErrUniqueAddressMappingPkey *UniqueConstraintError -} diff --git a/db/dberrors/arcgis.layer.bob.go b/db/dberrors/arcgis.layer.bob.go deleted file mode 100644 index f07d57e6..00000000 --- a/db/dberrors/arcgis.layer.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisLayerErrors = &arcgisLayerErrors{ - ErrUniqueLayerPkey: &UniqueConstraintError{ - schema: "arcgis", - table: "layer", - columns: []string{"feature_service_item_id", "index_"}, - s: "layer_pkey", - }, -} - -type arcgisLayerErrors struct { - ErrUniqueLayerPkey *UniqueConstraintError -} diff --git a/db/dberrors/arcgis.layer_field.bob.go b/db/dberrors/arcgis.layer_field.bob.go deleted file mode 100644 index 5fb95136..00000000 --- a/db/dberrors/arcgis.layer_field.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisLayerFieldErrors = &arcgisLayerFieldErrors{ - ErrUniqueLayerFieldPkey: &UniqueConstraintError{ - schema: "arcgis", - table: "layer_field", - columns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - s: "layer_field_pkey", - }, -} - -type arcgisLayerFieldErrors struct { - ErrUniqueLayerFieldPkey *UniqueConstraintError -} diff --git a/db/dberrors/arcgis.oauth_token.bob.go b/db/dberrors/arcgis.oauth_token.bob.go deleted file mode 100644 index 0caef41d..00000000 --- a/db/dberrors/arcgis.oauth_token.bob.go +++ /dev/null @@ -1,17 +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 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.parcel_mapping.bob.go b/db/dberrors/arcgis.parcel_mapping.bob.go deleted file mode 100644 index 8d10a16c..00000000 --- a/db/dberrors/arcgis.parcel_mapping.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisParcelMappingErrors = &arcgisParcelMappingErrors{ - ErrUniqueParcelMappingPkey: &UniqueConstraintError{ - schema: "arcgis", - table: "parcel_mapping", - columns: []string{"organization_id", "destination"}, - s: "parcel_mapping_pkey", - }, -} - -type arcgisParcelMappingErrors struct { - ErrUniqueParcelMappingPkey *UniqueConstraintError -} diff --git a/db/dberrors/arcgis.service_feature.bob.go b/db/dberrors/arcgis.service_feature.bob.go deleted file mode 100644 index fb4e1d6c..00000000 --- a/db/dberrors/arcgis.service_feature.bob.go +++ /dev/null @@ -1,17 +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 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 deleted file mode 100644 index 695fb572..00000000 --- a/db/dberrors/arcgis.service_map.bob.go +++ /dev/null @@ -1,17 +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 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/arcgis.user_.bob.go b/db/dberrors/arcgis.user_.bob.go deleted file mode 100644 index ecdd2bf4..00000000 --- a/db/dberrors/arcgis.user_.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisUserErrors = &arcgisuserErrors{ - ErrUniqueUser_Pkey: &UniqueConstraintError{ - schema: "arcgis", - table: "user_", - columns: []string{"id"}, - s: "user__pkey", - }, -} - -type arcgisuserErrors struct { - ErrUniqueUser_Pkey *UniqueConstraintError -} diff --git a/db/dberrors/arcgis.user_privilege.bob.go b/db/dberrors/arcgis.user_privilege.bob.go deleted file mode 100644 index 1539a638..00000000 --- a/db/dberrors/arcgis.user_privilege.bob.go +++ /dev/null @@ -1,17 +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 dberrors - -var ArcgisUserPrivilegeErrors = &arcgisUserPrivilegeErrors{ - ErrUniqueUserPrivilegePkey: &UniqueConstraintError{ - schema: "arcgis", - table: "user_privilege", - columns: []string{"user_id", "privilege"}, - s: "user_privilege_pkey", - }, -} - -type arcgisUserPrivilegeErrors struct { - ErrUniqueUserPrivilegePkey *UniqueConstraintError -} diff --git a/db/dbinfo/arcgis.account.bob.go b/db/dbinfo/arcgis.account.bob.go deleted file mode 100644 index 8abee1e2..00000000 --- a/db/dbinfo/arcgis.account.bob.go +++ /dev/null @@ -1,177 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var 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.address_mapping.bob.go b/db/dbinfo/arcgis.address_mapping.bob.go deleted file mode 100644 index 29f83022..00000000 --- a/db/dbinfo/arcgis.address_mapping.bob.go +++ /dev/null @@ -1,162 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisAddressMappings = Table[ - arcgisAddressMappingColumns, - arcgisAddressMappingIndexes, - arcgisAddressMappingForeignKeys, - arcgisAddressMappingUniques, - arcgisAddressMappingChecks, -]{ - Schema: "arcgis", - Name: "address_mapping", - Columns: arcgisAddressMappingColumns{ - Destination: column{ - Name: "destination", - DBType: "arcgis.mappingdestinationaddress", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerFeatureServiceItemID: column{ - Name: "layer_feature_service_item_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerIndex: column{ - Name: "layer_index", - DBType: "integer", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerFieldName: column{ - Name: "layer_field_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, - }, - }, - Indexes: arcgisAddressMappingIndexes{ - AddressMappingPkey: index{ - Type: "btree", - Name: "address_mapping_pkey", - Columns: []indexColumn{ - { - Name: "organization_id", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "destination", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - }, - Unique: true, - Comment: "", - NullsFirst: []bool{false, false}, - NullsDistinct: false, - Where: "", - Include: []string{}, - }, - }, - PrimaryKey: &constraint{ - Name: "address_mapping_pkey", - Columns: []string{"organization_id", "destination"}, - Comment: "", - }, - ForeignKeys: arcgisAddressMappingForeignKeys{ - ArcgisAddressMappingAddressMappingLayerFeatureServiceItemIDLayerIndexFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.address_mapping.address_mapping_layer_feature_service_item_id_layer_index__fkey", - Columns: []string{"layer_feature_service_item_id", "layer_index", "layer_field_name"}, - Comment: "", - }, - ForeignTable: "arcgis.layer_field", - ForeignColumns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - }, - ArcgisAddressMappingAddressMappingOrganizationIDFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.address_mapping.address_mapping_organization_id_fkey", - Columns: []string{"organization_id"}, - Comment: "", - }, - ForeignTable: "organization", - ForeignColumns: []string{"id"}, - }, - }, - - Comment: "", -} - -type arcgisAddressMappingColumns struct { - Destination column - LayerFeatureServiceItemID column - LayerIndex column - LayerFieldName column - OrganizationID column -} - -func (c arcgisAddressMappingColumns) AsSlice() []column { - return []column{ - c.Destination, c.LayerFeatureServiceItemID, c.LayerIndex, c.LayerFieldName, c.OrganizationID, - } -} - -type arcgisAddressMappingIndexes struct { - AddressMappingPkey index -} - -func (i arcgisAddressMappingIndexes) AsSlice() []index { - return []index{ - i.AddressMappingPkey, - } -} - -type arcgisAddressMappingForeignKeys struct { - ArcgisAddressMappingAddressMappingLayerFeatureServiceItemIDLayerIndexFkey foreignKey - ArcgisAddressMappingAddressMappingOrganizationIDFkey foreignKey -} - -func (f arcgisAddressMappingForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisAddressMappingAddressMappingLayerFeatureServiceItemIDLayerIndexFkey, f.ArcgisAddressMappingAddressMappingOrganizationIDFkey, - } -} - -type arcgisAddressMappingUniques struct{} - -func (u arcgisAddressMappingUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisAddressMappingChecks struct{} - -func (c arcgisAddressMappingChecks) AsSlice() []check { - return []check{} -} diff --git a/db/dbinfo/arcgis.layer.bob.go b/db/dbinfo/arcgis.layer.bob.go deleted file mode 100644 index a5f2173b..00000000 --- a/db/dbinfo/arcgis.layer.bob.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisLayers = Table[ - arcgisLayerColumns, - arcgisLayerIndexes, - arcgisLayerForeignKeys, - arcgisLayerUniques, - arcgisLayerChecks, -]{ - Schema: "arcgis", - Name: "layer", - Columns: arcgisLayerColumns{ - Extent: column{ - Name: "extent", - DBType: "box2d", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - FeatureServiceItemID: column{ - Name: "feature_service_item_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Index: column{ - Name: "index_", - DBType: "integer", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - }, - Indexes: arcgisLayerIndexes{ - LayerPkey: index{ - Type: "btree", - Name: "layer_pkey", - Columns: []indexColumn{ - { - Name: "feature_service_item_id", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "index_", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - }, - Unique: true, - Comment: "", - NullsFirst: []bool{false, false}, - NullsDistinct: false, - Where: "", - Include: []string{}, - }, - }, - PrimaryKey: &constraint{ - Name: "layer_pkey", - Columns: []string{"feature_service_item_id", "index_"}, - Comment: "", - }, - ForeignKeys: arcgisLayerForeignKeys{ - ArcgisLayerLayerFeatureServiceItemIDFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.layer.layer_feature_service_item_id_fkey", - Columns: []string{"feature_service_item_id"}, - Comment: "", - }, - ForeignTable: "arcgis.service_feature", - ForeignColumns: []string{"item_id"}, - }, - }, - - Comment: "", -} - -type arcgisLayerColumns struct { - Extent column - FeatureServiceItemID column - Index column -} - -func (c arcgisLayerColumns) AsSlice() []column { - return []column{ - c.Extent, c.FeatureServiceItemID, c.Index, - } -} - -type arcgisLayerIndexes struct { - LayerPkey index -} - -func (i arcgisLayerIndexes) AsSlice() []index { - return []index{ - i.LayerPkey, - } -} - -type arcgisLayerForeignKeys struct { - ArcgisLayerLayerFeatureServiceItemIDFkey foreignKey -} - -func (f arcgisLayerForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisLayerLayerFeatureServiceItemIDFkey, - } -} - -type arcgisLayerUniques struct{} - -func (u arcgisLayerUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisLayerChecks struct{} - -func (c arcgisLayerChecks) AsSlice() []check { - return []check{} -} diff --git a/db/dbinfo/arcgis.layer_field.bob.go b/db/dbinfo/arcgis.layer_field.bob.go deleted file mode 100644 index 4a1207d5..00000000 --- a/db/dbinfo/arcgis.layer_field.bob.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisLayerFields = Table[ - arcgisLayerFieldColumns, - arcgisLayerFieldIndexes, - arcgisLayerFieldForeignKeys, - arcgisLayerFieldUniques, - arcgisLayerFieldChecks, -]{ - Schema: "arcgis", - Name: "layer_field", - Columns: arcgisLayerFieldColumns{ - LayerFeatureServiceItemID: column{ - Name: "layer_feature_service_item_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerIndex: column{ - Name: "layer_index", - DBType: "integer", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Name: column{ - Name: "name", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Type: column{ - Name: "type_", - DBType: "arcgis.fieldtype", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - }, - Indexes: arcgisLayerFieldIndexes{ - LayerFieldPkey: index{ - Type: "btree", - Name: "layer_field_pkey", - Columns: []indexColumn{ - { - Name: "layer_feature_service_item_id", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "layer_index", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "name", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - }, - Unique: true, - Comment: "", - NullsFirst: []bool{false, false, false}, - NullsDistinct: false, - Where: "", - Include: []string{}, - }, - }, - PrimaryKey: &constraint{ - Name: "layer_field_pkey", - Columns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - Comment: "", - }, - ForeignKeys: arcgisLayerFieldForeignKeys{ - ArcgisLayerFieldLayerFieldLayerFeatureServiceItemIDLayerIndexFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey", - Columns: []string{"layer_feature_service_item_id", "layer_index"}, - Comment: "", - }, - ForeignTable: "arcgis.layer", - ForeignColumns: []string{"feature_service_item_id", "index_"}, - }, - }, - - Comment: "", -} - -type arcgisLayerFieldColumns struct { - LayerFeatureServiceItemID column - LayerIndex column - Name column - Type column -} - -func (c arcgisLayerFieldColumns) AsSlice() []column { - return []column{ - c.LayerFeatureServiceItemID, c.LayerIndex, c.Name, c.Type, - } -} - -type arcgisLayerFieldIndexes struct { - LayerFieldPkey index -} - -func (i arcgisLayerFieldIndexes) AsSlice() []index { - return []index{ - i.LayerFieldPkey, - } -} - -type arcgisLayerFieldForeignKeys struct { - ArcgisLayerFieldLayerFieldLayerFeatureServiceItemIDLayerIndexFkey foreignKey -} - -func (f arcgisLayerFieldForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisLayerFieldLayerFieldLayerFeatureServiceItemIDLayerIndexFkey, - } -} - -type arcgisLayerFieldUniques struct{} - -func (u arcgisLayerFieldUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisLayerFieldChecks struct{} - -func (c arcgisLayerFieldChecks) AsSlice() []check { - return []check{} -} diff --git a/db/dbinfo/arcgis.oauth_token.bob.go b/db/dbinfo/arcgis.oauth_token.bob.go deleted file mode 100644 index b7202fc3..00000000 --- a/db/dbinfo/arcgis.oauth_token.bob.go +++ /dev/null @@ -1,227 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var 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.parcel_mapping.bob.go b/db/dbinfo/arcgis.parcel_mapping.bob.go deleted file mode 100644 index 30433a27..00000000 --- a/db/dbinfo/arcgis.parcel_mapping.bob.go +++ /dev/null @@ -1,162 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisParcelMappings = Table[ - arcgisParcelMappingColumns, - arcgisParcelMappingIndexes, - arcgisParcelMappingForeignKeys, - arcgisParcelMappingUniques, - arcgisParcelMappingChecks, -]{ - Schema: "arcgis", - Name: "parcel_mapping", - Columns: arcgisParcelMappingColumns{ - Destination: column{ - Name: "destination", - DBType: "arcgis.mappingdestinationparcel", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerFeatureServiceItemID: column{ - Name: "layer_feature_service_item_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerIndex: column{ - Name: "layer_index", - DBType: "integer", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - LayerFieldName: column{ - Name: "layer_field_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, - }, - }, - Indexes: arcgisParcelMappingIndexes{ - ParcelMappingPkey: index{ - Type: "btree", - Name: "parcel_mapping_pkey", - Columns: []indexColumn{ - { - Name: "organization_id", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "destination", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - }, - Unique: true, - Comment: "", - NullsFirst: []bool{false, false}, - NullsDistinct: false, - Where: "", - Include: []string{}, - }, - }, - PrimaryKey: &constraint{ - Name: "parcel_mapping_pkey", - Columns: []string{"organization_id", "destination"}, - Comment: "", - }, - ForeignKeys: arcgisParcelMappingForeignKeys{ - ArcgisParcelMappingParcelMappingLayerFeatureServiceItemIDLayerIndexLFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.parcel_mapping.parcel_mapping_layer_feature_service_item_id_layer_index_l_fkey", - Columns: []string{"layer_feature_service_item_id", "layer_index", "layer_field_name"}, - Comment: "", - }, - ForeignTable: "arcgis.layer_field", - ForeignColumns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - }, - ArcgisParcelMappingParcelMappingOrganizationIDFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.parcel_mapping.parcel_mapping_organization_id_fkey", - Columns: []string{"organization_id"}, - Comment: "", - }, - ForeignTable: "organization", - ForeignColumns: []string{"id"}, - }, - }, - - Comment: "", -} - -type arcgisParcelMappingColumns struct { - Destination column - LayerFeatureServiceItemID column - LayerIndex column - LayerFieldName column - OrganizationID column -} - -func (c arcgisParcelMappingColumns) AsSlice() []column { - return []column{ - c.Destination, c.LayerFeatureServiceItemID, c.LayerIndex, c.LayerFieldName, c.OrganizationID, - } -} - -type arcgisParcelMappingIndexes struct { - ParcelMappingPkey index -} - -func (i arcgisParcelMappingIndexes) AsSlice() []index { - return []index{ - i.ParcelMappingPkey, - } -} - -type arcgisParcelMappingForeignKeys struct { - ArcgisParcelMappingParcelMappingLayerFeatureServiceItemIDLayerIndexLFkey foreignKey - ArcgisParcelMappingParcelMappingOrganizationIDFkey foreignKey -} - -func (f arcgisParcelMappingForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisParcelMappingParcelMappingLayerFeatureServiceItemIDLayerIndexLFkey, f.ArcgisParcelMappingParcelMappingOrganizationIDFkey, - } -} - -type arcgisParcelMappingUniques struct{} - -func (u arcgisParcelMappingUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisParcelMappingChecks struct{} - -func (c arcgisParcelMappingChecks) AsSlice() []check { - return []check{} -} diff --git a/db/dbinfo/arcgis.service_feature.bob.go b/db/dbinfo/arcgis.service_feature.bob.go deleted file mode 100644 index 96a3e142..00000000 --- a/db/dbinfo/arcgis.service_feature.bob.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var 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 deleted file mode 100644 index 911ca46c..00000000 --- a/db/dbinfo/arcgis.service_map.bob.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var 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/arcgis.user_.bob.go b/db/dbinfo/arcgis.user_.bob.go deleted file mode 100644 index 0e70ba47..00000000 --- a/db/dbinfo/arcgis.user_.bob.go +++ /dev/null @@ -1,237 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisUsers = Table[ - arcgisuserColumns, - arcgisuserIndexes, - arcgisuserForeignKeys, - arcgisuserUniques, - arcgisuserChecks, -]{ - Schema: "arcgis", - Name: "user_", - Columns: arcgisuserColumns{ - Access: column{ - Name: "access", - DBType: "text", - 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, - }, - Email: column{ - Name: "email", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - FullName: column{ - Name: "full_name", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - ID: column{ - Name: "id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Level: column{ - Name: "level", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - OrgID: column{ - Name: "org_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - PublicUserID: column{ - Name: "public_user_id", - DBType: "integer", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Region: column{ - Name: "region", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Role: column{ - Name: "role", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - RoleID: column{ - Name: "role_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Username: column{ - Name: "username", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - UserLicenseTypeID: column{ - Name: "user_license_type_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - UserType: column{ - Name: "user_type", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - }, - Indexes: arcgisuserIndexes{ - UserPkey: index{ - Type: "btree", - Name: "user__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: "user__pkey", - Columns: []string{"id"}, - Comment: "", - }, - ForeignKeys: arcgisuserForeignKeys{ - ArcgisUserUserPublicUserIDFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.user_.user__public_user_id_fkey", - Columns: []string{"public_user_id"}, - Comment: "", - }, - ForeignTable: "user_", - ForeignColumns: []string{"id"}, - }, - }, - - Comment: "", -} - -type arcgisuserColumns struct { - Access column - Created column - Email column - FullName column - ID column - Level column - OrgID column - PublicUserID column - Region column - Role column - RoleID column - Username column - UserLicenseTypeID column - UserType column -} - -func (c arcgisuserColumns) AsSlice() []column { - return []column{ - c.Access, c.Created, c.Email, c.FullName, c.ID, c.Level, c.OrgID, c.PublicUserID, c.Region, c.Role, c.RoleID, c.Username, c.UserLicenseTypeID, c.UserType, - } -} - -type arcgisuserIndexes struct { - UserPkey index -} - -func (i arcgisuserIndexes) AsSlice() []index { - return []index{ - i.UserPkey, - } -} - -type arcgisuserForeignKeys struct { - ArcgisUserUserPublicUserIDFkey foreignKey -} - -func (f arcgisuserForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisUserUserPublicUserIDFkey, - } -} - -type arcgisuserUniques struct{} - -func (u arcgisuserUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisuserChecks struct{} - -func (c arcgisuserChecks) AsSlice() []check { - return []check{} -} diff --git a/db/dbinfo/arcgis.user_privilege.bob.go b/db/dbinfo/arcgis.user_privilege.bob.go deleted file mode 100644 index 56de66b9..00000000 --- a/db/dbinfo/arcgis.user_privilege.bob.go +++ /dev/null @@ -1,122 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package dbinfo - -import "github.com/aarondl/opt/null" - -var ArcgisUserPrivileges = Table[ - arcgisUserPrivilegeColumns, - arcgisUserPrivilegeIndexes, - arcgisUserPrivilegeForeignKeys, - arcgisUserPrivilegeUniques, - arcgisUserPrivilegeChecks, -]{ - Schema: "arcgis", - Name: "user_privilege", - Columns: arcgisUserPrivilegeColumns{ - UserID: column{ - Name: "user_id", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - Privilege: column{ - Name: "privilege", - DBType: "text", - Default: "", - Comment: "", - Nullable: false, - Generated: false, - AutoIncr: false, - }, - }, - Indexes: arcgisUserPrivilegeIndexes{ - UserPrivilegePkey: index{ - Type: "btree", - Name: "user_privilege_pkey", - Columns: []indexColumn{ - { - Name: "user_id", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - { - Name: "privilege", - Desc: null.FromCond(false, true), - IsExpression: false, - }, - }, - Unique: true, - Comment: "", - NullsFirst: []bool{false, false}, - NullsDistinct: false, - Where: "", - Include: []string{}, - }, - }, - PrimaryKey: &constraint{ - Name: "user_privilege_pkey", - Columns: []string{"user_id", "privilege"}, - Comment: "", - }, - ForeignKeys: arcgisUserPrivilegeForeignKeys{ - ArcgisUserPrivilegeUserPrivilegeUserIDFkey: foreignKey{ - constraint: constraint{ - Name: "arcgis.user_privilege.user_privilege_user_id_fkey", - Columns: []string{"user_id"}, - Comment: "", - }, - ForeignTable: "arcgis.user_", - ForeignColumns: []string{"id"}, - }, - }, - - Comment: "", -} - -type arcgisUserPrivilegeColumns struct { - UserID column - Privilege column -} - -func (c arcgisUserPrivilegeColumns) AsSlice() []column { - return []column{ - c.UserID, c.Privilege, - } -} - -type arcgisUserPrivilegeIndexes struct { - UserPrivilegePkey index -} - -func (i arcgisUserPrivilegeIndexes) AsSlice() []index { - return []index{ - i.UserPrivilegePkey, - } -} - -type arcgisUserPrivilegeForeignKeys struct { - ArcgisUserPrivilegeUserPrivilegeUserIDFkey foreignKey -} - -func (f arcgisUserPrivilegeForeignKeys) AsSlice() []foreignKey { - return []foreignKey{ - f.ArcgisUserPrivilegeUserPrivilegeUserIDFkey, - } -} - -type arcgisUserPrivilegeUniques struct{} - -func (u arcgisUserPrivilegeUniques) AsSlice() []constraint { - return []constraint{} -} - -type arcgisUserPrivilegeChecks struct{} - -func (c arcgisUserPrivilegeChecks) AsSlice() []check { - return []check{} -} diff --git a/db/enums/enums.bob.go b/db/enums/enums.bob.go index b370865d..c25ed42e 100644 --- a/db/enums/enums.bob.go +++ b/db/enums/enums.bob.go @@ -8,270 +8,6 @@ import ( "fmt" ) -// Enum values for ArcgisFieldtype -const ( - ArcgisFieldtypeEsrifieldtypesmallinteger ArcgisFieldtype = "esriFieldTypeSmallInteger" - ArcgisFieldtypeEsrifieldtypeinteger ArcgisFieldtype = "esriFieldTypeInteger" - ArcgisFieldtypeEsrifieldtypesingle ArcgisFieldtype = "esriFieldTypeSingle" - ArcgisFieldtypeEsrifieldtypedouble ArcgisFieldtype = "esriFieldTypeDouble" - ArcgisFieldtypeEsrifieldtypestring ArcgisFieldtype = "esriFieldTypeString" - ArcgisFieldtypeEsrifieldtypedate ArcgisFieldtype = "esriFieldTypeDate" - ArcgisFieldtypeEsrifieldtypeoid ArcgisFieldtype = "esriFieldTypeOID" - ArcgisFieldtypeEsrifieldtypegeometry ArcgisFieldtype = "esriFieldTypeGeometry" - ArcgisFieldtypeEsrifieldtypeblob ArcgisFieldtype = "esriFieldTypeBlob" - ArcgisFieldtypeEsrifieldtyperaster ArcgisFieldtype = "esriFieldTypeRaster" - ArcgisFieldtypeEsrifieldtypeguid ArcgisFieldtype = "esriFieldTypeGUID" - ArcgisFieldtypeEsrifieldtypeglobalid ArcgisFieldtype = "esriFieldTypeGlobalID" - ArcgisFieldtypeEsrifieldtypexml ArcgisFieldtype = "esriFieldTypeXML" - ArcgisFieldtypeEsrifieldtypebiginteger ArcgisFieldtype = "esriFieldTypeBigInteger" -) - -func AllArcgisFieldtype() []ArcgisFieldtype { - return []ArcgisFieldtype{ - ArcgisFieldtypeEsrifieldtypesmallinteger, - ArcgisFieldtypeEsrifieldtypeinteger, - ArcgisFieldtypeEsrifieldtypesingle, - ArcgisFieldtypeEsrifieldtypedouble, - ArcgisFieldtypeEsrifieldtypestring, - ArcgisFieldtypeEsrifieldtypedate, - ArcgisFieldtypeEsrifieldtypeoid, - ArcgisFieldtypeEsrifieldtypegeometry, - ArcgisFieldtypeEsrifieldtypeblob, - ArcgisFieldtypeEsrifieldtyperaster, - ArcgisFieldtypeEsrifieldtypeguid, - ArcgisFieldtypeEsrifieldtypeglobalid, - ArcgisFieldtypeEsrifieldtypexml, - ArcgisFieldtypeEsrifieldtypebiginteger, - } -} - -type ArcgisFieldtype string - -func (e ArcgisFieldtype) String() string { - return string(e) -} - -func (e ArcgisFieldtype) Valid() bool { - switch e { - case ArcgisFieldtypeEsrifieldtypesmallinteger, - ArcgisFieldtypeEsrifieldtypeinteger, - ArcgisFieldtypeEsrifieldtypesingle, - ArcgisFieldtypeEsrifieldtypedouble, - ArcgisFieldtypeEsrifieldtypestring, - ArcgisFieldtypeEsrifieldtypedate, - ArcgisFieldtypeEsrifieldtypeoid, - ArcgisFieldtypeEsrifieldtypegeometry, - ArcgisFieldtypeEsrifieldtypeblob, - ArcgisFieldtypeEsrifieldtyperaster, - ArcgisFieldtypeEsrifieldtypeguid, - ArcgisFieldtypeEsrifieldtypeglobalid, - ArcgisFieldtypeEsrifieldtypexml, - ArcgisFieldtypeEsrifieldtypebiginteger: - return true - default: - return false - } -} - -// useful when testing in other packages -func (e ArcgisFieldtype) All() []ArcgisFieldtype { - return AllArcgisFieldtype() -} - -func (e ArcgisFieldtype) MarshalText() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisFieldtype) UnmarshalText(text []byte) error { - return e.Scan(text) -} - -func (e ArcgisFieldtype) MarshalBinary() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisFieldtype) UnmarshalBinary(data []byte) error { - return e.Scan(data) -} - -func (e ArcgisFieldtype) Value() (driver.Value, error) { - return string(e), nil -} - -func (e *ArcgisFieldtype) Scan(value any) error { - switch x := value.(type) { - case string: - *e = ArcgisFieldtype(x) - case []byte: - *e = ArcgisFieldtype(x) - case nil: - return fmt.Errorf("cannot nil into ArcgisFieldtype") - default: - return fmt.Errorf("cannot scan type %T: %v", value, value) - } - - if !e.Valid() { - return fmt.Errorf("invalid ArcgisFieldtype value: %s", *e) - } - - return nil -} - -// Enum values for ArcgisMappingdestinationaddress -const ( - ArcgisMappingdestinationaddressCountry ArcgisMappingdestinationaddress = "country" - ArcgisMappingdestinationaddressLocality ArcgisMappingdestinationaddress = "locality" - ArcgisMappingdestinationaddressPostalCode ArcgisMappingdestinationaddress = "postal_code" - ArcgisMappingdestinationaddressStreet ArcgisMappingdestinationaddress = "street" - ArcgisMappingdestinationaddressUnit ArcgisMappingdestinationaddress = "unit" -) - -func AllArcgisMappingdestinationaddress() []ArcgisMappingdestinationaddress { - return []ArcgisMappingdestinationaddress{ - ArcgisMappingdestinationaddressCountry, - ArcgisMappingdestinationaddressLocality, - ArcgisMappingdestinationaddressPostalCode, - ArcgisMappingdestinationaddressStreet, - ArcgisMappingdestinationaddressUnit, - } -} - -type ArcgisMappingdestinationaddress string - -func (e ArcgisMappingdestinationaddress) String() string { - return string(e) -} - -func (e ArcgisMappingdestinationaddress) Valid() bool { - switch e { - case ArcgisMappingdestinationaddressCountry, - ArcgisMappingdestinationaddressLocality, - ArcgisMappingdestinationaddressPostalCode, - ArcgisMappingdestinationaddressStreet, - ArcgisMappingdestinationaddressUnit: - return true - default: - return false - } -} - -// useful when testing in other packages -func (e ArcgisMappingdestinationaddress) All() []ArcgisMappingdestinationaddress { - return AllArcgisMappingdestinationaddress() -} - -func (e ArcgisMappingdestinationaddress) MarshalText() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisMappingdestinationaddress) UnmarshalText(text []byte) error { - return e.Scan(text) -} - -func (e ArcgisMappingdestinationaddress) MarshalBinary() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisMappingdestinationaddress) UnmarshalBinary(data []byte) error { - return e.Scan(data) -} - -func (e ArcgisMappingdestinationaddress) Value() (driver.Value, error) { - return string(e), nil -} - -func (e *ArcgisMappingdestinationaddress) Scan(value any) error { - switch x := value.(type) { - case string: - *e = ArcgisMappingdestinationaddress(x) - case []byte: - *e = ArcgisMappingdestinationaddress(x) - case nil: - return fmt.Errorf("cannot nil into ArcgisMappingdestinationaddress") - default: - return fmt.Errorf("cannot scan type %T: %v", value, value) - } - - if !e.Valid() { - return fmt.Errorf("invalid ArcgisMappingdestinationaddress value: %s", *e) - } - - return nil -} - -// Enum values for ArcgisMappingdestinationparcel -const ( - ArcgisMappingdestinationparcelApn ArcgisMappingdestinationparcel = "apn" - ArcgisMappingdestinationparcelDescription ArcgisMappingdestinationparcel = "description" -) - -func AllArcgisMappingdestinationparcel() []ArcgisMappingdestinationparcel { - return []ArcgisMappingdestinationparcel{ - ArcgisMappingdestinationparcelApn, - ArcgisMappingdestinationparcelDescription, - } -} - -type ArcgisMappingdestinationparcel string - -func (e ArcgisMappingdestinationparcel) String() string { - return string(e) -} - -func (e ArcgisMappingdestinationparcel) Valid() bool { - switch e { - case ArcgisMappingdestinationparcelApn, - ArcgisMappingdestinationparcelDescription: - return true - default: - return false - } -} - -// useful when testing in other packages -func (e ArcgisMappingdestinationparcel) All() []ArcgisMappingdestinationparcel { - return AllArcgisMappingdestinationparcel() -} - -func (e ArcgisMappingdestinationparcel) MarshalText() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisMappingdestinationparcel) UnmarshalText(text []byte) error { - return e.Scan(text) -} - -func (e ArcgisMappingdestinationparcel) MarshalBinary() ([]byte, error) { - return []byte(e), nil -} - -func (e *ArcgisMappingdestinationparcel) UnmarshalBinary(data []byte) error { - return e.Scan(data) -} - -func (e ArcgisMappingdestinationparcel) Value() (driver.Value, error) { - return string(e), nil -} - -func (e *ArcgisMappingdestinationparcel) Scan(value any) error { - switch x := value.(type) { - case string: - *e = ArcgisMappingdestinationparcel(x) - case []byte: - *e = ArcgisMappingdestinationparcel(x) - case nil: - return fmt.Errorf("cannot nil into ArcgisMappingdestinationparcel") - default: - return fmt.Errorf("cannot scan type %T: %v", value, value) - } - - if !e.Valid() { - return fmt.Errorf("invalid ArcgisMappingdestinationparcel value: %s", *e) - } - - return nil -} - // Enum values for Arcgislicensetype const ( ArcgislicensetypeAdvancedut Arcgislicensetype = "advancedUT" diff --git a/db/jet/main.go b/db/jet/main.go index b47026a6..efb987b2 100644 --- a/db/jet/main.go +++ b/db/jet/main.go @@ -5,6 +5,7 @@ import ( "log" "os" + "github.com/Gleipnir-Technology/nidus-sync/db/types" "github.com/go-jet/jet/v2/generator/metadata" genpostgres "github.com/go-jet/jet/v2/generator/postgres" "github.com/go-jet/jet/v2/generator/template" @@ -12,11 +13,6 @@ import ( _ "github.com/lib/pq" ) -type Box2D struct { - X float64 - Y float64 -} - var schemas []string = []string{ "arcgis", "stadia", @@ -29,7 +25,7 @@ func customTemplate() template.Template { defaultTableModelField := template.DefaultTableModelField(column) //log.Printf("'%s' '%s' '%s'", table.Name, column.Name, column.DataType.Name) if column.Name == "extent" && column.DataType.Name == "box2d" { - defaultTableModelField.Type = template.NewType(Box2D{}) + defaultTableModelField.Type = template.NewType(types.Box2D{}) } return defaultTableModelField }) diff --git a/db/models/arcgis.account.bob.go b/db/models/arcgis.account.bob.go deleted file mode 100644 index 17a78c0e..00000000 --- a/db/models/arcgis.account.bob.go +++ /dev/null @@ -1,1445 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/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:"-" ` -} - -// 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 -} diff --git a/db/models/arcgis.address_mapping.bob.go b/db/models/arcgis.address_mapping.bob.go deleted file mode 100644 index f62de49e..00000000 --- a/db/models/arcgis.address_mapping.bob.go +++ /dev/null @@ -1,837 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" - "github.com/aarondl/opt/omit" -) - -// ArcgisAddressMapping is an object representing the database table. -type ArcgisAddressMapping struct { - Destination enums.ArcgisMappingdestinationaddress `db:"destination,pk" ` - LayerFeatureServiceItemID string `db:"layer_feature_service_item_id" ` - LayerIndex int32 `db:"layer_index" ` - LayerFieldName string `db:"layer_field_name" ` - OrganizationID int32 `db:"organization_id,pk" ` - - R arcgisAddressMappingR `db:"-" ` -} - -// ArcgisAddressMappingSlice is an alias for a slice of pointers to ArcgisAddressMapping. -// This should almost always be used instead of []*ArcgisAddressMapping. -type ArcgisAddressMappingSlice []*ArcgisAddressMapping - -// ArcgisAddressMappings contains methods to work with the address_mapping table -var ArcgisAddressMappings = psql.NewTablex[*ArcgisAddressMapping, ArcgisAddressMappingSlice, *ArcgisAddressMappingSetter]("arcgis", "address_mapping", buildArcgisAddressMappingColumns("arcgis.address_mapping")) - -// ArcgisAddressMappingsQuery is a query on the address_mapping table -type ArcgisAddressMappingsQuery = *psql.ViewQuery[*ArcgisAddressMapping, ArcgisAddressMappingSlice] - -// arcgisAddressMappingR is where relationships are stored. -type arcgisAddressMappingR struct { - LayerField *ArcgisLayerField // arcgis.address_mapping.address_mapping_layer_feature_service_item_id_layer_index__fkey - Organization *Organization // arcgis.address_mapping.address_mapping_organization_id_fkey -} - -func buildArcgisAddressMappingColumns(alias string) arcgisAddressMappingColumns { - return arcgisAddressMappingColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "destination", "layer_feature_service_item_id", "layer_index", "layer_field_name", "organization_id", - ).WithParent("arcgis.address_mapping"), - tableAlias: alias, - Destination: psql.Quote(alias, "destination"), - LayerFeatureServiceItemID: psql.Quote(alias, "layer_feature_service_item_id"), - LayerIndex: psql.Quote(alias, "layer_index"), - LayerFieldName: psql.Quote(alias, "layer_field_name"), - OrganizationID: psql.Quote(alias, "organization_id"), - } -} - -type arcgisAddressMappingColumns struct { - expr.ColumnsExpr - tableAlias string - Destination psql.Expression - LayerFeatureServiceItemID psql.Expression - LayerIndex psql.Expression - LayerFieldName psql.Expression - OrganizationID psql.Expression -} - -func (c arcgisAddressMappingColumns) Alias() string { - return c.tableAlias -} - -func (arcgisAddressMappingColumns) AliasedAs(alias string) arcgisAddressMappingColumns { - return buildArcgisAddressMappingColumns(alias) -} - -// ArcgisAddressMappingSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisAddressMappingSetter struct { - Destination omit.Val[enums.ArcgisMappingdestinationaddress] `db:"destination,pk" ` - LayerFeatureServiceItemID omit.Val[string] `db:"layer_feature_service_item_id" ` - LayerIndex omit.Val[int32] `db:"layer_index" ` - LayerFieldName omit.Val[string] `db:"layer_field_name" ` - OrganizationID omit.Val[int32] `db:"organization_id,pk" ` -} - -func (s ArcgisAddressMappingSetter) SetColumns() []string { - vals := make([]string, 0, 5) - if s.Destination.IsValue() { - vals = append(vals, "destination") - } - if s.LayerFeatureServiceItemID.IsValue() { - vals = append(vals, "layer_feature_service_item_id") - } - if s.LayerIndex.IsValue() { - vals = append(vals, "layer_index") - } - if s.LayerFieldName.IsValue() { - vals = append(vals, "layer_field_name") - } - if s.OrganizationID.IsValue() { - vals = append(vals, "organization_id") - } - return vals -} - -func (s ArcgisAddressMappingSetter) Overwrite(t *ArcgisAddressMapping) { - if s.Destination.IsValue() { - t.Destination = s.Destination.MustGet() - } - if s.LayerFeatureServiceItemID.IsValue() { - t.LayerFeatureServiceItemID = s.LayerFeatureServiceItemID.MustGet() - } - if s.LayerIndex.IsValue() { - t.LayerIndex = s.LayerIndex.MustGet() - } - if s.LayerFieldName.IsValue() { - t.LayerFieldName = s.LayerFieldName.MustGet() - } - if s.OrganizationID.IsValue() { - t.OrganizationID = s.OrganizationID.MustGet() - } -} - -func (s *ArcgisAddressMappingSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisAddressMappings.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.Destination.IsValue() { - vals[0] = psql.Arg(s.Destination.MustGet()) - } else { - vals[0] = psql.Raw("DEFAULT") - } - - if s.LayerFeatureServiceItemID.IsValue() { - vals[1] = psql.Arg(s.LayerFeatureServiceItemID.MustGet()) - } else { - vals[1] = psql.Raw("DEFAULT") - } - - if s.LayerIndex.IsValue() { - vals[2] = psql.Arg(s.LayerIndex.MustGet()) - } else { - vals[2] = psql.Raw("DEFAULT") - } - - if s.LayerFieldName.IsValue() { - vals[3] = psql.Arg(s.LayerFieldName.MustGet()) - } else { - vals[3] = psql.Raw("DEFAULT") - } - - if s.OrganizationID.IsValue() { - vals[4] = psql.Arg(s.OrganizationID.MustGet()) - } else { - vals[4] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisAddressMappingSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisAddressMappingSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 5) - - if s.Destination.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "destination")...), - psql.Arg(s.Destination), - }}) - } - - if s.LayerFeatureServiceItemID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_feature_service_item_id")...), - psql.Arg(s.LayerFeatureServiceItemID), - }}) - } - - if s.LayerIndex.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_index")...), - psql.Arg(s.LayerIndex), - }}) - } - - if s.LayerFieldName.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_field_name")...), - psql.Arg(s.LayerFieldName), - }}) - } - - if s.OrganizationID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "organization_id")...), - psql.Arg(s.OrganizationID), - }}) - } - - return exprs -} - -// FindArcgisAddressMapping retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisAddressMapping(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, DestinationPK enums.ArcgisMappingdestinationaddress, cols ...string) (*ArcgisAddressMapping, error) { - if len(cols) == 0 { - return ArcgisAddressMappings.Query( - sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - ).One(ctx, exec) - } - - return ArcgisAddressMappings.Query( - sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - sm.Columns(ArcgisAddressMappings.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisAddressMappingExists checks the presence of a single record by primary key -func ArcgisAddressMappingExists(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, DestinationPK enums.ArcgisMappingdestinationaddress) (bool, error) { - return ArcgisAddressMappings.Query( - sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisAddressMapping is retrieved from the database -func (o *ArcgisAddressMapping) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisAddressMappings.AfterSelectHooks.RunHooks(ctx, exec, ArcgisAddressMappingSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisAddressMappings.AfterInsertHooks.RunHooks(ctx, exec, ArcgisAddressMappingSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisAddressMappings.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisAddressMappingSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisAddressMappings.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisAddressMappingSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisAddressMapping -func (o *ArcgisAddressMapping) primaryKeyVals() bob.Expression { - return psql.ArgGroup( - o.OrganizationID, - o.Destination, - ) -} - -func (o *ArcgisAddressMapping) pkEQ() dialect.Expression { - return psql.Group(psql.Quote("arcgis.address_mapping", "organization_id"), psql.Quote("arcgis.address_mapping", "destination")).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 ArcgisAddressMapping -func (o *ArcgisAddressMapping) Update(ctx context.Context, exec bob.Executor, s *ArcgisAddressMappingSetter) error { - v, err := ArcgisAddressMappings.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 ArcgisAddressMapping record with an executor -func (o *ArcgisAddressMapping) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisAddressMappings.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisAddressMapping using the executor -func (o *ArcgisAddressMapping) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisAddressMappings.Query( - sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(o.OrganizationID))), - sm.Where(ArcgisAddressMappings.Columns.Destination.EQ(psql.Arg(o.Destination))), - ).One(ctx, exec) - if err != nil { - return err - } - o2.R = o.R - *o = *o2 - - return nil -} - -// AfterQueryHook is called after ArcgisAddressMappingSlice is retrieved from the database -func (o ArcgisAddressMappingSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisAddressMappings.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisAddressMappings.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisAddressMappings.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisAddressMappings.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisAddressMappingSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Group(psql.Quote("arcgis.address_mapping", "organization_id"), psql.Quote("arcgis.address_mapping", "destination")).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 ArcgisAddressMappingSlice) copyMatchingRows(from ...*ArcgisAddressMapping) { - for i, old := range o { - for _, new := range from { - if new.OrganizationID != old.OrganizationID { - continue - } - if new.Destination != old.Destination { - continue - } - new.R = old.R - o[i] = new - break - } - } -} - -// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" -func (o ArcgisAddressMappingSlice) 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 ArcgisAddressMappings.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 *ArcgisAddressMapping: - o.copyMatchingRows(retrieved) - case []*ArcgisAddressMapping: - o.copyMatchingRows(retrieved...) - case ArcgisAddressMappingSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisAddressMapping or a slice of ArcgisAddressMapping - // then run the AfterUpdateHooks on the slice - _, err = ArcgisAddressMappings.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisAddressMappingSlice) 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 ArcgisAddressMappings.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 *ArcgisAddressMapping: - o.copyMatchingRows(retrieved) - case []*ArcgisAddressMapping: - o.copyMatchingRows(retrieved...) - case ArcgisAddressMappingSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisAddressMapping or a slice of ArcgisAddressMapping - // then run the AfterDeleteHooks on the slice - _, err = ArcgisAddressMappings.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisAddressMappingSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisAddressMappingSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisAddressMappings.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisAddressMappingSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisAddressMappings.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisAddressMappingSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisAddressMappings.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// LayerField starts a query for related objects on arcgis.layer_field -func (o *ArcgisAddressMapping) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - return ArcgisLayerFields.Query(append(mods, - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(o.LayerFieldName))), - )...) -} - -func (os ArcgisAddressMappingSlice) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkLayerIndex := make(pgtypes.Array[int32], 0, len(os)) - - pkLayerFieldName := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID) - pkLayerIndex = append(pkLayerIndex, o.LayerIndex) - pkLayerFieldName = append(pkLayerFieldName, o.LayerFieldName) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFieldName), "text[]")), - )) - - return ArcgisLayerFields.Query(append(mods, - sm.Where(psql.Group(ArcgisLayerFields.Columns.LayerFeatureServiceItemID, ArcgisLayerFields.Columns.LayerIndex, ArcgisLayerFields.Columns.Name).OP("IN", PKArgExpr)), - )...) -} - -// Organization starts a query for related objects on organization -func (o *ArcgisAddressMapping) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { - return Organizations.Query(append(mods, - sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))), - )...) -} - -func (os ArcgisAddressMappingSlice) 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)), - )...) -} - -func attachArcgisAddressMappingLayerField0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMapping0 *ArcgisAddressMapping, arcgisLayerField1 *ArcgisLayerField) (*ArcgisAddressMapping, error) { - setter := &ArcgisAddressMappingSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayerField1.LayerFeatureServiceItemID), - LayerIndex: omit.From(arcgisLayerField1.LayerIndex), - LayerFieldName: omit.From(arcgisLayerField1.Name), - } - - err := arcgisAddressMapping0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisAddressMappingLayerField0: %w", err) - } - - return arcgisAddressMapping0, nil -} - -func (arcgisAddressMapping0 *ArcgisAddressMapping) InsertLayerField(ctx context.Context, exec bob.Executor, related *ArcgisLayerFieldSetter) error { - var err error - - arcgisLayerField1, err := ArcgisLayerFields.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachArcgisAddressMappingLayerField0(ctx, exec, 1, arcgisAddressMapping0, arcgisLayerField1) - if err != nil { - return err - } - - arcgisAddressMapping0.R.LayerField = arcgisLayerField1 - - arcgisLayerField1.R.AddressMappings = append(arcgisLayerField1.R.AddressMappings, arcgisAddressMapping0) - - return nil -} - -func (arcgisAddressMapping0 *ArcgisAddressMapping) AttachLayerField(ctx context.Context, exec bob.Executor, arcgisLayerField1 *ArcgisLayerField) error { - var err error - - _, err = attachArcgisAddressMappingLayerField0(ctx, exec, 1, arcgisAddressMapping0, arcgisLayerField1) - if err != nil { - return err - } - - arcgisAddressMapping0.R.LayerField = arcgisLayerField1 - - arcgisLayerField1.R.AddressMappings = append(arcgisLayerField1.R.AddressMappings, arcgisAddressMapping0) - - return nil -} - -func attachArcgisAddressMappingOrganization0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMapping0 *ArcgisAddressMapping, organization1 *Organization) (*ArcgisAddressMapping, error) { - setter := &ArcgisAddressMappingSetter{ - OrganizationID: omit.From(organization1.ID), - } - - err := arcgisAddressMapping0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisAddressMappingOrganization0: %w", err) - } - - return arcgisAddressMapping0, nil -} - -func (arcgisAddressMapping0 *ArcgisAddressMapping) 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 = attachArcgisAddressMappingOrganization0(ctx, exec, 1, arcgisAddressMapping0, organization1) - if err != nil { - return err - } - - arcgisAddressMapping0.R.Organization = organization1 - - organization1.R.AddressMappings = append(organization1.R.AddressMappings, arcgisAddressMapping0) - - return nil -} - -func (arcgisAddressMapping0 *ArcgisAddressMapping) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error { - var err error - - _, err = attachArcgisAddressMappingOrganization0(ctx, exec, 1, arcgisAddressMapping0, organization1) - if err != nil { - return err - } - - arcgisAddressMapping0.R.Organization = organization1 - - organization1.R.AddressMappings = append(organization1.R.AddressMappings, arcgisAddressMapping0) - - return nil -} - -type arcgisAddressMappingWhere[Q psql.Filterable] struct { - Destination psql.WhereMod[Q, enums.ArcgisMappingdestinationaddress] - LayerFeatureServiceItemID psql.WhereMod[Q, string] - LayerIndex psql.WhereMod[Q, int32] - LayerFieldName psql.WhereMod[Q, string] - OrganizationID psql.WhereMod[Q, int32] -} - -func (arcgisAddressMappingWhere[Q]) AliasedAs(alias string) arcgisAddressMappingWhere[Q] { - return buildArcgisAddressMappingWhere[Q](buildArcgisAddressMappingColumns(alias)) -} - -func buildArcgisAddressMappingWhere[Q psql.Filterable](cols arcgisAddressMappingColumns) arcgisAddressMappingWhere[Q] { - return arcgisAddressMappingWhere[Q]{ - Destination: psql.Where[Q, enums.ArcgisMappingdestinationaddress](cols.Destination), - LayerFeatureServiceItemID: psql.Where[Q, string](cols.LayerFeatureServiceItemID), - LayerIndex: psql.Where[Q, int32](cols.LayerIndex), - LayerFieldName: psql.Where[Q, string](cols.LayerFieldName), - OrganizationID: psql.Where[Q, int32](cols.OrganizationID), - } -} - -func (o *ArcgisAddressMapping) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "LayerField": - rel, ok := retrieved.(*ArcgisLayerField) - if !ok { - return fmt.Errorf("arcgisAddressMapping cannot load %T as %q", retrieved, name) - } - - o.R.LayerField = rel - - if rel != nil { - rel.R.AddressMappings = ArcgisAddressMappingSlice{o} - } - return nil - case "Organization": - rel, ok := retrieved.(*Organization) - if !ok { - return fmt.Errorf("arcgisAddressMapping cannot load %T as %q", retrieved, name) - } - - o.R.Organization = rel - - if rel != nil { - rel.R.AddressMappings = ArcgisAddressMappingSlice{o} - } - return nil - default: - return fmt.Errorf("arcgisAddressMapping has no relationship %q", name) - } -} - -type arcgisAddressMappingPreloader struct { - LayerField func(...psql.PreloadOption) psql.Preloader - Organization func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisAddressMappingPreloader() arcgisAddressMappingPreloader { - return arcgisAddressMappingPreloader{ - LayerField: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisLayerField, ArcgisLayerFieldSlice](psql.PreloadRel{ - Name: "LayerField", - Sides: []psql.PreloadSide{ - { - From: ArcgisAddressMappings, - To: ArcgisLayerFields, - FromColumns: []string{"layer_feature_service_item_id", "layer_index", "layer_field_name"}, - ToColumns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - }, - }, - }, ArcgisLayerFields.Columns.Names(), opts...) - }, - Organization: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{ - Name: "Organization", - Sides: []psql.PreloadSide{ - { - From: ArcgisAddressMappings, - To: Organizations, - FromColumns: []string{"organization_id"}, - ToColumns: []string{"id"}, - }, - }, - }, Organizations.Columns.Names(), opts...) - }, - } -} - -type arcgisAddressMappingThenLoader[Q orm.Loadable] struct { - LayerField func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] -} - -func buildArcgisAddressMappingThenLoader[Q orm.Loadable]() arcgisAddressMappingThenLoader[Q] { - type LayerFieldLoadInterface interface { - LoadLayerField(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type OrganizationLoadInterface interface { - LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - - return arcgisAddressMappingThenLoader[Q]{ - LayerField: thenLoadBuilder[Q]( - "LayerField", - func(ctx context.Context, exec bob.Executor, retrieved LayerFieldLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadLayerField(ctx, exec, mods...) - }, - ), - 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...) - }, - ), - } -} - -// LoadLayerField loads the arcgisAddressMapping's LayerField into the .R struct -func (o *ArcgisAddressMapping) LoadLayerField(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.LayerField = nil - - related, err := o.LayerField(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.AddressMappings = ArcgisAddressMappingSlice{o} - - o.R.LayerField = related - return nil -} - -// LoadLayerField loads the arcgisAddressMapping's LayerField into the .R struct -func (os ArcgisAddressMappingSlice) LoadLayerField(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisLayerFields, err := os.LayerField(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisLayerFields { - - if !(o.LayerFeatureServiceItemID == rel.LayerFeatureServiceItemID) { - continue - } - - if !(o.LayerIndex == rel.LayerIndex) { - continue - } - - if !(o.LayerFieldName == rel.Name) { - continue - } - - rel.R.AddressMappings = append(rel.R.AddressMappings, o) - - o.R.LayerField = rel - break - } - } - - return nil -} - -// LoadOrganization loads the arcgisAddressMapping's Organization into the .R struct -func (o *ArcgisAddressMapping) 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.AddressMappings = ArcgisAddressMappingSlice{o} - - o.R.Organization = related - return nil -} - -// LoadOrganization loads the arcgisAddressMapping's Organization into the .R struct -func (os ArcgisAddressMappingSlice) 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.AddressMappings = append(rel.R.AddressMappings, o) - - o.R.Organization = rel - break - } - } - - return nil -} diff --git a/db/models/arcgis.layer.bob.go b/db/models/arcgis.layer.bob.go deleted file mode 100644 index b9757a26..00000000 --- a/db/models/arcgis.layer.bob.go +++ /dev/null @@ -1,795 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/omit" -) - -// ArcgisLayer is an object representing the database table. -type ArcgisLayer struct { - Extent string `db:"extent" ` - FeatureServiceItemID string `db:"feature_service_item_id,pk" ` - Index int32 `db:"index_,pk" ` - - R arcgisLayerR `db:"-" ` -} - -// ArcgisLayerSlice is an alias for a slice of pointers to ArcgisLayer. -// This should almost always be used instead of []*ArcgisLayer. -type ArcgisLayerSlice []*ArcgisLayer - -// ArcgisLayers contains methods to work with the layer table -var ArcgisLayers = psql.NewTablex[*ArcgisLayer, ArcgisLayerSlice, *ArcgisLayerSetter]("arcgis", "layer", buildArcgisLayerColumns("arcgis.layer")) - -// ArcgisLayersQuery is a query on the layer table -type ArcgisLayersQuery = *psql.ViewQuery[*ArcgisLayer, ArcgisLayerSlice] - -// arcgisLayerR is where relationships are stored. -type arcgisLayerR struct { - 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 -} - -func buildArcgisLayerColumns(alias string) arcgisLayerColumns { - return arcgisLayerColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "extent", "feature_service_item_id", "index_", - ).WithParent("arcgis.layer"), - tableAlias: alias, - Extent: psql.Quote(alias, "extent"), - FeatureServiceItemID: psql.Quote(alias, "feature_service_item_id"), - Index: psql.Quote(alias, "index_"), - } -} - -type arcgisLayerColumns struct { - expr.ColumnsExpr - tableAlias string - Extent psql.Expression - FeatureServiceItemID psql.Expression - Index psql.Expression -} - -func (c arcgisLayerColumns) Alias() string { - return c.tableAlias -} - -func (arcgisLayerColumns) AliasedAs(alias string) arcgisLayerColumns { - return buildArcgisLayerColumns(alias) -} - -// ArcgisLayerSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisLayerSetter struct { - Extent omit.Val[string] `db:"extent" ` - FeatureServiceItemID omit.Val[string] `db:"feature_service_item_id,pk" ` - Index omit.Val[int32] `db:"index_,pk" ` -} - -func (s ArcgisLayerSetter) SetColumns() []string { - vals := make([]string, 0, 3) - if s.Extent.IsValue() { - vals = append(vals, "extent") - } - if s.FeatureServiceItemID.IsValue() { - vals = append(vals, "feature_service_item_id") - } - if s.Index.IsValue() { - vals = append(vals, "index_") - } - return vals -} - -func (s ArcgisLayerSetter) Overwrite(t *ArcgisLayer) { - if s.Extent.IsValue() { - t.Extent = s.Extent.MustGet() - } - if s.FeatureServiceItemID.IsValue() { - t.FeatureServiceItemID = s.FeatureServiceItemID.MustGet() - } - if s.Index.IsValue() { - t.Index = s.Index.MustGet() - } -} - -func (s *ArcgisLayerSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisLayers.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.Extent.IsValue() { - vals[0] = psql.Arg(s.Extent.MustGet()) - } else { - vals[0] = psql.Raw("DEFAULT") - } - - if s.FeatureServiceItemID.IsValue() { - vals[1] = psql.Arg(s.FeatureServiceItemID.MustGet()) - } else { - vals[1] = psql.Raw("DEFAULT") - } - - if s.Index.IsValue() { - vals[2] = psql.Arg(s.Index.MustGet()) - } else { - vals[2] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisLayerSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisLayerSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 3) - - if s.Extent.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "extent")...), - psql.Arg(s.Extent), - }}) - } - - if s.FeatureServiceItemID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "feature_service_item_id")...), - psql.Arg(s.FeatureServiceItemID), - }}) - } - - if s.Index.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "index_")...), - psql.Arg(s.Index), - }}) - } - - return exprs -} - -// FindArcgisLayer retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisLayer(ctx context.Context, exec bob.Executor, FeatureServiceItemIDPK string, IndexPK int32, cols ...string) (*ArcgisLayer, error) { - if len(cols) == 0 { - return ArcgisLayers.Query( - sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))), - sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))), - ).One(ctx, exec) - } - - return ArcgisLayers.Query( - sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))), - sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))), - sm.Columns(ArcgisLayers.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisLayerExists checks the presence of a single record by primary key -func ArcgisLayerExists(ctx context.Context, exec bob.Executor, FeatureServiceItemIDPK string, IndexPK int32) (bool, error) { - return ArcgisLayers.Query( - sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(FeatureServiceItemIDPK))), - sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(IndexPK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisLayer is retrieved from the database -func (o *ArcgisLayer) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisLayers.AfterSelectHooks.RunHooks(ctx, exec, ArcgisLayerSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisLayers.AfterInsertHooks.RunHooks(ctx, exec, ArcgisLayerSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisLayers.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisLayerSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisLayers.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisLayerSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisLayer -func (o *ArcgisLayer) primaryKeyVals() bob.Expression { - return psql.ArgGroup( - o.FeatureServiceItemID, - o.Index, - ) -} - -func (o *ArcgisLayer) pkEQ() dialect.Expression { - return psql.Group(psql.Quote("arcgis.layer", "feature_service_item_id"), psql.Quote("arcgis.layer", "index_")).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 ArcgisLayer -func (o *ArcgisLayer) Update(ctx context.Context, exec bob.Executor, s *ArcgisLayerSetter) error { - v, err := ArcgisLayers.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 ArcgisLayer record with an executor -func (o *ArcgisLayer) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisLayers.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisLayer using the executor -func (o *ArcgisLayer) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisLayers.Query( - sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(o.FeatureServiceItemID))), - sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(o.Index))), - ).One(ctx, exec) - if err != nil { - return err - } - o2.R = o.R - *o = *o2 - - return nil -} - -// AfterQueryHook is called after ArcgisLayerSlice is retrieved from the database -func (o ArcgisLayerSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisLayers.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisLayers.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisLayers.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisLayers.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisLayerSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Group(psql.Quote("arcgis.layer", "feature_service_item_id"), psql.Quote("arcgis.layer", "index_")).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 ArcgisLayerSlice) copyMatchingRows(from ...*ArcgisLayer) { - for i, old := range o { - for _, new := range from { - if new.FeatureServiceItemID != old.FeatureServiceItemID { - continue - } - if new.Index != old.Index { - continue - } - new.R = old.R - o[i] = new - break - } - } -} - -// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" -func (o ArcgisLayerSlice) 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 ArcgisLayers.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 *ArcgisLayer: - o.copyMatchingRows(retrieved) - case []*ArcgisLayer: - o.copyMatchingRows(retrieved...) - case ArcgisLayerSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisLayer or a slice of ArcgisLayer - // then run the AfterUpdateHooks on the slice - _, err = ArcgisLayers.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisLayerSlice) 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 ArcgisLayers.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 *ArcgisLayer: - o.copyMatchingRows(retrieved) - case []*ArcgisLayer: - o.copyMatchingRows(retrieved...) - case ArcgisLayerSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisLayer or a slice of ArcgisLayer - // then run the AfterDeleteHooks on the slice - _, err = ArcgisLayers.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisLayerSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisLayerSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisLayers.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisLayerSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisLayers.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisLayerSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisLayers.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// 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) FeatureServiceItemServiceFeature(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceFeaturesQuery { - pkFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkFeatureServiceItemID = append(pkFeatureServiceItemID, o.FeatureServiceItemID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkFeatureServiceItemID), "text[]")), - )) - - return ArcgisServiceFeatures.Query(append(mods, - sm.Where(psql.Group(ArcgisServiceFeatures.Columns.ItemID).OP("IN", PKArgExpr)), - )...) -} - -// LayerFields starts a query for related objects on arcgis.layer_field -func (o *ArcgisLayer) LayerFields(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - return ArcgisLayerFields.Query(append(mods, - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.FeatureServiceItemID))), sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(o.Index))), - )...) -} - -func (os ArcgisLayerSlice) LayerFields(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - pkFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkIndex := make(pgtypes.Array[int32], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkFeatureServiceItemID = append(pkFeatureServiceItemID, o.FeatureServiceItemID) - pkIndex = append(pkIndex, o.Index) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkIndex), "integer[]")), - )) - - return ArcgisLayerFields.Query(append(mods, - sm.Where(psql.Group(ArcgisLayerFields.Columns.LayerFeatureServiceItemID, ArcgisLayerFields.Columns.LayerIndex).OP("IN", PKArgExpr)), - )...) -} - -func attachArcgisLayerFeatureServiceItemServiceFeature0(ctx context.Context, exec bob.Executor, count int, arcgisLayer0 *ArcgisLayer, arcgisServiceFeature1 *ArcgisServiceFeature) (*ArcgisLayer, error) { - setter := &ArcgisLayerSetter{ - FeatureServiceItemID: omit.From(arcgisServiceFeature1.ItemID), - } - - err := arcgisLayer0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisLayerFeatureServiceItemServiceFeature0: %w", err) - } - - return arcgisLayer0, nil -} - -func (arcgisLayer0 *ArcgisLayer) InsertFeatureServiceItemServiceFeature(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 = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1) - if err != nil { - return err - } - - arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1 - - arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0) - - return nil -} - -func (arcgisLayer0 *ArcgisLayer) AttachFeatureServiceItemServiceFeature(ctx context.Context, exec bob.Executor, arcgisServiceFeature1 *ArcgisServiceFeature) error { - var err error - - _, err = attachArcgisLayerFeatureServiceItemServiceFeature0(ctx, exec, 1, arcgisLayer0, arcgisServiceFeature1) - if err != nil { - return err - } - - arcgisLayer0.R.FeatureServiceItemServiceFeature = arcgisServiceFeature1 - - arcgisServiceFeature1.R.FeatureServiceItemLayers = append(arcgisServiceFeature1.R.FeatureServiceItemLayers, arcgisLayer0) - - return nil -} - -func insertArcgisLayerLayerFields0(ctx context.Context, exec bob.Executor, arcgisLayerFields1 []*ArcgisLayerFieldSetter, arcgisLayer0 *ArcgisLayer) (ArcgisLayerFieldSlice, error) { - for i := range arcgisLayerFields1 { - arcgisLayerFields1[i].LayerFeatureServiceItemID = omit.From(arcgisLayer0.FeatureServiceItemID) - arcgisLayerFields1[i].LayerIndex = omit.From(arcgisLayer0.Index) - } - - ret, err := ArcgisLayerFields.Insert(bob.ToMods(arcgisLayerFields1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisLayerLayerFields0: %w", err) - } - - return ret, nil -} - -func attachArcgisLayerLayerFields0(ctx context.Context, exec bob.Executor, count int, arcgisLayerFields1 ArcgisLayerFieldSlice, arcgisLayer0 *ArcgisLayer) (ArcgisLayerFieldSlice, error) { - setter := &ArcgisLayerFieldSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayer0.FeatureServiceItemID), - LayerIndex: omit.From(arcgisLayer0.Index), - } - - err := arcgisLayerFields1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisLayerLayerFields0: %w", err) - } - - return arcgisLayerFields1, nil -} - -func (arcgisLayer0 *ArcgisLayer) InsertLayerFields(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerFieldSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisLayerFields1, err := insertArcgisLayerLayerFields0(ctx, exec, related, arcgisLayer0) - if err != nil { - return err - } - - arcgisLayer0.R.LayerFields = append(arcgisLayer0.R.LayerFields, arcgisLayerFields1...) - - for _, rel := range arcgisLayerFields1 { - rel.R.Layer = arcgisLayer0 - } - return nil -} - -func (arcgisLayer0 *ArcgisLayer) AttachLayerFields(ctx context.Context, exec bob.Executor, related ...*ArcgisLayerField) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisLayerFields1 := ArcgisLayerFieldSlice(related) - - _, err = attachArcgisLayerLayerFields0(ctx, exec, len(related), arcgisLayerFields1, arcgisLayer0) - if err != nil { - return err - } - - arcgisLayer0.R.LayerFields = append(arcgisLayer0.R.LayerFields, arcgisLayerFields1...) - - for _, rel := range related { - rel.R.Layer = arcgisLayer0 - } - - return nil -} - -type arcgisLayerWhere[Q psql.Filterable] struct { - Extent psql.WhereMod[Q, string] - FeatureServiceItemID psql.WhereMod[Q, string] - Index psql.WhereMod[Q, int32] -} - -func (arcgisLayerWhere[Q]) AliasedAs(alias string) arcgisLayerWhere[Q] { - return buildArcgisLayerWhere[Q](buildArcgisLayerColumns(alias)) -} - -func buildArcgisLayerWhere[Q psql.Filterable](cols arcgisLayerColumns) arcgisLayerWhere[Q] { - return arcgisLayerWhere[Q]{ - Extent: psql.Where[Q, string](cols.Extent), - FeatureServiceItemID: psql.Where[Q, string](cols.FeatureServiceItemID), - Index: psql.Where[Q, int32](cols.Index), - } -} - -func (o *ArcgisLayer) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "FeatureServiceItemServiceFeature": - rel, ok := retrieved.(*ArcgisServiceFeature) - if !ok { - return fmt.Errorf("arcgisLayer cannot load %T as %q", retrieved, name) - } - - o.R.FeatureServiceItemServiceFeature = rel - - if rel != nil { - rel.R.FeatureServiceItemLayers = ArcgisLayerSlice{o} - } - return nil - case "LayerFields": - rels, ok := retrieved.(ArcgisLayerFieldSlice) - if !ok { - return fmt.Errorf("arcgisLayer cannot load %T as %q", retrieved, name) - } - - o.R.LayerFields = rels - - for _, rel := range rels { - if rel != nil { - rel.R.Layer = o - } - } - return nil - default: - return fmt.Errorf("arcgisLayer has no relationship %q", name) - } -} - -type arcgisLayerPreloader struct { - FeatureServiceItemServiceFeature func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisLayerPreloader() arcgisLayerPreloader { - return arcgisLayerPreloader{ - FeatureServiceItemServiceFeature: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisServiceFeature, ArcgisServiceFeatureSlice](psql.PreloadRel{ - Name: "FeatureServiceItemServiceFeature", - Sides: []psql.PreloadSide{ - { - From: ArcgisLayers, - To: ArcgisServiceFeatures, - FromColumns: []string{"feature_service_item_id"}, - ToColumns: []string{"item_id"}, - }, - }, - }, ArcgisServiceFeatures.Columns.Names(), opts...) - }, - } -} - -type arcgisLayerThenLoader[Q orm.Loadable] struct { - 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 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]{ - 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]( - "LayerFields", - func(ctx context.Context, exec bob.Executor, retrieved LayerFieldsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadLayerFields(ctx, exec, mods...) - }, - ), - } -} - -// 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.FeatureServiceItemServiceFeature = nil - - related, err := o.FeatureServiceItemServiceFeature(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.FeatureServiceItemLayers = ArcgisLayerSlice{o} - - o.R.FeatureServiceItemServiceFeature = related - return nil -} - -// 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 - } - - arcgisServiceFeatures, err := os.FeatureServiceItemServiceFeature(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisServiceFeatures { - - if !(o.FeatureServiceItemID == rel.ItemID) { - continue - } - - rel.R.FeatureServiceItemLayers = append(rel.R.FeatureServiceItemLayers, o) - - o.R.FeatureServiceItemServiceFeature = rel - break - } - } - - return nil -} - -// LoadLayerFields loads the arcgisLayer's LayerFields into the .R struct -func (o *ArcgisLayer) LoadLayerFields(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.LayerFields = nil - - related, err := o.LayerFields(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.Layer = o - } - - o.R.LayerFields = related - return nil -} - -// LoadLayerFields loads the arcgisLayer's LayerFields into the .R struct -func (os ArcgisLayerSlice) LoadLayerFields(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisLayerFields, err := os.LayerFields(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.LayerFields = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisLayerFields { - - if !(o.FeatureServiceItemID == rel.LayerFeatureServiceItemID) { - continue - } - - if !(o.Index == rel.LayerIndex) { - continue - } - - rel.R.Layer = o - - o.R.LayerFields = append(o.R.LayerFields, rel) - } - } - - return nil -} diff --git a/db/models/arcgis.layer_field.bob.go b/db/models/arcgis.layer_field.bob.go deleted file mode 100644 index 760fc564..00000000 --- a/db/models/arcgis.layer_field.bob.go +++ /dev/null @@ -1,1046 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" - "github.com/aarondl/opt/omit" -) - -// ArcgisLayerField is an object representing the database table. -type ArcgisLayerField struct { - LayerFeatureServiceItemID string `db:"layer_feature_service_item_id,pk" ` - LayerIndex int32 `db:"layer_index,pk" ` - Name string `db:"name,pk" ` - Type enums.ArcgisFieldtype `db:"type_" ` - - R arcgisLayerFieldR `db:"-" ` -} - -// ArcgisLayerFieldSlice is an alias for a slice of pointers to ArcgisLayerField. -// This should almost always be used instead of []*ArcgisLayerField. -type ArcgisLayerFieldSlice []*ArcgisLayerField - -// ArcgisLayerFields contains methods to work with the layer_field table -var ArcgisLayerFields = psql.NewTablex[*ArcgisLayerField, ArcgisLayerFieldSlice, *ArcgisLayerFieldSetter]("arcgis", "layer_field", buildArcgisLayerFieldColumns("arcgis.layer_field")) - -// ArcgisLayerFieldsQuery is a query on the layer_field table -type ArcgisLayerFieldsQuery = *psql.ViewQuery[*ArcgisLayerField, ArcgisLayerFieldSlice] - -// arcgisLayerFieldR is where relationships are stored. -type arcgisLayerFieldR struct { - AddressMappings ArcgisAddressMappingSlice // arcgis.address_mapping.address_mapping_layer_feature_service_item_id_layer_index__fkey - Layer *ArcgisLayer // arcgis.layer_field.layer_field_layer_feature_service_item_id_layer_index_fkey - ParcelMappings ArcgisParcelMappingSlice // arcgis.parcel_mapping.parcel_mapping_layer_feature_service_item_id_layer_index_l_fkey -} - -func buildArcgisLayerFieldColumns(alias string) arcgisLayerFieldColumns { - return arcgisLayerFieldColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "layer_feature_service_item_id", "layer_index", "name", "type_", - ).WithParent("arcgis.layer_field"), - tableAlias: alias, - LayerFeatureServiceItemID: psql.Quote(alias, "layer_feature_service_item_id"), - LayerIndex: psql.Quote(alias, "layer_index"), - Name: psql.Quote(alias, "name"), - Type: psql.Quote(alias, "type_"), - } -} - -type arcgisLayerFieldColumns struct { - expr.ColumnsExpr - tableAlias string - LayerFeatureServiceItemID psql.Expression - LayerIndex psql.Expression - Name psql.Expression - Type psql.Expression -} - -func (c arcgisLayerFieldColumns) Alias() string { - return c.tableAlias -} - -func (arcgisLayerFieldColumns) AliasedAs(alias string) arcgisLayerFieldColumns { - return buildArcgisLayerFieldColumns(alias) -} - -// ArcgisLayerFieldSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisLayerFieldSetter struct { - LayerFeatureServiceItemID omit.Val[string] `db:"layer_feature_service_item_id,pk" ` - LayerIndex omit.Val[int32] `db:"layer_index,pk" ` - Name omit.Val[string] `db:"name,pk" ` - Type omit.Val[enums.ArcgisFieldtype] `db:"type_" ` -} - -func (s ArcgisLayerFieldSetter) SetColumns() []string { - vals := make([]string, 0, 4) - if s.LayerFeatureServiceItemID.IsValue() { - vals = append(vals, "layer_feature_service_item_id") - } - if s.LayerIndex.IsValue() { - vals = append(vals, "layer_index") - } - if s.Name.IsValue() { - vals = append(vals, "name") - } - if s.Type.IsValue() { - vals = append(vals, "type_") - } - return vals -} - -func (s ArcgisLayerFieldSetter) Overwrite(t *ArcgisLayerField) { - if s.LayerFeatureServiceItemID.IsValue() { - t.LayerFeatureServiceItemID = s.LayerFeatureServiceItemID.MustGet() - } - if s.LayerIndex.IsValue() { - t.LayerIndex = s.LayerIndex.MustGet() - } - if s.Name.IsValue() { - t.Name = s.Name.MustGet() - } - if s.Type.IsValue() { - t.Type = s.Type.MustGet() - } -} - -func (s *ArcgisLayerFieldSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisLayerFields.BeforeInsertHooks.RunHooks(ctx, exec, s) - }) - - q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) { - vals := make([]bob.Expression, 4) - if s.LayerFeatureServiceItemID.IsValue() { - vals[0] = psql.Arg(s.LayerFeatureServiceItemID.MustGet()) - } else { - vals[0] = psql.Raw("DEFAULT") - } - - if s.LayerIndex.IsValue() { - vals[1] = psql.Arg(s.LayerIndex.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.Type.IsValue() { - vals[3] = psql.Arg(s.Type.MustGet()) - } else { - vals[3] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisLayerFieldSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisLayerFieldSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 4) - - if s.LayerFeatureServiceItemID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_feature_service_item_id")...), - psql.Arg(s.LayerFeatureServiceItemID), - }}) - } - - if s.LayerIndex.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_index")...), - psql.Arg(s.LayerIndex), - }}) - } - - if s.Name.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "name")...), - psql.Arg(s.Name), - }}) - } - - if s.Type.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "type_")...), - psql.Arg(s.Type), - }}) - } - - return exprs -} - -// FindArcgisLayerField retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisLayerField(ctx context.Context, exec bob.Executor, LayerFeatureServiceItemIDPK string, LayerIndexPK int32, NamePK string, cols ...string) (*ArcgisLayerField, error) { - if len(cols) == 0 { - return ArcgisLayerFields.Query( - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(LayerFeatureServiceItemIDPK))), - sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(LayerIndexPK))), - sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(NamePK))), - ).One(ctx, exec) - } - - return ArcgisLayerFields.Query( - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(LayerFeatureServiceItemIDPK))), - sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(LayerIndexPK))), - sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(NamePK))), - sm.Columns(ArcgisLayerFields.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisLayerFieldExists checks the presence of a single record by primary key -func ArcgisLayerFieldExists(ctx context.Context, exec bob.Executor, LayerFeatureServiceItemIDPK string, LayerIndexPK int32, NamePK string) (bool, error) { - return ArcgisLayerFields.Query( - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(LayerFeatureServiceItemIDPK))), - sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(LayerIndexPK))), - sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(NamePK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisLayerField is retrieved from the database -func (o *ArcgisLayerField) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisLayerFields.AfterSelectHooks.RunHooks(ctx, exec, ArcgisLayerFieldSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisLayerFields.AfterInsertHooks.RunHooks(ctx, exec, ArcgisLayerFieldSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisLayerFields.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisLayerFieldSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisLayerFields.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisLayerFieldSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisLayerField -func (o *ArcgisLayerField) primaryKeyVals() bob.Expression { - return psql.ArgGroup( - o.LayerFeatureServiceItemID, - o.LayerIndex, - o.Name, - ) -} - -func (o *ArcgisLayerField) pkEQ() dialect.Expression { - return psql.Group(psql.Quote("arcgis.layer_field", "layer_feature_service_item_id"), psql.Quote("arcgis.layer_field", "layer_index"), psql.Quote("arcgis.layer_field", "name")).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 ArcgisLayerField -func (o *ArcgisLayerField) Update(ctx context.Context, exec bob.Executor, s *ArcgisLayerFieldSetter) error { - v, err := ArcgisLayerFields.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 ArcgisLayerField record with an executor -func (o *ArcgisLayerField) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisLayerFields.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisLayerField using the executor -func (o *ArcgisLayerField) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisLayerFields.Query( - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), - sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), - sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(o.Name))), - ).One(ctx, exec) - if err != nil { - return err - } - o2.R = o.R - *o = *o2 - - return nil -} - -// AfterQueryHook is called after ArcgisLayerFieldSlice is retrieved from the database -func (o ArcgisLayerFieldSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisLayerFields.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisLayerFields.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisLayerFields.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisLayerFields.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisLayerFieldSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Group(psql.Quote("arcgis.layer_field", "layer_feature_service_item_id"), psql.Quote("arcgis.layer_field", "layer_index"), psql.Quote("arcgis.layer_field", "name")).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 ArcgisLayerFieldSlice) copyMatchingRows(from ...*ArcgisLayerField) { - for i, old := range o { - for _, new := range from { - if new.LayerFeatureServiceItemID != old.LayerFeatureServiceItemID { - continue - } - if new.LayerIndex != old.LayerIndex { - continue - } - if new.Name != old.Name { - continue - } - new.R = old.R - o[i] = new - break - } - } -} - -// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" -func (o ArcgisLayerFieldSlice) 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 ArcgisLayerFields.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 *ArcgisLayerField: - o.copyMatchingRows(retrieved) - case []*ArcgisLayerField: - o.copyMatchingRows(retrieved...) - case ArcgisLayerFieldSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisLayerField or a slice of ArcgisLayerField - // then run the AfterUpdateHooks on the slice - _, err = ArcgisLayerFields.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisLayerFieldSlice) 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 ArcgisLayerFields.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 *ArcgisLayerField: - o.copyMatchingRows(retrieved) - case []*ArcgisLayerField: - o.copyMatchingRows(retrieved...) - case ArcgisLayerFieldSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisLayerField or a slice of ArcgisLayerField - // then run the AfterDeleteHooks on the slice - _, err = ArcgisLayerFields.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisLayerFieldSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisLayerFieldSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisLayerFields.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisLayerFieldSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisLayerFields.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisLayerFieldSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisLayerFields.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// AddressMappings starts a query for related objects on arcgis.address_mapping -func (o *ArcgisLayerField) AddressMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAddressMappingsQuery { - return ArcgisAddressMappings.Query(append(mods, - sm.Where(ArcgisAddressMappings.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisAddressMappings.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), sm.Where(ArcgisAddressMappings.Columns.LayerFieldName.EQ(psql.Arg(o.Name))), - )...) -} - -func (os ArcgisLayerFieldSlice) AddressMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAddressMappingsQuery { - pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkLayerIndex := make(pgtypes.Array[int32], 0, len(os)) - - pkName := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID) - pkLayerIndex = append(pkLayerIndex, o.LayerIndex) - pkName = append(pkName, o.Name) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkName), "text[]")), - )) - - return ArcgisAddressMappings.Query(append(mods, - sm.Where(psql.Group(ArcgisAddressMappings.Columns.LayerFeatureServiceItemID, ArcgisAddressMappings.Columns.LayerIndex, ArcgisAddressMappings.Columns.LayerFieldName).OP("IN", PKArgExpr)), - )...) -} - -// Layer starts a query for related objects on arcgis.layer -func (o *ArcgisLayerField) Layer(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayersQuery { - return ArcgisLayers.Query(append(mods, - sm.Where(ArcgisLayers.Columns.FeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisLayers.Columns.Index.EQ(psql.Arg(o.LayerIndex))), - )...) -} - -func (os ArcgisLayerFieldSlice) Layer(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayersQuery { - pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkLayerIndex := make(pgtypes.Array[int32], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID) - pkLayerIndex = append(pkLayerIndex, o.LayerIndex) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")), - )) - - return ArcgisLayers.Query(append(mods, - sm.Where(psql.Group(ArcgisLayers.Columns.FeatureServiceItemID, ArcgisLayers.Columns.Index).OP("IN", PKArgExpr)), - )...) -} - -// ParcelMappings starts a query for related objects on arcgis.parcel_mapping -func (o *ArcgisLayerField) ParcelMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisParcelMappingsQuery { - return ArcgisParcelMappings.Query(append(mods, - sm.Where(ArcgisParcelMappings.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisParcelMappings.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), sm.Where(ArcgisParcelMappings.Columns.LayerFieldName.EQ(psql.Arg(o.Name))), - )...) -} - -func (os ArcgisLayerFieldSlice) ParcelMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisParcelMappingsQuery { - pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkLayerIndex := make(pgtypes.Array[int32], 0, len(os)) - - pkName := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID) - pkLayerIndex = append(pkLayerIndex, o.LayerIndex) - pkName = append(pkName, o.Name) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkName), "text[]")), - )) - - return ArcgisParcelMappings.Query(append(mods, - sm.Where(psql.Group(ArcgisParcelMappings.Columns.LayerFeatureServiceItemID, ArcgisParcelMappings.Columns.LayerIndex, ArcgisParcelMappings.Columns.LayerFieldName).OP("IN", PKArgExpr)), - )...) -} - -func insertArcgisLayerFieldAddressMappings0(ctx context.Context, exec bob.Executor, arcgisAddressMappings1 []*ArcgisAddressMappingSetter, arcgisLayerField0 *ArcgisLayerField) (ArcgisAddressMappingSlice, error) { - for i := range arcgisAddressMappings1 { - arcgisAddressMappings1[i].LayerFeatureServiceItemID = omit.From(arcgisLayerField0.LayerFeatureServiceItemID) - arcgisAddressMappings1[i].LayerIndex = omit.From(arcgisLayerField0.LayerIndex) - arcgisAddressMappings1[i].LayerFieldName = omit.From(arcgisLayerField0.Name) - } - - ret, err := ArcgisAddressMappings.Insert(bob.ToMods(arcgisAddressMappings1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisLayerFieldAddressMappings0: %w", err) - } - - return ret, nil -} - -func attachArcgisLayerFieldAddressMappings0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMappings1 ArcgisAddressMappingSlice, arcgisLayerField0 *ArcgisLayerField) (ArcgisAddressMappingSlice, error) { - setter := &ArcgisAddressMappingSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayerField0.LayerFeatureServiceItemID), - LayerIndex: omit.From(arcgisLayerField0.LayerIndex), - LayerFieldName: omit.From(arcgisLayerField0.Name), - } - - err := arcgisAddressMappings1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisLayerFieldAddressMappings0: %w", err) - } - - return arcgisAddressMappings1, nil -} - -func (arcgisLayerField0 *ArcgisLayerField) InsertAddressMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisAddressMappingSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisAddressMappings1, err := insertArcgisLayerFieldAddressMappings0(ctx, exec, related, arcgisLayerField0) - if err != nil { - return err - } - - arcgisLayerField0.R.AddressMappings = append(arcgisLayerField0.R.AddressMappings, arcgisAddressMappings1...) - - for _, rel := range arcgisAddressMappings1 { - rel.R.LayerField = arcgisLayerField0 - } - return nil -} - -func (arcgisLayerField0 *ArcgisLayerField) AttachAddressMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisAddressMapping) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisAddressMappings1 := ArcgisAddressMappingSlice(related) - - _, err = attachArcgisLayerFieldAddressMappings0(ctx, exec, len(related), arcgisAddressMappings1, arcgisLayerField0) - if err != nil { - return err - } - - arcgisLayerField0.R.AddressMappings = append(arcgisLayerField0.R.AddressMappings, arcgisAddressMappings1...) - - for _, rel := range related { - rel.R.LayerField = arcgisLayerField0 - } - - return nil -} - -func attachArcgisLayerFieldLayer0(ctx context.Context, exec bob.Executor, count int, arcgisLayerField0 *ArcgisLayerField, arcgisLayer1 *ArcgisLayer) (*ArcgisLayerField, error) { - setter := &ArcgisLayerFieldSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayer1.FeatureServiceItemID), - LayerIndex: omit.From(arcgisLayer1.Index), - } - - err := arcgisLayerField0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisLayerFieldLayer0: %w", err) - } - - return arcgisLayerField0, nil -} - -func (arcgisLayerField0 *ArcgisLayerField) InsertLayer(ctx context.Context, exec bob.Executor, related *ArcgisLayerSetter) error { - var err error - - arcgisLayer1, err := ArcgisLayers.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachArcgisLayerFieldLayer0(ctx, exec, 1, arcgisLayerField0, arcgisLayer1) - if err != nil { - return err - } - - arcgisLayerField0.R.Layer = arcgisLayer1 - - arcgisLayer1.R.LayerFields = append(arcgisLayer1.R.LayerFields, arcgisLayerField0) - - return nil -} - -func (arcgisLayerField0 *ArcgisLayerField) AttachLayer(ctx context.Context, exec bob.Executor, arcgisLayer1 *ArcgisLayer) error { - var err error - - _, err = attachArcgisLayerFieldLayer0(ctx, exec, 1, arcgisLayerField0, arcgisLayer1) - if err != nil { - return err - } - - arcgisLayerField0.R.Layer = arcgisLayer1 - - arcgisLayer1.R.LayerFields = append(arcgisLayer1.R.LayerFields, arcgisLayerField0) - - return nil -} - -func insertArcgisLayerFieldParcelMappings0(ctx context.Context, exec bob.Executor, arcgisParcelMappings1 []*ArcgisParcelMappingSetter, arcgisLayerField0 *ArcgisLayerField) (ArcgisParcelMappingSlice, error) { - for i := range arcgisParcelMappings1 { - arcgisParcelMappings1[i].LayerFeatureServiceItemID = omit.From(arcgisLayerField0.LayerFeatureServiceItemID) - arcgisParcelMappings1[i].LayerIndex = omit.From(arcgisLayerField0.LayerIndex) - arcgisParcelMappings1[i].LayerFieldName = omit.From(arcgisLayerField0.Name) - } - - ret, err := ArcgisParcelMappings.Insert(bob.ToMods(arcgisParcelMappings1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisLayerFieldParcelMappings0: %w", err) - } - - return ret, nil -} - -func attachArcgisLayerFieldParcelMappings0(ctx context.Context, exec bob.Executor, count int, arcgisParcelMappings1 ArcgisParcelMappingSlice, arcgisLayerField0 *ArcgisLayerField) (ArcgisParcelMappingSlice, error) { - setter := &ArcgisParcelMappingSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayerField0.LayerFeatureServiceItemID), - LayerIndex: omit.From(arcgisLayerField0.LayerIndex), - LayerFieldName: omit.From(arcgisLayerField0.Name), - } - - err := arcgisParcelMappings1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisLayerFieldParcelMappings0: %w", err) - } - - return arcgisParcelMappings1, nil -} - -func (arcgisLayerField0 *ArcgisLayerField) InsertParcelMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisParcelMappingSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisParcelMappings1, err := insertArcgisLayerFieldParcelMappings0(ctx, exec, related, arcgisLayerField0) - if err != nil { - return err - } - - arcgisLayerField0.R.ParcelMappings = append(arcgisLayerField0.R.ParcelMappings, arcgisParcelMappings1...) - - for _, rel := range arcgisParcelMappings1 { - rel.R.LayerField = arcgisLayerField0 - } - return nil -} - -func (arcgisLayerField0 *ArcgisLayerField) AttachParcelMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisParcelMapping) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisParcelMappings1 := ArcgisParcelMappingSlice(related) - - _, err = attachArcgisLayerFieldParcelMappings0(ctx, exec, len(related), arcgisParcelMappings1, arcgisLayerField0) - if err != nil { - return err - } - - arcgisLayerField0.R.ParcelMappings = append(arcgisLayerField0.R.ParcelMappings, arcgisParcelMappings1...) - - for _, rel := range related { - rel.R.LayerField = arcgisLayerField0 - } - - return nil -} - -type arcgisLayerFieldWhere[Q psql.Filterable] struct { - LayerFeatureServiceItemID psql.WhereMod[Q, string] - LayerIndex psql.WhereMod[Q, int32] - Name psql.WhereMod[Q, string] - Type psql.WhereMod[Q, enums.ArcgisFieldtype] -} - -func (arcgisLayerFieldWhere[Q]) AliasedAs(alias string) arcgisLayerFieldWhere[Q] { - return buildArcgisLayerFieldWhere[Q](buildArcgisLayerFieldColumns(alias)) -} - -func buildArcgisLayerFieldWhere[Q psql.Filterable](cols arcgisLayerFieldColumns) arcgisLayerFieldWhere[Q] { - return arcgisLayerFieldWhere[Q]{ - LayerFeatureServiceItemID: psql.Where[Q, string](cols.LayerFeatureServiceItemID), - LayerIndex: psql.Where[Q, int32](cols.LayerIndex), - Name: psql.Where[Q, string](cols.Name), - Type: psql.Where[Q, enums.ArcgisFieldtype](cols.Type), - } -} - -func (o *ArcgisLayerField) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "AddressMappings": - rels, ok := retrieved.(ArcgisAddressMappingSlice) - if !ok { - return fmt.Errorf("arcgisLayerField cannot load %T as %q", retrieved, name) - } - - o.R.AddressMappings = rels - - for _, rel := range rels { - if rel != nil { - rel.R.LayerField = o - } - } - return nil - case "Layer": - rel, ok := retrieved.(*ArcgisLayer) - if !ok { - return fmt.Errorf("arcgisLayerField cannot load %T as %q", retrieved, name) - } - - o.R.Layer = rel - - if rel != nil { - rel.R.LayerFields = ArcgisLayerFieldSlice{o} - } - return nil - case "ParcelMappings": - rels, ok := retrieved.(ArcgisParcelMappingSlice) - if !ok { - return fmt.Errorf("arcgisLayerField cannot load %T as %q", retrieved, name) - } - - o.R.ParcelMappings = rels - - for _, rel := range rels { - if rel != nil { - rel.R.LayerField = o - } - } - return nil - default: - return fmt.Errorf("arcgisLayerField has no relationship %q", name) - } -} - -type arcgisLayerFieldPreloader struct { - Layer func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisLayerFieldPreloader() arcgisLayerFieldPreloader { - return arcgisLayerFieldPreloader{ - Layer: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisLayer, ArcgisLayerSlice](psql.PreloadRel{ - Name: "Layer", - Sides: []psql.PreloadSide{ - { - From: ArcgisLayerFields, - To: ArcgisLayers, - FromColumns: []string{"layer_feature_service_item_id", "layer_index"}, - ToColumns: []string{"feature_service_item_id", "index_"}, - }, - }, - }, ArcgisLayers.Columns.Names(), opts...) - }, - } -} - -type arcgisLayerFieldThenLoader[Q orm.Loadable] struct { - AddressMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Layer func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - ParcelMappings func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] -} - -func buildArcgisLayerFieldThenLoader[Q orm.Loadable]() arcgisLayerFieldThenLoader[Q] { - type AddressMappingsLoadInterface interface { - LoadAddressMappings(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type LayerLoadInterface interface { - LoadLayer(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type ParcelMappingsLoadInterface interface { - LoadParcelMappings(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - - return arcgisLayerFieldThenLoader[Q]{ - AddressMappings: thenLoadBuilder[Q]( - "AddressMappings", - func(ctx context.Context, exec bob.Executor, retrieved AddressMappingsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadAddressMappings(ctx, exec, mods...) - }, - ), - Layer: thenLoadBuilder[Q]( - "Layer", - func(ctx context.Context, exec bob.Executor, retrieved LayerLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadLayer(ctx, exec, mods...) - }, - ), - ParcelMappings: thenLoadBuilder[Q]( - "ParcelMappings", - func(ctx context.Context, exec bob.Executor, retrieved ParcelMappingsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadParcelMappings(ctx, exec, mods...) - }, - ), - } -} - -// LoadAddressMappings loads the arcgisLayerField's AddressMappings into the .R struct -func (o *ArcgisLayerField) LoadAddressMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.AddressMappings = nil - - related, err := o.AddressMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.LayerField = o - } - - o.R.AddressMappings = related - return nil -} - -// LoadAddressMappings loads the arcgisLayerField's AddressMappings into the .R struct -func (os ArcgisLayerFieldSlice) LoadAddressMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisAddressMappings, err := os.AddressMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.AddressMappings = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisAddressMappings { - - if !(o.LayerFeatureServiceItemID == rel.LayerFeatureServiceItemID) { - continue - } - - if !(o.LayerIndex == rel.LayerIndex) { - continue - } - - if !(o.Name == rel.LayerFieldName) { - continue - } - - rel.R.LayerField = o - - o.R.AddressMappings = append(o.R.AddressMappings, rel) - } - } - - return nil -} - -// LoadLayer loads the arcgisLayerField's Layer into the .R struct -func (o *ArcgisLayerField) LoadLayer(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.Layer = nil - - related, err := o.Layer(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.LayerFields = ArcgisLayerFieldSlice{o} - - o.R.Layer = related - return nil -} - -// LoadLayer loads the arcgisLayerField's Layer into the .R struct -func (os ArcgisLayerFieldSlice) LoadLayer(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisLayers, err := os.Layer(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisLayers { - - if !(o.LayerFeatureServiceItemID == rel.FeatureServiceItemID) { - continue - } - - if !(o.LayerIndex == rel.Index) { - continue - } - - rel.R.LayerFields = append(rel.R.LayerFields, o) - - o.R.Layer = rel - break - } - } - - return nil -} - -// LoadParcelMappings loads the arcgisLayerField's ParcelMappings into the .R struct -func (o *ArcgisLayerField) LoadParcelMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ParcelMappings = nil - - related, err := o.ParcelMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.LayerField = o - } - - o.R.ParcelMappings = related - return nil -} - -// LoadParcelMappings loads the arcgisLayerField's ParcelMappings into the .R struct -func (os ArcgisLayerFieldSlice) LoadParcelMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisParcelMappings, err := os.ParcelMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.ParcelMappings = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisParcelMappings { - - if !(o.LayerFeatureServiceItemID == rel.LayerFeatureServiceItemID) { - continue - } - - if !(o.LayerIndex == rel.LayerIndex) { - continue - } - - if !(o.Name == rel.LayerFieldName) { - continue - } - - rel.R.LayerField = o - - o.R.ParcelMappings = append(o.R.ParcelMappings, rel) - } - } - - return nil -} diff --git a/db/models/arcgis.oauth_token.bob.go b/db/models/arcgis.oauth_token.bob.go deleted file mode 100644 index 233eddd3..00000000 --- a/db/models/arcgis.oauth_token.bob.go +++ /dev/null @@ -1,989 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - "time" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/null" - "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" -) - -// 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 -} diff --git a/db/models/arcgis.parcel_mapping.bob.go b/db/models/arcgis.parcel_mapping.bob.go deleted file mode 100644 index 8b7a8081..00000000 --- a/db/models/arcgis.parcel_mapping.bob.go +++ /dev/null @@ -1,837 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" - "github.com/aarondl/opt/omit" -) - -// ArcgisParcelMapping is an object representing the database table. -type ArcgisParcelMapping struct { - Destination enums.ArcgisMappingdestinationparcel `db:"destination,pk" ` - LayerFeatureServiceItemID string `db:"layer_feature_service_item_id" ` - LayerIndex int32 `db:"layer_index" ` - LayerFieldName string `db:"layer_field_name" ` - OrganizationID int32 `db:"organization_id,pk" ` - - R arcgisParcelMappingR `db:"-" ` -} - -// ArcgisParcelMappingSlice is an alias for a slice of pointers to ArcgisParcelMapping. -// This should almost always be used instead of []*ArcgisParcelMapping. -type ArcgisParcelMappingSlice []*ArcgisParcelMapping - -// ArcgisParcelMappings contains methods to work with the parcel_mapping table -var ArcgisParcelMappings = psql.NewTablex[*ArcgisParcelMapping, ArcgisParcelMappingSlice, *ArcgisParcelMappingSetter]("arcgis", "parcel_mapping", buildArcgisParcelMappingColumns("arcgis.parcel_mapping")) - -// ArcgisParcelMappingsQuery is a query on the parcel_mapping table -type ArcgisParcelMappingsQuery = *psql.ViewQuery[*ArcgisParcelMapping, ArcgisParcelMappingSlice] - -// arcgisParcelMappingR is where relationships are stored. -type arcgisParcelMappingR struct { - LayerField *ArcgisLayerField // arcgis.parcel_mapping.parcel_mapping_layer_feature_service_item_id_layer_index_l_fkey - Organization *Organization // arcgis.parcel_mapping.parcel_mapping_organization_id_fkey -} - -func buildArcgisParcelMappingColumns(alias string) arcgisParcelMappingColumns { - return arcgisParcelMappingColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "destination", "layer_feature_service_item_id", "layer_index", "layer_field_name", "organization_id", - ).WithParent("arcgis.parcel_mapping"), - tableAlias: alias, - Destination: psql.Quote(alias, "destination"), - LayerFeatureServiceItemID: psql.Quote(alias, "layer_feature_service_item_id"), - LayerIndex: psql.Quote(alias, "layer_index"), - LayerFieldName: psql.Quote(alias, "layer_field_name"), - OrganizationID: psql.Quote(alias, "organization_id"), - } -} - -type arcgisParcelMappingColumns struct { - expr.ColumnsExpr - tableAlias string - Destination psql.Expression - LayerFeatureServiceItemID psql.Expression - LayerIndex psql.Expression - LayerFieldName psql.Expression - OrganizationID psql.Expression -} - -func (c arcgisParcelMappingColumns) Alias() string { - return c.tableAlias -} - -func (arcgisParcelMappingColumns) AliasedAs(alias string) arcgisParcelMappingColumns { - return buildArcgisParcelMappingColumns(alias) -} - -// ArcgisParcelMappingSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisParcelMappingSetter struct { - Destination omit.Val[enums.ArcgisMappingdestinationparcel] `db:"destination,pk" ` - LayerFeatureServiceItemID omit.Val[string] `db:"layer_feature_service_item_id" ` - LayerIndex omit.Val[int32] `db:"layer_index" ` - LayerFieldName omit.Val[string] `db:"layer_field_name" ` - OrganizationID omit.Val[int32] `db:"organization_id,pk" ` -} - -func (s ArcgisParcelMappingSetter) SetColumns() []string { - vals := make([]string, 0, 5) - if s.Destination.IsValue() { - vals = append(vals, "destination") - } - if s.LayerFeatureServiceItemID.IsValue() { - vals = append(vals, "layer_feature_service_item_id") - } - if s.LayerIndex.IsValue() { - vals = append(vals, "layer_index") - } - if s.LayerFieldName.IsValue() { - vals = append(vals, "layer_field_name") - } - if s.OrganizationID.IsValue() { - vals = append(vals, "organization_id") - } - return vals -} - -func (s ArcgisParcelMappingSetter) Overwrite(t *ArcgisParcelMapping) { - if s.Destination.IsValue() { - t.Destination = s.Destination.MustGet() - } - if s.LayerFeatureServiceItemID.IsValue() { - t.LayerFeatureServiceItemID = s.LayerFeatureServiceItemID.MustGet() - } - if s.LayerIndex.IsValue() { - t.LayerIndex = s.LayerIndex.MustGet() - } - if s.LayerFieldName.IsValue() { - t.LayerFieldName = s.LayerFieldName.MustGet() - } - if s.OrganizationID.IsValue() { - t.OrganizationID = s.OrganizationID.MustGet() - } -} - -func (s *ArcgisParcelMappingSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisParcelMappings.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.Destination.IsValue() { - vals[0] = psql.Arg(s.Destination.MustGet()) - } else { - vals[0] = psql.Raw("DEFAULT") - } - - if s.LayerFeatureServiceItemID.IsValue() { - vals[1] = psql.Arg(s.LayerFeatureServiceItemID.MustGet()) - } else { - vals[1] = psql.Raw("DEFAULT") - } - - if s.LayerIndex.IsValue() { - vals[2] = psql.Arg(s.LayerIndex.MustGet()) - } else { - vals[2] = psql.Raw("DEFAULT") - } - - if s.LayerFieldName.IsValue() { - vals[3] = psql.Arg(s.LayerFieldName.MustGet()) - } else { - vals[3] = psql.Raw("DEFAULT") - } - - if s.OrganizationID.IsValue() { - vals[4] = psql.Arg(s.OrganizationID.MustGet()) - } else { - vals[4] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisParcelMappingSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisParcelMappingSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 5) - - if s.Destination.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "destination")...), - psql.Arg(s.Destination), - }}) - } - - if s.LayerFeatureServiceItemID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_feature_service_item_id")...), - psql.Arg(s.LayerFeatureServiceItemID), - }}) - } - - if s.LayerIndex.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_index")...), - psql.Arg(s.LayerIndex), - }}) - } - - if s.LayerFieldName.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "layer_field_name")...), - psql.Arg(s.LayerFieldName), - }}) - } - - if s.OrganizationID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "organization_id")...), - psql.Arg(s.OrganizationID), - }}) - } - - return exprs -} - -// FindArcgisParcelMapping retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisParcelMapping(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, DestinationPK enums.ArcgisMappingdestinationparcel, cols ...string) (*ArcgisParcelMapping, error) { - if len(cols) == 0 { - return ArcgisParcelMappings.Query( - sm.Where(ArcgisParcelMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisParcelMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - ).One(ctx, exec) - } - - return ArcgisParcelMappings.Query( - sm.Where(ArcgisParcelMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisParcelMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - sm.Columns(ArcgisParcelMappings.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisParcelMappingExists checks the presence of a single record by primary key -func ArcgisParcelMappingExists(ctx context.Context, exec bob.Executor, OrganizationIDPK int32, DestinationPK enums.ArcgisMappingdestinationparcel) (bool, error) { - return ArcgisParcelMappings.Query( - sm.Where(ArcgisParcelMappings.Columns.OrganizationID.EQ(psql.Arg(OrganizationIDPK))), - sm.Where(ArcgisParcelMappings.Columns.Destination.EQ(psql.Arg(DestinationPK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisParcelMapping is retrieved from the database -func (o *ArcgisParcelMapping) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisParcelMappings.AfterSelectHooks.RunHooks(ctx, exec, ArcgisParcelMappingSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisParcelMappings.AfterInsertHooks.RunHooks(ctx, exec, ArcgisParcelMappingSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisParcelMappings.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisParcelMappingSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisParcelMappings.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisParcelMappingSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisParcelMapping -func (o *ArcgisParcelMapping) primaryKeyVals() bob.Expression { - return psql.ArgGroup( - o.OrganizationID, - o.Destination, - ) -} - -func (o *ArcgisParcelMapping) pkEQ() dialect.Expression { - return psql.Group(psql.Quote("arcgis.parcel_mapping", "organization_id"), psql.Quote("arcgis.parcel_mapping", "destination")).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 ArcgisParcelMapping -func (o *ArcgisParcelMapping) Update(ctx context.Context, exec bob.Executor, s *ArcgisParcelMappingSetter) error { - v, err := ArcgisParcelMappings.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 ArcgisParcelMapping record with an executor -func (o *ArcgisParcelMapping) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisParcelMappings.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisParcelMapping using the executor -func (o *ArcgisParcelMapping) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisParcelMappings.Query( - sm.Where(ArcgisParcelMappings.Columns.OrganizationID.EQ(psql.Arg(o.OrganizationID))), - sm.Where(ArcgisParcelMappings.Columns.Destination.EQ(psql.Arg(o.Destination))), - ).One(ctx, exec) - if err != nil { - return err - } - o2.R = o.R - *o = *o2 - - return nil -} - -// AfterQueryHook is called after ArcgisParcelMappingSlice is retrieved from the database -func (o ArcgisParcelMappingSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisParcelMappings.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisParcelMappings.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisParcelMappings.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisParcelMappings.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisParcelMappingSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Group(psql.Quote("arcgis.parcel_mapping", "organization_id"), psql.Quote("arcgis.parcel_mapping", "destination")).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 ArcgisParcelMappingSlice) copyMatchingRows(from ...*ArcgisParcelMapping) { - for i, old := range o { - for _, new := range from { - if new.OrganizationID != old.OrganizationID { - continue - } - if new.Destination != old.Destination { - continue - } - new.R = old.R - o[i] = new - break - } - } -} - -// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" -func (o ArcgisParcelMappingSlice) 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 ArcgisParcelMappings.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 *ArcgisParcelMapping: - o.copyMatchingRows(retrieved) - case []*ArcgisParcelMapping: - o.copyMatchingRows(retrieved...) - case ArcgisParcelMappingSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisParcelMapping or a slice of ArcgisParcelMapping - // then run the AfterUpdateHooks on the slice - _, err = ArcgisParcelMappings.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisParcelMappingSlice) 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 ArcgisParcelMappings.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 *ArcgisParcelMapping: - o.copyMatchingRows(retrieved) - case []*ArcgisParcelMapping: - o.copyMatchingRows(retrieved...) - case ArcgisParcelMappingSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisParcelMapping or a slice of ArcgisParcelMapping - // then run the AfterDeleteHooks on the slice - _, err = ArcgisParcelMappings.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisParcelMappingSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisParcelMappingSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisParcelMappings.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisParcelMappingSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisParcelMappings.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisParcelMappingSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisParcelMappings.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// LayerField starts a query for related objects on arcgis.layer_field -func (o *ArcgisParcelMapping) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - return ArcgisLayerFields.Query(append(mods, - sm.Where(ArcgisLayerFields.Columns.LayerFeatureServiceItemID.EQ(psql.Arg(o.LayerFeatureServiceItemID))), sm.Where(ArcgisLayerFields.Columns.LayerIndex.EQ(psql.Arg(o.LayerIndex))), sm.Where(ArcgisLayerFields.Columns.Name.EQ(psql.Arg(o.LayerFieldName))), - )...) -} - -func (os ArcgisParcelMappingSlice) LayerField(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisLayerFieldsQuery { - pkLayerFeatureServiceItemID := make(pgtypes.Array[string], 0, len(os)) - - pkLayerIndex := make(pgtypes.Array[int32], 0, len(os)) - - pkLayerFieldName := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkLayerFeatureServiceItemID = append(pkLayerFeatureServiceItemID, o.LayerFeatureServiceItemID) - pkLayerIndex = append(pkLayerIndex, o.LayerIndex) - pkLayerFieldName = append(pkLayerFieldName, o.LayerFieldName) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFeatureServiceItemID), "text[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerIndex), "integer[]")), - psql.F("unnest", psql.Cast(psql.Arg(pkLayerFieldName), "text[]")), - )) - - return ArcgisLayerFields.Query(append(mods, - sm.Where(psql.Group(ArcgisLayerFields.Columns.LayerFeatureServiceItemID, ArcgisLayerFields.Columns.LayerIndex, ArcgisLayerFields.Columns.Name).OP("IN", PKArgExpr)), - )...) -} - -// Organization starts a query for related objects on organization -func (o *ArcgisParcelMapping) Organization(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { - return Organizations.Query(append(mods, - sm.Where(Organizations.Columns.ID.EQ(psql.Arg(o.OrganizationID))), - )...) -} - -func (os ArcgisParcelMappingSlice) 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)), - )...) -} - -func attachArcgisParcelMappingLayerField0(ctx context.Context, exec bob.Executor, count int, arcgisParcelMapping0 *ArcgisParcelMapping, arcgisLayerField1 *ArcgisLayerField) (*ArcgisParcelMapping, error) { - setter := &ArcgisParcelMappingSetter{ - LayerFeatureServiceItemID: omit.From(arcgisLayerField1.LayerFeatureServiceItemID), - LayerIndex: omit.From(arcgisLayerField1.LayerIndex), - LayerFieldName: omit.From(arcgisLayerField1.Name), - } - - err := arcgisParcelMapping0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisParcelMappingLayerField0: %w", err) - } - - return arcgisParcelMapping0, nil -} - -func (arcgisParcelMapping0 *ArcgisParcelMapping) InsertLayerField(ctx context.Context, exec bob.Executor, related *ArcgisLayerFieldSetter) error { - var err error - - arcgisLayerField1, err := ArcgisLayerFields.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachArcgisParcelMappingLayerField0(ctx, exec, 1, arcgisParcelMapping0, arcgisLayerField1) - if err != nil { - return err - } - - arcgisParcelMapping0.R.LayerField = arcgisLayerField1 - - arcgisLayerField1.R.ParcelMappings = append(arcgisLayerField1.R.ParcelMappings, arcgisParcelMapping0) - - return nil -} - -func (arcgisParcelMapping0 *ArcgisParcelMapping) AttachLayerField(ctx context.Context, exec bob.Executor, arcgisLayerField1 *ArcgisLayerField) error { - var err error - - _, err = attachArcgisParcelMappingLayerField0(ctx, exec, 1, arcgisParcelMapping0, arcgisLayerField1) - if err != nil { - return err - } - - arcgisParcelMapping0.R.LayerField = arcgisLayerField1 - - arcgisLayerField1.R.ParcelMappings = append(arcgisLayerField1.R.ParcelMappings, arcgisParcelMapping0) - - return nil -} - -func attachArcgisParcelMappingOrganization0(ctx context.Context, exec bob.Executor, count int, arcgisParcelMapping0 *ArcgisParcelMapping, organization1 *Organization) (*ArcgisParcelMapping, error) { - setter := &ArcgisParcelMappingSetter{ - OrganizationID: omit.From(organization1.ID), - } - - err := arcgisParcelMapping0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisParcelMappingOrganization0: %w", err) - } - - return arcgisParcelMapping0, nil -} - -func (arcgisParcelMapping0 *ArcgisParcelMapping) 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 = attachArcgisParcelMappingOrganization0(ctx, exec, 1, arcgisParcelMapping0, organization1) - if err != nil { - return err - } - - arcgisParcelMapping0.R.Organization = organization1 - - organization1.R.ParcelMappings = append(organization1.R.ParcelMappings, arcgisParcelMapping0) - - return nil -} - -func (arcgisParcelMapping0 *ArcgisParcelMapping) AttachOrganization(ctx context.Context, exec bob.Executor, organization1 *Organization) error { - var err error - - _, err = attachArcgisParcelMappingOrganization0(ctx, exec, 1, arcgisParcelMapping0, organization1) - if err != nil { - return err - } - - arcgisParcelMapping0.R.Organization = organization1 - - organization1.R.ParcelMappings = append(organization1.R.ParcelMappings, arcgisParcelMapping0) - - return nil -} - -type arcgisParcelMappingWhere[Q psql.Filterable] struct { - Destination psql.WhereMod[Q, enums.ArcgisMappingdestinationparcel] - LayerFeatureServiceItemID psql.WhereMod[Q, string] - LayerIndex psql.WhereMod[Q, int32] - LayerFieldName psql.WhereMod[Q, string] - OrganizationID psql.WhereMod[Q, int32] -} - -func (arcgisParcelMappingWhere[Q]) AliasedAs(alias string) arcgisParcelMappingWhere[Q] { - return buildArcgisParcelMappingWhere[Q](buildArcgisParcelMappingColumns(alias)) -} - -func buildArcgisParcelMappingWhere[Q psql.Filterable](cols arcgisParcelMappingColumns) arcgisParcelMappingWhere[Q] { - return arcgisParcelMappingWhere[Q]{ - Destination: psql.Where[Q, enums.ArcgisMappingdestinationparcel](cols.Destination), - LayerFeatureServiceItemID: psql.Where[Q, string](cols.LayerFeatureServiceItemID), - LayerIndex: psql.Where[Q, int32](cols.LayerIndex), - LayerFieldName: psql.Where[Q, string](cols.LayerFieldName), - OrganizationID: psql.Where[Q, int32](cols.OrganizationID), - } -} - -func (o *ArcgisParcelMapping) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "LayerField": - rel, ok := retrieved.(*ArcgisLayerField) - if !ok { - return fmt.Errorf("arcgisParcelMapping cannot load %T as %q", retrieved, name) - } - - o.R.LayerField = rel - - if rel != nil { - rel.R.ParcelMappings = ArcgisParcelMappingSlice{o} - } - return nil - case "Organization": - rel, ok := retrieved.(*Organization) - if !ok { - return fmt.Errorf("arcgisParcelMapping cannot load %T as %q", retrieved, name) - } - - o.R.Organization = rel - - if rel != nil { - rel.R.ParcelMappings = ArcgisParcelMappingSlice{o} - } - return nil - default: - return fmt.Errorf("arcgisParcelMapping has no relationship %q", name) - } -} - -type arcgisParcelMappingPreloader struct { - LayerField func(...psql.PreloadOption) psql.Preloader - Organization func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisParcelMappingPreloader() arcgisParcelMappingPreloader { - return arcgisParcelMappingPreloader{ - LayerField: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisLayerField, ArcgisLayerFieldSlice](psql.PreloadRel{ - Name: "LayerField", - Sides: []psql.PreloadSide{ - { - From: ArcgisParcelMappings, - To: ArcgisLayerFields, - FromColumns: []string{"layer_feature_service_item_id", "layer_index", "layer_field_name"}, - ToColumns: []string{"layer_feature_service_item_id", "layer_index", "name"}, - }, - }, - }, ArcgisLayerFields.Columns.Names(), opts...) - }, - Organization: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*Organization, OrganizationSlice](psql.PreloadRel{ - Name: "Organization", - Sides: []psql.PreloadSide{ - { - From: ArcgisParcelMappings, - To: Organizations, - FromColumns: []string{"organization_id"}, - ToColumns: []string{"id"}, - }, - }, - }, Organizations.Columns.Names(), opts...) - }, - } -} - -type arcgisParcelMappingThenLoader[Q orm.Loadable] struct { - LayerField func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Organization func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] -} - -func buildArcgisParcelMappingThenLoader[Q orm.Loadable]() arcgisParcelMappingThenLoader[Q] { - type LayerFieldLoadInterface interface { - LoadLayerField(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type OrganizationLoadInterface interface { - LoadOrganization(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - - return arcgisParcelMappingThenLoader[Q]{ - LayerField: thenLoadBuilder[Q]( - "LayerField", - func(ctx context.Context, exec bob.Executor, retrieved LayerFieldLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadLayerField(ctx, exec, mods...) - }, - ), - 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...) - }, - ), - } -} - -// LoadLayerField loads the arcgisParcelMapping's LayerField into the .R struct -func (o *ArcgisParcelMapping) LoadLayerField(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.LayerField = nil - - related, err := o.LayerField(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.ParcelMappings = ArcgisParcelMappingSlice{o} - - o.R.LayerField = related - return nil -} - -// LoadLayerField loads the arcgisParcelMapping's LayerField into the .R struct -func (os ArcgisParcelMappingSlice) LoadLayerField(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisLayerFields, err := os.LayerField(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisLayerFields { - - if !(o.LayerFeatureServiceItemID == rel.LayerFeatureServiceItemID) { - continue - } - - if !(o.LayerIndex == rel.LayerIndex) { - continue - } - - if !(o.LayerFieldName == rel.Name) { - continue - } - - rel.R.ParcelMappings = append(rel.R.ParcelMappings, o) - - o.R.LayerField = rel - break - } - } - - return nil -} - -// LoadOrganization loads the arcgisParcelMapping's Organization into the .R struct -func (o *ArcgisParcelMapping) 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.ParcelMappings = ArcgisParcelMappingSlice{o} - - o.R.Organization = related - return nil -} - -// LoadOrganization loads the arcgisParcelMapping's Organization into the .R struct -func (os ArcgisParcelMappingSlice) 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.ParcelMappings = append(rel.R.ParcelMappings, o) - - o.R.Organization = rel - break - } - } - - return nil -} diff --git a/db/models/arcgis.service_feature.bob.go b/db/models/arcgis.service_feature.bob.go deleted file mode 100644 index f39485ca..00000000 --- a/db/models/arcgis.service_feature.bob.go +++ /dev/null @@ -1,1011 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/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:"-" ` -} - -// 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 -} diff --git a/db/models/arcgis.service_map.bob.go b/db/models/arcgis.service_map.bob.go deleted file mode 100644 index 1972ee20..00000000 --- a/db/models/arcgis.service_map.bob.go +++ /dev/null @@ -1,1010 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" -) - -// 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 - ArcgisMapServiceOrganizations OrganizationSlice // organization.organization_arcgis_map_service_id_fkey - ArcgisServices TileServiceSlice // tile.service.service_arcgis_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)), - )...) -} - -// ArcgisMapServiceOrganizations starts a query for related objects on organization -func (o *ArcgisServiceMap) ArcgisMapServiceOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { - return Organizations.Query(append(mods, - sm.Where(Organizations.Columns.ArcgisMapServiceID.EQ(psql.Arg(o.ArcgisID))), - )...) -} - -func (os ArcgisServiceMapSlice) ArcgisMapServiceOrganizations(mods ...bob.Mod[*dialect.SelectQuery]) OrganizationsQuery { - pkArcgisID := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkArcgisID = append(pkArcgisID, o.ArcgisID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkArcgisID), "text[]")), - )) - - return Organizations.Query(append(mods, - sm.Where(psql.Group(Organizations.Columns.ArcgisMapServiceID).OP("IN", PKArgExpr)), - )...) -} - -// ArcgisServices starts a query for related objects on tile.service -func (o *ArcgisServiceMap) ArcgisServices(mods ...bob.Mod[*dialect.SelectQuery]) TileServicesQuery { - return TileServices.Query(append(mods, - sm.Where(TileServices.Columns.ArcgisID.EQ(psql.Arg(o.ArcgisID))), - )...) -} - -func (os ArcgisServiceMapSlice) ArcgisServices(mods ...bob.Mod[*dialect.SelectQuery]) TileServicesQuery { - pkArcgisID := make(pgtypes.Array[string], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkArcgisID = append(pkArcgisID, o.ArcgisID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkArcgisID), "text[]")), - )) - - return TileServices.Query(append(mods, - sm.Where(psql.Group(TileServices.Columns.ArcgisID).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 -} - -func insertArcgisServiceMapArcgisMapServiceOrganizations0(ctx context.Context, exec bob.Executor, organizations1 []*OrganizationSetter, arcgisServiceMap0 *ArcgisServiceMap) (OrganizationSlice, error) { - for i := range organizations1 { - organizations1[i].ArcgisMapServiceID = omitnull.From(arcgisServiceMap0.ArcgisID) - } - - ret, err := Organizations.Insert(bob.ToMods(organizations1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisServiceMapArcgisMapServiceOrganizations0: %w", err) - } - - return ret, nil -} - -func attachArcgisServiceMapArcgisMapServiceOrganizations0(ctx context.Context, exec bob.Executor, count int, organizations1 OrganizationSlice, arcgisServiceMap0 *ArcgisServiceMap) (OrganizationSlice, error) { - setter := &OrganizationSetter{ - ArcgisMapServiceID: omitnull.From(arcgisServiceMap0.ArcgisID), - } - - err := organizations1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisServiceMapArcgisMapServiceOrganizations0: %w", err) - } - - return organizations1, nil -} - -func (arcgisServiceMap0 *ArcgisServiceMap) InsertArcgisMapServiceOrganizations(ctx context.Context, exec bob.Executor, related ...*OrganizationSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - organizations1, err := insertArcgisServiceMapArcgisMapServiceOrganizations0(ctx, exec, related, arcgisServiceMap0) - if err != nil { - return err - } - - arcgisServiceMap0.R.ArcgisMapServiceOrganizations = append(arcgisServiceMap0.R.ArcgisMapServiceOrganizations, organizations1...) - - for _, rel := range organizations1 { - rel.R.ArcgisMapServiceServiceMap = arcgisServiceMap0 - } - return nil -} - -func (arcgisServiceMap0 *ArcgisServiceMap) AttachArcgisMapServiceOrganizations(ctx context.Context, exec bob.Executor, related ...*Organization) error { - if len(related) == 0 { - return nil - } - - var err error - organizations1 := OrganizationSlice(related) - - _, err = attachArcgisServiceMapArcgisMapServiceOrganizations0(ctx, exec, len(related), organizations1, arcgisServiceMap0) - if err != nil { - return err - } - - arcgisServiceMap0.R.ArcgisMapServiceOrganizations = append(arcgisServiceMap0.R.ArcgisMapServiceOrganizations, organizations1...) - - for _, rel := range related { - rel.R.ArcgisMapServiceServiceMap = arcgisServiceMap0 - } - - return nil -} - -func insertArcgisServiceMapArcgisServices0(ctx context.Context, exec bob.Executor, tileServices1 []*TileServiceSetter, arcgisServiceMap0 *ArcgisServiceMap) (TileServiceSlice, error) { - for i := range tileServices1 { - tileServices1[i].ArcgisID = omitnull.From(arcgisServiceMap0.ArcgisID) - } - - ret, err := TileServices.Insert(bob.ToMods(tileServices1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisServiceMapArcgisServices0: %w", err) - } - - return ret, nil -} - -func attachArcgisServiceMapArcgisServices0(ctx context.Context, exec bob.Executor, count int, tileServices1 TileServiceSlice, arcgisServiceMap0 *ArcgisServiceMap) (TileServiceSlice, error) { - setter := &TileServiceSetter{ - ArcgisID: omitnull.From(arcgisServiceMap0.ArcgisID), - } - - err := tileServices1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisServiceMapArcgisServices0: %w", err) - } - - return tileServices1, nil -} - -func (arcgisServiceMap0 *ArcgisServiceMap) InsertArcgisServices(ctx context.Context, exec bob.Executor, related ...*TileServiceSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - tileServices1, err := insertArcgisServiceMapArcgisServices0(ctx, exec, related, arcgisServiceMap0) - if err != nil { - return err - } - - arcgisServiceMap0.R.ArcgisServices = append(arcgisServiceMap0.R.ArcgisServices, tileServices1...) - - for _, rel := range tileServices1 { - rel.R.ArcgisServiceMap = arcgisServiceMap0 - } - return nil -} - -func (arcgisServiceMap0 *ArcgisServiceMap) AttachArcgisServices(ctx context.Context, exec bob.Executor, related ...*TileService) error { - if len(related) == 0 { - return nil - } - - var err error - tileServices1 := TileServiceSlice(related) - - _, err = attachArcgisServiceMapArcgisServices0(ctx, exec, len(related), tileServices1, arcgisServiceMap0) - if err != nil { - return err - } - - arcgisServiceMap0.R.ArcgisServices = append(arcgisServiceMap0.R.ArcgisServices, tileServices1...) - - for _, rel := range related { - rel.R.ArcgisServiceMap = 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 - case "ArcgisMapServiceOrganizations": - rels, ok := retrieved.(OrganizationSlice) - if !ok { - return fmt.Errorf("arcgisServiceMap cannot load %T as %q", retrieved, name) - } - - o.R.ArcgisMapServiceOrganizations = rels - - for _, rel := range rels { - if rel != nil { - rel.R.ArcgisMapServiceServiceMap = o - } - } - return nil - case "ArcgisServices": - rels, ok := retrieved.(TileServiceSlice) - if !ok { - return fmt.Errorf("arcgisServiceMap cannot load %T as %q", retrieved, name) - } - - o.R.ArcgisServices = rels - - for _, rel := range rels { - if rel != nil { - rel.R.ArcgisServiceMap = 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] - ArcgisMapServiceOrganizations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - ArcgisServices 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 - } - type ArcgisMapServiceOrganizationsLoadInterface interface { - LoadArcgisMapServiceOrganizations(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type ArcgisServicesLoadInterface interface { - LoadArcgisServices(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...) - }, - ), - ArcgisMapServiceOrganizations: thenLoadBuilder[Q]( - "ArcgisMapServiceOrganizations", - func(ctx context.Context, exec bob.Executor, retrieved ArcgisMapServiceOrganizationsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadArcgisMapServiceOrganizations(ctx, exec, mods...) - }, - ), - ArcgisServices: thenLoadBuilder[Q]( - "ArcgisServices", - func(ctx context.Context, exec bob.Executor, retrieved ArcgisServicesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadArcgisServices(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 -} - -// LoadArcgisMapServiceOrganizations loads the arcgisServiceMap's ArcgisMapServiceOrganizations into the .R struct -func (o *ArcgisServiceMap) LoadArcgisMapServiceOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ArcgisMapServiceOrganizations = nil - - related, err := o.ArcgisMapServiceOrganizations(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.ArcgisMapServiceServiceMap = o - } - - o.R.ArcgisMapServiceOrganizations = related - return nil -} - -// LoadArcgisMapServiceOrganizations loads the arcgisServiceMap's ArcgisMapServiceOrganizations into the .R struct -func (os ArcgisServiceMapSlice) LoadArcgisMapServiceOrganizations(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - organizations, err := os.ArcgisMapServiceOrganizations(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.ArcgisMapServiceOrganizations = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range organizations { - - if !rel.ArcgisMapServiceID.IsValue() { - continue - } - if !(rel.ArcgisMapServiceID.IsValue() && o.ArcgisID == rel.ArcgisMapServiceID.MustGet()) { - continue - } - - rel.R.ArcgisMapServiceServiceMap = o - - o.R.ArcgisMapServiceOrganizations = append(o.R.ArcgisMapServiceOrganizations, rel) - } - } - - return nil -} - -// LoadArcgisServices loads the arcgisServiceMap's ArcgisServices into the .R struct -func (o *ArcgisServiceMap) LoadArcgisServices(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ArcgisServices = nil - - related, err := o.ArcgisServices(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.ArcgisServiceMap = o - } - - o.R.ArcgisServices = related - return nil -} - -// LoadArcgisServices loads the arcgisServiceMap's ArcgisServices into the .R struct -func (os ArcgisServiceMapSlice) LoadArcgisServices(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - tileServices, err := os.ArcgisServices(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.ArcgisServices = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range tileServices { - - if !rel.ArcgisID.IsValue() { - continue - } - if !(rel.ArcgisID.IsValue() && o.ArcgisID == rel.ArcgisID.MustGet()) { - continue - } - - rel.R.ArcgisServiceMap = o - - o.R.ArcgisServices = append(o.R.ArcgisServices, rel) - } - } - - return nil -} diff --git a/db/models/arcgis.user_.bob.go b/db/models/arcgis.user_.bob.go deleted file mode 100644 index 6a60b461..00000000 --- a/db/models/arcgis.user_.bob.go +++ /dev/null @@ -1,1051 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - "time" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/omit" -) - -// ArcgisUser is an object representing the database table. -type ArcgisUser struct { - Access string `db:"access" ` - Created time.Time `db:"created" ` - Email string `db:"email" ` - FullName string `db:"full_name" ` - ID string `db:"id,pk" ` - Level string `db:"level" ` - OrgID string `db:"org_id" ` - PublicUserID int32 `db:"public_user_id" ` - Region string `db:"region" ` - Role string `db:"role" ` - RoleID string `db:"role_id" ` - Username string `db:"username" ` - UserLicenseTypeID string `db:"user_license_type_id" ` - UserType string `db:"user_type" ` - - R arcgisuserR `db:"-" ` -} - -// ArcgisUserSlice is an alias for a slice of pointers to ArcgisUser. -// This should almost always be used instead of []*ArcgisUser. -type ArcgisUserSlice []*ArcgisUser - -// ArcgisUsers contains methods to work with the user_ table -var ArcgisUsers = psql.NewTablex[*ArcgisUser, ArcgisUserSlice, *ArcgisUserSetter]("arcgis", "user_", buildArcgisUserColumns("arcgis.user_")) - -// ArcgisUsersQuery is a query on the user_ table -type ArcgisUsersQuery = *psql.ViewQuery[*ArcgisUser, ArcgisUserSlice] - -// arcgisuserR is where relationships are stored. -type arcgisuserR struct { - PublicUserUser *User // arcgis.user_.user__public_user_id_fkey - UserUserPrivileges ArcgisUserPrivilegeSlice // arcgis.user_privilege.user_privilege_user_id_fkey -} - -func buildArcgisUserColumns(alias string) arcgisuserColumns { - return arcgisuserColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "access", "created", "email", "full_name", "id", "level", "org_id", "public_user_id", "region", "role", "role_id", "username", "user_license_type_id", "user_type", - ).WithParent("arcgis.user_"), - tableAlias: alias, - Access: psql.Quote(alias, "access"), - Created: psql.Quote(alias, "created"), - Email: psql.Quote(alias, "email"), - FullName: psql.Quote(alias, "full_name"), - ID: psql.Quote(alias, "id"), - Level: psql.Quote(alias, "level"), - OrgID: psql.Quote(alias, "org_id"), - PublicUserID: psql.Quote(alias, "public_user_id"), - Region: psql.Quote(alias, "region"), - Role: psql.Quote(alias, "role"), - RoleID: psql.Quote(alias, "role_id"), - Username: psql.Quote(alias, "username"), - UserLicenseTypeID: psql.Quote(alias, "user_license_type_id"), - UserType: psql.Quote(alias, "user_type"), - } -} - -type arcgisuserColumns struct { - expr.ColumnsExpr - tableAlias string - Access psql.Expression - Created psql.Expression - Email psql.Expression - FullName psql.Expression - ID psql.Expression - Level psql.Expression - OrgID psql.Expression - PublicUserID psql.Expression - Region psql.Expression - Role psql.Expression - RoleID psql.Expression - Username psql.Expression - UserLicenseTypeID psql.Expression - UserType psql.Expression -} - -func (c arcgisuserColumns) Alias() string { - return c.tableAlias -} - -func (arcgisuserColumns) AliasedAs(alias string) arcgisuserColumns { - return buildArcgisUserColumns(alias) -} - -// ArcgisUserSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisUserSetter struct { - Access omit.Val[string] `db:"access" ` - Created omit.Val[time.Time] `db:"created" ` - Email omit.Val[string] `db:"email" ` - FullName omit.Val[string] `db:"full_name" ` - ID omit.Val[string] `db:"id,pk" ` - Level omit.Val[string] `db:"level" ` - OrgID omit.Val[string] `db:"org_id" ` - PublicUserID omit.Val[int32] `db:"public_user_id" ` - Region omit.Val[string] `db:"region" ` - Role omit.Val[string] `db:"role" ` - RoleID omit.Val[string] `db:"role_id" ` - Username omit.Val[string] `db:"username" ` - UserLicenseTypeID omit.Val[string] `db:"user_license_type_id" ` - UserType omit.Val[string] `db:"user_type" ` -} - -func (s ArcgisUserSetter) SetColumns() []string { - vals := make([]string, 0, 14) - if s.Access.IsValue() { - vals = append(vals, "access") - } - if s.Created.IsValue() { - vals = append(vals, "created") - } - if s.Email.IsValue() { - vals = append(vals, "email") - } - if s.FullName.IsValue() { - vals = append(vals, "full_name") - } - if s.ID.IsValue() { - vals = append(vals, "id") - } - if s.Level.IsValue() { - vals = append(vals, "level") - } - if s.OrgID.IsValue() { - vals = append(vals, "org_id") - } - if s.PublicUserID.IsValue() { - vals = append(vals, "public_user_id") - } - if s.Region.IsValue() { - vals = append(vals, "region") - } - if s.Role.IsValue() { - vals = append(vals, "role") - } - if s.RoleID.IsValue() { - vals = append(vals, "role_id") - } - if s.Username.IsValue() { - vals = append(vals, "username") - } - if s.UserLicenseTypeID.IsValue() { - vals = append(vals, "user_license_type_id") - } - if s.UserType.IsValue() { - vals = append(vals, "user_type") - } - return vals -} - -func (s ArcgisUserSetter) Overwrite(t *ArcgisUser) { - if s.Access.IsValue() { - t.Access = s.Access.MustGet() - } - if s.Created.IsValue() { - t.Created = s.Created.MustGet() - } - if s.Email.IsValue() { - t.Email = s.Email.MustGet() - } - if s.FullName.IsValue() { - t.FullName = s.FullName.MustGet() - } - if s.ID.IsValue() { - t.ID = s.ID.MustGet() - } - if s.Level.IsValue() { - t.Level = s.Level.MustGet() - } - if s.OrgID.IsValue() { - t.OrgID = s.OrgID.MustGet() - } - if s.PublicUserID.IsValue() { - t.PublicUserID = s.PublicUserID.MustGet() - } - if s.Region.IsValue() { - t.Region = s.Region.MustGet() - } - if s.Role.IsValue() { - t.Role = s.Role.MustGet() - } - if s.RoleID.IsValue() { - t.RoleID = s.RoleID.MustGet() - } - if s.Username.IsValue() { - t.Username = s.Username.MustGet() - } - if s.UserLicenseTypeID.IsValue() { - t.UserLicenseTypeID = s.UserLicenseTypeID.MustGet() - } - if s.UserType.IsValue() { - t.UserType = s.UserType.MustGet() - } -} - -func (s *ArcgisUserSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisUsers.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, 14) - if s.Access.IsValue() { - vals[0] = psql.Arg(s.Access.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.Email.IsValue() { - vals[2] = psql.Arg(s.Email.MustGet()) - } else { - vals[2] = psql.Raw("DEFAULT") - } - - if s.FullName.IsValue() { - vals[3] = psql.Arg(s.FullName.MustGet()) - } else { - vals[3] = psql.Raw("DEFAULT") - } - - if s.ID.IsValue() { - vals[4] = psql.Arg(s.ID.MustGet()) - } else { - vals[4] = psql.Raw("DEFAULT") - } - - if s.Level.IsValue() { - vals[5] = psql.Arg(s.Level.MustGet()) - } else { - vals[5] = psql.Raw("DEFAULT") - } - - if s.OrgID.IsValue() { - vals[6] = psql.Arg(s.OrgID.MustGet()) - } else { - vals[6] = psql.Raw("DEFAULT") - } - - if s.PublicUserID.IsValue() { - vals[7] = psql.Arg(s.PublicUserID.MustGet()) - } else { - vals[7] = psql.Raw("DEFAULT") - } - - if s.Region.IsValue() { - vals[8] = psql.Arg(s.Region.MustGet()) - } else { - vals[8] = psql.Raw("DEFAULT") - } - - if s.Role.IsValue() { - vals[9] = psql.Arg(s.Role.MustGet()) - } else { - vals[9] = psql.Raw("DEFAULT") - } - - if s.RoleID.IsValue() { - vals[10] = psql.Arg(s.RoleID.MustGet()) - } else { - vals[10] = psql.Raw("DEFAULT") - } - - if s.Username.IsValue() { - vals[11] = psql.Arg(s.Username.MustGet()) - } else { - vals[11] = psql.Raw("DEFAULT") - } - - if s.UserLicenseTypeID.IsValue() { - vals[12] = psql.Arg(s.UserLicenseTypeID.MustGet()) - } else { - vals[12] = psql.Raw("DEFAULT") - } - - if s.UserType.IsValue() { - vals[13] = psql.Arg(s.UserType.MustGet()) - } else { - vals[13] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisUserSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisUserSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 14) - - if s.Access.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "access")...), - psql.Arg(s.Access), - }}) - } - - if s.Created.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "created")...), - psql.Arg(s.Created), - }}) - } - - if s.Email.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "email")...), - psql.Arg(s.Email), - }}) - } - - if s.FullName.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "full_name")...), - psql.Arg(s.FullName), - }}) - } - - if s.ID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "id")...), - psql.Arg(s.ID), - }}) - } - - if s.Level.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "level")...), - psql.Arg(s.Level), - }}) - } - - if s.OrgID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "org_id")...), - psql.Arg(s.OrgID), - }}) - } - - if s.PublicUserID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "public_user_id")...), - psql.Arg(s.PublicUserID), - }}) - } - - if s.Region.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "region")...), - psql.Arg(s.Region), - }}) - } - - if s.Role.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "role")...), - psql.Arg(s.Role), - }}) - } - - if s.RoleID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "role_id")...), - psql.Arg(s.RoleID), - }}) - } - - if s.Username.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "username")...), - psql.Arg(s.Username), - }}) - } - - if s.UserLicenseTypeID.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "user_license_type_id")...), - psql.Arg(s.UserLicenseTypeID), - }}) - } - - if s.UserType.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "user_type")...), - psql.Arg(s.UserType), - }}) - } - - return exprs -} - -// FindArcgisUser retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisUser(ctx context.Context, exec bob.Executor, IDPK string, cols ...string) (*ArcgisUser, error) { - if len(cols) == 0 { - return ArcgisUsers.Query( - sm.Where(ArcgisUsers.Columns.ID.EQ(psql.Arg(IDPK))), - ).One(ctx, exec) - } - - return ArcgisUsers.Query( - sm.Where(ArcgisUsers.Columns.ID.EQ(psql.Arg(IDPK))), - sm.Columns(ArcgisUsers.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisUserExists checks the presence of a single record by primary key -func ArcgisUserExists(ctx context.Context, exec bob.Executor, IDPK string) (bool, error) { - return ArcgisUsers.Query( - sm.Where(ArcgisUsers.Columns.ID.EQ(psql.Arg(IDPK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisUser is retrieved from the database -func (o *ArcgisUser) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisUsers.AfterSelectHooks.RunHooks(ctx, exec, ArcgisUserSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisUsers.AfterInsertHooks.RunHooks(ctx, exec, ArcgisUserSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisUsers.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisUserSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisUsers.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisUserSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisUser -func (o *ArcgisUser) primaryKeyVals() bob.Expression { - return psql.Arg(o.ID) -} - -func (o *ArcgisUser) pkEQ() dialect.Expression { - return psql.Quote("arcgis.user_", "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 ArcgisUser -func (o *ArcgisUser) Update(ctx context.Context, exec bob.Executor, s *ArcgisUserSetter) error { - v, err := ArcgisUsers.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 ArcgisUser record with an executor -func (o *ArcgisUser) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisUsers.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisUser using the executor -func (o *ArcgisUser) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisUsers.Query( - sm.Where(ArcgisUsers.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 ArcgisUserSlice is retrieved from the database -func (o ArcgisUserSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisUsers.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisUsers.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisUsers.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisUsers.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisUserSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Quote("arcgis.user_", "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 ArcgisUserSlice) copyMatchingRows(from ...*ArcgisUser) { - 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 ArcgisUserSlice) 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 ArcgisUsers.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 *ArcgisUser: - o.copyMatchingRows(retrieved) - case []*ArcgisUser: - o.copyMatchingRows(retrieved...) - case ArcgisUserSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisUser or a slice of ArcgisUser - // then run the AfterUpdateHooks on the slice - _, err = ArcgisUsers.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisUserSlice) 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 ArcgisUsers.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 *ArcgisUser: - o.copyMatchingRows(retrieved) - case []*ArcgisUser: - o.copyMatchingRows(retrieved...) - case ArcgisUserSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisUser or a slice of ArcgisUser - // then run the AfterDeleteHooks on the slice - _, err = ArcgisUsers.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisUserSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisUserSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisUsers.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisUserSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisUsers.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisUserSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisUsers.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// PublicUserUser starts a query for related objects on user_ -func (o *ArcgisUser) PublicUserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { - return Users.Query(append(mods, - sm.Where(Users.Columns.ID.EQ(psql.Arg(o.PublicUserID))), - )...) -} - -func (os ArcgisUserSlice) PublicUserUser(mods ...bob.Mod[*dialect.SelectQuery]) UsersQuery { - pkPublicUserID := make(pgtypes.Array[int32], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkPublicUserID = append(pkPublicUserID, o.PublicUserID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkPublicUserID), "integer[]")), - )) - - return Users.Query(append(mods, - sm.Where(psql.Group(Users.Columns.ID).OP("IN", PKArgExpr)), - )...) -} - -// UserUserPrivileges starts a query for related objects on arcgis.user_privilege -func (o *ArcgisUser) UserUserPrivileges(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUserPrivilegesQuery { - return ArcgisUserPrivileges.Query(append(mods, - sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(o.ID))), - )...) -} - -func (os ArcgisUserSlice) UserUserPrivileges(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUserPrivilegesQuery { - 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 ArcgisUserPrivileges.Query(append(mods, - sm.Where(psql.Group(ArcgisUserPrivileges.Columns.UserID).OP("IN", PKArgExpr)), - )...) -} - -func attachArcgisUserPublicUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisuser0 *ArcgisUser, user1 *User) (*ArcgisUser, error) { - setter := &ArcgisUserSetter{ - PublicUserID: omit.From(user1.ID), - } - - err := arcgisuser0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisUserPublicUserUser0: %w", err) - } - - return arcgisuser0, nil -} - -func (arcgisuser0 *ArcgisUser) InsertPublicUserUser(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 = attachArcgisUserPublicUserUser0(ctx, exec, 1, arcgisuser0, user1) - if err != nil { - return err - } - - arcgisuser0.R.PublicUserUser = user1 - - user1.R.PublicUserUser = append(user1.R.PublicUserUser, arcgisuser0) - - return nil -} - -func (arcgisuser0 *ArcgisUser) AttachPublicUserUser(ctx context.Context, exec bob.Executor, user1 *User) error { - var err error - - _, err = attachArcgisUserPublicUserUser0(ctx, exec, 1, arcgisuser0, user1) - if err != nil { - return err - } - - arcgisuser0.R.PublicUserUser = user1 - - user1.R.PublicUserUser = append(user1.R.PublicUserUser, arcgisuser0) - - return nil -} - -func insertArcgisUserUserUserPrivileges0(ctx context.Context, exec bob.Executor, arcgisUserPrivileges1 []*ArcgisUserPrivilegeSetter, arcgisuser0 *ArcgisUser) (ArcgisUserPrivilegeSlice, error) { - for i := range arcgisUserPrivileges1 { - arcgisUserPrivileges1[i].UserID = omit.From(arcgisuser0.ID) - } - - ret, err := ArcgisUserPrivileges.Insert(bob.ToMods(arcgisUserPrivileges1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertArcgisUserUserUserPrivileges0: %w", err) - } - - return ret, nil -} - -func attachArcgisUserUserUserPrivileges0(ctx context.Context, exec bob.Executor, count int, arcgisUserPrivileges1 ArcgisUserPrivilegeSlice, arcgisuser0 *ArcgisUser) (ArcgisUserPrivilegeSlice, error) { - setter := &ArcgisUserPrivilegeSetter{ - UserID: omit.From(arcgisuser0.ID), - } - - err := arcgisUserPrivileges1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisUserUserUserPrivileges0: %w", err) - } - - return arcgisUserPrivileges1, nil -} - -func (arcgisuser0 *ArcgisUser) InsertUserUserPrivileges(ctx context.Context, exec bob.Executor, related ...*ArcgisUserPrivilegeSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisUserPrivileges1, err := insertArcgisUserUserUserPrivileges0(ctx, exec, related, arcgisuser0) - if err != nil { - return err - } - - arcgisuser0.R.UserUserPrivileges = append(arcgisuser0.R.UserUserPrivileges, arcgisUserPrivileges1...) - - for _, rel := range arcgisUserPrivileges1 { - rel.R.UserUser = arcgisuser0 - } - return nil -} - -func (arcgisuser0 *ArcgisUser) AttachUserUserPrivileges(ctx context.Context, exec bob.Executor, related ...*ArcgisUserPrivilege) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisUserPrivileges1 := ArcgisUserPrivilegeSlice(related) - - _, err = attachArcgisUserUserUserPrivileges0(ctx, exec, len(related), arcgisUserPrivileges1, arcgisuser0) - if err != nil { - return err - } - - arcgisuser0.R.UserUserPrivileges = append(arcgisuser0.R.UserUserPrivileges, arcgisUserPrivileges1...) - - for _, rel := range related { - rel.R.UserUser = arcgisuser0 - } - - return nil -} - -type arcgisuserWhere[Q psql.Filterable] struct { - Access psql.WhereMod[Q, string] - Created psql.WhereMod[Q, time.Time] - Email psql.WhereMod[Q, string] - FullName psql.WhereMod[Q, string] - ID psql.WhereMod[Q, string] - Level psql.WhereMod[Q, string] - OrgID psql.WhereMod[Q, string] - PublicUserID psql.WhereMod[Q, int32] - Region psql.WhereMod[Q, string] - Role psql.WhereMod[Q, string] - RoleID psql.WhereMod[Q, string] - Username psql.WhereMod[Q, string] - UserLicenseTypeID psql.WhereMod[Q, string] - UserType psql.WhereMod[Q, string] -} - -func (arcgisuserWhere[Q]) AliasedAs(alias string) arcgisuserWhere[Q] { - return buildArcgisUserWhere[Q](buildArcgisUserColumns(alias)) -} - -func buildArcgisUserWhere[Q psql.Filterable](cols arcgisuserColumns) arcgisuserWhere[Q] { - return arcgisuserWhere[Q]{ - Access: psql.Where[Q, string](cols.Access), - Created: psql.Where[Q, time.Time](cols.Created), - Email: psql.Where[Q, string](cols.Email), - FullName: psql.Where[Q, string](cols.FullName), - ID: psql.Where[Q, string](cols.ID), - Level: psql.Where[Q, string](cols.Level), - OrgID: psql.Where[Q, string](cols.OrgID), - PublicUserID: psql.Where[Q, int32](cols.PublicUserID), - Region: psql.Where[Q, string](cols.Region), - Role: psql.Where[Q, string](cols.Role), - RoleID: psql.Where[Q, string](cols.RoleID), - Username: psql.Where[Q, string](cols.Username), - UserLicenseTypeID: psql.Where[Q, string](cols.UserLicenseTypeID), - UserType: psql.Where[Q, string](cols.UserType), - } -} - -func (o *ArcgisUser) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "PublicUserUser": - rel, ok := retrieved.(*User) - if !ok { - return fmt.Errorf("arcgisuser cannot load %T as %q", retrieved, name) - } - - o.R.PublicUserUser = rel - - if rel != nil { - rel.R.PublicUserUser = ArcgisUserSlice{o} - } - return nil - case "UserUserPrivileges": - rels, ok := retrieved.(ArcgisUserPrivilegeSlice) - if !ok { - return fmt.Errorf("arcgisuser cannot load %T as %q", retrieved, name) - } - - o.R.UserUserPrivileges = rels - - for _, rel := range rels { - if rel != nil { - rel.R.UserUser = o - } - } - return nil - default: - return fmt.Errorf("arcgisuser has no relationship %q", name) - } -} - -type arcgisuserPreloader struct { - PublicUserUser func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisUserPreloader() arcgisuserPreloader { - return arcgisuserPreloader{ - PublicUserUser: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*User, UserSlice](psql.PreloadRel{ - Name: "PublicUserUser", - Sides: []psql.PreloadSide{ - { - From: ArcgisUsers, - To: Users, - FromColumns: []string{"public_user_id"}, - ToColumns: []string{"id"}, - }, - }, - }, Users.Columns.Names(), opts...) - }, - } -} - -type arcgisuserThenLoader[Q orm.Loadable] struct { - PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - UserUserPrivileges func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] -} - -func buildArcgisUserThenLoader[Q orm.Loadable]() arcgisuserThenLoader[Q] { - type PublicUserUserLoadInterface interface { - LoadPublicUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type UserUserPrivilegesLoadInterface interface { - LoadUserUserPrivileges(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - - return arcgisuserThenLoader[Q]{ - 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...) - }, - ), - UserUserPrivileges: thenLoadBuilder[Q]( - "UserUserPrivileges", - func(ctx context.Context, exec bob.Executor, retrieved UserUserPrivilegesLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadUserUserPrivileges(ctx, exec, mods...) - }, - ), - } -} - -// LoadPublicUserUser loads the arcgisuser's PublicUserUser into the .R struct -func (o *ArcgisUser) LoadPublicUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.PublicUserUser = nil - - related, err := o.PublicUserUser(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.PublicUserUser = ArcgisUserSlice{o} - - o.R.PublicUserUser = related - return nil -} - -// LoadPublicUserUser loads the arcgisuser's PublicUserUser into the .R struct -func (os ArcgisUserSlice) LoadPublicUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - users, err := os.PublicUserUser(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range users { - - if !(o.PublicUserID == rel.ID) { - continue - } - - rel.R.PublicUserUser = append(rel.R.PublicUserUser, o) - - o.R.PublicUserUser = rel - break - } - } - - return nil -} - -// LoadUserUserPrivileges loads the arcgisuser's UserUserPrivileges into the .R struct -func (o *ArcgisUser) LoadUserUserPrivileges(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.UserUserPrivileges = nil - - related, err := o.UserUserPrivileges(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.UserUser = o - } - - o.R.UserUserPrivileges = related - return nil -} - -// LoadUserUserPrivileges loads the arcgisuser's UserUserPrivileges into the .R struct -func (os ArcgisUserSlice) LoadUserUserPrivileges(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisUserPrivileges, err := os.UserUserPrivileges(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.UserUserPrivileges = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisUserPrivileges { - - if !(o.ID == rel.UserID) { - continue - } - - rel.R.UserUser = o - - o.R.UserUserPrivileges = append(o.R.UserUserPrivileges, rel) - } - } - - return nil -} diff --git a/db/models/arcgis.user_privilege.bob.go b/db/models/arcgis.user_privilege.bob.go deleted file mode 100644 index 7573f0dd..00000000 --- a/db/models/arcgis.user_privilege.bob.go +++ /dev/null @@ -1,582 +0,0 @@ -// Code generated by BobGen psql v0.42.5. DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package models - -import ( - "context" - "fmt" - "io" - - "github.com/Gleipnir-Technology/bob" - "github.com/Gleipnir-Technology/bob/dialect/psql" - "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" - "github.com/Gleipnir-Technology/bob/dialect/psql/dm" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" - "github.com/Gleipnir-Technology/bob/expr" - "github.com/Gleipnir-Technology/bob/orm" - "github.com/Gleipnir-Technology/bob/types/pgtypes" - "github.com/aarondl/opt/omit" -) - -// ArcgisUserPrivilege is an object representing the database table. -type ArcgisUserPrivilege struct { - UserID string `db:"user_id,pk" ` - Privilege string `db:"privilege,pk" ` - - R arcgisUserPrivilegeR `db:"-" ` -} - -// ArcgisUserPrivilegeSlice is an alias for a slice of pointers to ArcgisUserPrivilege. -// This should almost always be used instead of []*ArcgisUserPrivilege. -type ArcgisUserPrivilegeSlice []*ArcgisUserPrivilege - -// ArcgisUserPrivileges contains methods to work with the user_privilege table -var ArcgisUserPrivileges = psql.NewTablex[*ArcgisUserPrivilege, ArcgisUserPrivilegeSlice, *ArcgisUserPrivilegeSetter]("arcgis", "user_privilege", buildArcgisUserPrivilegeColumns("arcgis.user_privilege")) - -// ArcgisUserPrivilegesQuery is a query on the user_privilege table -type ArcgisUserPrivilegesQuery = *psql.ViewQuery[*ArcgisUserPrivilege, ArcgisUserPrivilegeSlice] - -// arcgisUserPrivilegeR is where relationships are stored. -type arcgisUserPrivilegeR struct { - UserUser *ArcgisUser // arcgis.user_privilege.user_privilege_user_id_fkey -} - -func buildArcgisUserPrivilegeColumns(alias string) arcgisUserPrivilegeColumns { - return arcgisUserPrivilegeColumns{ - ColumnsExpr: expr.NewColumnsExpr( - "user_id", "privilege", - ).WithParent("arcgis.user_privilege"), - tableAlias: alias, - UserID: psql.Quote(alias, "user_id"), - Privilege: psql.Quote(alias, "privilege"), - } -} - -type arcgisUserPrivilegeColumns struct { - expr.ColumnsExpr - tableAlias string - UserID psql.Expression - Privilege psql.Expression -} - -func (c arcgisUserPrivilegeColumns) Alias() string { - return c.tableAlias -} - -func (arcgisUserPrivilegeColumns) AliasedAs(alias string) arcgisUserPrivilegeColumns { - return buildArcgisUserPrivilegeColumns(alias) -} - -// ArcgisUserPrivilegeSetter is used for insert/upsert/update operations -// All values are optional, and do not have to be set -// Generated columns are not included -type ArcgisUserPrivilegeSetter struct { - UserID omit.Val[string] `db:"user_id,pk" ` - Privilege omit.Val[string] `db:"privilege,pk" ` -} - -func (s ArcgisUserPrivilegeSetter) SetColumns() []string { - vals := make([]string, 0, 2) - if s.UserID.IsValue() { - vals = append(vals, "user_id") - } - if s.Privilege.IsValue() { - vals = append(vals, "privilege") - } - return vals -} - -func (s ArcgisUserPrivilegeSetter) Overwrite(t *ArcgisUserPrivilege) { - if s.UserID.IsValue() { - t.UserID = s.UserID.MustGet() - } - if s.Privilege.IsValue() { - t.Privilege = s.Privilege.MustGet() - } -} - -func (s *ArcgisUserPrivilegeSetter) Apply(q *dialect.InsertQuery) { - q.AppendHooks(func(ctx context.Context, exec bob.Executor) (context.Context, error) { - return ArcgisUserPrivileges.BeforeInsertHooks.RunHooks(ctx, exec, s) - }) - - q.AppendValues(bob.ExpressionFunc(func(ctx context.Context, w io.StringWriter, d bob.Dialect, start int) ([]any, error) { - vals := make([]bob.Expression, 2) - if s.UserID.IsValue() { - vals[0] = psql.Arg(s.UserID.MustGet()) - } else { - vals[0] = psql.Raw("DEFAULT") - } - - if s.Privilege.IsValue() { - vals[1] = psql.Arg(s.Privilege.MustGet()) - } else { - vals[1] = psql.Raw("DEFAULT") - } - - return bob.ExpressSlice(ctx, w, d, start, vals, "", ", ", "") - })) -} - -func (s ArcgisUserPrivilegeSetter) UpdateMod() bob.Mod[*dialect.UpdateQuery] { - return um.Set(s.Expressions()...) -} - -func (s ArcgisUserPrivilegeSetter) Expressions(prefix ...string) []bob.Expression { - exprs := make([]bob.Expression, 0, 2) - - 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.Privilege.IsValue() { - exprs = append(exprs, expr.Join{Sep: " = ", Exprs: []bob.Expression{ - psql.Quote(append(prefix, "privilege")...), - psql.Arg(s.Privilege), - }}) - } - - return exprs -} - -// FindArcgisUserPrivilege retrieves a single record by primary key -// If cols is empty Find will return all columns. -func FindArcgisUserPrivilege(ctx context.Context, exec bob.Executor, UserIDPK string, PrivilegePK string, cols ...string) (*ArcgisUserPrivilege, error) { - if len(cols) == 0 { - return ArcgisUserPrivileges.Query( - sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))), - sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))), - ).One(ctx, exec) - } - - return ArcgisUserPrivileges.Query( - sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))), - sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))), - sm.Columns(ArcgisUserPrivileges.Columns.Only(cols...)), - ).One(ctx, exec) -} - -// ArcgisUserPrivilegeExists checks the presence of a single record by primary key -func ArcgisUserPrivilegeExists(ctx context.Context, exec bob.Executor, UserIDPK string, PrivilegePK string) (bool, error) { - return ArcgisUserPrivileges.Query( - sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(UserIDPK))), - sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(PrivilegePK))), - ).Exists(ctx, exec) -} - -// AfterQueryHook is called after ArcgisUserPrivilege is retrieved from the database -func (o *ArcgisUserPrivilege) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisUserPrivileges.AfterSelectHooks.RunHooks(ctx, exec, ArcgisUserPrivilegeSlice{o}) - case bob.QueryTypeInsert: - ctx, err = ArcgisUserPrivileges.AfterInsertHooks.RunHooks(ctx, exec, ArcgisUserPrivilegeSlice{o}) - case bob.QueryTypeUpdate: - ctx, err = ArcgisUserPrivileges.AfterUpdateHooks.RunHooks(ctx, exec, ArcgisUserPrivilegeSlice{o}) - case bob.QueryTypeDelete: - ctx, err = ArcgisUserPrivileges.AfterDeleteHooks.RunHooks(ctx, exec, ArcgisUserPrivilegeSlice{o}) - } - - return err -} - -// primaryKeyVals returns the primary key values of the ArcgisUserPrivilege -func (o *ArcgisUserPrivilege) primaryKeyVals() bob.Expression { - return psql.ArgGroup( - o.UserID, - o.Privilege, - ) -} - -func (o *ArcgisUserPrivilege) pkEQ() dialect.Expression { - return psql.Group(psql.Quote("arcgis.user_privilege", "user_id"), psql.Quote("arcgis.user_privilege", "privilege")).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 ArcgisUserPrivilege -func (o *ArcgisUserPrivilege) Update(ctx context.Context, exec bob.Executor, s *ArcgisUserPrivilegeSetter) error { - v, err := ArcgisUserPrivileges.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 ArcgisUserPrivilege record with an executor -func (o *ArcgisUserPrivilege) Delete(ctx context.Context, exec bob.Executor) error { - _, err := ArcgisUserPrivileges.Delete(dm.Where(o.pkEQ())).Exec(ctx, exec) - return err -} - -// Reload refreshes the ArcgisUserPrivilege using the executor -func (o *ArcgisUserPrivilege) Reload(ctx context.Context, exec bob.Executor) error { - o2, err := ArcgisUserPrivileges.Query( - sm.Where(ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(o.UserID))), - sm.Where(ArcgisUserPrivileges.Columns.Privilege.EQ(psql.Arg(o.Privilege))), - ).One(ctx, exec) - if err != nil { - return err - } - o2.R = o.R - *o = *o2 - - return nil -} - -// AfterQueryHook is called after ArcgisUserPrivilegeSlice is retrieved from the database -func (o ArcgisUserPrivilegeSlice) AfterQueryHook(ctx context.Context, exec bob.Executor, queryType bob.QueryType) error { - var err error - - switch queryType { - case bob.QueryTypeSelect: - ctx, err = ArcgisUserPrivileges.AfterSelectHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeInsert: - ctx, err = ArcgisUserPrivileges.AfterInsertHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeUpdate: - ctx, err = ArcgisUserPrivileges.AfterUpdateHooks.RunHooks(ctx, exec, o) - case bob.QueryTypeDelete: - ctx, err = ArcgisUserPrivileges.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err -} - -func (o ArcgisUserPrivilegeSlice) pkIN() dialect.Expression { - if len(o) == 0 { - return psql.Raw("NULL") - } - - return psql.Group(psql.Quote("arcgis.user_privilege", "user_id"), psql.Quote("arcgis.user_privilege", "privilege")).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 ArcgisUserPrivilegeSlice) copyMatchingRows(from ...*ArcgisUserPrivilege) { - for i, old := range o { - for _, new := range from { - if new.UserID != old.UserID { - continue - } - if new.Privilege != old.Privilege { - continue - } - new.R = old.R - o[i] = new - break - } - } -} - -// UpdateMod modifies an update query with "WHERE primary_key IN (o...)" -func (o ArcgisUserPrivilegeSlice) 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 ArcgisUserPrivileges.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 *ArcgisUserPrivilege: - o.copyMatchingRows(retrieved) - case []*ArcgisUserPrivilege: - o.copyMatchingRows(retrieved...) - case ArcgisUserPrivilegeSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisUserPrivilege or a slice of ArcgisUserPrivilege - // then run the AfterUpdateHooks on the slice - _, err = ArcgisUserPrivileges.AfterUpdateHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -// DeleteMod modifies an delete query with "WHERE primary_key IN (o...)" -func (o ArcgisUserPrivilegeSlice) 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 ArcgisUserPrivileges.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 *ArcgisUserPrivilege: - o.copyMatchingRows(retrieved) - case []*ArcgisUserPrivilege: - o.copyMatchingRows(retrieved...) - case ArcgisUserPrivilegeSlice: - o.copyMatchingRows(retrieved...) - default: - // If the retrieved value is not a ArcgisUserPrivilege or a slice of ArcgisUserPrivilege - // then run the AfterDeleteHooks on the slice - _, err = ArcgisUserPrivileges.AfterDeleteHooks.RunHooks(ctx, exec, o) - } - - return err - })) - - q.AppendWhere(o.pkIN()) - }) -} - -func (o ArcgisUserPrivilegeSlice) UpdateAll(ctx context.Context, exec bob.Executor, vals ArcgisUserPrivilegeSetter) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisUserPrivileges.Update(vals.UpdateMod(), o.UpdateMod()).All(ctx, exec) - return err -} - -func (o ArcgisUserPrivilegeSlice) DeleteAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - _, err := ArcgisUserPrivileges.Delete(o.DeleteMod()).Exec(ctx, exec) - return err -} - -func (o ArcgisUserPrivilegeSlice) ReloadAll(ctx context.Context, exec bob.Executor) error { - if len(o) == 0 { - return nil - } - - o2, err := ArcgisUserPrivileges.Query(sm.Where(o.pkIN())).All(ctx, exec) - if err != nil { - return err - } - - o.copyMatchingRows(o2...) - - return nil -} - -// UserUser starts a query for related objects on arcgis.user_ -func (o *ArcgisUserPrivilege) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery { - return ArcgisUsers.Query(append(mods, - sm.Where(ArcgisUsers.Columns.ID.EQ(psql.Arg(o.UserID))), - )...) -} - -func (os ArcgisUserPrivilegeSlice) UserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery { - pkUserID := make(pgtypes.Array[string], 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), "text[]")), - )) - - return ArcgisUsers.Query(append(mods, - sm.Where(psql.Group(ArcgisUsers.Columns.ID).OP("IN", PKArgExpr)), - )...) -} - -func attachArcgisUserPrivilegeUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisUserPrivilege0 *ArcgisUserPrivilege, arcgisuser1 *ArcgisUser) (*ArcgisUserPrivilege, error) { - setter := &ArcgisUserPrivilegeSetter{ - UserID: omit.From(arcgisuser1.ID), - } - - err := arcgisUserPrivilege0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachArcgisUserPrivilegeUserUser0: %w", err) - } - - return arcgisUserPrivilege0, nil -} - -func (arcgisUserPrivilege0 *ArcgisUserPrivilege) InsertUserUser(ctx context.Context, exec bob.Executor, related *ArcgisUserSetter) error { - var err error - - arcgisuser1, err := ArcgisUsers.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachArcgisUserPrivilegeUserUser0(ctx, exec, 1, arcgisUserPrivilege0, arcgisuser1) - if err != nil { - return err - } - - arcgisUserPrivilege0.R.UserUser = arcgisuser1 - - arcgisuser1.R.UserUserPrivileges = append(arcgisuser1.R.UserUserPrivileges, arcgisUserPrivilege0) - - return nil -} - -func (arcgisUserPrivilege0 *ArcgisUserPrivilege) AttachUserUser(ctx context.Context, exec bob.Executor, arcgisuser1 *ArcgisUser) error { - var err error - - _, err = attachArcgisUserPrivilegeUserUser0(ctx, exec, 1, arcgisUserPrivilege0, arcgisuser1) - if err != nil { - return err - } - - arcgisUserPrivilege0.R.UserUser = arcgisuser1 - - arcgisuser1.R.UserUserPrivileges = append(arcgisuser1.R.UserUserPrivileges, arcgisUserPrivilege0) - - return nil -} - -type arcgisUserPrivilegeWhere[Q psql.Filterable] struct { - UserID psql.WhereMod[Q, string] - Privilege psql.WhereMod[Q, string] -} - -func (arcgisUserPrivilegeWhere[Q]) AliasedAs(alias string) arcgisUserPrivilegeWhere[Q] { - return buildArcgisUserPrivilegeWhere[Q](buildArcgisUserPrivilegeColumns(alias)) -} - -func buildArcgisUserPrivilegeWhere[Q psql.Filterable](cols arcgisUserPrivilegeColumns) arcgisUserPrivilegeWhere[Q] { - return arcgisUserPrivilegeWhere[Q]{ - UserID: psql.Where[Q, string](cols.UserID), - Privilege: psql.Where[Q, string](cols.Privilege), - } -} - -func (o *ArcgisUserPrivilege) Preload(name string, retrieved any) error { - if o == nil { - return nil - } - - switch name { - case "UserUser": - rel, ok := retrieved.(*ArcgisUser) - if !ok { - return fmt.Errorf("arcgisUserPrivilege cannot load %T as %q", retrieved, name) - } - - o.R.UserUser = rel - - if rel != nil { - rel.R.UserUserPrivileges = ArcgisUserPrivilegeSlice{o} - } - return nil - default: - return fmt.Errorf("arcgisUserPrivilege has no relationship %q", name) - } -} - -type arcgisUserPrivilegePreloader struct { - UserUser func(...psql.PreloadOption) psql.Preloader -} - -func buildArcgisUserPrivilegePreloader() arcgisUserPrivilegePreloader { - return arcgisUserPrivilegePreloader{ - UserUser: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisUser, ArcgisUserSlice](psql.PreloadRel{ - Name: "UserUser", - Sides: []psql.PreloadSide{ - { - From: ArcgisUserPrivileges, - To: ArcgisUsers, - FromColumns: []string{"user_id"}, - ToColumns: []string{"id"}, - }, - }, - }, ArcgisUsers.Columns.Names(), opts...) - }, - } -} - -type arcgisUserPrivilegeThenLoader[Q orm.Loadable] struct { - UserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] -} - -func buildArcgisUserPrivilegeThenLoader[Q orm.Loadable]() arcgisUserPrivilegeThenLoader[Q] { - type UserUserLoadInterface interface { - LoadUserUser(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - - return arcgisUserPrivilegeThenLoader[Q]{ - UserUser: thenLoadBuilder[Q]( - "UserUser", - func(ctx context.Context, exec bob.Executor, retrieved UserUserLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadUserUser(ctx, exec, mods...) - }, - ), - } -} - -// LoadUserUser loads the arcgisUserPrivilege's UserUser into the .R struct -func (o *ArcgisUserPrivilege) 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.UserUserPrivileges = ArcgisUserPrivilegeSlice{o} - - o.R.UserUser = related - return nil -} - -// LoadUserUser loads the arcgisUserPrivilege's UserUser into the .R struct -func (os ArcgisUserPrivilegeSlice) LoadUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisusers, err := os.UserUser(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisusers { - - if !(o.UserID == rel.ID) { - continue - } - - rel.R.UserUserPrivileges = append(rel.R.UserUserPrivileges, o) - - o.R.UserUser = rel - break - } - } - - return nil -} diff --git a/db/models/bob_loaders.bob.go b/db/models/bob_loaders.bob.go index 132a439f..7b35b588 100644 --- a/db/models/bob_loaders.bob.go +++ b/db/models/bob_loaders.bob.go @@ -18,16 +18,6 @@ var Preload = getPreloaders() type preloaders struct { Address addressPreloader - ArcgisAccount arcgisAccountPreloader - ArcgisAddressMapping arcgisAddressMappingPreloader - ArcgisLayer arcgisLayerPreloader - ArcgisLayerField arcgisLayerFieldPreloader - ArcgisOauthToken arcgisOauthTokenPreloader - ArcgisParcelMapping arcgisParcelMappingPreloader - ArcgisServiceFeature arcgisServiceFeaturePreloader - ArcgisServiceMap arcgisServiceMapPreloader - ArcgisUser arcgisuserPreloader - ArcgisUserPrivilege arcgisUserPrivilegePreloader CommsEmailContact commsEmailContactPreloader CommsEmailLog commsEmailLogPreloader CommsEmailTemplate commsEmailTemplatePreloader @@ -122,16 +112,6 @@ type preloaders struct { func getPreloaders() preloaders { return preloaders{ Address: buildAddressPreloader(), - ArcgisAccount: buildArcgisAccountPreloader(), - ArcgisAddressMapping: buildArcgisAddressMappingPreloader(), - ArcgisLayer: buildArcgisLayerPreloader(), - ArcgisLayerField: buildArcgisLayerFieldPreloader(), - ArcgisOauthToken: buildArcgisOauthTokenPreloader(), - ArcgisParcelMapping: buildArcgisParcelMappingPreloader(), - ArcgisServiceFeature: buildArcgisServiceFeaturePreloader(), - ArcgisServiceMap: buildArcgisServiceMapPreloader(), - ArcgisUser: buildArcgisUserPreloader(), - ArcgisUserPrivilege: buildArcgisUserPrivilegePreloader(), CommsEmailContact: buildCommsEmailContactPreloader(), CommsEmailLog: buildCommsEmailLogPreloader(), CommsEmailTemplate: buildCommsEmailTemplatePreloader(), @@ -232,16 +212,6 @@ var ( type thenLoaders[Q orm.Loadable] struct { Address addressThenLoader[Q] - ArcgisAccount arcgisAccountThenLoader[Q] - ArcgisAddressMapping arcgisAddressMappingThenLoader[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] CommsEmailLog commsEmailLogThenLoader[Q] CommsEmailTemplate commsEmailTemplateThenLoader[Q] @@ -336,16 +306,6 @@ 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](), - 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](), CommsEmailLog: buildCommsEmailLogThenLoader[Q](), CommsEmailTemplate: buildCommsEmailTemplateThenLoader[Q](), diff --git a/db/models/bob_where.bob.go b/db/models/bob_where.bob.go index 43062d3b..d86c6277 100644 --- a/db/models/bob_where.bob.go +++ b/db/models/bob_where.bob.go @@ -18,16 +18,6 @@ var ( func Where[Q psql.Filterable]() struct { Addresses addressWhere[Q] - ArcgisAccounts arcgisAccountWhere[Q] - ArcgisAddressMappings arcgisAddressMappingWhere[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] @@ -130,16 +120,6 @@ func Where[Q psql.Filterable]() struct { } { return struct { Addresses addressWhere[Q] - ArcgisAccounts arcgisAccountWhere[Q] - ArcgisAddressMappings arcgisAddressMappingWhere[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] @@ -241,16 +221,6 @@ func Where[Q psql.Filterable]() struct { Users userWhere[Q] }{ Addresses: buildAddressWhere[Q](Addresses.Columns), - ArcgisAccounts: buildArcgisAccountWhere[Q](ArcgisAccounts.Columns), - ArcgisAddressMappings: buildArcgisAddressMappingWhere[Q](ArcgisAddressMappings.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), diff --git a/db/models/organization.bob.go b/db/models/organization.bob.go index 8905ccf2..01ce4fbb 100644 --- a/db/models/organization.bob.go +++ b/db/models/organization.bob.go @@ -78,54 +78,48 @@ type OrganizationsQuery = *psql.ViewQuery[*Organization, OrganizationSlice] // organizationR is where relationships are stored. type organizationR struct { - 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 - Features FeatureSlice // feature.feature_organization_id_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 - H3Aggregations H3AggregationSlice // h3_aggregation.h3_aggregation_organization_id_fkey - Leads LeadSlice // lead.lead_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 - ArcgisMapServiceServiceMap *ArcgisServiceMap // organization.organization_arcgis_map_service_id_fkey - FieldseekerServiceFeatureItemServiceFeature *ArcgisServiceFeature // organization.organization_fieldseeker_service_feature_item_id_fkey - NuisanceOlds PublicreportNuisanceOldSlice // publicreport.nuisance_old.nuisance_organization_id_fkey - Reports PublicreportReportSlice // publicreport.report.report_organization_id_fkey - WaterOlds PublicreportWaterOldSlice // publicreport.water_old.pool_organization_id_fkey - ReviewTasks ReviewTaskSlice // review_task.review_task_organization_id_fkey - Signals SignalSlice // signal.signal_organization_id_fkey - User UserSlice // user_.user__organization_id_fkey + 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 + Features FeatureSlice // feature.feature_organization_id_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 + H3Aggregations H3AggregationSlice // h3_aggregation.h3_aggregation_organization_id_fkey + Leads LeadSlice // lead.lead_organization_id_fkey + NoteAudios NoteAudioSlice // note_audio.note_audio_organization_id_fkey + NoteImages NoteImageSlice // note_image.note_image_organization_id_fkey + NuisanceOlds PublicreportNuisanceOldSlice // publicreport.nuisance_old.nuisance_organization_id_fkey + Reports PublicreportReportSlice // publicreport.report.report_organization_id_fkey + WaterOlds PublicreportWaterOldSlice // publicreport.water_old.pool_organization_id_fkey + ReviewTasks ReviewTaskSlice // review_task.review_task_organization_id_fkey + Signals SignalSlice // signal.signal_organization_id_fkey + User UserSlice // user_.user__organization_id_fkey } func buildOrganizationColumns(alias string) organizationColumns { @@ -978,78 +972,6 @@ 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, - sm.Where(ArcgisAddressMappings.Columns.OrganizationID.EQ(psql.Arg(o.ID))), - )...) -} - -func (os OrganizationSlice) AddressMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisAddressMappingsQuery { - 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 ArcgisAddressMappings.Query(append(mods, - sm.Where(psql.Group(ArcgisAddressMappings.Columns.OrganizationID).OP("IN", PKArgExpr)), - )...) -} - -// ParcelMappings starts a query for related objects on arcgis.parcel_mapping -func (o *Organization) ParcelMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisParcelMappingsQuery { - return ArcgisParcelMappings.Query(append(mods, - sm.Where(ArcgisParcelMappings.Columns.OrganizationID.EQ(psql.Arg(o.ID))), - )...) -} - -func (os OrganizationSlice) ParcelMappings(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisParcelMappingsQuery { - 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 ArcgisParcelMappings.Query(append(mods, - sm.Where(psql.Group(ArcgisParcelMappings.Columns.OrganizationID).OP("IN", PKArgExpr)), - )...) -} - // EmailContacts starts a query for related objects on comms.email_contact func (o *Organization) EmailContacts(mods ...bob.Mod[*dialect.SelectQuery]) CommsEmailContactsQuery { return CommsEmailContacts.Query(append(mods, @@ -1924,78 +1846,6 @@ 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)), - )...) -} - -// ArcgisMapServiceServiceMap starts a query for related objects on arcgis.service_map -func (o *Organization) ArcgisMapServiceServiceMap(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { - return ArcgisServiceMaps.Query(append(mods, - sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(o.ArcgisMapServiceID))), - )...) -} - -func (os OrganizationSlice) ArcgisMapServiceServiceMap(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { - pkArcgisMapServiceID := make(pgtypes.Array[null.Val[string]], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkArcgisMapServiceID = append(pkArcgisMapServiceID, o.ArcgisMapServiceID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkArcgisMapServiceID), "text[]")), - )) - - return ArcgisServiceMaps.Query(append(mods, - sm.Where(psql.Group(ArcgisServiceMaps.Columns.ArcgisID).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)), - )...) -} - // NuisanceOlds starts a query for related objects on publicreport.nuisance_old func (o *Organization) NuisanceOlds(mods ...bob.Mod[*dialect.SelectQuery]) PublicreportNuisanceOldsQuery { return PublicreportNuisanceOlds.Query(append(mods, @@ -2140,210 +1990,6 @@ 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) - } - - ret, err := ArcgisAddressMappings.Insert(bob.ToMods(arcgisAddressMappings1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertOrganizationAddressMappings0: %w", err) - } - - return ret, nil -} - -func attachOrganizationAddressMappings0(ctx context.Context, exec bob.Executor, count int, arcgisAddressMappings1 ArcgisAddressMappingSlice, organization0 *Organization) (ArcgisAddressMappingSlice, error) { - setter := &ArcgisAddressMappingSetter{ - OrganizationID: omit.From(organization0.ID), - } - - err := arcgisAddressMappings1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachOrganizationAddressMappings0: %w", err) - } - - return arcgisAddressMappings1, nil -} - -func (organization0 *Organization) InsertAddressMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisAddressMappingSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisAddressMappings1, err := insertOrganizationAddressMappings0(ctx, exec, related, organization0) - if err != nil { - return err - } - - organization0.R.AddressMappings = append(organization0.R.AddressMappings, arcgisAddressMappings1...) - - for _, rel := range arcgisAddressMappings1 { - rel.R.Organization = organization0 - } - return nil -} - -func (organization0 *Organization) AttachAddressMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisAddressMapping) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisAddressMappings1 := ArcgisAddressMappingSlice(related) - - _, err = attachOrganizationAddressMappings0(ctx, exec, len(related), arcgisAddressMappings1, organization0) - if err != nil { - return err - } - - organization0.R.AddressMappings = append(organization0.R.AddressMappings, arcgisAddressMappings1...) - - for _, rel := range related { - rel.R.Organization = organization0 - } - - return nil -} - -func insertOrganizationParcelMappings0(ctx context.Context, exec bob.Executor, arcgisParcelMappings1 []*ArcgisParcelMappingSetter, organization0 *Organization) (ArcgisParcelMappingSlice, error) { - for i := range arcgisParcelMappings1 { - arcgisParcelMappings1[i].OrganizationID = omit.From(organization0.ID) - } - - ret, err := ArcgisParcelMappings.Insert(bob.ToMods(arcgisParcelMappings1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertOrganizationParcelMappings0: %w", err) - } - - return ret, nil -} - -func attachOrganizationParcelMappings0(ctx context.Context, exec bob.Executor, count int, arcgisParcelMappings1 ArcgisParcelMappingSlice, organization0 *Organization) (ArcgisParcelMappingSlice, error) { - setter := &ArcgisParcelMappingSetter{ - OrganizationID: omit.From(organization0.ID), - } - - err := arcgisParcelMappings1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachOrganizationParcelMappings0: %w", err) - } - - return arcgisParcelMappings1, nil -} - -func (organization0 *Organization) InsertParcelMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisParcelMappingSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisParcelMappings1, err := insertOrganizationParcelMappings0(ctx, exec, related, organization0) - if err != nil { - return err - } - - organization0.R.ParcelMappings = append(organization0.R.ParcelMappings, arcgisParcelMappings1...) - - for _, rel := range arcgisParcelMappings1 { - rel.R.Organization = organization0 - } - return nil -} - -func (organization0 *Organization) AttachParcelMappings(ctx context.Context, exec bob.Executor, related ...*ArcgisParcelMapping) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisParcelMappings1 := ArcgisParcelMappingSlice(related) - - _, err = attachOrganizationParcelMappings0(ctx, exec, len(related), arcgisParcelMappings1, organization0) - if err != nil { - return err - } - - organization0.R.ParcelMappings = append(organization0.R.ParcelMappings, arcgisParcelMappings1...) - - for _, rel := range related { - rel.R.Organization = organization0 - } - - return nil -} - func attachOrganizationEmailContacts0(ctx context.Context, exec bob.Executor, count int, organization0 *Organization, commsEmailContacts2 CommsEmailContactSlice) (DistrictSubscriptionEmailSlice, error) { setters := make([]*DistrictSubscriptionEmailSetter, count) for i := range count { @@ -4786,150 +4432,6 @@ 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 attachOrganizationArcgisMapServiceServiceMap0(ctx context.Context, exec bob.Executor, count int, organization0 *Organization, arcgisServiceMap1 *ArcgisServiceMap) (*Organization, error) { - setter := &OrganizationSetter{ - ArcgisMapServiceID: omitnull.From(arcgisServiceMap1.ArcgisID), - } - - err := organization0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachOrganizationArcgisMapServiceServiceMap0: %w", err) - } - - return organization0, nil -} - -func (organization0 *Organization) InsertArcgisMapServiceServiceMap(ctx context.Context, exec bob.Executor, related *ArcgisServiceMapSetter) error { - var err error - - arcgisServiceMap1, err := ArcgisServiceMaps.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachOrganizationArcgisMapServiceServiceMap0(ctx, exec, 1, organization0, arcgisServiceMap1) - if err != nil { - return err - } - - organization0.R.ArcgisMapServiceServiceMap = arcgisServiceMap1 - - arcgisServiceMap1.R.ArcgisMapServiceOrganizations = append(arcgisServiceMap1.R.ArcgisMapServiceOrganizations, organization0) - - return nil -} - -func (organization0 *Organization) AttachArcgisMapServiceServiceMap(ctx context.Context, exec bob.Executor, arcgisServiceMap1 *ArcgisServiceMap) error { - var err error - - _, err = attachOrganizationArcgisMapServiceServiceMap0(ctx, exec, 1, organization0, arcgisServiceMap1) - if err != nil { - return err - } - - organization0.R.ArcgisMapServiceServiceMap = arcgisServiceMap1 - - arcgisServiceMap1.R.ArcgisMapServiceOrganizations = append(arcgisServiceMap1.R.ArcgisMapServiceOrganizations, 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 insertOrganizationNuisanceOlds0(ctx context.Context, exec bob.Executor, publicreportNuisanceOlds1 []*PublicreportNuisanceOldSetter, organization0 *Organization) (PublicreportNuisanceOldSlice, error) { for i := range publicreportNuisanceOlds1 { publicreportNuisanceOlds1[i].OrganizationID = omit.From(organization0.ID) @@ -5426,48 +4928,6 @@ 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 { - return fmt.Errorf("organization cannot load %T as %q", retrieved, name) - } - - o.R.AddressMappings = rels - - for _, rel := range rels { - if rel != nil { - rel.R.Organization = o - } - } - return nil - case "ParcelMappings": - rels, ok := retrieved.(ArcgisParcelMappingSlice) - if !ok { - return fmt.Errorf("organization cannot load %T as %q", retrieved, name) - } - - o.R.ParcelMappings = rels - - for _, rel := range rels { - if rel != nil { - rel.R.Organization = o - } - } - return nil case "EmailContacts": rels, ok := retrieved.(CommsEmailContactSlice) if !ok { @@ -5972,42 +5432,6 @@ 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 "ArcgisMapServiceServiceMap": - rel, ok := retrieved.(*ArcgisServiceMap) - if !ok { - return fmt.Errorf("organization cannot load %T as %q", retrieved, name) - } - - o.R.ArcgisMapServiceServiceMap = rel - - if rel != nil { - rel.R.ArcgisMapServiceOrganizations = 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 "NuisanceOlds": rels, ok := retrieved.(PublicreportNuisanceOldSlice) if !ok { @@ -6097,117 +5521,58 @@ func (o *Organization) Preload(name string, retrieved any) error { } } -type organizationPreloader struct { - ArcgisAccountAccount func(...psql.PreloadOption) psql.Preloader - ArcgisMapServiceServiceMap func(...psql.PreloadOption) psql.Preloader - FieldseekerServiceFeatureItemServiceFeature func(...psql.PreloadOption) psql.Preloader -} +type organizationPreloader struct{} func buildOrganizationPreloader() 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...) - }, - ArcgisMapServiceServiceMap: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisServiceMap, ArcgisServiceMapSlice](psql.PreloadRel{ - Name: "ArcgisMapServiceServiceMap", - Sides: []psql.PreloadSide{ - { - From: Organizations, - To: ArcgisServiceMaps, - FromColumns: []string{"arcgis_map_service_id"}, - ToColumns: []string{"arcgis_id"}, - }, - }, - }, ArcgisServiceMaps.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...) - }, - } + return organizationPreloader{} } type organizationThenLoader[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] - Phones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Features 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] - H3Aggregations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Leads 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] - ArcgisMapServiceServiceMap func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - FieldseekerServiceFeatureItemServiceFeature func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - NuisanceOlds func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Reports func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - WaterOlds func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - ReviewTasks func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - Signals func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - User func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + EmailContacts func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Phones func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Features 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] + H3Aggregations func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Leads 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] + NuisanceOlds func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Reports func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + WaterOlds func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + ReviewTasks func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + Signals func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + User func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } 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 - } - type ParcelMappingsLoadInterface interface { - LoadParcelMappings(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } type EmailContactsLoadInterface interface { LoadEmailContacts(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -6316,15 +5681,6 @@ 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 ArcgisMapServiceServiceMapLoadInterface interface { - LoadArcgisMapServiceServiceMap(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } - type FieldseekerServiceFeatureItemServiceFeatureLoadInterface interface { - LoadFieldseekerServiceFeatureItemServiceFeature(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } type NuisanceOldsLoadInterface interface { LoadNuisanceOlds(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -6345,24 +5701,6 @@ 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 { - return retrieved.LoadAddressMappings(ctx, exec, mods...) - }, - ), - ParcelMappings: thenLoadBuilder[Q]( - "ParcelMappings", - func(ctx context.Context, exec bob.Executor, retrieved ParcelMappingsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadParcelMappings(ctx, exec, mods...) - }, - ), EmailContacts: thenLoadBuilder[Q]( "EmailContacts", func(ctx context.Context, exec bob.Executor, retrieved EmailContactsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -6579,24 +5917,6 @@ 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...) - }, - ), - ArcgisMapServiceServiceMap: thenLoadBuilder[Q]( - "ArcgisMapServiceServiceMap", - func(ctx context.Context, exec bob.Executor, retrieved ArcgisMapServiceServiceMapLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadArcgisMapServiceServiceMap(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...) - }, - ), NuisanceOlds: thenLoadBuilder[Q]( "NuisanceOlds", func(ctx context.Context, exec bob.Executor, retrieved NuisanceOldsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -6636,189 +5956,6 @@ 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 { - return nil - } - - // Reset the relationship - o.R.AddressMappings = nil - - related, err := o.AddressMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.Organization = o - } - - o.R.AddressMappings = related - return nil -} - -// LoadAddressMappings loads the organization's AddressMappings into the .R struct -func (os OrganizationSlice) LoadAddressMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisAddressMappings, err := os.AddressMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.AddressMappings = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisAddressMappings { - - if !(o.ID == rel.OrganizationID) { - continue - } - - rel.R.Organization = o - - o.R.AddressMappings = append(o.R.AddressMappings, rel) - } - } - - return nil -} - -// LoadParcelMappings loads the organization's ParcelMappings into the .R struct -func (o *Organization) LoadParcelMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ParcelMappings = nil - - related, err := o.ParcelMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.Organization = o - } - - o.R.ParcelMappings = related - return nil -} - -// LoadParcelMappings loads the organization's ParcelMappings into the .R struct -func (os OrganizationSlice) LoadParcelMappings(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisParcelMappings, err := os.ParcelMappings(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.ParcelMappings = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisParcelMappings { - - if !(o.ID == rel.OrganizationID) { - continue - } - - rel.R.Organization = o - - o.R.ParcelMappings = append(o.R.ParcelMappings, rel) - } - } - - return nil -} - // LoadEmailContacts loads the organization's EmailContacts into the .R struct func (o *Organization) LoadEmailContacts(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { @@ -9055,171 +8192,6 @@ 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 -} - -// LoadArcgisMapServiceServiceMap loads the organization's ArcgisMapServiceServiceMap into the .R struct -func (o *Organization) LoadArcgisMapServiceServiceMap(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ArcgisMapServiceServiceMap = nil - - related, err := o.ArcgisMapServiceServiceMap(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.ArcgisMapServiceOrganizations = OrganizationSlice{o} - - o.R.ArcgisMapServiceServiceMap = related - return nil -} - -// LoadArcgisMapServiceServiceMap loads the organization's ArcgisMapServiceServiceMap into the .R struct -func (os OrganizationSlice) LoadArcgisMapServiceServiceMap(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisServiceMaps, err := os.ArcgisMapServiceServiceMap(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisServiceMaps { - if !o.ArcgisMapServiceID.IsValue() { - continue - } - - if !(o.ArcgisMapServiceID.IsValue() && o.ArcgisMapServiceID.MustGet() == rel.ArcgisID) { - continue - } - - rel.R.ArcgisMapServiceOrganizations = append(rel.R.ArcgisMapServiceOrganizations, o) - - o.R.ArcgisMapServiceServiceMap = 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 -} - // LoadNuisanceOlds loads the organization's NuisanceOlds into the .R struct func (o *Organization) LoadNuisanceOlds(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { diff --git a/db/models/tile.service.bob.go b/db/models/tile.service.bob.go index fa5d9333..c05c48bd 100644 --- a/db/models/tile.service.bob.go +++ b/db/models/tile.service.bob.go @@ -43,8 +43,7 @@ type TileServicesQuery = *psql.ViewQuery[*TileService, TileServiceSlice] // tileServiceR is where relationships are stored. type tileServiceR struct { - CachedImages TileCachedImageSlice // tile.cached_image.cached_image_service_id_fkey - ArcgisServiceMap *ArcgisServiceMap // tile.service.service_arcgis_id_fkey + CachedImages TileCachedImageSlice // tile.cached_image.cached_image_service_id_fkey } func buildTileServiceColumns(alias string) tileServiceColumns { @@ -417,30 +416,6 @@ func (os TileServiceSlice) CachedImages(mods ...bob.Mod[*dialect.SelectQuery]) T )...) } -// ArcgisServiceMap starts a query for related objects on arcgis.service_map -func (o *TileService) ArcgisServiceMap(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { - return ArcgisServiceMaps.Query(append(mods, - sm.Where(ArcgisServiceMaps.Columns.ArcgisID.EQ(psql.Arg(o.ArcgisID))), - )...) -} - -func (os TileServiceSlice) ArcgisServiceMap(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisServiceMapsQuery { - pkArcgisID := make(pgtypes.Array[null.Val[string]], 0, len(os)) - for _, o := range os { - if o == nil { - continue - } - pkArcgisID = append(pkArcgisID, o.ArcgisID) - } - PKArgExpr := psql.Select(sm.Columns( - psql.F("unnest", psql.Cast(psql.Arg(pkArcgisID), "text[]")), - )) - - return ArcgisServiceMaps.Query(append(mods, - sm.Where(psql.Group(ArcgisServiceMaps.Columns.ArcgisID).OP("IN", PKArgExpr)), - )...) -} - func insertTileServiceCachedImages0(ctx context.Context, exec bob.Executor, tileCachedImages1 []*TileCachedImageSetter, tileService0 *TileService) (TileCachedImageSlice, error) { for i := range tileCachedImages1 { tileCachedImages1[i].ServiceID = omit.From(tileService0.ID) @@ -509,54 +484,6 @@ func (tileService0 *TileService) AttachCachedImages(ctx context.Context, exec bo return nil } -func attachTileServiceArcgisServiceMap0(ctx context.Context, exec bob.Executor, count int, tileService0 *TileService, arcgisServiceMap1 *ArcgisServiceMap) (*TileService, error) { - setter := &TileServiceSetter{ - ArcgisID: omitnull.From(arcgisServiceMap1.ArcgisID), - } - - err := tileService0.Update(ctx, exec, setter) - if err != nil { - return nil, fmt.Errorf("attachTileServiceArcgisServiceMap0: %w", err) - } - - return tileService0, nil -} - -func (tileService0 *TileService) InsertArcgisServiceMap(ctx context.Context, exec bob.Executor, related *ArcgisServiceMapSetter) error { - var err error - - arcgisServiceMap1, err := ArcgisServiceMaps.Insert(related).One(ctx, exec) - if err != nil { - return fmt.Errorf("inserting related objects: %w", err) - } - - _, err = attachTileServiceArcgisServiceMap0(ctx, exec, 1, tileService0, arcgisServiceMap1) - if err != nil { - return err - } - - tileService0.R.ArcgisServiceMap = arcgisServiceMap1 - - arcgisServiceMap1.R.ArcgisServices = append(arcgisServiceMap1.R.ArcgisServices, tileService0) - - return nil -} - -func (tileService0 *TileService) AttachArcgisServiceMap(ctx context.Context, exec bob.Executor, arcgisServiceMap1 *ArcgisServiceMap) error { - var err error - - _, err = attachTileServiceArcgisServiceMap0(ctx, exec, 1, tileService0, arcgisServiceMap1) - if err != nil { - return err - } - - tileService0.R.ArcgisServiceMap = arcgisServiceMap1 - - arcgisServiceMap1.R.ArcgisServices = append(arcgisServiceMap1.R.ArcgisServices, tileService0) - - return nil -} - type tileServiceWhere[Q psql.Filterable] struct { ID psql.WhereMod[Q, int32] Name psql.WhereMod[Q, string] @@ -595,57 +522,25 @@ func (o *TileService) Preload(name string, retrieved any) error { } } return nil - case "ArcgisServiceMap": - rel, ok := retrieved.(*ArcgisServiceMap) - if !ok { - return fmt.Errorf("tileService cannot load %T as %q", retrieved, name) - } - - o.R.ArcgisServiceMap = rel - - if rel != nil { - rel.R.ArcgisServices = TileServiceSlice{o} - } - return nil default: return fmt.Errorf("tileService has no relationship %q", name) } } -type tileServicePreloader struct { - ArcgisServiceMap func(...psql.PreloadOption) psql.Preloader -} +type tileServicePreloader struct{} func buildTileServicePreloader() tileServicePreloader { - return tileServicePreloader{ - ArcgisServiceMap: func(opts ...psql.PreloadOption) psql.Preloader { - return psql.Preload[*ArcgisServiceMap, ArcgisServiceMapSlice](psql.PreloadRel{ - Name: "ArcgisServiceMap", - Sides: []psql.PreloadSide{ - { - From: TileServices, - To: ArcgisServiceMaps, - FromColumns: []string{"arcgis_id"}, - ToColumns: []string{"arcgis_id"}, - }, - }, - }, ArcgisServiceMaps.Columns.Names(), opts...) - }, - } + return tileServicePreloader{} } type tileServiceThenLoader[Q orm.Loadable] struct { - CachedImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - ArcgisServiceMap func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] + CachedImages func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] } func buildTileServiceThenLoader[Q orm.Loadable]() tileServiceThenLoader[Q] { type CachedImagesLoadInterface interface { LoadCachedImages(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } - type ArcgisServiceMapLoadInterface interface { - LoadArcgisServiceMap(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error - } return tileServiceThenLoader[Q]{ CachedImages: thenLoadBuilder[Q]( @@ -654,12 +549,6 @@ func buildTileServiceThenLoader[Q orm.Loadable]() tileServiceThenLoader[Q] { return retrieved.LoadCachedImages(ctx, exec, mods...) }, ), - ArcgisServiceMap: thenLoadBuilder[Q]( - "ArcgisServiceMap", - func(ctx context.Context, exec bob.Executor, retrieved ArcgisServiceMapLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { - return retrieved.LoadArcgisServiceMap(ctx, exec, mods...) - }, - ), } } @@ -723,58 +612,3 @@ func (os TileServiceSlice) LoadCachedImages(ctx context.Context, exec bob.Execut return nil } - -// LoadArcgisServiceMap loads the tileService's ArcgisServiceMap into the .R struct -func (o *TileService) LoadArcgisServiceMap(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if o == nil { - return nil - } - - // Reset the relationship - o.R.ArcgisServiceMap = nil - - related, err := o.ArcgisServiceMap(mods...).One(ctx, exec) - if err != nil { - return err - } - - related.R.ArcgisServices = TileServiceSlice{o} - - o.R.ArcgisServiceMap = related - return nil -} - -// LoadArcgisServiceMap loads the tileService's ArcgisServiceMap into the .R struct -func (os TileServiceSlice) LoadArcgisServiceMap(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisServiceMaps, err := os.ArcgisServiceMap(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisServiceMaps { - if !o.ArcgisID.IsValue() { - continue - } - - if !(o.ArcgisID.IsValue() && o.ArcgisID.MustGet() == rel.ArcgisID) { - continue - } - - rel.R.ArcgisServices = append(rel.R.ArcgisServices, o) - - o.R.ArcgisServiceMap = rel - break - } - } - - return nil -} diff --git a/db/models/user_.bob.go b/db/models/user_.bob.go index 4a04e4ab..44c82b3f 100644 --- a/db/models/user_.bob.go +++ b/db/models/user_.bob.go @@ -60,8 +60,6 @@ type UsersQuery = *psql.ViewQuery[*User, UserSlice] // userR is where relationships are stored. type userR struct { - UserOauthTokens ArcgisOauthTokenSlice // arcgis.oauth_token.oauth_token_user_id_fkey - PublicUserUser ArcgisUserSlice // arcgis.user_.user__public_user_id_fkey CreatorTextJobs CommsTextJobSlice // comms.text_job.text_job_creator_id_fkey ClosedByCommunications CommunicationSlice // communication.communication_closed_by_fkey InvalidatedByCommunications CommunicationSlice // communication.communication_invalidated_by_fkey @@ -748,54 +746,6 @@ 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, - sm.Where(ArcgisUsers.Columns.PublicUserID.EQ(psql.Arg(o.ID))), - )...) -} - -func (os UserSlice) PublicUserUser(mods ...bob.Mod[*dialect.SelectQuery]) ArcgisUsersQuery { - 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 ArcgisUsers.Query(append(mods, - sm.Where(psql.Group(ArcgisUsers.Columns.PublicUserID).OP("IN", PKArgExpr)), - )...) -} - // CreatorTextJobs starts a query for related objects on comms.text_job func (o *User) CreatorTextJobs(mods ...bob.Mod[*dialect.SelectQuery]) CommsTextJobsQuery { return CommsTextJobs.Query(append(mods, @@ -1516,142 +1466,6 @@ 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) - } - - ret, err := ArcgisUsers.Insert(bob.ToMods(arcgisusers1...)).All(ctx, exec) - if err != nil { - return ret, fmt.Errorf("insertUserPublicUserUser0: %w", err) - } - - return ret, nil -} - -func attachUserPublicUserUser0(ctx context.Context, exec bob.Executor, count int, arcgisusers1 ArcgisUserSlice, user0 *User) (ArcgisUserSlice, error) { - setter := &ArcgisUserSetter{ - PublicUserID: omit.From(user0.ID), - } - - err := arcgisusers1.UpdateAll(ctx, exec, *setter) - if err != nil { - return nil, fmt.Errorf("attachUserPublicUserUser0: %w", err) - } - - return arcgisusers1, nil -} - -func (user0 *User) InsertPublicUserUser(ctx context.Context, exec bob.Executor, related ...*ArcgisUserSetter) error { - if len(related) == 0 { - return nil - } - - var err error - - arcgisusers1, err := insertUserPublicUserUser0(ctx, exec, related, user0) - if err != nil { - return err - } - - user0.R.PublicUserUser = append(user0.R.PublicUserUser, arcgisusers1...) - - for _, rel := range arcgisusers1 { - rel.R.PublicUserUser = user0 - } - return nil -} - -func (user0 *User) AttachPublicUserUser(ctx context.Context, exec bob.Executor, related ...*ArcgisUser) error { - if len(related) == 0 { - return nil - } - - var err error - arcgisusers1 := ArcgisUserSlice(related) - - _, err = attachUserPublicUserUser0(ctx, exec, len(related), arcgisusers1, user0) - if err != nil { - return err - } - - user0.R.PublicUserUser = append(user0.R.PublicUserUser, arcgisusers1...) - - for _, rel := range related { - rel.R.PublicUserUser = user0 - } - - return nil -} - func insertUserCreatorTextJobs0(ctx context.Context, exec bob.Executor, commsTextJobs1 []*CommsTextJobSetter, user0 *User) (CommsTextJobSlice, error) { for i := range commsTextJobs1 { commsTextJobs1[i].CreatorID = omitnull.From(user0.ID) @@ -3724,34 +3538,6 @@ 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 { - return fmt.Errorf("user cannot load %T as %q", retrieved, name) - } - - o.R.PublicUserUser = rels - - for _, rel := range rels { - if rel != nil { - rel.R.PublicUserUser = o - } - } - return nil case "CreatorTextJobs": rels, ok := retrieved.(CommsTextJobSlice) if !ok { @@ -4198,8 +3984,6 @@ func buildUserPreloader() userPreloader { } type userThenLoader[Q orm.Loadable] struct { - UserOauthTokens func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] - PublicUserUser func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] CreatorTextJobs func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] ClosedByCommunications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] InvalidatedByCommunications func(...bob.Mod[*dialect.SelectQuery]) orm.Loader[Q] @@ -4233,12 +4017,6 @@ type userThenLoader[Q orm.Loadable] struct { } 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 CreatorTextJobsLoadInterface interface { LoadCreatorTextJobs(context.Context, bob.Executor, ...bob.Mod[*dialect.SelectQuery]) error } @@ -4331,18 +4109,6 @@ 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...) - }, - ), CreatorTextJobs: thenLoadBuilder[Q]( "CreatorTextJobs", func(ctx context.Context, exec bob.Executor, retrieved CreatorTextJobsLoadInterface, mods ...bob.Mod[*dialect.SelectQuery]) error { @@ -4526,128 +4292,6 @@ 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 { - return nil - } - - // Reset the relationship - o.R.PublicUserUser = nil - - related, err := o.PublicUserUser(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, rel := range related { - rel.R.PublicUserUser = o - } - - o.R.PublicUserUser = related - return nil -} - -// LoadPublicUserUser loads the user's PublicUserUser into the .R struct -func (os UserSlice) LoadPublicUserUser(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { - if len(os) == 0 { - return nil - } - - arcgisusers, err := os.PublicUserUser(mods...).All(ctx, exec) - if err != nil { - return err - } - - for _, o := range os { - if o == nil { - continue - } - - o.R.PublicUserUser = nil - } - - for _, o := range os { - if o == nil { - continue - } - - for _, rel := range arcgisusers { - - if !(o.ID == rel.PublicUserID) { - continue - } - - rel.R.PublicUserUser = o - - o.R.PublicUserUser = append(o.R.PublicUserUser, rel) - } - } - - return nil -} - // LoadCreatorTextJobs loads the user's CreatorTextJobs into the .R struct func (o *User) LoadCreatorTextJobs(ctx context.Context, exec bob.Executor, mods ...bob.Mod[*dialect.SelectQuery]) error { if o == nil { diff --git a/db/query/arcgis/account.go b/db/query/arcgis/account.go new file mode 100644 index 00000000..c484a978 --- /dev/null +++ b/db/query/arcgis/account.go @@ -0,0 +1,24 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/bob" + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func AccountFromID(ctx context.Context, org_id string) (*model.Account, error) { + statement := table.Account.SELECT( + table.Account.AllColumns, + ).FROM(table.Account). + WHERE(table.Account.ID.EQ(postgres.String(org_id))) + return db.ExecuteOne[model.Account](ctx, statement) +} +func AccountInsert(ctx context.Context, txn bob.Tx, m *model.Account) (*model.Account, error) { + statement := table.Account.INSERT(table.Account.AllColumns). + MODEL(m) + return db.ExecuteOneTx[model.Account](ctx, txn, statement) +} diff --git a/db/query/arcgis/oauth.go b/db/query/arcgis/oauth.go new file mode 100644 index 00000000..340469a1 --- /dev/null +++ b/db/query/arcgis/oauth.go @@ -0,0 +1,87 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func OAuthTokenInsert(ctx context.Context, m *model.OAuthToken) (*model.OAuthToken, error) { + statement := table.OAuthToken.INSERT(table.OAuthToken.MutableColumns). + MODEL(m) + return db.ExecuteOne[model.OAuthToken](ctx, statement) +} +func OAuthTokenInvalidate(ctx context.Context, id int64) error { + statement := table.OAuthToken.UPDATE(). + SET(table.OAuthToken.InvalidatedAt.SET(postgres.LOCALTIMESTAMP())). + WHERE(table.OAuthToken.ID.EQ(postgres.Int(id))) + return db.ExecuteNone(ctx, statement) +} +func OAuthTokensValid(ctx context.Context) ([]*model.OAuthToken, error) { + statement := table.OAuthToken.SELECT(table.OAuthToken.AllColumns). + FROM(table.OAuthToken). + WHERE(table.OAuthToken.InvalidatedAt.IS_NULL()) + return db.ExecuteMany[model.OAuthToken](ctx, statement) +} +func OAuthTokenFromID(ctx context.Context, id int64) (*model.OAuthToken, error) { + statement := table.OAuthToken.SELECT( + table.OAuthToken.AllColumns, + ).FROM(table.OAuthToken). + WHERE(table.OAuthToken.ID.EQ(postgres.Int(id))) + return db.ExecuteOne[model.OAuthToken](ctx, statement) +} +func OAuthTokenForUser(ctx context.Context, user_id int64) (*model.OAuthToken, error) { + statement := table.OAuthToken.SELECT(table.OAuthToken.AllColumns). + FROM(table.OAuthToken). + WHERE(table.OAuthToken.InvalidatedAt.IS_NULL().AND( + table.OAuthToken.UserID.EQ(postgres.Int(user_id)), + )). + ORDER_BY(table.OAuthToken.Created.DESC()). + LIMIT(1) + return db.ExecuteOne[model.OAuthToken](ctx, statement) +} +func OAuthTokensForUser(ctx context.Context, user_id int64) ([]*model.OAuthToken, error) { + statement := table.OAuthToken.SELECT(table.OAuthToken.AllColumns). + FROM(table.OAuthToken). + WHERE(table.OAuthToken.InvalidatedAt.IS_NULL().AND( + table.OAuthToken.UserID.EQ(postgres.Int(user_id)), + )) + return db.ExecuteMany[model.OAuthToken](ctx, statement) +} +func OAuthTokenForUserExists(ctx context.Context, user_id int64) (*bool, error) { + statement := table.OAuthToken.SELECT(postgres.Bool(true)). + FROM(table.OAuthToken). + WHERE(table.OAuthToken.UserID.EQ(postgres.Int(user_id))). + LIMIT(1) + return db.ExecuteOne[bool](ctx, statement) +} +func OAuthTokenUpdateAccessToken(ctx context.Context, oauth_id int64, updates *model.OAuthToken) error { + statement := table.OAuthToken.UPDATE( + table.OAuthToken.AccessToken, + table.OAuthToken.AccessTokenExpires, + table.OAuthToken.Username, + ).MODEL(updates). + WHERE(table.OAuthToken.ID.EQ(postgres.Int(oauth_id))) + return db.ExecuteNone(ctx, statement) +} +func OAuthTokenUpdateRefreshToken(ctx context.Context, oauth_id int64, updates *model.OAuthToken) error { + statement := table.OAuthToken.UPDATE( + table.OAuthToken.RefreshToken, + table.OAuthToken.RefreshTokenExpires, + table.OAuthToken.Username, + ).MODEL(updates). + WHERE(table.OAuthToken.ID.EQ(postgres.Int(oauth_id))) + return db.ExecuteNone(ctx, statement) + +} +func OAuthTokenUpdateLicense(ctx context.Context, refresh_token string, updates *model.OAuthToken) error { + statement := table.OAuthToken.UPDATE( + table.OAuthToken.ArcgisID, + table.OAuthToken.ArcgisLicenseTypeID, + ).MODEL(updates). + WHERE(table.OAuthToken.RefreshToken.EQ(postgres.String(refresh_token))) + return db.ExecuteNone(ctx, statement) +} diff --git a/db/query/arcgis/service_feature.go b/db/query/arcgis/service_feature.go new file mode 100644 index 00000000..fc9238a2 --- /dev/null +++ b/db/query/arcgis/service_feature.go @@ -0,0 +1,31 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/bob" + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func ServiceFeatureFromID(ctx context.Context, id string) (*model.ServiceFeature, error) { + statement := table.ServiceFeature.SELECT( + table.ServiceFeature.AllColumns, + ).FROM(table.ServiceFeature). + WHERE(table.ServiceFeature.ItemID.EQ(postgres.String(id))) + return db.ExecuteOne[model.ServiceFeature](ctx, statement) +} +func ServiceFeatureFromURL(ctx context.Context, url string) (*model.ServiceFeature, error) { + statement := table.ServiceFeature.SELECT( + table.ServiceFeature.AllColumns, + ).FROM(table.ServiceFeature). + WHERE(table.ServiceFeature.URL.EQ(postgres.String(url))) + return db.ExecuteOne[model.ServiceFeature](ctx, statement) +} +func ServiceFeatureInsert(ctx context.Context, txn bob.Tx, m *model.ServiceFeature) error { + statement := table.ServiceMap.INSERT(table.ServiceMap.MutableColumns). + MODEL(m) + return db.ExecuteNoneTx(ctx, txn, statement) +} diff --git a/db/query/arcgis/service_map.go b/db/query/arcgis/service_map.go new file mode 100644 index 00000000..4a7fe05f --- /dev/null +++ b/db/query/arcgis/service_map.go @@ -0,0 +1,31 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/bob" + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func ServiceMapFromID(ctx context.Context, id string) (*model.ServiceMap, error) { + statement := table.ServiceMap.SELECT( + table.ServiceMap.AllColumns, + ).FROM(table.ServiceMap). + WHERE(table.ServiceMap.ArcgisID.EQ(postgres.String(id))) + return db.ExecuteOne[model.ServiceMap](ctx, statement) +} +func ServiceMapsFromAccountID(ctx context.Context, account_id string) ([]*model.ServiceMap, error) { + statement := table.ServiceMap.SELECT( + table.ServiceMap.AllColumns, + ).FROM(table.ServiceMap). + WHERE(table.ServiceMap.AccountID.EQ(postgres.String(account_id))) + return db.ExecuteMany[model.ServiceMap](ctx, statement) +} +func ServiceMapInsert(ctx context.Context, txn bob.Tx, m *model.ServiceMap) error { + statement := table.ServiceMap.INSERT(table.ServiceMap.MutableColumns). + MODEL(m) + return db.ExecuteNoneTx(ctx, txn, statement) +} diff --git a/db/query/arcgis/user.go b/db/query/arcgis/user.go new file mode 100644 index 00000000..33f0f43f --- /dev/null +++ b/db/query/arcgis/user.go @@ -0,0 +1,24 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/bob" + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func UserFromID(ctx context.Context, id string) (*model.User, error) { + statement := table.User.SELECT(table.User.AllColumns). + FROM(table.User). + WHERE(table.User.ID.EQ(postgres.String(id))) + return db.ExecuteOne[model.User](ctx, statement) +} +func UserInsert(ctx context.Context, txn bob.Tx, m *model.User) (*model.User, error) { + statement := table.User.INSERT(table.User.MutableColumns). + MODEL(m). + RETURNING(table.User.AllColumns) + return db.ExecuteOneTx[model.User](ctx, txn, statement) +} diff --git a/db/query/arcgis/user_privileges.go b/db/query/arcgis/user_privileges.go new file mode 100644 index 00000000..9947a718 --- /dev/null +++ b/db/query/arcgis/user_privileges.go @@ -0,0 +1,22 @@ +package arcgis + +import ( + "context" + + "github.com/Gleipnir-Technology/bob" + "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/table" + "github.com/go-jet/jet/v2/postgres" +) + +func UserPrivilegesDeleteByUserID(ctx context.Context, txn bob.Tx, id string) error { + statement := table.User.DELETE(). + WHERE(table.User.ID.EQ(postgres.String(id))) + return db.ExecuteNoneTx(ctx, txn, statement) +} +func UserPrivilegeInsert(ctx context.Context, txn bob.Tx, m *model.UserPrivilege) error { + statement := table.UserPrivilege.INSERT(table.UserPrivilege.MutableColumns). + MODEL(m) + return db.ExecuteNoneTx(ctx, txn, statement) +} diff --git a/db/types/box2d.go b/db/types/box2d.go new file mode 100644 index 00000000..785fad62 --- /dev/null +++ b/db/types/box2d.go @@ -0,0 +1,8 @@ +package types + +type Box2D struct { + XMax float64 + YMax float64 + XMin float64 + YMin float64 +} diff --git a/platform/arcgis.go b/platform/arcgis.go index 5ace8a99..4c5bd0d9 100644 --- a/platform/arcgis.go +++ b/platform/arcgis.go @@ -27,13 +27,14 @@ import ( "github.com/Gleipnir-Technology/bob/dialect/psql/dialect" "github.com/Gleipnir-Technology/bob/dialect/psql/dm" "github.com/Gleipnir-Technology/bob/dialect/psql/im" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" - "github.com/Gleipnir-Technology/bob/dialect/psql/um" "github.com/Gleipnir-Technology/nidus-sync/config" "github.com/Gleipnir-Technology/nidus-sync/db" "github.com/Gleipnir-Technology/nidus-sync/db/enums" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" "github.com/Gleipnir-Technology/nidus-sync/db/models" + queryarcgis "github.com/Gleipnir-Technology/nidus-sync/db/query/arcgis" "github.com/Gleipnir-Technology/nidus-sync/db/sql" + "github.com/Gleipnir-Technology/nidus-sync/db/types" "github.com/Gleipnir-Technology/nidus-sync/debug" "github.com/Gleipnir-Technology/nidus-sync/h3utils" "github.com/Gleipnir-Technology/nidus-sync/platform/oauth" @@ -51,27 +52,23 @@ var syncStatusByOrg map[int32]bool var CodeVerifier string = "random_secure_string_min_43_chars_long_should_be_stored_in_session" func HasFieldseekerConnection(ctx context.Context, user_id int32) (bool, error) { - result, err := models.ArcgisOauthTokens.Query( - sm.Where( - models.ArcgisOauthTokens.Columns.UserID.EQ(psql.Arg(user_id)), - ), - ).Exists(ctx, db.PGInstance.BobDB) + result, err := queryarcgis.OAuthTokenForUserExists(ctx, int64(user_id)) if err != nil { return false, err } - return result, nil + return *result, nil } func IsSyncOngoing(org_id int32) bool { return syncStatusByOrg[org_id] } -func getOAuthForOrg(ctx context.Context, org *models.Organization) (*models.ArcgisOauthToken, error) { +func getOAuthForOrg(ctx context.Context, org *models.Organization) (*model.OAuthToken, error) { users, err := org.User().All(ctx, db.PGInstance.BobDB) if err != nil { return nil, fmt.Errorf("Failed to query all users for org: %w", err) } for _, user := range users { - oauths, err := user.UserOauthTokens(models.SelectWhere.ArcgisOauthTokens.InvalidatedAt.IsNull()).All(ctx, db.PGInstance.BobDB) + oauths, err := queryarcgis.OAuthTokensForUser(ctx, int64(user.ID)) if err != nil { return nil, fmt.Errorf("Failed to query all oauth tokens for org: %w", err) } @@ -90,7 +87,7 @@ func refreshFieldseekerData(background_ctx context.Context, newOauthCh <-chan st workerCtx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup - oauths, err := models.ArcgisOauthTokens.Query(models.SelectWhere.ArcgisOauthTokens.InvalidatedAt.IsNull()).All(ctx, db.PGInstance.BobDB) + oauths, err := queryarcgis.OAuthTokensValid(ctx) if err != nil { log.Error().Err(err).Msg("Failed to get oauths") return @@ -220,7 +217,7 @@ func generateCodeVerifier() string { } // Find out what we can about this user -func updateArcgisUserData(ctx context.Context, user *models.User, oauth *models.ArcgisOauthToken) { +func updateArcgisUserData(ctx context.Context, user *models.User, oauth *model.OAuthToken) { client, err := arcgis.NewArcGISAuth( ctx, &arcgis.AuthenticatorOAuth{ @@ -254,13 +251,11 @@ func updateArcgisUserData(ctx context.Context, user *models.User, oauth *models. return } - _, err = models.ArcgisOauthTokens.Update( - //um.SetCol(string(models.ArcgisOauthTokens.Columns.ArcgisID)).ToArg(portal.User.ID), - //um.SetCol(string(models.ArcgisOauthTokens.Columns.ArcgisLicenseTypeID)).ToArg(portal.User.UserLicenseTypeID), - um.SetCol("arcgis_id").ToArg(ag_user.ID), - um.SetCol("arcgis_license_type_id").ToArg(ag_user.UserLicenseTypeID), - um.Where(models.ArcgisOauthTokens.Columns.RefreshToken.EQ(psql.Arg(oauth.RefreshToken))), - ).Exec(ctx, db.PGInstance.BobDB) + model := model.OAuthToken{ + ArcgisID: &ag_user.ID, + ArcgisLicenseTypeID: &ag_user.UserLicenseTypeID, + } + err = queryarcgis.OAuthTokenUpdateLicense(ctx, oauth.RefreshToken, &model) if err != nil { log.Error().Err(err).Msg("Failed to update oauth token portal data") return @@ -287,9 +282,7 @@ func updateArcgisUserData(ctx context.Context, user *models.User, oauth *models. // Ensure the fieldseeker service is saved on the account // Why yes, we do get 'ArcGIS' and 'arcgis' from the API, why do you ask? url_corrected := strings.Replace(fssync.ServiceFeature.URL.String(), "/arcgis/", "/ArcGIS/", 1) - service_account, err := models.ArcgisServiceFeatures.Query( - models.SelectWhere.ArcgisServiceFeatures.URL.EQ(url_corrected), - ).One(ctx, txn) + service_account, err := queryarcgis.ServiceFeatureFromURL(ctx, url_corrected) if err != nil { log.Error().Err(err).Str("url", fssync.ServiceFeature.URL.String()).Str("url_corrected", url_corrected).Msg("no fieldseeker service to link, it should have been created before") return @@ -308,7 +301,7 @@ func updateArcgisUserData(ctx context.Context, user *models.User, oauth *models. newOAuthTokenChannel <- struct{}{} } -func newFieldSeeker(ctx context.Context, oa *models.ArcgisOauthToken) (*fieldseeker.FieldSeeker, error) { +func newFieldSeeker(ctx context.Context, oa *model.OAuthToken) (*fieldseeker.FieldSeeker, error) { if oa == nil { return nil, fmt.Errorf("no oath token") } @@ -351,7 +344,7 @@ func newFieldSeeker(ctx context.Context, oa *models.ArcgisOauthToken) (*fieldsee } return fssync, nil } -func updateArcgisAccount(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User) (*models.ArcgisAccount, *models.ArcgisUser, error) { +func updateArcgisAccount(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User) (*model.Account, *model.User, error) { p, err := client.PortalsSelf(ctx) if err != nil { return nil, nil, fmt.Errorf("Failed to get ArcGIS user data: %w", err) @@ -359,27 +352,27 @@ func updateArcgisAccount(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, // Ensure that an arcgis account exists to attach to account, err := ensureArcgisAccount(ctx, txn, p, user) - ag_user, err := models.FindArcgisUser(ctx, txn, p.User.ID) + ag_user, err := queryarcgis.UserFromID(ctx, p.User.ID) if err != nil { log.Warn().Err(err).Msg("need arcgis user account?") if err.Error() == "sql: no rows in result set" { - setter := models.ArcgisUserSetter{ - Access: omit.From(p.Access), - Created: omit.From(time.Unix(p.User.Created, 0)), - Email: omit.From(p.User.Email), - FullName: omit.From(p.User.FullName), - ID: omit.From(p.User.ID), - Level: omit.From(p.User.Level), - OrgID: omit.From(p.User.OrgID), - PublicUserID: omit.From(user.ID), - Region: omit.From(p.Region), - Role: omit.From(p.User.Role), - RoleID: omit.From(p.User.RoleId), - Username: omit.From(p.User.Username), - UserLicenseTypeID: omit.From(p.User.UserLicenseTypeID), - UserType: omit.From(p.User.UserType), + setter := model.User{ + Access: p.Access, + Created: time.Unix(p.User.Created, 0), + Email: p.User.Email, + FullName: p.User.FullName, + ID: p.User.ID, + Level: p.User.Level, + OrgID: p.User.OrgID, + PublicUserID: user.ID, + Region: p.Region, + Role: p.User.Role, + RoleID: p.User.RoleId, + Username: p.User.Username, + UserLicenseTypeID: p.User.UserLicenseTypeID, + UserType: p.User.UserType, } - ag_user, err = models.ArcgisUsers.Insert(&setter).One(ctx, txn) + ag_user, err = queryarcgis.UserInsert(ctx, txn, &setter) if err != nil { return nil, nil, fmt.Errorf("Failed to add arcgis user data: %w", err) } @@ -388,22 +381,18 @@ func updateArcgisAccount(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, } } - _, err = models.ArcgisUserPrivileges.Delete( - dm.Where( - models.ArcgisUserPrivileges.Columns.UserID.EQ(psql.Arg(p.User.ID)), - ), - ).Exec(ctx, txn) + err = queryarcgis.UserPrivilegesDeleteByUserID(ctx, txn, p.User.ID) if err != nil { return nil, nil, fmt.Errorf("Failed to delete previous user privilege data: %w", err) } for _, priv := range p.User.Privileges { - s := models.ArcgisUserPrivilegeSetter{ - Privilege: omit.From(priv), - UserID: omit.From(p.User.ID), + s := model.UserPrivilege{ + Privilege: priv, + UserID: p.User.ID, } - _, err := models.ArcgisUserPrivileges.Insert(&s).One(ctx, txn) + err := queryarcgis.UserPrivilegeInsert(ctx, txn, &s) if err != nil { return nil, nil, fmt.Errorf("Failed to add arcgis user privilege data: %w", err) } @@ -411,24 +400,24 @@ func updateArcgisAccount(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, log.Info().Str("username", p.User.Username).Str("user_id", p.User.ID).Str("org_id", p.User.OrgID).Str("org_name", p.Name).Str("license_type_id", p.User.UserLicenseTypeID).Msg("Updated portals data") return account, ag_user, nil } -func updateServiceData(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User, account *models.ArcgisAccount) error { +func updateServiceData(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User, account *model.Account) error { service_maps, err := client.MapServices(ctx) if err != nil { return fmt.Errorf("list map services: %w", err) } for _, sm := range service_maps { log.Info().Str("account-id", account.ID).Str("arcgis-id", sm.ID).Str("name", sm.Name).Str("title", sm.Title).Str("url", sm.URL.String()).Msg("inserting map service") - _, err := models.FindArcgisServiceMap(ctx, txn, sm.ID) + _, err := queryarcgis.ServiceMapFromID(ctx, sm.ID) if err != nil { if err.Error() == "sql: no rows in result set" { - setter := models.ArcgisServiceMapSetter{ - AccountID: omit.From(account.ID), - ArcgisID: omit.From(sm.ID), - Name: omit.From(sm.Name), - Title: omit.From(sm.Title), - URL: omit.From(sm.URL.String()), + setter := model.ServiceMap{ + AccountID: account.ID, + ArcgisID: sm.ID, + Name: sm.Name, + Title: sm.Title, + URL: sm.URL.String(), } - _, err := models.ArcgisServiceMaps.Insert(&setter).One(ctx, txn) + err := queryarcgis.ServiceMapInsert(ctx, txn, &setter) if err != nil { return fmt.Errorf("save map service: %w", err) } @@ -443,21 +432,6 @@ func updateServiceData(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, u return err } } - /* - - // Created this after (maybe mistakenly) marking the above as: - // TODO: No idea why this isn't working, but it's mixing up the inputs - _, err = psql.Insert( - im.Into("arcgis.service_map", "account_id", "arcgis_id", "name", "title", "url"), - im.Values( - psql.Arg(account.ID), - psql.Arg(sm.ID), - psql.Arg(sm.Name), - psql.Arg(sm.Title), - psql.Arg(sm.URL.String()), - ), - ).Exec(ctx, txn) - */ } services, err := client.Services(ctx) @@ -469,10 +443,8 @@ func updateServiceData(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, u } return nil } -func ensureServiceFeature(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User, account *models.ArcgisAccount, service *arcgis.ServiceFeature) error { - _, err := models.ArcgisServiceFeatures.Query( - models.SelectWhere.ArcgisServiceFeatures.URL.EQ(service.URL.String()), - ).One(ctx, txn) +func ensureServiceFeature(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS, user *models.User, account *model.Account, service *arcgis.ServiceFeature) error { + _, err := queryarcgis.ServiceFeatureFromURL(ctx, service.URL.String()) if err == nil { return nil } @@ -484,28 +456,19 @@ func ensureServiceFeature(ctx context.Context, txn bob.Tx, client *arcgis.ArcGIS return fmt.Errorf("populate metadata: %w", err) } - /* - TODO: figure out how to do this without raw insert - setter := models.ArcgisServiceFeatureSetter{ - AccountID: omitnull.From(account.ID), - Extent: omit.From(metadata.FullExtent), - ItemID: omit.From(metadata.ServiceItemId), - SpatialReference: omit.From(metadata.SpatialReference.LatestWKID), - URL: omit.From(service.URL.String()), - } - _, err = models.ArcgisServiceFeatures.Insert(&setter).One(ctx, txn) - */ - _, err = psql.Insert( - im.Into("arcgis.service_feature", "account_id", "extent", "item_id", "spatial_reference", "url"), - im.Values( - psql.Arg(account.ID), - psql.Raw("Box2D(ST_GeomFromText('LINESTRING(1 2, 3 4, 5 6)'))"), - psql.Arg(metadata.ServiceItemId), - psql.Arg(metadata.SpatialReference.LatestWKID), - psql.Arg(service.URL.String()), - ), - ).Exec(ctx, txn) - return err + setter := model.ServiceFeature{ + AccountID: &account.ID, + Extent: types.Box2D{ + XMax: 180, + YMax: 90, + XMin: -180, + YMin: -90, + }, + ItemID: metadata.ServiceItemId, + SpatialReference: int32(*metadata.SpatialReference.LatestWKID), + URL: service.URL.String(), + } + return queryarcgis.ServiceFeatureInsert(ctx, txn, &setter) } func maybeCreateWebhook(ctx context.Context, client *fieldseeker.FieldSeeker) { @@ -646,10 +609,10 @@ func logPermissions(ctx context.Context, fssync *fieldseeker.FieldSeeker) { } } -func maintainOAuth(ctx context.Context, aot *models.ArcgisOauthToken) error { +func maintainOAuth(ctx context.Context, aot *model.OAuthToken) error { for { // Refresh from the database - oa, err := models.FindArcgisOauthToken(ctx, db.PGInstance.BobDB, aot.ID) + oa, err := queryarcgis.OAuthTokenFromID(ctx, int64(aot.ID)) if err != nil { return fmt.Errorf("Failed to update oauth token from database: %w", err) } @@ -689,11 +652,8 @@ func maintainOAuth(ctx context.Context, aot *models.ArcgisOauthToken) error { // Mark that a given oauth token has failed. This includes a notification to // the user. -func markTokenFailed(ctx context.Context, oauth *models.ArcgisOauthToken) { - oauthSetter := models.ArcgisOauthTokenSetter{ - InvalidatedAt: omitnull.From(time.Now()), - } - err := oauth.Update(ctx, db.PGInstance.BobDB, &oauthSetter) +func markTokenFailed(ctx context.Context, oauth *model.OAuthToken) { + err := queryarcgis.OAuthTokenInvalidate(ctx, int64(oauth.ID)) if err != nil { log.Error().Str("err", err.Error()).Msg("Failed to mark token failed") } @@ -1602,22 +1562,22 @@ func exportFieldseekerLayer(ctx context.Context, group pond.ResultTaskGroup[Sync */ } -func ensureArcgisAccount(ctx context.Context, txn bob.Tx, portal *response.Portal, user *models.User) (*models.ArcgisAccount, error) { - account, err := models.FindArcgisAccount(ctx, txn, portal.User.OrgID) +func ensureArcgisAccount(ctx context.Context, txn bob.Tx, portal *response.Portal, user *models.User) (*model.Account, error) { + account, err := queryarcgis.AccountFromID(ctx, portal.User.OrgID) if err != nil { log.Warn().Err(err).Msg("need arcgis account?") if err.Error() == "sql: no rows in result set" { - setter := models.ArcgisAccountSetter{ - ID: omit.From(portal.User.OrgID), - Name: omit.From(portal.Name), - OrganizationID: omit.From(user.OrganizationID), - URLFeatures: omitnull.FromPtr[string](nil), - URLInsights: omitnull.FromPtr[string](nil), - URLGeometry: omitnull.FromPtr[string](nil), - URLNotebooks: omitnull.FromPtr[string](nil), - URLTiles: omitnull.FromPtr[string](nil), + setter := model.Account{ + ID: portal.User.OrgID, + Name: portal.Name, + OrganizationID: user.OrganizationID, + URLFeatures: nil, + URLInsights: nil, + URLGeometry: nil, + URLNotebooks: nil, + URLTiles: nil, } - account, err = models.ArcgisAccounts.Insert(&setter).One(ctx, txn) + account, err = queryarcgis.AccountInsert(ctx, txn, &setter) if err != nil { return nil, fmt.Errorf("create arcgis account: %w", err) } diff --git a/platform/geocode/geocode.go b/platform/geocode/geocode.go index bd8053ca..6c43e535 100644 --- a/platform/geocode/geocode.go +++ b/platform/geocode/geocode.go @@ -68,7 +68,7 @@ func restyMiddleware(rclient *resty.Client, response *resty.Response) error { Request: u, Response: string(resp_bytes), }).RETURNING(table.APIRequest.AllColumns) - data, err := db.Execute[model.APIRequest](ctx, statement) + data, err := db.ExecuteOne[model.APIRequest](ctx, statement) if err != nil { log.Error().Err(err).Msg("failed to insert stadia request") } else { diff --git a/platform/image.go b/platform/image.go index e64c12ad..00a60e06 100644 --- a/platform/image.go +++ b/platform/image.go @@ -114,6 +114,9 @@ func saveImageUploads(ctx context.Context, tx bob.Tx, uploads []ImageUpload) (mo um.SetCol("location").To(fmt.Sprintf("ST_Point(%f, %f, 4326)", u.Exif.GPS.Longitude, u.Exif.GPS.Latitude)), um.Where(psql.Quote("id").EQ(psql.Arg(image.ID))), ).Exec(ctx, tx) + if err != nil { + return images, fmt.Errorf("set location: %w", err) + } } exif_setters := make([]*models.PublicreportImageExifSetter, 0) diff --git a/platform/oauth.go b/platform/oauth.go index 0f1b1b8d..f611293b 100644 --- a/platform/oauth.go +++ b/platform/oauth.go @@ -6,13 +6,10 @@ import ( "net/url" "time" - "github.com/Gleipnir-Technology/bob/dialect/psql/sm" "github.com/Gleipnir-Technology/nidus-sync/config" - "github.com/Gleipnir-Technology/nidus-sync/db" - "github.com/Gleipnir-Technology/nidus-sync/db/models" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" + queryarcgis "github.com/Gleipnir-Technology/nidus-sync/db/query/arcgis" "github.com/Gleipnir-Technology/nidus-sync/platform/oauth" - "github.com/aarondl/opt/omit" - "github.com/aarondl/opt/omitnull" ) // When there is no oauth for an organization @@ -20,7 +17,7 @@ type NoOAuthForOrg struct{} func (e NoOAuthForOrg) Error() string { return "No oauth available for organization" } -func GetOAuthForOrg(ctx context.Context, org Organization) (*models.ArcgisOauthToken, error) { +func GetOAuthForOrg(ctx context.Context, org Organization) (*model.OAuthToken, error) { result, err := oauth.GetOAuthForOrg(ctx, org.model) if result == nil && err == nil { return nil, &NoOAuthForOrg{} @@ -28,10 +25,8 @@ func GetOAuthForOrg(ctx context.Context, org Organization) (*models.ArcgisOauthT return result, err } -func GetOAuthForUser(ctx context.Context, user User) (*models.ArcgisOauthToken, error) { - oauth, err := user.model.UserOauthTokens( - sm.OrderBy("created").Desc(), - ).One(ctx, db.PGInstance.BobDB) +func GetOAuthForUser(ctx context.Context, user User) (*model.OAuthToken, error) { + oauth, err := queryarcgis.OAuthTokenForUser(ctx, int64(user.ID)) if err != nil { if err.Error() == "sql: no rows in result set" { return nil, nil @@ -54,20 +49,20 @@ func HandleOauthAccessCode(ctx context.Context, user User, code string) error { } accessExpires := oauth.FutureUTCTimestamp(token.ExpiresIn) refreshExpires := oauth.FutureUTCTimestamp(token.RefreshTokenExpiresIn) - setter := models.ArcgisOauthTokenSetter{ - AccessToken: omit.From(token.AccessToken), - AccessTokenExpires: omit.From(accessExpires), - //ArcgisAccountID: omit.From( - ArcgisID: omitnull.FromPtr[string](nil), - ArcgisLicenseTypeID: omitnull.FromPtr[string](nil), - Created: omit.From(time.Now()), - InvalidatedAt: omitnull.FromPtr[time.Time](nil), - RefreshToken: omit.From(token.RefreshToken), - RefreshTokenExpires: omit.From(refreshExpires), - UserID: omit.From(int32(user.ID)), - Username: omit.From(token.Username), + setter := model.OAuthToken{ + AccessToken: token.AccessToken, + AccessTokenExpires: accessExpires, + ArcgisAccountID: nil, + ArcgisID: nil, + ArcgisLicenseTypeID: nil, + Created: time.Now(), + InvalidatedAt: nil, + RefreshToken: token.RefreshToken, + RefreshTokenExpires: refreshExpires, + UserID: int32(user.ID), + Username: token.Username, } - oauth, err := models.ArcgisOauthTokens.Insert(&setter).One(ctx, db.PGInstance.BobDB) + oauth, err := queryarcgis.OAuthTokenInsert(ctx, &setter) if err != nil { return fmt.Errorf("Failed to save token to database: %w", err) } diff --git a/platform/oauth/oauth.go b/platform/oauth/oauth.go index e1c21ef2..e17f174f 100644 --- a/platform/oauth/oauth.go +++ b/platform/oauth/oauth.go @@ -13,8 +13,9 @@ import ( "github.com/Gleipnir-Technology/arcgis-go" "github.com/Gleipnir-Technology/nidus-sync/config" "github.com/Gleipnir-Technology/nidus-sync/db" + "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/arcgis/model" "github.com/Gleipnir-Technology/nidus-sync/db/models" - "github.com/aarondl/opt/omit" + queryarcgis "github.com/Gleipnir-Technology/nidus-sync/db/query/arcgis" "github.com/rs/zerolog/log" ) @@ -90,13 +91,13 @@ func FutureUTCTimestamp(secondsFromNow int) time.Time { return time.Now().UTC().Add(time.Duration(secondsFromNow) * time.Second) } -func GetOAuthForOrg(ctx context.Context, org *models.Organization) (*models.ArcgisOauthToken, error) { +func GetOAuthForOrg(ctx context.Context, org *models.Organization) (*model.OAuthToken, error) { users, err := org.User().All(ctx, db.PGInstance.BobDB) if err != nil { return nil, fmt.Errorf("Failed to query all users for org: %w", err) } for _, user := range users { - oauths, err := user.UserOauthTokens(models.SelectWhere.ArcgisOauthTokens.InvalidatedAt.IsNull()).All(ctx, db.PGInstance.BobDB) + oauths, err := queryarcgis.OAuthTokensForUser(ctx, int64(user.ID)) if err != nil { return nil, fmt.Errorf("Failed to query all oauth tokens for org: %w", err) } @@ -108,7 +109,7 @@ func GetOAuthForOrg(ctx context.Context, org *models.Organization) (*models.Arcg } // Update the access token to keep it fresh and alive -func RefreshAccessToken(ctx context.Context, oauth *models.ArcgisOauthToken) error { +func RefreshAccessToken(ctx context.Context, oauth *model.OAuthToken) error { form := url.Values{ "grant_type": []string{"refresh_token"}, "client_id": []string{config.ClientID}, @@ -119,12 +120,12 @@ func RefreshAccessToken(ctx context.Context, oauth *models.ArcgisOauthToken) err return fmt.Errorf("Failed to handle request: %w", err) } accessExpires := FutureUTCTimestamp(token.ExpiresIn) - setter := models.ArcgisOauthTokenSetter{ - AccessToken: omit.From(token.AccessToken), - AccessTokenExpires: omit.From(accessExpires), - Username: omit.From(token.Username), + model := model.OAuthToken{ + AccessToken: token.AccessToken, + AccessTokenExpires: accessExpires, + Username: token.Username, } - err = oauth.Update(ctx, db.PGInstance.BobDB, &setter) + err = queryarcgis.OAuthTokenUpdateAccessToken(ctx, int64(oauth.ID), &model) if err != nil { return fmt.Errorf("Failed to update oauth in database: %w", err) } @@ -133,7 +134,7 @@ func RefreshAccessToken(ctx context.Context, oauth *models.ArcgisOauthToken) err } // Update the refresh token to keep it fresh and alive -func RefreshRefreshToken(ctx context.Context, oauth *models.ArcgisOauthToken) error { +func RefreshRefreshToken(ctx context.Context, oauth *model.OAuthToken) error { form := url.Values{ "grant_type": []string{"exchange_refresh_token"}, @@ -146,12 +147,12 @@ func RefreshRefreshToken(ctx context.Context, oauth *models.ArcgisOauthToken) er return fmt.Errorf("Failed to handle request: %w", err) } refreshExpires := FutureUTCTimestamp(token.ExpiresIn) - setter := models.ArcgisOauthTokenSetter{ - RefreshToken: omit.From(token.RefreshToken), - RefreshTokenExpires: omit.From(refreshExpires), - Username: omit.From(token.Username), + model := model.OAuthToken{ + RefreshToken: token.RefreshToken, + RefreshTokenExpires: refreshExpires, + Username: token.Username, } - err = oauth.Update(ctx, db.PGInstance.BobDB, &setter) + err = queryarcgis.OAuthTokenUpdateRefreshToken(ctx, int64(oauth.ID), &model) if err != nil { return fmt.Errorf("Failed to update oauth in database: %w", err) } diff --git a/resource/communication.go b/resource/communication.go index f7ded790..bd379f15 100644 --- a/resource/communication.go +++ b/resource/communication.go @@ -28,6 +28,7 @@ type communication struct { Created time.Time `json:"created"` ID string `json:"id"` PublicReport string `json:"public_report"` + Source string `json:"source"` Type string `json:"type"` } type communicationList struct {