Skip to content

Commit

Permalink
Merge pull request #3916 from aloisklink/fix/use-determenistic-uuids-…
Browse files Browse the repository at this point in the history
…for-er-diagrams

fix(er): switch to deterministic UUIDs in ER
  • Loading branch information
sidharthv96 authored Dec 16, 2022
2 parents 33f78a5 + 7855eda commit f019250
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/mermaid/src/diagrams/er/erRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import utils from '../../utils';
import erMarkers from './erMarkers';
import { configureSvgSize } from '../../setupGraphViewbox';
import { parseGenericTypes } from '../common/common';
import { v4 as uuid4 } from 'uuid';
import { v5 as uuid5 } from 'uuid';

/** Regex used to remove chars from the entity name so the result can be used in an id */
const BAD_ID_CHARS_REGEXP = /[^\dA-Za-z](\W)*/g;
Expand Down Expand Up @@ -643,9 +643,24 @@ export const draw = function (text, id, _version, diagObj) {
svg.attr('viewBox', `${svgBounds.x - padding} ${svgBounds.y - padding} ${width} ${height}`);
}; // draw

/**
* UUID namespace for ER diagram IDs
*
* This can be generated via running:
*
* ```js
* const { v5: uuid5 } = await import('uuid');
* uuid5(
* 'https://mermaid-js.github.io/mermaid/syntax/entityRelationshipDiagram.html',
* uuid5.URL
* );
* ```
*/
const MERMAID_ERDIAGRAM_UUID = '28e9f9db-3c8d-5aa5-9faf-44286ae5937c';

/**
* Return a unique id based on the given string. Start with the prefix, then a hyphen, then the
* simplified str, then a hyphen, then a unique uuid. (Hyphens are only included if needed.)
* simplified str, then a hyphen, then a unique uuid based on the str. (Hyphens are only included if needed.)
* Although the official XML standard for ids says that many more characters are valid in the id,
* this keeps things simple by accepting only A-Za-z0-9.
*
Expand All @@ -656,7 +671,11 @@ export const draw = function (text, id, _version, diagObj) {
*/
export function generateId(str = '', prefix = '') {
const simplifiedStr = str.replace(BAD_ID_CHARS_REGEXP, '');
return `${strWithHyphen(prefix)}${strWithHyphen(simplifiedStr)}${uuid4()}`;
// we use `uuid v5` so that UUIDs are consistent given a string.
return `${strWithHyphen(prefix)}${strWithHyphen(simplifiedStr)}${uuid5(
str,
MERMAID_ERDIAGRAM_UUID
)}`;
}

/**
Expand Down
12 changes: 12 additions & 0 deletions packages/mermaid/src/diagrams/er/erRenderer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { generateId } from './erRenderer';

describe('erRenderer', () => {
describe('generateId', () => {
it('should be deterministic', () => {
const id1 = generateId('hello world', 'my-prefix');
const id2 = generateId('hello world', 'my-prefix');

expect(id1).toBe(id2);
});
});
});

0 comments on commit f019250

Please sign in to comment.