線上資料庫關係圖設計工具 dbdiagram.io
前段時間,筆者在設計某個系統模組的時候,需要增加十幾張表。
為了簡單快速地把這十幾張表設計並定義出來,我找到了一個可以線上設計資料庫關係圖(database relationship diagram)且可以匯出DDL SQL的工具——dbdiagram.io。
dbdiagram.io 是holistics.io這款商業產品的社群版。
dbdiagram.io 使用DSL語言,可以簡單快速地建立資料庫關係圖。
這款工具的操作介面也非常簡約並具有設計感:

-
有時候我們需要在關係型資料庫中設計一些表,以便實現我們的業務功能。
-
或者我們對某個系統的表結構不是很熟悉,希望畫個圖表示一下這些實體之間的關係。
-
又或者我們希望把設計好的資料庫關係圖直接轉化為DDL SQL。
-
而且我們不想使用複雜的工具,付出高昂的學習成本。
-
也不想用太重的工具,佔用記憶體。
這個時候這個線上的資料庫關係圖工具就排上用場了。
語法
下面介紹一下它的語法。
定義表的語法如下:
Table users { id integer [pk] username varchar [not null, unique] full_name type [not null] ..... } 複製程式碼
如果表名太長還支援取別名:
Table longtablename as t_alias { ..... } 複製程式碼
定義外來鍵支援如下三種關係:
< : One-to-many > : Many-to-one - : One-to-one 複製程式碼
並且提供了3種定義外來鍵的方式:
Ref name-optional { table1.field1 < table2.field2 } Ref name-optional: t1.f1 < t2.f2 Table posts { id integer [pk, ref: < comments.post_id] user_id integer [ref: > users.id] } 複製程式碼
例子
下面以電商系統常用的幾張表作為例子演示一下它的用法。
當你登入自己的Google賬號以後,可以把你設計好的圖形儲存到線上,這樣就可以通過一個唯一的連結訪問 : dbdiagram.io/d/5cc9103ef…
這裡是DSL:
Table orders { id int [primary key] user_id int [not null, unique] status varchar created_at varchar } Table order_items { order_id int product_id int quantity int } Table products { id int [primary key] name varchar merchant_id int [not null] price int status varchar created_at varchar category_id int } Table users { id int [primary key] full_name varchar email varchar [unique] gender varchar date_of_birth varchar created_at varchar country_code int } Table merchants { id int [primary key] admin_id int merchant_name varchar country_code int created_at varchar } Table categories { id int [primary key] cat_name varchar parent_id int } Table countries { code int [primary key] name varchar continent_name varchar } Ref { orders.user_id > users.id } Ref { order_items.order_id > orders.id } Ref { order_items.product_id > products.id } Ref { products.merchant_id > merchants.id } Ref { products.category_id > categories.id } Ref { categories.parent_id > categories.id } Ref { users.country_code > countries.code } Ref { merchants.admin_id > users.id } Ref { merchants.country_code > countries.code } 複製程式碼
這裡是匯出的資料庫關係圖PDF:

總結
最後總結一下dbdiagram.io的特點:
- DSL : 使用簡單的DSL語言即可定義資料庫關係圖
- Google Account :使用Google賬號可以線上儲存設計好的圖
- Online :不需要安裝軟體,方便快捷,而且支援拖動和調節
- Import/Export : 支援匯出DDL SQL和PDF,支援匯入外部資料
- Share : 可以生成一個分享連結,方便團隊成員協作
