mirror of
https://github.com/hanzoai/o11y.git
synced 2026-10-15 12:58:33 +00:00
# Conflicts: # .github/workflows/build-community.yaml # .github/workflows/build-enterprise.yaml # .github/workflows/gor-signoz-community.yaml # cmd/community/Dockerfile # cmd/community/Dockerfile.multi-arch # cmd/community/main.go # cmd/community/server.go # cmd/enterprise/Dockerfile # cmd/enterprise/Dockerfile.integration # cmd/enterprise/Dockerfile.with-web.integration # cmd/server/metastore.go # cmd/zap.go # conf/prometheus.yml # deploy/docker-swarm/generator/hotrod/docker-compose.yaml # deploy/docker-swarm/generator/infra/docker-compose.yaml # deploy/docker-swarm/generator/infra/otel-agent-config.yaml # deploy/docker-swarm/generator/infra/otel-metrics-config.yaml # deploy/docker/generator/hotrod/docker-compose.yaml # deploy/docker/generator/infra/docker-compose.yaml # deploy/docker/generator/infra/otel-collector-config.yaml # docs/contributing/go/integration.md # ee/anomaly/hourly.go # ee/anomaly/params.go # ee/anomaly/seasonal.go # ee/authn/callbackauthn/oidccallbackauthn/authn.go # ee/authz/openfgaauthz/provider.go # ee/authz/openfgaschema/base.fga # ee/authz/openfgaserver/server.go # ee/licensing/config.go # ee/licensing/httplicensing/provider.go # ee/modules/dashboard/impldashboard/module.go # ee/querier/handler.go # ee/query-service/anomaly/seasonal.go # ee/query-service/app/api/cloudIntegrations.go # ee/query-service/app/api/featureFlags.go # ee/query-service/app/api/license.go # ee/query-service/app/api/queryrange.go # ee/query-service/rules/anomaly.go # ee/query-service/rules/anomaly_test.go # ee/query-service/rules/manager.go # ee/query-service/rules/manager_test.go # ee/query-service/usage/manager.go # ee/sqlschema/postgressqlschema/provider.go # ee/sqlstore/postgressqlstore/dialect.go # ee/sqlstore/postgressqlstore/provider.go # ee/zeus/config.go # ee/zeus/httpzeus/provider.go # frontend/.eslintrc.cjs # frontend/e2e/test-plan/README.md # frontend/e2e/test-plan/validation-report.md # frontend/e2e/tests/settings/account-settings/account-settings-settings.spec.ts # frontend/e2e/tests/settings/api-keys/api-keys-settings.spec.ts # frontend/playwright.config.ts # frontend/public/Images/signoz-hero-image.webp # frontend/public/Logos/signoz-brand-logo.svg # frontend/scripts/generate-permissions-type.cjs # frontend/src/assets/Images/o11y-hero-image.webp # frontend/src/assets/Images/signoz-hero-image.webp # frontend/src/assets/Logos/hanzo-brand-logo.svg # frontend/src/assets/Logos/hanzo-icon.svg # frontend/src/assets/Logos/o11y-brand-logo.svg # frontend/src/assets/Logos/signoz-brand-logo.svg # frontend/src/assets/SigNoz-dark.svg # frontend/src/assets/SigNoz-white.svg # frontend/src/assets/signoz.svg # frontend/src/components/DetailsDrawer/DetailsDrawer.styles.scss # frontend/src/components/HostMetricsDetail/HostMetricTraces/HostMetricTraces.styles.scss # frontend/src/components/HostMetricsDetail/HostMetricTraces/constants.ts # frontend/src/components/HostMetricsDetail/HostMetricsDetail.styles.scss # frontend/src/components/HostMetricsDetail/HostMetricsDetails.tsx # frontend/src/components/HostMetricsDetail/HostMetricsLogs/NoLogsContainer.tsx # frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts # frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.styles.scss # frontend/src/components/WelcomeLeftContainer/index.tsx # frontend/src/container/APIKeys/APIKeys.styles.scss # frontend/src/container/APIKeys/APIKeys.test.tsx # frontend/src/container/APIKeys/APIKeys.tsx # frontend/src/container/CloudIntegrationPage/Header/Header.tsx # frontend/src/container/CloudIntegrationPage/HeroSection/HeroSection.tsx # frontend/src/container/CloudIntegrationPage/HeroSection/components/AccountActions.style.scss # frontend/src/container/CloudIntegrationPage/HeroSection/components/AccountActions.tsx # frontend/src/container/CloudIntegrationPage/HeroSection/components/AccountSettingsModal.style.scss # frontend/src/container/CloudIntegrationPage/HeroSection/components/AccountSettingsModal.tsx # frontend/src/container/CloudIntegrationPage/HeroSection/components/CloudAccountSetupModal.style.scss # frontend/src/container/CloudIntegrationPage/HeroSection/components/RemoveIntegrationAccount.tsx # frontend/src/container/CloudIntegrationPage/ServicesSection/ConfigureServiceModal.tsx # frontend/src/container/CloudIntegrationPage/ServicesSection/ServicesTabs.style.scss # frontend/src/container/CloudIntegrationPage/ServicesSection/ServicesTabs.tsx # frontend/src/container/DashboardContainer/DashboardSettings/General/AddTags/AddTags.styles.scss # frontend/src/container/DashboardContainer/DashboardSettings/General/GeneralSettings.styles.scss # frontend/src/container/FormAlertRules/ChQuerySection/ChQuerySection.tsx # frontend/src/container/FormAlertRules/UserGuide/index.tsx # frontend/src/container/InfraMonitoringHosts/HostsEmptyOrIncorrectMetrics.tsx # frontend/src/container/InfraMonitoringHosts/InfraMonitoring.styles.scss # frontend/src/container/InfraMonitoringHosts/__tests__/HostsEmptyOrIncorrectMetrics.test.tsx # frontend/src/container/InfraMonitoringK8s/Clusters/ClusterDetails/ClusterDetails.tsx # frontend/src/container/InfraMonitoringK8s/Clusters/utils.tsx # frontend/src/container/InfraMonitoringK8s/DaemonSets/DaemonSetDetails/DaemonSetDetails.tsx # frontend/src/container/InfraMonitoringK8s/DaemonSets/utils.tsx # frontend/src/container/InfraMonitoringK8s/Deployments/DeploymentDetails/DeploymentDetails.tsx # frontend/src/container/InfraMonitoringK8s/Deployments/utils.tsx # frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/entityEvents.styles.scss # frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityTraces/entityTraces.styles.scss # frontend/src/container/InfraMonitoringK8s/InfraMonitoringK8s.styles.scss # frontend/src/container/InfraMonitoringK8s/Jobs/JobDetails/JobDetails.tsx # frontend/src/container/InfraMonitoringK8s/Jobs/utils.tsx # frontend/src/container/InfraMonitoringK8s/K8sEmptyOrIncorrectMetrics.tsx # frontend/src/container/InfraMonitoringK8s/K8sFiltersSidePanel/K8sFiltersSidePanel.styles.scss # frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.styles.scss # frontend/src/container/InfraMonitoringK8s/Namespaces/NamespaceDetails/NamespaceDetails.tsx # frontend/src/container/InfraMonitoringK8s/Namespaces/utils.tsx # frontend/src/container/InfraMonitoringK8s/Nodes/NodeDetails/NodeDetails.tsx # frontend/src/container/InfraMonitoringK8s/Nodes/utils.tsx # frontend/src/container/InfraMonitoringK8s/Pods/PodDetails/PodDetails.tsx # frontend/src/container/InfraMonitoringK8s/StatefulSets/StatefulSetDetails/StatefulSetDetails.tsx # frontend/src/container/InfraMonitoringK8s/StatefulSets/utils.tsx # frontend/src/container/InfraMonitoringK8s/Volumes/VolumeDetails/VolumeDetails.tsx # frontend/src/container/InfraMonitoringK8s/Volumes/utils.tsx # frontend/src/container/ListAlertRules/AlertsEmptyState/AlertsEmptyState.styles.scss # frontend/src/container/ListAlertRules/ListAlert.tsx # frontend/src/container/LogsContextList/styles.ts # frontend/src/container/LogsExplorerList/ColumnView/ColumnView.tsx # frontend/src/container/LogsExplorerViews/QueryStatus.tsx # frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexTraces.tsx # frontend/src/container/MetricsExplorer/Explorer/RelatedMetrics.tsx # frontend/src/container/MetricsExplorer/Explorer/useGetRelatedMetricsGraphs.ts # frontend/src/container/MetricsExplorer/Summary/MetricTypeSearch.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/ClickHouse/index.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/ClickHouse/query.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/index.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/query.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/datastore/index.tsx # frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/datastore/query.tsx # frontend/src/container/OnboardingQuestionaire/OnboardingFooter/OnboardingFooter.tsx # frontend/src/container/OnboardingQuestionaire/OnboardingHeader/OnboardingHeader.styles.scss # frontend/src/container/OnboardingQuestionaire/OnboardingHeader/OnboardingHeader.tsx # frontend/src/container/OnboardingV2Container/onboarding-configs/onboarding-config-with-links.json # frontend/src/container/QueryBuilder/QueryBuilder.tsx # frontend/src/container/QueryBuilder/components/Query/Query.tsx # frontend/src/container/RolesSettings/__tests__/utils.test.ts # frontend/src/container/ServiceTable/SkipOnBoardModal/index.tsx # frontend/src/container/TraceDetail/Missingtrace.tsx # frontend/src/container/TraceDetail/SelectedSpanDetails/config.ts # frontend/src/lib/uPlotV2/components/Tooltip/Tooltip.styles.scss # frontend/src/mocks-server/__mockdata__/apiKeys.ts # frontend/src/pages/AlertDetails/AlertHeader/AlertStatus/AlertStatus.tsx # frontend/src/pages/Integrations/IntegrationDetailPage/IntegrationDetailPage.styles.scss # frontend/src/pages/Integrations/IntegrationDetailPage/IntegrationDetailPage.tsx # frontend/src/pages/Integrations/IntegrationsList.tsx # frontend/src/pages/Integrations/utils.ts # frontend/src/types/api/integrations/aws.ts # pkg/alertmanager/o11yalertmanager/handler.go # pkg/apiserver/o11yapiserver/alertmanager.go # pkg/apiserver/o11yapiserver/cloudintegration.go # pkg/apiserver/o11yapiserver/inframonitoring.go # pkg/apiserver/o11yapiserver/llmpricingrule.go # pkg/apiserver/o11yapiserver/rawdataexport.go # pkg/apiserver/o11yapiserver/registry.go # pkg/apiserver/o11yapiserver/ruler.go # pkg/apiserver/o11yapiserver/ruler_examples.go # pkg/apiserver/o11yapiserver/ruler_examples_test.go # pkg/apiserver/o11yapiserver/rulestatehistory.go # pkg/apiserver/o11yapiserver/spanmapper.go # pkg/apiserver/o11yapiserver/tracedetail.go # pkg/authn/callbackauthn/googlecallbackauthn/authn.go # pkg/authz/openfgaauthz/provider.go # pkg/authz/openfgaschema/base.fga # pkg/authz/openfgaserver/server.go # pkg/authz/openfgaserver/server_test.go # pkg/authz/openfgaserver/sqlstore.go # pkg/http/middleware/api_key.go # pkg/http/middleware/authn.go # pkg/instrumentation/metric.go # pkg/modules/user/impluser/module.go # pkg/prometheus/clickhouseprometheus/client.go # pkg/prometheus/clickhouseprometheus/client_query_test.go # pkg/prometheus/clickhouseprometheus/provider.go # pkg/prometheus/config.go # pkg/prometheus/engine.go # pkg/prometheus/label.go # pkg/prometheus/prometheus.go # pkg/prometheus/prometheustest/provider.go # pkg/prometheus/prometheustest/utils_test.go # pkg/querier/promql_query.go # pkg/query-service/app/cloudintegrations/Readme.md # pkg/query-service/app/cloudintegrations/accountsRepo.go # pkg/query-service/app/cloudintegrations/constants.go # pkg/query-service/app/cloudintegrations/controller.go # pkg/query-service/app/cloudintegrations/models.go # pkg/query-service/app/cloudintegrations/serviceconfig_db.go # pkg/query-service/app/cloudintegrations/services/definitions/aws/eks/assets/dashboards/containerinsights.json # pkg/query-service/app/cloudintegrations/services/definitions/aws/eks/assets/dashboards/containerinsights_dot.json # pkg/query-service/app/cloudintegrations/services/definitions/aws/eks/assets/dashboards/overview.json # pkg/query-service/app/cloudintegrations/services/definitions/aws/eks/assets/dashboards/overview_dot.json # pkg/query-service/app/cloudintegrations/services/models.go # pkg/query-service/app/cloudintegrations/services/services.go # pkg/query-service/app/cloudintegrations/services/services_test.go # pkg/query-service/app/integrations/builtin_integrations/clickhouse/assets/dashboards/overview_dot.json # pkg/query-service/app/integrations/builtin_integrations/datastore/assets/dashboards/overview_dot.json # pkg/query-service/app/metricsexplorer/parser.go # pkg/query-service/app/metricsexplorer/summary.go # pkg/query-service/app/querier/querier_test.go # pkg/query-service/app/querier/v2/querier_test.go # pkg/query-service/app/summary.go # pkg/query-service/model/metrics_explorer/summary.go # pkg/query-service/rules/base_rule_test.go # pkg/query-service/rules/manager_test.go # pkg/query-service/rules/prom_rule.go # pkg/query-service/rules/prom_rule_task.go # pkg/query-service/rules/prom_rule_test.go # pkg/query-service/rules/threshold_rule_test.go # pkg/querybuilder/resourcefilter/tables.go # pkg/queryparser/queryfilterextractor/promql.go # pkg/ruler/o11yruler/handler.go # pkg/sqlmigration/088_migrate_ii_dashboards/clickhouse/overview.json # pkg/telemetrymetadata/metadata_test.go # pkg/telemetrystore/datastoretelemetrystore/telemetry.go # pkg/types/authtypes/name.go # pkg/types/authtypes/object.go # pkg/types/authtypes/selector.go # pkg/types/authtypes/typeable.go # pkg/types/authtypes/typeable_anonymous.go # pkg/types/authtypes/typeable_metaresource.go # pkg/types/authtypes/typeable_metaresources.go # pkg/types/authtypes/typeable_organization.go # pkg/types/authtypes/typeable_role.go # pkg/types/authtypes/typeable_user.go # pkg/types/authtypes/uuid.go # pkg/types/ctxtypes/auth.go # pkg/types/factor_api_key.go # pkg/types/integrationtypes/integration.go # pkg/types/roletypes/store.go # pkg/types/ruletypes/maintenance.go # pkg/types/serviceaccounttypes/service_account_role.go # pkg/types/serviceaccounttypes/store.go
512 lines
13 KiB
Go
512 lines
13 KiB
Go
package sqlitesqlstore
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"reflect"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/hanzoai/o11y/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
const (
|
|
Identity string = "id"
|
|
Integer string = "INTEGER"
|
|
Text string = "TEXT"
|
|
)
|
|
|
|
const (
|
|
Org string = "org"
|
|
User string = "user"
|
|
UserNoCascade string = "user_no_cascade"
|
|
FactorPassword string = "factor_password"
|
|
CloudIntegration string = "cloud_integration"
|
|
AgentConfigVersion string = "agent_config_version"
|
|
)
|
|
|
|
const (
|
|
OrgReference string = `("org_id") REFERENCES "organizations" ("id")`
|
|
UserReference string = `("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE`
|
|
UserNoCascadeReference string = `("user_id") REFERENCES "users" ("id")`
|
|
FactorPasswordReference string = `("password_id") REFERENCES "factor_password" ("id")`
|
|
CloudIntegrationReference string = `("cloud_integration_id") REFERENCES "cloud_integration" ("id") ON DELETE CASCADE`
|
|
AgentConfigVersionReference string = `("version_id") REFERENCES "agent_config_version" ("id")`
|
|
)
|
|
|
|
const (
|
|
OrgField string = "org_id"
|
|
)
|
|
|
|
type dialect struct{}
|
|
|
|
func (dialect *dialect) GetColumnType(ctx context.Context, bun bun.IDB, table string, column string) (string, error) {
|
|
var columnType string
|
|
|
|
err := bun.
|
|
NewSelect().
|
|
ColumnExpr("type").
|
|
TableExpr("pragma_table_info(?)", table).
|
|
Where("name = ?", column).
|
|
Scan(ctx, &columnType)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return columnType, nil
|
|
}
|
|
|
|
func (dialect *dialect) IntToTimestamp(ctx context.Context, bun bun.IDB, table string, column string) error {
|
|
columnType, err := dialect.GetColumnType(ctx, bun, table, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if columnType != "INTEGER" {
|
|
return nil
|
|
}
|
|
|
|
// if the columns is integer then do this
|
|
if _, err := bun.ExecContext(ctx, `ALTER TABLE `+table+` RENAME COLUMN `+column+` TO `+column+`_old`); err != nil {
|
|
return err
|
|
}
|
|
|
|
// add new timestamp column
|
|
if _, err := bun.
|
|
NewAddColumn().
|
|
Table(table).
|
|
ColumnExpr(column + " TIMESTAMP").
|
|
Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// copy data from old column to new column, converting from int (unix timestamp) to timestamp
|
|
if _, err := bun.
|
|
NewUpdate().
|
|
Table(table).
|
|
Set(column + " = datetime(" + column + "_old, 'unixepoch')").
|
|
Where("1=1").
|
|
Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// drop old column
|
|
if _, err := bun.NewDropColumn().Table(table).Column(column + "_old").Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) IntToBoolean(ctx context.Context, bun bun.IDB, table string, column string) error {
|
|
columnExists, err := dialect.ColumnExists(ctx, bun, table, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !columnExists {
|
|
return nil
|
|
}
|
|
|
|
columnType, err := dialect.GetColumnType(ctx, bun, table, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if columnType != "INTEGER" {
|
|
return nil
|
|
}
|
|
|
|
if _, err := bun.ExecContext(ctx, `ALTER TABLE `+table+` RENAME COLUMN `+column+` TO `+column+`_old`); err != nil {
|
|
return err
|
|
}
|
|
|
|
// add new boolean column
|
|
if _, err := bun.NewAddColumn().Table(table).ColumnExpr(column + " BOOLEAN").Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// copy data from old column to new column, converting from int to boolean
|
|
if _, err := bun.
|
|
NewUpdate().
|
|
Table(table).
|
|
Set(column + " = CASE WHEN " + column + "_old = 1 THEN true ELSE false END").
|
|
Where("1=1").
|
|
Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// drop old column
|
|
if _, err := bun.NewDropColumn().Table(table).Column(column + "_old").Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) ColumnExists(ctx context.Context, bun bun.IDB, table string, column string) (bool, error) {
|
|
var count int
|
|
err := bun.NewSelect().
|
|
ColumnExpr("COUNT(*)").
|
|
TableExpr("pragma_table_info(?)", table).
|
|
Where("name = ?", column).
|
|
Scan(ctx, &count)
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return count > 0, nil
|
|
}
|
|
|
|
func (dialect *dialect) AddColumn(ctx context.Context, bun bun.IDB, table string, column string, columnExpr string) error {
|
|
exists, err := dialect.ColumnExists(ctx, bun, table, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !exists {
|
|
_, err = bun.
|
|
NewAddColumn().
|
|
Table(table).
|
|
ColumnExpr(column + " " + columnExpr).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) RenameColumn(ctx context.Context, bun bun.IDB, table string, oldColumnName string, newColumnName string) (bool, error) {
|
|
oldColumnExists, err := dialect.ColumnExists(ctx, bun, table, oldColumnName)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
newColumnExists, err := dialect.ColumnExists(ctx, bun, table, newColumnName)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if newColumnExists {
|
|
return true, nil
|
|
}
|
|
|
|
if !oldColumnExists {
|
|
return false, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "old column: %s doesn't exist", oldColumnName)
|
|
}
|
|
|
|
_, err = bun.
|
|
ExecContext(ctx, "ALTER TABLE "+table+" RENAME COLUMN "+oldColumnName+" TO "+newColumnName)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
func (dialect *dialect) DropColumn(ctx context.Context, bun bun.IDB, table string, column string) error {
|
|
exists, err := dialect.ColumnExists(ctx, bun, table, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
_, err = bun.
|
|
NewDropColumn().
|
|
Table(table).
|
|
Column(column).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) TableExists(ctx context.Context, bun bun.IDB, table interface{}) (bool, error) {
|
|
count := 0
|
|
err := bun.
|
|
NewSelect().
|
|
ColumnExpr("count(*)").
|
|
Table("sqlite_master").
|
|
Where("type = ?", "table").
|
|
Where("name = ?", bun.Dialect().Tables().Get(reflect.TypeOf(table)).Name).
|
|
Scan(ctx, &count)
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if count == 0 {
|
|
return false, nil
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
func (dialect *dialect) RenameTableAndModifyModel(ctx context.Context, bun bun.IDB, oldModel interface{}, newModel interface{}, references []string, cb func(context.Context) error) error {
|
|
if len(references) == 0 {
|
|
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot run migration without reference")
|
|
}
|
|
exists, err := dialect.TableExists(ctx, bun, newModel)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
return nil
|
|
}
|
|
|
|
var fkReferences []string
|
|
for _, reference := range references {
|
|
if reference == Org && !slices.Contains(fkReferences, OrgReference) {
|
|
fkReferences = append(fkReferences, OrgReference)
|
|
} else if reference == User && !slices.Contains(fkReferences, UserReference) {
|
|
fkReferences = append(fkReferences, UserReference)
|
|
} else if reference == UserNoCascade && !slices.Contains(fkReferences, UserNoCascadeReference) {
|
|
fkReferences = append(fkReferences, UserNoCascadeReference)
|
|
} else if reference == FactorPassword && !slices.Contains(fkReferences, FactorPasswordReference) {
|
|
fkReferences = append(fkReferences, FactorPasswordReference)
|
|
} else if reference == CloudIntegration && !slices.Contains(fkReferences, CloudIntegrationReference) {
|
|
fkReferences = append(fkReferences, CloudIntegrationReference)
|
|
} else if reference == AgentConfigVersion && !slices.Contains(fkReferences, AgentConfigVersionReference) {
|
|
fkReferences = append(fkReferences, AgentConfigVersionReference)
|
|
}
|
|
}
|
|
|
|
createTable := bun.
|
|
NewCreateTable().
|
|
IfNotExists().
|
|
Model(newModel)
|
|
|
|
for _, fk := range fkReferences {
|
|
createTable = createTable.ForeignKey(fk)
|
|
}
|
|
|
|
_, err = createTable.Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = cb(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bun.
|
|
NewDropTable().
|
|
IfExists().
|
|
Model(oldModel).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) AddNotNullDefaultToColumn(ctx context.Context, bun bun.IDB, table string, column, columnType, defaultValue string) error {
|
|
if _, err := bun.NewAddColumn().Table(table).ColumnExpr(fmt.Sprintf("%s_new %s NOT NULL DEFAULT %s ", column, columnType, defaultValue)).Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := bun.NewUpdate().Table(table).Set(fmt.Sprintf("%s_new = %s", column, column)).Where("1=1").Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := bun.NewDropColumn().Table(table).ColumnExpr(column).Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err := bun.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s RENAME COLUMN %s_new TO %s", table, column, column)); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) UpdatePrimaryKey(ctx context.Context, bun bun.IDB, oldModel interface{}, newModel interface{}, reference string, cb func(context.Context) error) error {
|
|
if reference == "" {
|
|
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot run migration without reference")
|
|
}
|
|
oldTableName := bun.Dialect().Tables().Get(reflect.TypeOf(oldModel)).Name
|
|
newTableName := bun.Dialect().Tables().Get(reflect.TypeOf(newModel)).Name
|
|
|
|
columnType, err := dialect.GetColumnType(ctx, bun, oldTableName, Identity)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if columnType == Text {
|
|
return nil
|
|
}
|
|
|
|
fkReference := ""
|
|
switch reference {
|
|
case Org:
|
|
fkReference = OrgReference
|
|
case User:
|
|
fkReference = UserReference
|
|
}
|
|
|
|
_, err = bun.
|
|
NewCreateTable().
|
|
IfNotExists().
|
|
Model(newModel).
|
|
ForeignKey(fkReference).
|
|
Exec(ctx)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = cb(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bun.
|
|
NewDropTable().
|
|
IfExists().
|
|
Model(oldModel).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bun.
|
|
ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTableName, oldTableName))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) AddPrimaryKey(ctx context.Context, bun bun.IDB, oldModel interface{}, newModel interface{}, reference string, cb func(context.Context) error) error {
|
|
if reference == "" {
|
|
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "cannot run migration without reference")
|
|
}
|
|
oldTableName := bun.Dialect().Tables().Get(reflect.TypeOf(oldModel)).Name
|
|
newTableName := bun.Dialect().Tables().Get(reflect.TypeOf(newModel)).Name
|
|
|
|
identityExists, err := dialect.ColumnExists(ctx, bun, oldTableName, Identity)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if identityExists {
|
|
return nil
|
|
}
|
|
|
|
fkReference := ""
|
|
switch reference {
|
|
case Org:
|
|
fkReference = OrgReference
|
|
case User:
|
|
fkReference = UserReference
|
|
}
|
|
|
|
_, err = bun.
|
|
NewCreateTable().
|
|
IfNotExists().
|
|
Model(newModel).
|
|
ForeignKey(fkReference).
|
|
Exec(ctx)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = cb(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bun.
|
|
NewDropTable().
|
|
IfExists().
|
|
Model(oldModel).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bun.
|
|
ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTableName, oldTableName))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) DropColumnWithForeignKeyConstraint(ctx context.Context, bunIDB bun.IDB, model interface{}, column string) error {
|
|
var isForeignKeyEnabled bool
|
|
if err := bunIDB.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&isForeignKeyEnabled); err != nil {
|
|
return err
|
|
}
|
|
|
|
if isForeignKeyEnabled {
|
|
return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "foreign keys are enabled, please disable them before running this migration")
|
|
}
|
|
|
|
existingTable := bunIDB.Dialect().Tables().Get(reflect.TypeOf(model))
|
|
columnExists, err := dialect.ColumnExists(ctx, bunIDB, existingTable.Name, column)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !columnExists {
|
|
return nil
|
|
}
|
|
|
|
newTableName := existingTable.Name + "_tmp"
|
|
|
|
// Create the newTmpTable query
|
|
createTableQuery := bunIDB.NewCreateTable().Model(model).ModelTableExpr(newTableName)
|
|
|
|
var columnNames []string
|
|
|
|
for _, field := range existingTable.Fields {
|
|
if field.Name != column {
|
|
columnNames = append(columnNames, string(field.SQLName))
|
|
}
|
|
|
|
if field.Name == OrgField {
|
|
createTableQuery = createTableQuery.ForeignKey(OrgReference)
|
|
}
|
|
}
|
|
|
|
if _, err = createTableQuery.Exec(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Copy data from old table to new table
|
|
if _, err := bunIDB.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s SELECT %s FROM %s", newTableName, strings.Join(columnNames, ", "), existingTable.Name)); err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bunIDB.NewDropTable().Table(existingTable.Name).Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = bunIDB.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTableName, existingTable.Name))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (dialect *dialect) ToggleForeignKeyConstraint(ctx context.Context, bun *bun.DB, enable bool) error {
|
|
if enable {
|
|
_, err := bun.ExecContext(ctx, "PRAGMA foreign_keys = ON")
|
|
return err
|
|
}
|
|
|
|
_, err := bun.ExecContext(ctx, "PRAGMA foreign_keys = OFF")
|
|
return err
|
|
}
|