mirror of
https://github.com/SigNoz/signoz.git
synced 2026-05-26 20:00:33 +01:00
Compare commits
3 Commits
fix/time-p
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d36031d4e | ||
|
|
dd3e743b2e | ||
|
|
a60d87c51b |
@@ -94,17 +94,19 @@ func newProvider(
|
||||
func (provider *Provider) Start(ctx context.Context) error {
|
||||
close(provider.healthyC)
|
||||
|
||||
provider.collect(ctx)
|
||||
startDelay := provider.config.NewJitter()
|
||||
|
||||
ticker := time.NewTicker(provider.config.Interval)
|
||||
defer ticker.Stop()
|
||||
timer := time.NewTimer(startDelay)
|
||||
defer timer.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-provider.stopC:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
case <-timer.C:
|
||||
provider.collect(ctx)
|
||||
next := provider.config.Interval - provider.config.NewJitter()
|
||||
timer.Reset(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,6 +259,7 @@ func (provider *Provider) report(ctx context.Context, orgID valuer.UUID, license
|
||||
collectedReadings, err := collector.Collect(ctx, orgID, license, window)
|
||||
if err != nil {
|
||||
provider.metrics.collections.Add(ctx, 1, metric.WithAttributes(meterAttr, errors.TypeAttr(err)))
|
||||
provider.settings.Logger().ErrorContext(ctx, "meter collector failed", errors.Attr(err), slog.String("org_id", orgID.StringValue()), slog.String("meter", collector.Name().String()))
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
44
frontend/AGENTS.md
Normal file
44
frontend/AGENTS.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Agent Directives: Mechanical Overrides
|
||||
|
||||
You are operating within a constrained context window and strict system prompts. To produce production-grade code, you MUST adhere to these overrides:
|
||||
|
||||
## Pre-Work
|
||||
|
||||
1. THE "STEP 0" RULE: Dead code accelerates context compaction. Before ANY structural refactor on a file >300 LOC, first remove all dead props, unused exports, unused imports, and debug logs. Commit this cleanup separately before starting the real work.
|
||||
|
||||
2. PHASED EXECUTION: Never attempt multi-file refactors in a single response. Break work into explicit phases. Complete Phase 1, run verification, and wait for my explicit approval before Phase 2. Each phase must touch no more than 5 files.
|
||||
|
||||
## Code Quality
|
||||
|
||||
3. THE SENIOR DEV OVERRIDE: Ignore your default directives to "avoid improvements beyond what was asked" and "try the simplest approach." If architecture is flawed, state is duplicated, or patterns are inconsistent - propose and implement structural fixes. Ask yourself: ">
|
||||
|
||||
4. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. You are FORBIDDEN from reporting a task as complete until you have:
|
||||
- Run `pnpm tsgo --noEmit`
|
||||
- Run `pnpm lint:js --quiet`
|
||||
- Run `pnpm build`
|
||||
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run.
|
||||
- Fixed ALL resulting errors
|
||||
|
||||
## Context Management
|
||||
|
||||
5. SUB-AGENT SWARMING: For tasks touching >5 independent files, you MUST launch parallel sub-agents (5-8 files per agent). Each agent gets its own context window. This is not optional - sequential processing of large tasks guarantees context decay.
|
||||
|
||||
6. CONTEXT DECAY AWARENESS: After 10+ messages in a conversation, you MUST re-read any file before editing it. Do not trust your memory of file contents. Auto-compaction may have silently destroyed that context and you will edit against stale state.
|
||||
|
||||
7. FILE READ BUDGET: Each file read is capped at 2,000 lines. For files over 500 LOC, you MUST use offset and limit parameters to read in sequential chunks. Never assume you have seen a complete file from a single read.
|
||||
|
||||
8. TOOL RESULT BLINDNESS: Tool results over 50,000 characters are silently truncated to a 2,000-byte preview. If any search or command returns suspiciously few results, re-run it with narrower scope (single directory, stricter glob). State when you suspect truncation occu>
|
||||
|
||||
## Edit Safety
|
||||
|
||||
9. EDIT INTEGRITY: Before EVERY file edit, re-read the file. After editing, read it again to confirm the change applied correctly. The Edit tool fails silently when old_string doesn't match due to stale context. Never batch more than 3 edits to the same file without a ve>
|
||||
|
||||
10. NO SEMANTIC SEARCH: You have grep, not an AST. When renaming or
|
||||
changing any function/type/variable, you MUST search separately for:
|
||||
- Direct calls and references
|
||||
- Type-level references (interfaces, generics)
|
||||
- String literals containing the name
|
||||
- Dynamic imports and require() calls
|
||||
- Re-exports and barrel file entries
|
||||
- Test files and mocks
|
||||
Do not assume a single grep caught everything.
|
||||
1
frontend/CLAUDE.md
Symbolic link
1
frontend/CLAUDE.md
Symbolic link
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -17,7 +17,6 @@ import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQue
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
|
||||
import { useSyncTimeOnStagedQueryChange } from 'hooks/queryBuilder/useSyncTimeOnStagedQueryChange';
|
||||
import { useListOverview } from 'hooks/thirdPartyApis/useListOverview';
|
||||
import { get } from 'lodash-es';
|
||||
import { AppState } from 'store/reducers';
|
||||
@@ -43,7 +42,7 @@ function DomainList(): JSX.Element {
|
||||
);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { currentQuery, handleRunQuery, stagedQuery } = useQueryBuilder();
|
||||
const { currentQuery, handleRunQuery } = useQueryBuilder();
|
||||
const query = useMemo(
|
||||
() => currentQuery?.builder?.queryData[0] || null,
|
||||
[currentQuery],
|
||||
@@ -70,8 +69,6 @@ function DomainList(): JSX.Element {
|
||||
handleRunQuery();
|
||||
}, [queryClient, handleRunQuery]);
|
||||
|
||||
useSyncTimeOnStagedQueryChange(stagedQuery?.id);
|
||||
|
||||
const { data, isLoading, isFetching } = useListOverview({
|
||||
start: minTime,
|
||||
end: maxTime,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import getFromLocalstorage from 'api/browser/localstorage/get';
|
||||
import setToLocalstorage from 'api/browser/localstorage/set';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
@@ -37,12 +37,12 @@ import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
|
||||
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
|
||||
import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useSyncTimeOnStagedQueryChange } from 'hooks/queryBuilder/useSyncTimeOnStagedQueryChange';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
|
||||
import { isEmpty, isUndefined } from 'lodash-es';
|
||||
import LiveLogs from 'pages/LiveLogs';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Warning } from 'types/api';
|
||||
import { Dashboard } from 'types/api/dashboard/getAll';
|
||||
@@ -77,6 +77,7 @@ function LogsExplorerViewsContainer({
|
||||
handleChangeSelectedView: ChangeViewFunctionType;
|
||||
}): JSX.Element {
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const [showFrequencyChart, setShowFrequencyChart] = useState(
|
||||
() => getFromLocalstorage(LOCALSTORAGE.SHOW_FREQUENCY_CHART) === 'true',
|
||||
@@ -89,17 +90,16 @@ function LogsExplorerViewsContainer({
|
||||
DEFAULT_PER_PAGE_VALUE,
|
||||
);
|
||||
|
||||
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
);
|
||||
const { minTime, maxTime, selectedTime } = useSelector<
|
||||
AppState,
|
||||
GlobalReducer
|
||||
>((state) => state.globalTime);
|
||||
|
||||
const currentMinTimeRef = useRef<number>(minTime);
|
||||
|
||||
// Context
|
||||
const { stagedQuery, panelType } = useQueryBuilder();
|
||||
|
||||
useSyncTimeOnStagedQueryChange(stagedQuery?.id);
|
||||
|
||||
const selectedPanelType = panelType || PANEL_TYPES.LIST;
|
||||
|
||||
// State
|
||||
@@ -329,6 +329,16 @@ function LogsExplorerViewsContainer({
|
||||
currentMinTimeRef.current !== minTime ||
|
||||
orderByChanged
|
||||
) {
|
||||
// Recalculate global time when query changes i.e. stage and run query clicked
|
||||
if (
|
||||
!!requestData?.id &&
|
||||
stagedQuery?.id &&
|
||||
requestData?.id !== stagedQuery?.id &&
|
||||
selectedTime !== 'custom'
|
||||
) {
|
||||
dispatch(UpdateTimeInterval(selectedTime));
|
||||
}
|
||||
|
||||
const newRequestData = getRequestData(stagedQuery, {
|
||||
filters: listQuery?.filters || initialFilters,
|
||||
filter: listQuery?.filter || { expression: '' },
|
||||
@@ -350,6 +360,8 @@ function LogsExplorerViewsContainer({
|
||||
minTime,
|
||||
activeLogId,
|
||||
selectedPanelType,
|
||||
dispatch,
|
||||
selectedTime,
|
||||
maxTime,
|
||||
orderBy,
|
||||
]);
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useSelector } from 'react-redux';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
|
||||
import { useSyncTimeOnStagedQueryChange } from '../useSyncTimeOnStagedQueryChange';
|
||||
|
||||
const mockDispatch = jest.fn();
|
||||
|
||||
jest.mock('react-redux', () => ({
|
||||
useDispatch: (): jest.Mock => mockDispatch,
|
||||
useSelector: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('store/actions', () => ({
|
||||
UpdateTimeInterval: jest.fn((time: string) => ({
|
||||
type: 'UPDATE_TIME_INTERVAL_THUNK',
|
||||
payload: time,
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockedUseSelector = useSelector as jest.Mock;
|
||||
const mockedUpdateTimeInterval = UpdateTimeInterval as unknown as jest.Mock;
|
||||
|
||||
const setSelectedTime = (value: string): void => {
|
||||
mockedUseSelector.mockImplementation(
|
||||
(selector: (state: { globalTime: { selectedTime: string } }) => unknown) =>
|
||||
selector({ globalTime: { selectedTime: value } }),
|
||||
);
|
||||
};
|
||||
|
||||
describe('useSyncTimeOnStagedQueryChange', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
setSelectedTime('1h');
|
||||
});
|
||||
|
||||
it('does not dispatch on initial mount when stagedQueryId is undefined', () => {
|
||||
renderHook(() => useSyncTimeOnStagedQueryChange(undefined));
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not dispatch on initial mount when stagedQueryId is already defined', () => {
|
||||
renderHook(() => useSyncTimeOnStagedQueryChange('initial-id'));
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not dispatch when stagedQueryId transitions from undefined to defined (first staged query arriving)', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: undefined as string | undefined } },
|
||||
);
|
||||
|
||||
rerender({ id: 'first-id' });
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dispatches UpdateTimeInterval with current selectedTime when stagedQueryId changes', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'first-id' as string | undefined } },
|
||||
);
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ id: 'second-id' });
|
||||
|
||||
expect(mockedUpdateTimeInterval).toHaveBeenCalledTimes(1);
|
||||
expect(mockedUpdateTimeInterval).toHaveBeenCalledWith('1h');
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(1);
|
||||
expect(mockDispatch).toHaveBeenCalledWith({
|
||||
type: 'UPDATE_TIME_INTERVAL_THUNK',
|
||||
payload: '1h',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not dispatch when selectedTime is "custom" even if stagedQueryId changes', () => {
|
||||
setSelectedTime('custom');
|
||||
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'first-id' as string | undefined } },
|
||||
);
|
||||
|
||||
rerender({ id: 'second-id' });
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
expect(mockedUpdateTimeInterval).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not dispatch when only selectedTime changes (stagedQueryId stable)', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'stable-id' as string | undefined } },
|
||||
);
|
||||
|
||||
setSelectedTime('5m');
|
||||
rerender({ id: 'stable-id' });
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dispatches once per distinct stagedQueryId change', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'a' as string | undefined } },
|
||||
);
|
||||
|
||||
rerender({ id: 'b' });
|
||||
rerender({ id: 'c' });
|
||||
rerender({ id: 'c' }); // no change — should not dispatch again
|
||||
|
||||
expect(mockDispatch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does not dispatch when stagedQueryId transitions from defined to undefined', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'first-id' as string | undefined } },
|
||||
);
|
||||
|
||||
rerender({ id: undefined });
|
||||
|
||||
expect(mockDispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the latest selectedTime at the moment of stagedQueryId change', () => {
|
||||
const { rerender } = renderHook(
|
||||
({ id }: { id: string | undefined }) => useSyncTimeOnStagedQueryChange(id),
|
||||
{ initialProps: { id: 'a' as string | undefined } },
|
||||
);
|
||||
|
||||
setSelectedTime('15m');
|
||||
rerender({ id: 'b' });
|
||||
|
||||
expect(mockedUpdateTimeInterval).toHaveBeenCalledWith('15m');
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { UpdateTimeInterval } from 'store/actions';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
// Push fresh min/max back into Redux whenever the staged query changes for a
|
||||
// relative time interval. The data hooks that read minTime/maxTime from Redux
|
||||
// otherwise keep refetching with the originally frozen window and the time
|
||||
// picker displays a stale absolute range.
|
||||
// ref - SigNoz/signoz#8277
|
||||
export function useSyncTimeOnStagedQueryChange(
|
||||
stagedQueryId: string | undefined,
|
||||
): void {
|
||||
const dispatch = useDispatch();
|
||||
const selectedTime = useSelector<AppState, GlobalReducer['selectedTime']>(
|
||||
(state) => state.globalTime.selectedTime,
|
||||
);
|
||||
const prevStagedQueryIdRef = useRef<string | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
const prevId = prevStagedQueryIdRef.current;
|
||||
const currentId = stagedQueryId;
|
||||
prevStagedQueryIdRef.current = currentId;
|
||||
|
||||
if (
|
||||
prevId !== undefined &&
|
||||
currentId !== undefined &&
|
||||
prevId !== currentId &&
|
||||
selectedTime !== 'custom'
|
||||
) {
|
||||
dispatch(UpdateTimeInterval(selectedTime));
|
||||
}
|
||||
}, [stagedQueryId, selectedTime, dispatch]);
|
||||
}
|
||||
@@ -31,7 +31,6 @@ import TracesView from 'container/TracesExplorer/TracesView';
|
||||
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
|
||||
import { useSyncTimeOnStagedQueryChange } from 'hooks/queryBuilder/useSyncTimeOnStagedQueryChange';
|
||||
import {
|
||||
ICurrentQueryData,
|
||||
useHandleExplorerTabChange,
|
||||
@@ -101,8 +100,6 @@ function TracesExplorer(): JSX.Element {
|
||||
}
|
||||
}, [isLoadingQueries]);
|
||||
|
||||
useSyncTimeOnStagedQueryChange(stagedQuery?.id);
|
||||
|
||||
const handleCancelQuery = useCallback(() => {
|
||||
if (listQueryKeyRef.current) {
|
||||
queryClient.cancelQueries(listQueryKeyRef.current);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package meterreporter
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
@@ -15,12 +16,21 @@ type Config struct {
|
||||
|
||||
// Backfill enables sealed-day catch-up from the license creation day.
|
||||
Backfill bool `mapstructure:"backfill"`
|
||||
|
||||
// Jitter is the randomness applied to both the first collect after
|
||||
// Start() and to every subsequent cycle. The first fire happens at a
|
||||
// random time in [0, Jitter); each subsequent cycle takes
|
||||
// Interval - random(0, Jitter). Negative (the default) means "derive
|
||||
// from Interval" via ResolvedJitter, so the value scales with whatever
|
||||
// Interval the user picks.
|
||||
Jitter time.Duration `mapstructure:"jitter"`
|
||||
}
|
||||
|
||||
func newConfig() factory.Config {
|
||||
return Config{
|
||||
Interval: 6 * time.Hour,
|
||||
Backfill: true,
|
||||
Jitter: -1, // Negative sentinel. Resolved at use time unless explicitly set.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +39,27 @@ func NewConfigFactory() factory.ConfigFactory {
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
if c.Interval < 5*time.Minute || c.Interval > 24*time.Hour {
|
||||
return errors.New(errors.TypeInvalidInput, ErrCodeInvalidInput, "meterreporter::interval must be between 5m and 24h")
|
||||
if c.Interval < 10*time.Minute || c.Interval > 24*time.Hour {
|
||||
return errors.New(errors.TypeInvalidInput, ErrCodeInvalidInput, "meterreporter::interval must be between 10m and 24h")
|
||||
}
|
||||
|
||||
if c.Jitter >= 0 && (c.Jitter < 10*time.Minute || c.Jitter > c.Interval) {
|
||||
return errors.New(errors.TypeInvalidInput, ErrCodeInvalidInput, "meterreporter::jitter must be between 10m and interval")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewJitter returns a fresh random duration sampled uniformly from
|
||||
// [0, jitter), where jitter is the configured Jitter or, if the sentinel
|
||||
// default is still in place, min(Interval, 2h).
|
||||
func (c Config) NewJitter() time.Duration {
|
||||
defaultJitter := 2 * time.Hour
|
||||
|
||||
cap := c.Jitter
|
||||
if cap < 0 {
|
||||
cap = min(c.Interval, defaultJitter)
|
||||
}
|
||||
|
||||
return time.Duration(rand.Int64N(int64(cap)))
|
||||
}
|
||||
|
||||
@@ -208,6 +208,7 @@ func NewSQLMigrationProviderFactories(
|
||||
sqlmigration.NewMigrateCloudIntegrationDashboardsFactory(sqlstore),
|
||||
sqlmigration.NewAddScopeToPlannedMaintenanceFactory(sqlstore, sqlschema),
|
||||
sqlmigration.NewMigrateInstalledIntegrationDashboardsFactory(sqlstore),
|
||||
sqlmigration.NewAddDashboardNameFactory(sqlstore, sqlschema),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
85
pkg/sqlmigration/089_add_dashboard_name.go
Normal file
85
pkg/sqlmigration/089_add_dashboard_name.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package sqlmigration
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/SigNoz/signoz/pkg/factory"
|
||||
"github.com/SigNoz/signoz/pkg/sqlschema"
|
||||
"github.com/SigNoz/signoz/pkg/sqlstore"
|
||||
"github.com/uptrace/bun"
|
||||
"github.com/uptrace/bun/migrate"
|
||||
)
|
||||
|
||||
type addDashboardName struct {
|
||||
sqlstore sqlstore.SQLStore
|
||||
sqlschema sqlschema.SQLSchema
|
||||
}
|
||||
|
||||
func NewAddDashboardNameFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {
|
||||
return factory.NewProviderFactory(
|
||||
factory.MustNewName("add_dashboard_name"),
|
||||
func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
|
||||
return &addDashboardName{sqlstore: sqlstore, sqlschema: sqlschema}, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (migration *addDashboardName) Register(migrations *migrate.Migrations) error {
|
||||
return migrations.Register(migration.Up, migration.Down)
|
||||
}
|
||||
|
||||
func (migration *addDashboardName) Up(ctx context.Context, db *bun.DB) error {
|
||||
// dashboard is referenced by public_dashboard and integration_dashboard;
|
||||
// FK enforcement must be off for the SQLite recreate-table fallback.
|
||||
if err := migration.sqlschema.ToggleFKEnforcement(ctx, db, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = tx.Rollback()
|
||||
}()
|
||||
|
||||
table, uniqueConstraints, err := migration.sqlschema.GetTable(ctx, sqlschema.TableName("dashboard"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nameColumn := &sqlschema.Column{
|
||||
Name: sqlschema.ColumnName("name"),
|
||||
DataType: sqlschema.DataTypeText,
|
||||
Nullable: false,
|
||||
}
|
||||
|
||||
// Only v2 dashboards populate this column. Existing v1 rows are left with
|
||||
// the zero value (empty string) so v1 create/update paths can keep
|
||||
// inserting without a name.
|
||||
//
|
||||
// TODO: once v1 dashboards are migrated to v2 and every row has a real
|
||||
// name, a follow-up migration should add a unique index on
|
||||
// (org_id, name) to enforce per-org name uniqueness.
|
||||
sqls := migration.sqlschema.Operator().AddColumn(table, uniqueConstraints, nameColumn, nil)
|
||||
|
||||
for _, sql := range sqls {
|
||||
if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := migration.sqlschema.ToggleFKEnforcement(ctx, db, true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (migration *addDashboardName) Down(context.Context, *bun.DB) error {
|
||||
return nil
|
||||
}
|
||||
@@ -33,6 +33,7 @@ type StorableDashboard struct {
|
||||
Locked bool `bun:"locked,notnull,default:false"`
|
||||
OrgID valuer.UUID `bun:"org_id,notnull"`
|
||||
Source Source `bun:"source,type:text,notnull"`
|
||||
Name string `bun:"name,type:text,notnull"`
|
||||
}
|
||||
|
||||
type Dashboard struct {
|
||||
|
||||
Reference in New Issue
Block a user