Advertisement
Guest User

Untitled

a guest
May 13th, 2017
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 25.42 KB | None | 0 0
  1. --
  2. -- PropelExport v0.5
  3. --
  4. -- The PropelExport Module allows you to export a catalog as propel xml-schema.
  5. -- Currently Propel 1.2 and 1.3 is fully supported. It should also work with Propel 1.4, however
  6. -- 1.4-specific features (such as behaviours) are not yet supported
  7. --
  8. --
  9. -- This Module is Copyright (c) 2008-2009 CN-Consult GmbH
  10. -- Author: Daniel Haas <daniel.haas@cn-consult.eu>
  11. --
  12. --
  13. -- This module is free software; you can redistribute it and/or modify
  14. -- it under the terms of the GNU General Public License as published by
  15. -- the Free Software Foundation; version 2 of the License.
  16. --
  17. --
  18. -- The module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  19. -- without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  20. -- See the GNU General Public License for more details.
  21. --
  22. --
  23. -- * IMPORTANT:
  24. -- * If you find BUGS in this module or have ideas for IMPROVEMENTS or PATCHES, dont hesitate
  25. -- * to contact me at daniel.haas@cn-consult.eu! Thanks!
  26. --
  27.  
  28. -- CHANGELOG:
  29. -- Version 0.1: Internal Version
  30. -- Version 0.2: First released Version
  31. -- Version 0.3: Added support for *TEXT columns (are converted to VARCHAR/LONGVARCHAR/CLOBs for propel)
  32. -- Version 0.4:
  33. --   * Added support to set database baseClass manually
  34. --   * Added support to set phpName per table manually
  35. --   * Added support for onDelete and onUpdate foreign key constraints (based on work by Antoine Noal aka Hvannentir)
  36. --   * DATETIME type is converted to TIMESTAMP type
  37. --   * size and scale support for DECIMAL columns (based on work by Antoine Noal aka Hvannentir)
  38. --   * support for multiple foreign key references (thanks for pointing that out Antoine!)
  39. -- Version 0.4.1: Fixed MEDIUMINT not being converted to INT for propel
  40. -- Version 0.5:
  41. --   * Works with Workbench 5.1
  42. --   * Added support for workbenchs user data types (This also fixes BOOLEANS appearing als UNKNOWN in WB 5.1)
  43. --     (Note: This does not work with user-types defining precision and scale, due to a Bug in Workbench)
  44. --   * Added support for Propel 1.3 defaultExpr
  45. --   * Add name-attribute to unique-tags and index-tags
  46. --   * Add size-attribute to unique- and index-tags only if a size is available
  47. --   Note: This is the last Version that will support Propel 1.2, newer releases will only support >=Propel 1.3 (default= will be replaced with defaultValue=)
  48.  
  49.  
  50. --
  51. -- standard module/plugin functions
  52. --
  53.  
  54. -- this function is called first by MySQL Workbench core to determine number of plugins in this module and basic plugin info
  55. -- see the comments in the function body and adjust the parameters as appropriate
  56. function getModuleInfo()
  57.     return {
  58.         name= "PropelExport",                     -- put your module name here; must be a valid identifier unique among
  59.                                                         -- all other plugin names
  60.         author= "CN-Consult GmbH",                  -- put your company name here
  61.         version= "1.0",                         -- put module version string in form major.minor
  62.         implements= "PluginInterface",          -- don't change this
  63.         functions= {
  64.                   "getPluginInfo:l<o@app.Plugin>:",     -- don't change this
  65.                   "exportPropelSchemaToClipboard:i:o@db.Catalog",   -- list all your plugin function names and accepted argument types,
  66.                   "exportPropelSchemaToFile:i:o@db.Catalog",
  67.                   "setPropelExportBaseClass:i:o@db.Catalog",
  68.                   "setPropelExportPhpName:i:o@db.Table"
  69.                                                         -- keeping the rest unchanged; in this example there's only one
  70.                                                         -- function, function name is PluginFunctionName and argument type
  71.                                                         -- is db.Catalog
  72.         }
  73.     }
  74. end
  75.  
  76.  
  77. -- helper function to create a descriptor for an argument of a specific type of object
  78. -- you don't need to change here anything
  79. function objectPluginInput(type)
  80.     return grtV.newObj("app.PluginObjectInput", {objectStructName= type})
  81. end
  82.  
  83. -- this function is called by MySQL Workbench core after a successful call to getModuleInfo()
  84. -- to gather information about the plugins in this module and the functions that the plugins expose;
  85. -- a plugin should expose only one function that will handle a menu command for a class of objects
  86. -- see the comments in the function body and adjust the parameters as appropriate
  87. function getPluginInfo()
  88.     local l
  89.     local plugin
  90.  
  91.     -- create the list of plugins that this module exports
  92.     l= grtV.newList("object", "app.Plugin")
  93.  
  94.     -- create a new app.Plugin object for every plugin
  95.     plugin= grtV.newObj("app.Plugin", {
  96.         name= "wb.catalog.util.exportPropelSchemaToClipboard",      -- plugin namespace
  97.         caption= "PropelExport: Copy Catalog as Propel-Schema to Clipboard",                 -- plugin textual description (will appear as menu item name)
  98.         moduleName= "PropelExport",                         -- this should be in sync with what you sepcified previously for module
  99.                                                             -- name in getModuleInfo()
  100.         pluginType= "normal",                            -- don't change this
  101.         moduleFunctionName= "exportPropelSchemaToClipboard",        -- the function that this plugin exposes
  102.         inputValues= {objectPluginInput("db.Catalog")},  -- the type of object
  103.         rating= 100,                                     -- don't change this
  104.         showProgress= 0,                                 -- don't change this
  105.         groups= {"Catalog/Utilities", "Menu/Catalog"}  -- use "Catalog/Utilities" to show the menu item on the overview page,
  106.                                                                  -- or "Model/Utilities" to show the menu item on the canvas;
  107.                                                                  -- the "Menu/*" entries control how the plugin will appear in main menu
  108.                                                                  -- the possible values for it are "Menu/Model", "Menu/Catalog", "Menu/Objects",
  109.                                                                  -- "Menu/Database", "Menu/Utilities"
  110.     })
  111.  
  112.     -- fixup owner
  113.     plugin.inputValues[1].owner= plugin
  114.  
  115.     -- add to the list of plugins
  116.     grtV.insert(l, plugin)
  117.  
  118.  
  119.  
  120.  
  121.     -- create a new app.Plugin object for every plugin
  122.     plugin= grtV.newObj("app.Plugin", {
  123.         name= "wb.catalog.util.exportPropelSchemaToFile",      -- plugin namespace
  124.         caption= "PropelExport: Export Catalog as Propel-Schema to File",                 -- plugin textual description (will appear as menu item name)
  125.         moduleName= "PropelExport",                        -- this should be in sync with what you sepcified previously for module
  126.                                                                  -- name in getModuleInfo()
  127.         pluginType= "normal",                            -- don't change this
  128.         moduleFunctionName= "exportPropelSchemaToFile",        -- the function that this plugin exposes
  129.         inputValues= {objectPluginInput("db.Catalog")},  -- the type of object
  130.         rating= 100,                                     -- don't change this
  131.         showProgress= 0,                                 -- don't change this
  132.         groups= {"Catalog/Utilities", "Menu/Catalog"}  -- use "Catalog/Utilities" to show the menu item on the overview page,
  133.                                                                  -- or "Model/Utilities" to show the menu item on the canvas;
  134.                                                                  -- the "Menu/*" entries control how the plugin will appear in main menu
  135.                                                                  -- the possible values for it are "Menu/Model", "Menu/Catalog", "Menu/Objects",
  136.                                                                  -- "Menu/Database", "Menu/Utilities"
  137.     })
  138.  
  139.     -- fixup owner
  140.     plugin.inputValues[1].owner= plugin
  141.  
  142.     -- add to the list of plugins
  143.     grtV.insert(l, plugin)
  144.  
  145.  
  146.  
  147.  
  148.     -- create a new app.Plugin object for every plugin
  149.     plugin= grtV.newObj("app.Plugin", {
  150.         name= "wb.catalog.util.setPropelExportBaseClass",
  151.         caption= "PropelExport: Set custom baseClass",
  152.         moduleName= "PropelExport",
  153.         pluginType= "normal",
  154.         moduleFunctionName= "setPropelExportBaseClass",
  155.         inputValues= {objectPluginInput("db.Catalog")},
  156.         rating= 100,
  157.         showProgress= 0,
  158.         groups= {"Catalog/Utilities", "Menu/Catalog"}
  159.     })
  160.  
  161.     -- fixup owner
  162.     plugin.inputValues[1].owner= plugin
  163.  
  164.     -- add to the list of plugins
  165.     grtV.insert(l, plugin)
  166.  
  167.  
  168.  
  169.     -- create a new app.Plugin object for every plugin
  170.     plugin= grtV.newObj("app.Plugin", {
  171.         name= "wb.table.util.setPropelExportPhpName",
  172.         caption= "PropelExport: Set custom phpName",
  173.         moduleName= "PropelExport",
  174.         pluginType= "normal",
  175.         moduleFunctionName= "setPropelExportPhpName",
  176.         inputValues= {objectPluginInput("db.Table")},
  177.         rating= 100,
  178.         showProgress= 0,
  179.         groups= {"Catalog/Utilities", "Menu/Table"}
  180.     })
  181.     -- fixup owner
  182.     plugin.inputValues[1].owner= plugin
  183.  
  184.     -- add to the list of plugins
  185.     grtV.insert(l, plugin)
  186.  
  187.     return l
  188. end
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195. -- Some needed definitions for the XMLWriter "class" (metatable)
  196. XMLWriter = {}
  197. XMLWriter_mt = {}
  198. XMLWriter_mt.__index = XMLWriter
  199.  
  200. -- This is a very simplistic xml-serializer "class" in lua
  201. -- With this method you create a new xmlwriter.
  202. -- You have to at least pass the _rootTag
  203. function XMLWriter:new(_rootTag,_encoding)
  204.     xmlwriter={
  205.         rootTag=_rootTag,
  206.         encoding = _encoding or 'UTF-8',
  207.         xml='',
  208.         state='',
  209.         openedTags={},
  210.         newline='',
  211.         indent='',
  212.         useIndent=false
  213.     }
  214.     setmetatable(xmlwriter,XMLWriter_mt)
  215.     xmlwriter:start()
  216.     return xmlwriter
  217. end
  218.  
  219. -- Start a new xml document
  220. function XMLWriter:start()
  221.     self.xml='<?xml version="1.0" encoding="'..self.encoding..'"?>\n'
  222.     self.state='documentOpen'
  223.     self.xml=self.xml..'<'..self.rootTag
  224. end
  225.  
  226. -- Use this method to enable indenting the generated xml-code
  227. -- Otherwise the xml is generated all on one line
  228. function XMLWriter:enableIndent()
  229.     self.useIndent=true
  230.     self.newline='\n'
  231. end
  232.  
  233. -- Internal method for pretty indenting
  234. function XMLWriter:increaseIndent()
  235.     if (self.useIndent==true) then
  236.         local indent=string.len(self.indent)
  237.         self.indent=string.rep(' ',indent+2)
  238.     end
  239. end
  240.  
  241. -- Internal method for pretty indenting
  242. function XMLWriter:decreaseIndent()
  243.     if (self.useIndent==true) then
  244.         local indent=string.len(self.indent)
  245.         if (indent<2) then indent=2 end
  246.         self.indent=string.rep(' ',indent-2)
  247.     end
  248. end
  249.  
  250. -- begin a new tag with the given name
  251. -- To add attributes to the tag use addAttribute().
  252. -- Use addContent() to add content to the tag, or openTag() to add subtags.
  253. function XMLWriter:openTag(_tagname)
  254.     if (self.state~='tagClosed' and self.state~='insideTag') then self.increaseIndent(self) end
  255.     if (_tagname) then
  256.         if (self.state=='documentOpen' or self.state=='tagOpen' or self.state=='subTagOpen') then
  257.             self.xml=self.xml..'>'..self.newline
  258.         end
  259.         self.xml=self.xml..self.indent..'<'.._tagname..''
  260.         self.openedTags[#self.openedTags+1]=_tagname
  261.         if (self.state=='tagOpen') then
  262.             self.state='subTagOpen'
  263.         else
  264.             self.state='tagOpen'
  265.         end
  266.     else
  267.         print("You have to pass a tagname when you open a tag!")
  268.     end
  269. end
  270.  
  271. -- Add an attribute to the currently open tag
  272. -- Note: this method may not be called when you added content to the tag already
  273. function XMLWriter:addAttribute(_name, _value)
  274.     if (self.state=='tagOpen' or self.state=='subTagOpen' or self.state=='documentOpen') then
  275.         self.xml=self.xml..' '.._name..'="'.._value..'"'
  276.     end
  277. end
  278.  
  279. -- Add content (cdata) to the currently open tag
  280. -- Note: When adding content to a tag, you may not add attributes anymore to the tag
  281. function XMLWriter:addContent(_content)
  282.     if (self.state=='tagOpen' or self.state=='subTagOpen') then
  283.         self.xml=self.xml..'>'
  284.         self.state='insideTag'
  285.     end
  286.     self.xml=self.xml.._content;
  287.  
  288. end
  289.  
  290. -- Close a previously opened tag
  291. function XMLWriter:closeTag()
  292.     if (self.state=='tagOpen' or self.state=='subTagOpen') then
  293.         self.xml=self.xml..'/>'..self.newline
  294.         self.openedTags[#self.openedTags]=nil
  295.         if (#self.openedTags==0) then
  296.             self.state='tagClosed'
  297.         else
  298.             self.state='insideTag'
  299.         end
  300.     else if (self.state=='insideTag') then
  301.         self.decreaseIndent(self)
  302.         self.xml=self.xml..self.indent..'</'..self.openedTags[#self.openedTags]..'>'..self.newline
  303.         self.openedTags[#self.openedTags]=nil
  304.         if (#self.openedTags==0) then self.state='tagClosed' end
  305.  
  306.     end
  307.     end
  308.  
  309. end
  310.  
  311. -- Finishes the document
  312. -- This means closing the root tag
  313. function XMLWriter:finishDocument()
  314.     if (#self.openedTags > 0) then
  315.         print("You still have opened tags!")
  316.     else
  317.         if (self.state=='documentOpen') then self.xml=self.xml..'>'..self.newline end
  318.         self.xml=self.xml..'</'..self.rootTag..'>\n'
  319.     end
  320.     self.xml=self.xml..'FINISH'
  321. end
  322.  
  323. -- Return the XML of the generated document
  324. function XMLWriter:getXML()
  325.     return self.xml
  326. end
  327.  
  328.  
  329.  
  330.  
  331. -- Test method which tests the XML Serializer
  332. function testXml(catalog)
  333.     print('This is lua Version '.._VERSION)
  334.     local xml=XMLWriter:new('database')
  335.     xml:enableIndent()
  336.     xml:addAttribute("cool","ness")
  337.     xml:openTag('test')
  338.     xml:closeTag()
  339.     xml:openTag('cool')
  340.         xml:addAttribute('master','commander')
  341.     xml:closeTag()
  342.     xml:openTag('multi')
  343.         xml:addAttribute('master','commander')
  344.         xml:addContent('Mycontent')
  345.     xml:closeTag()
  346.  
  347.     xml:openTag('aaaargh')
  348.         xml:addAttribute('thelast','test')
  349.         xml:openTag('subtag')
  350.             xml:addAttribute('subattrib','value')
  351.         xml:closeTag()
  352.     xml:closeTag()
  353.  
  354.     xml:finishDocument()
  355.  
  356.     print (xml:getXML())
  357. end
  358.  
  359.  
  360.  
  361.  
  362.  
  363.  
  364.  
  365. ------------------------------
  366. --- PropelExport util methods:
  367. ------------------------------
  368.  
  369. --
  370. -- Print some version information and copyright to the output window
  371. function printVersion()
  372.     print("\n\n\nThis is PropelExport v0.5\nCopyright (c) 2008-2009 CN-Consult GmbH")
  373. end
  374.  
  375.  
  376. --
  377. -- Convert workbench simple types to propel types
  378. function wbSimpleType2PropelDatatype(simpleType)
  379.  
  380.   -- local propelType="**UNKNOWN** ("..simpleType.name..")"
  381.   -- We assume that the simpleType corresponds to the propel type by default
  382.   -- This is correct 95% of the time
  383.   if (simpleType~=nil) then
  384.  
  385.       local propelType=simpleType.name
  386.  
  387.       -- convert INT to INTEGER
  388.       if (simpleType.name=="INT" or simpleType.name=="MEDIUMINT") then
  389.         propelType = "INTEGER"
  390.       end
  391.  
  392.       -- convert text types to CLOBs
  393.       if (simpleType.name=="TINYTEXT") then
  394.         propelType = "VARCHAR"
  395.       end
  396.       if (simpleType.name=="TEXT") then
  397.         propelType = "LONGVARCHAR"
  398.       end
  399.       if (simpleType.name=="MEDIUMTEXT") then
  400.         propelType = "CLOB"
  401.       end
  402.       if (simpleType.name=="LONGTEXT") then
  403.         propelType = "CLOB"
  404.       end
  405.  
  406.       -- convert DATETIME TO TIMESTAMP (this will be converted back to DATETIME by Propel 1.3)
  407.       if (simpleType.name=="DATETIME") then
  408.         propelType = "TIMESTAMP"
  409.       end
  410.  
  411.  
  412.     return propelType
  413.   else
  414.     return "EMPTY SIMPLETYPE"
  415.   end
  416. end
  417.  
  418. --
  419. -- Tries to convert workbench user types to propel types
  420. function wbUserType2PropelDatatype(userType)
  421.  
  422.   -- local propelType="**UNKNOWN** ("..simpleType.name..")"
  423.   -- We assume that the simpleType corresponds to the propel type by default
  424.   -- This is correct 95% of the time
  425.   if (userType~=nil) then
  426.  
  427.       local propelType=""
  428.  
  429.       -- convert MySQL Workbench defined user-types to Propel-Types
  430.       if (userType.name=="BOOL") then
  431.         propelType = "BOOLEAN"
  432.       end
  433.       if (userType.name=="BOOLEAN") then
  434.         propelType = "BOOLEAN"
  435.       end
  436.  
  437.       -- if you have custom mappings you could add cases for them here:
  438.  
  439.  
  440.       -- Check if we found a conversion, if not use the simple-type converter with the actual definition of the user-type
  441.       if (propelType=="") then
  442.         propelType=wbSimpleType2PropelDatatype(userType.actualType)
  443.       end
  444.  
  445.     return propelType
  446.   else
  447.     return "EMPTY USERTYPE"
  448.   end
  449. end
  450.  
  451.  
  452. --
  453. -- converts unusable characters to underscores
  454. function sanitizeName(name)
  455.     local newName= name.gsub(name,'%-','_')
  456.     local newName2=string.gsub(newName,'%s+',"_")
  457.     return newName2;
  458. end
  459.  
  460.  
  461.  
  462.  
  463. --
  464. -- Takes a catalog object and converts it to a propel xml-schema
  465. -- This method is called from the two plugin entry-points to generate the actual schema
  466. function geneneratePropelSchemaFromCatalog(catalog)
  467.   local xml=XMLWriter:new('database')
  468.   xml:enableIndent()
  469.  
  470.   local firstSchema = catalog.schemata[1]
  471.  
  472.   xml:addAttribute("defaultIdMethod","native")
  473.   xml:addAttribute("name",firstSchema.name)
  474.  
  475.   if (catalog.customData["propelExportBaseClass"]~= nil) then
  476.     xml:addAttribute("baseClass",catalog.customData["propelExportBaseClass"]);
  477.   end
  478.  
  479.  
  480.   -- go through all tables:
  481.     for i = 1, grtV.getn(catalog.schemata) do
  482.         schema = catalog.schemata[i]
  483.         --print(getListItemByObjName("db.catalog", "Foreign"))
  484.         --currentRelation = sc
  485.        
  486.        
  487.         for j = 1, grtV.getn(schema.tables) do
  488.             currentTable = schema.tables[j]
  489.             xml:openTag('table')
  490.                 xml:addAttribute('name',currentTable.name)
  491.            
  492.  
  493.             if (currentTable.customData["phpName"]~=nil)
  494.             then
  495.                 xml:addAttribute('phpName',currentTable.customData["phpName"]);
  496.             end
  497.  
  498.             -- now fetch all columns:
  499.             for k = 1, grtV.getn(currentTable.columns) do
  500.                 currentColumn=currentTable.columns[k]
  501.                 local propelType=''
  502.                 xml:openTag('column')
  503.                     xml:addAttribute('name',currentColumn.name)
  504.  
  505.                     if (currentColumn.simpleType~=nil)
  506.                     then
  507.                         propelType=wbSimpleType2PropelDatatype(currentColumn.simpleType)
  508.                     else
  509.                         propelType=wbUserType2PropelDatatype(currentColumn.userType)
  510.                     end
  511.  
  512.                     xml:addAttribute('type',propelType)
  513.  
  514.                     if (currentColumn.length~=-1) then
  515.                         xml:addAttribute('size',currentColumn.length)
  516.                     end
  517.  
  518.                     local columnType=nil;
  519.                     if (currentColumn.simpleType~=nil)
  520.                     then columnType=currentColumn.simpleType
  521.                     else columnType=currentColumn.userType.actualType end
  522.  
  523.  
  524.                     if (propelType=="CLOB" or propelType=="VARCHAR") then
  525.                         if     (columnType.name=="TINYTEXT")    then xml:addAttribute('size',255);
  526.                         elseif (columnType.name=="MEDIUMTEXT")then xml:addAttribute('size',16777215);
  527.                         elseif (columnType.name=="LONGTEXT")    then xml:addAttribute('size',4294967295); end
  528.                     elseif (columnType.name=="DECIMAL") then
  529.                         xml:addAttribute('size',currentColumn.precision);
  530.                         xml:addAttribute('scale',currentColumn.scale);
  531.                     end
  532.  
  533.  
  534.                     -- try to find out if this is the primary key column
  535.                     for k = 1, grtV.getn(currentTable.indices) do
  536.                         index=currentTable.indices[k]
  537.                         if (index.indexType=="PRIMARY") then
  538.                             for l=1, grtV.getn(index.columns) do
  539.                                 column=index.columns[l]
  540.                                 if (column.referencedColumn.name==currentColumn.name) then
  541.                                     xml:addAttribute('primaryKey','true')
  542.                                 end
  543.                             end
  544.                         end
  545.                     end
  546.  
  547.                     if (currentColumn.isNotNull==1) then
  548.                         xml:addAttribute('required','true')
  549.                     end
  550.                     -- add a default value if available
  551.                     if (currentColumn.defaultValue~='' and currentColumn.defaultValue~='CURRENT_TIMESTAMP') then
  552.                         xml:addAttribute('default',currentColumn.defaultValue)
  553.                     end
  554.                     -- add Propel 1.3 defaultExpr
  555.                     if (currentColumn.defaultValue~="") then
  556.                         xml:addAttribute('defaultExpr',currentColumn.defaultValue)
  557.                         -- print ("Default Value:"..currentColumn.defaultValue.."\n")
  558.                     end
  559.                     if (currentColumn.autoIncrement==1) then
  560.                         xml:addAttribute('autoIncrement','true')
  561.                     end
  562.                     if (currentColumn.comment~='') then
  563.                         xml:addAttribute('description',currentColumn.comment)
  564.                     end
  565.                 xml:closeTag()
  566.             end
  567.             -- add foreign keys:
  568.             for k = 1, grtV.getn(currentTable.foreignKeys) do
  569.                 foreignKey=currentTable.foreignKeys[k]
  570.                 --print (foreignKey)
  571.                 xml:openTag('foreign-key')
  572.                     xml:addAttribute('name',sanitizeName(foreignKey.name))
  573.                     xml:addAttribute('foreignTable',foreignKey.referencedTable.name)
  574.                     if(foreignKey.deleteRule~="" and foreignKey.deleteRule~="NO ACTION") then
  575.                         xml:addAttribute('onDelete',string.lower(foreignKey.deleteRule))
  576.                     end
  577.                     if(foreignKey.updateRule~="" and foreignKey.updateRule~="NO ACTION") then
  578.                         xml:addAttribute('onUpdate',string.lower(foreignKey.updateRule))
  579.                     end
  580.                     for l=1, grtV.getn(foreignKey.columns) do
  581.                         xml:openTag('reference')
  582.                             xml:addAttribute('local',foreignKey.columns[l].name)
  583.                             xml:addAttribute('foreign',foreignKey.referencedColumns[l].name)
  584.                             xml:addAttribute('coment' ,foreignKey.referencedColumns[l].comment )
  585.                             --print (foreignKey.columns[l])
  586.                         xml:closeTag()
  587.                     end
  588.                 xml:closeTag()
  589.             end
  590.             -- add unique keys:
  591.             for k = 1, grtV.getn(currentTable.indices) do
  592.                 index=currentTable.indices[k]
  593.                 if (index.indexType=="UNIQUE") then
  594.                     xml:openTag('unique')
  595.                     xml:addAttribute('name',sanitizeName(index.name))
  596.                     for l=1, grtV.getn(index.columns) do
  597.                         column=index.columns[l]
  598.                         xml:openTag('unique-column')
  599.                             xml:addAttribute('name',column.referencedColumn.name)
  600.                             if (column.referencedColumn.length>0) then xml:addAttribute('size',column.referencedColumn.length) end
  601.                         xml:closeTag()
  602.                     end
  603.                     xml:closeTag()
  604.                 end
  605.             end
  606.             -- add remaining indices
  607.             for k = 1, grtV.getn(currentTable.indices) do
  608.                 index=currentTable.indices[k]
  609.                 if (index.indexType=="INDEX") then
  610.                     xml:openTag('index')
  611.                     xml:addAttribute('name',sanitizeName(index.name))
  612.                     for l=1, grtV.getn(index.columns) do
  613.                         column=index.columns[l]
  614.                         xml:openTag('index-column')
  615.                             xml:addAttribute('name',column.referencedColumn.name)
  616.                         xml:closeTag()
  617.                     end
  618.                     xml:closeTag()
  619.                 end
  620.             end
  621.             xml:closeTag()
  622.         end
  623.        
  624.         for bla = 1, grtV.getn(schema.relationships) do
  625.            --currentRelation = schema.relationship[bla]
  626.            print("IHELO!")
  627.         end
  628.        
  629.     end
  630.   --print (catalog.schemata)
  631.   xml:finishDocument()
  632.   return xml:getXML();
  633.  
  634. end
  635.  
  636.  
  637.  
  638.  
  639.  
  640.  
  641.  
  642.  
  643.  
  644.  
  645.  
  646.  
  647.  
  648.  
  649.  
  650.  
  651. ------------------
  652. -- Plugin methods:
  653. ------------------
  654.  
  655.  
  656.  
  657.  
  658. --
  659. -- Export the propel-schema of the selected catalog to the clipboard
  660. -- This is the main plugin method which is called from the menu
  661. function exportPropelSchemaToClipboard(catalog)
  662.   printVersion();
  663.  
  664.   local propelSchema=geneneratePropelSchemaFromCatalog(catalog);
  665.   --  print ("Propel-Schema looks like this:\n")
  666.   --  print(propelSchema);
  667.  
  668.   Workbench:copyToClipboard(propelSchema)
  669.   print('\n > Propel-Schema was copied to clipboard');
  670.   return 0
  671. end
  672.  
  673.  
  674.  
  675.  
  676.  
  677. --
  678. -- Export the propel-schema of the selected catalog to the a filename
  679. -- This is the main plugin method which is called from the menu
  680. function exportPropelSchemaToFile(catalog)
  681.   --printVersion();
  682.  
  683.   local propelSchema=geneneratePropelSchemaFromCatalog(catalog);
  684.   --  print ("Propel-Schema looks like this:\n")
  685.   --  print(propelSchema);
  686.  
  687.   if (catalog.customData["propelExportPath"] ~= nil) then
  688.     -- print("\nFilepath is: "..catalog.customData["propelExportPath"]);
  689.     if (Workbench:confirm("Proceed?","Do you want to overwrite previously exported file "..catalog.customData["propelExportPath"].." ?") == 1)
  690.     then
  691.         propelExportPath=catalog.customData["propelExportPath"];
  692.     else
  693.         propelExportPath=Workbench:input('Filename? Please enter Filename to export the propel schema to');
  694.         if (propelExportPath~="")
  695.         then
  696.             -- Try to save the filepath for the next time:
  697.             catalog.customData["propelExportPath"]=propelExportPath;
  698.         end
  699.     end
  700.   else
  701.     propelExportPath=Workbench:input('Filename? Please enter Filename to export the propel schema to');
  702.     if (propelExportPath~="")
  703.     then
  704.         -- Try to save the filepath for the next time:
  705.         catalog.customData["propelExportPath"]=propelExportPath;
  706.     end
  707.   end
  708.  
  709.   if propelExportPath~='' then
  710.     f = io.open(propelExportPath,"w");
  711.     if (f~=nil) then
  712.         f.write(f,propelSchema);
  713.         f.close(f);
  714.         print('\n > Propel-Schema was exported to '..propelExportPath);
  715.     else
  716.         print('\n > Could not open file '..propelExportPath..'!');
  717.     end
  718.   else
  719.     print('\n > Propel-Schema was NOT exported as no path was given!');
  720.   end
  721.  
  722.   return 0
  723. end
  724.  
  725.  
  726. --
  727. -- Set a custom baseClass to be added to the database tag of the resulting schema file.
  728. -- This is saved inside the workbench file, so on subsequent exports it is reused.
  729. function setPropelExportBaseClass(catalog)
  730.     printVersion();
  731.     print("Setting baseClass...");
  732.  
  733.     local question="New baseClass?";
  734.     if (catalog.customData["propelExportBaseClass"]~=nil) then
  735.         question = question .. " (" .. catalog.customData["propelExportBaseClass"] ..")"
  736.     end
  737.     propelExportBaseClass=Workbench:input(question);
  738.  
  739.         if (propelExportBaseClass==" ")
  740.         then
  741.             -- Remove the previously set base-class
  742.             catalog.customData["propelExportBaseClass"]=nil;
  743.         elseif (propelExportBaseClass~="")
  744.         then
  745.             -- Try to save the base-class
  746.             catalog.customData["propelExportBaseClass"]=propelExportBaseClass;
  747.         end
  748.     print ("done");
  749. end
  750.  
  751.  
  752.  
  753.  
  754. --
  755. -- Sets a custom phpName for a table.
  756. -- If you want to unset the phpName, enter a single space as phpName
  757. function setPropelExportPhpName(_table)
  758.     printVersion();
  759.     print("Setting phpName of " .. _table.name);
  760.  
  761.     local question="New phpName?";
  762.     if (_table.customData["phpName"]~=nil) then
  763.         question = question .. " (" .. _table.customData["phpName"] ..")";
  764.     end
  765.     phpName=Workbench:input(question);
  766.  
  767.     if (phpName==" ")
  768.     then
  769.         -- Remove the previously set phpName
  770.         _table.customData["phpName"]=nil;
  771.     elseif (phpName~="")
  772.     then
  773.         -- Try to save the phpName
  774.         _table.customData["phpName"]=phpName;
  775.     end
  776.  
  777.     --this is a trick to let MySQL Workbench believe there are changes in the file:
  778.     _table.owner.owner.owner.customData["phpName".._table.name]="set";
  779.     print ("done");
  780. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement