軟件設(shè)計技巧之數(shù)據(jù)庫設(shè)計還能這樣玩
數(shù)據(jù)庫設(shè)計回顧
記得剛學習java開發(fā)的時候,老師推薦PowerDesigner設(shè)計數(shù)據(jù)庫,圖形化更加直觀易懂。
后來工作后,實際開發(fā),喜歡直接連接數(shù)據(jù)庫操作,因此使用Navicat作為數(shù)據(jù)庫管理工具,順帶包攬設(shè)計工作。
而在團隊協(xié)作中,數(shù)據(jù)庫文檔是評審必須的,想想自己整理的word文檔,免不了會吐槽一番。最近幾年,word文檔寫的很少了(除非正式的文檔),因為markdown的出現(xiàn),更加符合程序員的編寫習慣,感覺就和寫代碼一樣,縮進、特殊標記、代碼插入、表格等,很方便的就能實現(xiàn)。
為了講下面的內(nèi)容,這里我簡單說明下markdown是什么。
markdown是一種標記語言,使用更加易懂的純文本格式,很方便實現(xiàn)寫文章所需的各種效果。
那么,你有沒有想過,數(shù)據(jù)庫設(shè)計也能通過類似的標記語言呢?
數(shù)據(jù)庫標記語言
今天要講的主角正式登場(^_^),她就是DBML,全稱是Database Markup Language(數(shù)據(jù)庫標記語言)。講之前,先來張靚照瞧瞧

從上圖可以看到,table、pk、varchar等關(guān)鍵字,再熟悉不過了。這種語言是專門為數(shù)據(jù)庫設(shè)計的,所以叫數(shù)據(jù)庫標記語言,接下來我們就想起的細品下她的美好。
DBML語法
- 表定義
- Table table_name {
- column_name column_type [column_settings]
- }
table_name:表名
column_name:字段名
column_type:字段類型
column_settings:字段的設(shè)置
- 字段定義
- Table buildings {
- ...
- address varchar(255) [unique, not null, note: 'to include unit number']
- id integer [ pk, unique, default: 123, note: 'Number' ]
- }
主鍵:primary key 或 pk
空/非空:null 或 not null
注釋:note
唯一索引:unique
默認值:default
- 索引定義
- Table bookings {
- id integer
- country varchar
- booking_date date
- created_at timestamp
- indexes {
- (id, country) [pk] // composite primary key
- created_at [note: 'Date']
- booking_date
- (country, booking_date) [unique]
- booking_date [type: hash]
- (`id*2`)
- (`id*3`,`getdate()`)
- (`id*3`,id)
- }
- }
主要分三種索引:
單字段索引、復合索引、表達式索引
- 外鍵關(guān)系定義
- //Long form
- Ref name_optional {
- table1.column1 < table2.column2
- }
- //Short form:
- Ref name_optional: table1.column1 < table2.column2
- // Inline form
- Table posts {
- id integer
- user_id integer [ref: > users.id]
- }
- 注釋
- // Inline form
使用雙斜杠即可
- 備注
- Table users {
- id int [pk]
- name varchar
- Note: 'This is a note of this table'
- // or
- Note {
- 'This is a note of this table'
- }
- }
- 枚舉
- enum job_status {
- created [note: 'Waiting to be processed']
- running
- done
- failure
- }
DBML工具
通過DBML可以讓表設(shè)計,通過純文本的方式,很方便的描述。那么,如果僅僅是這樣的,肯定不夠吸引,我猜你還希望
- DBML轉(zhuǎn)成SQL語句
- SQL語句轉(zhuǎn)換成DBML
- 可視化
當然了,這些DBML都給你提供了,先來看張圖

這個是所見即所得,在線工具。
至于DBML與SQL的互相轉(zhuǎn)化,DBML提供了基于node的命令工具dbml2sql、sql2dbml
總結(jié)
DBML是一個新型的數(shù)據(jù)庫設(shè)計工具,當然有人喜歡,有人吐槽,當然希望你能夠喜歡哈。軟件設(shè)計隨著時光的推進,很多新的理念被推出,作為程序員,當然是要不斷的吸收和轉(zhuǎn)化。