Skip to content

Database diagrams editor that allows you to visualize and design your DB with a single query.

fix: rels dbml diffs (#1037)

Guy Ben-Aharonc39b699e93b9
diff --git a/src/context/diff-context/diff-context.tsx b/src/context/diff-context/diff-context.tsx
index 3ea40afd..62c831bc 100644
--- a/src/context/diff-context/diff-context.tsx
+++ b/src/context/diff-context/diff-context.tsx
@@ -35,6 +35,7 @@ export interface DiffContext {
diffMap: DiffMap;
hasDiff: boolean;
isSummaryOnly: boolean;
+ relationshipIdMap: Map<string, string>;
calculateDiff: ({
diagram,
@@ -114,6 +115,11 @@ export interface DiffContext {
}) => { old: boolean; new: boolean } | null;
// relationship diff
+ checkIfRelationshipHasChange: ({
+ relationshipId,
+ }: {
+ relationshipId: string;
+ }) => boolean;
checkIfNewRelationship: ({
relationshipId,
}: {
@@ -124,6 +130,11 @@ export interface DiffContext {
}: {
relationshipId: string;
}) => boolean;
+ getRelationshipNewName: ({
+ relationshipId,
+ }: {
+ relationshipId: string;
+ }) => { old: string; new: string } | null;
// area diff
checkIfNewArea: ({ areaId }: { areaId: string }) => boolean;
diff --git a/src/context/diff-context/diff-provider.tsx b/src/context/diff-context/diff-provider.tsx
index c90e3449..dd596155 100644
--- a/src/context/diff-context/diff-provider.tsx
+++ b/src/context/diff-context/diff-provider.tsx
@@ -33,6 +33,12 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
const [fieldsChanged, setFieldsChanged] = React.useState<
Map<string, boolean>
>(new Map<string, boolean>());
+ const [relationshipsChanged, setRelationshipsChanged] = React.useState<
+ Map<string, boolean>
+ >(new Map<string, boolean>());
+ const [relationshipIdMap, setRelationshipIdMap] = React.useState<
+ Map<string, string>
+ >(new Map<string, string>());
const [isSummaryOnly, setIsSummaryOnly] = React.useState<boolean>(false);
const events = useEventEmitter<DiffEvent>();
@@ -164,11 +170,15 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
diffMap: newDiffs,
changedTables: newChangedTables,
changedFields: newChangedFields,
+ changedRelationships: newChangedRelationships,
+ relationshipIdMap: newRelationshipIdMap,
} = generateDiff({ diagram, newDiagram: newDiagramArg });
setDiffMap(newDiffs);
setTablesChanged(newChangedTables);
setFieldsChanged(newChangedFields);
+ setRelationshipsChanged(newChangedRelationships);
+ setRelationshipIdMap(newRelationshipIdMap);
setNewDiagram(newDiagramArg);
setOriginalDiagram(diagram);
setIsSummaryOnly(options?.summaryOnly ?? false);
@@ -502,6 +512,62 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
[diffMap]
);
+ const checkIfRelationshipHasChange = useCallback<
+ DiffContext['checkIfRelationshipHasChange']
+ >(
+ ({ relationshipId }) =>
+ relationshipsChanged.get(relationshipId) ?? false,
+ [relationshipsChanged]
+ );
+
+ const getRelationshipNewName = useCallback<
+ DiffContext['getRelationshipNewName']
+ >(
+ ({ relationshipId }) => {
+ // Try with the given ID first
+ const relationshipNameKey = getDiffMapKey({
+ diffObject: 'relationship',
+ objectId: relationshipId,
+ attribute: 'name',
+ });
+
+ if (diffMap.has(relationshipNameKey)) {
+ const diff = diffMap.get(relationshipNameKey);
+
+ if (diff?.type === 'changed') {
+ return {
+ new: diff.newValue as string,
+ old: diff.oldValue as string,
+ };
+ }
+ }
+
+ // If not found, try with the mapped ID (old <-> new mapping)
+ const mappedId = relationshipIdMap.get(relationshipId);
+ if (mappedId) {
+ const mappedKey = getDiffMapKey({
+ diffObject: 'relationship',
+ objectId: mappedId,
+ attribute: 'name',
+ });
+
+ if (diffMap.has(mappedKey)) {
+ const diff = diffMap.get(mappedKey);
+
+ if (diff?.type === 'changed') {
+ return {
+ new: diff.newValue as string,
+ old: diff.oldValue as string,
+ };
+ }
+ }
+ }
+
+ return null;
+ },
+ [diffMap, relationshipIdMap]
+ );
+
const checkIfNewRelationship = useCallback<
DiffContext['checkIfNewRelationship']
>(
@@ -568,6 +634,8 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
setDiffMap(new Map<string, ChartDBDiff>());
setTablesChanged(new Map<string, boolean>());
setFieldsChanged(new Map<string, boolean>());
+ setRelationshipsChanged(new Map<string, boolean>());
+ setRelationshipIdMap(new Map<string, string>());
setNewDiagram(null);
setOriginalDiagram(null);
setIsSummaryOnly(false);
@@ -606,8 +674,11 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
getFieldNewIsArray,
// relationship diff
+ checkIfRelationshipHasChange,
checkIfNewRelationship,
checkIfRelationshipRemoved,
+ getRelationshipNewName,
+ relationshipIdMap,
// area diff
checkIfNewArea,
diff --git a/src/lib/domain/diff/diff-check/__tests__/diff-check.test.ts b/src/lib/domain/diff/diff-check/__tests__/diff-check.test.ts
index 3eb5bfed..408fca34 100644
--- a/src/lib/domain/diff/diff-check/__tests__/diff-check.test.ts
+++ b/src/lib/domain/diff/diff-check/__tests__/diff-check.test.ts
@@ -13,6 +13,7 @@ import type { FieldDiffChanged } from '../../field-diff';
import type { AreaDiffChanged } from '../../area-diff';
import type { NoteDiffChanged } from '../../note-diff';
import type { IndexDiffChanged } from '../../index-diff';
+import type { RelationshipDiffChanged } from '../../relationship-diff';
// Helper function to create a mock diagram
function createMockDiagram(overrides?: Partial<Diagram>): Diagram {
@@ -61,11 +62,14 @@ function createMockRelationship(
): DBRelationship {
return {
id: 'rel-1',
+ name: 'fk_default',
sourceTableId: 'table-1',
targetTableId: 'table-2',
sourceFieldId: 'field-1',
targetFieldId: 'field-2',
- type: 'one-to-many',
+ sourceCardinality: 'one',
+ targetCardinality: 'many',
+ createdAt: Date.now(),
...overrides,
} as DBRelationship;
}
@@ -839,6 +843,7 @@ describe('generateDiff', () => {
const diff = result.diffMap.get('relationship-rel-1');
expect(diff).toBeDefined();
expect(diff?.type).toBe('added');
+ expect(result.changedRelationships.has('rel-1')).toBe(true);
});
it('should detect removed relationships', () => {
@@ -856,6 +861,565 @@ describe('generateDiff', () => {
const diff = result.diffMap.get('relationship-rel-1');
expect(diff).toBeDefined();
expect(diff?.type).toBe('removed');
+ expect(result.changedRelationships.has('rel-1')).toBe(true);
+ });
+
+ it('should detect relationship name changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ name: 'fk_old_name' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ name: 'fk_new_name' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-name-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe('name');
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe(
+ 'fk_old_name'
+ );
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe(
+ 'fk_new_name'
+ );
+ expect(result.changedRelationships.has('rel-1')).toBe(true);
+ });
+
+ it('should detect relationship sourceCardinality changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceCardinality: 'one' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceCardinality: 'many' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get(
+ 'relationship-sourceCardinality-rel-1'
+ );
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'sourceCardinality'
+ );
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe('one');
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe('many');
+ });
+
+ it('should detect relationship targetCardinality changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetCardinality: 'many' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetCardinality: 'one' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get(
+ 'relationship-targetCardinality-rel-1'
+ );
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'targetCardinality'
+ );
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe('many');
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe('one');
+ });
+
+ it('should detect multiple relationship attribute changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_old',
+ sourceCardinality: 'one',
+ targetCardinality: 'many',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_new',
+ sourceCardinality: 'many',
+ targetCardinality: 'one',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(3);
+ expect(result.diffMap.has('relationship-name-rel-1')).toBe(true);
+ expect(
+ result.diffMap.has('relationship-sourceCardinality-rel-1')
+ ).toBe(true);
+ expect(
+ result.diffMap.has('relationship-targetCardinality-rel-1')
+ ).toBe(true);
+ });
+
+ it('should only check specified relationship attributes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_old',
+ sourceCardinality: 'one',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_new',
+ sourceCardinality: 'many',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ options: {
+ attributes: {
+ relationships: ['name'], // Only check name changes
+ },
+ },
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ expect(result.diffMap.has('relationship-name-rel-1')).toBe(true);
+ expect(
+ result.diffMap.has('relationship-sourceCardinality-rel-1')
+ ).toBe(false);
+ });
+
+ it('should only check specified relationship change types', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ id: 'rel-1', name: 'fk_old' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ // Use different sourceFieldId to ensure it's a truly different relationship
+ createMockRelationship({
+ id: 'rel-2',
+ name: 'fk_new',
+ sourceFieldId: 'field-3',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ options: {
+ changeTypes: {
+ relationships: ['added'], // Only check for added relationships
+ },
+ },
+ });
+
+ // Should only detect added relationship (rel-2)
+ const addedRelationships = Array.from(
+ result.diffMap.values()
+ ).filter(
+ (diff) =>
+ diff.type === 'added' && diff.object === 'relationship'
+ );
+ expect(addedRelationships.length).toBe(1);
+
+ // Should not detect removed relationship (rel-1)
+ const removedRelationships = Array.from(
+ result.diffMap.values()
+ ).filter(
+ (diff) =>
+ diff.type === 'removed' && diff.object === 'relationship'
+ );
+ expect(removedRelationships.length).toBe(0);
+ });
+
+ it('should use custom relationship matcher', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ id: 'rel-1',
+ name: 'fk_users_orders',
+ sourceCardinality: 'one',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ id: 'rel-2',
+ name: 'fk_users_orders',
+ sourceCardinality: 'many',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ options: {
+ matchers: {
+ relationship: (rel, rels) =>
+ rels.find((r) => r.name === rel.name),
+ },
+ },
+ });
+
+ // With name-based matching, rel-1 should match rel-2 by name
+ // and detect the sourceCardinality change
+ const cardinalityChange = result.diffMap.get(
+ 'relationship-sourceCardinality-rel-1'
+ );
+ expect(cardinalityChange).toBeDefined();
+ expect(cardinalityChange?.type).toBe('changed');
+ expect(
+ (cardinalityChange as RelationshipDiffChanged)?.attribute
+ ).toBe('sourceCardinality');
+ expect(
+ (cardinalityChange as RelationshipDiffChanged)?.oldValue
+ ).toBe('one');
+ expect(
+ (cardinalityChange as RelationshipDiffChanged)?.newValue
+ ).toBe('many');
+ });
+
+ it('should not detect changes when relationships are unchanged', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_users_orders',
+ sourceCardinality: 'one',
+ targetCardinality: 'many',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_users_orders',
+ sourceCardinality: 'one',
+ targetCardinality: 'many',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(0);
+ expect(result.changedRelationships.size).toBe(0);
+ });
+
+ it('should detect relationship sourceSchema changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceSchema: 'public' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceSchema: 'private' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-sourceSchema-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'sourceSchema'
+ );
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe('public');
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe('private');
+ });
+
+ it('should detect relationship targetSchema changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetSchema: 'schema_a' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetSchema: 'schema_b' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-targetSchema-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'targetSchema'
+ );
+ });
+
+ it('should detect relationship sourceTableId changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceTableId: 'table-1' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceTableId: 'table-3' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-sourceTableId-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'sourceTableId'
+ );
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe('table-1');
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe('table-3');
+ });
+
+ it('should detect relationship targetTableId changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetTableId: 'table-2' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetTableId: 'table-4' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-targetTableId-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'targetTableId'
+ );
+ });
+
+ it('should detect relationship sourceFieldId changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceFieldId: 'field-1' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ sourceFieldId: 'field-5' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-sourceFieldId-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'sourceFieldId'
+ );
+ expect((diff as RelationshipDiffChanged)?.oldValue).toBe('field-1');
+ expect((diff as RelationshipDiffChanged)?.newValue).toBe('field-5');
+ });
+
+ it('should detect relationship targetFieldId changes', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetFieldId: 'field-2' }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({ targetFieldId: 'field-6' }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(1);
+ const diff = result.diffMap.get('relationship-targetFieldId-rel-1');
+ expect(diff).toBeDefined();
+ expect(diff?.type).toBe('changed');
+ expect((diff as RelationshipDiffChanged)?.attribute).toBe(
+ 'targetFieldId'
+ );
+ });
+
+ it('should detect all relationship attribute changes simultaneously', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_old',
+ sourceSchema: 'public',
+ sourceTableId: 'table-1',
+ targetSchema: 'public',
+ targetTableId: 'table-2',
+ sourceFieldId: 'field-1',
+ targetFieldId: 'field-2',
+ sourceCardinality: 'one',
+ targetCardinality: 'many',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_new',
+ sourceSchema: 'private',
+ sourceTableId: 'table-3',
+ targetSchema: 'private',
+ targetTableId: 'table-4',
+ sourceFieldId: 'field-5',
+ targetFieldId: 'field-6',
+ sourceCardinality: 'many',
+ targetCardinality: 'one',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ });
+
+ expect(result.diffMap.size).toBe(9);
+ expect(result.diffMap.has('relationship-name-rel-1')).toBe(true);
+ expect(result.diffMap.has('relationship-sourceSchema-rel-1')).toBe(
+ true
+ );
+ expect(result.diffMap.has('relationship-sourceTableId-rel-1')).toBe(
+ true
+ );
+ expect(result.diffMap.has('relationship-targetSchema-rel-1')).toBe(
+ true
+ );
+ expect(result.diffMap.has('relationship-targetTableId-rel-1')).toBe(
+ true
+ );
+ expect(result.diffMap.has('relationship-sourceFieldId-rel-1')).toBe(
+ true
+ );
+ expect(result.diffMap.has('relationship-targetFieldId-rel-1')).toBe(
+ true
+ );
+ expect(
+ result.diffMap.has('relationship-sourceCardinality-rel-1')
+ ).toBe(true);
+ expect(
+ result.diffMap.has('relationship-targetCardinality-rel-1')
+ ).toBe(true);
+ });
+
+ it('should filter relationship attributes correctly', () => {
+ const oldDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_old',
+ sourceSchema: 'public',
+ sourceTableId: 'table-1',
+ sourceCardinality: 'one',
+ }),
+ ],
+ });
+ const newDiagram = createMockDiagram({
+ relationships: [
+ createMockRelationship({
+ name: 'fk_new',
+ sourceSchema: 'private',
+ sourceTableId: 'table-3',
+ sourceCardinality: 'many',
+ }),
+ ],
+ });
+
+ const result = generateDiff({
+ diagram: oldDiagram,
+ newDiagram,
+ options: {
+ attributes: {
+ relationships: ['name', 'sourceCardinality'], // Only check these
+ },
+ },
+ });
+
+ expect(result.diffMap.size).toBe(2);
+ expect(result.diffMap.has('relationship-name-rel-1')).toBe(true);
+ expect(
+ result.diffMap.has('relationship-sourceCardinality-rel-1')
+ ).toBe(true);
+ // Should not detect sourceSchema or sourceTableId changes
+ expect(result.diffMap.has('relationship-sourceSchema-rel-1')).toBe(
+ false
+ );
+ expect(result.diffMap.has('relationship-sourceTableId-rel-1')).toBe(
+ false
+ );
});
});
diff --git a/src/lib/domain/diff/diff-check/diff-check.ts b/src/lib/domain/diff/diff-check/diff-check.ts
index 6b519b25..994ff00a 100644
--- a/src/lib/domain/diff/diff-check/diff-check.ts
+++ b/src/lib/domain/diff/diff-check/diff-check.ts
@@ -17,7 +17,10 @@ import type { TableDiff, TableDiffAttribute } from '../table-diff';
import type { AreaDiff, AreaDiffAttribute } from '../area-diff';
import type { NoteDiff, NoteDiffAttribute } from '../note-diff';
import type { IndexDiff, IndexDiffAttribute } from '../index-diff';
-import type { RelationshipDiff } from '../relationship-diff';
+import type {
+ RelationshipDiff,
+ RelationshipDiffAttribute,
+} from '../relationship-diff';
import { areBooleansEqual } from '@/lib/utils';
import type { DatabaseType } from '../../database-type';
@@ -119,6 +122,7 @@ export interface GenerateDiffOptions {
tables?: TableDiffAttribute[];
fields?: FieldDiffAttribute[];
indexes?: IndexDiffAttribute[];
+ relationships?: RelationshipDiffAttribute[];
areas?: AreaDiffAttribute[];
notes?: NoteDiffAttribute[];
};
@@ -126,6 +130,7 @@ export interface GenerateDiffOptions {
changedTablesAttributes?: TableDiffAttribute[];
changedFieldsAttributes?: FieldDiffAttribute[];
changedIndexesAttributes?: IndexDiffAttribute[];
+ changedRelationshipsAttributes?: RelationshipDiffAttribute[];
changedAreasAttributes?: AreaDiffAttribute[];
changedNotesAttributes?: NoteDiffAttribute[];
};
@@ -163,8 +168,10 @@ export function generateDiff({
changedTables: Map<string, boolean>;
changedFields: Map<string, boolean>;
changedIndexes: Map<string, boolean>;
+ changedRelationships: Map<string, boolean>;
changedAreas: Map<string, boolean>;
changedNotes: Map<string, boolean>;
+ relationshipIdMap: Map<string, string>;
} {
// Merge with default options
const mergedOptions: GenerateDiffOptions = {
@@ -184,8 +191,10 @@ export function generateDiff({
const changedTables = new Map<string, boolean>();
const changedFields = new Map<string, boolean>();
const changedIndexes = new Map<string, boolean>();
+ const changedRelationships = new Map<string, boolean>();
const changedAreas = new Map<string, boolean>();
const changedNotes = new Map<string, boolean>();
+ const relationshipIdMap = new Map<string, string>();
// Use provided matchers or default ones
const tableMatcher = mergedOptions.matchers?.table ?? defaultTableMatcher;
@@ -238,6 +247,11 @@ export function generateDiff({
diagram,
newDiagram,
diffMap: newDiffs,
+ changedRelationships,
+ relationshipIdMap,
+ attributes: mergedOptions.attributes?.relationships,
+ changedRelationshipsAttributes:
+ mergedOptions.changedMaps?.changedRelationshipsAttributes,
changeTypes: mergedOptions.changeTypes?.relationships,
relationshipMatcher,
});
@@ -278,8 +292,10 @@ export function generateDiff({
changedTables,
changedFields,
changedIndexes,
+ changedRelationships,
changedAreas,
changedNotes,
+ relationshipIdMap,
};
}
@@ -1101,12 +1117,20 @@ function compareRelationships({
diagram,
newDiagram,
diffMap,
+ changedRelationships,
+ relationshipIdMap,
+ attributes,
+ changedRelationshipsAttributes,
changeTypes,
relationshipMatcher,
}: {
diagram: Diagram;
newDiagram: Diagram;
diffMap: DiffMap;
+ changedRelationships: Map<string, boolean>;
+ relationshipIdMap: Map<string, string>;
+ attributes?: RelationshipDiffAttribute[];
+ changedRelationshipsAttributes?: RelationshipDiffAttribute[];
changeTypes?: RelationshipDiff['type'][];
relationshipMatcher: (
relationship: DBRelationship,
@@ -1119,7 +1143,7 @@ function compareRelationships({
}
// If changeTypes is undefined, check all types
- const typesToCheck = changeTypes ?? ['added', 'removed'];
+ const typesToCheck = changeTypes ?? ['added', 'removed', 'changed'];
const oldRelationships = diagram.relationships || [];
const newRelationships = newDiagram.relationships || [];
@@ -1138,6 +1162,7 @@ function compareRelationships({
newRelationship,
}
);
+ changedRelationships.set(newRelationship.id, true);
}
}
}
@@ -1157,9 +1182,164 @@ function compareRelationships({
relationshipId: oldRelationship.id,
}
);
+ changedRelationships.set(oldRelationship.id, true);
}
}
}
+
+ // Check for relationship changes
+ if (typesToCheck.includes('changed')) {
+ for (const oldRelationship of oldRelationships) {
+ const newRelationship = relationshipMatcher(
+ oldRelationship,
+ newRelationships
+ );
+ if (!newRelationship) continue;
+
+ compareRelationshipProperties({
+ oldRelationship,
+ newRelationship,
+ diffMap,
+ changedRelationships,
+ relationshipIdMap,
+ attributes,
+ changedRelationshipsAttributes,
+ });
+ }
+ }
+}
+
+// Compare relationship properties
+function compareRelationshipProperties({
+ oldRelationship,
+ newRelationship,
+ diffMap,
+ changedRelationships,
+ relationshipIdMap,
+ attributes,
+ changedRelationshipsAttributes,
+}: {
+ oldRelationship: DBRelationship;
+ newRelationship: DBRelationship;
+ diffMap: DiffMap;
+ changedRelationships: Map<string, boolean>;
+ relationshipIdMap: Map<string, string>;
+ attributes?: RelationshipDiffAttribute[];
+ changedRelationshipsAttributes?: RelationshipDiffAttribute[];
+}) {
+ // If attributes are specified, only check those attributes
+ const attributesToCheck: RelationshipDiffAttribute[] = attributes ?? [
+ 'name',
+ 'sourceSchema',
+ 'sourceTableId',
+ 'targetSchema',
+ 'targetTableId',
+ 'sourceFieldId',
+ 'targetFieldId',
+ 'sourceCardinality',
+ 'targetCardinality',
+ ];
+
+ const changedAttributes: RelationshipDiffAttribute[] = [];
+
+ if (
+ attributesToCheck.includes('name') &&
+ oldRelationship.name !== newRelationship.name
+ ) {
+ changedAttributes.push('name');
+ }
+
+ if (
+ attributesToCheck.includes('sourceSchema') &&
+ oldRelationship.sourceSchema !== newRelationship.sourceSchema
+ ) {
+ changedAttributes.push('sourceSchema');
+ }
+
+ if (
+ attributesToCheck.includes('sourceTableId') &&
+ oldRelationship.sourceTableId !== newRelationship.sourceTableId
+ ) {
+ changedAttributes.push('sourceTableId');
+ }
+
+ if (
+ attributesToCheck.includes('targetSchema') &&
+ oldRelationship.targetSchema !== newRelationship.targetSchema
+ ) {
+ changedAttributes.push('targetSchema');
+ }
+
+ if (
+ attributesToCheck.includes('targetTableId') &&
+ oldRelationship.targetTableId !== newRelationship.targetTableId
+ ) {
+ changedAttributes.push('targetTableId');
+ }
+
+ if (
+ attributesToCheck.includes('sourceFieldId') &&
+ oldRelationship.sourceFieldId !== newRelationship.sourceFieldId
+ ) {
+ changedAttributes.push('sourceFieldId');
+ }
+
+ if (
+ attributesToCheck.includes('targetFieldId') &&
+ oldRelationship.targetFieldId !== newRelationship.targetFieldId
+ ) {
+ changedAttributes.push('targetFieldId');
+ }
+
+ if (
+ attributesToCheck.includes('sourceCardinality') &&
+ oldRelationship.sourceCardinality !== newRelationship.sourceCardinality
+ ) {
+ changedAttributes.push('sourceCardinality');
+ }
+
+ if (
+ attributesToCheck.includes('targetCardinality') &&
+ oldRelationship.targetCardinality !== newRelationship.targetCardinality
+ ) {
+ changedAttributes.push('targetCardinality');
+ }
+
+ if (changedAttributes.length > 0) {
+ // Track which attributes should trigger adding to changed maps
+ const attributesThatTriggerChange = changedAttributes.filter((attr) =>
+ shouldAddToChangedMap(attr, changedRelationshipsAttributes)
+ );
+
+ for (const attribute of changedAttributes) {
+ diffMap.set(
+ getDiffMapKey({
+ diffObject: 'relationship',
+ objectId: oldRelationship.id,
+ attribute,
+ }),
+ {
+ object: 'relationship',
+ type: 'changed',
+ relationshipId: oldRelationship.id,
+ newRelationshipId: newRelationship.id,
+ attribute,
+ oldValue: oldRelationship[attribute],
+ newValue: newRelationship[attribute],
+ }
+ );
+ }
+
+ // Only add to changed maps if at least one attribute should trigger a change
+ if (attributesThatTriggerChange.length > 0) {
+ changedRelationships.set(oldRelationship.id, true);
+ changedRelationships.set(newRelationship.id, true);
+
+ // Store bidirectional mapping between old and new IDs
+ relationshipIdMap.set(oldRelationship.id, newRelationship.id);
+ relationshipIdMap.set(newRelationship.id, oldRelationship.id);
+ }
+ }
}
// Compare areas between diagrams
@@ -1677,7 +1857,35 @@ const defaultRelationshipMatcher = (
relationship: DBRelationship,
relationships: DBRelationship[]
): DBRelationship | undefined => {
- return relationships.find((r) => r.id === relationship.id);
+ // Priority 1: Match by ID
+ const byId = relationships.find((r) => r.id === relationship.id);
+ if (byId) {
+ return byId;
+ }
+
+ // Priority 2: Match by name (only if unique match)
+ if (relationship.name) {
+ const byName = relationships.filter(
+ (r) => r.name === relationship.name
+ );
+ if (byName.length === 1) {
+ return byName[0];
+ }
+ }
+
+ // Priority 3: Match by structural identity (source/target table and field IDs)
+ const byStructure = relationships.filter(
+ (r) =>
+ r.sourceTableId === relationship.sourceTableId &&
+ r.targetTableId === relationship.targetTableId &&
+ r.sourceFieldId === relationship.sourceFieldId &&
+ r.targetFieldId === relationship.targetFieldId
+ );
+ if (byStructure.length === 1) {
+ return byStructure[0];
+ }
+
+ return undefined;
};
const defaultAreaMatcher = (area: Area, areas: Area[]): Area | undefined => {
diff --git a/src/lib/domain/diff/relationship-diff.ts b/src/lib/domain/diff/relationship-diff.ts
index 0eafe86b..1dcae058 100644
--- a/src/lib/domain/diff/relationship-diff.ts
+++ b/src/lib/domain/diff/relationship-diff.ts
@@ -1,5 +1,29 @@
import { z } from 'zod';
-import type { DBRelationship } from '../db-relationship';
+import type { Cardinality, DBRelationship } from '../db-relationship';
+
+export type RelationshipDiffAttribute =
+ | 'name'
+ | 'sourceSchema'
+ | 'sourceTableId'
+ | 'targetSchema'
+ | 'targetTableId'
+ | 'sourceFieldId'
+ | 'targetFieldId'
+ | 'sourceCardinality'
+ | 'targetCardinality';
+
+export const relationshipDiffAttributeSchema: z.ZodType<RelationshipDiffAttribute> =
+ z.union([
+ z.literal('name'),
+ z.literal('sourceSchema'),
+ z.literal('sourceTableId'),
+ z.literal('targetSchema'),
+ z.literal('targetTableId'),
+ z.literal('sourceFieldId'),
+ z.literal('targetFieldId'),
+ z.literal('sourceCardinality'),
+ z.literal('targetCardinality'),
+ ]);
export interface RelationshipDiffAdded<T = DBRelationship> {
object: 'relationship';
@@ -30,9 +54,31 @@ export const relationshipDiffRemovedSchema: z.ZodType<RelationshipDiffRemoved> =
relationshipId: z.string(),
});
+export interface RelationshipDiffChanged {
+ object: 'relationship';
+ type: 'changed';
+ relationshipId: string;
+ newRelationshipId: string;
+ attribute: RelationshipDiffAttribute;
+ oldValue?: string | Cardinality | null;
+ newValue?: string | Cardinality | null;
+}
+
+export const relationshipDiffChangedSchema: z.ZodType<RelationshipDiffChanged> =
+ z.object({
+ object: z.literal('relationship'),
+ type: z.literal('changed'),
+ relationshipId: z.string(),
+ newRelationshipId: z.string(),
+ attribute: relationshipDiffAttributeSchema,
+ oldValue: z.union([z.string(), z.null()]).optional(),
+ newValue: z.union([z.string(), z.null()]).optional(),
+ });
+
export type RelationshipDiff<T = DBRelationship> =
| RelationshipDiffAdded<T>
- | RelationshipDiffRemoved;
+ | RelationshipDiffRemoved
+ | RelationshipDiffChanged;
export const createRelationshipDiffSchema = <T = DBRelationship>(
relationshipSchema: z.ZodType<T>
@@ -40,5 +86,6 @@ export const createRelationshipDiffSchema = <T = DBRelationship>(
return z.union([
createRelationshipDiffAddedSchema(relationshipSchema),
relationshipDiffRemovedSchema,
+ relationshipDiffChangedSchema,
]) as z.ZodType<RelationshipDiff<T>>;
};