Skip to content

Modular logistics and supply chain operating system (LSOS)

Automate ERD refresh for release branches

Ronald A. Richardsone315a35b112e
diff --git a/.github/workflows/erd.yml b/.github/workflows/erd.yml
new file mode 100644
index 00000000..2f7d9c17
--- /dev/null
+++ b/.github/workflows/erd.yml
@@ -0,0 +1,143 @@
+name: Refresh ERD
+
+on:
+ push:
+ branches:
+ - 'dev-v*'
+ workflow_dispatch:
+
+concurrency:
+ group: erd-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: write
+ pull-requests: write
+
+jobs:
+ refresh:
+ name: Generate ERD and open PR
+ if: startsWith(github.ref, 'refs/heads/dev-v')
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+
+ steps:
+ - name: Checkout release branch
+ uses: actions/checkout@v4
+ with:
+ submodules: recursive
+
+ - name: Validate generator scripts
+ run: |
+ bash -n create-erd.sh
+ docker run --rm \
+ --volume "$GITHUB_WORKSPACE/create-erd.sh:/work/create-erd.sh:ro" \
+ koalaman/shellcheck-alpine:v0.10.0 \
+ /work/create-erd.sh
+ python3 -m unittest discover -s tests/erd -p 'test_*.py' -v
+ docker run --rm \
+ --volume "$GITHUB_WORKSPACE/.github/workflows/erd.yml:/work/erd.yml:ro" \
+ rhysd/actionlint:1.7.7 \
+ -color /work/erd.yml
+
+ - name: Require Composer authentication
+ env:
+ COMPOSER_AUTH_TOKEN: ${{ secrets._GITHUB_AUTH_TOKEN }}
+ run: |
+ if [[ -z "$COMPOSER_AUTH_TOKEN" ]]; then
+ echo "_GITHUB_AUTH_TOKEN is required to resolve Fleetbase Composer dependencies" >&2
+ exit 1
+ fi
+
+ - name: Prepare clean database and environment
+ run: |
+ sudo rm -rf docker/database/mysql
+ mkdir -p docker/database/mysql
+ if [[ ! -f api/.env ]]; then
+ cp api/.env.example api/.env 2>/dev/null || touch api/.env
+ fi
+
+ - name: Build release API image
+ env:
+ COMPOSER_AUTH_TOKEN: ${{ secrets._GITHUB_AUTH_TOKEN }}
+ run: |
+ docker build \
+ --file docker/Dockerfile \
+ --target app-release \
+ --build-arg GITHUB_AUTH_KEY="$COMPOSER_AUTH_TOKEN" \
+ --tag fleetbase/fleetbase-api:erd \
+ .
+ docker tag fleetbase/fleetbase-api:erd fleetbase/fleetbase-api:latest
+
+ - name: Start MySQL and Redis
+ run: docker compose up -d --wait database cache
+
+ - name: Create databases and run migrations
+ run: |
+ docker compose run --rm --no-deps application sh -c \
+ 'php artisan mysql:createdb && php artisan migrate --force'
+ docker compose run --rm --no-deps application \
+ php artisan migrate:status --no-ansi
+
+ - name: Resolve Docker network
+ run: |
+ database_container="$(docker compose ps -q database)"
+ network="$(docker inspect "$database_container" --format '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{end}}')"
+ if [[ -z "$network" ]]; then
+ echo "Unable to resolve the database container network" >&2
+ exit 1
+ fi
+ echo "ERD_DOCKER_NETWORK=$network" >> "$GITHUB_ENV"
+
+ - name: Generate and validate ERD outputs
+ env:
+ ERD_USE_DOCKER: 'true'
+ ERD_DB_HOST: database
+ ERD_DB_PORT: '3306'
+ ERD_DB_NAME: fleetbase
+ ERD_DB_USER: root
+ ERD_DB_PASSWORD: ''
+ run: ./create-erd.sh
+
+ - name: Show service logs on failure
+ if: failure()
+ run: docker compose logs --no-color --tail=300 || true
+
+ - name: Tear down services
+ if: always()
+ run: docker compose down -v || true
+
+ - name: Create or update ERD pull request
+ if: success()
+ id: erd-pr
+ uses: peter-evans/create-pull-request@v8
+ with:
+ token: ${{ github.token }}
+ base: ${{ github.ref_name }}
+ branch: automation/erd/${{ github.ref_name }}
+ delete-branch: true
+ add-paths: |
+ database.mmd
+ erd.svg
+ erd-dark.svg
+ commit-message: Refresh ERD for ${{ github.ref_name }}
+ committer: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
+ author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
+ title: Refresh ERD for ${{ github.ref_name }}
+ body: |
+ Regenerates the database ERD from the release schema at `${{ github.sha }}`.
+
+ Generated artifacts:
+ - `database.mmd`
+ - `erd.svg`
+ - `erd-dark.svg`
+
+ This pull request is maintained automatically as `${{ github.ref_name }}` changes.
+ draft: false
+
+ - name: Report pull request
+ if: steps.erd-pr.outputs.pull-request-url
+ env:
+ PR_URL: ${{ steps.erd-pr.outputs.pull-request-url }}
+ PR_OPERATION: ${{ steps.erd-pr.outputs.pull-request-operation }}
+ run: echo "::notice::$PR_URL was $PR_OPERATION"
diff --git a/.gitignore b/.gitignore
index 14d2dbb0..3efbc8c3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,6 @@
/node_modules
+__pycache__/
+*.py[cod]
.fleetbase-dev-links.json
.env
.env.backup
diff --git a/create-erd.sh b/create-erd.sh
old mode 100644
new mode 100755
index 59a5bcdc..373b0a60
--- a/create-erd.sh
+++ b/create-erd.sh
@@ -1,13 +1,170 @@
-#!/bin/bash
+#!/usr/bin/env bash
-# Exit the script as soon as a command fails
-set -e
+set -euo pipefail
-# Run schemacrawler
-# To use schemacrawler see https://www.schemacrawler.com/downloads.html
-schemacrawler.sh --server mysql --host localhost --database fleetbase --user root --info-level standard --command script --script-language python --script mermaid.py --output-file database.mmd
-schemacrawler.sh --server mysql --host localhost --database fleetbase --user root --info-level standard --command=schema --grep-tables="^(?!fleetbase_sandbox\.).*" --output-format=svg --output-file=erd.svg
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-# Generate a SVG ERD diagram using `dark` theme
-# To use mmdc see https://github.com/mermaid-js/mermaid-cli
-mmdc -i database.mmd -o erd-dark.svg -t dark -b transparent --configFile="mmdc.json"
\ No newline at end of file
+ERD_DB_HOST="${ERD_DB_HOST:-localhost}"
+ERD_DB_PORT="${ERD_DB_PORT:-3306}"
+ERD_DB_NAME="${ERD_DB_NAME:-fleetbase}"
+ERD_DB_USER="${ERD_DB_USER:-root}"
+ERD_DB_PASSWORD="${ERD_DB_PASSWORD:-}"
+ERD_SCHEMA_PATTERN="${ERD_SCHEMA_PATTERN:-^(?!(information_schema|mysql|performance_schema|sys)\\.)(?![^.]+_sandbox\\.).*}"
+ERD_DOCKER_NETWORK="${ERD_DOCKER_NETWORK:-}"
+ERD_USE_DOCKER="${ERD_USE_DOCKER:-false}"
+
+# 16.20.4 is the pinned release that provides the catalog API consumed by
+# mermaid.py and matches the provenance of the repository's existing ERD.
+SCHEMACRAWLER_IMAGE="${SCHEMACRAWLER_IMAGE:-schemacrawler/schemacrawler:v16.20.4}"
+MERMAID_CLI_IMAGE="${MERMAID_CLI_IMAGE:-ghcr.io/mermaid-js/mermaid-cli/mermaid-cli:11.16.0}"
+
+TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/fleetbase-erd.XXXXXX")"
+trap 'rm -rf "$TMP_DIR"' EXIT
+
+schema_args=(
+ --server mysql
+ --host "$ERD_DB_HOST"
+ --port "$ERD_DB_PORT"
+ --database "$ERD_DB_NAME"
+ --user "$ERD_DB_USER"
+ --info-level standard
+ --grep-tables "$ERD_SCHEMA_PATTERN"
+ --no-info
+)
+
+if [[ -n "$ERD_DB_PASSWORD" ]]; then
+ schema_args+=(--password "$ERD_DB_PASSWORD")
+fi
+
+run_with_docker() {
+ command -v docker >/dev/null 2>&1 || {
+ echo "docker is required when ERD_USE_DOCKER=true" >&2
+ exit 1
+ }
+
+ local network_args=()
+ if [[ -n "$ERD_DOCKER_NETWORK" ]]; then
+ network_args=(--network "$ERD_DOCKER_NETWORK")
+ fi
+
+ local user_args=()
+ if command -v id >/dev/null 2>&1; then
+ user_args=(--user "$(id -u):$(id -g)")
+ fi
+
+ docker run --rm \
+ "${network_args[@]}" \
+ "${user_args[@]}" \
+ --volume "$SCRIPT_DIR/mermaid.py:/home/schcrwlr/share/mermaid.py:ro" \
+ --volume "$TMP_DIR:/home/schcrwlr/output" \
+ "$SCHEMACRAWLER_IMAGE" \
+ /opt/schemacrawler/bin/schemacrawler.sh \
+ "${schema_args[@]}" \
+ --command script \
+ --script-language python \
+ --script share/mermaid.py \
+ --output-file output/database.mmd
+
+ docker run --rm \
+ "${network_args[@]}" \
+ "${user_args[@]}" \
+ --volume "$TMP_DIR:/home/schcrwlr/output" \
+ "$SCHEMACRAWLER_IMAGE" \
+ /opt/schemacrawler/bin/schemacrawler.sh \
+ "${schema_args[@]}" \
+ --command schema \
+ --output-format svg \
+ --output-file output/erd.svg
+
+ docker run --rm \
+ "${user_args[@]}" \
+ --volume "$SCRIPT_DIR/mmdc.json:/data/mmdc.json:ro" \
+ --volume "$TMP_DIR:/output" \
+ "$MERMAID_CLI_IMAGE" \
+ -i /output/database.mmd \
+ -o /output/erd-dark.svg \
+ -t dark \
+ -b transparent \
+ --configFile /data/mmdc.json
+}
+
+run_with_local_tools() {
+ local schemacrawler_bin=""
+ if command -v schemacrawler.sh >/dev/null 2>&1; then
+ schemacrawler_bin="$(command -v schemacrawler.sh)"
+ elif command -v schemacrawler >/dev/null 2>&1; then
+ schemacrawler_bin="$(command -v schemacrawler)"
+ else
+ echo "schemacrawler or schemacrawler.sh is required (or set ERD_USE_DOCKER=true)" >&2
+ exit 1
+ fi
+
+ command -v mmdc >/dev/null 2>&1 || {
+ echo "mmdc is required (or set ERD_USE_DOCKER=true)" >&2
+ exit 1
+ }
+
+ "$schemacrawler_bin" \
+ "${schema_args[@]}" \
+ --command script \
+ --script-language python \
+ --script "$SCRIPT_DIR/mermaid.py" \
+ --output-file "$TMP_DIR/database.mmd"
+
+ "$schemacrawler_bin" \
+ "${schema_args[@]}" \
+ --command schema \
+ --output-format svg \
+ --output-file "$TMP_DIR/erd.svg"
+
+ mmdc \
+ -i "$TMP_DIR/database.mmd" \
+ -o "$TMP_DIR/erd-dark.svg" \
+ -t dark \
+ -b transparent \
+ --configFile "$SCRIPT_DIR/mmdc.json"
+}
+
+validate_outputs() {
+ grep -q '^erDiagram$' "$TMP_DIR/database.mmd"
+ grep -Eq '^ [[:alnum:]_]+ \{$' "$TMP_DIR/database.mmd"
+ grep -Fq '||--o{' "$TMP_DIR/database.mmd"
+
+ if grep -Eiq '^ (information_schema|performance_schema|mysql|sys|[^[:space:]]+_sandbox)_' "$TMP_DIR/database.mmd"; then
+ echo "Generated Mermaid contains a sandbox or system schema" >&2
+ exit 1
+ fi
+
+ for svg in "$TMP_DIR/erd.svg" "$TMP_DIR/erd-dark.svg"; do
+ [[ -s "$svg" ]] || {
+ echo "Generated SVG is empty: $svg" >&2
+ exit 1
+ }
+ grep -Eq '<svg([[:space:]>])' "$svg"
+ if grep -Eiq 'generated on|generated_on' "$svg"; then
+ echo "Generated SVG contains a non-deterministic timestamp: $svg" >&2
+ exit 1
+ fi
+ if command -v xmllint >/dev/null 2>&1; then
+ xmllint --noout "$svg"
+ fi
+ done
+}
+
+ERD_USE_DOCKER_NORMALIZED="$(printf '%s' "$ERD_USE_DOCKER" | tr '[:upper:]' '[:lower:]')"
+case "$ERD_USE_DOCKER_NORMALIZED" in
+ 1|true|yes) run_with_docker ;;
+ 0|false|no) run_with_local_tools ;;
+ *)
+ echo "ERD_USE_DOCKER must be true or false" >&2
+ exit 1
+ ;;
+esac
+
+validate_outputs
+
+install -m 0644 "$TMP_DIR/database.mmd" "$SCRIPT_DIR/database.mmd"
+install -m 0644 "$TMP_DIR/erd.svg" "$SCRIPT_DIR/erd.svg"
+install -m 0644 "$TMP_DIR/erd-dark.svg" "$SCRIPT_DIR/erd-dark.svg"
+
+echo "Generated database.mmd, erd.svg, and erd-dark.svg"
diff --git a/mermaid.py b/mermaid.py
index 418609fb..944f70c2 100644
--- a/mermaid.py
+++ b/mermaid.py
@@ -1,43 +1,121 @@
from __future__ import print_function
+
import re
+
+SYSTEM_SCHEMAS = {
+ "information_schema",
+ "mysql",
+ "performance_schema",
+ "sys",
+}
+
+
def cleanname(name):
- return re.sub(r'[^\d\w_]', '', name)
+ """Return a Mermaid-safe identifier fragment."""
+ return re.sub(r"[^\d\w_]", "", str(name))
+
+
+def split_table_name(full_name):
+ parts = str(full_name).split(".", 1)
+ if len(parts) != 2:
+ return None, None
+ return parts[0], parts[1]
+
def format_table_name(full_name):
- parts = full_name.split('.')
- if len(parts) == 2 and not parts[0].endswith('_sandbox'):
- return cleanname(parts[0] + '_' + parts[1])
- else:
+ schema, table = split_table_name(full_name)
+ if not schema or not table:
return None
-print('erDiagram')
-print('')
-for table in catalog.tables:
- formatted_name = format_table_name(table.fullName)
- if formatted_name:
- print(' ' + formatted_name + ' {')
+ normalized_schema = schema.lower()
+ if normalized_schema in SYSTEM_SCHEMAS or normalized_schema.endswith("_sandbox"):
+ return None
+
+ return cleanname(schema + "_" + table)
+
+
+def format_remarks(remarks):
+ """Collapse remarks to one safe Mermaid quoted string."""
+ value = " ".join(str(remarks).split())
+ return value.replace("\\", "/").replace('"', "'")
+
+
+def column_markers(column):
+ markers = []
+ if column.isPartOfPrimaryKey():
+ markers.append("PK")
+ if column.isPartOfForeignKey():
+ markers.append("FK")
+ if column.isPartOfUniqueIndex():
+ markers.append("UK")
+ return markers
+
+
+def included_tables(catalog):
+ tables = [table for table in catalog.tables if format_table_name(table.fullName)]
+ return sorted(tables, key=lambda table: str(table.fullName).lower())
+
+
+def validate_unique_names(tables):
+ names = {}
+ for table in tables:
+ formatted_name = format_table_name(table.fullName)
+ previous = names.get(formatted_name)
+ if previous is not None and previous != str(table.fullName):
+ raise ValueError(
+ "Table names %s and %s both normalize to %s"
+ % (previous, table.fullName, formatted_name)
+ )
+ names[formatted_name] = str(table.fullName)
+
+
+def render(catalog):
+ tables = included_tables(catalog)
+ validate_unique_names(tables)
+ included_full_names = {str(table.fullName) for table in tables}
+
+ print("erDiagram")
+ print("")
+
+ for table in tables:
+ print(" " + format_table_name(table.fullName) + " {")
for column in table.columns:
- print(' ' + cleanname(column.columnDataType.name) + ' ' + cleanname(column.name),
- end='')
- if column.isPartOfPrimaryKey():
- print(' PK', end='')
- elif column.isPartOfForeignKey():
- print(' FK', end='')
- elif column.isPartOfUniqueIndex():
- print(' UK', end='')
+ line = " %s %s" % (
+ cleanname(column.columnDataType.name),
+ cleanname(column.name),
+ )
+
+ markers = column_markers(column)
+ if markers:
+ line += " " + ", ".join(markers)
+
if column.hasRemarks():
- print(' "' + ' '.join(column.remarks.splitlines()) + '"',
- end='')
- print()
- print(' }')
- print('')
-
-for table in catalog.tables:
- formatted_name = format_table_name(table.fullName)
- if formatted_name:
- for childTable in table.referencingTables:
- child_formatted_name = format_table_name(childTable.fullName)
- if child_formatted_name:
- print(' ' + formatted_name + ' ||--o{ ' +
- child_formatted_name + ' : "foreign key"')
+ line += ' "' + format_remarks(column.remarks) + '"'
+
+ print(line)
+ print(" }")
+ print("")
+
+ relationships = set()
+ for table in tables:
+ for child_table in table.referencingTables:
+ if str(child_table.fullName) not in included_full_names:
+ continue
+ relationships.add(
+ (
+ format_table_name(table.fullName),
+ format_table_name(child_table.fullName),
+ )
+ )
+
+ for parent_name, child_name in sorted(relationships):
+ print(
+ ' %s ||--o{ %s : "foreign key"'
+ % (parent_name, child_name)
+ )
+
+
+# SchemaCrawler injects `catalog` into the script global namespace.
+if "catalog" in globals():
+ render(catalog)
diff --git a/tests/erd/test_mermaid.py b/tests/erd/test_mermaid.py
new file mode 100644
index 00000000..9bf0f6ec
--- /dev/null
+++ b/tests/erd/test_mermaid.py
@@ -0,0 +1,114 @@
+import contextlib
+import importlib.util
+import io
+import pathlib
+import unittest
+
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+SPEC = importlib.util.spec_from_file_location("fleetbase_mermaid", ROOT / "mermaid.py")
+MERMAID = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(MERMAID)
+
+
+class DataType:
+ def __init__(self, name):
+ self.name = name
+
+
+class Column:
+ def __init__(self, name, data_type="VARCHAR", *, pk=False, fk=False, uk=False, remarks=None):
+ self.name = name
+ self.columnDataType = DataType(data_type)
+ self._pk = pk
+ self._fk = fk
+ self._uk = uk
+ self.remarks = remarks
+
+ def isPartOfPrimaryKey(self):
+ return self._pk
+
+ def isPartOfForeignKey(self):
+ return self._fk
+
+ def isPartOfUniqueIndex(self):
+ return self._uk
+
+ def hasRemarks(self):
+ return self.remarks is not None
+
+
+class Table:
+ def __init__(self, full_name, columns=None):
+ self.fullName = full_name
+ self.columns = columns or []
+ self.referencingTables = []
+
+
+class Catalog:
+ def __init__(self, tables):
+ self.tables = tables
+
+
+def render(catalog):
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ MERMAID.render(catalog)
+ return output.getvalue()
+
+
+class MermaidRendererTest(unittest.TestCase):
+ def test_sorts_tables_and_relationships_and_excludes_non_application_schemas(self):
+ parent = Table("fleetbase.parents", [Column("id", pk=True)])
+ child_b = Table("fleetbase.z_children", [Column("parent_uuid", fk=True)])
+ child_a = Table("fleetbase.a_children", [Column("parent_uuid", fk=True)])
+ sandbox = Table("fleetbase_sandbox.parents", [Column("id")])
+ system = Table("mysql.users", [Column("Host")])
+ parent.referencingTables = [child_b, sandbox, child_a, child_a]
+
+ output = render(Catalog([child_b, system, parent, sandbox, child_a]))
+
+ self.assertLess(output.index("fleetbase_a_children"), output.index("fleetbase_parents"))
+ self.assertLess(output.index("fleetbase_parents"), output.index("fleetbase_z_children"))
+ self.assertNotIn("sandbox", output)
+ self.assertNotIn("mysql_users", output)
+ self.assertEqual(output.count("fleetbase_parents ||--o{ fleetbase_a_children"), 1)
+ self.assertLess(
+ output.index("fleetbase_parents ||--o{ fleetbase_a_children"),
+ output.index("fleetbase_parents ||--o{ fleetbase_z_children"),
+ )
+
+ def test_preserves_combined_keys_and_escapes_remarks(self):
+ table = Table(
+ "fleetbase.orders",
+ [
+ Column(
+ "customer-uuid",
+ "CHAR(36)",
+ pk=True,
+ fk=True,
+ uk=True,
+ remarks='Customer "identity"\npath\\value',
+ )
+ ],
+ )
+
+ output = render(Catalog([table]))
+
+ self.assertIn("CHAR36 customeruuid PK, FK, UK", output)
+ self.assertIn('"Customer \'identity\' path/value"', output)
+
+ def test_rejects_normalized_table_name_collisions(self):
+ catalog = Catalog([Table("foo-bar.users"), Table("foobar.users")])
+
+ with self.assertRaisesRegex(ValueError, "both normalize to foobar_users"):
+ render(catalog)
+
+ def test_ignores_unqualified_names(self):
+ output = render(Catalog([Table("users", [Column("id")])]))
+
+ self.assertEqual(output, "erDiagram\n\n")
+
+
+if __name__ == "__main__":
+ unittest.main()