In particular it did not behave well with Rails style databases because of the following -
- Table names are plural
- Foreign keys are singular! E.g. a foreign key to table "Products" will be called "product_id"!
- Primary keys are always "id", regardless of the table name.
Well I recently discovered the "successor" to DBDesigner called MySQL Workbench. And amongst all the cool things it brings, the most important is its support for LUA scripting! Surely that can do some nifty things like add support for rails schemas! Alas a quick search on the net revealed no prior scripts I could use.
Now I'm knew zero percent Lua before today but a few minutes with the Lua cheat sheet got me up to speed! It is kind of like a mix between Python and C. I also found some handy prebuilt functions for Lua scripting here which really helped me understand the MySQL Workbench API (which is sadly enough mostly undocumented).
A few hours of hacking later I had the solution ready in the form of a script! Here are the steps to import a rails schema with all the relationships -
- Download the script
here. - Then run it by pressing Ctrl+Shift+R and selecting wb_library.lua from the location where you saved it.
- Make sure there are no errors in the output window.
- Reverse engineer your DB schema to get all the tables into an ER diagram. None of the tables will be related to each other die to the problems mentioned above. We'll fix that in a minute!
- Select "view > advanced > GRT shell" to open the shell which will allow you to invoke functions from the script.
- Now the semi-hard part. You need to get an object of your schema so that you can pass it to the script. Type the following in the shell - print(get_schema(1).name);. If this matches your database name then great! otherwise try print(get_schema(2).name); then print(get_schema(3).name); and so on till you find the index of your schema. (Remember that Lua is NOT zero indexed like usual programming languages. This means that there is no index 0). I'll assume that the correct index is 2.
- Type the following in the shell - sc = get_schema(2). Where 2 is the number you got in the previous step. Now the variable sc points to the correct schema.
- Now the final magic step! Type connect_all_rails_fk_relationships (sc); in the shell! Watch the magic happen!
PS: The script also includes a Lua port of the RoR inflectors (pluralise and singularise). Maybe those are useful independent of MySQL workbench. Check them out.
4 comments:
Kudos! Just what I was looking for, thanks you for sharing.
Very handy, thanks! I noticed it doesn't work with polymorphic associations but I guess there'd be no way to figure that out without looking at the code for the models.
Thank you!! Way cool!
Hey, the link is broken, can somebody upload it somewhere else?
Thanks!
Post a Comment