From 2d006e0910372237f3c29b9c5397524ab56149ce Mon Sep 17 00:00:00 2001 From: Allen Gilliland <agilliland@gmail.com> Date: Fri, 30 Oct 2015 17:38:35 -0700 Subject: [PATCH] add a function in our schema metadata lib for `foreignKeyCountsByOriginTable` which counts the occurrences of FK relationships by the origin table they come from. this allows us to know if a given origin table is represented multiple times in a list of FKs. --- frontend/src/lib/schema_metadata.js | 18 ++++++++++++++++++ frontend/test/unit/lib/schema_metadata.spec.js | 15 ++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/frontend/src/lib/schema_metadata.js b/frontend/src/lib/schema_metadata.js index b0fab5bd65e..b30ae777beb 100644 --- a/frontend/src/lib/schema_metadata.js +++ b/frontend/src/lib/schema_metadata.js @@ -418,3 +418,21 @@ export function hasLatitudeAndLongitudeColumns(columnDefs) { } return hasLatitude && hasLongitude; } + +export function foreignKeyCountsByOriginTable(fks) { + if (fks === null || !Array.isArray(fks)) { + return null; + } + + return fks.map(function(fk) { + return ('origin' in fk) ? fk.origin.table.id : null; + }).reduce(function(prev, curr, idx, array) { + if (curr in prev) { + prev[curr]++; + } else { + prev[curr] = 1; + } + + return prev; + }, {}); +} diff --git a/frontend/test/unit/lib/schema_metadata.spec.js b/frontend/test/unit/lib/schema_metadata.spec.js index 74547d87513..e33605e3f02 100644 --- a/frontend/test/unit/lib/schema_metadata.spec.js +++ b/frontend/test/unit/lib/schema_metadata.spec.js @@ -7,7 +7,8 @@ import { NUMBER, BOOLEAN, LOCATION, - COORDINATE + COORDINATE, + foreignKeyCountsByOriginTable } from 'metabase/lib/schema_metadata'; describe('schema_metadata', () => { @@ -44,4 +45,16 @@ describe('schema_metadata', () => { expect(getFieldType({ base_type: 'DERP DERP DERP' })).toEqual(undefined) }); }); + + describe('foreignKeyCountsByOriginTable', () => { + it('should work with null input', () => { + expect(foreignKeyCountsByOriginTable(null)).toEqual(null) + }); + it('should require an array as input', () => { + expect(foreignKeyCountsByOriginTable({})).toEqual(null) + }); + it('should count occurrences by origin.table.id', () => { + expect(foreignKeyCountsByOriginTable([{ origin: {table: {id: 123}} }, { origin: {table: {id: 123}} }, { origin: {table: {id: 123}} }, { origin: {table: {id: 456}} }])).toEqual({123: 3, 456: 1}) + }); + }); }); -- GitLab