fuelen / ecto_erd

A mix task for generating Entity Relationship Diagram from Ecto schemas available in your project.
Apache License 2.0
215 stars 15 forks source link

Comments Support #54

Closed zorbash closed 4 months ago

zorbash commented 4 months ago

Mermaid supports comments (doc) and I'm inquiring about getting this library to support them as well.

Example:

erDiagram
    CAR ||--o{ NAMED-DRIVER : allows
    CAR {
        string registrationNumber PK
        string make
        string model
        string[] parts
    }
    PERSON ||--o{ NAMED-DRIVER : is
    PERSON {
        string driversLicense PK "The license #"
        string(99) firstName "Only 99 characters are allowed"
        string lastName
        string phone UK
        int age
    }
    NAMED-DRIVER {
        string carRegistrationNumber PK, FK
        string driverLicence PK, FK
    }
    MANUFACTURER only one to zero or more CAR : makes

I took a stab at this locally and the following changes would be sufficient:

diff --git a/lib/ecto/erd/document/mermaid.ex b/lib/ecto/erd/document/mermaid.ex
index afbcc01..a4c9705 100644
--- a/lib/ecto/erd/document/mermaid.ex
+++ b/lib/ecto/erd/document/mermaid.ex
@@ -91,6 +89,11 @@ defmodule Ecto.ERD.Document.Mermaid do
           " PK"
         else
           ""
+        end <>
+        if field.comment do
+          ~s( "#{field.comment}")
+        else
+          ""
         end
     else
       Logger.warning(
diff --git a/lib/ecto/erd/field.ex b/lib/ecto/erd/field.ex
index 0fbec3a..d43a44a 100644
--- a/lib/ecto/erd/field.ex
+++ b/lib/ecto/erd/field.ex
@@ -1,6 +1,6 @@
 defmodule Ecto.ERD.Field do
   @moduledoc false
-  defstruct [:name, :type, :primary?]
+  defstruct [:name, :type, :primary?, :comment]

   def new(%{name: name, type: type} = params) do
     %__MODULE__{

To populate the comments in the .ecto_erd.exs I have:

[
  map_node: fn
    %Ecto.ERD.Node{schema_module: schema_module} = node ->
      update_in(node, [Access.key(:fields), Access.all()], fn field ->
        case TypeDoc.doc({schema_module, field.name}) do
          nil ->
            field

          doc ->
            %{field | comment: String.replace(doc, "\"", "")}
        end
      end)
  end
]

In the snipped above TypeDoc is a tiny library which returns the documentation for schema fields, which is not open-source. There doesn't seem to be a standardized way to add such metadata like comments to Ecto.Schema as of now. Therefore this can be left to the user.

Is this something the maintainer(s) find worth-adding to the library? If so I'd be happy to submit a PR.

Related Resources

fuelen commented 4 months ago

This could be a nice addition. PR is welcome.

fuelen commented 4 months ago

Published new version 0.6.0