-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatadict_grt.py
332 lines (272 loc) · 8.6 KB
/
datadict_grt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# WB Datadict - MySQL Workbench plugin to generate data dictionaries.
#
# Public domain 2011 sirgazil. All rights waived.
import os
import datetime
import webbrowser
from wb import *
import grt
import mforms as gui
# CONSTANTS
# =========
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="author" content="WB Datadict">
<meta name="description" content="[PROJECTNAME] Data Dictionary.">
<title>[PROJECTNAME] Data Dictionary</title>
<script>
// Highlight table corresponding to the current fragment in the URL.
document.addEventListener("DOMContentLoaded", function(){
var tables = document.querySelectorAll("table");
document.querySelectorAll("nav a").forEach(function(link) {
link.addEventListener("click", function() {
// Remove all classes from tables.
tables.forEach(function(table) {
table.classList.remove("focused");
});
// Get a.href value and extract its fragment id.
// Highlight table using fragment id.
document.querySelector(this.hash).classList.add("focused");
});
});
});
</script>
<style type="text/css">
a {
text-decoration: none;
}
abbr {
cursor: help;
}
header {
color: #6A6A6A;
text-align: right;
}
table {
border-collapse: collapse;
margin-bottom: 30px;
width: 100%;
}
table caption {
font-size: 120%;
font-weight: bold;
}
table, td, th {
border-color: silver;
border-style: solid;
border-width: 1px;
}
caption {
color: black;
}
td, th {
padding: 1em;
}
tr:hover {
color: #333;
background-color: #F2F2F2;
}
th {
background-color: #F5F5F5;
}
td {
color: #6A6A6A;
}
ul {
font-style: italic;
}
.centered {
text-align: center;
}
.field {
color: #4C4C4C;
font-weight: bold;
}
.focused {
outline-color: aqua;
outline-style: solid;
outline-width: thin;
}
</style>
</head>
<body>
<header>
<h1>[PROJECTNAME]<br> Data Dictionary</h1>
<p>
<em>[EDITION]</em>
</p>
<p>
<em>[DESCRIPTION]</em>
</p>
</header>
[INDEX]
[MAIN]
</body>
</html>
"""
# PLUGIN
# ======
ModuleInfo = DefineModule(name="WB Datadict",
author="sirgazil",
version="1.1.0")
@ModuleInfo.plugin("my.plugin.create_datadict",
caption="Generate HTML Data Dictionary",
input=[wbinputs.currentCatalog()],
pluginMenu="Catalog")
@ModuleInfo.export(grt.INT, grt.classes.db_Catalog)
def create_datadict(catalog):
# Get default schema
schema = catalog.defaultSchema
# Get table objects and sort them alphabetically
tables = sorted(schema.tables, key=lambda table: table.name)
# Fill HTML template
markup = HTML_TEMPLATE
markup = markup.replace("[PROJECTNAME]", schema.name)
markup = markup.replace("[DESCRIPTION]", escape(schema.comment))
markup = markup.replace("[EDITION]", str(datetime.date.today()))
markup = markup.replace("[INDEX]", html_index(tables))
markup = markup.replace("[MAIN]", html_main(tables))
# Write the HTML file to disk (GUI Dialog)
doc_path = os.path.dirname(grt.root.wb.docPath)
dialog = gui.FileChooser(gui.SaveFile)
dialog.set_title("Save HTML data dictionary")
dialog.set_directory(doc_path)
response = dialog.run_modal()
file_path = dialog.get_path()
if response:
save(markup, file_path)
return 0
# HELPER FUNCTIONS
# ================
def column_as_html(column, table):
"""Return column as an HTML row."""
markup = "<tr>"
markup += "<td class='field'>{0}</td>".format(column.name)
markup += "<td>{0}</td>".format(column.formattedType)
# Check for Primary Key
if table.isPrimaryKeyColumn(column):
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
# Check for Foreign Key
if table.isForeignKeyColumn(column):
markup += "<td class='centered'><a href='#{0}'>✔</a></td>".format(column.name.replace("_id", ""))
else:
markup += "<td class='centered'> </td>"
# Check for Not Null attribute
if column.isNotNull == 1:
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
# Check for Unique attribute
if is_unique(column, table):
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
# Check for Binary, Unsigned and Zero Fill attributes
flags = list(column.flags)
if flags.count("BINARY"):
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
if flags.count("UNSIGNED"):
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
if flags.count("ZEROFILL"):
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
# Check for Auto Increment attribute
if column.autoIncrement == 1:
markup += "<td class='centered'>✔</td>"
else:
markup += "<td class='centered'> </td>"
# Default value
markup += "<td>{0}</td>".format(column.defaultValue)
# Comment
markup += "<td>{0}</td>".format(escape(column.comment))
markup += "</tr>"
return markup
def escape(text):
"""Return text as an HTML-safe sequence."""
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace('"', """)
text = text.replace("'", "'")
return text
def html_index(tables):
"""Return index of tables as HTML nav."""
markup = "<nav>"
markup += "<h2>Index</h2>"
markup += "<ul>"
for table in tables:
markup += "<li><a href='#{0}'>{0}</a></li>".format(table.name)
markup += "</ul></nav>"
return markup
def html_main(tables):
"""Return the main content of the HTML document."""
markup = "<div>"
for table in tables:
markup += table_as_html(table)
markup += "</div>"
return markup
def html_table_header():
"""Return the HTML row with header cells used in all tables."""
markup = ("<tr>" +
"<th>Column name</th>" +
"<th>DataType</th>" +
"<th><abbr title='Primary Key'>PK</abbr></th>" +
"<th><abbr title='Foreign Key'>FK</abbr></th>" +
"<th><abbr title='Not Null'>NN</abbr></th>" +
"<th><abbr title='Unique'>UQ</abbr></th>" +
"<th><abbr title='Binary'>BIN</abbr></th>" +
"<th><abbr title='Unsigned'>UN</abbr></th>" +
"<th><abbr title='Zero Fill'>ZF</abbr></th>" +
"<th><abbr title='Auto Increment'>AI</abbr></th>" +
"<th>Default</th>" +
"<th>Comment</th>" +
"</tr>")
return markup
def is_unique(column, table):
"""Return true if the column is UNIQUE."""
result = False
for index in table.indices:
if index.name == "{0}_UNIQUE".format(column.name):
result = True
break
return result
def save(html, path):
"""Save HTML to the given file system path."""
try:
html_file = open(path, "w")
except IOError:
text = "Could not open {0}.".format(path)
gui.Utilities.show_error("Error saving the file", text, "Ok", "", "")
else:
html_file.write(html)
html_file.close()
# Display success dialog
text = "The data dictionary was successfully generated."
gui.Utilities.show_message("WB Datadict", text, "Ok", "", "")
# Open HTML file in the Web browser
try:
webbrowser.open_new(path)
except webbrowser.Error:
print("Warning: Could not launch the Web browser " +
"to display the data dictionary saved in")
print(path)
def table_as_html(table):
"""Return table as an HTML table."""
markup = "<table id='{0}'>".format(table.name)
markup += "<caption>{0}</caption>".format(table.name)
markup += "<tr><td colspan='12'>{0}</td></tr>".format(escape(table.comment))
markup += html_table_header()
# Format column objects in HTML
for column in table.columns:
markup += column_as_html(column, table)
markup += "</table>"
return markup