diff --git a/codegen/assets/templates/gocode/store/interfaces.go.tpl b/codegen/assets/templates/gocode/store/interfaces.go.tpl index 0e767f1cf..16079e9c2 100644 --- a/codegen/assets/templates/gocode/store/interfaces.go.tpl +++ b/codegen/assets/templates/gocode/store/interfaces.go.tpl @@ -37,7 +37,7 @@ type ( Tx(context.Context, func(context.Context, Storer) error) error // Upgrade store's schema to the latest version - Upgrade(context.Context, *zap.Logger) error + Upgrade(context.Context) error {{- range .types }} {{ .expIdentPlural }} diff --git a/codegen/assets/templates/gocode/store/rdbms/aux_types.go.tpl b/codegen/assets/templates/gocode/store/rdbms/aux_types.go.tpl index 74990bead..6721e9c6c 100644 --- a/codegen/assets/templates/gocode/store/rdbms/aux_types.go.tpl +++ b/codegen/assets/templates/gocode/store/rdbms/aux_types.go.tpl @@ -46,7 +46,7 @@ func (aux {{ .auxIdent }}) decode() (res *{{ .goType }}, _ error) { // scans row and fills {{ .auxIdent }} fields // // This function is auto-generated -func (aux *{{ .auxIdent }})scan(row scalable) (error) { +func (aux *{{ .auxIdent }})scan(row scanner) (error) { return row.Scan( {{- range .auxStruct }} &aux.{{ .expIdent }}, diff --git a/codegen/assets/templates/gocode/store/rdbms/rdbms.go.tpl b/codegen/assets/templates/gocode/store/rdbms/rdbms.go.tpl index 984183373..4b9546bbc 100644 --- a/codegen/assets/templates/gocode/store/rdbms/rdbms.go.tpl +++ b/codegen/assets/templates/gocode/store/rdbms/rdbms.go.tpl @@ -44,7 +44,7 @@ func (s *Store) Create{{ .expIdent }}(ctx context.Context, {{ template "extraArg return } - if err = s.Exec(ctx, {{ .ident }}InsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, {{ .ident }}InsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -62,7 +62,7 @@ func (s *Store) Update{{ .expIdent }}(ctx context.Context, {{ template "extraArg return } - if err = s.Exec(ctx, {{ .ident }}UpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, {{ .ident }}UpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -79,7 +79,7 @@ func (s *Store) Upsert{{ .expIdent }}(ctx context.Context, {{ template "extraArg return } - if err = s.Exec(ctx, {{ .ident }}UpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, {{ .ident }}UpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -92,7 +92,7 @@ func (s *Store) Upsert{{ .expIdent }}(ctx context.Context, {{ template "extraArg // This function is auto-generated func (s *Store) Delete{{ .expIdent }}(ctx context.Context, {{ template "extraArgs" .ident }} rr ...*{{ .goType }}) (err error) { for i := range rr { - if err = s.Exec(ctx, {{ .ident }}DeleteQuery(s.config.Dialect, {{ .ident }}PrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, {{ .ident }}DeleteQuery(s.Dialect, {{ .ident }}PrimaryKeys(rr[i]))); err != nil { return } } @@ -104,7 +104,7 @@ func (s *Store) Delete{{ .expIdent }}(ctx context.Context, {{ template "extraArg // // This function is auto-generated func (s *Store) {{ .api.deleteByPK.expFnIdent }}(ctx context.Context, {{ template "extraArgs" .ident }} {{ range .api.deleteByPK.primaryKeys }}{{ .ident }} {{ .goType }},{{ end }}) error { - return s.Exec(ctx, {{ .ident }}DeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, {{ .ident }}DeleteQuery(s.Dialect, goqu.Ex{ {{- range .api.deleteByPK.primaryKeys }} {{ printf "%q" .storeIdent }}: {{ .ident }}, {{- end }} @@ -112,8 +112,8 @@ func (s *Store) {{ .api.deleteByPK.expFnIdent }}(ctx context.Context, {{ templat } // Truncate{{ .expIdentPlural }} Deletes all rows from the {{ .ident }} collection -func (s *Store) Truncate{{ .expIdentPlural }}(ctx context.Context, {{ template "extraArgs" .ident }}) error { - return s.Exec(ctx, {{ .ident }}TruncateQuery(s.config.Dialect)) +func (s Store) Truncate{{ .expIdentPlural }}(ctx context.Context, {{ template "extraArgs" .ident }}) error { + return s.Exec(ctx, {{ .ident }}TruncateQuery(s.Dialect)) } // Search{{ .expIdentPlural }} returns (filtered) set of {{ .expIdentPlural }} @@ -324,9 +324,9 @@ func (s *Store) Query{{ .expIdentPlural }}( {{ end }} ) - if s.config.Filters.{{ .expIdent }} != nil { + if s.Filters.{{ .expIdent }} != nil { // extended filter set - tExpr, f, err = s.config.Filters.{{ .expIdent }}(s, f) + tExpr, f, err = s.Filters.{{ .expIdent }}(s, f) } else { // using generated filter tExpr, f, err = {{ .expIdent }}Filter(f) @@ -351,7 +351,7 @@ func (s *Store) Query{{ .expIdentPlural }}( {{ end }} - query := {{ .ident }}SelectQuery(s.config.Dialect).Where(expr...) + query := {{ .ident }}SelectQuery(s.Dialect).Where(expr...) {{ if .features.sorting }} // sorting feature is enabled @@ -437,10 +437,10 @@ func (s *Store) Query{{ .expIdentPlural }}( var ( rows *sql.Rows aux = new({{ .auxIdent }}) - lookup = {{ .ident }}SelectQuery(s.config.Dialect).Where( + lookup = {{ .ident }}SelectQuery(s.Dialect).Where( {{- range .args }} {{- if .ignoreCase }} - s.config.Functions.LOWER(goqu.I({{ printf "%q" .storeIdent }})).Eq(strings.ToLower({{ .ident }})), + s.Functions.LOWER(goqu.I({{ printf "%q" .storeIdent }})).Eq(strings.ToLower({{ .ident }})), {{- else }} goqu.I({{ printf "%q" .storeIdent }}).Eq({{ .ident }}), {{- end }} diff --git a/federation/exposed-module.cue b/federation/module-exposed.cue similarity index 100% rename from federation/exposed-module.cue rename to federation/module-exposed.cue diff --git a/store/adapters/rdbms/aux_types.gen.go b/store/adapters/rdbms/aux_types.gen.go index 656c10b71..12f4a9aa6 100644 --- a/store/adapters/rdbms/aux_types.gen.go +++ b/store/adapters/rdbms/aux_types.gen.go @@ -621,7 +621,7 @@ func (aux auxActionlog) decode() (res *actionlogType.Action, _ error) { // scans row and fills auxActionlog fields // // This function is auto-generated -func (aux *auxActionlog) scan(row scalable) error { +func (aux *auxActionlog) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Timestamp, @@ -682,7 +682,7 @@ func (aux auxApigwFilter) decode() (res *systemType.ApigwFilter, _ error) { // scans row and fills auxApigwFilter fields // // This function is auto-generated -func (aux *auxApigwFilter) scan(row scalable) error { +func (aux *auxApigwFilter) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Route, @@ -742,7 +742,7 @@ func (aux auxApigwRoute) decode() (res *systemType.ApigwRoute, _ error) { // scans row and fills auxApigwRoute fields // // This function is auto-generated -func (aux *auxApigwRoute) scan(row scalable) error { +func (aux *auxApigwRoute) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Endpoint, @@ -795,7 +795,7 @@ func (aux auxApplication) decode() (res *systemType.Application, _ error) { // scans row and fills auxApplication fields // // This function is auto-generated -func (aux *auxApplication) scan(row scalable) error { +func (aux *auxApplication) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Name, @@ -847,7 +847,7 @@ func (aux auxAttachment) decode() (res *systemType.Attachment, _ error) { // scans row and fills auxAttachment fields // // This function is auto-generated -func (aux *auxAttachment) scan(row scalable) error { +func (aux *auxAttachment) scan(row scanner) error { return row.Scan( &aux.ID, &aux.OwnerID, @@ -918,7 +918,7 @@ func (aux auxAuthClient) decode() (res *systemType.AuthClient, _ error) { // scans row and fills auxAuthClient fields // // This function is auto-generated -func (aux *auxAuthClient) scan(row scalable) error { +func (aux *auxAuthClient) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -966,7 +966,7 @@ func (aux auxAuthConfirmedClient) decode() (res *systemType.AuthConfirmedClient, // scans row and fills auxAuthConfirmedClient fields // // This function is auto-generated -func (aux *auxAuthConfirmedClient) scan(row scalable) error { +func (aux *auxAuthConfirmedClient) scan(row scanner) error { return row.Scan( &aux.UserID, &aux.ClientID, @@ -1014,7 +1014,7 @@ func (aux auxAuthOa2token) decode() (res *systemType.AuthOa2token, _ error) { // scans row and fills auxAuthOa2token fields // // This function is auto-generated -func (aux *auxAuthOa2token) scan(row scalable) error { +func (aux *auxAuthOa2token) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Code, @@ -1062,7 +1062,7 @@ func (aux auxAuthSession) decode() (res *systemType.AuthSession, _ error) { // scans row and fills auxAuthSession fields // // This function is auto-generated -func (aux *auxAuthSession) scan(row scalable) error { +func (aux *auxAuthSession) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Data, @@ -1120,7 +1120,7 @@ func (aux auxAutomationSession) decode() (res *automationType.Session, _ error) // scans row and fills auxAutomationSession fields // // This function is auto-generated -func (aux *auxAutomationSession) scan(row scalable) error { +func (aux *auxAutomationSession) scan(row scanner) error { return row.Scan( &aux.ID, &aux.WorkflowID, @@ -1189,7 +1189,7 @@ func (aux auxAutomationTrigger) decode() (res *automationType.Trigger, _ error) // scans row and fills auxAutomationTrigger fields // // This function is auto-generated -func (aux *auxAutomationTrigger) scan(row scalable) error { +func (aux *auxAutomationTrigger) scan(row scanner) error { return row.Scan( &aux.ID, &aux.WorkflowID, @@ -1264,7 +1264,7 @@ func (aux auxAutomationWorkflow) decode() (res *automationType.Workflow, _ error // scans row and fills auxAutomationWorkflow fields // // This function is auto-generated -func (aux *auxAutomationWorkflow) scan(row scalable) error { +func (aux *auxAutomationWorkflow) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -1327,7 +1327,7 @@ func (aux auxComposeAttachment) decode() (res *composeType.Attachment, _ error) // scans row and fills auxComposeAttachment fields // // This function is auto-generated -func (aux *auxComposeAttachment) scan(row scalable) error { +func (aux *auxComposeAttachment) scan(row scanner) error { return row.Scan( &aux.ID, &aux.OwnerID, @@ -1377,7 +1377,7 @@ func (aux auxComposeChart) decode() (res *composeType.Chart, _ error) { // scans row and fills auxComposeChart fields // // This function is auto-generated -func (aux *auxComposeChart) scan(row scalable) error { +func (aux *auxComposeChart) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -1424,7 +1424,7 @@ func (aux auxComposeModule) decode() (res *composeType.Module, _ error) { // scans row and fills auxComposeModule fields // // This function is auto-generated -func (aux *auxComposeModule) scan(row scalable) error { +func (aux *auxComposeModule) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -1487,7 +1487,7 @@ func (aux auxComposeModuleField) decode() (res *composeType.ModuleField, _ error // scans row and fills auxComposeModuleField fields // // This function is auto-generated -func (aux *auxComposeModuleField) scan(row scalable) error { +func (aux *auxComposeModuleField) scan(row scanner) error { return row.Scan( &aux.ID, &aux.ModuleID, @@ -1542,7 +1542,7 @@ func (aux auxComposeNamespace) decode() (res *composeType.Namespace, _ error) { // scans row and fills auxComposeNamespace fields // // This function is auto-generated -func (aux *auxComposeNamespace) scan(row scalable) error { +func (aux *auxComposeNamespace) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Slug, @@ -1601,7 +1601,7 @@ func (aux auxComposePage) decode() (res *composeType.Page, _ error) { // scans row and fills auxComposePage fields // // This function is auto-generated -func (aux *auxComposePage) scan(row scalable) error { +func (aux *auxComposePage) scan(row scanner) error { return row.Scan( &aux.ID, &aux.SelfID, @@ -1658,7 +1658,7 @@ func (aux auxComposeRecord) decode() (res *composeType.Record, _ error) { // scans row and fills auxComposeRecord fields // // This function is auto-generated -func (aux *auxComposeRecord) scan(row scalable) error { +func (aux *auxComposeRecord) scan(row scanner) error { return row.Scan( &aux.ID, &aux.ModuleID, @@ -1703,7 +1703,7 @@ func (aux auxComposeRecordValue) decode() (res *composeType.RecordValue, _ error // scans row and fills auxComposeRecordValue fields // // This function is auto-generated -func (aux *auxComposeRecordValue) scan(row scalable) error { +func (aux *auxComposeRecordValue) scan(row scanner) error { return row.Scan( &aux.RecordID, &aux.Name, @@ -1754,7 +1754,7 @@ func (aux auxCredential) decode() (res *systemType.Credential, _ error) { // scans row and fills auxCredential fields // // This function is auto-generated -func (aux *auxCredential) scan(row scalable) error { +func (aux *auxCredential) scan(row scanner) error { return row.Scan( &aux.ID, &aux.OwnerID, @@ -1814,7 +1814,7 @@ func (aux auxFederationExposedModule) decode() (res *federationType.ExposedModul // scans row and fills auxFederationExposedModule fields // // This function is auto-generated -func (aux *auxFederationExposedModule) scan(row scalable) error { +func (aux *auxFederationExposedModule) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -1860,7 +1860,7 @@ func (aux auxFederationModuleMapping) decode() (res *federationType.ModuleMappin // scans row and fills auxFederationModuleMapping fields // // This function is auto-generated -func (aux *auxFederationModuleMapping) scan(row scalable) error { +func (aux *auxFederationModuleMapping) scan(row scanner) error { return row.Scan( &aux.NodeID, &aux.FederationModuleID, @@ -1916,7 +1916,7 @@ func (aux auxFederationNode) decode() (res *federationType.Node, _ error) { // scans row and fills auxFederationNode fields // // This function is auto-generated -func (aux *auxFederationNode) scan(row scalable) error { +func (aux *auxFederationNode) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Name, @@ -1963,7 +1963,7 @@ func (aux auxFederationNodeSync) decode() (res *federationType.NodeSync, _ error // scans row and fills auxFederationNodeSync fields // // This function is auto-generated -func (aux *auxFederationNodeSync) scan(row scalable) error { +func (aux *auxFederationNodeSync) scan(row scanner) error { return row.Scan( &aux.NodeID, &aux.ModuleID, @@ -2015,7 +2015,7 @@ func (aux auxFederationSharedModule) decode() (res *federationType.SharedModule, // scans row and fills auxFederationSharedModule fields // // This function is auto-generated -func (aux *auxFederationSharedModule) scan(row scalable) error { +func (aux *auxFederationSharedModule) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -2060,7 +2060,7 @@ func (aux auxFlag) decode() (res *flagType.Flag, _ error) { // scans row and fills auxFlag fields // // This function is auto-generated -func (aux *auxFlag) scan(row scalable) error { +func (aux *auxFlag) scan(row scanner) error { return row.Scan( &aux.Kind, &aux.ResourceID, @@ -2096,7 +2096,7 @@ func (aux auxLabel) decode() (res *labelsType.Label, _ error) { // scans row and fills auxLabel fields // // This function is auto-generated -func (aux *auxLabel) scan(row scalable) error { +func (aux *auxLabel) scan(row scanner) error { return row.Scan( &aux.Kind, &aux.ResourceID, @@ -2143,7 +2143,7 @@ func (aux auxQueue) decode() (res *systemType.Queue, _ error) { // scans row and fills auxQueue fields // // This function is auto-generated -func (aux *auxQueue) scan(row scalable) error { +func (aux *auxQueue) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Consumer, @@ -2186,7 +2186,7 @@ func (aux auxQueueMessage) decode() (res *systemType.QueueMessage, _ error) { // scans row and fills auxQueueMessage fields // // This function is auto-generated -func (aux *auxQueueMessage) scan(row scalable) error { +func (aux *auxQueueMessage) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Queue, @@ -2222,7 +2222,7 @@ func (aux auxRbacRule) decode() (res *rbacType.Rule, _ error) { // scans row and fills auxRbacRule fields // // This function is auto-generated -func (aux *auxRbacRule) scan(row scalable) error { +func (aux *auxRbacRule) scan(row scanner) error { return row.Scan( &aux.RoleID, &aux.Resource, @@ -2275,7 +2275,7 @@ func (aux auxReminder) decode() (res *systemType.Reminder, _ error) { // scans row and fills auxReminder fields // // This function is auto-generated -func (aux *auxReminder) scan(row scalable) error { +func (aux *auxReminder) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Resource, @@ -2337,7 +2337,7 @@ func (aux auxReport) decode() (res *systemType.Report, _ error) { // scans row and fills auxReport fields // // This function is auto-generated -func (aux *auxReport) scan(row scalable) error { +func (aux *auxReport) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -2385,7 +2385,7 @@ func (aux auxResourceActivity) decode() (res *discoveryType.ResourceActivity, _ // scans row and fills auxResourceActivity fields // // This function is auto-generated -func (aux *auxResourceActivity) scan(row scalable) error { +func (aux *auxResourceActivity) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Timestamp, @@ -2438,7 +2438,7 @@ func (aux auxResourceTranslation) decode() (res *systemType.ResourceTranslation, // scans row and fills auxResourceTranslation fields // // This function is auto-generated -func (aux *auxResourceTranslation) scan(row scalable) error { +func (aux *auxResourceTranslation) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Lang, @@ -2489,7 +2489,7 @@ func (aux auxRole) decode() (res *systemType.Role, _ error) { // scans row and fills auxRole fields // // This function is auto-generated -func (aux *auxRole) scan(row scalable) error { +func (aux *auxRole) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Name, @@ -2524,7 +2524,7 @@ func (aux auxRoleMember) decode() (res *systemType.RoleMember, _ error) { // scans row and fills auxRoleMember fields // // This function is auto-generated -func (aux *auxRoleMember) scan(row scalable) error { +func (aux *auxRoleMember) scan(row scanner) error { return row.Scan( &aux.UserID, &aux.RoleID, @@ -2559,7 +2559,7 @@ func (aux auxSettingValue) decode() (res *systemType.SettingValue, _ error) { // scans row and fills auxSettingValue fields // // This function is auto-generated -func (aux *auxSettingValue) scan(row scalable) error { +func (aux *auxSettingValue) scan(row scanner) error { return row.Scan( &aux.Name, &aux.OwnedBy, @@ -2611,7 +2611,7 @@ func (aux auxTemplate) decode() (res *systemType.Template, _ error) { // scans row and fills auxTemplate fields // // This function is auto-generated -func (aux *auxTemplate) scan(row scalable) error { +func (aux *auxTemplate) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, @@ -2670,7 +2670,7 @@ func (aux auxUser) decode() (res *systemType.User, _ error) { // scans row and fills auxUser fields // // This function is auto-generated -func (aux *auxUser) scan(row scalable) error { +func (aux *auxUser) scan(row scanner) error { return row.Scan( &aux.ID, &aux.Handle, diff --git a/store/adapters/rdbms/config.go b/store/adapters/rdbms/config.go index 4eb0abb5c..9cb87ebd2 100644 --- a/store/adapters/rdbms/config.go +++ b/store/adapters/rdbms/config.go @@ -7,31 +7,14 @@ import ( "strconv" "strings" "time" - - "github.com/cortezaproject/corteza-server/store" - "github.com/cortezaproject/corteza-server/store/adapters/rdbms/schema" - "github.com/doug-martin/goqu/v9" - "github.com/doug-martin/goqu/v9/exp" ) type ( - txRetryOnErrHandler func(int, error) bool - - Functions struct { - // returns lower case text - LOWER func(interface{}) exp.SQLFunctionExpression - - // returns date part of the input (YYYY-MM-DD) - DATE func(interface{}) exp.SQLFunctionExpression - } - - Config struct { + ConnConfig struct { DriverName string DataSourceName string DBName string - Dialect goqu.DialectWrapper - // MaxOpenConns sets maximum number of open connections to the database // defaults to same value as set in the db/sql MaxOpenConns int @@ -53,33 +36,8 @@ type ( // ConnTryTimeout sets timeout per try ConnTryTimeout time.Duration - // ConnTryMax maximum number of retrys for getting the connection + // ConnTryMax maximum number of retries for getting the connection ConnTryMax int - - // Disable transactions - TxDisabled bool - - // How many times should we retry failed transaction? - TxMaxRetries int - - // TxRetryErrHandler should return true if transaction should be retried - // - // Because retry algorithm varies between concrete rdbms implementations - // - // Handler must return true if failed transaction should be replied - // and false if we're safe to terminate it - TxRetryErrHandler txRetryOnErrHandler - - ErrorHandler store.ErrorHandler - - Functions Functions - - // additional per-resource filters used when searching - // these filters can modify expression used for querying the database - Filters extendedFilters - - // schema upgrade interface - Upgrader schema.Upgrader } ) @@ -88,30 +46,11 @@ var ( ) // MaskedDSN replaces username & password from DSN string dso it's usable for logging -func (c *Config) MaskedDSN() string { +func (c *ConnConfig) MaskedDSN() string { return dsnMasker.ReplaceAllString(c.DataSourceName, "$1****$2:$3****$4@") } -func (c *Config) SetDefaults() { - if c.TxMaxRetries == 0 { - c.TxMaxRetries = TxRetryHardLimit - } - - //if c.TxRetryErrHandler == nil { - // // Default transaction retry handler - // c.TxRetryErrHandler = TxNoRetry - //} - // - //if c.ErrorHandler == nil { - // c.ErrorHandler = ErrHandlerFallthrough - //} - // - //if c.UpsertBuilder == nil { - // c.UpsertBuilder = UpsertBuilder - //} - - // ** ** ** ** ** ** ** ** ** ** ** ** ** ** - +func (c *ConnConfig) SetDefaults() { if c.MaxIdleConns == 0 { // Same as default in the db/sql c.MaxIdleConns = 32 @@ -144,35 +83,11 @@ func (c *Config) SetDefaults() { if c.ConnTryMax == 0 { c.ConnTryMax = 99 } - - //if c.TriggerHandlers == nil { - // c.TriggerHandlers = TriggerHandlers{} - //} - // - //if c.SqlSortHandler == nil { - // c.SqlSortHandler = SqlSortHandler - //} - - //if c.Functions == nil { - // c.Functions = func(ident string, args ...interface{}) (*db.RawExpr, error) { - // switch strings.ToUpper(ident) { - // case "LOWER": - // if len(args) != 1 { - // return nil, errors.Internal("LOWER() function expects exactly 1 argument") - // } - // return db.Raw("LOWER(?)", args[0]), nil - // } - // - // return nil, errors.Internal("unknown function %q", ident) - // } - //} - c.Functions.SetDefaults() - c.Filters.SetDefaults() } // ParseExtra parses extra params (params starting with *) // from DSN's querystring (after ?) -func (c *Config) ParseExtra() (err error) { +func (c *ConnConfig) ParseExtra() (err error) { // Make sure we only got qs const q = "?" var ( @@ -253,18 +168,3 @@ func (c *Config) ParseExtra() (err error) { return nil } - -func (f *Functions) SetDefaults() { - if f.LOWER == nil { - f.LOWER = func(value interface{}) exp.SQLFunctionExpression { - return goqu.Func("LOWER", value) - } - } - - if f.DATE == nil { - f.DATE = func(value interface{}) exp.SQLFunctionExpression { - return goqu.Func("DATE", value) - } - } - -} diff --git a/store/adapters/rdbms/connect.go b/store/adapters/rdbms/connect.go index 98f03f258..dfe1403f0 100644 --- a/store/adapters/rdbms/connect.go +++ b/store/adapters/rdbms/connect.go @@ -6,26 +6,11 @@ import ( "fmt" "time" - "github.com/cortezaproject/corteza-server/pkg/healthcheck" "github.com/cortezaproject/corteza-server/pkg/sentry" "github.com/jmoiron/sqlx" "go.uber.org/zap" ) -type ( - dbLayer interface { - sqlx.ExecerContext - SelectContext(context.Context, interface{}, string, ...interface{}) error - GetContext(context.Context, interface{}, string, ...interface{}) error - QueryRowContext(context.Context, string, ...interface{}) *sql.Row - QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) - } - - dbTransactionMaker interface { - BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error) - } -) - const ( // TxRetryHardLimit is the absolute maximum retries we'll allow TxRetryHardLimit = 100 @@ -38,74 +23,33 @@ const ( MaxLimit = 1000 ) -// Connect is called from the adapter's Connect function +// Connect is rdbms' package connector // -// It is intentionally not compatible with store.ConnectorFn -// and can not be used to register -func Connect(ctx context.Context, cfg *Config) (s *Store, err error) { - return s, func() error { - if err = cfg.ParseExtra(); err != nil { - return err - } - - cfg.SetDefaults() - s = &Store{ - config: cfg, - } - - return s.Connect(ctx) - }() -} - -// WithTx spins up new store instance with transaction -func (s *Store) withTx(tx dbLayer) *Store { - return &Store{ - config: s.config, - //sug: s.sug, - db: tx, - } -} - -func (s Store) DB() dbLayer { - return s.db -} - -func (s *Store) Connect(ctx context.Context) error { - s.log(ctx).Debug("opening connection", zap.String("driver", s.config.DriverName), zap.String("dsn", s.config.MaskedDSN())) - - db, err := sql.Open(s.config.DriverName, s.config.DataSourceName) - if err != nil { - return err - } - - healthcheck.Defaults().Add(dbHealthcheck(db), "Store/RDBMS/"+s.config.DriverName) - - dbx := sqlx.NewDb(db, s.config.DriverName) - s.log(ctx).Debug( - "setting connection parameters", - zap.Int("MaxOpenConns", s.config.MaxOpenConns), - zap.Duration("MaxLifetime", s.config.ConnMaxLifetime), - zap.Int("MaxIdleConns", s.config.MaxIdleConns), - ) - - dbx.SetMaxOpenConns(s.config.MaxOpenConns) - dbx.SetConnMaxLifetime(s.config.ConnMaxLifetime) - dbx.SetMaxIdleConns(s.config.MaxIdleConns) - - if err = s.tryToConnect(ctx, dbx); err != nil { - return err - } - - s.db = dbx - return err -} - -func (s Store) tryToConnect(ctx context.Context, db *sqlx.DB) error { +// Function is called from (store) driver's required connection function +// to open connection and bind it with +func Connect(ctx context.Context, log *zap.Logger, cfg *ConnConfig) (db *sqlx.DB, err error) { var ( connErrCh = make(chan error, 1) - patience = time.Now().Add(s.config.ConnTryPatience) + patience = time.Now().Add(cfg.ConnTryPatience) + base *sql.DB ) + if base, err = sql.Open(cfg.DriverName, cfg.DataSourceName); err != nil { + return + } + + db = sqlx.NewDb(base, cfg.DriverName) + log.Debug( + "setting connection parameters", + zap.Int("MaxOpenConns", cfg.MaxOpenConns), + zap.Duration("MaxLifetime", cfg.ConnMaxLifetime), + zap.Int("MaxIdleConns", cfg.MaxIdleConns), + ) + + db.SetMaxOpenConns(cfg.MaxOpenConns) + db.SetConnMaxLifetime(cfg.ConnMaxLifetime) + db.SetMaxIdleConns(cfg.MaxIdleConns) + go func() { defer sentry.Recover() @@ -113,16 +57,15 @@ func (s Store) tryToConnect(ctx context.Context, db *sqlx.DB) error { err error try = 0 - log = s.log(ctx). - // Make a small adjustment when - // collecting callers from the callstack for this - WithOptions(zap.AddCallerSkip(-2)) + // Make a small adjustment when + // collecting callers from the callstack for this + log = log.WithOptions(zap.AddCallerSkip(-2)) ) for { try++ - if s.config.ConnTryMax <= try { + if cfg.ConnTryMax <= try { connErrCh <- fmt.Errorf("could not connect in %d tries", try) return } @@ -136,7 +79,7 @@ func (s Store) tryToConnect(ctx context.Context, db *sqlx.DB) error { "could not connect to the database", zap.Error(err), zap.Int("try", try), - zap.Float64("delay", s.config.ConnTryBackoffDelay.Seconds()), + zap.Float64("delay", cfg.ConnTryBackoffDelay.Seconds()), ) } @@ -144,7 +87,7 @@ func (s Store) tryToConnect(ctx context.Context, db *sqlx.DB) error { case <-ctx.Done(): // Forced break break - case <-time.After(s.config.ConnTryBackoffDelay): + case <-time.After(cfg.ConnTryBackoffDelay): // Wait before next try continue } @@ -157,18 +100,38 @@ func (s Store) tryToConnect(ctx context.Context, db *sqlx.DB) error { connErrCh <- err }() - to := s.config.ConnTryTimeout * time.Duration(s.config.ConnTryMax*2) + to := cfg.ConnTryTimeout * time.Duration(cfg.ConnTryMax*2) select { - case err := <-connErrCh: - return err + case err = <-connErrCh: + return case <-time.After(to): // Wait before next try - return fmt.Errorf("timedout after %.2fs", to.Seconds()) + return nil, fmt.Errorf("timedout after %.2fs", to.Seconds()) case <-ctx.Done(): - return fmt.Errorf("connection cancelled") + return nil, fmt.Errorf("connection cancelled") } } -func dbHealthcheck(db *sql.DB) func(ctx context.Context) error { +// Connect is called from the adapter's Connect function +// +// It is intentionally not compatible with store.ConnectorFn +// and can not be used to register +//func Connect(ctx context.Context, cfg *ConnConfig) (s *Store, err error) { +// return s, func() error { +// if err = cfg.ParseExtra(); err != nil { +// return err +// } +// +// cfg.SetDefaults() +// s = &Store{ +// config: cfg, +// //schema: ddl.SchemaAPI(s.DB(), ddl.NewCommonDialect()), +// } +// +// return s.Connect(ctx) +// }() +//} + +func dbHealthcheck(db *sqlx.DB) func(ctx context.Context) error { return db.PingContext } diff --git a/store/adapters/rdbms/cursor.go b/store/adapters/rdbms/cursor.go index 8321ff886..3d8795a02 100644 --- a/store/adapters/rdbms/cursor.go +++ b/store/adapters/rdbms/cursor.go @@ -37,6 +37,10 @@ type ( cursorKeyMapper func(string) (KeyMap, error) ) +func Cursor(c *filter.PagingCursor) ([]goqu.Expression, error) { + return cursor(c) +} + func cursor(cursor *filter.PagingCursor) ([]goqu.Expression, error) { sql, args, err := CursorCondition(cursor, nil).ToSql() if err != nil { diff --git a/store/adapters/rdbms/custom_applications.go b/store/adapters/rdbms/custom_applications.go index 7304e02a4..70acc1448 100644 --- a/store/adapters/rdbms/custom_applications.go +++ b/store/adapters/rdbms/custom_applications.go @@ -15,7 +15,7 @@ func (s Store) ApplicationMetrics(ctx context.Context) (_ *systemType.Applicatio Valid uint `db:"valid"` }{} - query = applicationSelectQuery(s.config.Dialect). + query = applicationSelectQuery(s.Dialect). Select(timestampStatExpr("deleted")...) ) @@ -39,7 +39,7 @@ func (s Store) ReorderApplications(ctx context.Context, order []uint64) (err err f = systemType.ApplicationFilter{} query = func(id uint64, weight int) *goqu.UpdateDataset { - return s.config.Dialect. + return s.Dialect. Update(applicationTable). Set(goqu.Record{"weight": weight}). Where(goqu.C("id").Eq(id)) diff --git a/store/adapters/rdbms/custom_auth_oa2tokens.go b/store/adapters/rdbms/custom_auth_oa2tokens.go index 8d91be65d..2c1aa1867 100644 --- a/store/adapters/rdbms/custom_auth_oa2tokens.go +++ b/store/adapters/rdbms/custom_auth_oa2tokens.go @@ -8,21 +8,21 @@ import ( ) func (s Store) DeleteExpiredAuthOA2Tokens(ctx context.Context) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.C("expires_at").Lt(time.Now()))) + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.C("expires_at").Lt(time.Now()))) } func (s Store) DeleteAuthOA2TokenByCode(ctx context.Context, code string) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.C("code").Eq(code))) + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.C("code").Eq(code))) } func (s Store) DeleteAuthOA2TokenByAccess(ctx context.Context, access string) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.C("access").Eq(access))) + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.C("access").Eq(access))) } func (s Store) DeleteAuthOA2TokenByRefresh(ctx context.Context, refresh string) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.C("refresh").Eq(refresh))) + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.C("refresh").Eq(refresh))) } func (s Store) DeleteAuthOA2TokenByUserID(ctx context.Context, userID uint64) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.C("rel_user").Eq(userID))) + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.C("rel_user").Eq(userID))) } diff --git a/store/adapters/rdbms/custom_auth_sessions.go b/store/adapters/rdbms/custom_auth_sessions.go index b043cdf79..90ab913ec 100644 --- a/store/adapters/rdbms/custom_auth_sessions.go +++ b/store/adapters/rdbms/custom_auth_sessions.go @@ -8,9 +8,9 @@ import ( ) func (s Store) DeleteExpiredAuthSessions(ctx context.Context) error { - return s.Exec(ctx, authSessionDeleteQuery(s.config.Dialect, goqu.C("expires_at").Lt(time.Now()))) + return s.Exec(ctx, authSessionDeleteQuery(s.Dialect, goqu.C("expires_at").Lt(time.Now()))) } func (s Store) DeleteAuthSessionsByUserID(ctx context.Context, userID uint64) error { - return s.Exec(ctx, authSessionDeleteQuery(s.config.Dialect, goqu.C("rel_user").Eq(userID))) + return s.Exec(ctx, authSessionDeleteQuery(s.Dialect, goqu.C("rel_user").Eq(userID))) } diff --git a/store/adapters/rdbms/custom_compose_pages.go b/store/adapters/rdbms/custom_compose_pages.go index bae71859b..777753c6a 100644 --- a/store/adapters/rdbms/custom_compose_pages.go +++ b/store/adapters/rdbms/custom_compose_pages.go @@ -16,7 +16,7 @@ func (s Store) ReorderComposePages(ctx context.Context, namespaceID uint64, pare f = composeType.PageFilter{ParentID: parentID, NamespaceID: namespaceID} query = func(id uint64, weight int) *goqu.UpdateDataset { - return s.config.Dialect. + return s.Dialect. Update(composePageTable). Set(goqu.Record{"weight": weight}). Where(goqu.C("id").Eq(id)) diff --git a/store/adapters/rdbms/custom_labels.go b/store/adapters/rdbms/custom_labels.go index 52e91aa4c..64ad33550 100644 --- a/store/adapters/rdbms/custom_labels.go +++ b/store/adapters/rdbms/custom_labels.go @@ -8,7 +8,7 @@ import ( func (s Store) DeleteExtraLabels(ctx context.Context, kind string, resourceId uint64, name ...string) error { return s.Exec(ctx, labelDeleteQuery( - s.config.Dialect, + s.Dialect, goqu.C("kind").Eq(kind), goqu.C("rel_resource").Eq(resourceId), goqu.C("name").NotIn(name), diff --git a/store/adapters/rdbms/custom_metrics.go b/store/adapters/rdbms/custom_metrics.go index d19f2227d..ca09b142e 100644 --- a/store/adapters/rdbms/custom_metrics.go +++ b/store/adapters/rdbms/custom_metrics.go @@ -48,8 +48,8 @@ func (s Store) dailyMetrics(ctx context.Context, tbl exp.IdentifierExpression, e ) return rval, func() (err error) { - daily := s.config.Functions.DATE(goqu.C(field)) - query := s.config.Dialect. + daily := s.Functions.DATE(goqu.C(field)) + query := s.Dialect. Select(daily, goqu.COUNT(goqu.Star()).As("value")). From(tbl). Where(goqu.C(field).IsNotNull(), goqu.And(expr...)). diff --git a/store/adapters/rdbms/custom_rbac.go b/store/adapters/rdbms/custom_rbac.go index 6d909420c..e5fb76054 100644 --- a/store/adapters/rdbms/custom_rbac.go +++ b/store/adapters/rdbms/custom_rbac.go @@ -8,7 +8,7 @@ import ( func (s Store) TransferRbacRules(ctx context.Context, src, dst uint64) (err error) { var ( - transfer = s.config.Dialect.Update(rbacRuleTable). + transfer = s.Dialect.Update(rbacRuleTable). Set(goqu.Record{"rel_role": dst}). Where(goqu.Ex{"rel_role": src}) ) diff --git a/store/adapters/rdbms/custom_roles.go b/store/adapters/rdbms/custom_roles.go index e4f909eaa..838caa8c4 100644 --- a/store/adapters/rdbms/custom_roles.go +++ b/store/adapters/rdbms/custom_roles.go @@ -16,7 +16,7 @@ func (s Store) RoleMetrics(ctx context.Context) (m *systemType.RoleMetrics, err Archived uint `db:"archived"` }{} - query = roleSelectQuery(s.config.Dialect). + query = roleSelectQuery(s.Dialect). Select(timestampStatExpr("deleted", "archived")...) ) @@ -57,7 +57,7 @@ func (s Store) RoleMetrics(ctx context.Context) (m *systemType.RoleMetrics, err func (s Store) TransferRoleMembers(ctx context.Context, src, dst uint64) (err error) { var ( - transfer = s.config.Dialect.Update(roleMemberTable). + transfer = s.Dialect.Update(roleMemberTable). Set(goqu.Record{"rel_role": dst}). Where(goqu.Ex{"rel_role": src}) ) diff --git a/store/adapters/rdbms/custom_users.go b/store/adapters/rdbms/custom_users.go index 035107f4e..95b83de7b 100644 --- a/store/adapters/rdbms/custom_users.go +++ b/store/adapters/rdbms/custom_users.go @@ -12,9 +12,10 @@ func (s *Store) CountUsers(ctx context.Context, f systemType.UserFilter) (c uint aux = struct { Count uint `db:"count"` }{} - expr, _, err = s.config.Filters.User(s, f) - query = s.config.Dialect. + expr, _, err = s.Filters.User(s, f) + + query = s.Dialect. From(userTable). Select(goqu.COUNT(goqu.Star()).As("count")) ) @@ -30,7 +31,7 @@ func (s *Store) CountUsers(ctx context.Context, f systemType.UserFilter) (c uint return aux.Count, nil } -func (s Store) UserMetrics(ctx context.Context) (m *systemType.UserMetrics, err error) { +func (s *Store) UserMetrics(ctx context.Context) (m *systemType.UserMetrics, err error) { var ( aux = struct { Total uint `db:"total"` @@ -39,7 +40,7 @@ func (s Store) UserMetrics(ctx context.Context) (m *systemType.UserMetrics, err Suspended uint `db:"suspended"` }{} - query = userSelectQuery(s.config.Dialect). + query = userSelectQuery(s.Dialect). Select(timestampStatExpr("deleted", "suspended")...) ) diff --git a/store/adapters/rdbms/schema/def.go b/store/adapters/rdbms/ddl/def.go similarity index 99% rename from store/adapters/rdbms/schema/def.go rename to store/adapters/rdbms/ddl/def.go index 23680fcd3..0d03111f9 100644 --- a/store/adapters/rdbms/schema/def.go +++ b/store/adapters/rdbms/ddl/def.go @@ -1,4 +1,4 @@ -package schema +package ddl import ( "fmt" diff --git a/store/adapters/rdbms/ddl/dialect.go b/store/adapters/rdbms/ddl/dialect.go new file mode 100644 index 000000000..db1e96f63 --- /dev/null +++ b/store/adapters/rdbms/ddl/dialect.go @@ -0,0 +1,206 @@ +package ddl + +//import ( +// "bytes" +// "fmt" +// "regexp" +// "strings" +// "text/template" +//) +// +//type ( +// CommonDialect struct { +// tpl *template.Template +// +// CreateTable string +// CreateTableSuffix string +// CreateTableColumn string +// AddColumn string +// AddPrimaryKey string +// DropColumn string +// RenameColumn string +// CreateIndex string +// IndexName string +// IndexCondition string +// IndexFields string +// IfNotExistsClause string +// } +//) +// +//const ( +// CreateTable = "create-table" +// CreateTableSuffix = "create-table-suffix" +// CreateTableColumn = "create-table-column" +// AddColumn = "add-column" +// AddPrimaryKey = "add-primary-key" +// DropColumn = "drop-column" +// RenameColumn = "rename-column" +// CreateIndex = "create-index" +// IndexCondition = "index-condition" +// IndexName = "index-name" +// IndexFields = "index-fields" +// IfNotExistsClause = "if-not-exists-clause" +// TableExists = "table-exists" +// +// CreateTableDDL = ` +// CREATE TABLE {{template "if-not-exists-clause" .}} {{ .Name }} ( +// {{ range $n, $c := .Columns -}} +// {{ if $n }}, {{ else }} {{ end }}{{ template "create-table-column" . }} +// {{ end -}} +// {{- if .PrimaryKey }} +// , PRIMARY KEY {{ template "index-fields" .PrimaryKey.Fields }} +// {{- end }} +// ) {{- template "create-table-suffix" . -}} +// ` +// IfNotExistsClauseDDL = `IF NOT EXISTS` +// +// CreateTableSuffixDDL = `` +// +// CreateTableColumnDDL = ` +// {{- .Name }} {{ columnType .Type }} +// {{- if not .IsNull }} NOT NULL{{end}} +// {{- if .DefaultValue }} DEFAULT {{ .DefaultValue }} {{end}} +// ` +// +// //AddColumnDDL = `ALTER TABLE {{ .Table }} ADD {{ template "create-table-column" .Column }}` +// //AddPrimaryKeyDDL = `ALTER TABLE {{ .Table }} ADD CONSTRAINT PRIMARY KEY {{ template "index-fields" .PrimaryKey.Fields }}` +// //DropColumnDDL = `ALTER TABLE {{ .Table }} DROP {{ .Column }}` +// //RenameColumnDDL = `ALTER TABLE {{ .Table }} RENAME COLUMN {{ .OldName }} TO {{ .NewName }}` +// +// //CreateIndexDDL = `CREATE {{ if .Unique }}UNIQUE {{ end }}INDEX {{ template "if-not-exists-clause" . }} {{ template "index-name" . }} ON {{ .Table }} {{ template "index-fields" .Fields }}{{ template "index-condition" . }}` +// +// //IndexNameDDL = `{{ .Table }}_{{ .Name }}` +// //IndexConditionDDL = `{{- if .Condition }} WHERE ({{ .Condition }}){{ end }}` +// +// IndexFieldsDDL = ` +// ({{ range $n, $f := . -}} +// {{ if $n }}, {{ end }} +// {{- if .Expr}}({{ end }} +// {{- .Field }} +// {{- if .Expr}}){{ end }} +// {{- if .Desc }} DESC{{ end }} +// {{- end }}) +// ` +// +// TableExistDDL = ` +// SELECT COUNT(*) > 0" +// FROM INFORMATION_SCHEMA.TABLES +// WHERE TABLE_NAME = '{{ .Table }}' +// AND TABLE_SCHEMA = '{{ .Schema }}' +// ` +//) +// +//func NewCommonDialect() *CommonDialect { +// g := &CommonDialect{tpl: template.New("")} +// g.AddTemplateFunc("columnType", GenColumnType) +// g.AddTemplate(CreateTable, CreateTableDDL) +// g.AddTemplate(CreateTableSuffix, CreateTableSuffixDDL) +// g.AddTemplate(CreateTableColumn, CreateTableColumnDDL) +// //g.AddTemplate(AddColumn, AddColumnDDL) +// //g.AddTemplate(AddPrimaryKey, AddPrimaryKeyDDL) +// //g.AddTemplate(DropColumn, DropColumnDDL) +// //g.AddTemplate(RenameColumn, RenameColumnDDL) +// //g.AddTemplate(CreateIndex, CreateIndexDDL) +// //g.AddTemplate(IndexCondition, IndexConditionDDL) +// //g.AddTemplate(IndexName, IndexNameDDL) +// g.AddTemplate(IndexFields, IndexFieldsDDL) +// g.AddTemplate(IfNotExistsClause, IfNotExistsClauseDDL) +// g.AddTemplate(TableExists, TableExistDDL) +// +// return g +//} +// +//func (g *CommonDialect) GenerateSQL(name string, data interface{}) string { +// buf := &bytes.Buffer{} +// if err := g.tpl.ExecuteTemplate(buf, name, data); err != nil { +// panic(err) +// } +// +// return buf.String() +//} +// +//func (g *CommonDialect) AddTemplateFunc(name string, fn interface{}) { +// g.tpl.Funcs(template.FuncMap{name: fn}) +//} +// +//func (g *CommonDialect) AddTemplate(name, tpl string) { +// funcMap := template.FuncMap{ +// "trimExpression": func(s string) string { +// re := regexp.MustCompile(`^.*\((\w+)\).*$`) +// if str := re.FindAllStringSubmatch(s, 1); len(str) > 0 && len(str[0]) > 0 && len(str[0][1]) > 0 { +// return str[0][1] +// } +// return s +// }, +// } +// template.Must(g.tpl.Funcs(funcMap).New(name).Parse(strings.TrimSpace(tpl))) +//} +// +////func (g *CommonDialect) CreateTable(t *Table) string { +//// return g.GenerateSQL("create-table", t) +////} +//// +////func (g *CommonDialect) CreateIndex(i *Index) string { +//// return g.GenerateSQL("create-index", i) +////} +// +////func (g *CommonDialect) AddColumn(table string, c *Column) string { +//// return g.GenerateSQL("add-column", map[string]interface{}{ +//// "Table": table, +//// "Column": c, +//// }) +////} +//// +////func (g *CommonDialect) DropColumn(table, column string) string { +//// return g.GenerateSQL("drop-column", map[string]interface{}{ +//// "Table": table, +//// "Column": column, +//// }) +////} +//// +////func (g *CommonDialect) RenameColumn(table, oldName, newName string) string { +//// return g.GenerateSQL("rename-column", map[string]interface{}{ +//// "Table": table, +//// "OldName": oldName, +//// "NewName": newName, +//// }) +////} +//// +////func (g *CommonDialect) AddPrimaryKey(table string, pk *Index) string { +//// return g.GenerateSQL("add-primary-key", map[string]interface{}{ +//// "Table": table, +//// "PrimaryKey": pk, +//// }) +////} +// +//func GenColumnType(ct *ColumnType) string { +// switch ct.Type { +// case ColumnTypeIdentifier: +// return "BIGINT" +// case ColumnTypeVarchar: +// if ct.Length > 0 { +// // VARCHAR(0) is useless +// return fmt.Sprintf("VARCHAR(%d)", ct.Length) +// } +// return "VARCHAR" +// case ColumnTypeText: +// return "TEXT" +// case ColumnTypeJson: +// return "JSON" +// case ColumnTypeBinary: +// return "BYTEA" +// case ColumnTypeTimestamp: +// if ct.Length > -1 { +// // TIMESTAMPTZ(0) strips out milliseconds +// return fmt.Sprintf("TIMESTAMPTZ(%d)", ct.Length) +// } +// +// return "TIMESTAMPTZ" +// case ColumnTypeInteger: +// return "INTEGER" +// case ColumnTypeBoolean: +// return "BOOLEAN" +// default: +// panic(fmt.Sprintf("unhandled column type: %d ", ct.Type)) +// } +//} diff --git a/store/adapters/rdbms/ddl/generators.go b/store/adapters/rdbms/ddl/generators.go new file mode 100644 index 000000000..6ccae8094 --- /dev/null +++ b/store/adapters/rdbms/ddl/generators.go @@ -0,0 +1,267 @@ +package ddl + +import ( + "context" + "fmt" + + "github.com/davecgh/go-spew/spew" + "github.com/doug-martin/goqu/v9" + "github.com/doug-martin/goqu/v9/exp" + "github.com/jmoiron/sqlx" +) + +type ( + trColTypeFn func(ColumnType) string + + CreateTableTemplate struct { + *Table + OmitIfNotExistsClause bool + SuffixClause string + TrColumnTypes trColTypeFn + } + + CreateIndexTemplate struct { + *Index + OmitIfNotExistsClause bool + OmitFieldLength bool + } +) + +func CreateIndexTemplates(base *CreateIndexTemplate, ii ...*Index) []any { + var ( + tt = make([]any, len(ii)) + ) + + for i := range ii { + tt[i] = &CreateIndexTemplate{ + Index: ii[i], + OmitIfNotExistsClause: base.OmitIfNotExistsClause, + OmitFieldLength: base.OmitFieldLength, + } + } + + return tt +} + +// utility for executing series fo commands +func Exec(ctx context.Context, db sqlx.ExecerContext, ss ...any) (err error) { + for _, s := range ss { + var ( + sql string + args []any + ) + + switch c := s.(type) { + case string: + sql = c + case fmt.Stringer: + sql = c.String() + case exp.SQLExpression: + sql, args, err = c.ToSQL() + default: + panic(fmt.Sprintf("unexecutable input (%T)", s)) + } + + spew.Dump(sql, args) + if _, err = db.ExecContext(ctx, sql, args...); err != nil { + return + } + } + + return +} + +func TableExists(ctx context.Context, db sqlx.QueryerContext, d goqu.DialectWrapper, table, schema string) (bool, error) { + return GetBool(ctx, db, GenTableCheck(d, table, schema)) +} + +func GenTableCheck(d goqu.DialectWrapper, table, schema string) *goqu.SelectDataset { + return d.Select(goqu.COUNT(goqu.Star()).Gt(0)). + From("information_schema.tables"). + Where( + exp.ParseIdentifier("table_name").Eq(table), + exp.ParseIdentifier("table_schema").Eq(schema), + ) +} + +func IndexExists(ctx context.Context, db sqlx.QueryerContext, d goqu.DialectWrapper, index, table, schema string) (bool, error) { + return GetBool(ctx, db, GenIndexCheck(d, index, table, schema)) +} + +func GenIndexCheck(d goqu.DialectWrapper, index, table, schema string) *goqu.SelectDataset { + return d.Select(goqu.COUNT(goqu.Star()).Gt(0)). + From("information_schema.statistics"). + Where( + exp.ParseIdentifier("index_name").Eq(index), + exp.ParseIdentifier("table_name").Eq(table), + exp.ParseIdentifier("table_schema").Eq(schema), + ) +} + +func (t *CreateTableTemplate) String() string { + if t.TrColumnTypes == nil { + t.TrColumnTypes = ColumnTypeTranslator + } + + sql := "CREATE TABLE " + + if !t.OmitIfNotExistsClause { + sql += "IF NOT EXISTS " + } + + sql += "\"" + t.Name + "\" (\n" + sql += GenCreateTableBody(t.Table, t.TrColumnTypes) + sql += "\n)" + sql += t.SuffixClause + + return sql +} + +func GenCreateTableBody(t *Table, trColType trColTypeFn) string { + sql := "" + + for c, col := range t.Columns { + if c == 0 { + sql += " " + } else { + sql += ", " + } + + sql += GenTableColumn(col, trColType) + + sql += "\n" + } + + if t.PrimaryKey != nil { + sql += "\n, " + GenPrimaryKey(t.PrimaryKey) + } + + return sql +} + +func GenTableColumn(col *Column, trType trColTypeFn) string { + sql := "\"" + col.Name + "\" " + trType(col.Type) + + if !col.IsNull { + sql += " NOT NULL" + } + + if col.DefaultValue > "" { + sql += " DEFAULT " + col.DefaultValue + } + + return sql +} + +func GenPrimaryKey(pk *Index) string { + sql := "PRIMARY KEY (" + for f, field := range pk.Fields { + if f > 0 { + sql += ", " + } + sql += field.Field + } + sql += ")" + + return sql +} + +func (t *CreateIndexTemplate) String() string { + sql := "CREATE " + + if t.Index.Unique { + sql += "UNIQUE " + } + + sql += "INDEX " + + if !t.OmitIfNotExistsClause { + sql += "IF NOT EXISTS " + } + + sql += "\"" + t.Index.Name + "\" ON \"" + t.Index.Table + "\" (" + + for f, field := range t.Index.Fields { + if f > 0 { + sql += ", " + } + + if field.Expr { + sql += "(" + } + + sql += field.Field + + if field.Desc { + sql += " DESC" + } + + if field.Length > 0 && !t.OmitFieldLength { + sql += fmt.Sprintf("(%d)", field.Length) + } + + if field.Expr { + sql += ")" + } + } + sql += ")" + + if t.Index.Condition != "" { + sql += " WHERE " + t.Index.Condition + } + + return sql +} + +func GetBool(ctx context.Context, db sqlx.QueryerContext, query exp.SQLExpression) (bool, error) { + var ( + exists bool + sql, args, err = query.ToSQL() + ) + + if err != nil { + return false, fmt.Errorf("could not generate SQLk") + } + + if err = sqlx.GetContext(ctx, db, &exists, sql, args...); err != nil { + return false, err + } + + return exists, nil +} + +// ColumnTypeTranslator is the most generic translator of "corteza types" +// to db-native column types. +// +// @todo it might be smart to merge this with data.AttributeType (part of CRS feature) +func ColumnTypeTranslator(ct ColumnType) string { + switch ct.Type { + case ColumnTypeIdentifier: + return "BIGINT" + case ColumnTypeVarchar: + if ct.Length > 0 { + // VARCHAR(0) is useless + return fmt.Sprintf("VARCHAR(%d)", ct.Length) + } + return "VARCHAR" + case ColumnTypeText: + return "TEXT" + case ColumnTypeJson: + return "JSON" + case ColumnTypeBinary: + return "BYTEA" + case ColumnTypeTimestamp: + if ct.Length > -1 { + // TIMESTAMPTZ(0) strips out milliseconds + return fmt.Sprintf("TIMESTAMPTZ(%d)", ct.Length) + } + + return "TIMESTAMPTZ" + case ColumnTypeInteger: + return "INTEGER" + case ColumnTypeBoolean: + return "BOOLEAN" + default: + panic(fmt.Sprintf("unhandled column type: %d ", ct.Type)) + } +} diff --git a/store/adapters/rdbms/dialect.go b/store/adapters/rdbms/dialect.go new file mode 100644 index 000000000..9b10edf44 --- /dev/null +++ b/store/adapters/rdbms/dialect.go @@ -0,0 +1,64 @@ +package rdbms + +// dialect.go +// +// Generic SQL functions used by majority of RDBMS drivers + +import ( + "fmt" + "strings" + + "github.com/doug-martin/goqu/v9/exp" +) + +// DeepIdentJSON constructs expression with chain of JSON operators +// that point value inside JSON document +// +// Supported in databases: +// +// PostgreSQL +// https://www.postgresql.org/docs/9.3/functions-json.html +// +// MySQL +// https://dev.mysql.com/doc/expman/5.7/en/json-function-experence.html +// +// SQLite +// https://www.sqlite.org/json1.html#jptr +func DeepIdentJSON(ident string, pp ...any) exp.LiteralExpression { + var ( + sql = "?" + strings.Repeat("->?", len(pp)) + args = []any{exp.ParseIdentifier(ident)} + ) + + for _, p := range pp { + switch p.(type) { + case string, int: + args = append(args, exp.NewLiteralExpression("?", p)) + default: + panic("invalid type") + } + } + + return exp.NewLiteralExpression(sql, args...) +} + +// JsonPath constructs json-path string from the slice of path parts. +// +func JsonPath(pp ...any) string { + var ( + path = "$" + ) + + for i := range pp { + switch part := pp[i].(type) { + case string: + path = path + "." + part + case int: + path = path + fmt.Sprintf("[%d]", pp[i]) + default: + panic(fmt.Errorf("JsonPath expect string or int, got %T", i)) + } + } + + return path +} diff --git a/store/adapters/rdbms/dialect_test.go b/store/adapters/rdbms/dialect_test.go new file mode 100644 index 000000000..281024df9 --- /dev/null +++ b/store/adapters/rdbms/dialect_test.go @@ -0,0 +1,88 @@ +package rdbms + +import ( + "testing" + + "github.com/doug-martin/goqu/v9" + "github.com/stretchr/testify/require" + + _ "github.com/doug-martin/goqu/v9/dialect/postgres" +) + +// test deep ident expression generator +func Test_DeepIdentJSON(t *testing.T) { + var ( + pre = `SELECT ` + post = ` FROM "test"` + + cc = []struct { + input []interface{} + sql string + args []interface{} + }{ + { + input: []interface{}{"one"}, + sql: `"one"`, + args: []interface{}{}, + }, + { + input: []interface{}{"one", "two"}, + sql: `"one"->'two'`, + args: []interface{}{}, + }, + { + input: []interface{}{"one", 2, "three"}, + sql: `"one"->2->'three'`, + args: []interface{}{}, + }, + { + input: []interface{}{"one", "two", 3}, + sql: `"one"->'two'->3`, + args: []interface{}{}, + }, + } + ) + + for _, c := range cc { + t.Run(c.sql, func(t *testing.T) { + var ( + r = require.New(t) + ) + + sql, args, err := goqu.Dialect("postgres").Select(DeepIdentJSON(c.input[0].(string), c.input[1:]...)).From("test").ToSQL() + r.NoError(err) + r.Equal(pre+c.sql+post, sql) + r.Equal(c.args, args) + }) + } +} + +// test deep ident expression generator +func Test_JsonPath(t *testing.T) { + + var ( + cc = []struct { + input []interface{} + path string + }{ + { + input: []interface{}{"two"}, + path: `$.two`, + }, + { + input: []interface{}{2, "three"}, + path: `$[2].three`, + }, + { + input: []interface{}{"two", 3}, + path: `$.two[3]`, + }, + } + ) + + for _, c := range cc { + t.Run(c.path, func(t *testing.T) { + require.Equal(t, c.path, JsonPath(c.input...)) + }) + } +} diff --git a/store/adapters/rdbms/drivers/mysql/connect.go b/store/adapters/rdbms/drivers/mysql/connect.go index 1aa83ec5e..4457e14f3 100644 --- a/store/adapters/rdbms/drivers/mysql/connect.go +++ b/store/adapters/rdbms/drivers/mysql/connect.go @@ -7,12 +7,14 @@ import ( "strings" "github.com/cortezaproject/corteza-server/pkg/errors" + "github.com/cortezaproject/corteza-server/pkg/logger" "github.com/cortezaproject/corteza-server/store" "github.com/cortezaproject/corteza-server/store/adapters/rdbms" "github.com/cortezaproject/corteza-server/store/adapters/rdbms/instrumentation" "github.com/doug-martin/goqu/v9" _ "github.com/doug-martin/goqu/v9/dialect/mysql" "github.com/go-sql-driver/mysql" + "github.com/jmoiron/sqlx" "github.com/ngrok/sqlmw" ) @@ -23,36 +25,40 @@ func init() { func Connect(ctx context.Context, dsn string) (_ store.Storer, err error) { var ( - cfg *rdbms.Config - s *rdbms.Store + db *sqlx.DB + cfg *rdbms.ConnConfig ) - if cfg, err = ProcDataSourceName(dsn); err != nil { + if cfg, err = NewConfig(dsn); err != nil { return } - cfg.TxRetryErrHandler = txRetryErrHandler - cfg.ErrorHandler = errorHandler - - if s, err = rdbms.Connect(ctx, cfg); err != nil { + if db, err = rdbms.Connect(ctx, logger.Default(), cfg); err != nil { return } // See https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_ansi for details - if _, err = s.DB().ExecContext(ctx, "SET SESSION sql_mode = 'ANSI'"); err != nil { + if _, err = db.ExecContext(ctx, `SET SESSION sql_mode = 'ANSI'`); err != nil { return } - cfg.Upgrader = NewUpgrader(s) + dialect := goqu.Dialect("mysql") + s := &rdbms.Store{ + DB: db, + + Dialect: dialect, + TxRetryErrHandler: txRetryErrHandler, + ErrorHandler: errorHandler, + + SchemaAPI: &schema{dbName: cfg.DBName, dialect: dialect}, + } + + s.SetDefaults() return s, nil } -//func (s *Store) Upgrade(ctx context.Context, log *zap.Logger) (err error) { -// return (&rdbms.Schema{}).Upgrade(ctx, NewUpgrader(log, s)) -//} - -// ProcDataSourceName validates given DSN and ensures +// NewConfig validates given DSN and ensures // params are present and correct // // If param is missing it sets it to default but returns @@ -63,7 +69,7 @@ func Connect(ctx context.Context, dsn string) (_ store.Storer, err error) { // @todo similar fallback (autoconfig) for collation=utf8mb4_general_ci // but allow different collation values // -func ProcDataSourceName(in string) (*rdbms.Config, error) { +func NewConfig(in string) (*rdbms.ConnConfig, error) { const ( schemeDel = "://" validScheme = "mysql" @@ -72,9 +78,7 @@ func ProcDataSourceName(in string) (*rdbms.Config, error) { var ( endOfSchema = strings.Index(in, schemeDel) - c = &rdbms.Config{ - Dialect: goqu.Dialect("mysql"), - } + c = &rdbms.ConnConfig{} ) if endOfSchema > 0 && (in[:endOfSchema] == validScheme || strings.HasPrefix(in[:endOfSchema], validScheme+"+")) { @@ -94,6 +98,8 @@ func ProcDataSourceName(in string) (*rdbms.Config, error) { c.DBName = pdsn.DBName } + c.SetDefaults() + return c, nil } @@ -122,7 +128,6 @@ func txRetryErrHandler(try int, err error) bool { func errorHandler(err error) error { if err != nil { - if implErr, ok := err.(*mysql.MySQLError); ok { // https://www.fromdual.com/de/mysql-error-codes-and-messages switch implErr.Number { diff --git a/store/adapters/rdbms/drivers/mysql/connect_test.go b/store/adapters/rdbms/drivers/mysql/connect_test.go index abda8ef1e..fa02d388f 100644 --- a/store/adapters/rdbms/drivers/mysql/connect_test.go +++ b/store/adapters/rdbms/drivers/mysql/connect_test.go @@ -10,16 +10,16 @@ import ( func TestProcDataSourceName(t *testing.T) { var ( req = require.New(t) - c *rdbms.Config + c *rdbms.ConnConfig err error ) - c, err = ProcDataSourceName("mysql://uid:@/dbname?parseTime=true") + c, err = NewConfig("mysql://uid:@/dbname?parseTime=true") req.NoError(err) req.Contains(c.DataSourceName, "parseTime=true") req.Equal(c.DBName, "dbname") - c, err = ProcDataSourceName("mysql+foo://uid:@/dbname") + c, err = NewConfig("mysql+foo://uid:@/dbname") req.NoError(err) req.Contains(c.DataSourceName, "parseTime=true") req.Equal(c.DriverName, "mysql+foo") diff --git a/store/adapters/rdbms/drivers/mysql/schema.go b/store/adapters/rdbms/drivers/mysql/schema.go new file mode 100644 index 000000000..b59dd837f --- /dev/null +++ b/store/adapters/rdbms/drivers/mysql/schema.go @@ -0,0 +1,87 @@ +package mysql + +import ( + "context" + + "github.com/cortezaproject/corteza-server/store/adapters/rdbms/ddl" + "github.com/doug-martin/goqu/v9" + "github.com/jmoiron/sqlx" +) + +type ( + schema struct { + // ... + dbName string + dialect goqu.DialectWrapper + } +) + +func (s *schema) TableExists(ctx context.Context, db sqlx.QueryerContext, table string) (bool, error) { + return ddl.TableExists(ctx, db, s.dialect, table, "public") +} + +// CreateTable +// +// MySQL does not hav CREATE-INDEX-IF-NOT-EXISTS; we need to check index existance manually +func (s *schema) CreateTable(ctx context.Context, db sqlx.ExtContext, t *ddl.Table) (err error) { + tc := &ddl.CreateTableTemplate{ + Table: t, + TrColumnTypes: columnTypTranslator, + SuffixClause: "ENGINE=InnoDB DEFAULT CHARSET=utf8", + } + + if err = ddl.Exec(ctx, db, tc); err != nil { + return + } + + for _, index := range t.Indexes { + if index.Condition != "" { + // MySQL, sad little DB does not support + // conditional indexes + // + // We'll solve this on an application level + continue + } + + var doesIt bool + if doesIt, err = ddl.IndexExists(ctx, db, s.dialect, index.Name, index.Table, s.dbName); err != nil { + return + } else if doesIt { + continue + } + + ic := &ddl.CreateIndexTemplate{ + Index: index, + OmitIfNotExistsClause: true, + } + + if err = ddl.Exec(ctx, db, ic); err != nil { + return + } + + } + + return +} + +func columnTypTranslator(ct ddl.ColumnType) string { + switch ct.Type { + case ddl.ColumnTypeIdentifier: + return "BIGINT UNSIGNED" + case ddl.ColumnTypeText: + // @todo when compose_record_value is removed, this will no longer be needed + if y, has := ct.Flags["mysqlLongText"].(bool); has && y { + return "LONGTEXT" + } + + return "TEXT" + case ddl.ColumnTypeBinary: + return "BLOB" + case ddl.ColumnTypeTimestamp: + return "DATETIME" + case ddl.ColumnTypeBoolean: + return "TINYINT(1)" + default: + return ddl.ColumnTypeTranslator(ct) + } +} diff --git a/store/adapters/rdbms/drivers/mysql/upgrade.go b/store/adapters/rdbms/drivers/mysql/upgrade.go deleted file mode 100644 index ed51de451..000000000 --- a/store/adapters/rdbms/drivers/mysql/upgrade.go +++ /dev/null @@ -1,386 +0,0 @@ -package mysql - -// MySQL specific prefixes, sql -// templates, functions and other helpers - -import ( - "context" - "database/sql" - "fmt" - - "github.com/cortezaproject/corteza-server/store/adapters/rdbms" - "github.com/cortezaproject/corteza-server/store/adapters/rdbms/schema" - _ "github.com/go-sql-driver/mysql" - "go.uber.org/zap" -) - -type ( - upgrader struct { - log *zap.Logger - s *rdbms.Store - dialect *schema.CommonDialect - } -) - -// NewUpgrader returns MySQL schema upgrader -func NewUpgrader(store *rdbms.Store) *upgrader { - var g = &upgrader{ - log: zap.NewNop(), - s: store, - dialect: schema.NewCommonDialect(), - } - - // All modifications we need for the DDL generator - // to properly support MySQL dialect: - g.dialect.AddTemplate("create-table-suffix", "ENGINE=InnoDB DEFAULT CHARSET=utf8") - - // Sadly, MySQL does not support partial indexes - // - // To work around this, we'll ignore partial indexes - // and solve this on application level - g.dialect.AddTemplate( - "create-index", - `{{ if not .Condition }}CREATE {{ if .Unique }}UNIQUE {{ end }}INDEX {{ template "index-name" . }} ON {{ .Table }} {{ template "index-fields" .Fields }}{{ else }}SELECT 1 -- dummy sql, just to prevent "empty query" errors...{{ end }}`, - ) - - g.dialect.AddTemplate("if-not-exists-clause", "") - g.dialect.AddTemplate("index-fields", ` -({{ range $n, $f := . -}} - {{ if $n }}, {{ end }} - {{- if .Expr}}({{ end }} - {{- .Field }} - {{- if .Length}}({{ .Length }}){{ end }} - {{- if .Expr}}){{ end }} - {{- if .Desc }} DESC{{ end }} -{{- end }}) -`) - - // Cover mysql exceptions - g.dialect.AddTemplateFunc("columnType", func(ct *schema.ColumnType) string { - switch ct.Type { - case schema.ColumnTypeIdentifier: - return "BIGINT UNSIGNED" - case schema.ColumnTypeText: - if y, has := ct.Flags["mysqlLongText"].(bool); has && y { - return "LONGTEXT" - } - - return "TEXT" - case schema.ColumnTypeBinary: - return "BLOB" - case schema.ColumnTypeTimestamp: - return "DATETIME" - case schema.ColumnTypeBoolean: - return "TINYINT(1)" - default: - return schema.GenColumnType(ct) - } - }) - - return g -} - -func (u *upgrader) SetLogger(l *zap.Logger) { - u.log = l -} - -// Before runs before all tables are upgraded -func (u upgrader) Before(ctx context.Context) error { - tt := []func() error{ - func() error { - const migrations = "migrations" - if exists, err := u.TableExists(ctx, migrations); err != nil || !exists { - return err - } - - if _, err := u.s.DB().ExecContext(ctx, fmt.Sprintf(`DROP TABLE "%s"`, migrations)); err != nil { - return err - } - - u.log.Debug(fmt.Sprintf("%s table removed", migrations)) - - return nil - }, - func() error { - // in the first versions we created and used foreign keys - // this is now obsolete with future plans with the (composite) store architecture - var ( - // find and remove all foreign keys - find = `SELECT CONSTRAINT_NAME, TABLE_NAME FROM information_schema.TABLE_CONSTRAINTS where CONSTRAINT_SCHEMA = '%s' AND CONSTRAINT_TYPE = 'FOREIGN KEY';` - drop = `ALTER TABLE %s DROP FOREIGN KEY %s` - - table, constraint string - ) - - if rows, err := u.s.DB().QueryContext(ctx, fmt.Sprintf(find, u.s.Config().DBName)); err != nil { - return err - } else { - for rows.Next() { - if err = rows.Scan(&constraint, &table); err != nil { - return err - } - - u.log.Debug(fmt.Sprintf("removing foreign key %s from table %s", constraint, table)) - if _, err = u.s.DB().ExecContext(ctx, fmt.Sprintf(drop, table, constraint)); err != nil { - return err - } - } - } - - return nil - }, - } - - for _, t := range tt { - if err := t(); err != nil { - return err - } - } - - return schema.CommonUpgrades(u.log, u).Before(ctx) -} - -// After runs after all tables are upgraded -func (u upgrader) After(ctx context.Context) error { - return schema.CommonUpgrades(u.log, u).After(ctx) -} - -// CreateTable is triggered for every table defined in the rdbms package -// -// It checks if table is missing and creates it, otherwise -// it runs -func (u upgrader) CreateTable(ctx context.Context, t *schema.Table) (err error) { - var exists bool - if exists, err = u.TableExists(ctx, t.Name); err != nil { - return - } - - if !exists { - if err = u.Exec(ctx, u.dialect.CreateTable(t)); err != nil { - return err - } - - for _, i := range t.Indexes { - if err = u.Exec(ctx, u.dialect.CreateIndex(i)); err != nil { - return fmt.Errorf("could not create index %s on table %s: %w", i.Name, i.Table, err) - } - } - } - - if err = u.upgradeTable(ctx, t); err != nil { - return - } - - return nil -} - -func (u upgrader) DropTable(ctx context.Context, table string) (dropped bool, err error) { - var exists bool - exists, err = u.TableExists(ctx, table) - if err != nil || !exists { - return false, err - } - - err = u.Exec(ctx, fmt.Sprintf(`DROP TABLE "%s"`, table)) - if err != nil { - return false, err - } - - return true, nil -} - -func (u upgrader) Exec(ctx context.Context, sql string, aa ...interface{}) error { - _, err := u.s.DB().ExecContext(ctx, sql, aa...) - return err -} - -// upgradeTable applies any necessary changes connected to that specific table -func (u upgrader) upgradeTable(ctx context.Context, t *schema.Table) error { - g := schema.CommonUpgrades(u.log, u) - - switch t.Name { - default: - return g.Upgrade(ctx, t) - } -} - -func (u upgrader) TableExists(ctx context.Context, table string) (bool, error) { - var tmp interface{} - if err := u.s.DB().GetContext(ctx, &tmp, fmt.Sprintf(`SHOW TABLES LIKE '%s'`, table)); err == sql.ErrNoRows { - return false, nil - } else if err != nil { - return false, fmt.Errorf("could not check if table exists: %w", err) - } - - return true, nil -} - -func (u upgrader) TableSchema(ctx context.Context, table string) (schema.Columns, error) { - return nil, fmt.Errorf("pending implementation") -} - -// AddColumn adds column to table -func (u upgrader) AddColumn(ctx context.Context, table string, col *schema.Column) (added bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(col.Name) != nil { - return nil - } - - if col.Type.Type == schema.ColumnTypeText || col.Type.Type == schema.ColumnTypeJson { - col.DefaultValue = "" - } - - if err = u.Exec(ctx, u.dialect.AddColumn(table, col)); err != nil { - return err - } - - added = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not add column %q to %q: %w", col.Name, table, err) - } - - return -} - -// DropColumn drops column from table -func (u upgrader) DropColumn(ctx context.Context, table, column string) (dropped bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(column) == nil { - return nil - } - - if err = u.Exec(ctx, u.dialect.DropColumn(table, column)); err != nil { - return err - } - - dropped = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not drop column %q from %q: %w", column, table, err) - } - - return -} - -// RenameColumn renames column on a table -func (u upgrader) RenameColumn(ctx context.Context, table, oldName, newName string) (changed bool, err error) { - err = func() error { - if oldName == newName { - return nil - } - - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(oldName) == nil { - // Old column does not exist anymore - - if columns.Get(newName) == nil { - return fmt.Errorf("old and new columns are missing") - } - - return nil - } - - if columns.Get(newName) != nil { - return fmt.Errorf("new column already exists") - - } - - if err = u.Exec(ctx, u.dialect.RenameColumn(table, oldName, newName)); err != nil { - return err - } - - changed = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not rename column %q on table %q to %q: %w", oldName, table, newName, err) - } - - return -} - -func (u upgrader) AddPrimaryKey(ctx context.Context, table string, ind *schema.Index) (added bool, err error) { - if err = u.Exec(ctx, u.dialect.AddPrimaryKey(table, ind)); err != nil { - return false, fmt.Errorf("could not add primary key to table %s: %w", table, err) - } - - return true, nil -} - -func (u upgrader) CreateIndex(ctx context.Context, ind *schema.Index) (added bool, err error) { - if added, err = u.hasIndex(ctx, ind.Table, ind.Name); added || err != nil { - return - } - - if err = u.Exec(ctx, u.dialect.CreateIndex(ind)); err != nil { - return false, fmt.Errorf("could not create index on table %s: %w", ind.Table, err) - } - - return true, nil -} - -func (u upgrader) hasIndex(ctx context.Context, table, name string) (has bool, err error) { - var ( - lookup = "SELECT COUNT(*) > 0 FROM information_schema.statistics where table_schema = ? AND table_name = ? AND index_name = ?" - ) - - return has, u.s.DB().GetContext(ctx, &has, lookup, u.s.Config().DBName, table, table+"_"+name) -} - -// loads and returns all tables columns -func (u upgrader) getColumns(ctx context.Context, table string) (out schema.Columns, err error) { - type ( - col struct { - Name string `db:"COLUMN_NAME"` - IsNullable bool `db:"IS_NULLABLE"` - DataType string `db:"DATA_TYPE"` - } - ) - - var ( - lookup = `SELECT COLUMN_NAME, - IS_NULLABLE = 'YES' AS IS_NULLABLE, - DATA_TYPE - FROM INFORMATION_SCHEMA.COLUMNS - WHERE TABLE_SCHEMA = ? - AND TABLE_NAME = ?` - - cols []*col - ) - - if err = u.s.DB().SelectContext(ctx, &cols, lookup, u.s.Config().DBName, table); err != nil { - return nil, err - } - - out = make([]*schema.Column, len(cols)) - for i := range cols { - out[i] = &schema.Column{ - Name: cols[i].Name, - //Type: schema.ColumnType{}, - IsNull: cols[i].IsNullable, - //DefaultValue: "", - } - } - - return out, nil -} diff --git a/store/adapters/rdbms/drivers/postgres/connect.go b/store/adapters/rdbms/drivers/postgres/connect.go index a577d6977..5fb767808 100644 --- a/store/adapters/rdbms/drivers/postgres/connect.go +++ b/store/adapters/rdbms/drivers/postgres/connect.go @@ -6,11 +6,13 @@ import ( "net/url" "strings" + "github.com/cortezaproject/corteza-server/pkg/logger" "github.com/cortezaproject/corteza-server/store" "github.com/cortezaproject/corteza-server/store/adapters/rdbms" "github.com/cortezaproject/corteza-server/store/adapters/rdbms/instrumentation" "github.com/doug-martin/goqu/v9" _ "github.com/doug-martin/goqu/v9/dialect/postgres" + "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/ngrok/sqlmw" ) @@ -22,35 +24,36 @@ func init() { func Connect(ctx context.Context, dsn string) (_ store.Storer, err error) { var ( - cfg *rdbms.Config - s *rdbms.Store + db *sqlx.DB + cfg *rdbms.ConnConfig ) - if cfg, err = ProcDataSourceName(dsn); err != nil { + if cfg, err = NewConfig(dsn); err != nil { return } - cfg.ErrorHandler = errorHandler - - if s, err = rdbms.Connect(ctx, cfg); err != nil { + if db, err = rdbms.Connect(ctx, logger.Default(), cfg); err != nil { return } - cfg.Upgrader = NewUpgrader(s) + dialect := goqu.Dialect("postgres") + s := &rdbms.Store{ + DB: db, + + Dialect: dialect, + ErrorHandler: errorHandler, + + SchemaAPI: &schema{schemaName: "public", dialect: dialect}, + } + + s.SetDefaults() + return s, nil } -//func (s *Store) Upgrade(ctx context.Context, log *zap.Logger) (err error) { -// if err = (&rdbms.Schema{}).Upgrade(ctx, NewUpgrader(log, s)); err != nil { -// return fmt.Errorf("cannot upgrade postgresql schema: %w", err) -// } -// -// return nil -//} - -// ProcDataSourceName validates given DSN and ensures +// NewConfig validates given DSN and ensures // params are present and correct -func ProcDataSourceName(dsn string) (c *rdbms.Config, err error) { +func NewConfig(dsn string) (c *rdbms.ConnConfig, err error) { const ( validScheme = "postgres" ) @@ -68,12 +71,15 @@ func ProcDataSourceName(dsn string) (c *rdbms.Config, err error) { u.Scheme = validScheme } - return &rdbms.Config{ + c = &rdbms.ConnConfig{ DriverName: scheme, DataSourceName: u.String(), DBName: strings.Trim(u.Path, "/"), - Dialect: goqu.Dialect("postgres"), - }, nil + } + + c.SetDefaults() + + return c, nil } func errorHandler(err error) error { diff --git a/store/adapters/rdbms/drivers/postgres/schema.go b/store/adapters/rdbms/drivers/postgres/schema.go new file mode 100644 index 000000000..e32711c49 --- /dev/null +++ b/store/adapters/rdbms/drivers/postgres/schema.go @@ -0,0 +1,35 @@ +package postgres + +import ( + "context" + + "github.com/cortezaproject/corteza-server/store/adapters/rdbms/ddl" + "github.com/doug-martin/goqu/v9" + "github.com/jmoiron/sqlx" +) + +// PostgreSQL specific prefixes, sql +// templates, functions and other helpers + +type ( + schema struct { + schemaName string + dialect goqu.DialectWrapper + } +) + +func (s *schema) TableExists(ctx context.Context, db sqlx.QueryerContext, table string) (bool, error) { + return ddl.TableExists(ctx, db, s.dialect, table, "public") +} + +func (s *schema) CreateTable(ctx context.Context, db sqlx.ExtContext, t *ddl.Table) (err error) { + tt := append([]any{ + &ddl.CreateTableTemplate{ + Table: t, + SuffixClause: " WITHOUT OIDS", + }}, + ddl.CreateIndexTemplates(&ddl.CreateIndexTemplate{OmitFieldLength: true}, t.Indexes...)..., + ) + + return ddl.Exec(ctx, db, tt...) +} diff --git a/store/adapters/rdbms/drivers/postgres/upgrade.go b/store/adapters/rdbms/drivers/postgres/upgrade.go deleted file mode 100644 index 3abb5d7d2..000000000 --- a/store/adapters/rdbms/drivers/postgres/upgrade.go +++ /dev/null @@ -1,286 +0,0 @@ -package postgres - -// PostgreSQL specific prefixes, sql -// templates, functions and other helpers - -import ( - "context" - "fmt" - - "github.com/cortezaproject/corteza-server/store/adapters/rdbms" - "github.com/cortezaproject/corteza-server/store/adapters/rdbms/schema" - "go.uber.org/zap" -) - -type ( - upgrader struct { - log *zap.Logger - s *rdbms.Store - dialect *schema.CommonDialect - } -) - -var ( - _ schema.Upgrader = &upgrader{} -) - -// NewUpgrader returns PostgreSQL schema upgrader -func NewUpgrader(store *rdbms.Store) *upgrader { - var g = &upgrader{ - log: zap.NewNop(), - s: store, - dialect: schema.NewCommonDialect(), - } - - // Modification to general DDL dialect to support Postgres requirements - g.dialect.AddTemplate("create-table-suffix", "WITHOUT OIDS") - - return g -} - -func (u *upgrader) SetLogger(l *zap.Logger) { - u.log = l -} - -// Before runs before all tables are upgraded -func (u upgrader) Before(ctx context.Context) error { - return schema.CommonUpgrades(u.log, u).Before(ctx) -} - -// After runs after all tables are upgraded -func (u upgrader) After(ctx context.Context) error { - return schema.CommonUpgrades(u.log, u).After(ctx) -} - -// CreateTable is triggered for every table defined in the rdbms package -// -// It checks if table is missing and creates it, otherwise -// it runs -func (u upgrader) CreateTable(ctx context.Context, t *schema.Table) (err error) { - var exists bool - if exists, err = u.TableExists(ctx, t.Name); err != nil { - return - } - - if !exists { - if err = u.Exec(ctx, u.dialect.CreateTable(t)); err != nil { - return err - } - - for _, i := range t.Indexes { - if err = u.Exec(ctx, u.dialect.CreateIndex(i)); err != nil { - return fmt.Errorf("could not create index %s on table %s: %w", i.Name, i.Table, err) - } - } - } else { - return u.upgradeTable(ctx, t) - } - - return nil -} - -func (u upgrader) Exec(ctx context.Context, sql string, aa ...interface{}) error { - _, err := u.s.DB().ExecContext(ctx, sql, aa...) - return err -} - -// upgradeTable applies any necessary changes connected to that specific table -func (u upgrader) upgradeTable(ctx context.Context, t *schema.Table) error { - g := schema.CommonUpgrades(u.log, u) - - switch t.Name { - default: - return g.Upgrade(ctx, t) - } -} - -func (u upgrader) TableExists(ctx context.Context, table string) (bool, error) { - var exists bool - - if err := u.s.DB().GetContext(ctx, &exists, "SELECT TO_REGCLASS($1) IS NOT NULL", "public."+table); err != nil { - return false, fmt.Errorf("could not check if table exists: %w", err) - } - - return exists, nil -} - -func (u upgrader) DropTable(ctx context.Context, table string) (dropped bool, err error) { - var exists bool - exists, err = u.TableExists(ctx, table) - if err != nil || !exists { - return false, err - } - - err = u.Exec(ctx, fmt.Sprintf(`DROP TABLE %s`, table)) - if err != nil { - return false, err - } - - return true, nil -} - -func (u upgrader) TableSchema(ctx context.Context, table string) (schema.Columns, error) { - return nil, fmt.Errorf("pending implementation") -} - -// AddColumn adds column to table -func (u upgrader) AddColumn(ctx context.Context, table string, col *schema.Column) (added bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(col.Name) != nil { - return nil - } - - if err = u.Exec(ctx, u.dialect.AddColumn(table, col)); err != nil { - return err - } - - added = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not add column %q to %q: %w", col.Name, table, err) - } - - return -} - -// DropColumn drops column from table -func (u upgrader) DropColumn(ctx context.Context, table, column string) (dropped bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(column) == nil { - return nil - } - - if err = u.Exec(ctx, u.dialect.DropColumn(table, column)); err != nil { - return err - } - - dropped = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not drop column %q from %q: %w", column, table, err) - } - - return -} - -// RenameColumn renames column on a table -func (u upgrader) RenameColumn(ctx context.Context, table, oldName, newName string) (changed bool, err error) { - err = func() error { - if oldName == newName { - return nil - } - - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(oldName) == nil { - // Old column does not exist anymore - - if columns.Get(newName) == nil { - return fmt.Errorf("old and new columns are missing") - } - - return nil - } - - if columns.Get(newName) != nil { - return fmt.Errorf("new column already exists") - - } - - if err = u.Exec(ctx, u.dialect.RenameColumn(table, oldName, newName)); err != nil { - return err - } - - changed = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not rename column %q on table %q to %q: %w", oldName, table, newName, err) - } - - return -} - -func (u upgrader) AddPrimaryKey(ctx context.Context, table string, ind *schema.Index) (added bool, err error) { - if err = u.Exec(ctx, u.dialect.AddPrimaryKey(table, ind)); err != nil { - return false, fmt.Errorf("could not add primary key to table %s: %w", table, err) - } - - return true, nil -} - -func (u upgrader) CreateIndex(ctx context.Context, ind *schema.Index) (added bool, err error) { - if added, err = u.hasIndex(ctx, ind.Table, ind.Name); added || err != nil { - return - } - - if err = u.Exec(ctx, u.dialect.CreateIndex(ind)); err != nil { - return false, fmt.Errorf("could not create index on table %s: %w", ind.Table, err) - } - - return true, nil -} - -func (u upgrader) hasIndex(ctx context.Context, table, name string) (has bool, err error) { - var ( - lookup = "SELECT COUNT(*) > 0 FROM pg_indexes WHERE tablename = $1 AND indexname = $2" - ) - - return has, u.s.DB().GetContext(ctx, &has, lookup, table, table+"_"+name) -} - -// loads and returns all tables columns -func (u upgrader) getColumns(ctx context.Context, table string) (out schema.Columns, err error) { - type ( - col struct { - Name string `db:"column_name"` - IsNullable bool `db:"is_nullable"` - DataType string `db:"data_type"` - } - ) - - var ( - lookup = `SELECT column_name, - is_nullable = 'YES' AS is_nullable, - data_type - FROM information_schema.columns - WHERE table_catalog = $1 - AND table_name = $2` - - cols []*col - ) - - if err = u.s.DB().SelectContext(ctx, &cols, lookup, u.s.Config().DBName, table); err != nil { - return nil, err - } - - out = make([]*schema.Column, len(cols)) - for i := range cols { - out[i] = &schema.Column{ - Name: cols[i].Name, - //Type: schema.ColumnType{}, - IsNull: cols[i].IsNullable, - //DefaultValue: "", - } - } - - return out, nil -} diff --git a/store/adapters/rdbms/drivers/sqlite/connect.go b/store/adapters/rdbms/drivers/sqlite/connect.go index dd6953db4..82c738ac9 100644 --- a/store/adapters/rdbms/drivers/sqlite/connect.go +++ b/store/adapters/rdbms/drivers/sqlite/connect.go @@ -3,14 +3,15 @@ package sqlite import ( "context" "database/sql" - "errors" "fmt" "strings" + "github.com/cortezaproject/corteza-server/pkg/logger" "github.com/cortezaproject/corteza-server/store" "github.com/cortezaproject/corteza-server/store/adapters/rdbms" "github.com/cortezaproject/corteza-server/store/adapters/rdbms/instrumentation" "github.com/doug-martin/goqu/v9" + "github.com/jmoiron/sqlx" "github.com/mattn/go-sqlite3" "github.com/ngrok/sqlmw" ) @@ -22,30 +23,31 @@ func init() { func Connect(ctx context.Context, dsn string) (_ store.Storer, err error) { var ( - cfg *rdbms.Config - s *rdbms.Store + db *sqlx.DB + cfg *rdbms.ConnConfig ) - if cfg, err = ProcDataSourceName(dsn); err != nil { + + if cfg, err = NewConfig(dsn); err != nil { return } - cfg.TxRetryErrHandler = txRetryErrHandler - cfg.ErrorHandler = errorHandler - - // Using transactions in SQLite causes table locking - // @todo there must be a better way to go around this - cfg.TxDisabled = true - - // Set to zero - // Otherwise SQLite (in-memory) disconnects - // and all tables and data is lost - cfg.ConnMaxLifetime = 0 - - if s, err = rdbms.Connect(ctx, cfg); err != nil { + if db, err = rdbms.Connect(ctx, logger.Default(), cfg); err != nil { return } - cfg.Upgrader = NewUpgrader(s) + s := &rdbms.Store{ + DB: db, + + Dialect: goqu.Dialect("sqlite3"), + ErrorHandler: errorHandler, + + TxRetryLimit: -1, + //TxRetryErrHandler: txRetryErrHandler, + + SchemaAPI: &schema{}, + } + + s.SetDefaults() return s, nil } @@ -58,17 +60,9 @@ func ConnectInMemoryWithDebug(ctx context.Context) (s store.Storer, err error) { return Connect(ctx, "sqlite3+debug://file::memory:?cache=shared&mode=memory") } -//func (s *Store) Upgrade(ctx context.Context, log *zap.Logger) (err error) { -// if err = (&rdbms.Schema{}).Upgrade(ctx, NewUpgrader(log, s)); err != nil { -// return fmt.Errorf("cannot upgrade sqlite schema: %w", err) -// } -// -// return nil -//} - -// ProcDataSourceName validates given DSN and ensures +// NewConfig validates given DSN and ensures // params are present and correct -func ProcDataSourceName(in string) (*rdbms.Config, error) { +func NewConfig(in string) (*rdbms.ConnConfig, error) { const ( schemeDel = "://" validScheme = "sqlite3" @@ -77,41 +71,45 @@ func ProcDataSourceName(in string) (*rdbms.Config, error) { var ( endOfSchema = strings.Index(in, schemeDel) - c = &rdbms.Config{ - // note that we're not using vanilla SQLite - // see dialect.go - Dialect: goqu.Dialect("sqlite3"), - } + cfg = &rdbms.ConnConfig{} ) if endOfSchema > 0 && (in[:endOfSchema] == validScheme || strings.HasPrefix(in[:endOfSchema], validScheme+"+")) { - c.DriverName = in[:endOfSchema] - c.DataSourceName = in[endOfSchema+len(schemeDel):] + cfg.DriverName = in[:endOfSchema] + cfg.DataSourceName = in[endOfSchema+len(schemeDel):] } else { return nil, fmt.Errorf("expecting valid schema (sqlite3://) at the beginning of the DSN (%s)", in) } - return c, nil + // Set to zero + // Otherwise SQLite (in-memory) disconnects + // and all tables and data is lost + cfg.ConnMaxLifetime = 0 + + cfg.SetDefaults() + + return cfg, nil } -func txRetryErrHandler(try int, err error) bool { - for errors.Unwrap(err) != nil { - err = errors.Unwrap(err) - } - - var sqliteErr, ok = err.(sqlite3.Error) - if !ok { - return false - } - - switch sqliteErr.Code { - case sqlite3.ErrLocked: - return true - - } - - return false -} +// Transactions are disabled on SQLite +//func txRetryErrHandler(try int, err error) bool { +// for errors.Unwrap(err) != nil { +// err = errors.Unwrap(err) +// } +// +// var sqliteErr, ok = err.(sqlite3.Error) +// if !ok { +// return false +// } +// +// switch sqliteErr.Code { +// case sqlite3.ErrLocked: +// return true +// +// } +// +// return false +//} func errorHandler(err error) error { if err != nil { diff --git a/store/adapters/rdbms/drivers/sqlite/schema.go b/store/adapters/rdbms/drivers/sqlite/schema.go new file mode 100644 index 000000000..d1303c0a3 --- /dev/null +++ b/store/adapters/rdbms/drivers/sqlite/schema.go @@ -0,0 +1,53 @@ +package sqlite + +import ( + "context" + "fmt" + + "github.com/cortezaproject/corteza-server/store/adapters/rdbms/ddl" + "github.com/doug-martin/goqu/v9" + "github.com/jmoiron/sqlx" +) + +type ( + schema struct { + dialect goqu.DialectWrapper + } +) + +func (s *schema) TableExists(ctx context.Context, db sqlx.QueryerContext, table string) (bool, error) { + var ( + exists bool + sql = `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?` + ) + + if err := sqlx.GetContext(ctx, db, &exists, sql, table); err != nil { + return false, fmt.Errorf("could not check if table exists: %w", err) + } + + return exists, nil +} + +func (s *schema) CreateTable(ctx context.Context, db sqlx.ExtContext, t *ddl.Table) (err error) { + tt := append( + []any{&ddl.CreateTableTemplate{ + Table: t, + TrColumnTypes: columnTypTranslator, + }}, + ddl.CreateIndexTemplates(&ddl.CreateIndexTemplate{OmitFieldLength: true}, t.Indexes...)..., + ) + + return ddl.Exec(ctx, db, tt...) +} + +func columnTypTranslator(ct ddl.ColumnType) string { + switch ct.Type { + case ddl.ColumnTypeTimestamp: + return "TIMESTAMP" + case ddl.ColumnTypeBinary: + return "BLOB" + default: + return ddl.ColumnTypeTranslator(ct) + } + +} diff --git a/store/adapters/rdbms/drivers/sqlite/upgrade.go b/store/adapters/rdbms/drivers/sqlite/upgrade.go deleted file mode 100644 index 3fda5540e..000000000 --- a/store/adapters/rdbms/drivers/sqlite/upgrade.go +++ /dev/null @@ -1,273 +0,0 @@ -package sqlite - -// SQLite specific prefixes, sql -// templates, functions and other helpers - -import ( - "context" - "database/sql" - "fmt" - - "github.com/cortezaproject/corteza-server/store/adapters/rdbms" - "github.com/cortezaproject/corteza-server/store/adapters/rdbms/schema" - "go.uber.org/zap" -) - -type ( - upgrader struct { - log *zap.Logger - s *rdbms.Store - dialect *schema.CommonDialect - } -) - -// NewUpgrader returns SQLite schema upgrader -func NewUpgrader(store *rdbms.Store) *upgrader { - var g = &upgrader{ - log: zap.NewNop(), - s: store, - dialect: schema.NewCommonDialect(), - } - - // Modification to general DDL dialect to support Postgres requirements - - // Cover mysql exceptions - g.dialect.AddTemplateFunc("columnType", func(ct *schema.ColumnType) string { - switch ct.Type { - case schema.ColumnTypeTimestamp: - return "TIMESTAMP" - case schema.ColumnTypeBinary: - return "BLOB" - default: - return schema.GenColumnType(ct) - } - }) - - return g -} - -func (u *upgrader) SetLogger(l *zap.Logger) { - u.log = l -} - -// Before runs before all tables are upgraded -func (u upgrader) Before(ctx context.Context) error { - return schema.CommonUpgrades(u.log, u).Before(ctx) -} - -// After runs after all tables are upgraded -func (u upgrader) After(ctx context.Context) error { - return schema.CommonUpgrades(u.log, u).After(ctx) -} - -// CreateTable is triggered for every table defined in the rdbms package -// -// It checks if table is missing and creates it, otherwise -// it runs -func (u upgrader) CreateTable(ctx context.Context, t *schema.Table) (err error) { - var exists bool - if exists, err = u.TableExists(ctx, t.Name); err != nil { - return - } - - if !exists { - if err = u.Exec(ctx, u.dialect.CreateTable(t)); err != nil { - return err - } - - for _, i := range t.Indexes { - if err = u.Exec(ctx, u.dialect.CreateIndex(i)); err != nil { - return fmt.Errorf("could not create index %s on table %s: %w", i.Name, i.Table, err) - } - } - } else { - return u.upgradeTable(ctx, t) - } - - return nil -} - -func (u upgrader) Exec(ctx context.Context, sql string, aa ...interface{}) error { - _, err := u.s.DB().ExecContext(ctx, sql, aa...) - return err -} - -// upgradeTable applies any necessary changes connected to that specific table -func (u upgrader) upgradeTable(ctx context.Context, t *schema.Table) error { - g := schema.CommonUpgrades(u.log, u) - - switch t.Name { - default: - return g.Upgrade(ctx, t) - } -} - -func (u upgrader) TableExists(ctx context.Context, table string) (bool, error) { - var exists bool - - if err := u.s.DB().GetContext(ctx, &exists, "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = ?", table); err != nil { - return false, fmt.Errorf("could not check if table exists: %w", err) - } - - return exists, nil -} - -func (u upgrader) DropTable(ctx context.Context, table string) (dropped bool, err error) { - var exists bool - exists, err = u.TableExists(ctx, table) - if err != nil || !exists { - return false, err - } - - err = u.Exec(ctx, fmt.Sprintf(`DROP TABLE %s`, table)) - if err != nil { - return false, err - } - - return true, nil -} - -func (u upgrader) TableSchema(ctx context.Context, table string) (schema.Columns, error) { - return nil, fmt.Errorf("pending implementation") -} - -// AddColumn adds column to table -func (u upgrader) AddColumn(ctx context.Context, table string, col *schema.Column) (added bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(col.Name) != nil { - return nil - } - - if err = u.Exec(ctx, u.dialect.AddColumn(table, col)); err != nil { - return err - } - - added = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not add column %q to %q: %w", col.Name, table, err) - } - - return -} - -// DropColumn drops column from table -func (u upgrader) DropColumn(ctx context.Context, table, column string) (dropped bool, err error) { - err = func() error { - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(column) == nil { - return nil - } - - if err = u.Exec(ctx, u.dialect.DropColumn(table, column)); err != nil { - return err - } - - dropped = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not drop column %q from %q: %w", column, table, err) - } - - return -} - -// RenameColumn renames column on a table -func (u upgrader) RenameColumn(ctx context.Context, table, oldName, newName string) (changed bool, err error) { - err = func() error { - if oldName == newName { - return nil - } - - var columns schema.Columns - if columns, err = u.getColumns(ctx, table); err != nil { - return err - } - - if columns.Get(oldName) == nil { - // Old column does not exist anymore - - if columns.Get(newName) == nil { - return fmt.Errorf("old and new columns are missing") - } - - return nil - } - - if columns.Get(newName) != nil { - return fmt.Errorf("new column already exists") - - } - - if err = u.Exec(ctx, u.dialect.RenameColumn(table, oldName, newName)); err != nil { - return err - } - - changed = true - return nil - }() - - if err != nil { - return false, fmt.Errorf("could not rename column %q on table %q to %q: %w", oldName, table, newName, err) - } - - return -} - -func (u upgrader) AddPrimaryKey(ctx context.Context, table string, ind *schema.Index) (added bool, err error) { - return false, fmt.Errorf("adding primary keys on sqlite tables is not implemented") -} - -func (u upgrader) CreateIndex(ctx context.Context, ind *schema.Index) (added bool, err error) { - if err = u.Exec(ctx, u.dialect.CreateIndex(ind)); err != nil { - return false, fmt.Errorf("could not create index on table %s: %w", ind.Table, err) - } - - return true, nil -} - -// loads and returns all tables columns -func (u upgrader) getColumns(ctx context.Context, table string) (out schema.Columns, err error) { - type ( - col struct { - CID int `db:"cid"` - Name string `db:"name"` - NotNull bool `db:"notnull"` - PrimaryKey bool `db:"pk"` - DefaultValue sql.NullString `db:"dflt_value"` - Type string `db:"type"` - } - ) - - var ( - lookup = fmt.Sprintf(`PRAGMA TABLE_INFO(%q)`, table) - cols []*col - ) - - if err = u.s.DB().SelectContext(ctx, &cols, lookup, u.s.Config().DBName, table); err != nil { - return nil, err - } - - out = make([]*schema.Column, len(cols)) - for i := range cols { - out[i] = &schema.Column{ - Name: cols[i].Name, - IsNull: !cols[i].NotNull, - } - } - - return out, nil -} diff --git a/store/adapters/rdbms/filter.go b/store/adapters/rdbms/filter.go index b959da404..505887f9a 100644 --- a/store/adapters/rdbms/filter.go +++ b/store/adapters/rdbms/filter.go @@ -16,7 +16,9 @@ import ( "github.com/doug-martin/goqu/v9/exp" ) -func (f *extendedFilters) SetDefaults() { +func DefaultFilters() (f *extendedFilters) { + f = &extendedFilters{} + f.Actionlog = func(s *Store, f actionlog.Filter) (ee []goqu.Expression, _ actionlog.Filter, err error) { if ee, f, err = ActionlogFilter(f); err != nil { return @@ -178,7 +180,7 @@ func (f *extendedFilters) SetDefaults() { } if f.MemberID > 0 { - memberships := roleMemberSelectQuery(s.Config().Dialect). + memberships := roleMemberSelectQuery(s.Dialect). Select("rel_role"). Where(goqu.C("rel_user").In(f.MemberID)) @@ -198,7 +200,7 @@ func (f *extendedFilters) SetDefaults() { } if len(f.RoleID) > 0 { - members := roleMemberSelectQuery(s.Config().Dialect). + members := roleMemberSelectQuery(s.Dialect). Select("rel_user"). Where(goqu.C("rel_role").In(f.RoleID)) @@ -262,6 +264,12 @@ func (f *extendedFilters) SetDefaults() { return ee, f, err } + + return +} + +func Order(sort filter.SortExprSet, sortables map[string]string) (oo []exp.OrderedExpression, err error) { + return order(sort, sortables) } func order(sort filter.SortExprSet, sortables map[string]string) (oo []exp.OrderedExpression, err error) { @@ -270,8 +278,10 @@ func order(sort filter.SortExprSet, sortables map[string]string) (oo []exp.Order ) for _, s := range sort { - if s.Column, has = sortables[strings.ToLower(s.Column)]; !has { - return nil, fmt.Errorf("column %q is not sortable", s.Column) + if len(sortables) > 0 { + if s.Column, has = sortables[strings.ToLower(s.Column)]; !has { + return nil, fmt.Errorf("column %q is not sortable", s.Column) + } } if s.Descending { diff --git a/store/adapters/rdbms/log.go b/store/adapters/rdbms/log.go index c01f4597a..334ca269e 100644 --- a/store/adapters/rdbms/log.go +++ b/store/adapters/rdbms/log.go @@ -11,11 +11,11 @@ import ( // // It checks the given context for logger before falling back to one set on the store func (s Store) log(ctx context.Context) *zap.Logger { - return logger.ContextValue(ctx, s.logger). + return logger.ContextValue(ctx, s.Logger, logger.Default(), zap.NewNop()). Named("store.rdbms"). WithOptions(zap.AddCallerSkip(2)) } func (s Store) SetLogger(logger *zap.Logger) { - s.logger = logger + s.Logger = logger } diff --git a/store/adapters/rdbms/rdbms.gen.go b/store/adapters/rdbms/rdbms.gen.go index e7917cefc..dfe9f2178 100644 --- a/store/adapters/rdbms/rdbms.gen.go +++ b/store/adapters/rdbms/rdbms.gen.go @@ -80,7 +80,7 @@ func (s *Store) CreateActionlog(ctx context.Context, rr ...*actionlogType.Action return } - if err = s.Exec(ctx, actionlogInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, actionlogInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -97,7 +97,7 @@ func (s *Store) UpdateActionlog(ctx context.Context, rr ...*actionlogType.Action return } - if err = s.Exec(ctx, actionlogUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, actionlogUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -114,7 +114,7 @@ func (s *Store) UpsertActionlog(ctx context.Context, rr ...*actionlogType.Action return } - if err = s.Exec(ctx, actionlogUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, actionlogUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -127,7 +127,7 @@ func (s *Store) UpsertActionlog(ctx context.Context, rr ...*actionlogType.Action // This function is auto-generated func (s *Store) DeleteActionlog(ctx context.Context, rr ...*actionlogType.Action) (err error) { for i := range rr { - if err = s.Exec(ctx, actionlogDeleteQuery(s.config.Dialect, actionlogPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, actionlogDeleteQuery(s.Dialect, actionlogPrimaryKeys(rr[i]))); err != nil { return } } @@ -139,14 +139,14 @@ func (s *Store) DeleteActionlog(ctx context.Context, rr ...*actionlogType.Action // // This function is auto-generated func (s *Store) DeleteActionlogByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, actionlogDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, actionlogDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateActionlogs Deletes all rows from the actionlog collection -func (s *Store) TruncateActionlogs(ctx context.Context) error { - return s.Exec(ctx, actionlogTruncateQuery(s.config.Dialect)) +func (s Store) TruncateActionlogs(ctx context.Context) error { + return s.Exec(ctx, actionlogTruncateQuery(s.Dialect)) } // SearchActionlogs returns (filtered) set of Actionlogs @@ -183,9 +183,9 @@ func (s *Store) QueryActionlogs( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Actionlog != nil { + if s.Filters.Actionlog != nil { // extended filter set - tExpr, f, err = s.config.Filters.Actionlog(s, f) + tExpr, f, err = s.Filters.Actionlog(s, f) } else { // using generated filter tExpr, f, err = ActionlogFilter(f) @@ -198,7 +198,7 @@ func (s *Store) QueryActionlogs( expr = append(expr, tExpr...) - query := actionlogSelectQuery(s.config.Dialect).Where(expr...) + query := actionlogSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableActionlogFields()); err != nil { @@ -265,7 +265,7 @@ func (s *Store) LookupActionlogByID(ctx context.Context, id uint64) (_ *actionlo var ( rows *sql.Rows aux = new(auxActionlog) - lookup = actionlogSelectQuery(s.config.Dialect).Where( + lookup = actionlogSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -371,7 +371,7 @@ func (s *Store) CreateApigwFilter(ctx context.Context, rr ...*systemType.ApigwFi return } - if err = s.Exec(ctx, apigwFilterInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwFilterInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -388,7 +388,7 @@ func (s *Store) UpdateApigwFilter(ctx context.Context, rr ...*systemType.ApigwFi return } - if err = s.Exec(ctx, apigwFilterUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwFilterUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -405,7 +405,7 @@ func (s *Store) UpsertApigwFilter(ctx context.Context, rr ...*systemType.ApigwFi return } - if err = s.Exec(ctx, apigwFilterUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwFilterUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -418,7 +418,7 @@ func (s *Store) UpsertApigwFilter(ctx context.Context, rr ...*systemType.ApigwFi // This function is auto-generated func (s *Store) DeleteApigwFilter(ctx context.Context, rr ...*systemType.ApigwFilter) (err error) { for i := range rr { - if err = s.Exec(ctx, apigwFilterDeleteQuery(s.config.Dialect, apigwFilterPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, apigwFilterDeleteQuery(s.Dialect, apigwFilterPrimaryKeys(rr[i]))); err != nil { return } } @@ -430,14 +430,14 @@ func (s *Store) DeleteApigwFilter(ctx context.Context, rr ...*systemType.ApigwFi // // This function is auto-generated func (s *Store) DeleteApigwFilterByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, apigwFilterDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, apigwFilterDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateApigwFilters Deletes all rows from the apigwFilter collection -func (s *Store) TruncateApigwFilters(ctx context.Context) error { - return s.Exec(ctx, apigwFilterTruncateQuery(s.config.Dialect)) +func (s Store) TruncateApigwFilters(ctx context.Context) error { + return s.Exec(ctx, apigwFilterTruncateQuery(s.Dialect)) } // SearchApigwFilters returns (filtered) set of ApigwFilters @@ -637,9 +637,9 @@ func (s *Store) QueryApigwFilters( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ApigwFilter != nil { + if s.Filters.ApigwFilter != nil { // extended filter set - tExpr, f, err = s.config.Filters.ApigwFilter(s, f) + tExpr, f, err = s.Filters.ApigwFilter(s, f) } else { // using generated filter tExpr, f, err = ApigwFilterFilter(f) @@ -661,7 +661,7 @@ func (s *Store) QueryApigwFilters( } } - query := apigwFilterSelectQuery(s.config.Dialect).Where(expr...) + query := apigwFilterSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableApigwFilterFields()); err != nil { @@ -738,7 +738,7 @@ func (s *Store) LookupApigwFilterByID(ctx context.Context, id uint64) (_ *system var ( rows *sql.Rows aux = new(auxApigwFilter) - lookup = apigwFilterSelectQuery(s.config.Dialect).Where( + lookup = apigwFilterSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -778,7 +778,7 @@ func (s *Store) LookupApigwFilterByRoute(ctx context.Context, route uint64) (_ * var ( rows *sql.Rows aux = new(auxApigwFilter) - lookup = apigwFilterSelectQuery(s.config.Dialect).Where( + lookup = apigwFilterSelectQuery(s.Dialect).Where( goqu.I("rel_route").Eq(route), ).Limit(1) ) @@ -893,7 +893,7 @@ func (s *Store) CreateApigwRoute(ctx context.Context, rr ...*systemType.ApigwRou return } - if err = s.Exec(ctx, apigwRouteInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwRouteInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -910,7 +910,7 @@ func (s *Store) UpdateApigwRoute(ctx context.Context, rr ...*systemType.ApigwRou return } - if err = s.Exec(ctx, apigwRouteUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwRouteUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -927,7 +927,7 @@ func (s *Store) UpsertApigwRoute(ctx context.Context, rr ...*systemType.ApigwRou return } - if err = s.Exec(ctx, apigwRouteUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, apigwRouteUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -940,7 +940,7 @@ func (s *Store) UpsertApigwRoute(ctx context.Context, rr ...*systemType.ApigwRou // This function is auto-generated func (s *Store) DeleteApigwRoute(ctx context.Context, rr ...*systemType.ApigwRoute) (err error) { for i := range rr { - if err = s.Exec(ctx, apigwRouteDeleteQuery(s.config.Dialect, apigwRoutePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, apigwRouteDeleteQuery(s.Dialect, apigwRoutePrimaryKeys(rr[i]))); err != nil { return } } @@ -952,14 +952,14 @@ func (s *Store) DeleteApigwRoute(ctx context.Context, rr ...*systemType.ApigwRou // // This function is auto-generated func (s *Store) DeleteApigwRouteByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, apigwRouteDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, apigwRouteDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateApigwRoutes Deletes all rows from the apigwRoute collection -func (s *Store) TruncateApigwRoutes(ctx context.Context) error { - return s.Exec(ctx, apigwRouteTruncateQuery(s.config.Dialect)) +func (s Store) TruncateApigwRoutes(ctx context.Context) error { + return s.Exec(ctx, apigwRouteTruncateQuery(s.Dialect)) } // SearchApigwRoutes returns (filtered) set of ApigwRoutes @@ -1159,9 +1159,9 @@ func (s *Store) QueryApigwRoutes( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ApigwRoute != nil { + if s.Filters.ApigwRoute != nil { // extended filter set - tExpr, f, err = s.config.Filters.ApigwRoute(s, f) + tExpr, f, err = s.Filters.ApigwRoute(s, f) } else { // using generated filter tExpr, f, err = ApigwRouteFilter(f) @@ -1183,7 +1183,7 @@ func (s *Store) QueryApigwRoutes( } } - query := apigwRouteSelectQuery(s.config.Dialect).Where(expr...) + query := apigwRouteSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableApigwRouteFields()); err != nil { @@ -1262,7 +1262,7 @@ func (s *Store) LookupApigwRouteByID(ctx context.Context, id uint64) (_ *systemT var ( rows *sql.Rows aux = new(auxApigwRoute) - lookup = apigwRouteSelectQuery(s.config.Dialect).Where( + lookup = apigwRouteSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -1304,7 +1304,7 @@ func (s *Store) LookupApigwRouteByEndpoint(ctx context.Context, endpoint string) var ( rows *sql.Rows aux = new(auxApigwRoute) - lookup = apigwRouteSelectQuery(s.config.Dialect).Where( + lookup = apigwRouteSelectQuery(s.Dialect).Where( goqu.I("endpoint").Eq(endpoint), ).Limit(1) ) @@ -1419,7 +1419,7 @@ func (s *Store) CreateApplication(ctx context.Context, rr ...*systemType.Applica return } - if err = s.Exec(ctx, applicationInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, applicationInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1436,7 +1436,7 @@ func (s *Store) UpdateApplication(ctx context.Context, rr ...*systemType.Applica return } - if err = s.Exec(ctx, applicationUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, applicationUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1453,7 +1453,7 @@ func (s *Store) UpsertApplication(ctx context.Context, rr ...*systemType.Applica return } - if err = s.Exec(ctx, applicationUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, applicationUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1466,7 +1466,7 @@ func (s *Store) UpsertApplication(ctx context.Context, rr ...*systemType.Applica // This function is auto-generated func (s *Store) DeleteApplication(ctx context.Context, rr ...*systemType.Application) (err error) { for i := range rr { - if err = s.Exec(ctx, applicationDeleteQuery(s.config.Dialect, applicationPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, applicationDeleteQuery(s.Dialect, applicationPrimaryKeys(rr[i]))); err != nil { return } } @@ -1478,14 +1478,14 @@ func (s *Store) DeleteApplication(ctx context.Context, rr ...*systemType.Applica // // This function is auto-generated func (s *Store) DeleteApplicationByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, applicationDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, applicationDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateApplications Deletes all rows from the application collection -func (s *Store) TruncateApplications(ctx context.Context) error { - return s.Exec(ctx, applicationTruncateQuery(s.config.Dialect)) +func (s Store) TruncateApplications(ctx context.Context) error { + return s.Exec(ctx, applicationTruncateQuery(s.Dialect)) } // SearchApplications returns (filtered) set of Applications @@ -1685,9 +1685,9 @@ func (s *Store) QueryApplications( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Application != nil { + if s.Filters.Application != nil { // extended filter set - tExpr, f, err = s.config.Filters.Application(s, f) + tExpr, f, err = s.Filters.Application(s, f) } else { // using generated filter tExpr, f, err = ApplicationFilter(f) @@ -1709,7 +1709,7 @@ func (s *Store) QueryApplications( } } - query := applicationSelectQuery(s.config.Dialect).Where(expr...) + query := applicationSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableApplicationFields()); err != nil { @@ -1788,7 +1788,7 @@ func (s *Store) LookupApplicationByID(ctx context.Context, id uint64) (_ *system var ( rows *sql.Rows aux = new(auxApplication) - lookup = applicationSelectQuery(s.config.Dialect).Where( + lookup = applicationSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -1903,7 +1903,7 @@ func (s *Store) CreateAttachment(ctx context.Context, rr ...*systemType.Attachme return } - if err = s.Exec(ctx, attachmentInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, attachmentInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1920,7 +1920,7 @@ func (s *Store) UpdateAttachment(ctx context.Context, rr ...*systemType.Attachme return } - if err = s.Exec(ctx, attachmentUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, attachmentUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1937,7 +1937,7 @@ func (s *Store) UpsertAttachment(ctx context.Context, rr ...*systemType.Attachme return } - if err = s.Exec(ctx, attachmentUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, attachmentUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -1950,7 +1950,7 @@ func (s *Store) UpsertAttachment(ctx context.Context, rr ...*systemType.Attachme // This function is auto-generated func (s *Store) DeleteAttachment(ctx context.Context, rr ...*systemType.Attachment) (err error) { for i := range rr { - if err = s.Exec(ctx, attachmentDeleteQuery(s.config.Dialect, attachmentPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, attachmentDeleteQuery(s.Dialect, attachmentPrimaryKeys(rr[i]))); err != nil { return } } @@ -1962,14 +1962,14 @@ func (s *Store) DeleteAttachment(ctx context.Context, rr ...*systemType.Attachme // // This function is auto-generated func (s *Store) DeleteAttachmentByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, attachmentDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, attachmentDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAttachments Deletes all rows from the attachment collection -func (s *Store) TruncateAttachments(ctx context.Context) error { - return s.Exec(ctx, attachmentTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAttachments(ctx context.Context) error { + return s.Exec(ctx, attachmentTruncateQuery(s.Dialect)) } // SearchAttachments returns (filtered) set of Attachments @@ -2169,9 +2169,9 @@ func (s *Store) QueryAttachments( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Attachment != nil { + if s.Filters.Attachment != nil { // extended filter set - tExpr, f, err = s.config.Filters.Attachment(s, f) + tExpr, f, err = s.Filters.Attachment(s, f) } else { // using generated filter tExpr, f, err = AttachmentFilter(f) @@ -2193,7 +2193,7 @@ func (s *Store) QueryAttachments( } } - query := attachmentSelectQuery(s.config.Dialect).Where(expr...) + query := attachmentSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableAttachmentFields()); err != nil { @@ -2270,7 +2270,7 @@ func (s *Store) LookupAttachmentByID(ctx context.Context, id uint64) (_ *systemT var ( rows *sql.Rows aux = new(auxAttachment) - lookup = attachmentSelectQuery(s.config.Dialect).Where( + lookup = attachmentSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -2385,7 +2385,7 @@ func (s *Store) CreateAuthClient(ctx context.Context, rr ...*systemType.AuthClie return } - if err = s.Exec(ctx, authClientInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authClientInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2402,7 +2402,7 @@ func (s *Store) UpdateAuthClient(ctx context.Context, rr ...*systemType.AuthClie return } - if err = s.Exec(ctx, authClientUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authClientUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2419,7 +2419,7 @@ func (s *Store) UpsertAuthClient(ctx context.Context, rr ...*systemType.AuthClie return } - if err = s.Exec(ctx, authClientUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authClientUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2432,7 +2432,7 @@ func (s *Store) UpsertAuthClient(ctx context.Context, rr ...*systemType.AuthClie // This function is auto-generated func (s *Store) DeleteAuthClient(ctx context.Context, rr ...*systemType.AuthClient) (err error) { for i := range rr { - if err = s.Exec(ctx, authClientDeleteQuery(s.config.Dialect, authClientPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, authClientDeleteQuery(s.Dialect, authClientPrimaryKeys(rr[i]))); err != nil { return } } @@ -2444,14 +2444,14 @@ func (s *Store) DeleteAuthClient(ctx context.Context, rr ...*systemType.AuthClie // // This function is auto-generated func (s *Store) DeleteAuthClientByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, authClientDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, authClientDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAuthClients Deletes all rows from the authClient collection -func (s *Store) TruncateAuthClients(ctx context.Context) error { - return s.Exec(ctx, authClientTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAuthClients(ctx context.Context) error { + return s.Exec(ctx, authClientTruncateQuery(s.Dialect)) } // SearchAuthClients returns (filtered) set of AuthClients @@ -2651,9 +2651,9 @@ func (s *Store) QueryAuthClients( sortExpr []exp.OrderedExpression ) - if s.config.Filters.AuthClient != nil { + if s.Filters.AuthClient != nil { // extended filter set - tExpr, f, err = s.config.Filters.AuthClient(s, f) + tExpr, f, err = s.Filters.AuthClient(s, f) } else { // using generated filter tExpr, f, err = AuthClientFilter(f) @@ -2675,7 +2675,7 @@ func (s *Store) QueryAuthClients( } } - query := authClientSelectQuery(s.config.Dialect).Where(expr...) + query := authClientSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableAuthClientFields()); err != nil { @@ -2754,7 +2754,7 @@ func (s *Store) LookupAuthClientByID(ctx context.Context, id uint64) (_ *systemT var ( rows *sql.Rows aux = new(auxAuthClient) - lookup = authClientSelectQuery(s.config.Dialect).Where( + lookup = authClientSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -2796,8 +2796,8 @@ func (s *Store) LookupAuthClientByHandle(ctx context.Context, handle string) (_ var ( rows *sql.Rows aux = new(auxAuthClient) - lookup = authClientSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = authClientSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -2947,7 +2947,7 @@ func (s *Store) CreateAuthConfirmedClient(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, authConfirmedClientInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authConfirmedClientInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2964,7 +2964,7 @@ func (s *Store) UpdateAuthConfirmedClient(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, authConfirmedClientUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authConfirmedClientUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2981,7 +2981,7 @@ func (s *Store) UpsertAuthConfirmedClient(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, authConfirmedClientUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authConfirmedClientUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -2994,7 +2994,7 @@ func (s *Store) UpsertAuthConfirmedClient(ctx context.Context, rr ...*systemType // This function is auto-generated func (s *Store) DeleteAuthConfirmedClient(ctx context.Context, rr ...*systemType.AuthConfirmedClient) (err error) { for i := range rr { - if err = s.Exec(ctx, authConfirmedClientDeleteQuery(s.config.Dialect, authConfirmedClientPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, authConfirmedClientDeleteQuery(s.Dialect, authConfirmedClientPrimaryKeys(rr[i]))); err != nil { return } } @@ -3006,15 +3006,15 @@ func (s *Store) DeleteAuthConfirmedClient(ctx context.Context, rr ...*systemType // // This function is auto-generated func (s *Store) DeleteAuthConfirmedClientByUserIDClientID(ctx context.Context, userID uint64, clientID uint64) error { - return s.Exec(ctx, authConfirmedClientDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, authConfirmedClientDeleteQuery(s.Dialect, goqu.Ex{ "rel_user": userID, "rel_client": clientID, })) } // TruncateAuthConfirmedClients Deletes all rows from the authConfirmedClient collection -func (s *Store) TruncateAuthConfirmedClients(ctx context.Context) error { - return s.Exec(ctx, authConfirmedClientTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAuthConfirmedClients(ctx context.Context) error { + return s.Exec(ctx, authConfirmedClientTruncateQuery(s.Dialect)) } // SearchAuthConfirmedClients returns (filtered) set of AuthConfirmedClients @@ -3049,9 +3049,9 @@ func (s *Store) QueryAuthConfirmedClients( expr, tExpr []goqu.Expression ) - if s.config.Filters.AuthConfirmedClient != nil { + if s.Filters.AuthConfirmedClient != nil { // extended filter set - tExpr, f, err = s.config.Filters.AuthConfirmedClient(s, f) + tExpr, f, err = s.Filters.AuthConfirmedClient(s, f) } else { // using generated filter tExpr, f, err = AuthConfirmedClientFilter(f) @@ -3064,7 +3064,7 @@ func (s *Store) QueryAuthConfirmedClients( expr = append(expr, tExpr...) - query := authConfirmedClientSelectQuery(s.config.Dialect).Where(expr...) + query := authConfirmedClientSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -3121,7 +3121,7 @@ func (s *Store) LookupAuthConfirmedClientByUserIDClientID(ctx context.Context, u var ( rows *sql.Rows aux = new(auxAuthConfirmedClient) - lookup = authConfirmedClientSelectQuery(s.config.Dialect).Where( + lookup = authConfirmedClientSelectQuery(s.Dialect).Where( goqu.I("rel_user").Eq(userID), goqu.I("rel_client").Eq(clientID), ).Limit(1) @@ -3239,7 +3239,7 @@ func (s *Store) CreateAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa return } - if err = s.Exec(ctx, authOa2tokenInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authOa2tokenInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3256,7 +3256,7 @@ func (s *Store) UpdateAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa return } - if err = s.Exec(ctx, authOa2tokenUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authOa2tokenUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3273,7 +3273,7 @@ func (s *Store) UpsertAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa return } - if err = s.Exec(ctx, authOa2tokenUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authOa2tokenUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3286,7 +3286,7 @@ func (s *Store) UpsertAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa // This function is auto-generated func (s *Store) DeleteAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa2token) (err error) { for i := range rr { - if err = s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, authOa2tokenPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, authOa2tokenPrimaryKeys(rr[i]))); err != nil { return } } @@ -3298,14 +3298,14 @@ func (s *Store) DeleteAuthOa2token(ctx context.Context, rr ...*systemType.AuthOa // // This function is auto-generated func (s *Store) DeleteAuthOa2tokenByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, authOa2tokenDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, authOa2tokenDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAuthOa2tokens Deletes all rows from the authOa2token collection -func (s *Store) TruncateAuthOa2tokens(ctx context.Context) error { - return s.Exec(ctx, authOa2tokenTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAuthOa2tokens(ctx context.Context) error { + return s.Exec(ctx, authOa2tokenTruncateQuery(s.Dialect)) } // SearchAuthOa2tokens returns (filtered) set of AuthOa2tokens @@ -3340,9 +3340,9 @@ func (s *Store) QueryAuthOa2tokens( expr, tExpr []goqu.Expression ) - if s.config.Filters.AuthOa2token != nil { + if s.Filters.AuthOa2token != nil { // extended filter set - tExpr, f, err = s.config.Filters.AuthOa2token(s, f) + tExpr, f, err = s.Filters.AuthOa2token(s, f) } else { // using generated filter tExpr, f, err = AuthOa2tokenFilter(f) @@ -3355,7 +3355,7 @@ func (s *Store) QueryAuthOa2tokens( expr = append(expr, tExpr...) - query := authOa2tokenSelectQuery(s.config.Dialect).Where(expr...) + query := authOa2tokenSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -3412,7 +3412,7 @@ func (s *Store) LookupAuthOa2tokenByID(ctx context.Context, id uint64) (_ *syste var ( rows *sql.Rows aux = new(auxAuthOa2token) - lookup = authOa2tokenSelectQuery(s.config.Dialect).Where( + lookup = authOa2tokenSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -3452,7 +3452,7 @@ func (s *Store) LookupAuthOa2tokenByCode(ctx context.Context, code string) (_ *s var ( rows *sql.Rows aux = new(auxAuthOa2token) - lookup = authOa2tokenSelectQuery(s.config.Dialect).Where( + lookup = authOa2tokenSelectQuery(s.Dialect).Where( goqu.I("code").Eq(code), ).Limit(1) ) @@ -3492,7 +3492,7 @@ func (s *Store) LookupAuthOa2tokenByAccess(ctx context.Context, access string) ( var ( rows *sql.Rows aux = new(auxAuthOa2token) - lookup = authOa2tokenSelectQuery(s.config.Dialect).Where( + lookup = authOa2tokenSelectQuery(s.Dialect).Where( goqu.I("access").Eq(access), ).Limit(1) ) @@ -3532,7 +3532,7 @@ func (s *Store) LookupAuthOa2tokenByRefresh(ctx context.Context, refresh string) var ( rows *sql.Rows aux = new(auxAuthOa2token) - lookup = authOa2tokenSelectQuery(s.config.Dialect).Where( + lookup = authOa2tokenSelectQuery(s.Dialect).Where( goqu.I("refresh").Eq(refresh), ).Limit(1) ) @@ -3643,7 +3643,7 @@ func (s *Store) CreateAuthSession(ctx context.Context, rr ...*systemType.AuthSes return } - if err = s.Exec(ctx, authSessionInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authSessionInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3660,7 +3660,7 @@ func (s *Store) UpdateAuthSession(ctx context.Context, rr ...*systemType.AuthSes return } - if err = s.Exec(ctx, authSessionUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authSessionUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3677,7 +3677,7 @@ func (s *Store) UpsertAuthSession(ctx context.Context, rr ...*systemType.AuthSes return } - if err = s.Exec(ctx, authSessionUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, authSessionUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3690,7 +3690,7 @@ func (s *Store) UpsertAuthSession(ctx context.Context, rr ...*systemType.AuthSes // This function is auto-generated func (s *Store) DeleteAuthSession(ctx context.Context, rr ...*systemType.AuthSession) (err error) { for i := range rr { - if err = s.Exec(ctx, authSessionDeleteQuery(s.config.Dialect, authSessionPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, authSessionDeleteQuery(s.Dialect, authSessionPrimaryKeys(rr[i]))); err != nil { return } } @@ -3702,14 +3702,14 @@ func (s *Store) DeleteAuthSession(ctx context.Context, rr ...*systemType.AuthSes // // This function is auto-generated func (s *Store) DeleteAuthSessionByID(ctx context.Context, id string) error { - return s.Exec(ctx, authSessionDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, authSessionDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAuthSessions Deletes all rows from the authSession collection -func (s *Store) TruncateAuthSessions(ctx context.Context) error { - return s.Exec(ctx, authSessionTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAuthSessions(ctx context.Context) error { + return s.Exec(ctx, authSessionTruncateQuery(s.Dialect)) } // SearchAuthSessions returns (filtered) set of AuthSessions @@ -3744,9 +3744,9 @@ func (s *Store) QueryAuthSessions( expr, tExpr []goqu.Expression ) - if s.config.Filters.AuthSession != nil { + if s.Filters.AuthSession != nil { // extended filter set - tExpr, f, err = s.config.Filters.AuthSession(s, f) + tExpr, f, err = s.Filters.AuthSession(s, f) } else { // using generated filter tExpr, f, err = AuthSessionFilter(f) @@ -3759,7 +3759,7 @@ func (s *Store) QueryAuthSessions( expr = append(expr, tExpr...) - query := authSessionSelectQuery(s.config.Dialect).Where(expr...) + query := authSessionSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -3816,7 +3816,7 @@ func (s *Store) LookupAuthSessionByID(ctx context.Context, id string) (_ *system var ( rows *sql.Rows aux = new(auxAuthSession) - lookup = authSessionSelectQuery(s.config.Dialect).Where( + lookup = authSessionSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -3927,7 +3927,7 @@ func (s *Store) CreateAutomationSession(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationSessionInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationSessionInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3944,7 +3944,7 @@ func (s *Store) UpdateAutomationSession(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationSessionUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationSessionUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3961,7 +3961,7 @@ func (s *Store) UpsertAutomationSession(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationSessionUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationSessionUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -3974,7 +3974,7 @@ func (s *Store) UpsertAutomationSession(ctx context.Context, rr ...*automationTy // This function is auto-generated func (s *Store) DeleteAutomationSession(ctx context.Context, rr ...*automationType.Session) (err error) { for i := range rr { - if err = s.Exec(ctx, automationSessionDeleteQuery(s.config.Dialect, automationSessionPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, automationSessionDeleteQuery(s.Dialect, automationSessionPrimaryKeys(rr[i]))); err != nil { return } } @@ -3986,14 +3986,14 @@ func (s *Store) DeleteAutomationSession(ctx context.Context, rr ...*automationTy // // This function is auto-generated func (s *Store) DeleteAutomationSessionByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, automationSessionDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, automationSessionDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAutomationSessions Deletes all rows from the automationSession collection -func (s *Store) TruncateAutomationSessions(ctx context.Context) error { - return s.Exec(ctx, automationSessionTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAutomationSessions(ctx context.Context) error { + return s.Exec(ctx, automationSessionTruncateQuery(s.Dialect)) } // SearchAutomationSessions returns (filtered) set of AutomationSessions @@ -4193,9 +4193,9 @@ func (s *Store) QueryAutomationSessions( sortExpr []exp.OrderedExpression ) - if s.config.Filters.AutomationSession != nil { + if s.Filters.AutomationSession != nil { // extended filter set - tExpr, f, err = s.config.Filters.AutomationSession(s, f) + tExpr, f, err = s.Filters.AutomationSession(s, f) } else { // using generated filter tExpr, f, err = AutomationSessionFilter(f) @@ -4217,7 +4217,7 @@ func (s *Store) QueryAutomationSessions( } } - query := automationSessionSelectQuery(s.config.Dialect).Where(expr...) + query := automationSessionSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableAutomationSessionFields()); err != nil { @@ -4296,7 +4296,7 @@ func (s *Store) LookupAutomationSessionByID(ctx context.Context, id uint64) (_ * var ( rows *sql.Rows aux = new(auxAutomationSession) - lookup = automationSessionSelectQuery(s.config.Dialect).Where( + lookup = automationSessionSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -4415,7 +4415,7 @@ func (s *Store) CreateAutomationTrigger(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationTriggerInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationTriggerInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4432,7 +4432,7 @@ func (s *Store) UpdateAutomationTrigger(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationTriggerUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationTriggerUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4449,7 +4449,7 @@ func (s *Store) UpsertAutomationTrigger(ctx context.Context, rr ...*automationTy return } - if err = s.Exec(ctx, automationTriggerUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationTriggerUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4462,7 +4462,7 @@ func (s *Store) UpsertAutomationTrigger(ctx context.Context, rr ...*automationTy // This function is auto-generated func (s *Store) DeleteAutomationTrigger(ctx context.Context, rr ...*automationType.Trigger) (err error) { for i := range rr { - if err = s.Exec(ctx, automationTriggerDeleteQuery(s.config.Dialect, automationTriggerPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, automationTriggerDeleteQuery(s.Dialect, automationTriggerPrimaryKeys(rr[i]))); err != nil { return } } @@ -4474,14 +4474,14 @@ func (s *Store) DeleteAutomationTrigger(ctx context.Context, rr ...*automationTy // // This function is auto-generated func (s *Store) DeleteAutomationTriggerByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, automationTriggerDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, automationTriggerDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAutomationTriggers Deletes all rows from the automationTrigger collection -func (s *Store) TruncateAutomationTriggers(ctx context.Context) error { - return s.Exec(ctx, automationTriggerTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAutomationTriggers(ctx context.Context) error { + return s.Exec(ctx, automationTriggerTruncateQuery(s.Dialect)) } // SearchAutomationTriggers returns (filtered) set of AutomationTriggers @@ -4681,9 +4681,9 @@ func (s *Store) QueryAutomationTriggers( sortExpr []exp.OrderedExpression ) - if s.config.Filters.AutomationTrigger != nil { + if s.Filters.AutomationTrigger != nil { // extended filter set - tExpr, f, err = s.config.Filters.AutomationTrigger(s, f) + tExpr, f, err = s.Filters.AutomationTrigger(s, f) } else { // using generated filter tExpr, f, err = AutomationTriggerFilter(f) @@ -4705,7 +4705,7 @@ func (s *Store) QueryAutomationTriggers( } } - query := automationTriggerSelectQuery(s.config.Dialect).Where(expr...) + query := automationTriggerSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableAutomationTriggerFields()); err != nil { @@ -4784,7 +4784,7 @@ func (s *Store) LookupAutomationTriggerByID(ctx context.Context, id uint64) (_ * var ( rows *sql.Rows aux = new(auxAutomationTrigger) - lookup = automationTriggerSelectQuery(s.config.Dialect).Where( + lookup = automationTriggerSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -4899,7 +4899,7 @@ func (s *Store) CreateAutomationWorkflow(ctx context.Context, rr ...*automationT return } - if err = s.Exec(ctx, automationWorkflowInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationWorkflowInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4916,7 +4916,7 @@ func (s *Store) UpdateAutomationWorkflow(ctx context.Context, rr ...*automationT return } - if err = s.Exec(ctx, automationWorkflowUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationWorkflowUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4933,7 +4933,7 @@ func (s *Store) UpsertAutomationWorkflow(ctx context.Context, rr ...*automationT return } - if err = s.Exec(ctx, automationWorkflowUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, automationWorkflowUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -4946,7 +4946,7 @@ func (s *Store) UpsertAutomationWorkflow(ctx context.Context, rr ...*automationT // This function is auto-generated func (s *Store) DeleteAutomationWorkflow(ctx context.Context, rr ...*automationType.Workflow) (err error) { for i := range rr { - if err = s.Exec(ctx, automationWorkflowDeleteQuery(s.config.Dialect, automationWorkflowPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, automationWorkflowDeleteQuery(s.Dialect, automationWorkflowPrimaryKeys(rr[i]))); err != nil { return } } @@ -4958,14 +4958,14 @@ func (s *Store) DeleteAutomationWorkflow(ctx context.Context, rr ...*automationT // // This function is auto-generated func (s *Store) DeleteAutomationWorkflowByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, automationWorkflowDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, automationWorkflowDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateAutomationWorkflows Deletes all rows from the automationWorkflow collection -func (s *Store) TruncateAutomationWorkflows(ctx context.Context) error { - return s.Exec(ctx, automationWorkflowTruncateQuery(s.config.Dialect)) +func (s Store) TruncateAutomationWorkflows(ctx context.Context) error { + return s.Exec(ctx, automationWorkflowTruncateQuery(s.Dialect)) } // SearchAutomationWorkflows returns (filtered) set of AutomationWorkflows @@ -5165,9 +5165,9 @@ func (s *Store) QueryAutomationWorkflows( sortExpr []exp.OrderedExpression ) - if s.config.Filters.AutomationWorkflow != nil { + if s.Filters.AutomationWorkflow != nil { // extended filter set - tExpr, f, err = s.config.Filters.AutomationWorkflow(s, f) + tExpr, f, err = s.Filters.AutomationWorkflow(s, f) } else { // using generated filter tExpr, f, err = AutomationWorkflowFilter(f) @@ -5189,7 +5189,7 @@ func (s *Store) QueryAutomationWorkflows( } } - query := automationWorkflowSelectQuery(s.config.Dialect).Where(expr...) + query := automationWorkflowSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableAutomationWorkflowFields()); err != nil { @@ -5268,7 +5268,7 @@ func (s *Store) LookupAutomationWorkflowByID(ctx context.Context, id uint64) (_ var ( rows *sql.Rows aux = new(auxAutomationWorkflow) - lookup = automationWorkflowSelectQuery(s.config.Dialect).Where( + lookup = automationWorkflowSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -5310,8 +5310,8 @@ func (s *Store) LookupAutomationWorkflowByHandle(ctx context.Context, handle str var ( rows *sql.Rows aux = new(auxAutomationWorkflow) - lookup = automationWorkflowSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = automationWorkflowSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -5457,7 +5457,7 @@ func (s *Store) CreateComposeAttachment(ctx context.Context, rr ...*composeType. return } - if err = s.Exec(ctx, composeAttachmentInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeAttachmentInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5474,7 +5474,7 @@ func (s *Store) UpdateComposeAttachment(ctx context.Context, rr ...*composeType. return } - if err = s.Exec(ctx, composeAttachmentUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeAttachmentUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5491,7 +5491,7 @@ func (s *Store) UpsertComposeAttachment(ctx context.Context, rr ...*composeType. return } - if err = s.Exec(ctx, composeAttachmentUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeAttachmentUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5504,7 +5504,7 @@ func (s *Store) UpsertComposeAttachment(ctx context.Context, rr ...*composeType. // This function is auto-generated func (s *Store) DeleteComposeAttachment(ctx context.Context, rr ...*composeType.Attachment) (err error) { for i := range rr { - if err = s.Exec(ctx, composeAttachmentDeleteQuery(s.config.Dialect, composeAttachmentPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeAttachmentDeleteQuery(s.Dialect, composeAttachmentPrimaryKeys(rr[i]))); err != nil { return } } @@ -5516,14 +5516,14 @@ func (s *Store) DeleteComposeAttachment(ctx context.Context, rr ...*composeType. // // This function is auto-generated func (s *Store) DeleteComposeAttachmentByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composeAttachmentDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeAttachmentDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeAttachments Deletes all rows from the composeAttachment collection -func (s *Store) TruncateComposeAttachments(ctx context.Context) error { - return s.Exec(ctx, composeAttachmentTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeAttachments(ctx context.Context) error { + return s.Exec(ctx, composeAttachmentTruncateQuery(s.Dialect)) } // SearchComposeAttachments returns (filtered) set of ComposeAttachments @@ -5723,9 +5723,9 @@ func (s *Store) QueryComposeAttachments( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposeAttachment != nil { + if s.Filters.ComposeAttachment != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeAttachment(s, f) + tExpr, f, err = s.Filters.ComposeAttachment(s, f) } else { // using generated filter tExpr, f, err = ComposeAttachmentFilter(f) @@ -5747,7 +5747,7 @@ func (s *Store) QueryComposeAttachments( } } - query := composeAttachmentSelectQuery(s.config.Dialect).Where(expr...) + query := composeAttachmentSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposeAttachmentFields()); err != nil { @@ -5824,7 +5824,7 @@ func (s *Store) LookupComposeAttachmentByID(ctx context.Context, id uint64) (_ * var ( rows *sql.Rows aux = new(auxComposeAttachment) - lookup = composeAttachmentSelectQuery(s.config.Dialect).Where( + lookup = composeAttachmentSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -5939,7 +5939,7 @@ func (s *Store) CreateComposeChart(ctx context.Context, rr ...*composeType.Chart return } - if err = s.Exec(ctx, composeChartInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeChartInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5956,7 +5956,7 @@ func (s *Store) UpdateComposeChart(ctx context.Context, rr ...*composeType.Chart return } - if err = s.Exec(ctx, composeChartUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeChartUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5973,7 +5973,7 @@ func (s *Store) UpsertComposeChart(ctx context.Context, rr ...*composeType.Chart return } - if err = s.Exec(ctx, composeChartUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeChartUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -5986,7 +5986,7 @@ func (s *Store) UpsertComposeChart(ctx context.Context, rr ...*composeType.Chart // This function is auto-generated func (s *Store) DeleteComposeChart(ctx context.Context, rr ...*composeType.Chart) (err error) { for i := range rr { - if err = s.Exec(ctx, composeChartDeleteQuery(s.config.Dialect, composeChartPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeChartDeleteQuery(s.Dialect, composeChartPrimaryKeys(rr[i]))); err != nil { return } } @@ -5998,14 +5998,14 @@ func (s *Store) DeleteComposeChart(ctx context.Context, rr ...*composeType.Chart // // This function is auto-generated func (s *Store) DeleteComposeChartByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composeChartDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeChartDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeCharts Deletes all rows from the composeChart collection -func (s *Store) TruncateComposeCharts(ctx context.Context) error { - return s.Exec(ctx, composeChartTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeCharts(ctx context.Context) error { + return s.Exec(ctx, composeChartTruncateQuery(s.Dialect)) } // SearchComposeCharts returns (filtered) set of ComposeCharts @@ -6205,9 +6205,9 @@ func (s *Store) QueryComposeCharts( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposeChart != nil { + if s.Filters.ComposeChart != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeChart(s, f) + tExpr, f, err = s.Filters.ComposeChart(s, f) } else { // using generated filter tExpr, f, err = ComposeChartFilter(f) @@ -6229,7 +6229,7 @@ func (s *Store) QueryComposeCharts( } } - query := composeChartSelectQuery(s.config.Dialect).Where(expr...) + query := composeChartSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposeChartFields()); err != nil { @@ -6308,7 +6308,7 @@ func (s *Store) LookupComposeChartByID(ctx context.Context, id uint64) (_ *compo var ( rows *sql.Rows aux = new(auxComposeChart) - lookup = composeChartSelectQuery(s.config.Dialect).Where( + lookup = composeChartSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -6348,9 +6348,9 @@ func (s *Store) LookupComposeChartByNamespaceIDHandle(ctx context.Context, names var ( rows *sql.Rows aux = new(auxComposeChart) - lookup = composeChartSelectQuery(s.config.Dialect).Where( + lookup = composeChartSelectQuery(s.Dialect).Where( goqu.I("rel_namespace").Eq(namespaceID), - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -6469,7 +6469,7 @@ func (s *Store) CreateComposeModule(ctx context.Context, rr ...*composeType.Modu return } - if err = s.Exec(ctx, composeModuleInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -6486,7 +6486,7 @@ func (s *Store) UpdateComposeModule(ctx context.Context, rr ...*composeType.Modu return } - if err = s.Exec(ctx, composeModuleUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -6503,7 +6503,7 @@ func (s *Store) UpsertComposeModule(ctx context.Context, rr ...*composeType.Modu return } - if err = s.Exec(ctx, composeModuleUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -6516,7 +6516,7 @@ func (s *Store) UpsertComposeModule(ctx context.Context, rr ...*composeType.Modu // This function is auto-generated func (s *Store) DeleteComposeModule(ctx context.Context, rr ...*composeType.Module) (err error) { for i := range rr { - if err = s.Exec(ctx, composeModuleDeleteQuery(s.config.Dialect, composeModulePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeModuleDeleteQuery(s.Dialect, composeModulePrimaryKeys(rr[i]))); err != nil { return } } @@ -6528,14 +6528,14 @@ func (s *Store) DeleteComposeModule(ctx context.Context, rr ...*composeType.Modu // // This function is auto-generated func (s *Store) DeleteComposeModuleByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composeModuleDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeModuleDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeModules Deletes all rows from the composeModule collection -func (s *Store) TruncateComposeModules(ctx context.Context) error { - return s.Exec(ctx, composeModuleTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeModules(ctx context.Context) error { + return s.Exec(ctx, composeModuleTruncateQuery(s.Dialect)) } // SearchComposeModules returns (filtered) set of ComposeModules @@ -6735,9 +6735,9 @@ func (s *Store) QueryComposeModules( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposeModule != nil { + if s.Filters.ComposeModule != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeModule(s, f) + tExpr, f, err = s.Filters.ComposeModule(s, f) } else { // using generated filter tExpr, f, err = ComposeModuleFilter(f) @@ -6759,7 +6759,7 @@ func (s *Store) QueryComposeModules( } } - query := composeModuleSelectQuery(s.config.Dialect).Where(expr...) + query := composeModuleSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposeModuleFields()); err != nil { @@ -6836,9 +6836,9 @@ func (s *Store) LookupComposeModuleByNamespaceIDHandle(ctx context.Context, name var ( rows *sql.Rows aux = new(auxComposeModule) - lookup = composeModuleSelectQuery(s.config.Dialect).Where( + lookup = composeModuleSelectQuery(s.Dialect).Where( goqu.I("rel_namespace").Eq(namespaceID), - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -6878,7 +6878,7 @@ func (s *Store) LookupComposeModuleByNamespaceIDName(ctx context.Context, namesp var ( rows *sql.Rows aux = new(auxComposeModule) - lookup = composeModuleSelectQuery(s.config.Dialect).Where( + lookup = composeModuleSelectQuery(s.Dialect).Where( goqu.I("rel_namespace").Eq(namespaceID), goqu.I("name").Eq(name), goqu.I("deleted_at").IsNull(), @@ -6922,7 +6922,7 @@ func (s *Store) LookupComposeModuleByID(ctx context.Context, id uint64) (_ *comp var ( rows *sql.Rows aux = new(auxComposeModule) - lookup = composeModuleSelectQuery(s.config.Dialect).Where( + lookup = composeModuleSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -7073,7 +7073,7 @@ func (s *Store) CreateComposeModuleField(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeModuleFieldInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleFieldInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7090,7 +7090,7 @@ func (s *Store) UpdateComposeModuleField(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeModuleFieldUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleFieldUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7107,7 +7107,7 @@ func (s *Store) UpsertComposeModuleField(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeModuleFieldUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeModuleFieldUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7120,7 +7120,7 @@ func (s *Store) UpsertComposeModuleField(ctx context.Context, rr ...*composeType // This function is auto-generated func (s *Store) DeleteComposeModuleField(ctx context.Context, rr ...*composeType.ModuleField) (err error) { for i := range rr { - if err = s.Exec(ctx, composeModuleFieldDeleteQuery(s.config.Dialect, composeModuleFieldPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeModuleFieldDeleteQuery(s.Dialect, composeModuleFieldPrimaryKeys(rr[i]))); err != nil { return } } @@ -7132,14 +7132,14 @@ func (s *Store) DeleteComposeModuleField(ctx context.Context, rr ...*composeType // // This function is auto-generated func (s *Store) DeleteComposeModuleFieldByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composeModuleFieldDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeModuleFieldDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeModuleFields Deletes all rows from the composeModuleField collection -func (s *Store) TruncateComposeModuleFields(ctx context.Context) error { - return s.Exec(ctx, composeModuleFieldTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeModuleFields(ctx context.Context) error { + return s.Exec(ctx, composeModuleFieldTruncateQuery(s.Dialect)) } // SearchComposeModuleFields returns (filtered) set of ComposeModuleFields @@ -7174,9 +7174,9 @@ func (s *Store) QueryComposeModuleFields( expr, tExpr []goqu.Expression ) - if s.config.Filters.ComposeModuleField != nil { + if s.Filters.ComposeModuleField != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeModuleField(s, f) + tExpr, f, err = s.Filters.ComposeModuleField(s, f) } else { // using generated filter tExpr, f, err = ComposeModuleFieldFilter(f) @@ -7189,7 +7189,7 @@ func (s *Store) QueryComposeModuleFields( expr = append(expr, tExpr...) - query := composeModuleFieldSelectQuery(s.config.Dialect).Where(expr...) + query := composeModuleFieldSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -7246,7 +7246,7 @@ func (s *Store) LookupComposeModuleFieldByModuleIDName(ctx context.Context, modu var ( rows *sql.Rows aux = new(auxComposeModuleField) - lookup = composeModuleFieldSelectQuery(s.config.Dialect).Where( + lookup = composeModuleFieldSelectQuery(s.Dialect).Where( goqu.I("rel_module").Eq(moduleID), goqu.I("name").Eq(name), goqu.I("deleted_at").IsNull(), @@ -7383,7 +7383,7 @@ func (s *Store) CreateComposeNamespace(ctx context.Context, rr ...*composeType.N return } - if err = s.Exec(ctx, composeNamespaceInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeNamespaceInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7400,7 +7400,7 @@ func (s *Store) UpdateComposeNamespace(ctx context.Context, rr ...*composeType.N return } - if err = s.Exec(ctx, composeNamespaceUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeNamespaceUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7417,7 +7417,7 @@ func (s *Store) UpsertComposeNamespace(ctx context.Context, rr ...*composeType.N return } - if err = s.Exec(ctx, composeNamespaceUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeNamespaceUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7430,7 +7430,7 @@ func (s *Store) UpsertComposeNamespace(ctx context.Context, rr ...*composeType.N // This function is auto-generated func (s *Store) DeleteComposeNamespace(ctx context.Context, rr ...*composeType.Namespace) (err error) { for i := range rr { - if err = s.Exec(ctx, composeNamespaceDeleteQuery(s.config.Dialect, composeNamespacePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeNamespaceDeleteQuery(s.Dialect, composeNamespacePrimaryKeys(rr[i]))); err != nil { return } } @@ -7442,14 +7442,14 @@ func (s *Store) DeleteComposeNamespace(ctx context.Context, rr ...*composeType.N // // This function is auto-generated func (s *Store) DeleteComposeNamespaceByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composeNamespaceDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeNamespaceDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeNamespaces Deletes all rows from the composeNamespace collection -func (s *Store) TruncateComposeNamespaces(ctx context.Context) error { - return s.Exec(ctx, composeNamespaceTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeNamespaces(ctx context.Context) error { + return s.Exec(ctx, composeNamespaceTruncateQuery(s.Dialect)) } // SearchComposeNamespaces returns (filtered) set of ComposeNamespaces @@ -7649,9 +7649,9 @@ func (s *Store) QueryComposeNamespaces( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposeNamespace != nil { + if s.Filters.ComposeNamespace != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeNamespace(s, f) + tExpr, f, err = s.Filters.ComposeNamespace(s, f) } else { // using generated filter tExpr, f, err = ComposeNamespaceFilter(f) @@ -7673,7 +7673,7 @@ func (s *Store) QueryComposeNamespaces( } } - query := composeNamespaceSelectQuery(s.config.Dialect).Where(expr...) + query := composeNamespaceSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposeNamespaceFields()); err != nil { @@ -7750,7 +7750,7 @@ func (s *Store) LookupComposeNamespaceBySlug(ctx context.Context, slug string) ( var ( rows *sql.Rows aux = new(auxComposeNamespace) - lookup = composeNamespaceSelectQuery(s.config.Dialect).Where( + lookup = composeNamespaceSelectQuery(s.Dialect).Where( goqu.I("slug").Eq(slug), goqu.I("deleted_at").IsNull(), ).Limit(1) @@ -7793,7 +7793,7 @@ func (s *Store) LookupComposeNamespaceByID(ctx context.Context, id uint64) (_ *c var ( rows *sql.Rows aux = new(auxComposeNamespace) - lookup = composeNamespaceSelectQuery(s.config.Dialect).Where( + lookup = composeNamespaceSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -7935,7 +7935,7 @@ func (s *Store) CreateComposePage(ctx context.Context, rr ...*composeType.Page) return } - if err = s.Exec(ctx, composePageInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composePageInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7952,7 +7952,7 @@ func (s *Store) UpdateComposePage(ctx context.Context, rr ...*composeType.Page) return } - if err = s.Exec(ctx, composePageUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composePageUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7969,7 +7969,7 @@ func (s *Store) UpsertComposePage(ctx context.Context, rr ...*composeType.Page) return } - if err = s.Exec(ctx, composePageUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composePageUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -7982,7 +7982,7 @@ func (s *Store) UpsertComposePage(ctx context.Context, rr ...*composeType.Page) // This function is auto-generated func (s *Store) DeleteComposePage(ctx context.Context, rr ...*composeType.Page) (err error) { for i := range rr { - if err = s.Exec(ctx, composePageDeleteQuery(s.config.Dialect, composePagePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composePageDeleteQuery(s.Dialect, composePagePrimaryKeys(rr[i]))); err != nil { return } } @@ -7994,14 +7994,14 @@ func (s *Store) DeleteComposePage(ctx context.Context, rr ...*composeType.Page) // // This function is auto-generated func (s *Store) DeleteComposePageByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, composePageDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composePageDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposePages Deletes all rows from the composePage collection -func (s *Store) TruncateComposePages(ctx context.Context) error { - return s.Exec(ctx, composePageTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposePages(ctx context.Context) error { + return s.Exec(ctx, composePageTruncateQuery(s.Dialect)) } // SearchComposePages returns (filtered) set of ComposePages @@ -8201,9 +8201,9 @@ func (s *Store) QueryComposePages( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposePage != nil { + if s.Filters.ComposePage != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposePage(s, f) + tExpr, f, err = s.Filters.ComposePage(s, f) } else { // using generated filter tExpr, f, err = ComposePageFilter(f) @@ -8225,7 +8225,7 @@ func (s *Store) QueryComposePages( } } - query := composePageSelectQuery(s.config.Dialect).Where(expr...) + query := composePageSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposePageFields()); err != nil { @@ -8302,9 +8302,9 @@ func (s *Store) LookupComposePageByNamespaceIDHandle(ctx context.Context, namesp var ( rows *sql.Rows aux = new(auxComposePage) - lookup = composePageSelectQuery(s.config.Dialect).Where( + lookup = composePageSelectQuery(s.Dialect).Where( goqu.I("rel_namespace").Eq(namespaceID), - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -8344,7 +8344,7 @@ func (s *Store) LookupComposePageByNamespaceIDModuleID(ctx context.Context, name var ( rows *sql.Rows aux = new(auxComposePage) - lookup = composePageSelectQuery(s.config.Dialect).Where( + lookup = composePageSelectQuery(s.Dialect).Where( goqu.I("rel_namespace").Eq(namespaceID), goqu.I("rel_module").Eq(moduleID), goqu.I("deleted_at").IsNull(), @@ -8388,7 +8388,7 @@ func (s *Store) LookupComposePageByID(ctx context.Context, id uint64) (_ *compos var ( rows *sql.Rows aux = new(auxComposePage) - lookup = composePageSelectQuery(s.config.Dialect).Where( + lookup = composePageSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -8507,7 +8507,7 @@ func (s *Store) CreateComposeRecord(ctx context.Context, mod *composeType.Module return } - if err = s.Exec(ctx, composeRecordInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -8524,7 +8524,7 @@ func (s *Store) UpdateComposeRecord(ctx context.Context, mod *composeType.Module return } - if err = s.Exec(ctx, composeRecordUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -8541,7 +8541,7 @@ func (s *Store) UpsertComposeRecord(ctx context.Context, mod *composeType.Module return } - if err = s.Exec(ctx, composeRecordUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -8554,7 +8554,7 @@ func (s *Store) UpsertComposeRecord(ctx context.Context, mod *composeType.Module // This function is auto-generated func (s *Store) DeleteComposeRecord(ctx context.Context, mod *composeType.Module, rr ...*composeType.Record) (err error) { for i := range rr { - if err = s.Exec(ctx, composeRecordDeleteQuery(s.config.Dialect, composeRecordPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeRecordDeleteQuery(s.Dialect, composeRecordPrimaryKeys(rr[i]))); err != nil { return } } @@ -8566,14 +8566,14 @@ func (s *Store) DeleteComposeRecord(ctx context.Context, mod *composeType.Module // // This function is auto-generated func (s *Store) DeleteComposeRecordByID(ctx context.Context, mod *composeType.Module, id uint64) error { - return s.Exec(ctx, composeRecordDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeRecordDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateComposeRecords Deletes all rows from the composeRecord collection -func (s *Store) TruncateComposeRecords(ctx context.Context, mod *composeType.Module) error { - return s.Exec(ctx, composeRecordTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeRecords(ctx context.Context, mod *composeType.Module) error { + return s.Exec(ctx, composeRecordTruncateQuery(s.Dialect)) } // SearchComposeRecords returns (filtered) set of ComposeRecords @@ -8773,9 +8773,9 @@ func (s *Store) QueryComposeRecords( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ComposeRecord != nil { + if s.Filters.ComposeRecord != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeRecord(s, f) + tExpr, f, err = s.Filters.ComposeRecord(s, f) } else { // using generated filter tExpr, f, err = ComposeRecordFilter(f) @@ -8797,7 +8797,7 @@ func (s *Store) QueryComposeRecords( } } - query := composeRecordSelectQuery(s.config.Dialect).Where(expr...) + query := composeRecordSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableComposeRecordFields()); err != nil { @@ -8876,7 +8876,7 @@ func (s *Store) LookupComposeRecordByID(ctx context.Context, mod *composeType.Mo var ( rows *sql.Rows aux = new(auxComposeRecord) - lookup = composeRecordSelectQuery(s.config.Dialect).Where( + lookup = composeRecordSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -8991,7 +8991,7 @@ func (s *Store) CreateComposeRecordValue(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeRecordValueInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordValueInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9008,7 +9008,7 @@ func (s *Store) UpdateComposeRecordValue(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeRecordValueUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordValueUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9025,7 +9025,7 @@ func (s *Store) UpsertComposeRecordValue(ctx context.Context, rr ...*composeType return } - if err = s.Exec(ctx, composeRecordValueUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, composeRecordValueUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9038,7 +9038,7 @@ func (s *Store) UpsertComposeRecordValue(ctx context.Context, rr ...*composeType // This function is auto-generated func (s *Store) DeleteComposeRecordValue(ctx context.Context, rr ...*composeType.RecordValue) (err error) { for i := range rr { - if err = s.Exec(ctx, composeRecordValueDeleteQuery(s.config.Dialect, composeRecordValuePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, composeRecordValueDeleteQuery(s.Dialect, composeRecordValuePrimaryKeys(rr[i]))); err != nil { return } } @@ -9050,7 +9050,7 @@ func (s *Store) DeleteComposeRecordValue(ctx context.Context, rr ...*composeType // // This function is auto-generated func (s *Store) DeleteComposeRecordValueByRecordIDNamePlace(ctx context.Context, recordID uint64, name string, place uint) error { - return s.Exec(ctx, composeRecordValueDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, composeRecordValueDeleteQuery(s.Dialect, goqu.Ex{ "record_id": recordID, "name": name, "place": place, @@ -9058,8 +9058,8 @@ func (s *Store) DeleteComposeRecordValueByRecordIDNamePlace(ctx context.Context, } // TruncateComposeRecordValues Deletes all rows from the composeRecordValue collection -func (s *Store) TruncateComposeRecordValues(ctx context.Context) error { - return s.Exec(ctx, composeRecordValueTruncateQuery(s.config.Dialect)) +func (s Store) TruncateComposeRecordValues(ctx context.Context) error { + return s.Exec(ctx, composeRecordValueTruncateQuery(s.Dialect)) } // SearchComposeRecordValues returns (filtered) set of ComposeRecordValues @@ -9094,9 +9094,9 @@ func (s *Store) QueryComposeRecordValues( expr, tExpr []goqu.Expression ) - if s.config.Filters.ComposeRecordValue != nil { + if s.Filters.ComposeRecordValue != nil { // extended filter set - tExpr, f, err = s.config.Filters.ComposeRecordValue(s, f) + tExpr, f, err = s.Filters.ComposeRecordValue(s, f) } else { // using generated filter tExpr, f, err = ComposeRecordValueFilter(f) @@ -9109,7 +9109,7 @@ func (s *Store) QueryComposeRecordValues( expr = append(expr, tExpr...) - query := composeRecordValueSelectQuery(s.config.Dialect).Where(expr...) + query := composeRecordValueSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -9250,7 +9250,7 @@ func (s *Store) CreateCredential(ctx context.Context, rr ...*systemType.Credenti return } - if err = s.Exec(ctx, credentialInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, credentialInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9267,7 +9267,7 @@ func (s *Store) UpdateCredential(ctx context.Context, rr ...*systemType.Credenti return } - if err = s.Exec(ctx, credentialUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, credentialUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9284,7 +9284,7 @@ func (s *Store) UpsertCredential(ctx context.Context, rr ...*systemType.Credenti return } - if err = s.Exec(ctx, credentialUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, credentialUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9297,7 +9297,7 @@ func (s *Store) UpsertCredential(ctx context.Context, rr ...*systemType.Credenti // This function is auto-generated func (s *Store) DeleteCredential(ctx context.Context, rr ...*systemType.Credential) (err error) { for i := range rr { - if err = s.Exec(ctx, credentialDeleteQuery(s.config.Dialect, credentialPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, credentialDeleteQuery(s.Dialect, credentialPrimaryKeys(rr[i]))); err != nil { return } } @@ -9309,14 +9309,14 @@ func (s *Store) DeleteCredential(ctx context.Context, rr ...*systemType.Credenti // // This function is auto-generated func (s *Store) DeleteCredentialByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, credentialDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, credentialDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateCredentials Deletes all rows from the credential collection -func (s *Store) TruncateCredentials(ctx context.Context) error { - return s.Exec(ctx, credentialTruncateQuery(s.config.Dialect)) +func (s Store) TruncateCredentials(ctx context.Context) error { + return s.Exec(ctx, credentialTruncateQuery(s.Dialect)) } // SearchCredentials returns (filtered) set of Credentials @@ -9351,9 +9351,9 @@ func (s *Store) QueryCredentials( expr, tExpr []goqu.Expression ) - if s.config.Filters.Credential != nil { + if s.Filters.Credential != nil { // extended filter set - tExpr, f, err = s.config.Filters.Credential(s, f) + tExpr, f, err = s.Filters.Credential(s, f) } else { // using generated filter tExpr, f, err = CredentialFilter(f) @@ -9366,7 +9366,7 @@ func (s *Store) QueryCredentials( expr = append(expr, tExpr...) - query := credentialSelectQuery(s.config.Dialect).Where(expr...) + query := credentialSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -9425,7 +9425,7 @@ func (s *Store) LookupCredentialByID(ctx context.Context, id uint64) (_ *systemT var ( rows *sql.Rows aux = new(auxCredential) - lookup = credentialSelectQuery(s.config.Dialect).Where( + lookup = credentialSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -9548,7 +9548,7 @@ func (s *Store) CreateFederationExposedModule(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationExposedModuleInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationExposedModuleInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9565,7 +9565,7 @@ func (s *Store) UpdateFederationExposedModule(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationExposedModuleUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationExposedModuleUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9582,7 +9582,7 @@ func (s *Store) UpsertFederationExposedModule(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationExposedModuleUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationExposedModuleUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -9595,7 +9595,7 @@ func (s *Store) UpsertFederationExposedModule(ctx context.Context, rr ...*federa // This function is auto-generated func (s *Store) DeleteFederationExposedModule(ctx context.Context, rr ...*federationType.ExposedModule) (err error) { for i := range rr { - if err = s.Exec(ctx, federationExposedModuleDeleteQuery(s.config.Dialect, federationExposedModulePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, federationExposedModuleDeleteQuery(s.Dialect, federationExposedModulePrimaryKeys(rr[i]))); err != nil { return } } @@ -9607,14 +9607,14 @@ func (s *Store) DeleteFederationExposedModule(ctx context.Context, rr ...*federa // // This function is auto-generated func (s *Store) DeleteFederationExposedModuleByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, federationExposedModuleDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, federationExposedModuleDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateFederationExposedModules Deletes all rows from the federationExposedModule collection -func (s *Store) TruncateFederationExposedModules(ctx context.Context) error { - return s.Exec(ctx, federationExposedModuleTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFederationExposedModules(ctx context.Context) error { + return s.Exec(ctx, federationExposedModuleTruncateQuery(s.Dialect)) } // SearchFederationExposedModules returns (filtered) set of FederationExposedModules @@ -9814,9 +9814,9 @@ func (s *Store) QueryFederationExposedModules( sortExpr []exp.OrderedExpression ) - if s.config.Filters.FederationExposedModule != nil { + if s.Filters.FederationExposedModule != nil { // extended filter set - tExpr, f, err = s.config.Filters.FederationExposedModule(s, f) + tExpr, f, err = s.Filters.FederationExposedModule(s, f) } else { // using generated filter tExpr, f, err = FederationExposedModuleFilter(f) @@ -9838,7 +9838,7 @@ func (s *Store) QueryFederationExposedModules( } } - query := federationExposedModuleSelectQuery(s.config.Dialect).Where(expr...) + query := federationExposedModuleSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableFederationExposedModuleFields()); err != nil { @@ -9917,7 +9917,7 @@ func (s *Store) LookupFederationExposedModuleByID(ctx context.Context, id uint64 var ( rows *sql.Rows aux = new(auxFederationExposedModule) - lookup = federationExposedModuleSelectQuery(s.config.Dialect).Where( + lookup = federationExposedModuleSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -10036,7 +10036,7 @@ func (s *Store) CreateFederationModuleMapping(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationModuleMappingInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationModuleMappingInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10053,7 +10053,7 @@ func (s *Store) UpdateFederationModuleMapping(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationModuleMappingUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationModuleMappingUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10070,7 +10070,7 @@ func (s *Store) UpsertFederationModuleMapping(ctx context.Context, rr ...*federa return } - if err = s.Exec(ctx, federationModuleMappingUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationModuleMappingUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10083,7 +10083,7 @@ func (s *Store) UpsertFederationModuleMapping(ctx context.Context, rr ...*federa // This function is auto-generated func (s *Store) DeleteFederationModuleMapping(ctx context.Context, rr ...*federationType.ModuleMapping) (err error) { for i := range rr { - if err = s.Exec(ctx, federationModuleMappingDeleteQuery(s.config.Dialect, federationModuleMappingPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, federationModuleMappingDeleteQuery(s.Dialect, federationModuleMappingPrimaryKeys(rr[i]))); err != nil { return } } @@ -10095,12 +10095,12 @@ func (s *Store) DeleteFederationModuleMapping(ctx context.Context, rr ...*federa // // This function is auto-generated func (s *Store) DeleteFederationModuleMappingBy(ctx context.Context) error { - return s.Exec(ctx, federationModuleMappingDeleteQuery(s.config.Dialect, goqu.Ex{})) + return s.Exec(ctx, federationModuleMappingDeleteQuery(s.Dialect, goqu.Ex{})) } // TruncateFederationModuleMappings Deletes all rows from the federationModuleMapping collection -func (s *Store) TruncateFederationModuleMappings(ctx context.Context) error { - return s.Exec(ctx, federationModuleMappingTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFederationModuleMappings(ctx context.Context) error { + return s.Exec(ctx, federationModuleMappingTruncateQuery(s.Dialect)) } // SearchFederationModuleMappings returns (filtered) set of FederationModuleMappings @@ -10300,9 +10300,9 @@ func (s *Store) QueryFederationModuleMappings( sortExpr []exp.OrderedExpression ) - if s.config.Filters.FederationModuleMapping != nil { + if s.Filters.FederationModuleMapping != nil { // extended filter set - tExpr, f, err = s.config.Filters.FederationModuleMapping(s, f) + tExpr, f, err = s.Filters.FederationModuleMapping(s, f) } else { // using generated filter tExpr, f, err = FederationModuleMappingFilter(f) @@ -10324,7 +10324,7 @@ func (s *Store) QueryFederationModuleMappings( } } - query := federationModuleMappingSelectQuery(s.config.Dialect).Where(expr...) + query := federationModuleMappingSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableFederationModuleMappingFields()); err != nil { @@ -10403,7 +10403,7 @@ func (s *Store) LookupFederationModuleMappingByFederationModuleIDComposeModuleID var ( rows *sql.Rows aux = new(auxFederationModuleMapping) - lookup = federationModuleMappingSelectQuery(s.config.Dialect).Where( + lookup = federationModuleMappingSelectQuery(s.Dialect).Where( goqu.I("federation_module_id").Eq(federationModuleID), goqu.I("compose_module_id").Eq(composeModuleID), goqu.I("compose_namespace_id").Eq(composeNamespaceID), @@ -10447,7 +10447,7 @@ func (s *Store) LookupFederationModuleMappingByFederationModuleID(ctx context.Co var ( rows *sql.Rows aux = new(auxFederationModuleMapping) - lookup = federationModuleMappingSelectQuery(s.config.Dialect).Where( + lookup = federationModuleMappingSelectQuery(s.Dialect).Where( goqu.I("federation_module_id").Eq(federationModuleID), ).Limit(1) ) @@ -10524,7 +10524,7 @@ func (s *Store) CreateFederationNode(ctx context.Context, rr ...*federationType. return } - if err = s.Exec(ctx, federationNodeInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10541,7 +10541,7 @@ func (s *Store) UpdateFederationNode(ctx context.Context, rr ...*federationType. return } - if err = s.Exec(ctx, federationNodeUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10558,7 +10558,7 @@ func (s *Store) UpsertFederationNode(ctx context.Context, rr ...*federationType. return } - if err = s.Exec(ctx, federationNodeUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10571,7 +10571,7 @@ func (s *Store) UpsertFederationNode(ctx context.Context, rr ...*federationType. // This function is auto-generated func (s *Store) DeleteFederationNode(ctx context.Context, rr ...*federationType.Node) (err error) { for i := range rr { - if err = s.Exec(ctx, federationNodeDeleteQuery(s.config.Dialect, federationNodePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, federationNodeDeleteQuery(s.Dialect, federationNodePrimaryKeys(rr[i]))); err != nil { return } } @@ -10583,14 +10583,14 @@ func (s *Store) DeleteFederationNode(ctx context.Context, rr ...*federationType. // // This function is auto-generated func (s *Store) DeleteFederationNodeByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, federationNodeDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, federationNodeDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateFederationNodes Deletes all rows from the federationNode collection -func (s *Store) TruncateFederationNodes(ctx context.Context) error { - return s.Exec(ctx, federationNodeTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFederationNodes(ctx context.Context) error { + return s.Exec(ctx, federationNodeTruncateQuery(s.Dialect)) } // SearchFederationNodes returns (filtered) set of FederationNodes @@ -10627,9 +10627,9 @@ func (s *Store) QueryFederationNodes( expr, tExpr []goqu.Expression ) - if s.config.Filters.FederationNode != nil { + if s.Filters.FederationNode != nil { // extended filter set - tExpr, f, err = s.config.Filters.FederationNode(s, f) + tExpr, f, err = s.Filters.FederationNode(s, f) } else { // using generated filter tExpr, f, err = FederationNodeFilter(f) @@ -10642,7 +10642,7 @@ func (s *Store) QueryFederationNodes( expr = append(expr, tExpr...) - query := federationNodeSelectQuery(s.config.Dialect).Where(expr...) + query := federationNodeSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -10711,7 +10711,7 @@ func (s *Store) LookupFederationNodeByID(ctx context.Context, id uint64) (_ *fed var ( rows *sql.Rows aux = new(auxFederationNode) - lookup = federationNodeSelectQuery(s.config.Dialect).Where( + lookup = federationNodeSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -10751,7 +10751,7 @@ func (s *Store) LookupFederationNodeByBaseURLSharedNodeID(ctx context.Context, b var ( rows *sql.Rows aux = new(auxFederationNode) - lookup = federationNodeSelectQuery(s.config.Dialect).Where( + lookup = federationNodeSelectQuery(s.Dialect).Where( goqu.I("base_url").Eq(baseURL), goqu.I("shared_node_id").Eq(sharedNodeID), ).Limit(1) @@ -10792,7 +10792,7 @@ func (s *Store) LookupFederationNodeBySharedNodeID(ctx context.Context, sharedNo var ( rows *sql.Rows aux = new(auxFederationNode) - lookup = federationNodeSelectQuery(s.config.Dialect).Where( + lookup = federationNodeSelectQuery(s.Dialect).Where( goqu.I("shared_node_id").Eq(sharedNodeID), ).Limit(1) ) @@ -10907,7 +10907,7 @@ func (s *Store) CreateFederationNodeSync(ctx context.Context, rr ...*federationT return } - if err = s.Exec(ctx, federationNodeSyncInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeSyncInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10924,7 +10924,7 @@ func (s *Store) UpdateFederationNodeSync(ctx context.Context, rr ...*federationT return } - if err = s.Exec(ctx, federationNodeSyncUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeSyncUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10941,7 +10941,7 @@ func (s *Store) UpsertFederationNodeSync(ctx context.Context, rr ...*federationT return } - if err = s.Exec(ctx, federationNodeSyncUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationNodeSyncUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -10954,7 +10954,7 @@ func (s *Store) UpsertFederationNodeSync(ctx context.Context, rr ...*federationT // This function is auto-generated func (s *Store) DeleteFederationNodeSync(ctx context.Context, rr ...*federationType.NodeSync) (err error) { for i := range rr { - if err = s.Exec(ctx, federationNodeSyncDeleteQuery(s.config.Dialect, federationNodeSyncPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, federationNodeSyncDeleteQuery(s.Dialect, federationNodeSyncPrimaryKeys(rr[i]))); err != nil { return } } @@ -10966,14 +10966,14 @@ func (s *Store) DeleteFederationNodeSync(ctx context.Context, rr ...*federationT // // This function is auto-generated func (s *Store) DeleteFederationNodeSyncByNodeID(ctx context.Context, nodeID uint64) error { - return s.Exec(ctx, federationNodeSyncDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, federationNodeSyncDeleteQuery(s.Dialect, goqu.Ex{ "node_id": nodeID, })) } // TruncateFederationNodeSyncs Deletes all rows from the federationNodeSync collection -func (s *Store) TruncateFederationNodeSyncs(ctx context.Context) error { - return s.Exec(ctx, federationNodeSyncTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFederationNodeSyncs(ctx context.Context) error { + return s.Exec(ctx, federationNodeSyncTruncateQuery(s.Dialect)) } // SearchFederationNodeSyncs returns (filtered) set of FederationNodeSyncs @@ -11173,9 +11173,9 @@ func (s *Store) QueryFederationNodeSyncs( sortExpr []exp.OrderedExpression ) - if s.config.Filters.FederationNodeSync != nil { + if s.Filters.FederationNodeSync != nil { // extended filter set - tExpr, f, err = s.config.Filters.FederationNodeSync(s, f) + tExpr, f, err = s.Filters.FederationNodeSync(s, f) } else { // using generated filter tExpr, f, err = FederationNodeSyncFilter(f) @@ -11197,7 +11197,7 @@ func (s *Store) QueryFederationNodeSyncs( } } - query := federationNodeSyncSelectQuery(s.config.Dialect).Where(expr...) + query := federationNodeSyncSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableFederationNodeSyncFields()); err != nil { @@ -11276,7 +11276,7 @@ func (s *Store) LookupFederationNodeSyncByNodeID(ctx context.Context, nodeID uin var ( rows *sql.Rows aux = new(auxFederationNodeSync) - lookup = federationNodeSyncSelectQuery(s.config.Dialect).Where( + lookup = federationNodeSyncSelectQuery(s.Dialect).Where( goqu.I("node_id").Eq(nodeID), ).Limit(1) ) @@ -11318,7 +11318,7 @@ func (s *Store) LookupFederationNodeSyncByNodeIDModuleIDSyncTypeSyncStatus(ctx c var ( rows *sql.Rows aux = new(auxFederationNodeSync) - lookup = federationNodeSyncSelectQuery(s.config.Dialect).Where( + lookup = federationNodeSyncSelectQuery(s.Dialect).Where( goqu.I("node_id").Eq(nodeID), goqu.I("module_id").Eq(moduleID), goqu.I("sync_type").Eq(syncType), @@ -11429,7 +11429,7 @@ func (s *Store) CreateFederationSharedModule(ctx context.Context, rr ...*federat return } - if err = s.Exec(ctx, federationSharedModuleInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationSharedModuleInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11446,7 +11446,7 @@ func (s *Store) UpdateFederationSharedModule(ctx context.Context, rr ...*federat return } - if err = s.Exec(ctx, federationSharedModuleUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationSharedModuleUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11463,7 +11463,7 @@ func (s *Store) UpsertFederationSharedModule(ctx context.Context, rr ...*federat return } - if err = s.Exec(ctx, federationSharedModuleUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, federationSharedModuleUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11476,7 +11476,7 @@ func (s *Store) UpsertFederationSharedModule(ctx context.Context, rr ...*federat // This function is auto-generated func (s *Store) DeleteFederationSharedModule(ctx context.Context, rr ...*federationType.SharedModule) (err error) { for i := range rr { - if err = s.Exec(ctx, federationSharedModuleDeleteQuery(s.config.Dialect, federationSharedModulePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, federationSharedModuleDeleteQuery(s.Dialect, federationSharedModulePrimaryKeys(rr[i]))); err != nil { return } } @@ -11488,14 +11488,14 @@ func (s *Store) DeleteFederationSharedModule(ctx context.Context, rr ...*federat // // This function is auto-generated func (s *Store) DeleteFederationSharedModuleByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, federationSharedModuleDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, federationSharedModuleDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateFederationSharedModules Deletes all rows from the federationSharedModule collection -func (s *Store) TruncateFederationSharedModules(ctx context.Context) error { - return s.Exec(ctx, federationSharedModuleTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFederationSharedModules(ctx context.Context) error { + return s.Exec(ctx, federationSharedModuleTruncateQuery(s.Dialect)) } // SearchFederationSharedModules returns (filtered) set of FederationSharedModules @@ -11695,9 +11695,9 @@ func (s *Store) QueryFederationSharedModules( sortExpr []exp.OrderedExpression ) - if s.config.Filters.FederationSharedModule != nil { + if s.Filters.FederationSharedModule != nil { // extended filter set - tExpr, f, err = s.config.Filters.FederationSharedModule(s, f) + tExpr, f, err = s.Filters.FederationSharedModule(s, f) } else { // using generated filter tExpr, f, err = FederationSharedModuleFilter(f) @@ -11719,7 +11719,7 @@ func (s *Store) QueryFederationSharedModules( } } - query := federationSharedModuleSelectQuery(s.config.Dialect).Where(expr...) + query := federationSharedModuleSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableFederationSharedModuleFields()); err != nil { @@ -11798,7 +11798,7 @@ func (s *Store) LookupFederationSharedModuleByID(ctx context.Context, id uint64) var ( rows *sql.Rows aux = new(auxFederationSharedModule) - lookup = federationSharedModuleSelectQuery(s.config.Dialect).Where( + lookup = federationSharedModuleSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -11917,7 +11917,7 @@ func (s *Store) CreateFlag(ctx context.Context, rr ...*flagType.Flag) (err error return } - if err = s.Exec(ctx, flagInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, flagInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11934,7 +11934,7 @@ func (s *Store) UpdateFlag(ctx context.Context, rr ...*flagType.Flag) (err error return } - if err = s.Exec(ctx, flagUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, flagUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11951,7 +11951,7 @@ func (s *Store) UpsertFlag(ctx context.Context, rr ...*flagType.Flag) (err error return } - if err = s.Exec(ctx, flagUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, flagUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -11964,7 +11964,7 @@ func (s *Store) UpsertFlag(ctx context.Context, rr ...*flagType.Flag) (err error // This function is auto-generated func (s *Store) DeleteFlag(ctx context.Context, rr ...*flagType.Flag) (err error) { for i := range rr { - if err = s.Exec(ctx, flagDeleteQuery(s.config.Dialect, flagPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, flagDeleteQuery(s.Dialect, flagPrimaryKeys(rr[i]))); err != nil { return } } @@ -11976,7 +11976,7 @@ func (s *Store) DeleteFlag(ctx context.Context, rr ...*flagType.Flag) (err error // // This function is auto-generated func (s *Store) DeleteFlagByKindResourceIDOwnedByName(ctx context.Context, kind string, resourceID uint64, ownedBy uint64, name string) error { - return s.Exec(ctx, flagDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, flagDeleteQuery(s.Dialect, goqu.Ex{ "kind": kind, "rel_resource": resourceID, "owned_by": ownedBy, @@ -11985,8 +11985,8 @@ func (s *Store) DeleteFlagByKindResourceIDOwnedByName(ctx context.Context, kind } // TruncateFlags Deletes all rows from the flag collection -func (s *Store) TruncateFlags(ctx context.Context) error { - return s.Exec(ctx, flagTruncateQuery(s.config.Dialect)) +func (s Store) TruncateFlags(ctx context.Context) error { + return s.Exec(ctx, flagTruncateQuery(s.Dialect)) } // SearchFlags returns (filtered) set of Flags @@ -12021,9 +12021,9 @@ func (s *Store) QueryFlags( expr, tExpr []goqu.Expression ) - if s.config.Filters.Flag != nil { + if s.Filters.Flag != nil { // extended filter set - tExpr, f, err = s.config.Filters.Flag(s, f) + tExpr, f, err = s.Filters.Flag(s, f) } else { // using generated filter tExpr, f, err = FlagFilter(f) @@ -12036,7 +12036,7 @@ func (s *Store) QueryFlags( expr = append(expr, tExpr...) - query := flagSelectQuery(s.config.Dialect).Where(expr...) + query := flagSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -12093,11 +12093,11 @@ func (s *Store) LookupFlagByKindResourceIDOwnedByName(ctx context.Context, kind var ( rows *sql.Rows aux = new(auxFlag) - lookup = flagSelectQuery(s.config.Dialect).Where( + lookup = flagSelectQuery(s.Dialect).Where( goqu.I("kind").Eq(kind), goqu.I("rel_resource").Eq(resourceID), goqu.I("owned_by").Eq(ownedBy), - s.config.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), + s.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), ).Limit(1) ) @@ -12225,7 +12225,7 @@ func (s *Store) CreateLabel(ctx context.Context, rr ...*labelsType.Label) (err e return } - if err = s.Exec(ctx, labelInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, labelInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12242,7 +12242,7 @@ func (s *Store) UpdateLabel(ctx context.Context, rr ...*labelsType.Label) (err e return } - if err = s.Exec(ctx, labelUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, labelUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12259,7 +12259,7 @@ func (s *Store) UpsertLabel(ctx context.Context, rr ...*labelsType.Label) (err e return } - if err = s.Exec(ctx, labelUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, labelUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12272,7 +12272,7 @@ func (s *Store) UpsertLabel(ctx context.Context, rr ...*labelsType.Label) (err e // This function is auto-generated func (s *Store) DeleteLabel(ctx context.Context, rr ...*labelsType.Label) (err error) { for i := range rr { - if err = s.Exec(ctx, labelDeleteQuery(s.config.Dialect, labelPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, labelDeleteQuery(s.Dialect, labelPrimaryKeys(rr[i]))); err != nil { return } } @@ -12284,7 +12284,7 @@ func (s *Store) DeleteLabel(ctx context.Context, rr ...*labelsType.Label) (err e // // This function is auto-generated func (s *Store) DeleteLabelByKindResourceIDName(ctx context.Context, kind string, resourceID uint64, name string) error { - return s.Exec(ctx, labelDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, labelDeleteQuery(s.Dialect, goqu.Ex{ "kind": kind, "rel_resource": resourceID, "name": name, @@ -12292,8 +12292,8 @@ func (s *Store) DeleteLabelByKindResourceIDName(ctx context.Context, kind string } // TruncateLabels Deletes all rows from the label collection -func (s *Store) TruncateLabels(ctx context.Context) error { - return s.Exec(ctx, labelTruncateQuery(s.config.Dialect)) +func (s Store) TruncateLabels(ctx context.Context) error { + return s.Exec(ctx, labelTruncateQuery(s.Dialect)) } // SearchLabels returns (filtered) set of Labels @@ -12328,9 +12328,9 @@ func (s *Store) QueryLabels( expr, tExpr []goqu.Expression ) - if s.config.Filters.Label != nil { + if s.Filters.Label != nil { // extended filter set - tExpr, f, err = s.config.Filters.Label(s, f) + tExpr, f, err = s.Filters.Label(s, f) } else { // using generated filter tExpr, f, err = LabelFilter(f) @@ -12343,7 +12343,7 @@ func (s *Store) QueryLabels( expr = append(expr, tExpr...) - query := labelSelectQuery(s.config.Dialect).Where(expr...) + query := labelSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -12400,10 +12400,10 @@ func (s *Store) LookupLabelByKindResourceIDName(ctx context.Context, kind string var ( rows *sql.Rows aux = new(auxLabel) - lookup = labelSelectQuery(s.config.Dialect).Where( + lookup = labelSelectQuery(s.Dialect).Where( goqu.I("kind").Eq(kind), goqu.I("rel_resource").Eq(resourceID), - s.config.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), + s.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), ).Limit(1) ) @@ -12522,7 +12522,7 @@ func (s *Store) CreateQueue(ctx context.Context, rr ...*systemType.Queue) (err e return } - if err = s.Exec(ctx, queueInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12539,7 +12539,7 @@ func (s *Store) UpdateQueue(ctx context.Context, rr ...*systemType.Queue) (err e return } - if err = s.Exec(ctx, queueUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12556,7 +12556,7 @@ func (s *Store) UpsertQueue(ctx context.Context, rr ...*systemType.Queue) (err e return } - if err = s.Exec(ctx, queueUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -12569,7 +12569,7 @@ func (s *Store) UpsertQueue(ctx context.Context, rr ...*systemType.Queue) (err e // This function is auto-generated func (s *Store) DeleteQueue(ctx context.Context, rr ...*systemType.Queue) (err error) { for i := range rr { - if err = s.Exec(ctx, queueDeleteQuery(s.config.Dialect, queuePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, queueDeleteQuery(s.Dialect, queuePrimaryKeys(rr[i]))); err != nil { return } } @@ -12581,14 +12581,14 @@ func (s *Store) DeleteQueue(ctx context.Context, rr ...*systemType.Queue) (err e // // This function is auto-generated func (s *Store) DeleteQueueByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, queueDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, queueDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateQueues Deletes all rows from the queue collection -func (s *Store) TruncateQueues(ctx context.Context) error { - return s.Exec(ctx, queueTruncateQuery(s.config.Dialect)) +func (s Store) TruncateQueues(ctx context.Context) error { + return s.Exec(ctx, queueTruncateQuery(s.Dialect)) } // SearchQueues returns (filtered) set of Queues @@ -12788,9 +12788,9 @@ func (s *Store) QueryQueues( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Queue != nil { + if s.Filters.Queue != nil { // extended filter set - tExpr, f, err = s.config.Filters.Queue(s, f) + tExpr, f, err = s.Filters.Queue(s, f) } else { // using generated filter tExpr, f, err = QueueFilter(f) @@ -12812,7 +12812,7 @@ func (s *Store) QueryQueues( } } - query := queueSelectQuery(s.config.Dialect).Where(expr...) + query := queueSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableQueueFields()); err != nil { @@ -12889,7 +12889,7 @@ func (s *Store) LookupQueueByID(ctx context.Context, id uint64) (_ *systemType.Q var ( rows *sql.Rows aux = new(auxQueue) - lookup = queueSelectQuery(s.config.Dialect).Where( + lookup = queueSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -12929,7 +12929,7 @@ func (s *Store) LookupQueueByQueue(ctx context.Context, queue string) (_ *system var ( rows *sql.Rows aux = new(auxQueue) - lookup = queueSelectQuery(s.config.Dialect).Where( + lookup = queueSelectQuery(s.Dialect).Where( goqu.I("queue").Eq(queue), ).Limit(1) ) @@ -13044,7 +13044,7 @@ func (s *Store) CreateQueueMessage(ctx context.Context, rr ...*systemType.QueueM return } - if err = s.Exec(ctx, queueMessageInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueMessageInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13061,7 +13061,7 @@ func (s *Store) UpdateQueueMessage(ctx context.Context, rr ...*systemType.QueueM return } - if err = s.Exec(ctx, queueMessageUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueMessageUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13078,7 +13078,7 @@ func (s *Store) UpsertQueueMessage(ctx context.Context, rr ...*systemType.QueueM return } - if err = s.Exec(ctx, queueMessageUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, queueMessageUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13091,7 +13091,7 @@ func (s *Store) UpsertQueueMessage(ctx context.Context, rr ...*systemType.QueueM // This function is auto-generated func (s *Store) DeleteQueueMessage(ctx context.Context, rr ...*systemType.QueueMessage) (err error) { for i := range rr { - if err = s.Exec(ctx, queueMessageDeleteQuery(s.config.Dialect, queueMessagePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, queueMessageDeleteQuery(s.Dialect, queueMessagePrimaryKeys(rr[i]))); err != nil { return } } @@ -13103,14 +13103,14 @@ func (s *Store) DeleteQueueMessage(ctx context.Context, rr ...*systemType.QueueM // // This function is auto-generated func (s *Store) DeleteQueueMessageByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, queueMessageDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, queueMessageDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateQueueMessages Deletes all rows from the queueMessage collection -func (s *Store) TruncateQueueMessages(ctx context.Context) error { - return s.Exec(ctx, queueMessageTruncateQuery(s.config.Dialect)) +func (s Store) TruncateQueueMessages(ctx context.Context) error { + return s.Exec(ctx, queueMessageTruncateQuery(s.Dialect)) } // SearchQueueMessages returns (filtered) set of QueueMessages @@ -13308,9 +13308,9 @@ func (s *Store) QueryQueueMessages( sortExpr []exp.OrderedExpression ) - if s.config.Filters.QueueMessage != nil { + if s.Filters.QueueMessage != nil { // extended filter set - tExpr, f, err = s.config.Filters.QueueMessage(s, f) + tExpr, f, err = s.Filters.QueueMessage(s, f) } else { // using generated filter tExpr, f, err = QueueMessageFilter(f) @@ -13332,7 +13332,7 @@ func (s *Store) QueryQueueMessages( } } - query := queueMessageSelectQuery(s.config.Dialect).Where(expr...) + query := queueMessageSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableQueueMessageFields()); err != nil { @@ -13468,7 +13468,7 @@ func (s *Store) CreateRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err e return } - if err = s.Exec(ctx, rbacRuleInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, rbacRuleInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13485,7 +13485,7 @@ func (s *Store) UpdateRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err e return } - if err = s.Exec(ctx, rbacRuleUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, rbacRuleUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13502,7 +13502,7 @@ func (s *Store) UpsertRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err e return } - if err = s.Exec(ctx, rbacRuleUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, rbacRuleUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13515,7 +13515,7 @@ func (s *Store) UpsertRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err e // This function is auto-generated func (s *Store) DeleteRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err error) { for i := range rr { - if err = s.Exec(ctx, rbacRuleDeleteQuery(s.config.Dialect, rbacRulePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, rbacRuleDeleteQuery(s.Dialect, rbacRulePrimaryKeys(rr[i]))); err != nil { return } } @@ -13527,7 +13527,7 @@ func (s *Store) DeleteRbacRule(ctx context.Context, rr ...*rbacType.Rule) (err e // // This function is auto-generated func (s *Store) DeleteRbacRuleByRoleIDResourceOperation(ctx context.Context, roleID uint64, resource string, operation string) error { - return s.Exec(ctx, rbacRuleDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, rbacRuleDeleteQuery(s.Dialect, goqu.Ex{ "rel_role": roleID, "resource": resource, "operation": operation, @@ -13535,8 +13535,8 @@ func (s *Store) DeleteRbacRuleByRoleIDResourceOperation(ctx context.Context, rol } // TruncateRbacRules Deletes all rows from the rbacRule collection -func (s *Store) TruncateRbacRules(ctx context.Context) error { - return s.Exec(ctx, rbacRuleTruncateQuery(s.config.Dialect)) +func (s Store) TruncateRbacRules(ctx context.Context) error { + return s.Exec(ctx, rbacRuleTruncateQuery(s.Dialect)) } // SearchRbacRules returns (filtered) set of RbacRules @@ -13571,9 +13571,9 @@ func (s *Store) QueryRbacRules( expr, tExpr []goqu.Expression ) - if s.config.Filters.RbacRule != nil { + if s.Filters.RbacRule != nil { // extended filter set - tExpr, f, err = s.config.Filters.RbacRule(s, f) + tExpr, f, err = s.Filters.RbacRule(s, f) } else { // using generated filter tExpr, f, err = RbacRuleFilter(f) @@ -13586,7 +13586,7 @@ func (s *Store) QueryRbacRules( expr = append(expr, tExpr...) - query := rbacRuleSelectQuery(s.config.Dialect).Where(expr...) + query := rbacRuleSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -13723,7 +13723,7 @@ func (s *Store) CreateReminder(ctx context.Context, rr ...*systemType.Reminder) return } - if err = s.Exec(ctx, reminderInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reminderInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13740,7 +13740,7 @@ func (s *Store) UpdateReminder(ctx context.Context, rr ...*systemType.Reminder) return } - if err = s.Exec(ctx, reminderUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reminderUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13757,7 +13757,7 @@ func (s *Store) UpsertReminder(ctx context.Context, rr ...*systemType.Reminder) return } - if err = s.Exec(ctx, reminderUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reminderUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -13770,7 +13770,7 @@ func (s *Store) UpsertReminder(ctx context.Context, rr ...*systemType.Reminder) // This function is auto-generated func (s *Store) DeleteReminder(ctx context.Context, rr ...*systemType.Reminder) (err error) { for i := range rr { - if err = s.Exec(ctx, reminderDeleteQuery(s.config.Dialect, reminderPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, reminderDeleteQuery(s.Dialect, reminderPrimaryKeys(rr[i]))); err != nil { return } } @@ -13782,14 +13782,14 @@ func (s *Store) DeleteReminder(ctx context.Context, rr ...*systemType.Reminder) // // This function is auto-generated func (s *Store) DeleteReminderByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, reminderDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, reminderDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateReminders Deletes all rows from the reminder collection -func (s *Store) TruncateReminders(ctx context.Context) error { - return s.Exec(ctx, reminderTruncateQuery(s.config.Dialect)) +func (s Store) TruncateReminders(ctx context.Context) error { + return s.Exec(ctx, reminderTruncateQuery(s.Dialect)) } // SearchReminders returns (filtered) set of Reminders @@ -13989,9 +13989,9 @@ func (s *Store) QueryReminders( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Reminder != nil { + if s.Filters.Reminder != nil { // extended filter set - tExpr, f, err = s.config.Filters.Reminder(s, f) + tExpr, f, err = s.Filters.Reminder(s, f) } else { // using generated filter tExpr, f, err = ReminderFilter(f) @@ -14013,7 +14013,7 @@ func (s *Store) QueryReminders( } } - query := reminderSelectQuery(s.config.Dialect).Where(expr...) + query := reminderSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableReminderFields()); err != nil { @@ -14090,7 +14090,7 @@ func (s *Store) LookupReminderByID(ctx context.Context, id uint64) (_ *systemTyp var ( rows *sql.Rows aux = new(auxReminder) - lookup = reminderSelectQuery(s.config.Dialect).Where( + lookup = reminderSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -14217,7 +14217,7 @@ func (s *Store) CreateReport(ctx context.Context, rr ...*systemType.Report) (err return } - if err = s.Exec(ctx, reportInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reportInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14234,7 +14234,7 @@ func (s *Store) UpdateReport(ctx context.Context, rr ...*systemType.Report) (err return } - if err = s.Exec(ctx, reportUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reportUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14251,7 +14251,7 @@ func (s *Store) UpsertReport(ctx context.Context, rr ...*systemType.Report) (err return } - if err = s.Exec(ctx, reportUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, reportUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14264,7 +14264,7 @@ func (s *Store) UpsertReport(ctx context.Context, rr ...*systemType.Report) (err // This function is auto-generated func (s *Store) DeleteReport(ctx context.Context, rr ...*systemType.Report) (err error) { for i := range rr { - if err = s.Exec(ctx, reportDeleteQuery(s.config.Dialect, reportPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, reportDeleteQuery(s.Dialect, reportPrimaryKeys(rr[i]))); err != nil { return } } @@ -14276,14 +14276,14 @@ func (s *Store) DeleteReport(ctx context.Context, rr ...*systemType.Report) (err // // This function is auto-generated func (s *Store) DeleteReportByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, reportDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, reportDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateReports Deletes all rows from the report collection -func (s *Store) TruncateReports(ctx context.Context) error { - return s.Exec(ctx, reportTruncateQuery(s.config.Dialect)) +func (s Store) TruncateReports(ctx context.Context) error { + return s.Exec(ctx, reportTruncateQuery(s.Dialect)) } // SearchReports returns (filtered) set of Reports @@ -14483,9 +14483,9 @@ func (s *Store) QueryReports( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Report != nil { + if s.Filters.Report != nil { // extended filter set - tExpr, f, err = s.config.Filters.Report(s, f) + tExpr, f, err = s.Filters.Report(s, f) } else { // using generated filter tExpr, f, err = ReportFilter(f) @@ -14507,7 +14507,7 @@ func (s *Store) QueryReports( } } - query := reportSelectQuery(s.config.Dialect).Where(expr...) + query := reportSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableReportFields()); err != nil { @@ -14586,7 +14586,7 @@ func (s *Store) LookupReportByID(ctx context.Context, id uint64) (_ *systemType. var ( rows *sql.Rows aux = new(auxReport) - lookup = reportSelectQuery(s.config.Dialect).Where( + lookup = reportSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -14628,8 +14628,8 @@ func (s *Store) LookupReportByHandle(ctx context.Context, handle string) (_ *sys var ( rows *sql.Rows aux = new(auxReport) - lookup = reportSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = reportSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -14775,7 +14775,7 @@ func (s *Store) CreateResourceActivity(ctx context.Context, rr ...*discoveryType return } - if err = s.Exec(ctx, resourceActivityInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceActivityInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14792,7 +14792,7 @@ func (s *Store) UpdateResourceActivity(ctx context.Context, rr ...*discoveryType return } - if err = s.Exec(ctx, resourceActivityUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceActivityUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14809,7 +14809,7 @@ func (s *Store) UpsertResourceActivity(ctx context.Context, rr ...*discoveryType return } - if err = s.Exec(ctx, resourceActivityUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceActivityUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -14822,7 +14822,7 @@ func (s *Store) UpsertResourceActivity(ctx context.Context, rr ...*discoveryType // This function is auto-generated func (s *Store) DeleteResourceActivity(ctx context.Context, rr ...*discoveryType.ResourceActivity) (err error) { for i := range rr { - if err = s.Exec(ctx, resourceActivityDeleteQuery(s.config.Dialect, resourceActivityPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, resourceActivityDeleteQuery(s.Dialect, resourceActivityPrimaryKeys(rr[i]))); err != nil { return } } @@ -14834,14 +14834,14 @@ func (s *Store) DeleteResourceActivity(ctx context.Context, rr ...*discoveryType // // This function is auto-generated func (s *Store) DeleteResourceActivityByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, resourceActivityDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, resourceActivityDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateResourceActivitys Deletes all rows from the resourceActivity collection -func (s *Store) TruncateResourceActivitys(ctx context.Context) error { - return s.Exec(ctx, resourceActivityTruncateQuery(s.config.Dialect)) +func (s Store) TruncateResourceActivitys(ctx context.Context) error { + return s.Exec(ctx, resourceActivityTruncateQuery(s.Dialect)) } // SearchResourceActivitys returns (filtered) set of ResourceActivitys @@ -14876,9 +14876,9 @@ func (s *Store) QueryResourceActivitys( expr, tExpr []goqu.Expression ) - if s.config.Filters.ResourceActivity != nil { + if s.Filters.ResourceActivity != nil { // extended filter set - tExpr, f, err = s.config.Filters.ResourceActivity(s, f) + tExpr, f, err = s.Filters.ResourceActivity(s, f) } else { // using generated filter tExpr, f, err = ResourceActivityFilter(f) @@ -14891,7 +14891,7 @@ func (s *Store) QueryResourceActivitys( expr = append(expr, tExpr...) - query := resourceActivitySelectQuery(s.config.Dialect).Where(expr...) + query := resourceActivitySelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -15014,7 +15014,7 @@ func (s *Store) CreateResourceTranslation(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, resourceTranslationInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceTranslationInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15031,7 +15031,7 @@ func (s *Store) UpdateResourceTranslation(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, resourceTranslationUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceTranslationUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15048,7 +15048,7 @@ func (s *Store) UpsertResourceTranslation(ctx context.Context, rr ...*systemType return } - if err = s.Exec(ctx, resourceTranslationUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, resourceTranslationUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15061,7 +15061,7 @@ func (s *Store) UpsertResourceTranslation(ctx context.Context, rr ...*systemType // This function is auto-generated func (s *Store) DeleteResourceTranslation(ctx context.Context, rr ...*systemType.ResourceTranslation) (err error) { for i := range rr { - if err = s.Exec(ctx, resourceTranslationDeleteQuery(s.config.Dialect, resourceTranslationPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, resourceTranslationDeleteQuery(s.Dialect, resourceTranslationPrimaryKeys(rr[i]))); err != nil { return } } @@ -15073,14 +15073,14 @@ func (s *Store) DeleteResourceTranslation(ctx context.Context, rr ...*systemType // // This function is auto-generated func (s *Store) DeleteResourceTranslationByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, resourceTranslationDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, resourceTranslationDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateResourceTranslations Deletes all rows from the resourceTranslation collection -func (s *Store) TruncateResourceTranslations(ctx context.Context) error { - return s.Exec(ctx, resourceTranslationTruncateQuery(s.config.Dialect)) +func (s Store) TruncateResourceTranslations(ctx context.Context) error { + return s.Exec(ctx, resourceTranslationTruncateQuery(s.Dialect)) } // SearchResourceTranslations returns (filtered) set of ResourceTranslations @@ -15278,9 +15278,9 @@ func (s *Store) QueryResourceTranslations( sortExpr []exp.OrderedExpression ) - if s.config.Filters.ResourceTranslation != nil { + if s.Filters.ResourceTranslation != nil { // extended filter set - tExpr, f, err = s.config.Filters.ResourceTranslation(s, f) + tExpr, f, err = s.Filters.ResourceTranslation(s, f) } else { // using generated filter tExpr, f, err = ResourceTranslationFilter(f) @@ -15302,7 +15302,7 @@ func (s *Store) QueryResourceTranslations( } } - query := resourceTranslationSelectQuery(s.config.Dialect).Where(expr...) + query := resourceTranslationSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableResourceTranslationFields()); err != nil { @@ -15370,7 +15370,7 @@ func (s *Store) LookupResourceTranslationByID(ctx context.Context, id uint64) (_ var ( rows *sql.Rows aux = new(auxResourceTranslation) - lookup = resourceTranslationSelectQuery(s.config.Dialect).Where( + lookup = resourceTranslationSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -15485,7 +15485,7 @@ func (s *Store) CreateRole(ctx context.Context, rr ...*systemType.Role) (err err return } - if err = s.Exec(ctx, roleInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15502,7 +15502,7 @@ func (s *Store) UpdateRole(ctx context.Context, rr ...*systemType.Role) (err err return } - if err = s.Exec(ctx, roleUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15519,7 +15519,7 @@ func (s *Store) UpsertRole(ctx context.Context, rr ...*systemType.Role) (err err return } - if err = s.Exec(ctx, roleUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -15532,7 +15532,7 @@ func (s *Store) UpsertRole(ctx context.Context, rr ...*systemType.Role) (err err // This function is auto-generated func (s *Store) DeleteRole(ctx context.Context, rr ...*systemType.Role) (err error) { for i := range rr { - if err = s.Exec(ctx, roleDeleteQuery(s.config.Dialect, rolePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, roleDeleteQuery(s.Dialect, rolePrimaryKeys(rr[i]))); err != nil { return } } @@ -15544,14 +15544,14 @@ func (s *Store) DeleteRole(ctx context.Context, rr ...*systemType.Role) (err err // // This function is auto-generated func (s *Store) DeleteRoleByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, roleDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, roleDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateRoles Deletes all rows from the role collection -func (s *Store) TruncateRoles(ctx context.Context) error { - return s.Exec(ctx, roleTruncateQuery(s.config.Dialect)) +func (s Store) TruncateRoles(ctx context.Context) error { + return s.Exec(ctx, roleTruncateQuery(s.Dialect)) } // SearchRoles returns (filtered) set of Roles @@ -15751,9 +15751,9 @@ func (s *Store) QueryRoles( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Role != nil { + if s.Filters.Role != nil { // extended filter set - tExpr, f, err = s.config.Filters.Role(s, f) + tExpr, f, err = s.Filters.Role(s, f) } else { // using generated filter tExpr, f, err = RoleFilter(f) @@ -15775,7 +15775,7 @@ func (s *Store) QueryRoles( } } - query := roleSelectQuery(s.config.Dialect).Where(expr...) + query := roleSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableRoleFields()); err != nil { @@ -15854,7 +15854,7 @@ func (s *Store) LookupRoleByID(ctx context.Context, id uint64) (_ *systemType.Ro var ( rows *sql.Rows aux = new(auxRole) - lookup = roleSelectQuery(s.config.Dialect).Where( + lookup = roleSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -15896,8 +15896,8 @@ func (s *Store) LookupRoleByHandle(ctx context.Context, handle string) (_ *syste var ( rows *sql.Rows aux = new(auxRole) - lookup = roleSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = roleSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -15939,7 +15939,7 @@ func (s *Store) LookupRoleByName(ctx context.Context, name string) (_ *systemTyp var ( rows *sql.Rows aux = new(auxRole) - lookup = roleSelectQuery(s.config.Dialect).Where( + lookup = roleSelectQuery(s.Dialect).Where( goqu.I("name").Eq(name), goqu.I("deleted_at").IsNull(), ).Limit(1) @@ -16117,7 +16117,7 @@ func (s *Store) CreateRoleMember(ctx context.Context, rr ...*systemType.RoleMemb return } - if err = s.Exec(ctx, roleMemberInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleMemberInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16134,7 +16134,7 @@ func (s *Store) UpdateRoleMember(ctx context.Context, rr ...*systemType.RoleMemb return } - if err = s.Exec(ctx, roleMemberUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleMemberUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16151,7 +16151,7 @@ func (s *Store) UpsertRoleMember(ctx context.Context, rr ...*systemType.RoleMemb return } - if err = s.Exec(ctx, roleMemberUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, roleMemberUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16164,7 +16164,7 @@ func (s *Store) UpsertRoleMember(ctx context.Context, rr ...*systemType.RoleMemb // This function is auto-generated func (s *Store) DeleteRoleMember(ctx context.Context, rr ...*systemType.RoleMember) (err error) { for i := range rr { - if err = s.Exec(ctx, roleMemberDeleteQuery(s.config.Dialect, roleMemberPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, roleMemberDeleteQuery(s.Dialect, roleMemberPrimaryKeys(rr[i]))); err != nil { return } } @@ -16176,15 +16176,15 @@ func (s *Store) DeleteRoleMember(ctx context.Context, rr ...*systemType.RoleMemb // // This function is auto-generated func (s *Store) DeleteRoleMemberByUserIDRoleID(ctx context.Context, userID uint64, roleID uint64) error { - return s.Exec(ctx, roleMemberDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, roleMemberDeleteQuery(s.Dialect, goqu.Ex{ "rel_user": userID, "rel_role": roleID, })) } // TruncateRoleMembers Deletes all rows from the roleMember collection -func (s *Store) TruncateRoleMembers(ctx context.Context) error { - return s.Exec(ctx, roleMemberTruncateQuery(s.config.Dialect)) +func (s Store) TruncateRoleMembers(ctx context.Context) error { + return s.Exec(ctx, roleMemberTruncateQuery(s.Dialect)) } // SearchRoleMembers returns (filtered) set of RoleMembers @@ -16219,9 +16219,9 @@ func (s *Store) QueryRoleMembers( expr, tExpr []goqu.Expression ) - if s.config.Filters.RoleMember != nil { + if s.Filters.RoleMember != nil { // extended filter set - tExpr, f, err = s.config.Filters.RoleMember(s, f) + tExpr, f, err = s.Filters.RoleMember(s, f) } else { // using generated filter tExpr, f, err = RoleMemberFilter(f) @@ -16234,7 +16234,7 @@ func (s *Store) QueryRoleMembers( expr = append(expr, tExpr...) - query := roleMemberSelectQuery(s.config.Dialect).Where(expr...) + query := roleMemberSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -16364,7 +16364,7 @@ func (s *Store) CreateSettingValue(ctx context.Context, rr ...*systemType.Settin return } - if err = s.Exec(ctx, settingValueInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, settingValueInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16381,7 +16381,7 @@ func (s *Store) UpdateSettingValue(ctx context.Context, rr ...*systemType.Settin return } - if err = s.Exec(ctx, settingValueUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, settingValueUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16398,7 +16398,7 @@ func (s *Store) UpsertSettingValue(ctx context.Context, rr ...*systemType.Settin return } - if err = s.Exec(ctx, settingValueUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, settingValueUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16411,7 +16411,7 @@ func (s *Store) UpsertSettingValue(ctx context.Context, rr ...*systemType.Settin // This function is auto-generated func (s *Store) DeleteSettingValue(ctx context.Context, rr ...*systemType.SettingValue) (err error) { for i := range rr { - if err = s.Exec(ctx, settingValueDeleteQuery(s.config.Dialect, settingValuePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, settingValueDeleteQuery(s.Dialect, settingValuePrimaryKeys(rr[i]))); err != nil { return } } @@ -16423,15 +16423,15 @@ func (s *Store) DeleteSettingValue(ctx context.Context, rr ...*systemType.Settin // // This function is auto-generated func (s *Store) DeleteSettingValueByNameOwnedBy(ctx context.Context, name string, ownedBy uint64) error { - return s.Exec(ctx, settingValueDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, settingValueDeleteQuery(s.Dialect, goqu.Ex{ "name": name, "rel_owner": ownedBy, })) } // TruncateSettingValues Deletes all rows from the settingValue collection -func (s *Store) TruncateSettingValues(ctx context.Context) error { - return s.Exec(ctx, settingValueTruncateQuery(s.config.Dialect)) +func (s Store) TruncateSettingValues(ctx context.Context) error { + return s.Exec(ctx, settingValueTruncateQuery(s.Dialect)) } // SearchSettingValues returns (filtered) set of SettingValues @@ -16466,9 +16466,9 @@ func (s *Store) QuerySettingValues( expr, tExpr []goqu.Expression ) - if s.config.Filters.SettingValue != nil { + if s.Filters.SettingValue != nil { // extended filter set - tExpr, f, err = s.config.Filters.SettingValue(s, f) + tExpr, f, err = s.Filters.SettingValue(s, f) } else { // using generated filter tExpr, f, err = SettingValueFilter(f) @@ -16481,7 +16481,7 @@ func (s *Store) QuerySettingValues( expr = append(expr, tExpr...) - query := settingValueSelectQuery(s.config.Dialect).Where(expr...) + query := settingValueSelectQuery(s.Dialect).Where(expr...) if f.Limit > 0 { query = query.Limit(f.Limit) @@ -16538,8 +16538,8 @@ func (s *Store) LookupSettingValueByNameOwnedBy(ctx context.Context, name string var ( rows *sql.Rows aux = new(auxSettingValue) - lookup = settingValueSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), + lookup = settingValueSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("name")).Eq(strings.ToLower(name)), goqu.I("rel_owner").Eq(ownedBy), ).Limit(1) ) @@ -16655,7 +16655,7 @@ func (s *Store) CreateTemplate(ctx context.Context, rr ...*systemType.Template) return } - if err = s.Exec(ctx, templateInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, templateInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16672,7 +16672,7 @@ func (s *Store) UpdateTemplate(ctx context.Context, rr ...*systemType.Template) return } - if err = s.Exec(ctx, templateUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, templateUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16689,7 +16689,7 @@ func (s *Store) UpsertTemplate(ctx context.Context, rr ...*systemType.Template) return } - if err = s.Exec(ctx, templateUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, templateUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -16702,7 +16702,7 @@ func (s *Store) UpsertTemplate(ctx context.Context, rr ...*systemType.Template) // This function is auto-generated func (s *Store) DeleteTemplate(ctx context.Context, rr ...*systemType.Template) (err error) { for i := range rr { - if err = s.Exec(ctx, templateDeleteQuery(s.config.Dialect, templatePrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, templateDeleteQuery(s.Dialect, templatePrimaryKeys(rr[i]))); err != nil { return } } @@ -16714,14 +16714,14 @@ func (s *Store) DeleteTemplate(ctx context.Context, rr ...*systemType.Template) // // This function is auto-generated func (s *Store) DeleteTemplateByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, templateDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, templateDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateTemplates Deletes all rows from the template collection -func (s *Store) TruncateTemplates(ctx context.Context) error { - return s.Exec(ctx, templateTruncateQuery(s.config.Dialect)) +func (s Store) TruncateTemplates(ctx context.Context) error { + return s.Exec(ctx, templateTruncateQuery(s.Dialect)) } // SearchTemplates returns (filtered) set of Templates @@ -16921,9 +16921,9 @@ func (s *Store) QueryTemplates( sortExpr []exp.OrderedExpression ) - if s.config.Filters.Template != nil { + if s.Filters.Template != nil { // extended filter set - tExpr, f, err = s.config.Filters.Template(s, f) + tExpr, f, err = s.Filters.Template(s, f) } else { // using generated filter tExpr, f, err = TemplateFilter(f) @@ -16945,7 +16945,7 @@ func (s *Store) QueryTemplates( } } - query := templateSelectQuery(s.config.Dialect).Where(expr...) + query := templateSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableTemplateFields()); err != nil { @@ -17024,7 +17024,7 @@ func (s *Store) LookupTemplateByID(ctx context.Context, id uint64) (_ *systemTyp var ( rows *sql.Rows aux = new(auxTemplate) - lookup = templateSelectQuery(s.config.Dialect).Where( + lookup = templateSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -17066,8 +17066,8 @@ func (s *Store) LookupTemplateByHandle(ctx context.Context, handle string) (_ *s var ( rows *sql.Rows aux = new(auxTemplate) - lookup = templateSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = templateSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -17217,7 +17217,7 @@ func (s *Store) CreateUser(ctx context.Context, rr ...*systemType.User) (err err return } - if err = s.Exec(ctx, userInsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, userInsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -17234,7 +17234,7 @@ func (s *Store) UpdateUser(ctx context.Context, rr ...*systemType.User) (err err return } - if err = s.Exec(ctx, userUpdateQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, userUpdateQuery(s.Dialect, rr[i])); err != nil { return } } @@ -17251,7 +17251,7 @@ func (s *Store) UpsertUser(ctx context.Context, rr ...*systemType.User) (err err return } - if err = s.Exec(ctx, userUpsertQuery(s.config.Dialect, rr[i])); err != nil { + if err = s.Exec(ctx, userUpsertQuery(s.Dialect, rr[i])); err != nil { return } } @@ -17264,7 +17264,7 @@ func (s *Store) UpsertUser(ctx context.Context, rr ...*systemType.User) (err err // This function is auto-generated func (s *Store) DeleteUser(ctx context.Context, rr ...*systemType.User) (err error) { for i := range rr { - if err = s.Exec(ctx, userDeleteQuery(s.config.Dialect, userPrimaryKeys(rr[i]))); err != nil { + if err = s.Exec(ctx, userDeleteQuery(s.Dialect, userPrimaryKeys(rr[i]))); err != nil { return } } @@ -17276,14 +17276,14 @@ func (s *Store) DeleteUser(ctx context.Context, rr ...*systemType.User) (err err // // This function is auto-generated func (s *Store) DeleteUserByID(ctx context.Context, id uint64) error { - return s.Exec(ctx, userDeleteQuery(s.config.Dialect, goqu.Ex{ + return s.Exec(ctx, userDeleteQuery(s.Dialect, goqu.Ex{ "id": id, })) } // TruncateUsers Deletes all rows from the user collection -func (s *Store) TruncateUsers(ctx context.Context) error { - return s.Exec(ctx, userTruncateQuery(s.config.Dialect)) +func (s Store) TruncateUsers(ctx context.Context) error { + return s.Exec(ctx, userTruncateQuery(s.Dialect)) } // SearchUsers returns (filtered) set of Users @@ -17483,9 +17483,9 @@ func (s *Store) QueryUsers( sortExpr []exp.OrderedExpression ) - if s.config.Filters.User != nil { + if s.Filters.User != nil { // extended filter set - tExpr, f, err = s.config.Filters.User(s, f) + tExpr, f, err = s.Filters.User(s, f) } else { // using generated filter tExpr, f, err = UserFilter(f) @@ -17507,7 +17507,7 @@ func (s *Store) QueryUsers( } } - query := userSelectQuery(s.config.Dialect).Where(expr...) + query := userSelectQuery(s.Dialect).Where(expr...) // sorting feature is enabled if sortExpr, err = order(f.Sort, s.sortableUserFields()); err != nil { @@ -17586,7 +17586,7 @@ func (s *Store) LookupUserByID(ctx context.Context, id uint64) (_ *systemType.Us var ( rows *sql.Rows aux = new(auxUser) - lookup = userSelectQuery(s.config.Dialect).Where( + lookup = userSelectQuery(s.Dialect).Where( goqu.I("id").Eq(id), ).Limit(1) ) @@ -17628,8 +17628,8 @@ func (s *Store) LookupUserByEmail(ctx context.Context, email string) (_ *systemT var ( rows *sql.Rows aux = new(auxUser) - lookup = userSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("email")).Eq(strings.ToLower(email)), + lookup = userSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("email")).Eq(strings.ToLower(email)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -17671,8 +17671,8 @@ func (s *Store) LookupUserByHandle(ctx context.Context, handle string) (_ *syste var ( rows *sql.Rows aux = new(auxUser) - lookup = userSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), + lookup = userSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("handle")).Eq(strings.ToLower(handle)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) @@ -17714,8 +17714,8 @@ func (s *Store) LookupUserByUsername(ctx context.Context, username string) (_ *s var ( rows *sql.Rows aux = new(auxUser) - lookup = userSelectQuery(s.config.Dialect).Where( - s.config.Functions.LOWER(goqu.I("username")).Eq(strings.ToLower(username)), + lookup = userSelectQuery(s.Dialect).Where( + s.Functions.LOWER(goqu.I("username")).Eq(strings.ToLower(username)), goqu.I("deleted_at").IsNull(), ).Limit(1) ) diff --git a/store/adapters/rdbms/rdbms.go b/store/adapters/rdbms/rdbms.go deleted file mode 100644 index ff8949268..000000000 --- a/store/adapters/rdbms/rdbms.go +++ /dev/null @@ -1,105 +0,0 @@ -package rdbms - -import ( - "context" - "database/sql" - "fmt" - - "github.com/cortezaproject/corteza-server/store" - "github.com/doug-martin/goqu/v9" - "github.com/doug-martin/goqu/v9/exec" - "go.uber.org/zap" -) - -type ( - sqlizer interface { - ToSQL() (string, []interface{}, error) - } - - scalable interface { - Scan(...interface{}) error - } - - Store struct { - db dbLayer - - // rdbms store configuration - config *Config - - // Logger for connection - logger *zap.Logger - } -) - -func init() { - // goqu should always use placeholders! - // https://doug-martin.github.io/goqu/docs/interpolation.html - goqu.SetDefaultPrepared(true) -} - -func (s Store) Exec(ctx context.Context, q sqlizer) error { - var ( - query, args, err = q.ToSQL() - ) - - if err != nil { - return fmt.Errorf("could not build query: %w", err) - } - - _, err = s.db.ExecContext(ctx, query, args...) - return store.HandleError(err, s.config.ErrorHandler) -} - -func (s Store) Query(ctx context.Context, q sqlizer) (*sql.Rows, error) { - var ( - rr *sql.Rows - - query, args, err = q.ToSQL() - ) - - if err != nil { - return nil, fmt.Errorf("could not build query: %w", err) - } - - rr, err = s.db.QueryContext(ctx, query, args...) - if err = store.HandleError(err, s.config.ErrorHandler); err != nil { - return nil, err - } - - return rr, nil -} - -func (s Store) QueryOne(ctx context.Context, q sqlizer, dst interface{}) (err error) { - var ( - rows *sql.Rows - ) - - rows, err = s.Query(ctx, q) - if err != nil { - return - } - - defer func() { - closeError := rows.Close() - if err == nil { - // return error from close - err = closeError - } - }() - - if err = rows.Err(); err != nil { - return - } - - if !rows.Next() { - return store.ErrNotFound.Stack(1) - } - - return exec.NewScanner(rows).ScanStruct(dst) -} - -// Config returns store's config as a value -// as protection against changes -func (s Store) Config() Config { - return *s.config -} diff --git a/store/adapters/rdbms/rdbms_store.go b/store/adapters/rdbms/rdbms_store.go new file mode 100644 index 000000000..07503988e --- /dev/null +++ b/store/adapters/rdbms/rdbms_store.go @@ -0,0 +1,185 @@ +package rdbms + +import ( + "context" + "database/sql" + "fmt" + + "github.com/cortezaproject/corteza-server/store" + "github.com/cortezaproject/corteza-server/store/adapters/rdbms/ddl" + "github.com/doug-martin/goqu/v9" + "github.com/doug-martin/goqu/v9/exec" + "github.com/doug-martin/goqu/v9/exp" + "github.com/jmoiron/sqlx" + "go.uber.org/zap" +) + +type ( + sqlizer interface { + ToSQL() (string, []interface{}, error) + } + + scanner interface { + Scan(...interface{}) error + } + + txRetryOnErrHandler func(int, error) bool + + Functions struct { + // returns lower case text + LOWER func(interface{}) exp.SQLFunctionExpression + + // returns date part of the input (YYYY-MM-DD) + DATE func(interface{}) exp.SQLFunctionExpression + } + + schemaAPI interface { + TableExists(ctx context.Context, db sqlx.QueryerContext, table string) (bool, error) + CreateTable(ctx context.Context, db sqlx.ExtContext, t *ddl.Table) error + } + + Store struct { + DB sqlx.ExtContext + + // Logger for connection + Logger *zap.Logger + + // tools to modify DB schema (create tables, indexes..) + // @todo maybe this does not need to be here + SchemaAPI schemaAPI + + Dialect goqu.DialectWrapper + + // set to -1 to disable transactions + TxRetryLimit int + + // TxRetryErrHandler should return true if transaction should be retried + // + // Because retry algorithm varies between concrete rdbms implementations + // + // Handler must return true if failed transaction should be replied + // and false if we're safe to terminate it + TxRetryErrHandler txRetryOnErrHandler + + ErrorHandler store.ErrorHandler + + Functions *Functions + + // additional (per-resource-type) filters used when searching + // these filters can modify expression used for querying the database + Filters *extendedFilters + } +) + +// SetDefaults fn sets all defaults that need to be set +func (s *Store) SetDefaults() { + if s.TxRetryErrHandler == nil { + s.TxRetryErrHandler = func(i int, err error) bool { return false } + } + + if s.ErrorHandler == nil { + s.ErrorHandler = func(err error) error { return err } + } + + if s.Functions == nil { + s.Functions = DefaultFunctions() + } + + if s.Filters == nil { + s.Filters = DefaultFilters() + } +} + +// WithTx spins up new store instance with transaction +func (s *Store) withTx(tx sqlx.ExtContext) *Store { + return &Store{ + DB: tx, + + Logger: s.Logger, + SchemaAPI: s.SchemaAPI, + Dialect: s.Dialect, + TxRetryErrHandler: s.TxRetryErrHandler, + ErrorHandler: s.ErrorHandler, + Functions: s.Functions, + Filters: s.Filters, + } +} + +func (s Store) Exec(ctx context.Context, q sqlizer) error { + var ( + query, args, err = q.ToSQL() + ) + + if err != nil { + return fmt.Errorf("could not build query: %w", err) + } + + _, err = s.DB.ExecContext(ctx, query, args...) + return store.HandleError(err, s.ErrorHandler) +} + +func (s Store) Query(ctx context.Context, q sqlizer) (*sql.Rows, error) { + var ( + rr *sql.Rows + + query, args, err = q.ToSQL() + ) + + if err != nil { + return nil, fmt.Errorf("could not build query: %w", err) + } + + rr, err = s.DB.QueryContext(ctx, query, args...) + if err = store.HandleError(err, s.ErrorHandler); err != nil { + return nil, err + } + + return rr, nil +} + +func (s Store) QueryOne(ctx context.Context, q sqlizer, dst interface{}) (err error) { + var ( + rows *sql.Rows + ) + + rows, err = s.Query(ctx, q) + if err != nil { + return + } + + defer func() { + closeError := rows.Close() + if err == nil { + // return error from close + err = closeError + } + }() + + if err = rows.Err(); err != nil { + return + } + + if !rows.Next() { + return store.ErrNotFound.Stack(1) + } + + return exec.NewScanner(rows).ScanStruct(dst) +} + +func DefaultFunctions() *Functions { + f := &Functions{} + + if f.LOWER == nil { + f.LOWER = func(value interface{}) exp.SQLFunctionExpression { + return goqu.Func("LOWER", value) + } + } + + if f.DATE == nil { + f.DATE = func(value interface{}) exp.SQLFunctionExpression { + return goqu.Func("DATE", value) + } + } + + return f +} diff --git a/store/adapters/rdbms/rdbms_test.go b/store/adapters/rdbms/rdbms_store_test.go similarity index 100% rename from store/adapters/rdbms/rdbms_test.go rename to store/adapters/rdbms/rdbms_store_test.go diff --git a/store/adapters/rdbms/schema/README.md b/store/adapters/rdbms/schema/README.md deleted file mode 100644 index ea7a46d41..000000000 --- a/store/adapters/rdbms/schema/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# RDBMS Schema package - -Package contains - -1. DDL -2. Current schema definition instructions -3. Upgrade instructions using state detection and modification instructions - -## DDL or Data Definition Language - -This package provides building blocks and generic dialect for specifying RDBMS schema creation and alternation instructions. - -## Flow - -### General steps -1. Application (or tests) start the boot procedure -2. `store.Upgrade()` (`store/upgrade.go`) is called with current primary store connection - -### RDBMS specific steps - -RDBMS implementation of schema upgrade is unified across all drivers (store implementations) -3. `schema.Upgrade()` initializes common (across implementations) upgrade procedure and use `schemaUpgrader` interface that each store implementation provides. -4. diff --git a/store/adapters/rdbms/schema/dialect.go b/store/adapters/rdbms/schema/dialect.go deleted file mode 100644 index 2601be25b..000000000 --- a/store/adapters/rdbms/schema/dialect.go +++ /dev/null @@ -1,175 +0,0 @@ -package schema - -import ( - "bytes" - "fmt" - "regexp" - "strings" - "text/template" -) - -type ( - CommonDialect struct { - tpl *template.Template - } -) - -const ( - // table creation - commonCreateTable = ` - CREATE TABLE {{template "if-not-exists-clause" .}} {{ .Name }} ( - {{ range $n, $c := .Columns -}} - {{ if $n }}, {{ else }} {{ end }}{{ template "create-table-column" . }} - {{ end -}} - {{- if .PrimaryKey }} - , PRIMARY KEY {{ template "index-fields" .PrimaryKey.Fields }} - {{- end }} - ) {{- template "create-table-suffix" . -}} - ` - - commonCreateTableSuffix = `` - - commonCreateTableColumn = ` - {{- .Name }} {{ columnType .Type }} - {{- if not .IsNull }} NOT NULL{{end}} - {{- if .DefaultValue }} DEFAULT {{ .DefaultValue }} {{end}} - ` - - commonAddColumn = `ALTER TABLE {{ .Table }} ADD {{ template "create-table-column" .Column }}` - commonAddPrimaryKey = `ALTER TABLE {{ .Table }} ADD CONSTRAINT PRIMARY KEY {{ template "index-fields" .PrimaryKey.Fields }}` - commonDropColumn = `ALTER TABLE {{ .Table }} DROP {{ .Column }}` - commonRenameColumn = `ALTER TABLE {{ .Table }} RENAME COLUMN {{ .OldName }} TO {{ .NewName }}` - - // index creation - commonCreateIndex = `CREATE {{ if .Unique }}UNIQUE {{ end }}INDEX {{ template "if-not-exists-clause" . }} {{ template "index-name" . }} ON {{ .Table }} {{ template "index-fields" .Fields }}{{ template "index-condition" . }}` - - commonIndexName = `{{ .Table }}_{{ .Name }}` - commonIndexCondition = `{{- if .Condition }} WHERE ({{ .Condition }}){{ end }}` - - // index creation - commonIndexFields = ` - ({{ range $n, $f := . -}} - {{ if $n }}, {{ end }} - {{- if .Expr}}({{ end }} - {{- .Field }} - {{- if .Expr}}){{ end }} - {{- if .Desc }} DESC{{ end }} - {{- end }}) - ` - // table/index exist or not clause - commonIfNotExistsClause = `IF NOT EXISTS` -) - -func NewCommonDialect() *CommonDialect { - g := &CommonDialect{tpl: template.New("")} - g.AddTemplateFunc("columnType", GenColumnType) - g.AddTemplate("create-table", commonCreateTable) - g.AddTemplate("create-table-suffix", commonCreateTableSuffix) - g.AddTemplate("create-table-column", commonCreateTableColumn) - g.AddTemplate("add-column", commonAddColumn) - g.AddTemplate("add-primary-key", commonAddPrimaryKey) - g.AddTemplate("drop-column", commonDropColumn) - g.AddTemplate("rename-column", commonRenameColumn) - g.AddTemplate("create-index", commonCreateIndex) - g.AddTemplate("index-condition", commonIndexCondition) - g.AddTemplate("index-name", commonIndexName) - g.AddTemplate("index-fields", commonIndexFields) - g.AddTemplate("if-not-exists-clause", commonIfNotExistsClause) - - return g -} - -func (g *CommonDialect) executeTemplate(name string, data interface{}) string { - buf := &bytes.Buffer{} - if err := g.tpl.ExecuteTemplate(buf, name, data); err != nil { - panic(err) - } - - return buf.String() -} - -func (g *CommonDialect) AddTemplateFunc(name string, fn interface{}) { - g.tpl.Funcs(template.FuncMap{name: fn}) -} - -func (g *CommonDialect) AddTemplate(name, tpl string) { - funcMap := template.FuncMap{ - "trimExpression": func(s string) string { - re := regexp.MustCompile(`^.*\((\w+)\).*$`) - if str := re.FindAllStringSubmatch(s, 1); len(str) > 0 && len(str[0]) > 0 && len(str[0][1]) > 0 { - return str[0][1] - } - return s - }, - } - template.Must(g.tpl.Funcs(funcMap).New(name).Parse(strings.TrimSpace(tpl))) -} - -func (g *CommonDialect) CreateTable(t *Table) string { - return g.executeTemplate("create-table", t) -} - -func (g *CommonDialect) CreateIndex(i *Index) string { - return g.executeTemplate("create-index", i) -} - -func (g *CommonDialect) AddColumn(table string, c *Column) string { - return g.executeTemplate("add-column", map[string]interface{}{ - "Table": table, - "Column": c, - }) -} - -func (g *CommonDialect) DropColumn(table, column string) string { - return g.executeTemplate("drop-column", map[string]interface{}{ - "Table": table, - "Column": column, - }) -} - -func (g *CommonDialect) RenameColumn(table, oldName, newName string) string { - return g.executeTemplate("rename-column", map[string]interface{}{ - "Table": table, - "OldName": oldName, - "NewName": newName, - }) -} - -func (g *CommonDialect) AddPrimaryKey(table string, pk *Index) string { - return g.executeTemplate("add-primary-key", map[string]interface{}{ - "Table": table, - "PrimaryKey": pk, - }) -} - -func GenColumnType(ct *ColumnType) string { - switch ct.Type { - case ColumnTypeIdentifier: - return "BIGINT" - case ColumnTypeVarchar: - if ct.Length > 0 { - // VARCHAR(0) is useless - return fmt.Sprintf("VARCHAR(%d)", ct.Length) - } - return "VARCHAR" - case ColumnTypeText: - return "TEXT" - case ColumnTypeJson: - return "JSON" - case ColumnTypeBinary: - return "BYTEA" - case ColumnTypeTimestamp: - if ct.Length > -1 { - // TIMESTAMPTZ(0) strips out milliseconds - return fmt.Sprintf("TIMESTAMPTZ(%d)", ct.Length) - } - - return "TIMESTAMPTZ" - case ColumnTypeInteger: - return "INTEGER" - case ColumnTypeBoolean: - return "BOOLEAN" - default: - panic(fmt.Sprintf("unhandled column type: %d ", ct.Type)) - } -} diff --git a/store/adapters/rdbms/schema/dialect_test.go b/store/adapters/rdbms/schema/dialect_test.go deleted file mode 100644 index b44eaee6f..000000000 --- a/store/adapters/rdbms/schema/dialect_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package schema - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -func Test_generator_CreateTable(t *testing.T) { - var ( - tests = []struct { - name string - in *Table - out string - }{ - { - name: "2col", - in: TableDef("tbl", - ColumnDef("col1", ColumnTypeInteger, Null), - ColumnDef("col2", ColumnTypeVarchar, ColumnTypeLength(2)), - ), - out: ` -CREATE TABLE tbl ( - col1 INTEGER -, col2 VARCHAR(2) NOT NULL - -)`, - }, - { - name: "primary key", - in: TableDef("tbl", - ID, - ), - out: ` -CREATE TABLE tbl ( - id BIGINT NOT NULL - -, PRIMARY KEY (id) -)`, - }, - } - ) - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.New(t).Equal(strings.TrimSpace(tt.out), NewCommonDialect(zap.NewNop()).CreateTable(tt.in)) - }) - } -} - -func Test_generator_CreateIndex(t *testing.T) { - var ( - tests = []struct { - name string - in *Table - out string - }{ - { - name: "columns", - in: TableDef("tbl", - AddIndex("mix", IColumn("c1", "c2")), - ), - out: "CREATE INDEX tbl_mix ON tbl (c1, c2)", - }, - { - name: "expression", - in: TableDef("tbl", - AddIndex("mix", IExpr("LOWER(exp1)")), - ), - out: "CREATE INDEX tbl_mix ON tbl ((LOWER(exp1)))", - }, - { - name: "conditional", - in: TableDef("tbl", - AddIndex("mix", IColumn("c1"), IWhere("cnd IS NULL")), - ), - out: "CREATE INDEX tbl_mix ON tbl (c1) WHERE (cnd IS NULL)", - }, - } - ) - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.New(t).Equal(tt.out, NewCommonDialect(zap.NewNop()).CreateIndex(tt.in.Indexes[0])) - }) - } -} diff --git a/store/adapters/rdbms/schema/schema.go b/store/adapters/rdbms/schema/schema.go deleted file mode 100644 index fe74ee6ed..000000000 --- a/store/adapters/rdbms/schema/schema.go +++ /dev/null @@ -1,43 +0,0 @@ -package schema - -import ( - "context" - "fmt" - - "go.uber.org/zap" -) - -type ( - Schema struct{} - - // schemaUpgrader provides procedures to upgrade rdbms store tables - Upgrader interface { - SetLogger(*zap.Logger) - Before(context.Context) error - CreateTable(context.Context, *Table) error - After(context.Context) error - } -) - -// Upgrade upgrades given rdbms schema by adding all missing tables and applying changes to existing -func Upgrade(ctx context.Context, sud Upgrader) (err error) { - if sud == nil { - return fmt.Errorf("can not upgrade database schema, upgrade interface not set") - } - - if err = sud.Before(ctx); err != nil { - return fmt.Errorf("could not run \"before\" upgrade procedures: %w", err) - } - - for _, t := range tables() { - if err = sud.CreateTable(ctx, t); err != nil { - return fmt.Errorf("could not create table %s: %w", t.Name, err) - } - } - - if err = sud.After(ctx); err != nil { - return fmt.Errorf("could not run \"after\" upgrade procedures: %w", err) - } - - return nil -} diff --git a/store/adapters/rdbms/schema/upgrade.go b/store/adapters/rdbms/schema/upgrade.go deleted file mode 100644 index 41c0a690a..000000000 --- a/store/adapters/rdbms/schema/upgrade.go +++ /dev/null @@ -1,470 +0,0 @@ -package schema - -import ( - "context" - "fmt" - - "go.uber.org/zap" -) - -type ( - commonUpgrades struct { - log *zap.Logger - u upgrader - } - - // - upgrader interface { - TableExists(context.Context, string) (bool, error) - AddColumn(context.Context, string, *Column) (bool, error) - DropTable(context.Context, string) (bool, error) - DropColumn(context.Context, string, string) (bool, error) - RenameColumn(context.Context, string, string, string) (bool, error) - AddPrimaryKey(context.Context, string, *Index) (bool, error) - CreateIndex(context.Context, *Index) (bool, error) - Exec(context.Context, string, ...interface{}) error - } -) - -func CommonUpgrades(log *zap.Logger, u upgrader) *commonUpgrades { - return &commonUpgrades{log, u} -} - -func (g commonUpgrades) Before(ctx context.Context) error { - return g.all(ctx, - g.RenameActionlog, - g.RenameReminders, - g.RenameUsers, - g.RenameRoles, - g.RenameRoleMembers, - g.RenameCredentials, - g.RenameApplications, - g.DropOrganisationTable, - ) -} - -func (g commonUpgrades) After(ctx context.Context) error { - return nil -} - -func (g commonUpgrades) Upgrade(ctx context.Context, t *Table) error { - switch t.Name { - case "settings": - return g.all(ctx, - g.MergeSettingsTables, - ) - case "rbac_rules": - return g.all(ctx, - g.MergePermissionRulesTables, - ) - case "actionlog": - return g.all(ctx, - g.AlterActionlogAddID, - ) - case "applications": - return g.all(ctx, - g.AddWeightField, - ) - case "users": - return g.all(ctx, - g.AlterUsersDropOrganisation, - g.AlterUsersDropRelatedUser, - ) - case "roles": - return g.all(ctx, - g.AddRolesMetaField, - ) - case "compose_page": - return g.all(ctx, - g.AddComposeBlockConfigField, - ) - case "compose_module": - return g.all(ctx, - g.AlterComposeModuleRenameJsonToMeta, - ) - case "compose_module_field": - return g.all(ctx, - g.AlterComposeModuleFieldAddExpresions, - ) - case "automation_sessions": - return g.all(ctx, - g.CreateAutomationSessionIndexes, - ) - //case "compose_attachment_binds": - // return g.all(ctx, - // g.MigrateComposeAttachmentsToBindsTable, - // ) - - case "reports": - return g.all(ctx, - g.AddScenariosField, - ) - case "resource_activity_log": - return g.all(ctx, - g.AddResourceActivityLogMetaField, - ) - } - - return nil -} - -func (commonUpgrades) all(ctx context.Context, ffn ...func(context.Context) error) (err error) { - for _, fn := range ffn { - if err = fn(ctx); err != nil { - return err - } - } - - return nil -} - -// MergeSettingsTables merges "*_settings" tables into one single "settings" -func (g commonUpgrades) MergeSettingsTables(ctx context.Context) error { - var ( - err error - tt = []struct { - tbl string - applyNamePrefix string - }{ - {tbl: "sys_settings", applyNamePrefix: ""}, - {tbl: "compose_settings", applyNamePrefix: "compose."}, - } - - // CONCAT does not work in sqlite; we'll ignore this since sqlite should - // not even get execute this query (*_settings tables do not exist) - merge = ` - INSERT INTO settings (rel_owner, name, value, updated_by, updated_at) - SELECT rel_owner, CONCAT('%s', name), value, updated_by, updated_at - FROM %s` - ) - - for _, t := range tt { - if exists, err := g.u.TableExists(ctx, t.tbl); err != nil { - return err - } else if !exists { - g.log.Debug(fmt.Sprintf("skipping settings merge, table %s already removed", t.tbl)) - continue - } - - err = g.u.Exec(ctx, fmt.Sprintf(merge, t.applyNamePrefix, t.tbl)) - if err != nil { - return fmt.Errorf("could not merge %s: %w", t.tbl, err) - } - - _, err = g.u.DropTable(ctx, t.tbl) - if err != nil { - return fmt.Errorf("could not drop %s: %w", t.tbl, err) - } - - g.log.Debug(fmt.Sprintf("table %s merged into settings and removed", t.tbl)) - } - - return nil -} - -// MergeSettingsTables merges "*_settings" tables into one single "settings" -func (g commonUpgrades) MergePermissionRulesTables(ctx context.Context) error { - var ( - err error - tt = []struct { - tbl string - }{ - {tbl: "sys_permission_rules"}, - {tbl: "compose_permission_rules"}, - } - - // CONCAT does not work in sqlite but we'Ll ignore this since sqlite should - // not even get execute this query (*_permissions tables do not exist) - merge = ` - INSERT INTO rbac_rules (rel_role, resource, operation, access) - SELECT rel_role, resource, operation, access - FROM %s` - ) - - for _, t := range tt { - if exists, err := g.u.TableExists(ctx, t.tbl); err != nil { - return err - } else if !exists { - g.log.Debug(fmt.Sprintf("skipping rbac rules merge, table %s already Deleted", t.tbl)) - continue - } - - err = g.u.Exec(ctx, fmt.Sprintf(merge, t.tbl)) - if err != nil { - return fmt.Errorf("could not merge %s: %w", t.tbl, err) - } - - _, err = g.u.DropTable(ctx, t.tbl) - if err != nil { - return fmt.Errorf("could not drop %s: %w", t.tbl, err) - } - - g.log.Debug(fmt.Sprintf("table %s merged into rbac_rules and Deleted", t.tbl)) - } - - return nil -} - -func (g commonUpgrades) RenameActionlog(ctx context.Context) error { - return g.RenameTable(ctx, "sys_actionlog", "actionlog") -} - -func (g commonUpgrades) RenameUsers(ctx context.Context) error { - return g.RenameTable(ctx, "sys_user", "users") -} - -func (g commonUpgrades) RenameRoles(ctx context.Context) error { - return g.RenameTable(ctx, "sys_role", "roles") -} - -func (g commonUpgrades) RenameRoleMembers(ctx context.Context) error { - return g.RenameTable(ctx, "sys_role_member", "role_members") -} - -func (g commonUpgrades) RenameApplications(ctx context.Context) error { - return g.RenameTable(ctx, "sys_application", "applications") -} - -func (g commonUpgrades) RenameCredentials(ctx context.Context) error { - return g.RenameTable(ctx, "sys_credentials", "credentials") -} - -// AlterActionlogAddID adds ID column, fills it with values and adds PK on it -// -// This is MySQL only; other implementations were never in state with actionlog table -// without ID column. -func (g commonUpgrades) AlterActionlogAddID(ctx context.Context) (err error) { - var ( - added bool - col = &Column{Name: "id", Type: ColumnType{Type: ColumnTypeIdentifier}, IsNull: false} - ind = &Index{Fields: []*IField{{Field: col.Name}}} - upd = `UPDATE actionlog SET id = @v := COALESCE(@v, 0) + 1 WHERE id = 0` - ) - if added, err = g.u.AddColumn(ctx, "actionlog", col); err != nil { - return err - } else if !added { - // not added, no need to continue - return - } - - // Now prefill with generated IDs in any case -- if col was added or not - g.log.Debug(fmt.Sprintf("prefilling missing values for actionlog ID field, might take a while")) - if err = g.u.Exec(ctx, upd); err != nil { - return fmt.Errorf("could not prefill actionlog ID field: %w", err) - } - - if added, err = g.u.AddPrimaryKey(ctx, "actionlog", ind); err != nil { - return err - } - - return nil -} - -func (g commonUpgrades) AddWeightField(ctx context.Context) error { - _, err := g.u.AddColumn(ctx, "applications", &Column{ - Name: "weight", - Type: ColumnType{Type: ColumnTypeInteger}, - IsNull: false, - DefaultValue: "0", - }) - - return err -} - -func (g commonUpgrades) AddRolesMetaField(ctx context.Context) error { - _, err := g.u.AddColumn(ctx, "roles", &Column{ - Name: "meta", - Type: ColumnType{Type: ColumnTypeJson}, - IsNull: false, - DefaultValue: "'{}'", - }) - - return err -} - -func (g commonUpgrades) AddComposeBlockConfigField(ctx context.Context) error { - _, err := g.u.AddColumn(ctx, "compose_page", &Column{ - Name: "config", - Type: ColumnType{Type: ColumnTypeJson}, - IsNull: false, - DefaultValue: "'{}'", - }) - - return err -} - -func (g commonUpgrades) RenameReminders(ctx context.Context) error { - return g.RenameTable(ctx, "sys_reminder", "reminders") -} - -func (g commonUpgrades) DropOrganisationTable(ctx context.Context) error { - _, err := g.u.DropTable(ctx, "organization") - return err -} - -func (g commonUpgrades) AddScenariosField(ctx context.Context) error { - var ( - col = &Column{ - Name: "scenarios", - Type: ColumnType{Type: ColumnTypeJson}, - IsNull: false, - DefaultValue: "NULL", - } - ) - - _, err := g.u.AddColumn(ctx, "reports", col) - return err -} - -func (g commonUpgrades) AlterUsersDropOrganisation(ctx context.Context) error { - _, err := g.u.DropColumn(ctx, "users", "rel_organisation") - return err -} - -func (g commonUpgrades) AlterUsersDropRelatedUser(ctx context.Context) error { - _, err := g.u.DropColumn(ctx, "users", "rel_user_id") - return err -} - -func (g commonUpgrades) RenameTable(ctx context.Context, old, new string) error { - if exists, err := g.u.TableExists(ctx, old); err != nil { - return err - } else if !exists { - g.log.Debug(fmt.Sprintf("skipping %s table rename, old table does not exist", old)) - return nil - } - - if exists, err := g.u.TableExists(ctx, new); err != nil { - return err - } else if exists { - g.log.Debug(fmt.Sprintf("skipping %s table rename, new table already exist", new)) - return nil - } - - if err := g.u.Exec(ctx, fmt.Sprintf("ALTER TABLE %s RENAME TO %s", old, new)); err != nil { - return err - } - - g.log.Debug(fmt.Sprintf("table %s renamed to %s", old, new)) - - return nil -} - -//func (g commonUpgrades) MigrateComposeAttachmentsToLinksTable(ctx context.Context) error { -// var ( -// err error -// tt = []struct { -// tbl string -// }{ -// {tbl: "sys_permission_rules"}, -// {tbl: "compose_permission_rules"}, -// } -// -// // Are there entries in the attachment_binds table? -// check = `SELECT COUNT(*) > 0 FROM compose_attachment_links LIMIT 1` -// -// splitRecordAttachments = ` -// INSERT INTO compose_attachment_links ( -// rel_namespace, rel_attachment, kind, -// ref, -// owned_by -// created_by, updated_by, deleted_by, -// created_at, updated_at, deleted_at -// ) -// SELECT rel_namespace, rel_attachment, kind, -// CASE WHEN kind = 'page' THEN -//(SELECT -// WHEN kind = 'record' THEN 2 -// ELSE 0 END, -// owned_by, 0, 0, -// created_at, updated_at, deleted_at -// FROM compose_attachment -// INNER JOIN compose_record_Value` -// -// splitPageAttachments = ` -// INSERT INTO compose_attachment_links ( -// rel_namespace, rel_attachment, kind, -// ref, -// owned_by -// created_by, updated_by, deleted_by, -// created_at, updated_at, deleted_at -// ) -// SELECT rel_namespace, rel_attachment, kind, -// CASE WHEN kind = 'page' THEN -//(SELECT -// WHEN kind = 'record' THEN 2 -// ELSE 0 END, -// owned_by, 0, 0, -// created_at, updated_at, deleted_at -// FROM compose_attachment` -// ) -// -// g.log.Debug("splitting parts of compose_attachment to compose_attachment_links") -// err = g.u.Exec(ctx, split) -// if err != nil { -// return fmt.Errorf("failed to split compose_attachment: %w", err) -// } -// -// for _, col := range []string{"rel_namespace", "kind"} { -// _, err = g.u.DropColumn(ctx, "compose_attachment", col) -// if err != nil { -// return fmt.Errorf("could not drop column compose_attachment.%s: %w", col, err) -// } -// } -// -// g.log.Debug("compose_attachment split to compose_attachment_links") -// -// return nil -//} - -func (g commonUpgrades) AlterComposeModuleRenameJsonToMeta(ctx context.Context) error { - _, err := g.u.RenameColumn(ctx, "compose_module", "json", "meta") - return err -} - -func (g commonUpgrades) AlterComposeModuleFieldAddExpresions(ctx context.Context) (err error) { - var ( - col = &Column{ - Name: "expressions", - Type: ColumnType{Type: ColumnTypeJson}, - IsNull: false, - DefaultValue: "'{}'", - } - ) - - _, err = g.u.AddColumn(ctx, "compose_module_field", col) - return -} - -func (g commonUpgrades) CreateAutomationSessionIndexes(ctx context.Context) (err error) { - var ( - ii = []*Index{ - {Name: "event_type", Fields: []*IField{{Field: "event_type", Length: handleLength}}}, - {Name: "resource_type", Fields: []*IField{{Field: "resource_type", Length: handleLength}}}, - {Name: "status", Fields: []*IField{{Field: "status"}}}, - {Name: "created_at", Fields: []*IField{{Field: "created_at"}}}, - {Name: "completed_at", Fields: []*IField{{Field: "completed_at"}}}, - {Name: "suspended_at", Fields: []*IField{{Field: "suspended_at"}}}, - } - ) - - for _, i := range ii { - i.Table = "automation_sessions" - if _, err = g.u.CreateIndex(ctx, i); err != nil { - return - } - } - - return -} - -func (g commonUpgrades) AddResourceActivityLogMetaField(ctx context.Context) error { - _, err := g.u.AddColumn(ctx, "resource_activity_log", &Column{ - Name: "meta", - Type: ColumnType{Type: ColumnTypeJson}, - IsNull: false, - DefaultValue: "'{}'", - }) - - return err -} diff --git a/store/adapters/rdbms/tx.go b/store/adapters/rdbms/tx.go index 41e51722b..33b5bf48a 100644 --- a/store/adapters/rdbms/tx.go +++ b/store/adapters/rdbms/tx.go @@ -11,22 +11,28 @@ import ( "github.com/jmoiron/sqlx" ) -func (s Store) Tx(ctx context.Context, fn func(context.Context, store.Storer) error) error { - return tx(ctx, s.db, s.config, nil, func(ctx context.Context, tx dbLayer) error { +type ( + dbTransactionMaker interface { + BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error) + } +) + +func (s *Store) Tx(ctx context.Context, fn func(context.Context, store.Storer) error) error { + if s.TxRetryLimit < 0 { + return fn(ctx, s) + } + + return txHandler(ctx, s.DB, s.TxRetryLimit, s.TxRetryErrHandler, func(ctx context.Context, tx sqlx.ExtContext) error { return fn(ctx, s.withTx(tx)) }) } -// tx begins a new db transaction and handles it's retries when possible +// tx begins a new db transaction and handles retries when possible // // It utilizes configured transaction error handlers and max-retry limits // to determine if and how many times transaction should be retried // -func tx(ctx context.Context, dbCandidate interface{}, cfg *Config, txOpt *sql.TxOptions, task func(context.Context, dbLayer) error) error { - if cfg.TxDisabled { - return task(ctx, dbCandidate.(dbLayer)) - } - +func txHandler(ctx context.Context, dbc interface{}, max int, reh txRetryOnErrHandler, task func(context.Context, sqlx.ExtContext) error) error { var ( lastTaskErr error err error @@ -35,13 +41,13 @@ func tx(ctx context.Context, dbCandidate interface{}, cfg *Config, txOpt *sql.Tx try = 1 ) - switch dbCandidate.(type) { + switch dbc.(type) { case dbTransactionMaker: - // we can make a transaction, yay - db = dbCandidate.(*sqlx.DB) - case dbLayer: + // we can make a transaction! + db = dbc.(*sqlx.DB) + case sqlx.ExtContext: // Already in a transaction, run the given task and finish - return task(ctx, dbCandidate.(dbLayer)) + return task(ctx, dbc.(sqlx.ExtContext)) default: return fmt.Errorf("could not use the db connection for transaction") } @@ -50,7 +56,7 @@ func tx(ctx context.Context, dbCandidate interface{}, cfg *Config, txOpt *sql.Tx try++ // Start transaction - tx, err = db.BeginTxx(ctx, txOpt) + tx, err = db.BeginTxx(ctx, nil) if err != nil { return err } @@ -75,8 +81,8 @@ func tx(ctx context.Context, dbCandidate interface{}, cfg *Config, txOpt *sql.Tx // if this particular error should be retried or not // // We cannot generalize here because different store implementation have - // different errors and we need to act accordingly - if cfg.TxRetryErrHandler == nil || !cfg.TxRetryErrHandler(try, lastTaskErr) { + // different errors; we need to act accordingly + if reh != nil && !reh(try, lastTaskErr) { return fmt.Errorf("failed to complete transaction: %w", lastTaskErr) } @@ -84,7 +90,7 @@ func tx(ctx context.Context, dbCandidate interface{}, cfg *Config, txOpt *sql.Tx // break the retry-loop earlier, but that might not be always the case // // We'll check the configured and hard-limit maximums - if try >= cfg.TxMaxRetries || try >= TxRetryHardLimit { + if try >= max || try >= TxRetryHardLimit { return fmt.Errorf("failed to perform transaction (tries: %d), last error: %w", try, lastTaskErr) } diff --git a/store/adapters/rdbms/upgrade.go b/store/adapters/rdbms/upgrade.go index 5cb8436da..674cde928 100644 --- a/store/adapters/rdbms/upgrade.go +++ b/store/adapters/rdbms/upgrade.go @@ -3,22 +3,44 @@ package rdbms import ( "context" "fmt" - - "github.com/cortezaproject/corteza-server/store/adapters/rdbms/schema" - "go.uber.org/zap" ) -func (s Store) Upgrade(ctx context.Context, log *zap.Logger) error { - if s.config == nil { - return fmt.Errorf("config not set on RDBMS store") +func (s *Store) Upgrade(ctx context.Context) (err error) { + if err = UpgradeBeforeTableCreation(ctx, s); err != nil { + return } - if s.config.Upgrader == nil { - return fmt.Errorf("upgrader not configured on RDBMS store") - + if err = UpgradeCreateTables(ctx, s); err != nil { + return } - s.config.Upgrader.SetLogger(log) + if err = UpgradeAfterTableCreation(ctx, s); err != nil { + return + } - return schema.Upgrade(ctx, s.config.Upgrader) + return +} + +// UpgradeBeforeTableCreation all actions that need to happen before tables are created +// +// Important note! +// Corteza needs to be updated to the latest patch release under 2022.3.x before upgrading to 2022.9! +func UpgradeBeforeTableCreation(ctx context.Context, s *Store) (err error) { + // @todo figure out how we will detect if database is on the latest version + return +} + +// UpgradeCreateTables creates all tables needed by RDBMS store for Corteza to function properly +func UpgradeCreateTables(ctx context.Context, s *Store) (err error) { + for _, t := range Tables() { + if err = s.SchemaAPI.CreateTable(ctx, s.DB, t); err != nil { + return fmt.Errorf("could not create table %s: %w", t.Name, err) + } + } + + return +} + +func UpgradeAfterTableCreation(ctx context.Context, s *Store) (err error) { + return } diff --git a/store/adapters/rdbms/schema/tables.go b/store/adapters/rdbms/upgrade_tables.go similarity index 95% rename from store/adapters/rdbms/schema/tables.go rename to store/adapters/rdbms/upgrade_tables.go index 7ab9e3d05..d57d07c8c 100644 --- a/store/adapters/rdbms/schema/tables.go +++ b/store/adapters/rdbms/upgrade_tables.go @@ -1,4 +1,8 @@ -package schema +package rdbms + +import ( + . "github.com/cortezaproject/corteza-server/store/adapters/rdbms/ddl" +) const ( handleLength = 64 @@ -21,8 +25,8 @@ const ( languageKeyLength = 256 ) -// Tables fn holds a list of all tables that need to be created for Corteza -func tables() []*Table { +// Tables fn holds a list of all tables that need to be created +func Tables() []*Table { return []*Table{ tableUsers(), tableCredentials(), @@ -380,34 +384,6 @@ func tableComposeAttachment() *Table { ) } -//func tableComposeRecordAttachment() *Table { -// return TableDef("compose_record_attachments", -// ColumnDef("rel_attachment", ColumnTypeIdentifier), -// ColumnDef("rel_namespace", ColumnTypeIdentifier), -// ColumnDef("rel_module", ColumnTypeIdentifier), -// ColumnDef("rel_record", ColumnTypeIdentifier), -// ColumnDef("field", ColumnTypeIdentifier), -// ColumnDef("owned_by", ColumnTypeIdentifier), -// CUDTimestamps, -// CUDUsers, -// -// PrimaryKey(IColumn("rel_attachment", "rel_namespace", "rel_module", "field")), -// ) -//} - -//func tableComposePageAttachment() *Table { -// return TableDef("compose_record_attachments", -// ColumnDef("rel_attachment", ColumnTypeIdentifier), -// ColumnDef("rel_namespace", ColumnTypeIdentifier), -// ColumnDef("rel_page", ColumnTypeIdentifier), -// ColumnDef("owned_by", ColumnTypeIdentifier), -// CUDTimestamps, -// CUDUsers, -// -// PrimaryKey(IColumn("rel_attachment", "rel_namespace", "rel_page")), -// ) -//} - func tableComposeChart() *Table { return TableDef("compose_chart", ID, diff --git a/store/errors.go b/store/errors.go index a09d52c44..9d9c02b88 100644 --- a/store/errors.go +++ b/store/errors.go @@ -3,8 +3,9 @@ package store import "github.com/cortezaproject/corteza-server/pkg/errors" type ( + // ErrorHandler // each implementation can have internal error handler that can translate - // impl. specific errors liker transaction + // impl. specific errors like transaction ErrorHandler func(error) error ) diff --git a/store/interfaces.gen.go b/store/interfaces.gen.go index 539f420f8..e95ef2783 100644 --- a/store/interfaces.gen.go +++ b/store/interfaces.gen.go @@ -38,7 +38,7 @@ type ( Tx(context.Context, func(context.Context, Storer) error) error // Upgrade store's schema to the latest version - Upgrade(context.Context, *zap.Logger) error + Upgrade(context.Context) error Actionlogs ApigwFilters ApigwRoutes diff --git a/store/tests/labels_test.go b/store/tests/labels_test.go index f05a7f832..3f45150e3 100644 --- a/store/tests/labels_test.go +++ b/store/tests/labels_test.go @@ -2,11 +2,13 @@ package tests import ( "context" + "testing" + "github.com/cortezaproject/corteza-server/pkg/label/types" + "github.com/cortezaproject/corteza-server/pkg/logger" "github.com/cortezaproject/corteza-server/store" _ "github.com/joho/godotenv/autoload" "github.com/stretchr/testify/require" - "testing" ) func testLabels(t *testing.T, s store.Labels) { @@ -14,6 +16,8 @@ func testLabels(t *testing.T, s store.Labels) { ctx = context.Background() ) + ctx = logger.ContextWithValue(ctx, logger.MakeDebugLogger()) + t.Run("create", func(t *testing.T) { req := require.New(t) req.NoError(s.TruncateLabels(ctx)) diff --git a/store/tests/main_test.go b/store/tests/main_test.go index 97d369361..a8a42a49f 100644 --- a/store/tests/main_test.go +++ b/store/tests/main_test.go @@ -82,7 +82,7 @@ func setup(t *testing.T, connect store.ConnectorFn) (s store.Storer) { err = store.Upgrade(ctx, zap.NewNop(), s) if err != nil { - t.Errorf("failed to upgrade : %v", err) + t.Fatalf("failed to upgrade : %v", err) return } diff --git a/store/tx.go b/store/tx.go index aa82ce722..259da387b 100644 --- a/store/tx.go +++ b/store/tx.go @@ -1,6 +1,8 @@ package store -import "context" +import ( + "context" +) func Tx(ctx context.Context, s Storer, fn func(context.Context, Storer) error) error { return s.Tx(ctx, fn) diff --git a/store/upgrade.go b/store/upgrade.go index fcab00f99..98c2886ee 100644 --- a/store/upgrade.go +++ b/store/upgrade.go @@ -6,15 +6,10 @@ import ( "go.uber.org/zap" ) -type ( - upgradable interface { - Upgrade(context.Context, *zap.Logger) error - } -) - // Upgrade runs all needed upgrades on a specific store -// -// See store/adapters/rdbms/schema/README.md for more details on RDBMS implementations -func Upgrade(ctx context.Context, log *zap.Logger, s upgradable) error { - return s.Upgrade(ctx, log) +func Upgrade(ctx context.Context, log *zap.Logger, s Storer) error { + return Tx(ctx, s, func(ctx context.Context, s Storer) error { + s.SetLogger(log) + return s.Upgrade(ctx) + }) }