Python 实现数据库更新脚本的生成方法

作者:jingxian 时间:2024-01-15 22:35:43 

我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪里,哪里添加了什么,这个真是非常让人头疼。因此我就试着用Python来实现自动的生成更新脚本,以免我这烂记性,记不住事。

主要操作如下:

1.在原先 basedao.py 中添加如下方法,这样旧能很方便的获取数据库的数据,为测试数据库和生产数据库做对比打下了基础。


def select_database_struts(self):
   '''
   查找当前连接配置中的数据库结构以字典集合
   '''
   sql = '''SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_TYPE, COLUMN_KEY, COLUMN_COMMENT
       FROM information_schema.`COLUMNS`
       WHERE TABLE_SCHEMA="%s" AND TABLE_NAME="{0}" '''%(self.__database)
   struts = {}
   for k in self.__primaryKey_dict.keys():
     self.__cursor.execute(sql.format(k))
     results = self.__cursor.fetchall()
     struts[k] = {}
     for result in results:
       struts[k][result[0]] = {}
       struts[k][result[0]]["COLUMN_NAME"] = result[0]
       struts[k][result[0]]["IS_NULLABLE"] = result[1]
       struts[k][result[0]]["COLUMN_TYPE"] = result[2]
       struts[k][result[0]]["COLUMN_KEY"] = result[3]
       struts[k][result[0]]["COLUMN_COMMENT"] = result[4]
   return self.__config, struts

2.编写对比的Python脚本


'''
数据库迁移脚本, 目前支持一下几种功能:
1.生成旧数据库中没有的数据库表执行 SQL 脚本(支持是否带表数据),生成的 SQL 脚本在 temp 目录下(表名.sql)。
2.生成添加列 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。
3.生成修改列属性 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。
4.生成删除列 SQL 脚本,生成的 SQL 脚本统一放在 temp 目录下的 depoyed.sql 中。
'''
import json, os, sys
from basedao import BaseDao

temp_path = sys.path[0] + "/temp"
if not os.path.exists(temp_path):
 os.mkdir(temp_path)

def main(old, new, has_data=False):
 '''
 @old 旧数据库(目标数据库)
 @new 最新的数据库(源数据库)
 @has_data 是否生成结构+数据的sql脚本
 '''
 clear_temp()  # 先清理 temp 目录
 old_config, old_struts = old
 new_config, new_struts = new
 for new_table, new_fields in new_struts.items():
   if old_struts.get(new_table) is None:
     gc_sql(new_config["user"], new_config["password"], new_config["database"], new_table, has_data)
   else:
     cmp_table(old_struts[new_table], new_struts[new_table], new_table)

def cmp_table(old, new, table):
 '''
 对比表结构生成 sql
 '''
 old_fields = old
 new_fields = new

sql_add_column = "ALTER TABLE `{TABLE}` ADD COLUMN `{COLUMN_NAME}` {COLUMN_TYPE} COMMENT '{COLUMN_COMMENT}';\n"
 sql_change_column = "ALTER TABLE `{TABLE}` CHANGE `{COLUMN_NAME}` `{COLUMN_NAME}` {COLUMN_TYPE} COMMENT '{COLUMN_COMMENT}';\n"
 sql_del_column = "ALTER TABLE `{TABLE}` DROP {COLUMN_NAME};"

if old_fields != new_fields:
   f = open(sys.path[0] + "/temp/deploy.sql", "a", encoding="utf8")
   content = ""
   for new_field, new_field_dict in new_fields.items():
     old_filed_dict = old_fields.get(new_field)
     if old_filed_dict is None:
       # 生成添加列 sql
       content += sql_add_column.format(TABLE=table, **new_field_dict)
     else:
       # 生成修改列 sql
       if old_filed_dict != new_field_dict:
         content += sql_change_column.format(TABLE=table, **new_field_dict)
       pass
   # 生成删除列 sql
   for old_field, old_field_dict in old_fields.items():
     if new_fields.get(old_field) is None:
       content += sql_del_column.format(TABLE=table, COLUMN_NAME=old_field)

f.write(content)
   f.close()

def gc_sql(user, pwd, db, table, has_data):
 '''
 生成 sql 文件
 '''
 if has_data:
   sys_order = "mysqldump -u%s -p%s %s %s > %s/%s.sql"%(user, pwd, db, table, temp_path, table)
 else:
   sys_order = "mysqldump -u%s -p%s -d %s %s > %s/%s.sql"%(user, pwd, db, table, temp_path, table)
 os.system(sys_order)

def clear_temp():
 '''
 每次执行的时候调用这个,先清理下temp目录下面的旧文件
 '''
 if os.path.exists(temp_path):
   files = os.listdir(temp_path)
   for file in files:
     f = os.path.join(temp_path, file)
     if os.path.isfile(f):
       os.remove(f)
 print("临时文件目录清理完成")

if __name__ == "__main__":
 test1_config = {
   "user" : "root",
   "password" : "root",
   "database" : "test1",
 }
 test2_config = {
   "user" : "root",
   "password" : "root",
   "database" : "test2",
 }

test1_dao = BaseDao(**test1_config)
 test1_struts = test1_dao.select_database_struts()

test2_dao = BaseDao(**test2_config)
 test2_struts = test2_dao.select_database_struts()

main(test2_struts, test1_struts)

目前只支持了4种SQL脚本的生成。

标签:python,数据库,生成脚本
0
投稿

猜你喜欢

  • vue 点击展开显示更多(点击收起部分隐藏)

    2024-05-29 22:47:56
  • 5款非常棒的Python工具

    2023-03-22 15:58:03
  • django用户注册、登录、注销和用户扩展的示例

    2021-09-09 13:11:05
  • python操作ini类型配置文件的实例教程

    2021-05-12 13:11:23
  • Go处理JSON数据的实现

    2024-02-23 07:44:42
  • MySQL数据库连接异常汇总(值得收藏)

    2024-01-22 16:23:55
  • centos 6.5下 mysql-community-server. 5.7.18-1.el6安装

    2024-01-15 14:54:26
  • Python中安装库的常用方法介绍

    2022-04-03 08:13:17
  • 完美解决phpdoc导出文档中@package的warning及Error的错误

    2023-10-07 10:07:49
  • 一文带你深入了解Go语言中切片的奥秘

    2024-04-28 10:46:25
  • python操作docx写入内容,并控制文本的字体颜色

    2023-11-25 03:14:33
  • Python详细介绍模型封装部署流程

    2023-03-27 00:49:32
  • Python Selenium异常处理的实例分析

    2021-01-12 17:13:06
  • 激发你的灵感:50个优秀的Favicons设计

    2007-10-21 19:52:00
  • python可视化分析的实现(matplotlib、seaborn、ggplot2)

    2021-10-20 13:59:21
  • Oracle也有注入漏洞

    2010-07-23 13:03:00
  • 20行Python代码实现一款永久免费PDF编辑工具

    2023-11-17 23:51:45
  • Python代码块及缓存机制原理详解

    2023-07-02 08:12:07
  • python 如何在list中找Topk的数值和索引

    2022-01-20 10:28:27
  • 直接生成XML的Google SiteMap的asp代码

    2007-08-17 13:44:00
  • asp之家 网络编程 m.aspxhome.com