diff --git a/apiserver/README.md b/apiserver/README.md index 78ff150..8b14238 100644 --- a/apiserver/README.md +++ b/apiserver/README.md @@ -13,7 +13,7 @@ To see how to make this your own, look here: [README](https://openapi-generator.tech) - API version: 1.0.0 -- Build date: 2024-01-24T17:20:07.525819443Z[Etc/UTC] +- Build date: 2024-02-02T12:01:58.629258516Z[Etc/UTC] ### Running the server diff --git a/apiserver/api.go b/apiserver/api.go index a98433a..0416e58 100644 --- a/apiserver/api.go +++ b/apiserver/api.go @@ -18,13 +18,11 @@ import ( // The ConfigurationAPIRouter implementation should parse necessary information from the http request, // pass the data to a ConfigurationAPIServicer to perform the required actions, then write the service results to the http response. type ConfigurationAPIRouter interface { - GetAdvancedConfiguration(http.ResponseWriter, *http.Request) GetAttributeMapping(http.ResponseWriter, *http.Request) - GetBasicConfiguration(http.ResponseWriter, *http.Request) + GetConfiguration(http.ResponseWriter, *http.Request) GetPermissionMapping(http.ResponseWriter, *http.Request) - PutAdvancedConfiguration(http.ResponseWriter, *http.Request) PutAttributeMapping(http.ResponseWriter, *http.Request) - PutBasicConfiguration(http.ResponseWriter, *http.Request) + PutConfiguration(http.ResponseWriter, *http.Request) PutPermissionMapping(http.ResponseWriter, *http.Request) } @@ -57,13 +55,11 @@ type VersionAPIRouter interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type ConfigurationAPIServicer interface { - GetAdvancedConfiguration(context.Context) (ImplResponse, error) GetAttributeMapping(context.Context) (ImplResponse, error) - GetBasicConfiguration(context.Context) (ImplResponse, error) + GetConfiguration(context.Context) (ImplResponse, error) GetPermissionMapping(context.Context) (ImplResponse, error) - PutAdvancedConfiguration(context.Context, AdvancedConfiguration) (ImplResponse, error) PutAttributeMapping(context.Context, AttributeMap) (ImplResponse, error) - PutBasicConfiguration(context.Context, BasicConfiguration) (ImplResponse, error) + PutConfiguration(context.Context, Configuration) (ImplResponse, error) PutPermissionMapping(context.Context, Permissions) (ImplResponse, error) } diff --git a/apiserver/api_configuration.go b/apiserver/api_configuration.go index 4d75d27..a089ca8 100644 --- a/apiserver/api_configuration.go +++ b/apiserver/api_configuration.go @@ -50,40 +50,30 @@ func NewConfigurationAPIController(s ConfigurationAPIServicer, opts ...Configura // Routes returns all the api routes for the ConfigurationAPIController func (c *ConfigurationAPIController) Routes() Routes { return Routes{ - "GetAdvancedConfiguration": Route{ - strings.ToUpper("Get"), - "/v1/configuration/advanced", - c.GetAdvancedConfiguration, - }, "GetAttributeMapping": Route{ strings.ToUpper("Get"), "/v1/configuration/attribute-mapping", c.GetAttributeMapping, }, - "GetBasicConfiguration": Route{ + "GetConfiguration": Route{ strings.ToUpper("Get"), - "/v1/configuration/basic", - c.GetBasicConfiguration, + "/v1/configuration", + c.GetConfiguration, }, "GetPermissionMapping": Route{ strings.ToUpper("Get"), "/v1/configuration/permission-mapping", c.GetPermissionMapping, }, - "PutAdvancedConfiguration": Route{ - strings.ToUpper("Put"), - "/v1/configuration/advanced", - c.PutAdvancedConfiguration, - }, "PutAttributeMapping": Route{ strings.ToUpper("Put"), "/v1/configuration/attribute-mapping", c.PutAttributeMapping, }, - "PutBasicConfiguration": Route{ + "PutConfiguration": Route{ strings.ToUpper("Put"), - "/v1/configuration/basic", - c.PutBasicConfiguration, + "/v1/configuration", + c.PutConfiguration, }, "PutPermissionMapping": Route{ strings.ToUpper("Put"), @@ -93,18 +83,6 @@ func (c *ConfigurationAPIController) Routes() Routes { } } -// GetAdvancedConfiguration - Get Advanced Configuration -func (c *ConfigurationAPIController) GetAdvancedConfiguration(w http.ResponseWriter, r *http.Request) { - result, err := c.service.GetAdvancedConfiguration(r.Context()) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) -} - // GetAttributeMapping - Get Attribute Mapping func (c *ConfigurationAPIController) GetAttributeMapping(w http.ResponseWriter, r *http.Request) { result, err := c.service.GetAttributeMapping(r.Context()) @@ -117,9 +95,9 @@ func (c *ConfigurationAPIController) GetAttributeMapping(w http.ResponseWriter, EncodeJSONResponse(result.Body, &result.Code, w) } -// GetBasicConfiguration - Get Basic Configurations -func (c *ConfigurationAPIController) GetBasicConfiguration(w http.ResponseWriter, r *http.Request) { - result, err := c.service.GetBasicConfiguration(r.Context()) +// GetConfiguration - Get Configurations +func (c *ConfigurationAPIController) GetConfiguration(w http.ResponseWriter, r *http.Request) { + result, err := c.service.GetConfiguration(r.Context()) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -141,33 +119,6 @@ func (c *ConfigurationAPIController) GetPermissionMapping(w http.ResponseWriter, EncodeJSONResponse(result.Body, &result.Code, w) } -// PutAdvancedConfiguration - Creates or Update Advanced Configuration -func (c *ConfigurationAPIController) PutAdvancedConfiguration(w http.ResponseWriter, r *http.Request) { - advancedConfigurationParam := AdvancedConfiguration{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&advancedConfigurationParam); err != nil && !errors.Is(err, io.EOF) { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertAdvancedConfigurationRequired(advancedConfigurationParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertAdvancedConfigurationConstraints(advancedConfigurationParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - result, err := c.service.PutAdvancedConfiguration(r.Context(), advancedConfigurationParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) -} - // PutAttributeMapping - Creates or Update Attribute Mapping func (c *ConfigurationAPIController) PutAttributeMapping(w http.ResponseWriter, r *http.Request) { attributeMapParam := AttributeMap{} @@ -195,24 +146,24 @@ func (c *ConfigurationAPIController) PutAttributeMapping(w http.ResponseWriter, EncodeJSONResponse(result.Body, &result.Code, w) } -// PutBasicConfiguration - Creates or Update Basic Configuration -func (c *ConfigurationAPIController) PutBasicConfiguration(w http.ResponseWriter, r *http.Request) { - basicConfigurationParam := BasicConfiguration{} +// PutConfiguration - Creates or Update Configuration +func (c *ConfigurationAPIController) PutConfiguration(w http.ResponseWriter, r *http.Request) { + configurationParam := Configuration{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() - if err := d.Decode(&basicConfigurationParam); err != nil && !errors.Is(err, io.EOF) { + if err := d.Decode(&configurationParam); err != nil && !errors.Is(err, io.EOF) { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - if err := AssertBasicConfigurationRequired(basicConfigurationParam); err != nil { + if err := AssertConfigurationRequired(configurationParam); err != nil { c.errorHandler(w, r, err, nil) return } - if err := AssertBasicConfigurationConstraints(basicConfigurationParam); err != nil { + if err := AssertConfigurationConstraints(configurationParam); err != nil { c.errorHandler(w, r, err, nil) return } - result, err := c.service.PutBasicConfiguration(r.Context(), basicConfigurationParam) + result, err := c.service.PutConfiguration(r.Context(), configurationParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/apiserver/model_attribute_map.go b/apiserver/model_attribute_map.go index 4b01832..f4731a6 100644 --- a/apiserver/model_attribute_map.go +++ b/apiserver/model_attribute_map.go @@ -12,7 +12,7 @@ package apiserver // AttributeMap - Maps SAML Attributes to the Eliona User Attributes type AttributeMap struct { - // Configuration Id refer to basic config's id. Can only be 1 + // Configuration Id refer to config's id. Can only be 1 Id int32 `json:"id,omitempty"` // SAML attribute to map to the email (login) of a user diff --git a/apiserver/model_basic_configuration.go b/apiserver/model_configuration.go similarity index 52% rename from apiserver/model_basic_configuration.go rename to apiserver/model_configuration.go index e3fa66a..84affd8 100644 --- a/apiserver/model_basic_configuration.go +++ b/apiserver/model_configuration.go @@ -9,8 +9,8 @@ package apiserver -// BasicConfiguration - The Basic Configurations for running a SAML 2.0 Service Provider -type BasicConfiguration struct { +// Configuration - The Configurations for running a SAML 2.0 Service Provider +type Configuration struct { // Configuration Id. Can only be 1 Id int32 `json:"id,omitempty"` @@ -35,14 +35,32 @@ type BasicConfiguration struct { // If enabled, the new created user is archived and cannot login until a admin has activated it. UserToArchive bool `json:"userToArchive,omitempty"` + + // If the configuration is enabled or not + AllowInitializationByIdp bool `json:"allowInitializationByIdp,omitempty"` + + // If the SP should make a signed SAML Authn-Request or not + SignedRequest bool `json:"signedRequest,omitempty"` + + // Normaly this value is set to false for a SP. If set to true the user has to re-authenticate (login at IdP) even it has a valid session to the IdP. + ForceAuthn bool `json:"forceAuthn,omitempty"` + + // If you have to use a customized Entity Id, you can overwrite it here. Normally the default value can be left as it is. + EntityId string `json:"entityId,omitempty"` + + // only send cookies over encrypted connection (HTTPS) + CookieSecure bool `json:"cookieSecure,omitempty"` + + // The url to redirect if the login failed. If this value is null the default page /noLogin will showed up + LoginFailedUrl string `json:"loginFailedUrl,omitempty"` } -// AssertBasicConfigurationRequired checks if the required fields are not zero-ed -func AssertBasicConfigurationRequired(obj BasicConfiguration) error { +// AssertConfigurationRequired checks if the required fields are not zero-ed +func AssertConfigurationRequired(obj Configuration) error { return nil } -// AssertBasicConfigurationConstraints checks if the values respects the defined constraints -func AssertBasicConfigurationConstraints(obj BasicConfiguration) error { +// AssertConfigurationConstraints checks if the values respects the defined constraints +func AssertConfigurationConstraints(obj Configuration) error { return nil } diff --git a/apiserver/model_permissions.go b/apiserver/model_permissions.go index 21308e7..73f059a 100644 --- a/apiserver/model_permissions.go +++ b/apiserver/model_permissions.go @@ -12,7 +12,7 @@ package apiserver // Permissions - Sets default user permissions and optionaly maps SAML Attributes and Content to eliona's roles type Permissions struct { - // Configuration Id refer to basic config's id. Can only be 1 + // Configuration Id refer to config's id. Can only be 1 Id int32 `json:"id,omitempty"` DefaultSystemRole string `json:"default_system_role,omitempty"` diff --git a/apiservices/api_configuration_service.go b/apiservices/api_configuration_service.go index 74d195e..bc05cc6 100644 --- a/apiservices/api_configuration_service.go +++ b/apiservices/api_configuration_service.go @@ -33,58 +33,56 @@ func NewConfigurationApiService() apiserver.ConfigurationAPIServicer { return &ConfigurationApiService{} } -// GetAdvancedConfiguration - Get Advanced Configuration -func (s *ConfigurationApiService) GetAdvancedConfiguration(ctx context.Context) (apiserver.ImplResponse, error) { - advCnf, err := conf.GetAdvancedConfig(ctx) - - return apiserver.Response(http.StatusOK, advCnf), err -} - // GetAttributeMapping - Get Attribute Mapping func (s *ConfigurationApiService) GetAttributeMapping(ctx context.Context) (apiserver.ImplResponse, error) { - attrMap, err := conf.GetAttributeMapping(ctx) - - return apiserver.Response(http.StatusOK, attrMap), err + am, err := conf.GetAttributeMapping(ctx) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusOK, am), nil } -// GetBasicConfiguration - Get Basic Configurations -func (s *ConfigurationApiService) GetBasicConfiguration(ctx context.Context) (apiserver.ImplResponse, error) { - basicCnf, err := conf.GetBasicConfig(ctx) - - return apiserver.Response(http.StatusOK, basicCnf), err +// GetConfiguration - Get Configuration +func (s *ConfigurationApiService) GetConfiguration(ctx context.Context) (apiserver.ImplResponse, error) { + config, err := conf.GetConfig(ctx) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusOK, config), nil } // GetPermissionMapping - Get Permission Mapping func (s *ConfigurationApiService) GetPermissionMapping(ctx context.Context) (apiserver.ImplResponse, error) { - permMap, err := conf.GetPermissionSettings(ctx) - - return apiserver.Response(http.StatusOK, permMap), err -} - -// PutAdvancedConfiguration - Creates or Update Advanced Configuration -func (s *ConfigurationApiService) PutAdvancedConfiguration(ctx context.Context, advancedConfiguration apiserver.AdvancedConfiguration) (apiserver.ImplResponse, error) { - cnfRet, err := conf.SetAdvancedConfig(ctx, &advancedConfiguration) - - return apiserver.Response(http.StatusOK, cnfRet), err + pm, err := conf.GetPermissionMapping(ctx) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusOK, pm), nil } // PutAttributeMapping - Creates or Update Attribute Mapping func (s *ConfigurationApiService) PutAttributeMapping(ctx context.Context, attributeMap apiserver.AttributeMap) (apiserver.ImplResponse, error) { - mapRet, err := conf.SetAttributeMapping(ctx, &attributeMap) - - return apiserver.Response(http.StatusOK, mapRet), err + upsertedAttrMap, err := conf.SetAttributeMapping(ctx, &attributeMap) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusCreated, upsertedAttrMap), nil } -// PutBasicConfiguration - Creates or Update Basic Configuration -func (s *ConfigurationApiService) PutBasicConfiguration(ctx context.Context, basicConfiguration apiserver.BasicConfiguration) (apiserver.ImplResponse, error) { - cnfRet, err := conf.SetBasicConfig(ctx, &basicConfiguration) - - return apiserver.Response(http.StatusOK, cnfRet), err +// PutConfiguration - Creates or Update Basic Configuration +func (s *ConfigurationApiService) PutConfiguration(ctx context.Context, config apiserver.Configuration) (apiserver.ImplResponse, error) { + upsertedConfig, err := conf.SetConfig(ctx, &config) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusCreated, upsertedConfig), nil } // PutPermissionMapping - Creates or Update Permission Mapping Configurations func (s *ConfigurationApiService) PutPermissionMapping(ctx context.Context, permissions apiserver.Permissions) (apiserver.ImplResponse, error) { - permRet, err := conf.SetPermissionSettings(ctx, &permissions) - - return apiserver.Response(http.StatusOK, permRet), err + upsertedPerms, err := conf.SetPermissionMapping(ctx, &permissions) + if err != nil { + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + return apiserver.Response(http.StatusCreated, upsertedPerms), nil } diff --git a/apiservices/api_configuration_service_test.go b/apiservices/api_configuration_service_test.go index 5068eb3..34de762 100644 --- a/apiservices/api_configuration_service_test.go +++ b/apiservices/api_configuration_service_test.go @@ -45,19 +45,15 @@ func TestApp_AppApi_Configuration_InitDB(t *testing.T) { } } -func TestApp_AppApi_Configuration_GetBasicConfig(t *testing.T) { +func TestApp_AppApi_Configuration_GetConfig(t *testing.T) { apiService := apiservices.NewConfigurationApiService() - cnf, err := apiService.GetBasicConfiguration(context.Background()) + cnf, err := apiService.GetConfiguration(context.Background()) if err != sql.ErrNoRows { t.Error(err) } fmt.Println(cnf) } -func TestApp_AppApi_Configuration_GetAdvancedConfig(t *testing.T) { - -} - func TestApp_AppApi_Configuration_GetAttributeMapping(t *testing.T) { } @@ -66,11 +62,7 @@ func TestApp_AppApi_Configuration_GetPermissionMap(t *testing.T) { } -func TestApp_AppApi_Configuration_PutBasicConfig(t *testing.T) { - -} - -func TestApp_AppApi_Configuration_PutAdvancedConfig(t *testing.T) { +func TestApp_AppApi_Configuration_PutConfig(t *testing.T) { } diff --git a/apiservices/api_version_service.go b/apiservices/api_version_service.go index a249c1a..7a99297 100644 --- a/apiservices/api_version_service.go +++ b/apiservices/api_version_service.go @@ -1,5 +1,5 @@ // This file is part of the eliona project. -// Copyright © 2023 Eliona by IoTEC AG. All Rights Reserved. +// Copyright © 2022 LEICOM iTEC AG. All Rights Reserved. // ______ _ _ // | ____| (_) // | |__ | |_ ___ _ __ __ _ @@ -17,9 +17,15 @@ package apiservices import ( "context" - "errors" + "encoding/json" + "io" "net/http" + "os" "saml-sso/apiserver" + + "github.com/eliona-smart-building-assistant/go-utils/common" + "github.com/eliona-smart-building-assistant/go-utils/log" + "gopkg.in/yaml.v3" ) // VersionApiService is a service that implements the logic for the VersionApiServicer @@ -35,22 +41,39 @@ func NewVersionApiService() apiserver.VersionAPIServicer { // GetOpenAPI - OpenAPI specification for this API version func (s *VersionApiService) GetOpenAPI(ctx context.Context) (apiserver.ImplResponse, error) { - // TODO - update GetOpenAPI with the required logic for this service method. - // Add api_version_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(200, map[string]interface{}{}) or use other options such as http.Ok ... - //return Response(200, map[string]interface{}{}), nil + bytes, err := os.ReadFile("openapi.yaml") + if err != nil { + log.Error("services", "%s: %v", "GetOpenAPI", err) + return apiserver.ImplResponse{Code: http.StatusNotFound}, err + } + var body interface{} + err = yaml.Unmarshal(bytes, &body) + if err != nil { + log.Error("services", "%s: %v", "GetOpenAPI", err) + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, err + } + if err := tryJSONEncoding(body); err != nil { + log.Error("services", "openapi file not encodable to JSON: %v", err) + return apiserver.ImplResponse{Code: http.StatusInternalServerError}, nil + } + return apiserver.Response(http.StatusOK, body), nil +} - return apiserver.Response(http.StatusNotImplemented, nil), errors.New("GetOpenAPI method not implemented") +func tryJSONEncoding(i interface{}) error { + return json.NewEncoder(io.Discard).Encode(i) } +var BuildTimestamp string // injected during linking, see Dockerfile +var GitCommit string // injected during linking, see Dockerfile + // GetVersion - Version of the API func (s *VersionApiService) GetVersion(ctx context.Context) (apiserver.ImplResponse, error) { - // TODO - update GetVersion with the required logic for this service method. - // Add api_version_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(200, map[string]interface{}{}) or use other options such as http.Ok ... - //return Response(200, map[string]interface{}{}), nil + return apiserver.Response(http.StatusOK, common.Ptr(version())), nil +} - return apiserver.Response(http.StatusNotImplemented, nil), errors.New("GetVersion method not implemented") +func version() map[string]any { + return map[string]any{ + "timestamp": BuildTimestamp, + "commit": GitCommit, + } } diff --git a/app.go b/app.go index 2752db3..7049265 100644 --- a/app.go +++ b/app.go @@ -50,19 +50,14 @@ func run() { log.Debug(LOG_REGIO, "insert default config: %v", err) } - basicConfig, err := conf.GetBasicConfig(context.Background()) + config, err := conf.GetConfig(context.Background()) if err != nil { log.Fatal(LOG_REGIO, "cannot load basic config") } - advancedConfig, err := conf.GetAdvancedConfig(context.Background()) - if err != nil { - log.Fatal(LOG_REGIO, "cannot load advanced config") - } - - if basicConfig.IdpMetadataUrl != nil && *basicConfig.IdpMetadataUrl != "" { + if config.IdpMetadataUrl != nil && *config.IdpMetadataUrl != "" { // fetch metadata - metadataResp, err := http.Get(*basicConfig.IdpMetadataUrl) + metadataResp, err := http.Get(*config.IdpMetadataUrl) if err != nil { log.Error(LOG_REGIO, "cannot fetch IdP metadata from url: %v", err) } else { @@ -73,8 +68,8 @@ func run() { } metadata = metaB } - } else if basicConfig.IdpMetadataXml != nil { - metadata = []byte(*basicConfig.IdpMetadataXml) + } else if config.IdpMetadataXml != nil { + metadata = []byte(*config.IdpMetadataXml) } else { log.Error(LOG_REGIO, "not able to set IdP Metadata") } @@ -82,18 +77,18 @@ func run() { apiPort := common.Getenv("API_SERVER_PORT", strconv.Itoa(API_SERVER_PORT)) samlSpPort := common.Getenv("SSO_SERVER_PORT", strconv.Itoa(SSO_SERVER_PORT)) - log.Debug(LOG_REGIO, "own url: %v, api port: %v", basicConfig.OwnUrl, apiPort) + log.Debug(LOG_REGIO, "own url: %v, api port: %v", config.OwnUrl, apiPort) sp, err := saml.NewServiceProviderAdvanced( - basicConfig.ServiceProviderCertificate, - basicConfig.ServiceProviderPrivateKey, - basicConfig.OwnUrl, + config.ServiceProviderCertificate, + config.ServiceProviderPrivateKey, + config.OwnUrl, metadata, - &advancedConfig.EntityId, - &advancedConfig.AllowInitializationByIdp, - &advancedConfig.SignedRequest, - &advancedConfig.ForceAuthn, - &advancedConfig.CookieSecure, + &config.EntityId, + &config.AllowInitializationByIdp, + &config.SignedRequest, + &config.ForceAuthn, + &config.CookieSecure, ) if err != nil { log.Fatal(LOG_REGIO, "cannot initialize saml service provider: %v", err) @@ -119,8 +114,8 @@ func run() { }() // saml specific handle (no RESTful) to router - elionaAuth := eliona.NewSingleSignOn(basicConfig.OwnUrl, - basicConfig.UserToArchive, advancedConfig.LoginFailedUrl) + elionaAuth := eliona.NewSingleSignOn(config.OwnUrl, + config.UserToArchive, config.LoginFailedUrl) activeHandleFunc := http.HandlerFunc(elionaAuth.ActiveHandle) http.Handle(eliona.ENDPOINT_SSO_GENERIC_ACTIVE, activeHandleFunc) diff --git a/appdb/advanced_config.go b/appdb/advanced_config.go deleted file mode 100644 index 21f7cd1..0000000 --- a/appdb/advanced_config.go +++ /dev/null @@ -1,1309 +0,0 @@ -// Code generated by SQLBoiler 4.16.1 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package appdb - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/friendsofgo/errors" - "github.com/volatiletech/sqlboiler/v4/boil" - "github.com/volatiletech/sqlboiler/v4/queries" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" - "github.com/volatiletech/strmangle" -) - -// AdvancedConfig is an object representing the database table. -type AdvancedConfig struct { - ID int32 `boil:"id" json:"id" toml:"id" yaml:"id"` - AllowInitializationByIdp bool `boil:"allow_initialization_by_idp" json:"allow_initialization_by_idp" toml:"allow_initialization_by_idp" yaml:"allow_initialization_by_idp"` - SignedRequest bool `boil:"signed_request" json:"signed_request" toml:"signed_request" yaml:"signed_request"` - ForceAuthn bool `boil:"force_authn" json:"force_authn" toml:"force_authn" yaml:"force_authn"` - EntityID string `boil:"entity_id" json:"entity_id" toml:"entity_id" yaml:"entity_id"` - CookieSecure bool `boil:"cookie_secure" json:"cookie_secure" toml:"cookie_secure" yaml:"cookie_secure"` - LoginFailedURL string `boil:"login_failed_url" json:"login_failed_url" toml:"login_failed_url" yaml:"login_failed_url"` - - R *advancedConfigR `boil:"-" json:"-" toml:"-" yaml:"-"` - L advancedConfigL `boil:"-" json:"-" toml:"-" yaml:"-"` -} - -var AdvancedConfigColumns = struct { - ID string - AllowInitializationByIdp string - SignedRequest string - ForceAuthn string - EntityID string - CookieSecure string - LoginFailedURL string -}{ - ID: "id", - AllowInitializationByIdp: "allow_initialization_by_idp", - SignedRequest: "signed_request", - ForceAuthn: "force_authn", - EntityID: "entity_id", - CookieSecure: "cookie_secure", - LoginFailedURL: "login_failed_url", -} - -var AdvancedConfigTableColumns = struct { - ID string - AllowInitializationByIdp string - SignedRequest string - ForceAuthn string - EntityID string - CookieSecure string - LoginFailedURL string -}{ - ID: "advanced_config.id", - AllowInitializationByIdp: "advanced_config.allow_initialization_by_idp", - SignedRequest: "advanced_config.signed_request", - ForceAuthn: "advanced_config.force_authn", - EntityID: "advanced_config.entity_id", - CookieSecure: "advanced_config.cookie_secure", - LoginFailedURL: "advanced_config.login_failed_url", -} - -// Generated where - -type whereHelperint32 struct{ field string } - -func (w whereHelperint32) EQ(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } -func (w whereHelperint32) NEQ(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } -func (w whereHelperint32) LT(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } -func (w whereHelperint32) LTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } -func (w whereHelperint32) GT(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } -func (w whereHelperint32) GTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } -func (w whereHelperint32) IN(slice []int32) qm.QueryMod { - values := make([]interface{}, 0, len(slice)) - for _, value := range slice { - values = append(values, value) - } - return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...) -} -func (w whereHelperint32) NIN(slice []int32) qm.QueryMod { - values := make([]interface{}, 0, len(slice)) - for _, value := range slice { - values = append(values, value) - } - return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...) -} - -type whereHelperbool struct{ field string } - -func (w whereHelperbool) EQ(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } -func (w whereHelperbool) NEQ(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } -func (w whereHelperbool) LT(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } -func (w whereHelperbool) LTE(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } -func (w whereHelperbool) GT(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } -func (w whereHelperbool) GTE(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } - -type whereHelperstring struct{ field string } - -func (w whereHelperstring) EQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } -func (w whereHelperstring) NEQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } -func (w whereHelperstring) LT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } -func (w whereHelperstring) LTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } -func (w whereHelperstring) GT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } -func (w whereHelperstring) GTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } -func (w whereHelperstring) LIKE(x string) qm.QueryMod { return qm.Where(w.field+" LIKE ?", x) } -func (w whereHelperstring) NLIKE(x string) qm.QueryMod { return qm.Where(w.field+" NOT LIKE ?", x) } -func (w whereHelperstring) ILIKE(x string) qm.QueryMod { return qm.Where(w.field+" ILIKE ?", x) } -func (w whereHelperstring) NILIKE(x string) qm.QueryMod { return qm.Where(w.field+" NOT ILIKE ?", x) } -func (w whereHelperstring) IN(slice []string) qm.QueryMod { - values := make([]interface{}, 0, len(slice)) - for _, value := range slice { - values = append(values, value) - } - return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...) -} -func (w whereHelperstring) NIN(slice []string) qm.QueryMod { - values := make([]interface{}, 0, len(slice)) - for _, value := range slice { - values = append(values, value) - } - return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...) -} - -var AdvancedConfigWhere = struct { - ID whereHelperint32 - AllowInitializationByIdp whereHelperbool - SignedRequest whereHelperbool - ForceAuthn whereHelperbool - EntityID whereHelperstring - CookieSecure whereHelperbool - LoginFailedURL whereHelperstring -}{ - ID: whereHelperint32{field: "\"saml_sp\".\"advanced_config\".\"id\""}, - AllowInitializationByIdp: whereHelperbool{field: "\"saml_sp\".\"advanced_config\".\"allow_initialization_by_idp\""}, - SignedRequest: whereHelperbool{field: "\"saml_sp\".\"advanced_config\".\"signed_request\""}, - ForceAuthn: whereHelperbool{field: "\"saml_sp\".\"advanced_config\".\"force_authn\""}, - EntityID: whereHelperstring{field: "\"saml_sp\".\"advanced_config\".\"entity_id\""}, - CookieSecure: whereHelperbool{field: "\"saml_sp\".\"advanced_config\".\"cookie_secure\""}, - LoginFailedURL: whereHelperstring{field: "\"saml_sp\".\"advanced_config\".\"login_failed_url\""}, -} - -// AdvancedConfigRels is where relationship names are stored. -var AdvancedConfigRels = struct { - IDBasicConfig string -}{ - IDBasicConfig: "IDBasicConfig", -} - -// advancedConfigR is where relationships are stored. -type advancedConfigR struct { - IDBasicConfig *BasicConfig `boil:"IDBasicConfig" json:"IDBasicConfig" toml:"IDBasicConfig" yaml:"IDBasicConfig"` -} - -// NewStruct creates a new relationship struct -func (*advancedConfigR) NewStruct() *advancedConfigR { - return &advancedConfigR{} -} - -func (r *advancedConfigR) GetIDBasicConfig() *BasicConfig { - if r == nil { - return nil - } - return r.IDBasicConfig -} - -// advancedConfigL is where Load methods for each relationship are stored. -type advancedConfigL struct{} - -var ( - advancedConfigAllColumns = []string{"id", "allow_initialization_by_idp", "signed_request", "force_authn", "entity_id", "cookie_secure", "login_failed_url"} - advancedConfigColumnsWithoutDefault = []string{} - advancedConfigColumnsWithDefault = []string{"id", "allow_initialization_by_idp", "signed_request", "force_authn", "entity_id", "cookie_secure", "login_failed_url"} - advancedConfigPrimaryKeyColumns = []string{"id"} - advancedConfigGeneratedColumns = []string{} -) - -type ( - // AdvancedConfigSlice is an alias for a slice of pointers to AdvancedConfig. - // This should almost always be used instead of []AdvancedConfig. - AdvancedConfigSlice []*AdvancedConfig - // AdvancedConfigHook is the signature for custom AdvancedConfig hook methods - AdvancedConfigHook func(context.Context, boil.ContextExecutor, *AdvancedConfig) error - - advancedConfigQuery struct { - *queries.Query - } -) - -// Cache for insert, update and upsert -var ( - advancedConfigType = reflect.TypeOf(&AdvancedConfig{}) - advancedConfigMapping = queries.MakeStructMapping(advancedConfigType) - advancedConfigPrimaryKeyMapping, _ = queries.BindMapping(advancedConfigType, advancedConfigMapping, advancedConfigPrimaryKeyColumns) - advancedConfigInsertCacheMut sync.RWMutex - advancedConfigInsertCache = make(map[string]insertCache) - advancedConfigUpdateCacheMut sync.RWMutex - advancedConfigUpdateCache = make(map[string]updateCache) - advancedConfigUpsertCacheMut sync.RWMutex - advancedConfigUpsertCache = make(map[string]insertCache) -) - -var ( - // Force time package dependency for automated UpdatedAt/CreatedAt. - _ = time.Second - // Force qmhelper dependency for where clause generation (which doesn't - // always happen) - _ = qmhelper.Where -) - -var advancedConfigAfterSelectMu sync.Mutex -var advancedConfigAfterSelectHooks []AdvancedConfigHook - -var advancedConfigBeforeInsertMu sync.Mutex -var advancedConfigBeforeInsertHooks []AdvancedConfigHook -var advancedConfigAfterInsertMu sync.Mutex -var advancedConfigAfterInsertHooks []AdvancedConfigHook - -var advancedConfigBeforeUpdateMu sync.Mutex -var advancedConfigBeforeUpdateHooks []AdvancedConfigHook -var advancedConfigAfterUpdateMu sync.Mutex -var advancedConfigAfterUpdateHooks []AdvancedConfigHook - -var advancedConfigBeforeDeleteMu sync.Mutex -var advancedConfigBeforeDeleteHooks []AdvancedConfigHook -var advancedConfigAfterDeleteMu sync.Mutex -var advancedConfigAfterDeleteHooks []AdvancedConfigHook - -var advancedConfigBeforeUpsertMu sync.Mutex -var advancedConfigBeforeUpsertHooks []AdvancedConfigHook -var advancedConfigAfterUpsertMu sync.Mutex -var advancedConfigAfterUpsertHooks []AdvancedConfigHook - -// doAfterSelectHooks executes all "after Select" hooks. -func (o *AdvancedConfig) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigAfterSelectHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeInsertHooks executes all "before insert" hooks. -func (o *AdvancedConfig) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigBeforeInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterInsertHooks executes all "after Insert" hooks. -func (o *AdvancedConfig) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigAfterInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpdateHooks executes all "before Update" hooks. -func (o *AdvancedConfig) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigBeforeUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpdateHooks executes all "after Update" hooks. -func (o *AdvancedConfig) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigAfterUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *AdvancedConfig) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigBeforeDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterDeleteHooks executes all "after Delete" hooks. -func (o *AdvancedConfig) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigAfterDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *AdvancedConfig) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigBeforeUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *AdvancedConfig) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range advancedConfigAfterUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// AddAdvancedConfigHook registers your hook function for all future operations. -func AddAdvancedConfigHook(hookPoint boil.HookPoint, advancedConfigHook AdvancedConfigHook) { - switch hookPoint { - case boil.AfterSelectHook: - advancedConfigAfterSelectMu.Lock() - advancedConfigAfterSelectHooks = append(advancedConfigAfterSelectHooks, advancedConfigHook) - advancedConfigAfterSelectMu.Unlock() - case boil.BeforeInsertHook: - advancedConfigBeforeInsertMu.Lock() - advancedConfigBeforeInsertHooks = append(advancedConfigBeforeInsertHooks, advancedConfigHook) - advancedConfigBeforeInsertMu.Unlock() - case boil.AfterInsertHook: - advancedConfigAfterInsertMu.Lock() - advancedConfigAfterInsertHooks = append(advancedConfigAfterInsertHooks, advancedConfigHook) - advancedConfigAfterInsertMu.Unlock() - case boil.BeforeUpdateHook: - advancedConfigBeforeUpdateMu.Lock() - advancedConfigBeforeUpdateHooks = append(advancedConfigBeforeUpdateHooks, advancedConfigHook) - advancedConfigBeforeUpdateMu.Unlock() - case boil.AfterUpdateHook: - advancedConfigAfterUpdateMu.Lock() - advancedConfigAfterUpdateHooks = append(advancedConfigAfterUpdateHooks, advancedConfigHook) - advancedConfigAfterUpdateMu.Unlock() - case boil.BeforeDeleteHook: - advancedConfigBeforeDeleteMu.Lock() - advancedConfigBeforeDeleteHooks = append(advancedConfigBeforeDeleteHooks, advancedConfigHook) - advancedConfigBeforeDeleteMu.Unlock() - case boil.AfterDeleteHook: - advancedConfigAfterDeleteMu.Lock() - advancedConfigAfterDeleteHooks = append(advancedConfigAfterDeleteHooks, advancedConfigHook) - advancedConfigAfterDeleteMu.Unlock() - case boil.BeforeUpsertHook: - advancedConfigBeforeUpsertMu.Lock() - advancedConfigBeforeUpsertHooks = append(advancedConfigBeforeUpsertHooks, advancedConfigHook) - advancedConfigBeforeUpsertMu.Unlock() - case boil.AfterUpsertHook: - advancedConfigAfterUpsertMu.Lock() - advancedConfigAfterUpsertHooks = append(advancedConfigAfterUpsertHooks, advancedConfigHook) - advancedConfigAfterUpsertMu.Unlock() - } -} - -// OneG returns a single advancedConfig record from the query using the global executor. -func (q advancedConfigQuery) OneG(ctx context.Context) (*AdvancedConfig, error) { - return q.One(ctx, boil.GetContextDB()) -} - -// One returns a single advancedConfig record from the query. -func (q advancedConfigQuery) One(ctx context.Context, exec boil.ContextExecutor) (*AdvancedConfig, error) { - o := &AdvancedConfig{} - - queries.SetLimit(q.Query, 1) - - err := q.Bind(ctx, exec, o) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "appdb: failed to execute a one query for advanced_config") - } - - if err := o.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - - return o, nil -} - -// AllG returns all AdvancedConfig records from the query using the global executor. -func (q advancedConfigQuery) AllG(ctx context.Context) (AdvancedConfigSlice, error) { - return q.All(ctx, boil.GetContextDB()) -} - -// All returns all AdvancedConfig records from the query. -func (q advancedConfigQuery) All(ctx context.Context, exec boil.ContextExecutor) (AdvancedConfigSlice, error) { - var o []*AdvancedConfig - - err := q.Bind(ctx, exec, &o) - if err != nil { - return nil, errors.Wrap(err, "appdb: failed to assign all query results to AdvancedConfig slice") - } - - if len(advancedConfigAfterSelectHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - } - } - - return o, nil -} - -// CountG returns the count of all AdvancedConfig records in the query using the global executor -func (q advancedConfigQuery) CountG(ctx context.Context) (int64, error) { - return q.Count(ctx, boil.GetContextDB()) -} - -// Count returns the count of all AdvancedConfig records in the query. -func (q advancedConfigQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to count advanced_config rows") - } - - return count, nil -} - -// ExistsG checks if the row exists in the table using the global executor. -func (q advancedConfigQuery) ExistsG(ctx context.Context) (bool, error) { - return q.Exists(ctx, boil.GetContextDB()) -} - -// Exists checks if the row exists in the table. -func (q advancedConfigQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - queries.SetLimit(q.Query, 1) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return false, errors.Wrap(err, "appdb: failed to check if advanced_config exists") - } - - return count > 0, nil -} - -// IDBasicConfig pointed to by the foreign key. -func (o *AdvancedConfig) IDBasicConfig(mods ...qm.QueryMod) basicConfigQuery { - queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.ID), - } - - queryMods = append(queryMods, mods...) - - return BasicConfigs(queryMods...) -} - -// LoadIDBasicConfig allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for an N-1 relationship. -func (advancedConfigL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAdvancedConfig interface{}, mods queries.Applicator) error { - var slice []*AdvancedConfig - var object *AdvancedConfig - - if singular { - var ok bool - object, ok = maybeAdvancedConfig.(*AdvancedConfig) - if !ok { - object = new(AdvancedConfig) - ok = queries.SetFromEmbeddedStruct(&object, &maybeAdvancedConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeAdvancedConfig)) - } - } - } else { - s, ok := maybeAdvancedConfig.(*[]*AdvancedConfig) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeAdvancedConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeAdvancedConfig)) - } - } - } - - args := make(map[interface{}]struct{}) - if singular { - if object.R == nil { - object.R = &advancedConfigR{} - } - args[object.ID] = struct{}{} - - } else { - for _, obj := range slice { - if obj.R == nil { - obj.R = &advancedConfigR{} - } - - args[obj.ID] = struct{}{} - - } - } - - if len(args) == 0 { - return nil - } - - argsSlice := make([]interface{}, len(args)) - i := 0 - for arg := range args { - argsSlice[i] = arg - i++ - } - - query := NewQuery( - qm.From(`saml_sp.basic_config`), - qm.WhereIn(`saml_sp.basic_config.id in ?`, argsSlice...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load BasicConfig") - } - - var resultSlice []*BasicConfig - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice BasicConfig") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for basic_config") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for basic_config") - } - - if len(basicConfigAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - - if len(resultSlice) == 0 { - return nil - } - - if singular { - foreign := resultSlice[0] - object.R.IDBasicConfig = foreign - if foreign.R == nil { - foreign.R = &basicConfigR{} - } - foreign.R.IDAdvancedConfig = object - return nil - } - - for _, local := range slice { - for _, foreign := range resultSlice { - if local.ID == foreign.ID { - local.R.IDBasicConfig = foreign - if foreign.R == nil { - foreign.R = &basicConfigR{} - } - foreign.R.IDAdvancedConfig = local - break - } - } - } - - return nil -} - -// SetIDBasicConfigG of the advancedConfig to the related item. -// Sets o.R.IDBasicConfig to related. -// Adds o to related.R.IDAdvancedConfig. -// Uses the global database handle. -func (o *AdvancedConfig) SetIDBasicConfigG(ctx context.Context, insert bool, related *BasicConfig) error { - return o.SetIDBasicConfig(ctx, boil.GetContextDB(), insert, related) -} - -// SetIDBasicConfig of the advancedConfig to the related item. -// Sets o.R.IDBasicConfig to related. -// Adds o to related.R.IDAdvancedConfig. -func (o *AdvancedConfig) SetIDBasicConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *BasicConfig) error { - var err error - if insert { - if err = related.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } - - updateQuery := fmt.Sprintf( - "UPDATE \"saml_sp\".\"advanced_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), - strmangle.WhereClause("\"", "\"", 2, advancedConfigPrimaryKeyColumns), - ) - values := []interface{}{related.ID, o.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update local table") - } - - o.ID = related.ID - if o.R == nil { - o.R = &advancedConfigR{ - IDBasicConfig: related, - } - } else { - o.R.IDBasicConfig = related - } - - if related.R == nil { - related.R = &basicConfigR{ - IDAdvancedConfig: o, - } - } else { - related.R.IDAdvancedConfig = o - } - - return nil -} - -// AdvancedConfigs retrieves all the records using an executor. -func AdvancedConfigs(mods ...qm.QueryMod) advancedConfigQuery { - mods = append(mods, qm.From("\"saml_sp\".\"advanced_config\"")) - q := NewQuery(mods...) - if len(queries.GetSelect(q)) == 0 { - queries.SetSelect(q, []string{"\"saml_sp\".\"advanced_config\".*"}) - } - - return advancedConfigQuery{q} -} - -// FindAdvancedConfigG retrieves a single record by ID. -func FindAdvancedConfigG(ctx context.Context, iD int32, selectCols ...string) (*AdvancedConfig, error) { - return FindAdvancedConfig(ctx, boil.GetContextDB(), iD, selectCols...) -} - -// FindAdvancedConfig retrieves a single record by ID with an executor. -// If selectCols is empty Find will return all columns. -func FindAdvancedConfig(ctx context.Context, exec boil.ContextExecutor, iD int32, selectCols ...string) (*AdvancedConfig, error) { - advancedConfigObj := &AdvancedConfig{} - - sel := "*" - if len(selectCols) > 0 { - sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") - } - query := fmt.Sprintf( - "select %s from \"saml_sp\".\"advanced_config\" where \"id\"=$1", sel, - ) - - q := queries.Raw(query, iD) - - err := q.Bind(ctx, exec, advancedConfigObj) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "appdb: unable to select from advanced_config") - } - - if err = advancedConfigObj.doAfterSelectHooks(ctx, exec); err != nil { - return advancedConfigObj, err - } - - return advancedConfigObj, nil -} - -// InsertG a single record. See Insert for whitelist behavior description. -func (o *AdvancedConfig) InsertG(ctx context.Context, columns boil.Columns) error { - return o.Insert(ctx, boil.GetContextDB(), columns) -} - -// Insert a single record using an executor. -// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *AdvancedConfig) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { - if o == nil { - return errors.New("appdb: no advanced_config provided for insertion") - } - - var err error - - if err := o.doBeforeInsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(advancedConfigColumnsWithDefault, o) - - key := makeCacheKey(columns, nzDefaults) - advancedConfigInsertCacheMut.RLock() - cache, cached := advancedConfigInsertCache[key] - advancedConfigInsertCacheMut.RUnlock() - - if !cached { - wl, returnColumns := columns.InsertColumnSet( - advancedConfigAllColumns, - advancedConfigColumnsWithDefault, - advancedConfigColumnsWithoutDefault, - nzDefaults, - ) - - cache.valueMapping, err = queries.BindMapping(advancedConfigType, advancedConfigMapping, wl) - if err != nil { - return err - } - cache.retMapping, err = queries.BindMapping(advancedConfigType, advancedConfigMapping, returnColumns) - if err != nil { - return err - } - if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"saml_sp\".\"advanced_config\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) - } else { - cache.query = "INSERT INTO \"saml_sp\".\"advanced_config\" %sDEFAULT VALUES%s" - } - - var queryOutput, queryReturning string - - if len(cache.retMapping) != 0 { - queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) - } - - cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - - if err != nil { - return errors.Wrap(err, "appdb: unable to insert into advanced_config") - } - - if !cached { - advancedConfigInsertCacheMut.Lock() - advancedConfigInsertCache[key] = cache - advancedConfigInsertCacheMut.Unlock() - } - - return o.doAfterInsertHooks(ctx, exec) -} - -// UpdateG a single AdvancedConfig record using the global executor. -// See Update for more documentation. -func (o *AdvancedConfig) UpdateG(ctx context.Context, columns boil.Columns) (int64, error) { - return o.Update(ctx, boil.GetContextDB(), columns) -} - -// Update uses an executor to update the AdvancedConfig. -// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. -// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *AdvancedConfig) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { - var err error - if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { - return 0, err - } - key := makeCacheKey(columns, nil) - advancedConfigUpdateCacheMut.RLock() - cache, cached := advancedConfigUpdateCache[key] - advancedConfigUpdateCacheMut.RUnlock() - - if !cached { - wl := columns.UpdateColumnSet( - advancedConfigAllColumns, - advancedConfigPrimaryKeyColumns, - ) - - if !columns.IsWhitelist() { - wl = strmangle.SetComplement(wl, []string{"created_at"}) - } - if len(wl) == 0 { - return 0, errors.New("appdb: unable to update advanced_config, could not build whitelist") - } - - cache.query = fmt.Sprintf("UPDATE \"saml_sp\".\"advanced_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, wl), - strmangle.WhereClause("\"", "\"", len(wl)+1, advancedConfigPrimaryKeyColumns), - ) - cache.valueMapping, err = queries.BindMapping(advancedConfigType, advancedConfigMapping, append(wl, advancedConfigPrimaryKeyColumns...)) - if err != nil { - return 0, err - } - } - - values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, values) - } - var result sql.Result - result, err = exec.ExecContext(ctx, cache.query, values...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update advanced_config row") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by update for advanced_config") - } - - if !cached { - advancedConfigUpdateCacheMut.Lock() - advancedConfigUpdateCache[key] = cache - advancedConfigUpdateCacheMut.Unlock() - } - - return rowsAff, o.doAfterUpdateHooks(ctx, exec) -} - -// UpdateAllG updates all rows with the specified column values. -func (q advancedConfigQuery) UpdateAllG(ctx context.Context, cols M) (int64, error) { - return q.UpdateAll(ctx, boil.GetContextDB(), cols) -} - -// UpdateAll updates all rows with the specified column values. -func (q advancedConfigQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - queries.SetUpdate(q.Query, cols) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update all for advanced_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected for advanced_config") - } - - return rowsAff, nil -} - -// UpdateAllG updates all rows with the specified column values. -func (o AdvancedConfigSlice) UpdateAllG(ctx context.Context, cols M) (int64, error) { - return o.UpdateAll(ctx, boil.GetContextDB(), cols) -} - -// UpdateAll updates all rows with the specified column values, using an executor. -func (o AdvancedConfigSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - ln := int64(len(o)) - if ln == 0 { - return 0, nil - } - - if len(cols) == 0 { - return 0, errors.New("appdb: update all requires at least one column argument") - } - - colNames := make([]string, len(cols)) - args := make([]interface{}, len(cols)) - - i := 0 - for name, value := range cols { - colNames[i] = name - args[i] = value - i++ - } - - // Append all of the primary key values for each column - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), advancedConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := fmt.Sprintf("UPDATE \"saml_sp\".\"advanced_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, advancedConfigPrimaryKeyColumns, len(o))) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update all in advancedConfig slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected all in update all advancedConfig") - } - return rowsAff, nil -} - -// UpsertG attempts an insert, and does an update or ignore on conflict. -func (o *AdvancedConfig) UpsertG(ctx context.Context, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { - return o.Upsert(ctx, boil.GetContextDB(), updateOnConflict, conflictColumns, updateColumns, insertColumns, opts...) -} - -// Upsert attempts an insert using an executor, and does an update or ignore on conflict. -// See boil.Columns documentation for how to properly use updateColumns and insertColumns. -func (o *AdvancedConfig) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { - if o == nil { - return errors.New("appdb: no advanced_config provided for upsert") - } - - if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(advancedConfigColumnsWithDefault, o) - - // Build cache key in-line uglily - mysql vs psql problems - buf := strmangle.GetBuffer() - if updateOnConflict { - buf.WriteByte('t') - } else { - buf.WriteByte('f') - } - buf.WriteByte('.') - for _, c := range conflictColumns { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(updateColumns.Kind)) - for _, c := range updateColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(insertColumns.Kind)) - for _, c := range insertColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - for _, c := range nzDefaults { - buf.WriteString(c) - } - key := buf.String() - strmangle.PutBuffer(buf) - - advancedConfigUpsertCacheMut.RLock() - cache, cached := advancedConfigUpsertCache[key] - advancedConfigUpsertCacheMut.RUnlock() - - var err error - - if !cached { - insert, _ := insertColumns.InsertColumnSet( - advancedConfigAllColumns, - advancedConfigColumnsWithDefault, - advancedConfigColumnsWithoutDefault, - nzDefaults, - ) - - update := updateColumns.UpdateColumnSet( - advancedConfigAllColumns, - advancedConfigPrimaryKeyColumns, - ) - - if updateOnConflict && len(update) == 0 { - return errors.New("appdb: unable to upsert advanced_config, could not build update column list") - } - - ret := strmangle.SetComplement(advancedConfigAllColumns, strmangle.SetIntersect(insert, update)) - - conflict := conflictColumns - if len(conflict) == 0 && updateOnConflict && len(update) != 0 { - if len(advancedConfigPrimaryKeyColumns) == 0 { - return errors.New("appdb: unable to upsert advanced_config, could not build conflict column list") - } - - conflict = make([]string, len(advancedConfigPrimaryKeyColumns)) - copy(conflict, advancedConfigPrimaryKeyColumns) - } - cache.query = buildUpsertQueryPostgres(dialect, "\"saml_sp\".\"advanced_config\"", updateOnConflict, ret, update, conflict, insert, opts...) - - cache.valueMapping, err = queries.BindMapping(advancedConfigType, advancedConfigMapping, insert) - if err != nil { - return err - } - if len(ret) != 0 { - cache.retMapping, err = queries.BindMapping(advancedConfigType, advancedConfigMapping, ret) - if err != nil { - return err - } - } - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - var returns []interface{} - if len(cache.retMapping) != 0 { - returns = queries.PtrsFromMapping(value, cache.retMapping) - } - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) - if errors.Is(err, sql.ErrNoRows) { - err = nil // Postgres doesn't return anything when there's no update - } - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - if err != nil { - return errors.Wrap(err, "appdb: unable to upsert advanced_config") - } - - if !cached { - advancedConfigUpsertCacheMut.Lock() - advancedConfigUpsertCache[key] = cache - advancedConfigUpsertCacheMut.Unlock() - } - - return o.doAfterUpsertHooks(ctx, exec) -} - -// DeleteG deletes a single AdvancedConfig record. -// DeleteG will match against the primary key column to find the record to delete. -func (o *AdvancedConfig) DeleteG(ctx context.Context) (int64, error) { - return o.Delete(ctx, boil.GetContextDB()) -} - -// Delete deletes a single AdvancedConfig record with an executor. -// Delete will match against the primary key column to find the record to delete. -func (o *AdvancedConfig) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if o == nil { - return 0, errors.New("appdb: no AdvancedConfig provided for delete") - } - - if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), advancedConfigPrimaryKeyMapping) - sql := "DELETE FROM \"saml_sp\".\"advanced_config\" WHERE \"id\"=$1" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete from advanced_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by delete for advanced_config") - } - - if err := o.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - return rowsAff, nil -} - -func (q advancedConfigQuery) DeleteAllG(ctx context.Context) (int64, error) { - return q.DeleteAll(ctx, boil.GetContextDB()) -} - -// DeleteAll deletes all matching rows. -func (q advancedConfigQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if q.Query == nil { - return 0, errors.New("appdb: no advancedConfigQuery provided for delete all") - } - - queries.SetDelete(q.Query) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete all from advanced_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for advanced_config") - } - - return rowsAff, nil -} - -// DeleteAllG deletes all rows in the slice. -func (o AdvancedConfigSlice) DeleteAllG(ctx context.Context) (int64, error) { - return o.DeleteAll(ctx, boil.GetContextDB()) -} - -// DeleteAll deletes all rows in the slice, using an executor. -func (o AdvancedConfigSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if len(o) == 0 { - return 0, nil - } - - if len(advancedConfigBeforeDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - var args []interface{} - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), advancedConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "DELETE FROM \"saml_sp\".\"advanced_config\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, advancedConfigPrimaryKeyColumns, len(o)) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete all from advancedConfig slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for advanced_config") - } - - if len(advancedConfigAfterDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - return rowsAff, nil -} - -// ReloadG refetches the object from the database using the primary keys. -func (o *AdvancedConfig) ReloadG(ctx context.Context) error { - if o == nil { - return errors.New("appdb: no AdvancedConfig provided for reload") - } - - return o.Reload(ctx, boil.GetContextDB()) -} - -// Reload refetches the object from the database -// using the primary keys with an executor. -func (o *AdvancedConfig) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindAdvancedConfig(ctx, exec, o.ID) - if err != nil { - return err - } - - *o = *ret - return nil -} - -// ReloadAllG refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *AdvancedConfigSlice) ReloadAllG(ctx context.Context) error { - if o == nil { - return errors.New("appdb: empty AdvancedConfigSlice provided for reload all") - } - - return o.ReloadAll(ctx, boil.GetContextDB()) -} - -// ReloadAll refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *AdvancedConfigSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { - if o == nil || len(*o) == 0 { - return nil - } - - slice := AdvancedConfigSlice{} - var args []interface{} - for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), advancedConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "SELECT \"saml_sp\".\"advanced_config\".* FROM \"saml_sp\".\"advanced_config\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, advancedConfigPrimaryKeyColumns, len(*o)) - - q := queries.Raw(sql, args...) - - err := q.Bind(ctx, exec, &slice) - if err != nil { - return errors.Wrap(err, "appdb: unable to reload all in AdvancedConfigSlice") - } - - *o = slice - - return nil -} - -// AdvancedConfigExistsG checks if the AdvancedConfig row exists. -func AdvancedConfigExistsG(ctx context.Context, iD int32) (bool, error) { - return AdvancedConfigExists(ctx, boil.GetContextDB(), iD) -} - -// AdvancedConfigExists checks if the AdvancedConfig row exists. -func AdvancedConfigExists(ctx context.Context, exec boil.ContextExecutor, iD int32) (bool, error) { - var exists bool - sql := "select exists(select 1 from \"saml_sp\".\"advanced_config\" where \"id\"=$1 limit 1)" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, iD) - } - row := exec.QueryRowContext(ctx, sql, iD) - - err := row.Scan(&exists) - if err != nil { - return false, errors.Wrap(err, "appdb: unable to check if advanced_config exists") - } - - return exists, nil -} - -// Exists checks if the AdvancedConfig row exists. -func (o *AdvancedConfig) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - return AdvancedConfigExists(ctx, exec, o.ID) -} diff --git a/appdb/attribute_map.go b/appdb/attribute_map.go index 71335d5..4e86043 100644 --- a/appdb/attribute_map.go +++ b/appdb/attribute_map.go @@ -64,6 +64,56 @@ var AttributeMapTableColumns = struct { // Generated where +type whereHelperint32 struct{ field string } + +func (w whereHelperint32) EQ(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } +func (w whereHelperint32) NEQ(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } +func (w whereHelperint32) LT(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } +func (w whereHelperint32) LTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } +func (w whereHelperint32) GT(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } +func (w whereHelperint32) GTE(x int32) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } +func (w whereHelperint32) IN(slice []int32) qm.QueryMod { + values := make([]interface{}, 0, len(slice)) + for _, value := range slice { + values = append(values, value) + } + return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...) +} +func (w whereHelperint32) NIN(slice []int32) qm.QueryMod { + values := make([]interface{}, 0, len(slice)) + for _, value := range slice { + values = append(values, value) + } + return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...) +} + +type whereHelperstring struct{ field string } + +func (w whereHelperstring) EQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } +func (w whereHelperstring) NEQ(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } +func (w whereHelperstring) LT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } +func (w whereHelperstring) LTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } +func (w whereHelperstring) GT(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } +func (w whereHelperstring) GTE(x string) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } +func (w whereHelperstring) LIKE(x string) qm.QueryMod { return qm.Where(w.field+" LIKE ?", x) } +func (w whereHelperstring) NLIKE(x string) qm.QueryMod { return qm.Where(w.field+" NOT LIKE ?", x) } +func (w whereHelperstring) ILIKE(x string) qm.QueryMod { return qm.Where(w.field+" ILIKE ?", x) } +func (w whereHelperstring) NILIKE(x string) qm.QueryMod { return qm.Where(w.field+" NOT ILIKE ?", x) } +func (w whereHelperstring) IN(slice []string) qm.QueryMod { + values := make([]interface{}, 0, len(slice)) + for _, value := range slice { + values = append(values, value) + } + return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...) +} +func (w whereHelperstring) NIN(slice []string) qm.QueryMod { + values := make([]interface{}, 0, len(slice)) + for _, value := range slice { + values = append(values, value) + } + return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...) +} + type whereHelpernull_String struct{ field string } func (w whereHelpernull_String) EQ(x null.String) qm.QueryMod { @@ -130,14 +180,14 @@ var AttributeMapWhere = struct { // AttributeMapRels is where relationship names are stored. var AttributeMapRels = struct { - IDBasicConfig string + IDConfig string }{ - IDBasicConfig: "IDBasicConfig", + IDConfig: "IDConfig", } // attributeMapR is where relationships are stored. type attributeMapR struct { - IDBasicConfig *BasicConfig `boil:"IDBasicConfig" json:"IDBasicConfig" toml:"IDBasicConfig" yaml:"IDBasicConfig"` + IDConfig *Config `boil:"IDConfig" json:"IDConfig" toml:"IDConfig" yaml:"IDConfig"` } // NewStruct creates a new relationship struct @@ -145,11 +195,11 @@ func (*attributeMapR) NewStruct() *attributeMapR { return &attributeMapR{} } -func (r *attributeMapR) GetIDBasicConfig() *BasicConfig { +func (r *attributeMapR) GetIDConfig() *Config { if r == nil { return nil } - return r.IDBasicConfig + return r.IDConfig } // attributeMapL is where Load methods for each relationship are stored. @@ -488,20 +538,20 @@ func (q attributeMapQuery) Exists(ctx context.Context, exec boil.ContextExecutor return count > 0, nil } -// IDBasicConfig pointed to by the foreign key. -func (o *AttributeMap) IDBasicConfig(mods ...qm.QueryMod) basicConfigQuery { +// IDConfig pointed to by the foreign key. +func (o *AttributeMap) IDConfig(mods ...qm.QueryMod) configQuery { queryMods := []qm.QueryMod{ qm.Where("\"id\" = ?", o.ID), } queryMods = append(queryMods, mods...) - return BasicConfigs(queryMods...) + return Configs(queryMods...) } -// LoadIDBasicConfig allows an eager lookup of values, cached into the +// LoadIDConfig allows an eager lookup of values, cached into the // loaded structs of the objects. This is for an N-1 relationship. -func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAttributeMap interface{}, mods queries.Applicator) error { +func (attributeMapL) LoadIDConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybeAttributeMap interface{}, mods queries.Applicator) error { var slice []*AttributeMap var object *AttributeMap @@ -557,8 +607,8 @@ func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecut } query := NewQuery( - qm.From(`saml_sp.basic_config`), - qm.WhereIn(`saml_sp.basic_config.id in ?`, argsSlice...), + qm.From(`saml_sp.config`), + qm.WhereIn(`saml_sp.config.id in ?`, argsSlice...), ) if mods != nil { mods.Apply(query) @@ -566,22 +616,22 @@ func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecut results, err := query.QueryContext(ctx, e) if err != nil { - return errors.Wrap(err, "failed to eager load BasicConfig") + return errors.Wrap(err, "failed to eager load Config") } - var resultSlice []*BasicConfig + var resultSlice []*Config if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice BasicConfig") + return errors.Wrap(err, "failed to bind eager loaded slice Config") } if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for basic_config") + return errors.Wrap(err, "failed to close results of eager load for config") } if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for basic_config") + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for config") } - if len(basicConfigAfterSelectHooks) != 0 { + if len(configAfterSelectHooks) != 0 { for _, obj := range resultSlice { if err := obj.doAfterSelectHooks(ctx, e); err != nil { return err @@ -595,9 +645,9 @@ func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecut if singular { foreign := resultSlice[0] - object.R.IDBasicConfig = foreign + object.R.IDConfig = foreign if foreign.R == nil { - foreign.R = &basicConfigR{} + foreign.R = &configR{} } foreign.R.IDAttributeMap = object return nil @@ -606,9 +656,9 @@ func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecut for _, local := range slice { for _, foreign := range resultSlice { if local.ID == foreign.ID { - local.R.IDBasicConfig = foreign + local.R.IDConfig = foreign if foreign.R == nil { - foreign.R = &basicConfigR{} + foreign.R = &configR{} } foreign.R.IDAttributeMap = local break @@ -619,18 +669,18 @@ func (attributeMapL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecut return nil } -// SetIDBasicConfigG of the attributeMap to the related item. -// Sets o.R.IDBasicConfig to related. +// SetIDConfigG of the attributeMap to the related item. +// Sets o.R.IDConfig to related. // Adds o to related.R.IDAttributeMap. // Uses the global database handle. -func (o *AttributeMap) SetIDBasicConfigG(ctx context.Context, insert bool, related *BasicConfig) error { - return o.SetIDBasicConfig(ctx, boil.GetContextDB(), insert, related) +func (o *AttributeMap) SetIDConfigG(ctx context.Context, insert bool, related *Config) error { + return o.SetIDConfig(ctx, boil.GetContextDB(), insert, related) } -// SetIDBasicConfig of the attributeMap to the related item. -// Sets o.R.IDBasicConfig to related. +// SetIDConfig of the attributeMap to the related item. +// Sets o.R.IDConfig to related. // Adds o to related.R.IDAttributeMap. -func (o *AttributeMap) SetIDBasicConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *BasicConfig) error { +func (o *AttributeMap) SetIDConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Config) error { var err error if insert { if err = related.Insert(ctx, exec, boil.Infer()); err != nil { @@ -657,14 +707,14 @@ func (o *AttributeMap) SetIDBasicConfig(ctx context.Context, exec boil.ContextEx o.ID = related.ID if o.R == nil { o.R = &attributeMapR{ - IDBasicConfig: related, + IDConfig: related, } } else { - o.R.IDBasicConfig = related + o.R.IDConfig = related } if related.R == nil { - related.R = &basicConfigR{ + related.R = &configR{ IDAttributeMap: o, } } else { diff --git a/appdb/basic_config.go b/appdb/basic_config.go deleted file mode 100644 index ca3e400..0000000 --- a/appdb/basic_config.go +++ /dev/null @@ -1,1650 +0,0 @@ -// Code generated by SQLBoiler 4.16.1 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. -// This file is meant to be re-generated in place and/or deleted at any time. - -package appdb - -import ( - "context" - "database/sql" - "fmt" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/friendsofgo/errors" - "github.com/volatiletech/null/v8" - "github.com/volatiletech/sqlboiler/v4/boil" - "github.com/volatiletech/sqlboiler/v4/queries" - "github.com/volatiletech/sqlboiler/v4/queries/qm" - "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" - "github.com/volatiletech/strmangle" -) - -// BasicConfig is an object representing the database table. -type BasicConfig struct { - ID int32 `boil:"id" json:"id" toml:"id" yaml:"id"` - Enable bool `boil:"enable" json:"enable" toml:"enable" yaml:"enable"` - SPCertificate string `boil:"sp_certificate" json:"sp_certificate" toml:"sp_certificate" yaml:"sp_certificate"` - SPPrivateKey string `boil:"sp_private_key" json:"sp_private_key" toml:"sp_private_key" yaml:"sp_private_key"` - IdpMetadataURL null.String `boil:"idp_metadata_url" json:"idp_metadata_url,omitempty" toml:"idp_metadata_url" yaml:"idp_metadata_url,omitempty"` - MetadataXML null.String `boil:"metadata_xml" json:"metadata_xml,omitempty" toml:"metadata_xml" yaml:"metadata_xml,omitempty"` - OwnURL string `boil:"own_url" json:"own_url" toml:"own_url" yaml:"own_url"` - UserToArchive bool `boil:"user_to_archive" json:"user_to_archive" toml:"user_to_archive" yaml:"user_to_archive"` - - R *basicConfigR `boil:"-" json:"-" toml:"-" yaml:"-"` - L basicConfigL `boil:"-" json:"-" toml:"-" yaml:"-"` -} - -var BasicConfigColumns = struct { - ID string - Enable string - SPCertificate string - SPPrivateKey string - IdpMetadataURL string - MetadataXML string - OwnURL string - UserToArchive string -}{ - ID: "id", - Enable: "enable", - SPCertificate: "sp_certificate", - SPPrivateKey: "sp_private_key", - IdpMetadataURL: "idp_metadata_url", - MetadataXML: "metadata_xml", - OwnURL: "own_url", - UserToArchive: "user_to_archive", -} - -var BasicConfigTableColumns = struct { - ID string - Enable string - SPCertificate string - SPPrivateKey string - IdpMetadataURL string - MetadataXML string - OwnURL string - UserToArchive string -}{ - ID: "basic_config.id", - Enable: "basic_config.enable", - SPCertificate: "basic_config.sp_certificate", - SPPrivateKey: "basic_config.sp_private_key", - IdpMetadataURL: "basic_config.idp_metadata_url", - MetadataXML: "basic_config.metadata_xml", - OwnURL: "basic_config.own_url", - UserToArchive: "basic_config.user_to_archive", -} - -// Generated where - -var BasicConfigWhere = struct { - ID whereHelperint32 - Enable whereHelperbool - SPCertificate whereHelperstring - SPPrivateKey whereHelperstring - IdpMetadataURL whereHelpernull_String - MetadataXML whereHelpernull_String - OwnURL whereHelperstring - UserToArchive whereHelperbool -}{ - ID: whereHelperint32{field: "\"saml_sp\".\"basic_config\".\"id\""}, - Enable: whereHelperbool{field: "\"saml_sp\".\"basic_config\".\"enable\""}, - SPCertificate: whereHelperstring{field: "\"saml_sp\".\"basic_config\".\"sp_certificate\""}, - SPPrivateKey: whereHelperstring{field: "\"saml_sp\".\"basic_config\".\"sp_private_key\""}, - IdpMetadataURL: whereHelpernull_String{field: "\"saml_sp\".\"basic_config\".\"idp_metadata_url\""}, - MetadataXML: whereHelpernull_String{field: "\"saml_sp\".\"basic_config\".\"metadata_xml\""}, - OwnURL: whereHelperstring{field: "\"saml_sp\".\"basic_config\".\"own_url\""}, - UserToArchive: whereHelperbool{field: "\"saml_sp\".\"basic_config\".\"user_to_archive\""}, -} - -// BasicConfigRels is where relationship names are stored. -var BasicConfigRels = struct { - IDAdvancedConfig string - IDAttributeMap string - IDPermission string -}{ - IDAdvancedConfig: "IDAdvancedConfig", - IDAttributeMap: "IDAttributeMap", - IDPermission: "IDPermission", -} - -// basicConfigR is where relationships are stored. -type basicConfigR struct { - IDAdvancedConfig *AdvancedConfig `boil:"IDAdvancedConfig" json:"IDAdvancedConfig" toml:"IDAdvancedConfig" yaml:"IDAdvancedConfig"` - IDAttributeMap *AttributeMap `boil:"IDAttributeMap" json:"IDAttributeMap" toml:"IDAttributeMap" yaml:"IDAttributeMap"` - IDPermission *Permission `boil:"IDPermission" json:"IDPermission" toml:"IDPermission" yaml:"IDPermission"` -} - -// NewStruct creates a new relationship struct -func (*basicConfigR) NewStruct() *basicConfigR { - return &basicConfigR{} -} - -func (r *basicConfigR) GetIDAdvancedConfig() *AdvancedConfig { - if r == nil { - return nil - } - return r.IDAdvancedConfig -} - -func (r *basicConfigR) GetIDAttributeMap() *AttributeMap { - if r == nil { - return nil - } - return r.IDAttributeMap -} - -func (r *basicConfigR) GetIDPermission() *Permission { - if r == nil { - return nil - } - return r.IDPermission -} - -// basicConfigL is where Load methods for each relationship are stored. -type basicConfigL struct{} - -var ( - basicConfigAllColumns = []string{"id", "enable", "sp_certificate", "sp_private_key", "idp_metadata_url", "metadata_xml", "own_url", "user_to_archive"} - basicConfigColumnsWithoutDefault = []string{"sp_certificate", "sp_private_key", "own_url"} - basicConfigColumnsWithDefault = []string{"id", "enable", "idp_metadata_url", "metadata_xml", "user_to_archive"} - basicConfigPrimaryKeyColumns = []string{"id"} - basicConfigGeneratedColumns = []string{} -) - -type ( - // BasicConfigSlice is an alias for a slice of pointers to BasicConfig. - // This should almost always be used instead of []BasicConfig. - BasicConfigSlice []*BasicConfig - // BasicConfigHook is the signature for custom BasicConfig hook methods - BasicConfigHook func(context.Context, boil.ContextExecutor, *BasicConfig) error - - basicConfigQuery struct { - *queries.Query - } -) - -// Cache for insert, update and upsert -var ( - basicConfigType = reflect.TypeOf(&BasicConfig{}) - basicConfigMapping = queries.MakeStructMapping(basicConfigType) - basicConfigPrimaryKeyMapping, _ = queries.BindMapping(basicConfigType, basicConfigMapping, basicConfigPrimaryKeyColumns) - basicConfigInsertCacheMut sync.RWMutex - basicConfigInsertCache = make(map[string]insertCache) - basicConfigUpdateCacheMut sync.RWMutex - basicConfigUpdateCache = make(map[string]updateCache) - basicConfigUpsertCacheMut sync.RWMutex - basicConfigUpsertCache = make(map[string]insertCache) -) - -var ( - // Force time package dependency for automated UpdatedAt/CreatedAt. - _ = time.Second - // Force qmhelper dependency for where clause generation (which doesn't - // always happen) - _ = qmhelper.Where -) - -var basicConfigAfterSelectMu sync.Mutex -var basicConfigAfterSelectHooks []BasicConfigHook - -var basicConfigBeforeInsertMu sync.Mutex -var basicConfigBeforeInsertHooks []BasicConfigHook -var basicConfigAfterInsertMu sync.Mutex -var basicConfigAfterInsertHooks []BasicConfigHook - -var basicConfigBeforeUpdateMu sync.Mutex -var basicConfigBeforeUpdateHooks []BasicConfigHook -var basicConfigAfterUpdateMu sync.Mutex -var basicConfigAfterUpdateHooks []BasicConfigHook - -var basicConfigBeforeDeleteMu sync.Mutex -var basicConfigBeforeDeleteHooks []BasicConfigHook -var basicConfigAfterDeleteMu sync.Mutex -var basicConfigAfterDeleteHooks []BasicConfigHook - -var basicConfigBeforeUpsertMu sync.Mutex -var basicConfigBeforeUpsertHooks []BasicConfigHook -var basicConfigAfterUpsertMu sync.Mutex -var basicConfigAfterUpsertHooks []BasicConfigHook - -// doAfterSelectHooks executes all "after Select" hooks. -func (o *BasicConfig) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigAfterSelectHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeInsertHooks executes all "before insert" hooks. -func (o *BasicConfig) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigBeforeInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterInsertHooks executes all "after Insert" hooks. -func (o *BasicConfig) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigAfterInsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpdateHooks executes all "before Update" hooks. -func (o *BasicConfig) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigBeforeUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpdateHooks executes all "after Update" hooks. -func (o *BasicConfig) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigAfterUpdateHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeDeleteHooks executes all "before Delete" hooks. -func (o *BasicConfig) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigBeforeDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterDeleteHooks executes all "after Delete" hooks. -func (o *BasicConfig) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigAfterDeleteHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doBeforeUpsertHooks executes all "before Upsert" hooks. -func (o *BasicConfig) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigBeforeUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// doAfterUpsertHooks executes all "after Upsert" hooks. -func (o *BasicConfig) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { - if boil.HooksAreSkipped(ctx) { - return nil - } - - for _, hook := range basicConfigAfterUpsertHooks { - if err := hook(ctx, exec, o); err != nil { - return err - } - } - - return nil -} - -// AddBasicConfigHook registers your hook function for all future operations. -func AddBasicConfigHook(hookPoint boil.HookPoint, basicConfigHook BasicConfigHook) { - switch hookPoint { - case boil.AfterSelectHook: - basicConfigAfterSelectMu.Lock() - basicConfigAfterSelectHooks = append(basicConfigAfterSelectHooks, basicConfigHook) - basicConfigAfterSelectMu.Unlock() - case boil.BeforeInsertHook: - basicConfigBeforeInsertMu.Lock() - basicConfigBeforeInsertHooks = append(basicConfigBeforeInsertHooks, basicConfigHook) - basicConfigBeforeInsertMu.Unlock() - case boil.AfterInsertHook: - basicConfigAfterInsertMu.Lock() - basicConfigAfterInsertHooks = append(basicConfigAfterInsertHooks, basicConfigHook) - basicConfigAfterInsertMu.Unlock() - case boil.BeforeUpdateHook: - basicConfigBeforeUpdateMu.Lock() - basicConfigBeforeUpdateHooks = append(basicConfigBeforeUpdateHooks, basicConfigHook) - basicConfigBeforeUpdateMu.Unlock() - case boil.AfterUpdateHook: - basicConfigAfterUpdateMu.Lock() - basicConfigAfterUpdateHooks = append(basicConfigAfterUpdateHooks, basicConfigHook) - basicConfigAfterUpdateMu.Unlock() - case boil.BeforeDeleteHook: - basicConfigBeforeDeleteMu.Lock() - basicConfigBeforeDeleteHooks = append(basicConfigBeforeDeleteHooks, basicConfigHook) - basicConfigBeforeDeleteMu.Unlock() - case boil.AfterDeleteHook: - basicConfigAfterDeleteMu.Lock() - basicConfigAfterDeleteHooks = append(basicConfigAfterDeleteHooks, basicConfigHook) - basicConfigAfterDeleteMu.Unlock() - case boil.BeforeUpsertHook: - basicConfigBeforeUpsertMu.Lock() - basicConfigBeforeUpsertHooks = append(basicConfigBeforeUpsertHooks, basicConfigHook) - basicConfigBeforeUpsertMu.Unlock() - case boil.AfterUpsertHook: - basicConfigAfterUpsertMu.Lock() - basicConfigAfterUpsertHooks = append(basicConfigAfterUpsertHooks, basicConfigHook) - basicConfigAfterUpsertMu.Unlock() - } -} - -// OneG returns a single basicConfig record from the query using the global executor. -func (q basicConfigQuery) OneG(ctx context.Context) (*BasicConfig, error) { - return q.One(ctx, boil.GetContextDB()) -} - -// One returns a single basicConfig record from the query. -func (q basicConfigQuery) One(ctx context.Context, exec boil.ContextExecutor) (*BasicConfig, error) { - o := &BasicConfig{} - - queries.SetLimit(q.Query, 1) - - err := q.Bind(ctx, exec, o) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "appdb: failed to execute a one query for basic_config") - } - - if err := o.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - - return o, nil -} - -// AllG returns all BasicConfig records from the query using the global executor. -func (q basicConfigQuery) AllG(ctx context.Context) (BasicConfigSlice, error) { - return q.All(ctx, boil.GetContextDB()) -} - -// All returns all BasicConfig records from the query. -func (q basicConfigQuery) All(ctx context.Context, exec boil.ContextExecutor) (BasicConfigSlice, error) { - var o []*BasicConfig - - err := q.Bind(ctx, exec, &o) - if err != nil { - return nil, errors.Wrap(err, "appdb: failed to assign all query results to BasicConfig slice") - } - - if len(basicConfigAfterSelectHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterSelectHooks(ctx, exec); err != nil { - return o, err - } - } - } - - return o, nil -} - -// CountG returns the count of all BasicConfig records in the query using the global executor -func (q basicConfigQuery) CountG(ctx context.Context) (int64, error) { - return q.Count(ctx, boil.GetContextDB()) -} - -// Count returns the count of all BasicConfig records in the query. -func (q basicConfigQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to count basic_config rows") - } - - return count, nil -} - -// ExistsG checks if the row exists in the table using the global executor. -func (q basicConfigQuery) ExistsG(ctx context.Context) (bool, error) { - return q.Exists(ctx, boil.GetContextDB()) -} - -// Exists checks if the row exists in the table. -func (q basicConfigQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - var count int64 - - queries.SetSelect(q.Query, nil) - queries.SetCount(q.Query) - queries.SetLimit(q.Query, 1) - - err := q.Query.QueryRowContext(ctx, exec).Scan(&count) - if err != nil { - return false, errors.Wrap(err, "appdb: failed to check if basic_config exists") - } - - return count > 0, nil -} - -// IDAdvancedConfig pointed to by the foreign key. -func (o *BasicConfig) IDAdvancedConfig(mods ...qm.QueryMod) advancedConfigQuery { - queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.ID), - } - - queryMods = append(queryMods, mods...) - - return AdvancedConfigs(queryMods...) -} - -// IDAttributeMap pointed to by the foreign key. -func (o *BasicConfig) IDAttributeMap(mods ...qm.QueryMod) attributeMapQuery { - queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.ID), - } - - queryMods = append(queryMods, mods...) - - return AttributeMaps(queryMods...) -} - -// IDPermission pointed to by the foreign key. -func (o *BasicConfig) IDPermission(mods ...qm.QueryMod) permissionQuery { - queryMods := []qm.QueryMod{ - qm.Where("\"id\" = ?", o.ID), - } - - queryMods = append(queryMods, mods...) - - return Permissions(queryMods...) -} - -// LoadIDAdvancedConfig allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-1 relationship. -func (basicConfigL) LoadIDAdvancedConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybeBasicConfig interface{}, mods queries.Applicator) error { - var slice []*BasicConfig - var object *BasicConfig - - if singular { - var ok bool - object, ok = maybeBasicConfig.(*BasicConfig) - if !ok { - object = new(BasicConfig) - ok = queries.SetFromEmbeddedStruct(&object, &maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeBasicConfig)) - } - } - } else { - s, ok := maybeBasicConfig.(*[]*BasicConfig) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeBasicConfig)) - } - } - } - - args := make(map[interface{}]struct{}) - if singular { - if object.R == nil { - object.R = &basicConfigR{} - } - args[object.ID] = struct{}{} - } else { - for _, obj := range slice { - if obj.R == nil { - obj.R = &basicConfigR{} - } - - args[obj.ID] = struct{}{} - } - } - - if len(args) == 0 { - return nil - } - - argsSlice := make([]interface{}, len(args)) - i := 0 - for arg := range args { - argsSlice[i] = arg - i++ - } - - query := NewQuery( - qm.From(`saml_sp.advanced_config`), - qm.WhereIn(`saml_sp.advanced_config.id in ?`, argsSlice...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load AdvancedConfig") - } - - var resultSlice []*AdvancedConfig - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice AdvancedConfig") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for advanced_config") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for advanced_config") - } - - if len(advancedConfigAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - - if len(resultSlice) == 0 { - return nil - } - - if singular { - foreign := resultSlice[0] - object.R.IDAdvancedConfig = foreign - if foreign.R == nil { - foreign.R = &advancedConfigR{} - } - foreign.R.IDBasicConfig = object - } - - for _, local := range slice { - for _, foreign := range resultSlice { - if local.ID == foreign.ID { - local.R.IDAdvancedConfig = foreign - if foreign.R == nil { - foreign.R = &advancedConfigR{} - } - foreign.R.IDBasicConfig = local - break - } - } - } - - return nil -} - -// LoadIDAttributeMap allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-1 relationship. -func (basicConfigL) LoadIDAttributeMap(ctx context.Context, e boil.ContextExecutor, singular bool, maybeBasicConfig interface{}, mods queries.Applicator) error { - var slice []*BasicConfig - var object *BasicConfig - - if singular { - var ok bool - object, ok = maybeBasicConfig.(*BasicConfig) - if !ok { - object = new(BasicConfig) - ok = queries.SetFromEmbeddedStruct(&object, &maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeBasicConfig)) - } - } - } else { - s, ok := maybeBasicConfig.(*[]*BasicConfig) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeBasicConfig)) - } - } - } - - args := make(map[interface{}]struct{}) - if singular { - if object.R == nil { - object.R = &basicConfigR{} - } - args[object.ID] = struct{}{} - } else { - for _, obj := range slice { - if obj.R == nil { - obj.R = &basicConfigR{} - } - - args[obj.ID] = struct{}{} - } - } - - if len(args) == 0 { - return nil - } - - argsSlice := make([]interface{}, len(args)) - i := 0 - for arg := range args { - argsSlice[i] = arg - i++ - } - - query := NewQuery( - qm.From(`saml_sp.attribute_map`), - qm.WhereIn(`saml_sp.attribute_map.id in ?`, argsSlice...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load AttributeMap") - } - - var resultSlice []*AttributeMap - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice AttributeMap") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for attribute_map") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for attribute_map") - } - - if len(attributeMapAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - - if len(resultSlice) == 0 { - return nil - } - - if singular { - foreign := resultSlice[0] - object.R.IDAttributeMap = foreign - if foreign.R == nil { - foreign.R = &attributeMapR{} - } - foreign.R.IDBasicConfig = object - } - - for _, local := range slice { - for _, foreign := range resultSlice { - if local.ID == foreign.ID { - local.R.IDAttributeMap = foreign - if foreign.R == nil { - foreign.R = &attributeMapR{} - } - foreign.R.IDBasicConfig = local - break - } - } - } - - return nil -} - -// LoadIDPermission allows an eager lookup of values, cached into the -// loaded structs of the objects. This is for a 1-1 relationship. -func (basicConfigL) LoadIDPermission(ctx context.Context, e boil.ContextExecutor, singular bool, maybeBasicConfig interface{}, mods queries.Applicator) error { - var slice []*BasicConfig - var object *BasicConfig - - if singular { - var ok bool - object, ok = maybeBasicConfig.(*BasicConfig) - if !ok { - object = new(BasicConfig) - ok = queries.SetFromEmbeddedStruct(&object, &maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeBasicConfig)) - } - } - } else { - s, ok := maybeBasicConfig.(*[]*BasicConfig) - if ok { - slice = *s - } else { - ok = queries.SetFromEmbeddedStruct(&slice, maybeBasicConfig) - if !ok { - return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeBasicConfig)) - } - } - } - - args := make(map[interface{}]struct{}) - if singular { - if object.R == nil { - object.R = &basicConfigR{} - } - args[object.ID] = struct{}{} - } else { - for _, obj := range slice { - if obj.R == nil { - obj.R = &basicConfigR{} - } - - args[obj.ID] = struct{}{} - } - } - - if len(args) == 0 { - return nil - } - - argsSlice := make([]interface{}, len(args)) - i := 0 - for arg := range args { - argsSlice[i] = arg - i++ - } - - query := NewQuery( - qm.From(`saml_sp.permissions`), - qm.WhereIn(`saml_sp.permissions.id in ?`, argsSlice...), - ) - if mods != nil { - mods.Apply(query) - } - - results, err := query.QueryContext(ctx, e) - if err != nil { - return errors.Wrap(err, "failed to eager load Permission") - } - - var resultSlice []*Permission - if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice Permission") - } - - if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for permissions") - } - if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for permissions") - } - - if len(permissionAfterSelectHooks) != 0 { - for _, obj := range resultSlice { - if err := obj.doAfterSelectHooks(ctx, e); err != nil { - return err - } - } - } - - if len(resultSlice) == 0 { - return nil - } - - if singular { - foreign := resultSlice[0] - object.R.IDPermission = foreign - if foreign.R == nil { - foreign.R = &permissionR{} - } - foreign.R.IDBasicConfig = object - } - - for _, local := range slice { - for _, foreign := range resultSlice { - if local.ID == foreign.ID { - local.R.IDPermission = foreign - if foreign.R == nil { - foreign.R = &permissionR{} - } - foreign.R.IDBasicConfig = local - break - } - } - } - - return nil -} - -// SetIDAdvancedConfigG of the basicConfig to the related item. -// Sets o.R.IDAdvancedConfig to related. -// Adds o to related.R.IDBasicConfig. -// Uses the global database handle. -func (o *BasicConfig) SetIDAdvancedConfigG(ctx context.Context, insert bool, related *AdvancedConfig) error { - return o.SetIDAdvancedConfig(ctx, boil.GetContextDB(), insert, related) -} - -// SetIDAdvancedConfig of the basicConfig to the related item. -// Sets o.R.IDAdvancedConfig to related. -// Adds o to related.R.IDBasicConfig. -func (o *BasicConfig) SetIDAdvancedConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *AdvancedConfig) error { - var err error - - if insert { - related.ID = o.ID - - if err = related.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"saml_sp\".\"advanced_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), - strmangle.WhereClause("\"", "\"", 2, advancedConfigPrimaryKeyColumns), - ) - values := []interface{}{o.ID, related.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - related.ID = o.ID - } - - if o.R == nil { - o.R = &basicConfigR{ - IDAdvancedConfig: related, - } - } else { - o.R.IDAdvancedConfig = related - } - - if related.R == nil { - related.R = &advancedConfigR{ - IDBasicConfig: o, - } - } else { - related.R.IDBasicConfig = o - } - return nil -} - -// SetIDAttributeMapG of the basicConfig to the related item. -// Sets o.R.IDAttributeMap to related. -// Adds o to related.R.IDBasicConfig. -// Uses the global database handle. -func (o *BasicConfig) SetIDAttributeMapG(ctx context.Context, insert bool, related *AttributeMap) error { - return o.SetIDAttributeMap(ctx, boil.GetContextDB(), insert, related) -} - -// SetIDAttributeMap of the basicConfig to the related item. -// Sets o.R.IDAttributeMap to related. -// Adds o to related.R.IDBasicConfig. -func (o *BasicConfig) SetIDAttributeMap(ctx context.Context, exec boil.ContextExecutor, insert bool, related *AttributeMap) error { - var err error - - if insert { - related.ID = o.ID - - if err = related.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"saml_sp\".\"attribute_map\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), - strmangle.WhereClause("\"", "\"", 2, attributeMapPrimaryKeyColumns), - ) - values := []interface{}{o.ID, related.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - related.ID = o.ID - } - - if o.R == nil { - o.R = &basicConfigR{ - IDAttributeMap: related, - } - } else { - o.R.IDAttributeMap = related - } - - if related.R == nil { - related.R = &attributeMapR{ - IDBasicConfig: o, - } - } else { - related.R.IDBasicConfig = o - } - return nil -} - -// SetIDPermissionG of the basicConfig to the related item. -// Sets o.R.IDPermission to related. -// Adds o to related.R.IDBasicConfig. -// Uses the global database handle. -func (o *BasicConfig) SetIDPermissionG(ctx context.Context, insert bool, related *Permission) error { - return o.SetIDPermission(ctx, boil.GetContextDB(), insert, related) -} - -// SetIDPermission of the basicConfig to the related item. -// Sets o.R.IDPermission to related. -// Adds o to related.R.IDBasicConfig. -func (o *BasicConfig) SetIDPermission(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Permission) error { - var err error - - if insert { - related.ID = o.ID - - if err = related.Insert(ctx, exec, boil.Infer()); err != nil { - return errors.Wrap(err, "failed to insert into foreign table") - } - } else { - updateQuery := fmt.Sprintf( - "UPDATE \"saml_sp\".\"permissions\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), - strmangle.WhereClause("\"", "\"", 2, permissionPrimaryKeyColumns), - ) - values := []interface{}{o.ID, related.ID} - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, updateQuery) - fmt.Fprintln(writer, values) - } - if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { - return errors.Wrap(err, "failed to update foreign table") - } - - related.ID = o.ID - } - - if o.R == nil { - o.R = &basicConfigR{ - IDPermission: related, - } - } else { - o.R.IDPermission = related - } - - if related.R == nil { - related.R = &permissionR{ - IDBasicConfig: o, - } - } else { - related.R.IDBasicConfig = o - } - return nil -} - -// BasicConfigs retrieves all the records using an executor. -func BasicConfigs(mods ...qm.QueryMod) basicConfigQuery { - mods = append(mods, qm.From("\"saml_sp\".\"basic_config\"")) - q := NewQuery(mods...) - if len(queries.GetSelect(q)) == 0 { - queries.SetSelect(q, []string{"\"saml_sp\".\"basic_config\".*"}) - } - - return basicConfigQuery{q} -} - -// FindBasicConfigG retrieves a single record by ID. -func FindBasicConfigG(ctx context.Context, iD int32, selectCols ...string) (*BasicConfig, error) { - return FindBasicConfig(ctx, boil.GetContextDB(), iD, selectCols...) -} - -// FindBasicConfig retrieves a single record by ID with an executor. -// If selectCols is empty Find will return all columns. -func FindBasicConfig(ctx context.Context, exec boil.ContextExecutor, iD int32, selectCols ...string) (*BasicConfig, error) { - basicConfigObj := &BasicConfig{} - - sel := "*" - if len(selectCols) > 0 { - sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") - } - query := fmt.Sprintf( - "select %s from \"saml_sp\".\"basic_config\" where \"id\"=$1", sel, - ) - - q := queries.Raw(query, iD) - - err := q.Bind(ctx, exec, basicConfigObj) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, sql.ErrNoRows - } - return nil, errors.Wrap(err, "appdb: unable to select from basic_config") - } - - if err = basicConfigObj.doAfterSelectHooks(ctx, exec); err != nil { - return basicConfigObj, err - } - - return basicConfigObj, nil -} - -// InsertG a single record. See Insert for whitelist behavior description. -func (o *BasicConfig) InsertG(ctx context.Context, columns boil.Columns) error { - return o.Insert(ctx, boil.GetContextDB(), columns) -} - -// Insert a single record using an executor. -// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. -func (o *BasicConfig) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { - if o == nil { - return errors.New("appdb: no basic_config provided for insertion") - } - - var err error - - if err := o.doBeforeInsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(basicConfigColumnsWithDefault, o) - - key := makeCacheKey(columns, nzDefaults) - basicConfigInsertCacheMut.RLock() - cache, cached := basicConfigInsertCache[key] - basicConfigInsertCacheMut.RUnlock() - - if !cached { - wl, returnColumns := columns.InsertColumnSet( - basicConfigAllColumns, - basicConfigColumnsWithDefault, - basicConfigColumnsWithoutDefault, - nzDefaults, - ) - - cache.valueMapping, err = queries.BindMapping(basicConfigType, basicConfigMapping, wl) - if err != nil { - return err - } - cache.retMapping, err = queries.BindMapping(basicConfigType, basicConfigMapping, returnColumns) - if err != nil { - return err - } - if len(wl) != 0 { - cache.query = fmt.Sprintf("INSERT INTO \"saml_sp\".\"basic_config\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) - } else { - cache.query = "INSERT INTO \"saml_sp\".\"basic_config\" %sDEFAULT VALUES%s" - } - - var queryOutput, queryReturning string - - if len(cache.retMapping) != 0 { - queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) - } - - cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - - if err != nil { - return errors.Wrap(err, "appdb: unable to insert into basic_config") - } - - if !cached { - basicConfigInsertCacheMut.Lock() - basicConfigInsertCache[key] = cache - basicConfigInsertCacheMut.Unlock() - } - - return o.doAfterInsertHooks(ctx, exec) -} - -// UpdateG a single BasicConfig record using the global executor. -// See Update for more documentation. -func (o *BasicConfig) UpdateG(ctx context.Context, columns boil.Columns) (int64, error) { - return o.Update(ctx, boil.GetContextDB(), columns) -} - -// Update uses an executor to update the BasicConfig. -// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. -// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. -func (o *BasicConfig) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { - var err error - if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { - return 0, err - } - key := makeCacheKey(columns, nil) - basicConfigUpdateCacheMut.RLock() - cache, cached := basicConfigUpdateCache[key] - basicConfigUpdateCacheMut.RUnlock() - - if !cached { - wl := columns.UpdateColumnSet( - basicConfigAllColumns, - basicConfigPrimaryKeyColumns, - ) - - if !columns.IsWhitelist() { - wl = strmangle.SetComplement(wl, []string{"created_at"}) - } - if len(wl) == 0 { - return 0, errors.New("appdb: unable to update basic_config, could not build whitelist") - } - - cache.query = fmt.Sprintf("UPDATE \"saml_sp\".\"basic_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, wl), - strmangle.WhereClause("\"", "\"", len(wl)+1, basicConfigPrimaryKeyColumns), - ) - cache.valueMapping, err = queries.BindMapping(basicConfigType, basicConfigMapping, append(wl, basicConfigPrimaryKeyColumns...)) - if err != nil { - return 0, err - } - } - - values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, values) - } - var result sql.Result - result, err = exec.ExecContext(ctx, cache.query, values...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update basic_config row") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by update for basic_config") - } - - if !cached { - basicConfigUpdateCacheMut.Lock() - basicConfigUpdateCache[key] = cache - basicConfigUpdateCacheMut.Unlock() - } - - return rowsAff, o.doAfterUpdateHooks(ctx, exec) -} - -// UpdateAllG updates all rows with the specified column values. -func (q basicConfigQuery) UpdateAllG(ctx context.Context, cols M) (int64, error) { - return q.UpdateAll(ctx, boil.GetContextDB(), cols) -} - -// UpdateAll updates all rows with the specified column values. -func (q basicConfigQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - queries.SetUpdate(q.Query, cols) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update all for basic_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected for basic_config") - } - - return rowsAff, nil -} - -// UpdateAllG updates all rows with the specified column values. -func (o BasicConfigSlice) UpdateAllG(ctx context.Context, cols M) (int64, error) { - return o.UpdateAll(ctx, boil.GetContextDB(), cols) -} - -// UpdateAll updates all rows with the specified column values, using an executor. -func (o BasicConfigSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { - ln := int64(len(o)) - if ln == 0 { - return 0, nil - } - - if len(cols) == 0 { - return 0, errors.New("appdb: update all requires at least one column argument") - } - - colNames := make([]string, len(cols)) - args := make([]interface{}, len(cols)) - - i := 0 - for name, value := range cols { - colNames[i] = name - args[i] = value - i++ - } - - // Append all of the primary key values for each column - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), basicConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := fmt.Sprintf("UPDATE \"saml_sp\".\"basic_config\" SET %s WHERE %s", - strmangle.SetParamNames("\"", "\"", 1, colNames), - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, basicConfigPrimaryKeyColumns, len(o))) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to update all in basicConfig slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected all in update all basicConfig") - } - return rowsAff, nil -} - -// UpsertG attempts an insert, and does an update or ignore on conflict. -func (o *BasicConfig) UpsertG(ctx context.Context, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { - return o.Upsert(ctx, boil.GetContextDB(), updateOnConflict, conflictColumns, updateColumns, insertColumns, opts...) -} - -// Upsert attempts an insert using an executor, and does an update or ignore on conflict. -// See boil.Columns documentation for how to properly use updateColumns and insertColumns. -func (o *BasicConfig) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { - if o == nil { - return errors.New("appdb: no basic_config provided for upsert") - } - - if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { - return err - } - - nzDefaults := queries.NonZeroDefaultSet(basicConfigColumnsWithDefault, o) - - // Build cache key in-line uglily - mysql vs psql problems - buf := strmangle.GetBuffer() - if updateOnConflict { - buf.WriteByte('t') - } else { - buf.WriteByte('f') - } - buf.WriteByte('.') - for _, c := range conflictColumns { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(updateColumns.Kind)) - for _, c := range updateColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - buf.WriteString(strconv.Itoa(insertColumns.Kind)) - for _, c := range insertColumns.Cols { - buf.WriteString(c) - } - buf.WriteByte('.') - for _, c := range nzDefaults { - buf.WriteString(c) - } - key := buf.String() - strmangle.PutBuffer(buf) - - basicConfigUpsertCacheMut.RLock() - cache, cached := basicConfigUpsertCache[key] - basicConfigUpsertCacheMut.RUnlock() - - var err error - - if !cached { - insert, _ := insertColumns.InsertColumnSet( - basicConfigAllColumns, - basicConfigColumnsWithDefault, - basicConfigColumnsWithoutDefault, - nzDefaults, - ) - - update := updateColumns.UpdateColumnSet( - basicConfigAllColumns, - basicConfigPrimaryKeyColumns, - ) - - if updateOnConflict && len(update) == 0 { - return errors.New("appdb: unable to upsert basic_config, could not build update column list") - } - - ret := strmangle.SetComplement(basicConfigAllColumns, strmangle.SetIntersect(insert, update)) - - conflict := conflictColumns - if len(conflict) == 0 && updateOnConflict && len(update) != 0 { - if len(basicConfigPrimaryKeyColumns) == 0 { - return errors.New("appdb: unable to upsert basic_config, could not build conflict column list") - } - - conflict = make([]string, len(basicConfigPrimaryKeyColumns)) - copy(conflict, basicConfigPrimaryKeyColumns) - } - cache.query = buildUpsertQueryPostgres(dialect, "\"saml_sp\".\"basic_config\"", updateOnConflict, ret, update, conflict, insert, opts...) - - cache.valueMapping, err = queries.BindMapping(basicConfigType, basicConfigMapping, insert) - if err != nil { - return err - } - if len(ret) != 0 { - cache.retMapping, err = queries.BindMapping(basicConfigType, basicConfigMapping, ret) - if err != nil { - return err - } - } - } - - value := reflect.Indirect(reflect.ValueOf(o)) - vals := queries.ValuesFromMapping(value, cache.valueMapping) - var returns []interface{} - if len(cache.retMapping) != 0 { - returns = queries.PtrsFromMapping(value, cache.retMapping) - } - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, cache.query) - fmt.Fprintln(writer, vals) - } - if len(cache.retMapping) != 0 { - err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) - if errors.Is(err, sql.ErrNoRows) { - err = nil // Postgres doesn't return anything when there's no update - } - } else { - _, err = exec.ExecContext(ctx, cache.query, vals...) - } - if err != nil { - return errors.Wrap(err, "appdb: unable to upsert basic_config") - } - - if !cached { - basicConfigUpsertCacheMut.Lock() - basicConfigUpsertCache[key] = cache - basicConfigUpsertCacheMut.Unlock() - } - - return o.doAfterUpsertHooks(ctx, exec) -} - -// DeleteG deletes a single BasicConfig record. -// DeleteG will match against the primary key column to find the record to delete. -func (o *BasicConfig) DeleteG(ctx context.Context) (int64, error) { - return o.Delete(ctx, boil.GetContextDB()) -} - -// Delete deletes a single BasicConfig record with an executor. -// Delete will match against the primary key column to find the record to delete. -func (o *BasicConfig) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if o == nil { - return 0, errors.New("appdb: no BasicConfig provided for delete") - } - - if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), basicConfigPrimaryKeyMapping) - sql := "DELETE FROM \"saml_sp\".\"basic_config\" WHERE \"id\"=$1" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args...) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete from basic_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by delete for basic_config") - } - - if err := o.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - - return rowsAff, nil -} - -func (q basicConfigQuery) DeleteAllG(ctx context.Context) (int64, error) { - return q.DeleteAll(ctx, boil.GetContextDB()) -} - -// DeleteAll deletes all matching rows. -func (q basicConfigQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if q.Query == nil { - return 0, errors.New("appdb: no basicConfigQuery provided for delete all") - } - - queries.SetDelete(q.Query) - - result, err := q.Query.ExecContext(ctx, exec) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete all from basic_config") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for basic_config") - } - - return rowsAff, nil -} - -// DeleteAllG deletes all rows in the slice. -func (o BasicConfigSlice) DeleteAllG(ctx context.Context) (int64, error) { - return o.DeleteAll(ctx, boil.GetContextDB()) -} - -// DeleteAll deletes all rows in the slice, using an executor. -func (o BasicConfigSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { - if len(o) == 0 { - return 0, nil - } - - if len(basicConfigBeforeDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - var args []interface{} - for _, obj := range o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), basicConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "DELETE FROM \"saml_sp\".\"basic_config\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, basicConfigPrimaryKeyColumns, len(o)) - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, args) - } - result, err := exec.ExecContext(ctx, sql, args...) - if err != nil { - return 0, errors.Wrap(err, "appdb: unable to delete all from basicConfig slice") - } - - rowsAff, err := result.RowsAffected() - if err != nil { - return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for basic_config") - } - - if len(basicConfigAfterDeleteHooks) != 0 { - for _, obj := range o { - if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { - return 0, err - } - } - } - - return rowsAff, nil -} - -// ReloadG refetches the object from the database using the primary keys. -func (o *BasicConfig) ReloadG(ctx context.Context) error { - if o == nil { - return errors.New("appdb: no BasicConfig provided for reload") - } - - return o.Reload(ctx, boil.GetContextDB()) -} - -// Reload refetches the object from the database -// using the primary keys with an executor. -func (o *BasicConfig) Reload(ctx context.Context, exec boil.ContextExecutor) error { - ret, err := FindBasicConfig(ctx, exec, o.ID) - if err != nil { - return err - } - - *o = *ret - return nil -} - -// ReloadAllG refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *BasicConfigSlice) ReloadAllG(ctx context.Context) error { - if o == nil { - return errors.New("appdb: empty BasicConfigSlice provided for reload all") - } - - return o.ReloadAll(ctx, boil.GetContextDB()) -} - -// ReloadAll refetches every row with matching primary key column values -// and overwrites the original object slice with the newly updated slice. -func (o *BasicConfigSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { - if o == nil || len(*o) == 0 { - return nil - } - - slice := BasicConfigSlice{} - var args []interface{} - for _, obj := range *o { - pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), basicConfigPrimaryKeyMapping) - args = append(args, pkeyArgs...) - } - - sql := "SELECT \"saml_sp\".\"basic_config\".* FROM \"saml_sp\".\"basic_config\" WHERE " + - strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, basicConfigPrimaryKeyColumns, len(*o)) - - q := queries.Raw(sql, args...) - - err := q.Bind(ctx, exec, &slice) - if err != nil { - return errors.Wrap(err, "appdb: unable to reload all in BasicConfigSlice") - } - - *o = slice - - return nil -} - -// BasicConfigExistsG checks if the BasicConfig row exists. -func BasicConfigExistsG(ctx context.Context, iD int32) (bool, error) { - return BasicConfigExists(ctx, boil.GetContextDB(), iD) -} - -// BasicConfigExists checks if the BasicConfig row exists. -func BasicConfigExists(ctx context.Context, exec boil.ContextExecutor, iD int32) (bool, error) { - var exists bool - sql := "select exists(select 1 from \"saml_sp\".\"basic_config\" where \"id\"=$1 limit 1)" - - if boil.IsDebug(ctx) { - writer := boil.DebugWriterFrom(ctx) - fmt.Fprintln(writer, sql) - fmt.Fprintln(writer, iD) - } - row := exec.QueryRowContext(ctx, sql, iD) - - err := row.Scan(&exists) - if err != nil { - return false, errors.Wrap(err, "appdb: unable to check if basic_config exists") - } - - return exists, nil -} - -// Exists checks if the BasicConfig row exists. -func (o *BasicConfig) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { - return BasicConfigExists(ctx, exec, o.ID) -} diff --git a/appdb/boil_table_names.go b/appdb/boil_table_names.go index ebc69e3..4348fdf 100644 --- a/appdb/boil_table_names.go +++ b/appdb/boil_table_names.go @@ -4,13 +4,11 @@ package appdb var TableNames = struct { - AdvancedConfig string - AttributeMap string - BasicConfig string - Permissions string + AttributeMap string + Config string + Permissions string }{ - AdvancedConfig: "advanced_config", - AttributeMap: "attribute_map", - BasicConfig: "basic_config", - Permissions: "permissions", + AttributeMap: "attribute_map", + Config: "config", + Permissions: "permissions", } diff --git a/appdb/config.go b/appdb/config.go new file mode 100644 index 0000000..43fc41c --- /dev/null +++ b/appdb/config.go @@ -0,0 +1,1505 @@ +// Code generated by SQLBoiler 4.16.1 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT. +// This file is meant to be re-generated in place and/or deleted at any time. + +package appdb + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "strconv" + "strings" + "sync" + "time" + + "github.com/friendsofgo/errors" + "github.com/volatiletech/null/v8" + "github.com/volatiletech/sqlboiler/v4/boil" + "github.com/volatiletech/sqlboiler/v4/queries" + "github.com/volatiletech/sqlboiler/v4/queries/qm" + "github.com/volatiletech/sqlboiler/v4/queries/qmhelper" + "github.com/volatiletech/strmangle" +) + +// Config is an object representing the database table. +type Config struct { + ID int32 `boil:"id" json:"id" toml:"id" yaml:"id"` + Enable bool `boil:"enable" json:"enable" toml:"enable" yaml:"enable"` + SPCertificate string `boil:"sp_certificate" json:"sp_certificate" toml:"sp_certificate" yaml:"sp_certificate"` + SPPrivateKey string `boil:"sp_private_key" json:"sp_private_key" toml:"sp_private_key" yaml:"sp_private_key"` + IdpMetadataURL null.String `boil:"idp_metadata_url" json:"idp_metadata_url,omitempty" toml:"idp_metadata_url" yaml:"idp_metadata_url,omitempty"` + MetadataXML null.String `boil:"metadata_xml" json:"metadata_xml,omitempty" toml:"metadata_xml" yaml:"metadata_xml,omitempty"` + OwnURL string `boil:"own_url" json:"own_url" toml:"own_url" yaml:"own_url"` + UserToArchive bool `boil:"user_to_archive" json:"user_to_archive" toml:"user_to_archive" yaml:"user_to_archive"` + AllowInitializationByIdp bool `boil:"allow_initialization_by_idp" json:"allow_initialization_by_idp" toml:"allow_initialization_by_idp" yaml:"allow_initialization_by_idp"` + SignedRequest bool `boil:"signed_request" json:"signed_request" toml:"signed_request" yaml:"signed_request"` + ForceAuthn bool `boil:"force_authn" json:"force_authn" toml:"force_authn" yaml:"force_authn"` + EntityID string `boil:"entity_id" json:"entity_id" toml:"entity_id" yaml:"entity_id"` + CookieSecure bool `boil:"cookie_secure" json:"cookie_secure" toml:"cookie_secure" yaml:"cookie_secure"` + LoginFailedURL string `boil:"login_failed_url" json:"login_failed_url" toml:"login_failed_url" yaml:"login_failed_url"` + + R *configR `boil:"-" json:"-" toml:"-" yaml:"-"` + L configL `boil:"-" json:"-" toml:"-" yaml:"-"` +} + +var ConfigColumns = struct { + ID string + Enable string + SPCertificate string + SPPrivateKey string + IdpMetadataURL string + MetadataXML string + OwnURL string + UserToArchive string + AllowInitializationByIdp string + SignedRequest string + ForceAuthn string + EntityID string + CookieSecure string + LoginFailedURL string +}{ + ID: "id", + Enable: "enable", + SPCertificate: "sp_certificate", + SPPrivateKey: "sp_private_key", + IdpMetadataURL: "idp_metadata_url", + MetadataXML: "metadata_xml", + OwnURL: "own_url", + UserToArchive: "user_to_archive", + AllowInitializationByIdp: "allow_initialization_by_idp", + SignedRequest: "signed_request", + ForceAuthn: "force_authn", + EntityID: "entity_id", + CookieSecure: "cookie_secure", + LoginFailedURL: "login_failed_url", +} + +var ConfigTableColumns = struct { + ID string + Enable string + SPCertificate string + SPPrivateKey string + IdpMetadataURL string + MetadataXML string + OwnURL string + UserToArchive string + AllowInitializationByIdp string + SignedRequest string + ForceAuthn string + EntityID string + CookieSecure string + LoginFailedURL string +}{ + ID: "config.id", + Enable: "config.enable", + SPCertificate: "config.sp_certificate", + SPPrivateKey: "config.sp_private_key", + IdpMetadataURL: "config.idp_metadata_url", + MetadataXML: "config.metadata_xml", + OwnURL: "config.own_url", + UserToArchive: "config.user_to_archive", + AllowInitializationByIdp: "config.allow_initialization_by_idp", + SignedRequest: "config.signed_request", + ForceAuthn: "config.force_authn", + EntityID: "config.entity_id", + CookieSecure: "config.cookie_secure", + LoginFailedURL: "config.login_failed_url", +} + +// Generated where + +type whereHelperbool struct{ field string } + +func (w whereHelperbool) EQ(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) } +func (w whereHelperbool) NEQ(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) } +func (w whereHelperbool) LT(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) } +func (w whereHelperbool) LTE(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) } +func (w whereHelperbool) GT(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) } +func (w whereHelperbool) GTE(x bool) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) } + +var ConfigWhere = struct { + ID whereHelperint32 + Enable whereHelperbool + SPCertificate whereHelperstring + SPPrivateKey whereHelperstring + IdpMetadataURL whereHelpernull_String + MetadataXML whereHelpernull_String + OwnURL whereHelperstring + UserToArchive whereHelperbool + AllowInitializationByIdp whereHelperbool + SignedRequest whereHelperbool + ForceAuthn whereHelperbool + EntityID whereHelperstring + CookieSecure whereHelperbool + LoginFailedURL whereHelperstring +}{ + ID: whereHelperint32{field: "\"saml_sp\".\"config\".\"id\""}, + Enable: whereHelperbool{field: "\"saml_sp\".\"config\".\"enable\""}, + SPCertificate: whereHelperstring{field: "\"saml_sp\".\"config\".\"sp_certificate\""}, + SPPrivateKey: whereHelperstring{field: "\"saml_sp\".\"config\".\"sp_private_key\""}, + IdpMetadataURL: whereHelpernull_String{field: "\"saml_sp\".\"config\".\"idp_metadata_url\""}, + MetadataXML: whereHelpernull_String{field: "\"saml_sp\".\"config\".\"metadata_xml\""}, + OwnURL: whereHelperstring{field: "\"saml_sp\".\"config\".\"own_url\""}, + UserToArchive: whereHelperbool{field: "\"saml_sp\".\"config\".\"user_to_archive\""}, + AllowInitializationByIdp: whereHelperbool{field: "\"saml_sp\".\"config\".\"allow_initialization_by_idp\""}, + SignedRequest: whereHelperbool{field: "\"saml_sp\".\"config\".\"signed_request\""}, + ForceAuthn: whereHelperbool{field: "\"saml_sp\".\"config\".\"force_authn\""}, + EntityID: whereHelperstring{field: "\"saml_sp\".\"config\".\"entity_id\""}, + CookieSecure: whereHelperbool{field: "\"saml_sp\".\"config\".\"cookie_secure\""}, + LoginFailedURL: whereHelperstring{field: "\"saml_sp\".\"config\".\"login_failed_url\""}, +} + +// ConfigRels is where relationship names are stored. +var ConfigRels = struct { + IDAttributeMap string + IDPermission string +}{ + IDAttributeMap: "IDAttributeMap", + IDPermission: "IDPermission", +} + +// configR is where relationships are stored. +type configR struct { + IDAttributeMap *AttributeMap `boil:"IDAttributeMap" json:"IDAttributeMap" toml:"IDAttributeMap" yaml:"IDAttributeMap"` + IDPermission *Permission `boil:"IDPermission" json:"IDPermission" toml:"IDPermission" yaml:"IDPermission"` +} + +// NewStruct creates a new relationship struct +func (*configR) NewStruct() *configR { + return &configR{} +} + +func (r *configR) GetIDAttributeMap() *AttributeMap { + if r == nil { + return nil + } + return r.IDAttributeMap +} + +func (r *configR) GetIDPermission() *Permission { + if r == nil { + return nil + } + return r.IDPermission +} + +// configL is where Load methods for each relationship are stored. +type configL struct{} + +var ( + configAllColumns = []string{"id", "enable", "sp_certificate", "sp_private_key", "idp_metadata_url", "metadata_xml", "own_url", "user_to_archive", "allow_initialization_by_idp", "signed_request", "force_authn", "entity_id", "cookie_secure", "login_failed_url"} + configColumnsWithoutDefault = []string{"sp_certificate", "sp_private_key", "own_url"} + configColumnsWithDefault = []string{"id", "enable", "idp_metadata_url", "metadata_xml", "user_to_archive", "allow_initialization_by_idp", "signed_request", "force_authn", "entity_id", "cookie_secure", "login_failed_url"} + configPrimaryKeyColumns = []string{"id"} + configGeneratedColumns = []string{} +) + +type ( + // ConfigSlice is an alias for a slice of pointers to Config. + // This should almost always be used instead of []Config. + ConfigSlice []*Config + // ConfigHook is the signature for custom Config hook methods + ConfigHook func(context.Context, boil.ContextExecutor, *Config) error + + configQuery struct { + *queries.Query + } +) + +// Cache for insert, update and upsert +var ( + configType = reflect.TypeOf(&Config{}) + configMapping = queries.MakeStructMapping(configType) + configPrimaryKeyMapping, _ = queries.BindMapping(configType, configMapping, configPrimaryKeyColumns) + configInsertCacheMut sync.RWMutex + configInsertCache = make(map[string]insertCache) + configUpdateCacheMut sync.RWMutex + configUpdateCache = make(map[string]updateCache) + configUpsertCacheMut sync.RWMutex + configUpsertCache = make(map[string]insertCache) +) + +var ( + // Force time package dependency for automated UpdatedAt/CreatedAt. + _ = time.Second + // Force qmhelper dependency for where clause generation (which doesn't + // always happen) + _ = qmhelper.Where +) + +var configAfterSelectMu sync.Mutex +var configAfterSelectHooks []ConfigHook + +var configBeforeInsertMu sync.Mutex +var configBeforeInsertHooks []ConfigHook +var configAfterInsertMu sync.Mutex +var configAfterInsertHooks []ConfigHook + +var configBeforeUpdateMu sync.Mutex +var configBeforeUpdateHooks []ConfigHook +var configAfterUpdateMu sync.Mutex +var configAfterUpdateHooks []ConfigHook + +var configBeforeDeleteMu sync.Mutex +var configBeforeDeleteHooks []ConfigHook +var configAfterDeleteMu sync.Mutex +var configAfterDeleteHooks []ConfigHook + +var configBeforeUpsertMu sync.Mutex +var configBeforeUpsertHooks []ConfigHook +var configAfterUpsertMu sync.Mutex +var configAfterUpsertHooks []ConfigHook + +// doAfterSelectHooks executes all "after Select" hooks. +func (o *Config) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configAfterSelectHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeInsertHooks executes all "before insert" hooks. +func (o *Config) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configBeforeInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterInsertHooks executes all "after Insert" hooks. +func (o *Config) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configAfterInsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpdateHooks executes all "before Update" hooks. +func (o *Config) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configBeforeUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpdateHooks executes all "after Update" hooks. +func (o *Config) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configAfterUpdateHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeDeleteHooks executes all "before Delete" hooks. +func (o *Config) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configBeforeDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterDeleteHooks executes all "after Delete" hooks. +func (o *Config) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configAfterDeleteHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doBeforeUpsertHooks executes all "before Upsert" hooks. +func (o *Config) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configBeforeUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// doAfterUpsertHooks executes all "after Upsert" hooks. +func (o *Config) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) { + if boil.HooksAreSkipped(ctx) { + return nil + } + + for _, hook := range configAfterUpsertHooks { + if err := hook(ctx, exec, o); err != nil { + return err + } + } + + return nil +} + +// AddConfigHook registers your hook function for all future operations. +func AddConfigHook(hookPoint boil.HookPoint, configHook ConfigHook) { + switch hookPoint { + case boil.AfterSelectHook: + configAfterSelectMu.Lock() + configAfterSelectHooks = append(configAfterSelectHooks, configHook) + configAfterSelectMu.Unlock() + case boil.BeforeInsertHook: + configBeforeInsertMu.Lock() + configBeforeInsertHooks = append(configBeforeInsertHooks, configHook) + configBeforeInsertMu.Unlock() + case boil.AfterInsertHook: + configAfterInsertMu.Lock() + configAfterInsertHooks = append(configAfterInsertHooks, configHook) + configAfterInsertMu.Unlock() + case boil.BeforeUpdateHook: + configBeforeUpdateMu.Lock() + configBeforeUpdateHooks = append(configBeforeUpdateHooks, configHook) + configBeforeUpdateMu.Unlock() + case boil.AfterUpdateHook: + configAfterUpdateMu.Lock() + configAfterUpdateHooks = append(configAfterUpdateHooks, configHook) + configAfterUpdateMu.Unlock() + case boil.BeforeDeleteHook: + configBeforeDeleteMu.Lock() + configBeforeDeleteHooks = append(configBeforeDeleteHooks, configHook) + configBeforeDeleteMu.Unlock() + case boil.AfterDeleteHook: + configAfterDeleteMu.Lock() + configAfterDeleteHooks = append(configAfterDeleteHooks, configHook) + configAfterDeleteMu.Unlock() + case boil.BeforeUpsertHook: + configBeforeUpsertMu.Lock() + configBeforeUpsertHooks = append(configBeforeUpsertHooks, configHook) + configBeforeUpsertMu.Unlock() + case boil.AfterUpsertHook: + configAfterUpsertMu.Lock() + configAfterUpsertHooks = append(configAfterUpsertHooks, configHook) + configAfterUpsertMu.Unlock() + } +} + +// OneG returns a single config record from the query using the global executor. +func (q configQuery) OneG(ctx context.Context) (*Config, error) { + return q.One(ctx, boil.GetContextDB()) +} + +// One returns a single config record from the query. +func (q configQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Config, error) { + o := &Config{} + + queries.SetLimit(q.Query, 1) + + err := q.Bind(ctx, exec, o) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "appdb: failed to execute a one query for config") + } + + if err := o.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + + return o, nil +} + +// AllG returns all Config records from the query using the global executor. +func (q configQuery) AllG(ctx context.Context) (ConfigSlice, error) { + return q.All(ctx, boil.GetContextDB()) +} + +// All returns all Config records from the query. +func (q configQuery) All(ctx context.Context, exec boil.ContextExecutor) (ConfigSlice, error) { + var o []*Config + + err := q.Bind(ctx, exec, &o) + if err != nil { + return nil, errors.Wrap(err, "appdb: failed to assign all query results to Config slice") + } + + if len(configAfterSelectHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterSelectHooks(ctx, exec); err != nil { + return o, err + } + } + } + + return o, nil +} + +// CountG returns the count of all Config records in the query using the global executor +func (q configQuery) CountG(ctx context.Context) (int64, error) { + return q.Count(ctx, boil.GetContextDB()) +} + +// Count returns the count of all Config records in the query. +func (q configQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return 0, errors.Wrap(err, "appdb: failed to count config rows") + } + + return count, nil +} + +// ExistsG checks if the row exists in the table using the global executor. +func (q configQuery) ExistsG(ctx context.Context) (bool, error) { + return q.Exists(ctx, boil.GetContextDB()) +} + +// Exists checks if the row exists in the table. +func (q configQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + var count int64 + + queries.SetSelect(q.Query, nil) + queries.SetCount(q.Query) + queries.SetLimit(q.Query, 1) + + err := q.Query.QueryRowContext(ctx, exec).Scan(&count) + if err != nil { + return false, errors.Wrap(err, "appdb: failed to check if config exists") + } + + return count > 0, nil +} + +// IDAttributeMap pointed to by the foreign key. +func (o *Config) IDAttributeMap(mods ...qm.QueryMod) attributeMapQuery { + queryMods := []qm.QueryMod{ + qm.Where("\"id\" = ?", o.ID), + } + + queryMods = append(queryMods, mods...) + + return AttributeMaps(queryMods...) +} + +// IDPermission pointed to by the foreign key. +func (o *Config) IDPermission(mods ...qm.QueryMod) permissionQuery { + queryMods := []qm.QueryMod{ + qm.Where("\"id\" = ?", o.ID), + } + + queryMods = append(queryMods, mods...) + + return Permissions(queryMods...) +} + +// LoadIDAttributeMap allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for a 1-1 relationship. +func (configL) LoadIDAttributeMap(ctx context.Context, e boil.ContextExecutor, singular bool, maybeConfig interface{}, mods queries.Applicator) error { + var slice []*Config + var object *Config + + if singular { + var ok bool + object, ok = maybeConfig.(*Config) + if !ok { + object = new(Config) + ok = queries.SetFromEmbeddedStruct(&object, &maybeConfig) + if !ok { + return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeConfig)) + } + } + } else { + s, ok := maybeConfig.(*[]*Config) + if ok { + slice = *s + } else { + ok = queries.SetFromEmbeddedStruct(&slice, maybeConfig) + if !ok { + return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeConfig)) + } + } + } + + args := make(map[interface{}]struct{}) + if singular { + if object.R == nil { + object.R = &configR{} + } + args[object.ID] = struct{}{} + } else { + for _, obj := range slice { + if obj.R == nil { + obj.R = &configR{} + } + + args[obj.ID] = struct{}{} + } + } + + if len(args) == 0 { + return nil + } + + argsSlice := make([]interface{}, len(args)) + i := 0 + for arg := range args { + argsSlice[i] = arg + i++ + } + + query := NewQuery( + qm.From(`saml_sp.attribute_map`), + qm.WhereIn(`saml_sp.attribute_map.id in ?`, argsSlice...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load AttributeMap") + } + + var resultSlice []*AttributeMap + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice AttributeMap") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results of eager load for attribute_map") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for attribute_map") + } + + if len(attributeMapAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + + if len(resultSlice) == 0 { + return nil + } + + if singular { + foreign := resultSlice[0] + object.R.IDAttributeMap = foreign + if foreign.R == nil { + foreign.R = &attributeMapR{} + } + foreign.R.IDConfig = object + } + + for _, local := range slice { + for _, foreign := range resultSlice { + if local.ID == foreign.ID { + local.R.IDAttributeMap = foreign + if foreign.R == nil { + foreign.R = &attributeMapR{} + } + foreign.R.IDConfig = local + break + } + } + } + + return nil +} + +// LoadIDPermission allows an eager lookup of values, cached into the +// loaded structs of the objects. This is for a 1-1 relationship. +func (configL) LoadIDPermission(ctx context.Context, e boil.ContextExecutor, singular bool, maybeConfig interface{}, mods queries.Applicator) error { + var slice []*Config + var object *Config + + if singular { + var ok bool + object, ok = maybeConfig.(*Config) + if !ok { + object = new(Config) + ok = queries.SetFromEmbeddedStruct(&object, &maybeConfig) + if !ok { + return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", object, maybeConfig)) + } + } + } else { + s, ok := maybeConfig.(*[]*Config) + if ok { + slice = *s + } else { + ok = queries.SetFromEmbeddedStruct(&slice, maybeConfig) + if !ok { + return errors.New(fmt.Sprintf("failed to set %T from embedded struct %T", slice, maybeConfig)) + } + } + } + + args := make(map[interface{}]struct{}) + if singular { + if object.R == nil { + object.R = &configR{} + } + args[object.ID] = struct{}{} + } else { + for _, obj := range slice { + if obj.R == nil { + obj.R = &configR{} + } + + args[obj.ID] = struct{}{} + } + } + + if len(args) == 0 { + return nil + } + + argsSlice := make([]interface{}, len(args)) + i := 0 + for arg := range args { + argsSlice[i] = arg + i++ + } + + query := NewQuery( + qm.From(`saml_sp.permissions`), + qm.WhereIn(`saml_sp.permissions.id in ?`, argsSlice...), + ) + if mods != nil { + mods.Apply(query) + } + + results, err := query.QueryContext(ctx, e) + if err != nil { + return errors.Wrap(err, "failed to eager load Permission") + } + + var resultSlice []*Permission + if err = queries.Bind(results, &resultSlice); err != nil { + return errors.Wrap(err, "failed to bind eager loaded slice Permission") + } + + if err = results.Close(); err != nil { + return errors.Wrap(err, "failed to close results of eager load for permissions") + } + if err = results.Err(); err != nil { + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for permissions") + } + + if len(permissionAfterSelectHooks) != 0 { + for _, obj := range resultSlice { + if err := obj.doAfterSelectHooks(ctx, e); err != nil { + return err + } + } + } + + if len(resultSlice) == 0 { + return nil + } + + if singular { + foreign := resultSlice[0] + object.R.IDPermission = foreign + if foreign.R == nil { + foreign.R = &permissionR{} + } + foreign.R.IDConfig = object + } + + for _, local := range slice { + for _, foreign := range resultSlice { + if local.ID == foreign.ID { + local.R.IDPermission = foreign + if foreign.R == nil { + foreign.R = &permissionR{} + } + foreign.R.IDConfig = local + break + } + } + } + + return nil +} + +// SetIDAttributeMapG of the config to the related item. +// Sets o.R.IDAttributeMap to related. +// Adds o to related.R.IDConfig. +// Uses the global database handle. +func (o *Config) SetIDAttributeMapG(ctx context.Context, insert bool, related *AttributeMap) error { + return o.SetIDAttributeMap(ctx, boil.GetContextDB(), insert, related) +} + +// SetIDAttributeMap of the config to the related item. +// Sets o.R.IDAttributeMap to related. +// Adds o to related.R.IDConfig. +func (o *Config) SetIDAttributeMap(ctx context.Context, exec boil.ContextExecutor, insert bool, related *AttributeMap) error { + var err error + + if insert { + related.ID = o.ID + + if err = related.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } else { + updateQuery := fmt.Sprintf( + "UPDATE \"saml_sp\".\"attribute_map\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), + strmangle.WhereClause("\"", "\"", 2, attributeMapPrimaryKeyColumns), + ) + values := []interface{}{o.ID, related.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update foreign table") + } + + related.ID = o.ID + } + + if o.R == nil { + o.R = &configR{ + IDAttributeMap: related, + } + } else { + o.R.IDAttributeMap = related + } + + if related.R == nil { + related.R = &attributeMapR{ + IDConfig: o, + } + } else { + related.R.IDConfig = o + } + return nil +} + +// SetIDPermissionG of the config to the related item. +// Sets o.R.IDPermission to related. +// Adds o to related.R.IDConfig. +// Uses the global database handle. +func (o *Config) SetIDPermissionG(ctx context.Context, insert bool, related *Permission) error { + return o.SetIDPermission(ctx, boil.GetContextDB(), insert, related) +} + +// SetIDPermission of the config to the related item. +// Sets o.R.IDPermission to related. +// Adds o to related.R.IDConfig. +func (o *Config) SetIDPermission(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Permission) error { + var err error + + if insert { + related.ID = o.ID + + if err = related.Insert(ctx, exec, boil.Infer()); err != nil { + return errors.Wrap(err, "failed to insert into foreign table") + } + } else { + updateQuery := fmt.Sprintf( + "UPDATE \"saml_sp\".\"permissions\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, []string{"id"}), + strmangle.WhereClause("\"", "\"", 2, permissionPrimaryKeyColumns), + ) + values := []interface{}{o.ID, related.ID} + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, updateQuery) + fmt.Fprintln(writer, values) + } + if _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil { + return errors.Wrap(err, "failed to update foreign table") + } + + related.ID = o.ID + } + + if o.R == nil { + o.R = &configR{ + IDPermission: related, + } + } else { + o.R.IDPermission = related + } + + if related.R == nil { + related.R = &permissionR{ + IDConfig: o, + } + } else { + related.R.IDConfig = o + } + return nil +} + +// Configs retrieves all the records using an executor. +func Configs(mods ...qm.QueryMod) configQuery { + mods = append(mods, qm.From("\"saml_sp\".\"config\"")) + q := NewQuery(mods...) + if len(queries.GetSelect(q)) == 0 { + queries.SetSelect(q, []string{"\"saml_sp\".\"config\".*"}) + } + + return configQuery{q} +} + +// FindConfigG retrieves a single record by ID. +func FindConfigG(ctx context.Context, iD int32, selectCols ...string) (*Config, error) { + return FindConfig(ctx, boil.GetContextDB(), iD, selectCols...) +} + +// FindConfig retrieves a single record by ID with an executor. +// If selectCols is empty Find will return all columns. +func FindConfig(ctx context.Context, exec boil.ContextExecutor, iD int32, selectCols ...string) (*Config, error) { + configObj := &Config{} + + sel := "*" + if len(selectCols) > 0 { + sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") + } + query := fmt.Sprintf( + "select %s from \"saml_sp\".\"config\" where \"id\"=$1", sel, + ) + + q := queries.Raw(query, iD) + + err := q.Bind(ctx, exec, configObj) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, sql.ErrNoRows + } + return nil, errors.Wrap(err, "appdb: unable to select from config") + } + + if err = configObj.doAfterSelectHooks(ctx, exec); err != nil { + return configObj, err + } + + return configObj, nil +} + +// InsertG a single record. See Insert for whitelist behavior description. +func (o *Config) InsertG(ctx context.Context, columns boil.Columns) error { + return o.Insert(ctx, boil.GetContextDB(), columns) +} + +// Insert a single record using an executor. +// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts. +func (o *Config) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error { + if o == nil { + return errors.New("appdb: no config provided for insertion") + } + + var err error + + if err := o.doBeforeInsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(configColumnsWithDefault, o) + + key := makeCacheKey(columns, nzDefaults) + configInsertCacheMut.RLock() + cache, cached := configInsertCache[key] + configInsertCacheMut.RUnlock() + + if !cached { + wl, returnColumns := columns.InsertColumnSet( + configAllColumns, + configColumnsWithDefault, + configColumnsWithoutDefault, + nzDefaults, + ) + + cache.valueMapping, err = queries.BindMapping(configType, configMapping, wl) + if err != nil { + return err + } + cache.retMapping, err = queries.BindMapping(configType, configMapping, returnColumns) + if err != nil { + return err + } + if len(wl) != 0 { + cache.query = fmt.Sprintf("INSERT INTO \"saml_sp\".\"config\" (\"%s\") %%sVALUES (%s)%%s", strings.Join(wl, "\",\""), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1)) + } else { + cache.query = "INSERT INTO \"saml_sp\".\"config\" %sDEFAULT VALUES%s" + } + + var queryOutput, queryReturning string + + if len(cache.retMapping) != 0 { + queryReturning = fmt.Sprintf(" RETURNING \"%s\"", strings.Join(returnColumns, "\",\"")) + } + + cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning) + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...) + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + + if err != nil { + return errors.Wrap(err, "appdb: unable to insert into config") + } + + if !cached { + configInsertCacheMut.Lock() + configInsertCache[key] = cache + configInsertCacheMut.Unlock() + } + + return o.doAfterInsertHooks(ctx, exec) +} + +// UpdateG a single Config record using the global executor. +// See Update for more documentation. +func (o *Config) UpdateG(ctx context.Context, columns boil.Columns) (int64, error) { + return o.Update(ctx, boil.GetContextDB(), columns) +} + +// Update uses an executor to update the Config. +// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates. +// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records. +func (o *Config) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) { + var err error + if err = o.doBeforeUpdateHooks(ctx, exec); err != nil { + return 0, err + } + key := makeCacheKey(columns, nil) + configUpdateCacheMut.RLock() + cache, cached := configUpdateCache[key] + configUpdateCacheMut.RUnlock() + + if !cached { + wl := columns.UpdateColumnSet( + configAllColumns, + configPrimaryKeyColumns, + ) + + if !columns.IsWhitelist() { + wl = strmangle.SetComplement(wl, []string{"created_at"}) + } + if len(wl) == 0 { + return 0, errors.New("appdb: unable to update config, could not build whitelist") + } + + cache.query = fmt.Sprintf("UPDATE \"saml_sp\".\"config\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, wl), + strmangle.WhereClause("\"", "\"", len(wl)+1, configPrimaryKeyColumns), + ) + cache.valueMapping, err = queries.BindMapping(configType, configMapping, append(wl, configPrimaryKeyColumns...)) + if err != nil { + return 0, err + } + } + + values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, values) + } + var result sql.Result + result, err = exec.ExecContext(ctx, cache.query, values...) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to update config row") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: failed to get rows affected by update for config") + } + + if !cached { + configUpdateCacheMut.Lock() + configUpdateCache[key] = cache + configUpdateCacheMut.Unlock() + } + + return rowsAff, o.doAfterUpdateHooks(ctx, exec) +} + +// UpdateAllG updates all rows with the specified column values. +func (q configQuery) UpdateAllG(ctx context.Context, cols M) (int64, error) { + return q.UpdateAll(ctx, boil.GetContextDB(), cols) +} + +// UpdateAll updates all rows with the specified column values. +func (q configQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + queries.SetUpdate(q.Query, cols) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to update all for config") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected for config") + } + + return rowsAff, nil +} + +// UpdateAllG updates all rows with the specified column values. +func (o ConfigSlice) UpdateAllG(ctx context.Context, cols M) (int64, error) { + return o.UpdateAll(ctx, boil.GetContextDB(), cols) +} + +// UpdateAll updates all rows with the specified column values, using an executor. +func (o ConfigSlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) { + ln := int64(len(o)) + if ln == 0 { + return 0, nil + } + + if len(cols) == 0 { + return 0, errors.New("appdb: update all requires at least one column argument") + } + + colNames := make([]string, len(cols)) + args := make([]interface{}, len(cols)) + + i := 0 + for name, value := range cols { + colNames[i] = name + args[i] = value + i++ + } + + // Append all of the primary key values for each column + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), configPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := fmt.Sprintf("UPDATE \"saml_sp\".\"config\" SET %s WHERE %s", + strmangle.SetParamNames("\"", "\"", 1, colNames), + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), len(colNames)+1, configPrimaryKeyColumns, len(o))) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to update all in config slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to retrieve rows affected all in update all config") + } + return rowsAff, nil +} + +// UpsertG attempts an insert, and does an update or ignore on conflict. +func (o *Config) UpsertG(ctx context.Context, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { + return o.Upsert(ctx, boil.GetContextDB(), updateOnConflict, conflictColumns, updateColumns, insertColumns, opts...) +} + +// Upsert attempts an insert using an executor, and does an update or ignore on conflict. +// See boil.Columns documentation for how to properly use updateColumns and insertColumns. +func (o *Config) Upsert(ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns, insertColumns boil.Columns, opts ...UpsertOptionFunc) error { + if o == nil { + return errors.New("appdb: no config provided for upsert") + } + + if err := o.doBeforeUpsertHooks(ctx, exec); err != nil { + return err + } + + nzDefaults := queries.NonZeroDefaultSet(configColumnsWithDefault, o) + + // Build cache key in-line uglily - mysql vs psql problems + buf := strmangle.GetBuffer() + if updateOnConflict { + buf.WriteByte('t') + } else { + buf.WriteByte('f') + } + buf.WriteByte('.') + for _, c := range conflictColumns { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(updateColumns.Kind)) + for _, c := range updateColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + buf.WriteString(strconv.Itoa(insertColumns.Kind)) + for _, c := range insertColumns.Cols { + buf.WriteString(c) + } + buf.WriteByte('.') + for _, c := range nzDefaults { + buf.WriteString(c) + } + key := buf.String() + strmangle.PutBuffer(buf) + + configUpsertCacheMut.RLock() + cache, cached := configUpsertCache[key] + configUpsertCacheMut.RUnlock() + + var err error + + if !cached { + insert, _ := insertColumns.InsertColumnSet( + configAllColumns, + configColumnsWithDefault, + configColumnsWithoutDefault, + nzDefaults, + ) + + update := updateColumns.UpdateColumnSet( + configAllColumns, + configPrimaryKeyColumns, + ) + + if updateOnConflict && len(update) == 0 { + return errors.New("appdb: unable to upsert config, could not build update column list") + } + + ret := strmangle.SetComplement(configAllColumns, strmangle.SetIntersect(insert, update)) + + conflict := conflictColumns + if len(conflict) == 0 && updateOnConflict && len(update) != 0 { + if len(configPrimaryKeyColumns) == 0 { + return errors.New("appdb: unable to upsert config, could not build conflict column list") + } + + conflict = make([]string, len(configPrimaryKeyColumns)) + copy(conflict, configPrimaryKeyColumns) + } + cache.query = buildUpsertQueryPostgres(dialect, "\"saml_sp\".\"config\"", updateOnConflict, ret, update, conflict, insert, opts...) + + cache.valueMapping, err = queries.BindMapping(configType, configMapping, insert) + if err != nil { + return err + } + if len(ret) != 0 { + cache.retMapping, err = queries.BindMapping(configType, configMapping, ret) + if err != nil { + return err + } + } + } + + value := reflect.Indirect(reflect.ValueOf(o)) + vals := queries.ValuesFromMapping(value, cache.valueMapping) + var returns []interface{} + if len(cache.retMapping) != 0 { + returns = queries.PtrsFromMapping(value, cache.retMapping) + } + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, cache.query) + fmt.Fprintln(writer, vals) + } + if len(cache.retMapping) != 0 { + err = exec.QueryRowContext(ctx, cache.query, vals...).Scan(returns...) + if errors.Is(err, sql.ErrNoRows) { + err = nil // Postgres doesn't return anything when there's no update + } + } else { + _, err = exec.ExecContext(ctx, cache.query, vals...) + } + if err != nil { + return errors.Wrap(err, "appdb: unable to upsert config") + } + + if !cached { + configUpsertCacheMut.Lock() + configUpsertCache[key] = cache + configUpsertCacheMut.Unlock() + } + + return o.doAfterUpsertHooks(ctx, exec) +} + +// DeleteG deletes a single Config record. +// DeleteG will match against the primary key column to find the record to delete. +func (o *Config) DeleteG(ctx context.Context) (int64, error) { + return o.Delete(ctx, boil.GetContextDB()) +} + +// Delete deletes a single Config record with an executor. +// Delete will match against the primary key column to find the record to delete. +func (o *Config) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if o == nil { + return 0, errors.New("appdb: no Config provided for delete") + } + + if err := o.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), configPrimaryKeyMapping) + sql := "DELETE FROM \"saml_sp\".\"config\" WHERE \"id\"=$1" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args...) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to delete from config") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: failed to get rows affected by delete for config") + } + + if err := o.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + + return rowsAff, nil +} + +func (q configQuery) DeleteAllG(ctx context.Context) (int64, error) { + return q.DeleteAll(ctx, boil.GetContextDB()) +} + +// DeleteAll deletes all matching rows. +func (q configQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if q.Query == nil { + return 0, errors.New("appdb: no configQuery provided for delete all") + } + + queries.SetDelete(q.Query) + + result, err := q.Query.ExecContext(ctx, exec) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to delete all from config") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for config") + } + + return rowsAff, nil +} + +// DeleteAllG deletes all rows in the slice. +func (o ConfigSlice) DeleteAllG(ctx context.Context) (int64, error) { + return o.DeleteAll(ctx, boil.GetContextDB()) +} + +// DeleteAll deletes all rows in the slice, using an executor. +func (o ConfigSlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) { + if len(o) == 0 { + return 0, nil + } + + if len(configBeforeDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + var args []interface{} + for _, obj := range o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), configPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "DELETE FROM \"saml_sp\".\"config\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, configPrimaryKeyColumns, len(o)) + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, args) + } + result, err := exec.ExecContext(ctx, sql, args...) + if err != nil { + return 0, errors.Wrap(err, "appdb: unable to delete all from config slice") + } + + rowsAff, err := result.RowsAffected() + if err != nil { + return 0, errors.Wrap(err, "appdb: failed to get rows affected by deleteall for config") + } + + if len(configAfterDeleteHooks) != 0 { + for _, obj := range o { + if err := obj.doAfterDeleteHooks(ctx, exec); err != nil { + return 0, err + } + } + } + + return rowsAff, nil +} + +// ReloadG refetches the object from the database using the primary keys. +func (o *Config) ReloadG(ctx context.Context) error { + if o == nil { + return errors.New("appdb: no Config provided for reload") + } + + return o.Reload(ctx, boil.GetContextDB()) +} + +// Reload refetches the object from the database +// using the primary keys with an executor. +func (o *Config) Reload(ctx context.Context, exec boil.ContextExecutor) error { + ret, err := FindConfig(ctx, exec, o.ID) + if err != nil { + return err + } + + *o = *ret + return nil +} + +// ReloadAllG refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *ConfigSlice) ReloadAllG(ctx context.Context) error { + if o == nil { + return errors.New("appdb: empty ConfigSlice provided for reload all") + } + + return o.ReloadAll(ctx, boil.GetContextDB()) +} + +// ReloadAll refetches every row with matching primary key column values +// and overwrites the original object slice with the newly updated slice. +func (o *ConfigSlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error { + if o == nil || len(*o) == 0 { + return nil + } + + slice := ConfigSlice{} + var args []interface{} + for _, obj := range *o { + pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), configPrimaryKeyMapping) + args = append(args, pkeyArgs...) + } + + sql := "SELECT \"saml_sp\".\"config\".* FROM \"saml_sp\".\"config\" WHERE " + + strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 1, configPrimaryKeyColumns, len(*o)) + + q := queries.Raw(sql, args...) + + err := q.Bind(ctx, exec, &slice) + if err != nil { + return errors.Wrap(err, "appdb: unable to reload all in ConfigSlice") + } + + *o = slice + + return nil +} + +// ConfigExistsG checks if the Config row exists. +func ConfigExistsG(ctx context.Context, iD int32) (bool, error) { + return ConfigExists(ctx, boil.GetContextDB(), iD) +} + +// ConfigExists checks if the Config row exists. +func ConfigExists(ctx context.Context, exec boil.ContextExecutor, iD int32) (bool, error) { + var exists bool + sql := "select exists(select 1 from \"saml_sp\".\"config\" where \"id\"=$1 limit 1)" + + if boil.IsDebug(ctx) { + writer := boil.DebugWriterFrom(ctx) + fmt.Fprintln(writer, sql) + fmt.Fprintln(writer, iD) + } + row := exec.QueryRowContext(ctx, sql, iD) + + err := row.Scan(&exists) + if err != nil { + return false, errors.Wrap(err, "appdb: unable to check if config exists") + } + + return exists, nil +} + +// Exists checks if the Config row exists. +func (o *Config) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) { + return ConfigExists(ctx, exec, o.ID) +} diff --git a/appdb/permissions.go b/appdb/permissions.go index 15ddf7b..b389814 100644 --- a/appdb/permissions.go +++ b/appdb/permissions.go @@ -118,14 +118,14 @@ var PermissionWhere = struct { // PermissionRels is where relationship names are stored. var PermissionRels = struct { - IDBasicConfig string + IDConfig string }{ - IDBasicConfig: "IDBasicConfig", + IDConfig: "IDConfig", } // permissionR is where relationships are stored. type permissionR struct { - IDBasicConfig *BasicConfig `boil:"IDBasicConfig" json:"IDBasicConfig" toml:"IDBasicConfig" yaml:"IDBasicConfig"` + IDConfig *Config `boil:"IDConfig" json:"IDConfig" toml:"IDConfig" yaml:"IDConfig"` } // NewStruct creates a new relationship struct @@ -133,11 +133,11 @@ func (*permissionR) NewStruct() *permissionR { return &permissionR{} } -func (r *permissionR) GetIDBasicConfig() *BasicConfig { +func (r *permissionR) GetIDConfig() *Config { if r == nil { return nil } - return r.IDBasicConfig + return r.IDConfig } // permissionL is where Load methods for each relationship are stored. @@ -476,20 +476,20 @@ func (q permissionQuery) Exists(ctx context.Context, exec boil.ContextExecutor) return count > 0, nil } -// IDBasicConfig pointed to by the foreign key. -func (o *Permission) IDBasicConfig(mods ...qm.QueryMod) basicConfigQuery { +// IDConfig pointed to by the foreign key. +func (o *Permission) IDConfig(mods ...qm.QueryMod) configQuery { queryMods := []qm.QueryMod{ qm.Where("\"id\" = ?", o.ID), } queryMods = append(queryMods, mods...) - return BasicConfigs(queryMods...) + return Configs(queryMods...) } -// LoadIDBasicConfig allows an eager lookup of values, cached into the +// LoadIDConfig allows an eager lookup of values, cached into the // loaded structs of the objects. This is for an N-1 relationship. -func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybePermission interface{}, mods queries.Applicator) error { +func (permissionL) LoadIDConfig(ctx context.Context, e boil.ContextExecutor, singular bool, maybePermission interface{}, mods queries.Applicator) error { var slice []*Permission var object *Permission @@ -545,8 +545,8 @@ func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor } query := NewQuery( - qm.From(`saml_sp.basic_config`), - qm.WhereIn(`saml_sp.basic_config.id in ?`, argsSlice...), + qm.From(`saml_sp.config`), + qm.WhereIn(`saml_sp.config.id in ?`, argsSlice...), ) if mods != nil { mods.Apply(query) @@ -554,22 +554,22 @@ func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor results, err := query.QueryContext(ctx, e) if err != nil { - return errors.Wrap(err, "failed to eager load BasicConfig") + return errors.Wrap(err, "failed to eager load Config") } - var resultSlice []*BasicConfig + var resultSlice []*Config if err = queries.Bind(results, &resultSlice); err != nil { - return errors.Wrap(err, "failed to bind eager loaded slice BasicConfig") + return errors.Wrap(err, "failed to bind eager loaded slice Config") } if err = results.Close(); err != nil { - return errors.Wrap(err, "failed to close results of eager load for basic_config") + return errors.Wrap(err, "failed to close results of eager load for config") } if err = results.Err(); err != nil { - return errors.Wrap(err, "error occurred during iteration of eager loaded relations for basic_config") + return errors.Wrap(err, "error occurred during iteration of eager loaded relations for config") } - if len(basicConfigAfterSelectHooks) != 0 { + if len(configAfterSelectHooks) != 0 { for _, obj := range resultSlice { if err := obj.doAfterSelectHooks(ctx, e); err != nil { return err @@ -583,9 +583,9 @@ func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor if singular { foreign := resultSlice[0] - object.R.IDBasicConfig = foreign + object.R.IDConfig = foreign if foreign.R == nil { - foreign.R = &basicConfigR{} + foreign.R = &configR{} } foreign.R.IDPermission = object return nil @@ -594,9 +594,9 @@ func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor for _, local := range slice { for _, foreign := range resultSlice { if local.ID == foreign.ID { - local.R.IDBasicConfig = foreign + local.R.IDConfig = foreign if foreign.R == nil { - foreign.R = &basicConfigR{} + foreign.R = &configR{} } foreign.R.IDPermission = local break @@ -607,18 +607,18 @@ func (permissionL) LoadIDBasicConfig(ctx context.Context, e boil.ContextExecutor return nil } -// SetIDBasicConfigG of the permission to the related item. -// Sets o.R.IDBasicConfig to related. +// SetIDConfigG of the permission to the related item. +// Sets o.R.IDConfig to related. // Adds o to related.R.IDPermission. // Uses the global database handle. -func (o *Permission) SetIDBasicConfigG(ctx context.Context, insert bool, related *BasicConfig) error { - return o.SetIDBasicConfig(ctx, boil.GetContextDB(), insert, related) +func (o *Permission) SetIDConfigG(ctx context.Context, insert bool, related *Config) error { + return o.SetIDConfig(ctx, boil.GetContextDB(), insert, related) } -// SetIDBasicConfig of the permission to the related item. -// Sets o.R.IDBasicConfig to related. +// SetIDConfig of the permission to the related item. +// Sets o.R.IDConfig to related. // Adds o to related.R.IDPermission. -func (o *Permission) SetIDBasicConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *BasicConfig) error { +func (o *Permission) SetIDConfig(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Config) error { var err error if insert { if err = related.Insert(ctx, exec, boil.Infer()); err != nil { @@ -645,14 +645,14 @@ func (o *Permission) SetIDBasicConfig(ctx context.Context, exec boil.ContextExec o.ID = related.ID if o.R == nil { o.R = &permissionR{ - IDBasicConfig: related, + IDConfig: related, } } else { - o.R.IDBasicConfig = related + o.R.IDConfig = related } if related.R == nil { - related.R = &basicConfigR{ + related.R = &configR{ IDPermission: o, } } else { diff --git a/conf/conf.go b/conf/conf.go index 9af383c..2df3f00 100644 --- a/conf/conf.go +++ b/conf/conf.go @@ -53,20 +53,18 @@ const ( func InsertAutoSamlConfiguration(ctx context.Context) error { - bs, err := GetBasicConfig(context.Background()) + bs, err := GetConfig(context.Background()) if err == nil && bs != nil { log.Info(LOG_REGIO, "config already exists. skip insert default config.") return nil } var ( - basicConfig appdb.BasicConfig = appdb.BasicConfig{ - Enable: AUTO_CNF_DEFAULT_ENABLED, - IdpMetadataURL: null.StringFromPtr(nil), - MetadataXML: null.StringFromPtr(nil), - UserToArchive: AUTO_CNF_DEFAULT_USER_TO_ARCHIVE, - } - advancedConfig appdb.AdvancedConfig = appdb.AdvancedConfig{ + basicConfig appdb.Config = appdb.Config{ + Enable: AUTO_CNF_DEFAULT_ENABLED, + IdpMetadataURL: null.StringFromPtr(nil), + MetadataXML: null.StringFromPtr(nil), + UserToArchive: AUTO_CNF_DEFAULT_USER_TO_ARCHIVE, AllowInitializationByIdp: AUTO_CNF_DEFAULT_ALLOW_INIT_BY_IDP, SignedRequest: AUTO_CNF_DEFAULT_SIGNING_REQ, ForceAuthn: AUTO_CNF_DEFAULT_FORCE_AUTHN, @@ -105,11 +103,6 @@ func InsertAutoSamlConfiguration(ctx context.Context) error { return err } - err = advancedConfig.Insert(ctx, getDb(), boil.Infer()) - if err != nil { - return err - } - err = attributeMapping.Insert(ctx, getDb(), boil.Infer()) if err != nil { return err @@ -123,211 +116,89 @@ func InsertAutoSamlConfiguration(ctx context.Context) error { return err } -func GetBasicConfig(ctx context.Context) (*apiserver.BasicConfiguration, error) { - - var ( - err error - basicConfigDb *appdb.BasicConfig - - apiForm any - ) - - basicConfigDb, err = appdb.BasicConfigs().One(ctx, getDb()) +func GetConfig(ctx context.Context) (*apiserver.Configuration, error) { + basicConfigDb, err := appdb.Configs().One(ctx, getDb()) if err != nil { return nil, err } - apiForm, err = ConvertDbToApiForm(basicConfigDb) + basicConfigApi, err := ConfigDbToApiForm(basicConfigDb) if err != nil { return nil, err } - basicConfigApi := apiForm.(*apiserver.BasicConfiguration) - return basicConfigApi, err + return basicConfigApi, nil } -func SetBasicConfig(ctx context.Context, config *apiserver.BasicConfiguration) ( - *apiserver.BasicConfiguration, error) { - - var ( - err error - basicConfigDb *appdb.BasicConfig - - apiForm any - dbForm any - ) - +func SetConfig(ctx context.Context, config *apiserver.Configuration) (*apiserver.Configuration, error) { if config == nil { - return nil, errors.New("basic config is nil") + return nil, errors.New("config is nil") } config.Id = 1 // Enforced by table definition. - dbForm, err = ConvertApiToDbForm(config) + ConfigDb, err := ConfigApiToDbForm(config) if err != nil { return nil, err - } else { - basicConfigDb = dbForm.(*appdb.BasicConfig) } - exists, err := appdb.BasicConfigs().Exists(ctx, getDb()) + exists, err := appdb.Configs().Exists(ctx, getDb()) if err != nil { return nil, err } - log.Debug(LOG_REGIO, "basic config exists %v", exists) + log.Debug(LOG_REGIO, "config exists %v", exists) if exists { - _, err = basicConfigDb.Update(ctx, getDb(), - boil.Blacklist(appdb.BasicConfigColumns.ID)) + _, err = ConfigDb.Update(ctx, getDb(), + boil.Blacklist(appdb.ConfigColumns.ID), + ) } else { - err = basicConfigDb.Insert(ctx, getDb(), - boil.Greylist(appdb.BasicConfigColumns.Enable)) + err = ConfigDb.Insert(ctx, getDb(), + boil.Greylist(appdb.ConfigColumns.Enable, appdb.ConfigColumns.SignedRequest), + ) } if err != nil { return nil, err } - apiForm, err = ConvertDbToApiForm(basicConfigDb) + apiForm, err := ConfigDbToApiForm(ConfigDb) if err != nil { return nil, err } - return apiForm.(*apiserver.BasicConfiguration), err + return apiForm, err } -func DeleteBasicConfig(ctx context.Context) (int, error) { - ans, err := appdb.BasicConfigs().DeleteAll(ctx, getDb()) - - return int(ans), err -} - -func GetAdvancedConfig(ctx context.Context) (*apiserver.AdvancedConfiguration, error) { - - var ( - err error - advConfigDb *appdb.AdvancedConfig - advConfigApi *apiserver.AdvancedConfiguration - - apiForm any - ) - - advConfigDb, err = appdb.AdvancedConfigs().One(ctx, getDb()) - if err != nil { - return nil, err - } - - apiForm, err = ConvertDbToApiForm(advConfigDb) - if err != nil { - return nil, err - } else { - advConfigApi = apiForm.(*apiserver.AdvancedConfiguration) - } - - return advConfigApi, err -} - -func SetAdvancedConfig(ctx context.Context, config *apiserver.AdvancedConfiguration) ( - *apiserver.AdvancedConfiguration, error) { - - var ( - err error - advancedConfigDb *appdb.AdvancedConfig - - apiForm any - dbForm any - ) - - if config == nil { - return nil, errors.New("advanced config is nil") - } - config.Id = 1 // Enforced by table definition. - - dbForm, err = ConvertApiToDbForm(config) - if err != nil { - return nil, err - } else { - advancedConfigDb = dbForm.(*appdb.AdvancedConfig) - } - - exists, err := appdb.AdvancedConfigs().Exists(ctx, getDb()) - if err != nil { - return nil, err - } - - log.Debug(LOG_REGIO, "advanced config exists %v", exists) - - if exists { - _, err = advancedConfigDb.Update(ctx, getDb(), boil.Infer()) - } else { - err = advancedConfigDb.Insert(ctx, getDb(), - boil.Greylist(appdb.AdvancedConfigColumns.SignedRequest)) - } - - if err != nil { - return nil, err - } - - apiForm, err = ConvertDbToApiForm(advancedConfigDb) - if err != nil { - return nil, err - } - - return apiForm.(*apiserver.AdvancedConfiguration), err -} - -func DeleteAdvancedConfig(ctx context.Context) (int, error) { - ans, err := appdb.AdvancedConfigs().DeleteAll(ctx, getDb()) +func DeleteConfig(ctx context.Context) (int, error) { + ans, err := appdb.Configs().DeleteAll(ctx, getDb()) return int(ans), err } func GetAttributeMapping(ctx context.Context) (*apiserver.AttributeMap, error) { - - var ( - err error - attrMapDb *appdb.AttributeMap - attrMapApi *apiserver.AttributeMap - - apiForm any - ) - - attrMapDb, err = appdb.AttributeMaps().One(ctx, getDb()) + attrMapDb, err := appdb.AttributeMaps().One(ctx, getDb()) if err != nil { return nil, err } - apiForm, err = ConvertDbToApiForm(attrMapDb) + attrMapApi, err := AttributeMapDbToApiForm(attrMapDb) if err != nil { return nil, err - } else { - attrMapApi = apiForm.(*apiserver.AttributeMap) } return attrMapApi, err } -func SetAttributeMapping(ctx context.Context, mapping *apiserver.AttributeMap) ( - *apiserver.AttributeMap, error) { - - var ( - err error - attributeMappingDb *appdb.AttributeMap - - apiForm any - dbForm any - ) - +func SetAttributeMapping(ctx context.Context, mapping *apiserver.AttributeMap) (*apiserver.AttributeMap, error) { if mapping == nil { return nil, errors.New("attribute mapping is nil") } mapping.Id = 1 // Enforced by table definition. - dbForm, err = ConvertApiToDbForm(mapping) + attributeMappingDb, err := AttributeMapApiToDbForm(mapping) if err != nil { return nil, err - } else { - attributeMappingDb = dbForm.(*appdb.AttributeMap) } exists, err := appdb.AttributeMaps().Exists(ctx, getDb()) @@ -349,12 +220,12 @@ func SetAttributeMapping(ctx context.Context, mapping *apiserver.AttributeMap) ( return nil, err } - apiForm, err = ConvertDbToApiForm(attributeMappingDb) + apiForm, err := AttributeMapDbToApiForm(attributeMappingDb) if err != nil { return nil, err } - return apiForm.(*apiserver.AttributeMap), err + return apiForm, err } func DeleteAttributeMapping(ctx context.Context) (int, error) { @@ -363,53 +234,31 @@ func DeleteAttributeMapping(ctx context.Context) (int, error) { return int(ans), err } -func GetPermissionSettings(ctx context.Context) (*apiserver.Permissions, error) { - - var ( - err error - permDb *appdb.Permission - permApi *apiserver.Permissions - - apiForm any - ) - - permDb, err = appdb.Permissions().One(ctx, getDb()) +func GetPermissionMapping(ctx context.Context) (*apiserver.Permissions, error) { + permDb, err := appdb.Permissions().One(ctx, getDb()) if err != nil { return nil, err } - apiForm, err = ConvertDbToApiForm(permDb) + permApi, err := PermissionDbToApiForm(permDb) if err != nil { return nil, err - } else { - permApi = apiForm.(*apiserver.Permissions) } return permApi, err } -func SetPermissionSettings(ctx context.Context, permissions *apiserver.Permissions) ( - *apiserver.Permissions, error) { - - var ( - err error - permissionsDb *appdb.Permission - - apiForm any - dbForm any - ) - +func SetPermissionMapping(ctx context.Context, permissions *apiserver.Permissions) (*apiserver.Permissions, error) { if permissions == nil { return nil, errors.New("permissions nil") } else { permissions.Id = 1 // set id to 1, because it must } - dbForm, err = ConvertApiToDbForm(permissions) + permissionsDb, err := PermissionApiToDbForm(permissions) if err != nil { return nil, err } - permissionsDb = dbForm.(*appdb.Permission) exists, err := appdb.Permissions().Exists(ctx, getDb()) if err != nil { @@ -430,22 +279,22 @@ func SetPermissionSettings(ctx context.Context, permissions *apiserver.Permissio return nil, err } - apiForm, err = ConvertDbToApiForm(permissionsDb) + apiForm, err := PermissionDbToApiForm(permissionsDb) if err != nil { return nil, err } - return apiForm.(*apiserver.Permissions), err + return apiForm, err } -func DeletePermissionSettings(ctx context.Context) (int, error) { +func DeletePermissionMapping(ctx context.Context) (int, error) { ans, err := appdb.Permissions().DeleteAll(ctx, getDb()) return int(ans), err } func DeleteAllConfigurations(ctx context.Context) error { - _, err := DeletePermissionSettings(ctx) + _, err := DeletePermissionMapping(ctx) if err != nil { return err } @@ -453,26 +302,24 @@ func DeleteAllConfigurations(ctx context.Context) error { if err != nil { return err } - _, err = DeleteAdvancedConfig(ctx) - if err != nil { - return err - } - _, err = DeleteBasicConfig(ctx) - + _, err = DeleteConfig(ctx) return err } func getElionaHost() string { - var eliDomain string - db := getDb() row := db.QueryRow("SELECT domain_name FROM eliona_config ;") + + var eliDomain string err := row.Scan(&eliDomain) if err != nil { log.Error(LOG_REGIO, "scan getElionaHost: %v", err) } - return eliDomain + publicEndpoint := "apps-public/saml-sso" + ownURL := eliDomain + publicEndpoint + + return ownURL } func getDb() *sql.DB { diff --git a/conf/conf_test.go b/conf/conf_test.go index bbaa69e..b62e8e7 100644 --- a/conf/conf_test.go +++ b/conf/conf_test.go @@ -48,7 +48,6 @@ func TestApp_Conf_InitDB(t *testing.T) { } func TestApp_Conf_LoadAutoConfig(t *testing.T) { - err := conf.DeleteAllConfigurations(context.Background()) if err != nil { t.Error("Prepare DB (delete all config): ", err) @@ -59,39 +58,33 @@ func TestApp_Conf_LoadAutoConfig(t *testing.T) { t.Error(err) } - basicConfig, err := conf.GetBasicConfig(context.Background()) + config, err := conf.GetConfig(context.Background()) if err != nil { t.Error(err) } - if basicConfig.Id != 1 || - basicConfig.Enable != conf.AUTO_CNF_DEFAULT_ENABLED || - basicConfig.UserToArchive != conf.AUTO_CNF_DEFAULT_USER_TO_ARCHIVE || - !strings.Contains(basicConfig.OwnUrl, "https://") || - basicConfig.IdpMetadataUrl != nil || - basicConfig.IdpMetadataXml != nil || - !strings.Contains(basicConfig.ServiceProviderCertificate, + if config.Enable != conf.AUTO_CNF_DEFAULT_ENABLED || + config.UserToArchive != conf.AUTO_CNF_DEFAULT_USER_TO_ARCHIVE || + !strings.Contains(config.OwnUrl, "https://") || + config.IdpMetadataUrl != nil || + config.IdpMetadataXml != nil || + !strings.Contains(config.ServiceProviderCertificate, "-----BEGIN CERTIFICATE-----") || - !strings.Contains(basicConfig.ServiceProviderPrivateKey, + !strings.Contains(config.ServiceProviderPrivateKey, "-----BEGIN RSA PRIVATE KEY-----") { t.Error("mismatch auto config") } - _, err = utils.GetCombinedX509Certificate(basicConfig.ServiceProviderCertificate, - basicConfig.ServiceProviderPrivateKey) + _, err = utils.GetCombinedX509Certificate(config.ServiceProviderCertificate, + config.ServiceProviderPrivateKey) if err != nil { t.Error("auto gen certificate") } - advancedConfig, err := conf.GetAdvancedConfig(context.Background()) - if err != nil { - t.Error(err) - } - if advancedConfig.Id != 1 || - advancedConfig.AllowInitializationByIdp != conf.AUTO_CNF_DEFAULT_ALLOW_INIT_BY_IDP || - advancedConfig.CookieSecure != conf.AUTO_CNF_DEFAULT_COOKIE_SECURE || - advancedConfig.EntityId != conf.AUTO_CNF_DEFAULT_ENTITY_ID || - advancedConfig.ForceAuthn != conf.AUTO_CNF_DEFAULT_FORCE_AUTHN || - advancedConfig.LoginFailedUrl != conf.AUTO_CNF_DEFAULT_LOGIN_FAIL_URL || - advancedConfig.SignedRequest != conf.AUTO_CNF_DEFAULT_SIGNING_REQ { + if config.AllowInitializationByIdp != conf.AUTO_CNF_DEFAULT_ALLOW_INIT_BY_IDP || + config.CookieSecure != conf.AUTO_CNF_DEFAULT_COOKIE_SECURE || + config.EntityId != conf.AUTO_CNF_DEFAULT_ENTITY_ID || + config.ForceAuthn != conf.AUTO_CNF_DEFAULT_FORCE_AUTHN || + config.LoginFailedUrl != conf.AUTO_CNF_DEFAULT_LOGIN_FAIL_URL || + config.SignedRequest != conf.AUTO_CNF_DEFAULT_SIGNING_REQ { t.Error("invalid advanced auto conf") } @@ -107,7 +100,7 @@ func TestApp_Conf_LoadAutoConfig(t *testing.T) { t.Error("invalid attribute map auto conf") } - perms, err := conf.GetPermissionSettings(context.Background()) + perms, err := conf.GetPermissionMapping(context.Background()) if err != nil { t.Error(err) } @@ -123,22 +116,18 @@ func TestApp_Conf_LoadAutoConfig(t *testing.T) { } func TestApp_Conf_InsertUpdateConfig(t *testing.T) { - for i := 0; i < 5; i++ { - var ( - basicConfig1 apiserver.BasicConfiguration = utils.CreateRandomApiBasicConfig() - advConfig1 apiserver.AdvancedConfiguration = utils.CreateRandomApiAdvancedConfig() - attrMapping1 apiserver.AttributeMap = utils.CreateRandomApiAttributeMap() - perms1 apiserver.Permissions = utils.CreateRandomApiPermissions() + config1 apiserver.Configuration = utils.CreateRandomApiConfig() + attrMapping1 apiserver.AttributeMap = utils.CreateRandomApiAttributeMap() + perms1 apiserver.Permissions = utils.CreateRandomApiPermissions() - basicConfig2 apiserver.BasicConfiguration = utils.CreateRandomApiBasicConfig() - advConfig2 apiserver.AdvancedConfiguration = utils.CreateRandomApiAdvancedConfig() - attrMapping2 apiserver.AttributeMap = utils.CreateRandomApiAttributeMap() - perms2 apiserver.Permissions = utils.CreateRandomApiPermissions() + config2 apiserver.Configuration = utils.CreateRandomApiConfig() + attrMapping2 apiserver.AttributeMap = utils.CreateRandomApiAttributeMap() + perms2 apiserver.Permissions = utils.CreateRandomApiPermissions() ) - basicConfig1.Enable = false - basicConfig2.Enable = true + config1.Enable = false + config2.Enable = true err := conf.DeleteAllConfigurations(context.Background()) if err != nil { @@ -146,63 +135,33 @@ func TestApp_Conf_InsertUpdateConfig(t *testing.T) { } // Basic Config Test - basicRet1, err := conf.SetBasicConfig(context.Background(), &basicConfig1) - if err != nil { - t.Error(err) - } - if diff := deep.Equal(&basicConfig1, basicRet1); diff != nil { - t.Error("missmatch basic config 1: ", diff) - } - basicRet1, err = conf.GetBasicConfig(context.Background()) - if err != nil { - t.Error(err) - } - if diff := deep.Equal(&basicConfig1, basicRet1); diff != nil { - t.Error("missmatch basic config 1_1: ", diff) - } - basicRet2, err := conf.SetBasicConfig(context.Background(), &basicConfig2) - if err != nil { - t.Error(err) - } - if diff := deep.Equal(&basicConfig2, basicRet2); diff != nil { - t.Error("missmatch basic config 2: ", diff) - } - basicRet2, err = conf.GetBasicConfig(context.Background()) - if err != nil { - t.Error(err) - } - if diff := deep.Equal(&basicConfig2, basicRet2); diff != nil { - t.Error("missmatch basic config 2_2: ", diff) - } - - // Advanced Config Test - advRet1, err := conf.SetAdvancedConfig(context.Background(), &advConfig1) + confRet1, err := conf.SetConfig(context.Background(), &config1) if err != nil { t.Error(err) } - if diff := deep.Equal(&advConfig1, advRet1); diff != nil { - t.Error("missmatch advanced config 1: ", diff) + if diff := deep.Equal(&config1, confRet1); diff != nil { + t.Error("missmatch config 1: ", diff) } - advRet1, err = conf.GetAdvancedConfig(context.Background()) + confRet1, err = conf.GetConfig(context.Background()) if err != nil { t.Error(err) } - if diff := deep.Equal(&advConfig1, advRet1); diff != nil { - t.Error("missmatch advanced config 1_1: ", diff) + if diff := deep.Equal(&config1, confRet1); diff != nil { + t.Error("missmatch config 1_1: ", diff) } - advRet2, err := conf.SetAdvancedConfig(context.Background(), &advConfig2) + confRet2, err := conf.SetConfig(context.Background(), &config2) if err != nil { t.Error(err) } - if diff := deep.Equal(&advConfig2, advRet2); diff != nil { - t.Error("missmatch advanced config 2: ", diff) + if diff := deep.Equal(&config2, confRet2); diff != nil { + t.Error("missmatch config 2: ", diff) } - advRet2, err = conf.GetAdvancedConfig(context.Background()) + confRet2, err = conf.GetConfig(context.Background()) if err != nil { t.Error(err) } - if diff := deep.Equal(&advConfig2, advRet2); diff != nil { - t.Error("missmatch advanced config 2_2: ", diff) + if diff := deep.Equal(&config2, confRet2); diff != nil { + t.Error("missmatch config 2_2: ", diff) } // Attribute Mapping Test @@ -236,28 +195,28 @@ func TestApp_Conf_InsertUpdateConfig(t *testing.T) { } // Permission Cnf Test - permsRet1, err := conf.SetPermissionSettings(context.Background(), &perms1) + permsRet1, err := conf.SetPermissionMapping(context.Background(), &perms1) if err != nil { t.Error(err) } if diff := deep.Equal(&perms1, permsRet1); diff != nil { t.Error("missmatch permission config 1: ", diff) } - permsRet1, err = conf.GetPermissionSettings(context.Background()) + permsRet1, err = conf.GetPermissionMapping(context.Background()) if err != nil { t.Error(err) } if diff := deep.Equal(&perms1, permsRet1); diff != nil { t.Error("missmatch permission config 1_1: ", diff) } - permsRet2, err := conf.SetPermissionSettings(context.Background(), &perms2) + permsRet2, err := conf.SetPermissionMapping(context.Background(), &perms2) if err != nil { t.Error(err) } if diff := deep.Equal(&perms2, permsRet2); diff != nil { t.Error("missmatch permission config 2: ", diff) } - permsRet2, err = conf.GetPermissionSettings(context.Background()) + permsRet2, err = conf.GetPermissionMapping(context.Background()) if err != nil { t.Error(err) } diff --git a/conf/converter.go b/conf/converter.go index 172d607..b672c98 100644 --- a/conf/converter.go +++ b/conf/converter.go @@ -17,75 +17,33 @@ package conf import ( "encoding/json" - "errors" "saml-sso/apiserver" "saml-sso/appdb" "github.com/volatiletech/null/v8" ) -func ConvertApiToDbForm(apiForm any) (any, error) { - - var ( - err error - dbForm any - ) - - switch a := apiForm.(type) { - case *apiserver.BasicConfiguration: - dbForm, err = BasicConfigApiToDbForm(a) - case *apiserver.AdvancedConfiguration: - dbForm, err = AdvancedConfigApiToDbForm(a) - case *apiserver.AttributeMap: - dbForm, err = AttributeMapApiToDbForm(a) - case *apiserver.Permissions: - dbForm, err = PermissionApiToDbForm(a) - default: - err = errors.New("unknown api datatype") - } - - return dbForm, err -} - -func ConvertDbToApiForm(dbForm any) (any, error) { - - var ( - err error - apiForm any - ) - - switch d := dbForm.(type) { - case *appdb.BasicConfig: - apiForm, err = BasicConfigDbToApiForm(d) - case *appdb.AdvancedConfig: - apiForm, err = AdvancedConfigDbToApiForm(d) - case *appdb.AttributeMap: - apiForm, err = AttributeMapDbToApiForm(d) - case *appdb.Permission: - apiForm, err = PermissionDbToApiForm(d) - default: - err = errors.New("unknown db datatype") - } - - return apiForm, err -} - -func BasicConfigApiToDbForm(config *apiserver.BasicConfiguration) (*appdb.BasicConfig, error) { - - return &appdb.BasicConfig{ - ID: config.Id, - Enable: config.Enable, - SPCertificate: config.ServiceProviderCertificate, - SPPrivateKey: config.ServiceProviderPrivateKey, - IdpMetadataURL: null.StringFromPtr(config.IdpMetadataUrl), - MetadataXML: null.StringFromPtr(config.IdpMetadataXml), - OwnURL: config.OwnUrl, - UserToArchive: config.UserToArchive, +func ConfigApiToDbForm(config *apiserver.Configuration) (*appdb.Config, error) { + return &appdb.Config{ + ID: config.Id, + Enable: config.Enable, + SPCertificate: config.ServiceProviderCertificate, + SPPrivateKey: config.ServiceProviderPrivateKey, + IdpMetadataURL: null.StringFromPtr(config.IdpMetadataUrl), + MetadataXML: null.StringFromPtr(config.IdpMetadataXml), + OwnURL: config.OwnUrl, + UserToArchive: config.UserToArchive, + AllowInitializationByIdp: config.AllowInitializationByIdp, + SignedRequest: config.SignedRequest, + ForceAuthn: config.ForceAuthn, + EntityID: config.EntityId, + CookieSecure: config.CookieSecure, + LoginFailedURL: config.LoginFailedUrl, }, nil } -func BasicConfigDbToApiForm(config *appdb.BasicConfig) (*apiserver.BasicConfiguration, error) { - return &apiserver.BasicConfiguration{ +func ConfigDbToApiForm(config *appdb.Config) (*apiserver.Configuration, error) { + return &apiserver.Configuration{ Id: config.ID, Enable: config.Enable, ServiceProviderCertificate: config.SPCertificate, @@ -94,29 +52,12 @@ func BasicConfigDbToApiForm(config *appdb.BasicConfig) (*apiserver.BasicConfigur IdpMetadataXml: config.MetadataXML.Ptr(), OwnUrl: config.OwnURL, UserToArchive: config.UserToArchive, - }, nil -} - -func AdvancedConfigApiToDbForm(config *apiserver.AdvancedConfiguration) (*appdb.AdvancedConfig, error) { - return &appdb.AdvancedConfig{ - ID: config.Id, - AllowInitializationByIdp: config.AllowInitializationByIdp, - SignedRequest: config.SignedRequest, - ForceAuthn: config.ForceAuthn, - EntityID: config.EntityId, - CookieSecure: config.CookieSecure, - LoginFailedURL: config.LoginFailedUrl, - }, nil -} -func AdvancedConfigDbToApiForm(config *appdb.AdvancedConfig) (*apiserver.AdvancedConfiguration, error) { - return &apiserver.AdvancedConfiguration{ - Id: config.ID, - AllowInitializationByIdp: config.AllowInitializationByIdp, - SignedRequest: config.SignedRequest, - ForceAuthn: config.ForceAuthn, - EntityId: config.EntityID, - CookieSecure: config.CookieSecure, - LoginFailedUrl: config.LoginFailedURL, + AllowInitializationByIdp: config.AllowInitializationByIdp, + SignedRequest: config.SignedRequest, + ForceAuthn: config.ForceAuthn, + EntityId: config.EntityID, + CookieSecure: config.CookieSecure, + LoginFailedUrl: config.LoginFailedURL, }, nil } diff --git a/conf/converter_test.go b/conf/converter_test.go index 76e18fb..c3c21c3 100644 --- a/conf/converter_test.go +++ b/conf/converter_test.go @@ -27,69 +27,46 @@ import ( "github.com/go-test/deep" ) -func TestApp_Converter_ConvertBasicConfig(t *testing.T) { +func TestApp_Converter_ConvertConfig(t *testing.T) { for i := 0; i < 5; i++ { - apiBasicCnf := utils.CreateRandomApiBasicConfig() - dbBasicCnf, err := conf.ConvertApiToDbForm(&apiBasicCnf) + apiBasicCnf := utils.CreateRandomApiConfig() + dbBasicCnf, err := conf.ConfigApiToDbForm(&apiBasicCnf) if err != nil { t.Error("convert basic config from api to db form using general converter: ", err) } - err = compareBasicConfig(dbBasicCnf.(*appdb.BasicConfig), &apiBasicCnf) + err = compareConfig(dbBasicCnf, &apiBasicCnf) if err != nil { t.Error("convert basic config from api to db wrong content: ", err) } - apiBasicCnfReturned, err := conf.ConvertDbToApiForm(dbBasicCnf.(*appdb.BasicConfig)) + apiBasicCnfReturned, err := conf.ConfigDbToApiForm(dbBasicCnf) if err != nil { t.Error("convert basic config from db to api form using general converter: ", err) } - diff := deep.Equal(apiBasicCnfReturned.(*apiserver.BasicConfiguration), &apiBasicCnf) + diff := deep.Equal(apiBasicCnfReturned, &apiBasicCnf) if diff != nil { t.Error("convert basic config from db to api wrong content (not origin): ", err) } } } -func TestApp_Converter_ConvertAdvancedConfig(t *testing.T) { - for i := 0; i < 5; i++ { - apiAdvCnf := utils.CreateRandomApiAdvancedConfig() - dbAdvCnf, err := conf.ConvertApiToDbForm(&apiAdvCnf) - if err != nil { - t.Error("convert advanced config from api to db form using general converter: ", err) - } - err = compareAdvancedConfig(dbAdvCnf.(*appdb.AdvancedConfig), &apiAdvCnf) - if err != nil { - t.Error("convert advanced config from api to db wrong content: ", err) - } - - apiAdvCnfReturned, err := conf.ConvertDbToApiForm(dbAdvCnf.(*appdb.AdvancedConfig)) - if err != nil { - t.Error("convert advanced config from db to api form using general converter: ", err) - } - diff := deep.Equal(apiAdvCnfReturned.(*apiserver.AdvancedConfiguration), &apiAdvCnf) - if diff != nil { - t.Error("convert advanced config from db to api wrong content (not origin): ", err) - } - } -} - func TestApp_Converter_ConvertAttributeMapping(t *testing.T) { for i := 0; i < 5; i++ { apiAttrMap := utils.CreateRandomApiAttributeMap() - dbAttrMap, err := conf.ConvertApiToDbForm(&apiAttrMap) + dbAttrMap, err := conf.AttributeMapApiToDbForm(&apiAttrMap) if err != nil { t.Error("convert attribute map from api to db form using general converter: ", err) } - err = compareAttributeMaps(dbAttrMap.(*appdb.AttributeMap), &apiAttrMap) + err = compareAttributeMaps(dbAttrMap, &apiAttrMap) if err != nil { t.Error("convert attribute map config from api to db wrong content: ", err) } - apiAttrMapReturned, err := conf.ConvertDbToApiForm(dbAttrMap.(*appdb.AttributeMap)) + apiAttrMapReturned, err := conf.AttributeMapDbToApiForm(dbAttrMap) if err != nil { t.Error("convert attribute map config from db to api form using general converter: ", err) } - diff := deep.Equal(apiAttrMapReturned.(*apiserver.AttributeMap), &apiAttrMap) + diff := deep.Equal(apiAttrMapReturned, &apiAttrMap) if diff != nil { t.Error("convert attribute map config from db to api wrong content (not origin): ", err) } @@ -99,27 +76,27 @@ func TestApp_Converter_ConvertAttributeMapping(t *testing.T) { func TestApp_Converter_ConvertPermissionCnf(t *testing.T) { for i := 0; i < 5; i++ { apiPerm := utils.CreateRandomApiPermissions() - dbPerm, err := conf.ConvertApiToDbForm(&apiPerm) + dbPerm, err := conf.PermissionApiToDbForm(&apiPerm) if err != nil { t.Error("convert permissions from api to db form using general converter: ", err) } - err = comparePermissions(dbPerm.(*appdb.Permission), &apiPerm) + err = comparePermissions(dbPerm, &apiPerm) if err != nil { t.Error("convert permissions config from api to db wrong content: ", err) } - apiPermReturned, err := conf.ConvertDbToApiForm(dbPerm.(*appdb.Permission)) + apiPermReturned, err := conf.PermissionDbToApiForm(dbPerm) if err != nil { t.Error("convert permissions config from db to api form using general converter: ", err) } - diff := deep.Equal(apiPermReturned.(*apiserver.Permissions), &apiPerm) + diff := deep.Equal(apiPermReturned, &apiPerm) if diff != nil { t.Error("convert permissions config from db to api wrong content (not origin): ", diff) } } } -func compareBasicConfig(db *appdb.BasicConfig, api *apiserver.BasicConfiguration) error { +func compareConfig(db *appdb.Config, api *apiserver.Configuration) error { if db.ID != api.Id { return errors.New("id") } @@ -152,14 +129,6 @@ func compareBasicConfig(db *appdb.BasicConfig, api *apiserver.BasicConfiguration return errors.New("user to archive") } - return nil -} - -func compareAdvancedConfig(db *appdb.AdvancedConfig, api *apiserver.AdvancedConfiguration) error { - if db.ID != api.Id { - return errors.New("id") - } - if db.AllowInitializationByIdp != api.AllowInitializationByIdp { return errors.New("allow initialisation by idp") } diff --git a/conf/init.go b/conf/init.go index 2b30ce1..3e4527a 100644 --- a/conf/init.go +++ b/conf/init.go @@ -23,7 +23,5 @@ import ( // InitConfiguration initialize the configuration of the app func InitConfiguration(connection db.Connection) error { - return InsertAutoSamlConfiguration(context.Background()) - // return nil } diff --git a/conf/init.sql b/conf/init.sql index 27d9832..d86c691 100644 --- a/conf/init.sql +++ b/conf/init.sql @@ -18,37 +18,33 @@ CREATE SCHEMA IF NOT EXISTS saml_sp ; GRANT USAGE ON SCHEMA saml_sp TO leicom ; GRANT ALL ON SCHEMA saml_sp TO leicom ; -CREATE TABLE IF NOT EXISTS saml_sp.basic_config ( - id INT PRIMARY KEY NOT NULL DEFAULT 1 CHECK (id = 1), -- due to the architecture of eliona only one configuration (1 sso per instance) is possible - enable BOOLEAN NOT NULL DEFAULT true , - sp_certificate TEXT NOT NULL , - sp_private_key TEXT NOT NULL , - idp_metadata_url TEXT , - metadata_xml TEXT DEFAULT NULL , - own_url TEXT NOT NULL , - user_to_archive BOOLEAN NOT NULL DEFAULT false +CREATE TABLE IF NOT EXISTS saml_sp.config ( + id INT PRIMARY KEY NOT NULL DEFAULT 1 CHECK (id = 1) , -- due to the architecture of eliona only one configuration (1 sso per instance) is possible + enable BOOLEAN NOT NULL DEFAULT true , + sp_certificate TEXT NOT NULL , + sp_private_key TEXT NOT NULL , + idp_metadata_url TEXT , + metadata_xml TEXT DEFAULT NULL , + own_url TEXT NOT NULL , + user_to_archive BOOLEAN NOT NULL DEFAULT false , + allow_initialization_by_idp BOOLEAN NOT NULL DEFAULT false , + signed_request BOOLEAN NOT NULL DEFAULT true , + force_authn BOOLEAN NOT NULL DEFAULT false , + entity_id TEXT NOT NULL DEFAULT '{ownUrl}/saml/metadata', + cookie_secure BOOLEAN NOT NULL DEFAULT false , + login_failed_url TEXT NOT NULL DEFAULT '{ownUrl}/noLogin' ) ; CREATE TABLE IF NOT EXISTS saml_sp.attribute_map ( -- SAML session attribute names. - id INT PRIMARY KEY NOT NULL DEFAULT 1 REFERENCES saml_sp.basic_config(id) ON UPDATE CASCADE , + id INT PRIMARY KEY NOT NULL DEFAULT 1 REFERENCES saml_sp.config(id) ON UPDATE CASCADE , email TEXT NOT NULL DEFAULT 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn', first_name TEXT DEFAULT NULL , last_name TEXT DEFAULT NULL , phone TEXT DEFAULT NULL ) ; -CREATE TABLE IF NOT EXISTS saml_sp.advanced_config ( - id INT PRIMARY KEY NOT NULL DEFAULT 1 REFERENCES saml_sp.basic_config(id) ON UPDATE CASCADE, - allow_initialization_by_idp BOOLEAN NOT NULL DEFAULT false , - signed_request BOOLEAN NOT NULL DEFAULT true , - force_authn BOOLEAN NOT NULL DEFAULT false , - entity_id TEXT NOT NULL DEFAULT '{ownUrl}/saml/metadata' , - cookie_secure BOOLEAN NOT NULL DEFAULT false , - login_failed_url TEXT NOT NULL DEFAULT '{ownUrl}/noLogin' -) ; - CREATE TABLE IF NOT EXISTS saml_sp.permissions ( - id INT PRIMARY KEY NOT NULL DEFAULT 1 REFERENCES saml_sp.basic_config(id) ON UPDATE CASCADE, + id INT PRIMARY KEY NOT NULL DEFAULT 1 REFERENCES saml_sp.config(id) ON UPDATE CASCADE, default_system_role TEXT NOT NULL DEFAULT 'System user' , -- reference to is maybe a bad idea (due to the new ACL) default_proj_role TEXT NOT NULL DEFAULT 'Project user' , system_role_saml_attribute TEXT , diff --git a/eliona/single_sign_on.go b/eliona/single_sign_on.go index 00f076d..2443d1a 100644 --- a/eliona/single_sign_on.go +++ b/eliona/single_sign_on.go @@ -230,7 +230,7 @@ func (s *SingleSignOn) setUserPermissions(userId *string) error { permissions *apiserver.Permissions ) - permissions, err = conf.GetPermissionSettings(context.Background()) + permissions, err = conf.GetPermissionMapping(context.Background()) if err != nil { return err } diff --git a/go.mod b/go.mod index 125fe14..1efb60a 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/zenazn/goji v1.0.1 golang.org/x/crypto v0.18.0 golang.org/x/net v0.15.0 + gopkg.in/yaml.v3 v3.0.1 ) // Bugfix see: https://github.com/volatiletech/sqlboiler/blob/91c4f335dd886d95b03857aceaf17507c46f9ec5/README.md diff --git a/go.sum b/go.sum index 0f5a690..bebe871 100644 --- a/go.sum +++ b/go.sum @@ -1066,6 +1066,7 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= diff --git a/openapi.yaml b/openapi.yaml index b06d541..d90225d 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -63,7 +63,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Active' + $ref: "#/components/schemas/Active" /sso/auth: get: @@ -94,71 +94,38 @@ paths: "302": description: SAML response returned from the IdP redirected to the auth endpoint to logout - /configuration/basic: + /configuration: get: tags: - Configuration - summary: Get Basic Configurations - description: Get all the Basic Configuration which the SAML SP needs to work. - operationId: getBasicConfiguration + summary: Get Configurations + description: Get all the Configuration which the SAML SP needs to work. + operationId: getConfiguration responses: "200": - description: Successfully returned all basic configuration + description: Successfully returned all configuration content: application/json: schema: - $ref: '#/components/schemas/BasicConfiguration' + $ref: "#/components/schemas/Configuration" put: tags: - Configuration - summary: Creates or Update Basic Configuration - description: Creates or Update the Basic Configuration which the SAML SP needs to work. - operationId: putBasicConfiguration + summary: Creates or Update Configuration + description: Creates or Update the Configuration which the SAML SP needs to work. + operationId: putConfiguration requestBody: content: application/json: schema: - $ref: '#/components/schemas/BasicConfiguration' + $ref: "#/components/schemas/Configuration" responses: "200": - description: Successfully created / updated the basic configuration + description: Successfully created / updated the configuration content: application/json: schema: - $ref: '#/components/schemas/BasicConfiguration' - - /configuration/advanced: - get: - tags: - - Configuration - summary: Get Advanced Configuration - description: Get all the Advanced Configuration for the SAML SP (optional options). - operationId: getAdvancedConfiguration - responses: - "200": - description: Successfully returned all advanced configuration - content: - application/json: - schema: - $ref: '#/components/schemas/AdvancedConfiguration' - put: - tags: - - Configuration - summary: Creates or Update Advanced Configuration - description: Creates or Update the Advanced Configuration for the SAML SP (optional options). - operationId: putAdvancedConfiguration - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/AdvancedConfiguration' - responses: - "200": - description: Successfully created / updated the advanced configuration - content: - application/json: - schema: - $ref: '#/components/schemas/AdvancedConfiguration' + $ref: "#/components/schemas/Configuration" /configuration/attribute-mapping: get: @@ -173,7 +140,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/AttributeMap' + $ref: "#/components/schemas/AttributeMap" put: tags: - Configuration @@ -184,14 +151,14 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/AttributeMap' + $ref: "#/components/schemas/AttributeMap" responses: "200": description: Successfully created / updated the attribute mapping configuration content: application/json: schema: - $ref: '#/components/schemas/AttributeMap' + $ref: "#/components/schemas/AttributeMap" /configuration/permission-mapping: get: @@ -206,7 +173,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Permissions' + $ref: "#/components/schemas/Permissions" put: tags: - Configuration @@ -217,14 +184,14 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Permissions' + $ref: "#/components/schemas/Permissions" responses: "200": description: Successfully created / updated the permission mapping configuration content: application/json: schema: - $ref: '#/components/schemas/Permissions' + $ref: "#/components/schemas/Permissions" /version: get: @@ -258,9 +225,9 @@ paths: components: schemas: - BasicConfiguration: + Configuration: type: object - description: The Basic Configurations for running a SAML 2.0 Service Provider + description: The Configurations for running a SAML 2.0 Service Provider properties: id: type: integer @@ -281,8 +248,7 @@ components: type: string nullable: false readOnly: false - example: - "-----BEGIN CERTIFICATE----- + example: "-----BEGIN CERTIFICATE----- MIIEGzCCAwOgAwIBAgIUc/HUg5byijWRmU7Qqe5OSQtiNOwwDQYJKoZIhvcNAQEL BQAwgZwxCzAJBgNVBAYTAkNIMQ8wDQYDVQQIDAZadXJpY2gxEzARBgNVBAcMCldp bnRlcnRodXIxEjAQBgNVBAoMCUxlaWNvbSBBRzEXMBUGA1UECwwOU21hcnQgQnVp @@ -311,8 +277,7 @@ components: type: string nullable: false readOnly: false - example: - "-----BEGIN PRIVATE KEY----- + example: "-----BEGIN PRIVATE KEY----- **************************************************************** **************************************************************** **************************************************************** @@ -361,19 +326,6 @@ components: readOnly: false default: false example: false - - AdvancedConfiguration: - type: object - description: Advanced options to fine tune this SAML Service Provider (SP) - properties: - id: - type: integer - format: int32 - description: Configuration Id refer to basic config's id. Can only be 1 - nullable: false - readOnly: true - default: 1 - example: 1 allowInitializationByIdp: description: If the configuration is enabled or not type: boolean @@ -396,7 +348,7 @@ components: default: false example: false entityId: - description: If you have to use a customized Entity Id, you can overwrite it here. Normaly the default value can be leave as it is. + description: If you have to use a customized Entity Id, you can overwrite it here. Normally the default value can be left as it is. type: string nullable: false readOnly: false @@ -424,7 +376,7 @@ components: id: type: integer format: int32 - description: Configuration Id refer to basic config's id. Can only be 1 + description: Configuration Id refer to config's id. Can only be 1 nullable: false readOnly: true default: 1 @@ -465,7 +417,7 @@ components: id: type: integer format: int32 - description: Configuration Id refer to basic config's id. Can only be 1 + description: Configuration Id refer to config's id. Can only be 1 nullable: false readOnly: true default: 1 @@ -486,22 +438,22 @@ components: type: string nullable: true readOnly: false - example: 'systemRightsSamlAttribute' + example: "systemRightsSamlAttribute" system_role_map: type: array items: - $ref: '#/components/schemas/RoleMap' + $ref: "#/components/schemas/RoleMap" nullable: true readOnly: false proj_role_saml_attribute: type: string nullable: true readOnly: false - example: 'projectRightsSamlAttribute' + example: "projectRightsSamlAttribute" proj_role_map: type: array items: - $ref: '#/components/schemas/RoleMap' + $ref: "#/components/schemas/RoleMap" nullable: true readOnly: false @@ -516,7 +468,7 @@ components: samlValue: type: string nullable: false - example: 'Administrator' + example: "Administrator" Active: type: object diff --git a/saml/service_provider.go b/saml/service_provider.go index 1827340..a0ea910 100644 --- a/saml/service_provider.go +++ b/saml/service_provider.go @@ -57,7 +57,7 @@ func NewServiceProviderAdvanced(certificate string, privateKey string, baseUrl s idpMeta, err := samlsp.ParseMetadata(idpMetadata) if err != nil { log.Warn(LOG_REGIO, "cannot parse metadata. "+ - "continiue without, but cannot operate with a IdP in current state! ... %v", err) + "continuing without, but cannot operate with a IdP in current state! ... %v", err) // return nil, err } diff --git a/utils/testing.go b/utils/testing.go index 9e3c5eb..3ae1133 100644 --- a/utils/testing.go +++ b/utils/testing.go @@ -21,12 +21,18 @@ import ( "github.com/eliona-smart-building-assistant/go-utils/log" ) -func CreateRandomApiBasicConfig() apiserver.BasicConfiguration { - var basicCnf apiserver.BasicConfiguration = apiserver.BasicConfiguration{ - Id: 1, - Enable: RandomBoolean(), - OwnUrl: RandomUrl(), - UserToArchive: RandomBoolean(), +func CreateRandomApiConfig() apiserver.Configuration { + var basicCnf apiserver.Configuration = apiserver.Configuration{ + Id: 1, + Enable: RandomBoolean(), + OwnUrl: RandomUrl(), + UserToArchive: RandomBoolean(), + AllowInitializationByIdp: RandomBoolean(), + SignedRequest: RandomBoolean(), + ForceAuthn: RandomBoolean(), + EntityId: RandomUrl() + "/" + RandomCharacter(5, false), + CookieSecure: RandomBoolean(), + LoginFailedUrl: RandomUrl() + "/" + RandomCharacter(RandomInt(2, 10), false), } cert, key, err := CreateSelfsignedX509Certificate(RandomInt(10, 1000), 2048, nil, nil) @@ -47,18 +53,6 @@ func CreateRandomApiBasicConfig() apiserver.BasicConfiguration { return basicCnf } -func CreateRandomApiAdvancedConfig() apiserver.AdvancedConfiguration { - return apiserver.AdvancedConfiguration{ - Id: 1, - AllowInitializationByIdp: RandomBoolean(), - SignedRequest: RandomBoolean(), - ForceAuthn: RandomBoolean(), - EntityId: RandomUrl() + "/" + RandomCharacter(5, false), - CookieSecure: RandomBoolean(), - LoginFailedUrl: RandomUrl() + "/" + RandomCharacter(RandomInt(2, 10), false), - } -} - func CreateRandomApiAttributeMap() apiserver.AttributeMap { mapping := apiserver.AttributeMap{ Id: 1,