Skip to main content

Overview

The Import Metadata feature allows you to import database schemas from metadata JSON files generated by database introspection scripts. This is useful for importing existing database structures into ChartDB.

DatabaseMetadata Interface

The main interface for database metadata:
interface DatabaseMetadata {
    fk_info: ForeignKeyInfo[];
    pk_info: PrimaryKeyInfo[];
    columns: ColumnInfo[];
    indexes: IndexInfo[];
    tables: TableInfo[];
    views: ViewInfo[];
    check_constraints?: CheckConstraintInfo[];
    custom_types?: DBCustomTypeInfo[];
    database_name: string;
    version: string;
}

Metadata Components

TableInfo

Represents basic table information:
interface TableInfo {
    schema: string;
    table: string;
    rows?: number;
    type?: string;
    engine?: string;
    collation?: string;
    comment?: string;
}
schema
string
required
Database schema name
table
string
required
Table name
rows
number
Approximate row count
type
string
Table type (e.g., 'BASE TABLE', 'VIEW')
engine
string
Storage engine (MySQL/MariaDB: 'InnoDB', 'MyISAM')
collation
string
Default collation for the table
comment
string
Table comment/description

ColumnInfo

Detailed column information:
interface ColumnInfo {
    schema: string;
    table: string;
    name: string;
    type: string;
    ordinal_position: number;
    nullable: boolean | number;
    character_maximum_length?: string | null;
    precision?: {
        precision: number | null;
        scale: number | null;
    } | null;
    default?: string | null;
    collation?: string | null;
    comment?: string | null;
    is_identity?: boolean | null;
    is_array?: boolean | null;
}
schema
string
required
Schema name
table
string
required
Table name
name
string
required
Column name
type
string
required
Data type (e.g., 'varchar', 'integer', 'timestamp')
ordinal_position
number
required
Column position in the table (1-based)
nullable
boolean | number
required
Whether the column accepts NULL values
character_maximum_length
string | null
Maximum length for character types
precision
object | null
Numeric precision and scale:
  • precision: Total number of digits
  • scale: Number of decimal places
default
string | null
Default value expression
collation
string | null
Column collation
comment
string | null
Column comment/description
is_identity
boolean | null
Whether this is an auto-increment/identity column
is_array
boolean | null
Whether this is an array type (PostgreSQL)

ForeignKeyInfo

Foreign key relationship information:
interface ForeignKeyInfo {
    schema: string;
    table: string;
    column: string;
    foreign_key_name: string;
    reference_schema?: string;
    reference_table: string;
    reference_column: string;
    fk_def: string;
}
schema
string
required
Schema of the table with the foreign key
table
string
required
Table name with the foreign key
column
string
required
Column name (foreign key column)
foreign_key_name
string
required
Constraint name
reference_schema
string
Schema of the referenced table
reference_table
string
required
Referenced table name
reference_column
string
required
Referenced column name (typically a primary key)
fk_def
string
required
Full foreign key definition SQL

IndexInfo

Index information:
interface IndexInfo {
    schema: string;
    table: string;
    name: string;
    column: string;
    index_type: string;
    cardinality?: number | null;
    size?: number | null;
    unique: boolean | number;
    direction: string;
    column_position: number;
}
schema
string
required
Schema name
table
string
required
Table name
name
string
required
Index name
column
string
required
Column name in the index
index_type
string
required
Index type (e.g., 'BTREE', 'HASH', 'GIN')
cardinality
number | null
Estimated number of unique values
size
number | null
Index size in bytes
unique
boolean | number
required
Whether this is a unique index
direction
string
required
Sort direction ('ASC' or 'DESC')
column_position
number
required
Position of this column in a composite index (1-based)

Import Function

loadFromDatabaseMetadata

Converts database metadata to a ChartDB diagram:
const loadFromDatabaseMetadata = async ({
    databaseType,
    databaseMetadata,
    diagramNumber,
    databaseEdition,
}: {
    databaseType: DatabaseType;
    databaseMetadata: DatabaseMetadata;
    diagramNumber?: number;
    databaseEdition?: DatabaseEdition;
}): Promise<Diagram> => {
    // Creates tables from metadata
    const tables = createTablesFromMetadata({
        databaseMetadata,
        databaseType,
    });
    
    // Creates relationships from foreign keys
    const relationships = createRelationshipsFromMetadata({
        foreignKeys: databaseMetadata.fk_info,
        tables,
    });
    
    // Creates view dependencies
    const dependencies = await createDependenciesFromMetadata({
        views: databaseMetadata.views,
        tables,
        databaseType,
    });
    
    // Creates custom types (enums, composite)
    const dbCustomTypes = createCustomTypesFromMetadata({
        customTypes: databaseMetadata.custom_types,
    });
    
    // Adjust table positions automatically
    const adjustedTables = adjustTablePositions({
        tables,
        relationships,
        mode: 'perSchema',
    });
    
    return {
        id: generateDiagramId(),
        name: databaseMetadata.database_name || 'New Diagram',
        databaseType,
        databaseEdition,
        tables: adjustedTables,
        relationships,
        dependencies,
        customTypes: dbCustomTypes,
        createdAt: new Date(),
        updatedAt: new Date(),
    };
};

Example Metadata JSON

{
    "database_name": "ecommerce",
    "version": "PostgreSQL 14.5",
    "tables": [
        {
            "schema": "public",
            "table": "users",
            "type": "BASE TABLE",
            "rows": 1500,
            "comment": "User accounts"
        },
        {
            "schema": "public",
            "table": "orders",
            "type": "BASE TABLE",
            "rows": 5200
        }
    ],
    "columns": [
        {
            "schema": "public",
            "table": "users",
            "name": "id",
            "type": "uuid",
            "ordinal_position": 1,
            "nullable": false,
            "default": "gen_random_uuid()"
        },
        {
            "schema": "public",
            "table": "users",
            "name": "email",
            "type": "varchar",
            "ordinal_position": 2,
            "nullable": false,
            "character_maximum_length": "255"
        },
        {
            "schema": "public",
            "table": "orders",
            "name": "id",
            "type": "bigint",
            "ordinal_position": 1,
            "nullable": false,
            "is_identity": true
        },
        {
            "schema": "public",
            "table": "orders",
            "name": "user_id",
            "type": "uuid",
            "ordinal_position": 2,
            "nullable": false
        }
    ],
    "pk_info": [
        {
            "schema": "public",
            "table": "users",
            "column": "id",
            "constraint_name": "users_pkey"
        },
        {
            "schema": "public",
            "table": "orders",
            "column": "id",
            "constraint_name": "orders_pkey"
        }
    ],
    "fk_info": [
        {
            "schema": "public",
            "table": "orders",
            "column": "user_id",
            "foreign_key_name": "fk_orders_user_id",
            "reference_schema": "public",
            "reference_table": "users",
            "reference_column": "id",
            "fk_def": "FOREIGN KEY (user_id) REFERENCES users(id)"
        }
    ],
    "indexes": [
        {
            "schema": "public",
            "table": "users",
            "name": "idx_users_email",
            "column": "email",
            "index_type": "btree",
            "unique": true,
            "direction": "ASC",
            "column_position": 1
        }
    ],
    "views": [],
    "check_constraints": [],
    "custom_types": []
}

Usage Example

import { loadFromDatabaseMetadata } from './import-metadata';
import { DatabaseType } from './database-type';

// Load metadata JSON
const metadataJson = await fetch('/metadata.json').then(r => r.json());

// Convert to diagram
const diagram = await loadFromDatabaseMetadata({
    databaseType: DatabaseType.POSTGRESQL,
    databaseMetadata: metadataJson,
});

console.log(`Imported ${diagram.tables?.length} tables`);
console.log(`Imported ${diagram.relationships?.length} relationships`);

Validation

import { isDatabaseMetadata } from './metadata-types/database-metadata';

// Validate metadata structure
if (isDatabaseMetadata(jsonData)) {
    // Valid metadata
    const diagram = await loadFromDatabaseMetadata({
        databaseType: DatabaseType.POSTGRESQL,
        databaseMetadata: jsonData,
    });
} else {
    console.error('Invalid metadata format');
}