Skip to content

Commit 193866c

Browse files
committed
Added column reference support in mermaid
1 parent e5376bd commit 193866c

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/Sql2er/Mermaid.hs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,46 @@ sqlTypeToString PGtimestamptz = "timestamptz"
2828
sqlTypeToString PGBigSerial = "bigserial"
2929
sqlTypeToString SomeType = "unknown"
3030

31+
columnConstraintToText :: ColumnConstraint -> Text
32+
columnConstraintToText c =
33+
case c of
34+
PrimaryKey -> "Primary Key"
35+
Unique -> "Unique"
36+
NotNull -> "Not Null"
37+
Null -> ""
38+
Default t -> "Default " <> t
39+
ReferencesColumn _ _ -> ""
40+
Check t -> "Check " <> t
41+
42+
columnConstraintsToText :: [ColumnConstraint] -> Text
43+
columnConstraintsToText = foldMap columnConstraintToText
44+
3145
-- Function to convert a Column to Mermaid's attribute representation
3246
columnToMermaid :: Column -> Text
3347
columnToMermaid Column {columnName, columnType} =
34-
" " <> sqlTypeToString columnType <> " " <> columnName
48+
" "
49+
<> sqlTypeToString columnType
50+
<> " "
51+
<> columnName
52+
-- <> " "
53+
-- <> columnConstraintsToText cConstraints TODO: Mermaid not supporting spaces
3554

3655
-- Function to convert a Table to Mermaid's table representation
3756
tableToMermaid :: Table -> Text
3857
tableToMermaid Table {tableName, columns} =
39-
T.unlines $
40-
[tableName <> " {"] ++ map columnToMermaid columns ++ ["}"]
58+
T.unlines
59+
([tableName <> " {"] ++ map columnToMermaid columns ++ ["}"])
60+
<> addForeignKeys tableName columns
4161

62+
addForeignKeys :: TableName -> [Column] -> Text
63+
addForeignKeys originTableName cols = mconcat $ map addForeignKeys_ cols
64+
where
65+
addForeignKeys_ Column{cConstraints} = mconcat $ map referenceColumnToText cConstraints
66+
referenceColumnToText :: ColumnConstraint -> Text
67+
referenceColumnToText (ReferencesColumn tName mColName) = do
68+
originTableName <> " ||--o{ " <> tName <> maybe "" (" : " <>) mColName <> "\n"
69+
referenceColumnToText _ = ""
70+
4271
-- Function to create relationship representation for ForeignKeyConstraint
4372
foreignKeyToMermaid :: TableName -> TableConstraint -> [Text]
4473
foreignKeyToMermaid tableName (ForeignKeyConstraint targetTable targetColumn _) =

0 commit comments

Comments
 (0)