Skip to content

Instantly share code, notes, and snippets.

@ShinyChang
Created March 9, 2021 03:15
Show Gist options
  • Save ShinyChang/713c978234390bcefcea1c574d080ac6 to your computer and use it in GitHub Desktop.
Save ShinyChang/713c978234390bcefcea1c574d080ac6 to your computer and use it in GitHub Desktop.
Metabase tables schema to DiagramPlus Diagram

Metabase Table Schema to DiagramPlus Diagram

Steps

  1. fetch https://{metabase-domain}/api/database/{database-id}/metadata?schemaName=
  2. get tables from step1 response
  3. execute metabaseTablesToDiagramPlusDiagram(tables)
  4. save return value as json file
  5. visit https://diagramplus.com/ and create the new diagram and import the json file which generated in step 4
const metabaseTablesToDiagramPlusDiagram = (tables) => {
let _id = 0;
const genId = () => ++_id;
const normalizedTables = tables.reduce((acc, table) => {
acc[table.id] = {
id: table.id,
name: table.name,
description: table.description,
fields: table.fields.map((f) => ({
id: f.id,
name: f.name,
type: f.database_type,
description: f.description,
fk: f.fk_target_field_id,
target: f.target,
})),
};
return acc;
}, {});
const diagram = {
type: "edit",
version: 3,
columns: [
{ id: 0, value: { id: "0", name: "name", type: "string" } },
{ id: 1, value: { id: "1", name: "type", type: "string" } },
{
id: 2,
value: { id: "2", name: "nullable", type: "boolean" },
},
],
tables: [],
refs: [],
size: { width: 0, height: 0 },
schema: "main",
};
Object.values(normalizedTables).forEach((table) => {
diagram.tables.push({
id: table.id,
position: { top: 0, left: 0 },
rowsExpanded: false,
value: {
id: table.name,
name:
table.name +
(table.description
? ` (${table.description.replace(/\n/g, "")})`
: ""),
schema: "new",
rows: table.fields.map((field) => ({
id: field.id,
value: {
id: field.name,
type: field.type,
name:
field.name +
(field.description
? ` (${field.description.replace(/\n/g, "")})`
: ""),
},
})),
},
});
table.fields
.filter((field) => !!field.fk)
.forEach((field) => {
diagram.refs.push({
from: {
table: field.target.table_id,
rows: [field.target.id],
},
to: { table: table.id, rows: [field.id] },
id: genId(),
});
});
});
return diagram;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment