MySQL Workbench: Script for adding columns to all tables in a model

June 7, 2012 – 6:31 pm by akojima

Here’s a quick Python script for adding columns for all tables in your EER model. This will create a create_time and update_time columns in all tables, but you can modify it to your needs. To execute:

  1. go to Scripting -> Scripting Shell…
  2. click the New Script toolbar icon at the top left corner
  3. select Python Script and specify some name for the script file
  4. click Create
  5. copy/paste the script there
  6. click the Execute toolbar button

Make sure to backup your model before running this!

The code

# get a reference to the schema in the model. This will get the 1st schema in it.
schema = grt.root.wb.doc.physicalModels[0].catalog.schemata[0]
# iterate through all tables
for table in schema.tables:
    # create a new column object and set its name
    column = grt.classes.db_mysql_Column()
    column.name = "create_time"
    # add it to the table
    table.addColumn(column)
    # set the datatype of the column
    column.setParseType("TIMESTAMP", None)
    column.defaultValue = "CURRENT_TIMESTAMP"

    # same thing for the update_time column
    column = grt.classes.db_mysql_Column()
    column.name = "update_time"
    table.addColumn(column)
    column.setParseType("TIMESTAMP", None)
Alfredo Kojima

  1. 3 Responses to “MySQL Workbench: Script for adding columns to all tables in a model”

  2. Hello,
    I had a problem with this script. Data Types were not parsed to tables. I created one more variable and all is OK.

    datatypes = grt.root.wb.rdbmsMgmt.rdbms[0].simpleDatatypes

    I used datatypes instead none in column.setParseType(“DATETIME”, datatypes)

    Petr Slavicek

    By Petr Slavicek on Jun 22, 2012

  3. How would one go about creating indexes? Is there documentation supporting this need?

    By Brandon on Dec 29, 2012

  1. 1 Trackback(s)

  2. Aug 19, 2012: How to write Python or Lau scripts in MySQL Workbench | MacLochlainns Weblog

You must be logged in to post a comment.