Python

如何在 MySQL Workbench 中一次將列添加到多個表?

  • May 25, 2013

我有一個屬於 Ruby on Rails 應用程序的 MySQL Workbench 模型(圖表)。我現在需要在每個表中添加created_atupdated_at時間戳列。什麼是快速簡便的方法(而不是手動操作)?我的客戶不想使用 Rails 遷移,而是使用 Workbench 作為權威數據庫模式,所以我堅持在 Workbench 中執行此操作。

您可以在 MySQL Workbench 的 Scripting Shell 中使用此 Python 腳本。它是此處找到的腳本的改進版本:http: //mysqlworkbench.org/2012/06/mysql-workbench-script-for-adding-columns-to-all-tables-in-a-model/

# define your columns and types here
columns_types = {"created_at" : "DATETIME", "updated_at" : "DATETIME"}

# tables you want to skip
skip_tables = ["main_defs", "main_menu_items", "delayed_jobs", "delayed_job_workers", "delayed_job_logs"]



# 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:

   # skip the current table if it is in skip_tables
   if table.name in skip_tables:
       continue

   # iterate through all columns to be added
   for column_name, type in columns_types.items():

       # skip this column_name if there is already a column with this name
       column_names = [x.name for x in table.columns]
       if column_name in column_names:
           continue

       # create a new column object and set its name
       column = grt.classes.db_mysql_Column()
       column.name = column_name
       # add it to the table
       table.addColumn(column)
       # set the datatype of the column
       column.setParseType(type, None)

引用自:https://dba.stackexchange.com/questions/43042