-
Notifications
You must be signed in to change notification settings - Fork 0
/
export-laravel-5-migrations.py
359 lines (313 loc) · 15.5 KB
/
export-laravel-5-migrations.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# -*- coding: utf-8 -*-
# MySQL Workbench module
# A MySQL Workbench plugin which exports a Model to Laravel 5 Migrations
# Written in MySQL Workbench 6.3.6
import re
import cStringIO
import grt
import mforms
import datetime
from grt.modules import Workbench
from wb import DefineModule, wbinputs
from workbench.ui import WizardForm, WizardPage
from mforms import newButton, newCodeEditor, FileChooser
ModuleInfo = DefineModule(name='GenerateLaravel5Migration',
author='Brandon Eckenrode',
version='0.1.2')
@ModuleInfo.plugin('wb.util.generateLaravel5Migration',
caption='Export Laravel 5 Migration',
input=[wbinputs.currentCatalog()],
groups=['Catalog/Utilities', 'Menu/Catalog'])
@ModuleInfo.export(grt.INT, grt.classes.db_Catalog)
def generateLaravel5Migration(cat):
def export_schema(out, schema, is_main_schema):
if len(schema.tables) == 0:
return
foreign_keys = {}
migration_tables = []
global migrations
for tbl in schema.tables:
migration_tables.append(tbl.name)
migrations[tbl.name] = []
migrations[tbl.name].append('<?php\n')
migrations[tbl.name].append('\n')
migrations[tbl.name].append('use Illuminate\Database\Schema\Blueprint;\n')
migrations[tbl.name].append('use Illuminate\Database\Migrations\Migration;\n')
migrations[tbl.name].append('\n')
components = tbl.name.split('_')
migrations[tbl.name].append('class Create%sTable extends Migration\n' % ("".join(x.title() for x in components[0:])))
migrations[tbl.name].append('{\n')
migrations[tbl.name].append(' /**\n')
migrations[tbl.name].append(' * Run the migrations.\n')
migrations[tbl.name].append(' *\n')
migrations[tbl.name].append(' * @return void\n')
migrations[tbl.name].append(' */\n')
migrations[tbl.name].append(' public function up()\n')
migrations[tbl.name].append(' {\n')
migrations[tbl.name].append(' Schema::create(\'%s\', function (Blueprint $table) {\n' % (tbl.name))
created_at = created_at_nullable = updated_at = updated_at_nullable = deleted_at = timestamps = timestamps_nullable = False
for col in tbl.columns:
if col.name == 'created_at':
created_at = True
if col.isNotNull != 1:
created_at_nullable = True
elif col.name == 'updated_at':
updated_at = True
if col.isNotNull != 1:
updated_at_nullable = True
if created_at is True and updated_at is True and created_at_nullable is True and updated_at_nullable is True:
timestamps_nullable = True
elif created_at is True and updated_at is True:
timestamps = True
for col in tbl.columns:
if (col.name == 'created_at' or col.name == 'updated_at') and (timestamps is True or timestamps_nullable is True):
continue
if col.name == 'deleted_at':
deleted_at = True
continue
if col.simpleType:
col_type = col.simpleType.name
col_flags = col.simpleType.flags
else:
col_type = col.userType.name
col_flags = col.flags
primary_key = [i for i in tbl.indices if i.isPrimary == 1]
primary_key = primary_key[0] if len(primary_key) > 0 else None
pk_column = None
if primary_key and len(primary_key.columns) == 1:
pk_column = primary_key.columns[0].referencedColumn
if col == pk_column:
if col_type == 'BIGINT':
col_type = 'BIGINCREMENTS'
else:
col_type = 'INCREMENTS'
col_data = '\''
if typesDict[col_type] == 'char':
if col.length > -1:
col_data = '\', %s' % (str(col.length))
elif typesDict[col_type] == 'decimal':
if col.precision > -1 and col.scale > -1:
col_data = '\', %s, %s' % (str(col.precision), str(col.scale))
elif typesDict[col_type] == 'double':
if col.precision > -1 and col.length > -1:
col_data = '\', %s, %s' % (str(col.length), str(col.precision))
elif typesDict[col_type] == 'enum':
col_data = '\', [%s]' % (col.datatypeExplicitParams[1:-1])
elif typesDict[col_type] == 'string':
if col.length > -1:
col_data = '\', %s' % (str(col.length))
if col.name == 'remember_token' and typesDict[col_type] == 'string' and str(col.length) == 100:
migrations[tbl.name].append(' $table->rememberToken();\n')
elif(typesDict[col_type]) :
migrations[tbl.name].append(' $table->%s(\'%s%s)' % (typesDict[col_type], col.name, col_data))
if typesDict[col_type] == 'integer' and 'UNSIGNED' in col.flags:
migrations[tbl.name].append('->unsigned()')
if col.isNotNull != 1:
migrations[tbl.name].append('->nullable()')
if col.defaultValue != '' and col.defaultValueIsNull != 0:
migrations[tbl.name].append('->default(NULL)')
elif col.defaultValue != '':
migrations[tbl.name].append('->default(%s)' % (col.defaultValue))
if col.comment != '':
migrations[tbl.name].append('->comment(\'%s\')' % (col.comment))
migrations[tbl.name].append(";")
migrations[tbl.name].append('\n')
if deleted_at is True:
migrations[tbl.name].append(' $table->softDeletes();\n')
if timestamps is True:
migrations[tbl.name].append(' $table->timestamps();\n')
elif timestamps_nullable is True:
migrations[tbl.name].append(' $table->nullableTimestamps();\n')
first_foreign_created = 0
for fkey in tbl.foreignKeys:
if fkey.name != '':
if fkey.referencedColumns[0].owner.name in migration_tables:
if first_foreign_created == 0:
migrations[tbl.name].append('\n')
first_foreign_created = 1
migrations[tbl.name].append(' $table->foreign(\'%s\')->references(\'%s\')->on(\'%s\')->onDelete(\'%s\')->onUpdate(\'%s\');' % (fkey.columns[0].name, fkey.referencedColumns[0].name, fkey.referencedColumns[0].owner.name, fkey.deleteRule.lower(), fkey.updateRule.lower()))
migrations[tbl.name].append('\n')
else:
if fkey.referencedColumns[0].owner.name not in foreign_keys:
foreign_keys[fkey.referencedColumns[0].owner.name] = []
foreign_keys[fkey.referencedColumns[0].owner.name].append({'table':fkey.columns[0].owner.name, 'name':fkey.columns[0].name, 'referenced_table':fkey.referencedColumns[0].owner.name, 'referenced_name':fkey.referencedColumns[0].name, 'update_rule':fkey.updateRule, 'delete_rule':fkey.deleteRule})
migrations[tbl.name].append(" });\n")
for fkey, fval in foreign_keys.iteritems():
if fkey == tbl.name:
keyed_tables = []
schema_table = 0
for item in fval:
if item['table'] not in keyed_tables:
keyed_tables.append(item['table'])
if schema_table == 0:
migrations[tbl.name].append('\n')
migrations[tbl.name].append(' Schema::table(\'%s\', function (Blueprint $table) {\n' % (item['table']))
schema_table = 1
migrations[tbl.name].append(' $table->foreign(\'%s\')->references(\'%s\')->on(\'%s\')->onDelete(\'%s\')->onUpdate(\'%s\');\n' % (item['name'], item['referenced_name'], item['referenced_table'], item['delete_rule'].lower(), item['update_rule'].lower()))
if schema_table == 1:
migrations[tbl.name].append(" });\n")
migrations[tbl.name].append('\n')
migrations[tbl.name].append(' }\n')
migrations[tbl.name].append('\n')
migrations[tbl.name].append(' /**\n')
migrations[tbl.name].append(' * Reverse the migrations.\n')
migrations[tbl.name].append(' *\n')
migrations[tbl.name].append(' * @return void\n')
migrations[tbl.name].append(' */\n')
migrations[tbl.name].append(' public function down()\n')
migrations[tbl.name].append(' {\n')
first_foreign_created = 0
for fkey in tbl.foreignKeys:
if fkey.name != '':
if fkey.referencedColumns[0].owner.name in migration_tables:
if first_foreign_created == 0:
migrations[tbl.name].append(' Schema::table(\'%s\', function (Blueprint $table) {\n' % (tbl.name))
first_foreign_created = 1
migrations[tbl.name].append(' $table->dropForeign([\'%s\']);\n' % (fkey.columns[0].name))
if first_foreign_created == 1:
migrations[tbl.name].append(" });\n")
migrations[tbl.name].append('\n')
for fkey, fval in foreign_keys.iteritems():
if fkey == tbl.name:
keyed_tables = []
schema_table = 0
for item in fval:
if item['table'] not in keyed_tables:
keyed_tables.append(item['table'])
if schema_table == 0:
migrations[tbl.name].append(' Schema::table(\'%s\', function (Blueprint $table) {\n' % (item['table']))
schema_table = 1
migrations[tbl.name].append(' $table->dropForeign([\'%s\']);\n' % (item['name']))
if schema_table == 1:
migrations[tbl.name].append(" });\n")
migrations[tbl.name].append('\n')
migrations[tbl.name].append(' Schema::drop(\'%s\');\n' % (tbl.name))
migrations[tbl.name].append(' }\n')
migrations[tbl.name].append('}')
return migrations
out = cStringIO.StringIO()
try:
for schema in [(s, s.name == 'main') for s in cat.schemata]:
migrations = export_schema(out, schema[0], schema[1])
except GenerateLaravel5MigrationError as e:
Workbench.confirm(e.typ, e.message)
return 1
for mkey in sorted(migrations):
out.write(''.join(migrations[mkey]))
out.write('\n\n\n')
sql_text = out.getvalue()
out.close()
wizard = GenerateLaravel5MigrationWizard(sql_text)
wizard.run()
return 0
class GenerateLaravel5MigrationError(Exception):
def __init__(self, typ, message):
self.typ = typ
self.message = message
def __str__(self):
return repr(self.typ) + ': ' + repr(self.message)
class GenerateLaravel5MigrationWizard_PreviewPage(WizardPage):
def __init__(self, owner, sql_text):
WizardPage.__init__(self, owner, 'Review Generated Migration(s)')
self.save_button = mforms.newButton()
self.save_button.enable_internal_padding(True)
self.save_button.set_text('Save Migration(s) to Folder...')
self.save_button.set_tooltip('Select the folder to save your migration(s) to.')
self.save_button.add_clicked_callback(self.save_clicked)
self.sql_text = mforms.newCodeEditor()
self.sql_text.set_language(mforms.LanguageMySQL)
self.sql_text.set_text(sql_text)
def go_cancel(self):
self.main.finish()
def create_ui(self):
button_box = mforms.newBox(True)
button_box.set_padding(8)
button_box.add(self.save_button, False, True)
self.content.add_end(button_box, False, False)
self.content.add_end(self.sql_text, True, True)
def save_clicked(self):
file_chooser = mforms.newFileChooser(self.main, mforms.OpenDirectory)
if file_chooser.run_modal() == mforms.ResultOk:
path = file_chooser.get_path()
text = self.sql_text.get_text(False)
i = 0
now = datetime.datetime.now()
for mkey in sorted(migrations):
try:
with open(path + '/%s_%s_%s_%s_create_%s_table.php' % (now.strftime('%Y'), now.strftime('%m'), now.strftime('%d'), str(i).zfill(6), mkey), 'w+') as f:
f.write(''.join(migrations[mkey]))
i = i + 1
except IOError as e:
mforms.Utilities.show_error(
'Save to File',
'Could not save to file "%s": %s' % (path, str(e)),
'OK')
class GenerateLaravel5MigrationWizard(WizardForm):
def __init__(self, sql_text):
WizardForm.__init__(self, None)
self.set_name('generate_laravel_5_migration_wizard')
self.set_title('Generate Laravel 5 Migration Wizard')
self.preview_page = GenerateLaravel5MigrationWizard_PreviewPage(self, sql_text)
self.add_page(self.preview_page)
migrations = {}
typesDict = {
'BIGINCREMENTS':'bigIncrements', \
'INCREMENTS':'increments', \
'TINYINT':'tinyInteger', \
'SMALLINT':'smallInteger', \
'MEDIUMINT':'mediumInteger', \
'INT':'integer', \
'BIGINT':'bigInteger', \
'FLOAT':'float', \
'DOUBLE':'double', \
'DECIMAL':'decimal', \
'CHAR':'char', \
'VARCHAR':'string', \
'BINARY':'binary', \
'VARBINARY':'', \
'TINYTEXT':'text', \
'TEXT':'text', \
'MEDIUMTEXT':'mediumText', \
'LONGTEXT':'longText', \
'TINYBLOB':'binary', \
'BLOB':'binary', \
'MEDIUMBLOB':'binary', \
'LONGBLOB':'binary', \
'DATETIME':'dateTime', \
'DATETIME_F':'dateTime', \
'DATE':'date', \
'DATE_F':'date', \
'TIME':'time', \
'TIME_F':'time', \
'TIMESTAMP':'timestamp', \
'TIMESTAMP_F':'timestamp', \
'YEAR':'smallInteger', \
'GEOMETRY':'', \
'LINESTRING':'', \
'POLYGON':'', \
'MULTIPOINT':'', \
'MULTILINESTRING':'', \
'MULTIPOLYGON':'', \
'GEOMETRYCOLLECTION':'', \
'BIT':'', \
'ENUM':'enum', \
'SET':'', \
'BOOLEAN':'boolean', \
'BOOL':'boolean', \
'FIXED':'', \
'FLOAT4':'', \
'FLOAT8':'', \
'INT1':'tinyInteger', \
'INT2':'smallInteger', \
'INT3':'mediumInteger', \
'INT4':'integer', \
'INT8':'bigint', \
'INTEGER':'integer', \
'LONGVARBINARY':'', \
'LONGVARCHAR':'', \
'LONG':'', \
'MIDDLEINT':'mediumInteger', \
'NUMERIC':'decimal', \
'DEC':'decimal', \
'CHARACTER':'char'
}