mysql转达梦的python脚本

mysql_ddl:

sql 复制代码
CREATE TABLE `ops_app_import` (
  `id` char(32) NOT NULL COMMENT '主键ID',
  `pkg_name` varchar(255) NOT NULL DEFAULT '' COMMENT '导入包名称',
  `pkg_md5` varchar(32) NOT NULL COMMENT '导入包md5值',
  `backup_pkg_name` varchar(255) DEFAULT '' COMMENT '备份包名称',
  `backup_pkg_md5` varchar(32) DEFAULT '' COMMENT '备份包md5值',
  `process_status` varchar(32) DEFAULT '' COMMENT '处理状态',
  `comment` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
  `creator_id` char(32) DEFAULT '0' COMMENT '创建者ID',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用导入包';

dameng_ddl:

sql 复制代码
CREATE TABLE "ops_app_import" (
  "id" char(32) NOT NULL COMMENT '主键ID',
  "pkg_name" varchar(255) NOT NULL DEFAULT '' COMMENT '导入包名称',
  "pkg_md5" varchar(32) NOT NULL COMMENT '导入包md5值',
  "backup_pkg_name" varchar(255) DEFAULT '' COMMENT '备份包名称',
  "backup_pkg_md5" varchar(32) DEFAULT '' COMMENT '备份包md5值',
  "process_status" varchar(32) DEFAULT '' COMMENT '处理状态',
  "comment" varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
  "creator_id" char(32) DEFAULT '0' COMMENT '创建者ID',
  "gmt_create" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  "gmt_modified" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP  COMMENT '修改时间',
  PRIMARY KEY ("id")
);

脚本:

python 复制代码
index_sql_list = []


def replaceKey(line, currTable):
    indexColumnStart = line.index("(")
    indexColumnEnd = line.index(")")
    if (line.lstrip().upper().startswith("KEY")):
        indexSql = f"CREATE INDEX {line.lstrip()[4: indexColumnStart - 2]} ON {currTable}({line[indexColumnStart + 1: indexColumnEnd]});"
    else:
        indexSql = f"CREATE UNIQUE INDEX {line.lstrip()[11: indexColumnStart - 2]} ON {currTable}({line[indexColumnStart + 1: indexColumnEnd]});"
    index_sql_list.append(indexSql)


def getTable(line):
    indexCreate = 0
    if line.startswith("CREATE TABLE IF NOT EXISTS"):
        indexCreate = len("CREATE TABLE IF NOT EXISTS")
    elif line.startswith("CREATE TABLE"):
        indexCreate = len("CREATE TABLE")
    indexEnd = line.index("(")
    return line[indexCreate:indexEnd].rstrip("(").strip()


if __name__ == "__main__":
    result = []
    currTable = ''
    with open('mysql_ddl.sql', 'r') as file:
        line = file.readline()
        while line:
            # 替换`x`为"x"
            line = line.replace("`", "\"").replace("\n", "").replace("unsigned", "")
            # longtext替换
            line = line.replace("longtext", "text").replace("LONGTEXT", "TEXT")
            # mediumblob 替换
            line = line.replace("mediumblob", "blob").replace("MEDIUMBLOB", "BLOB")
            lTrimUpperLine = line.lstrip().upper()
            # 替换DEFAULT CURRENT_TIMESTAMP ON UPDATE
            if lTrimUpperLine.count("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP") > 0:
                line = line.replace("ON UPDATE CURRENT_TIMESTAMP", "") \
                    .replace("on UPDATE CURRENT_TIMESTAMP", "") \
                    .replace("on update CURRENT_TIMESTAMP", "") \
                    .replace("ON update CURRENT_TIMESTAMP", "")
            # 替换ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT
            if lTrimUpperLine.count(") ENGINE=INNODB") > 0:
                line = ");"
            # 查询当前所属表
            if lTrimUpperLine.startswith("CREATE TABLE "):
                currTable = getTable(line)
            # 移除bigint、int、tinyint的显示占位符
            if line.count(" bigint(") > 0:
                indexBigint = line.find("bigint(")
                right = line[indexBigint + 6:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 6] + right
            if line.count(" int(") > 0:
                indexBigint = line.find("int(")
                right = line[indexBigint + 3:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 3] + right
            if line.count(" tinyint(") > 0:
                indexBigint = line.find("tinyint(")
                right = line[indexBigint + 7:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 7] + right
            # 唯一索引替换
            if lTrimUpperLine.startswith("UNIQUE "):
                column = line[line.index("("):line.index(")") + 1]
                line = f"UNIQUE {column},"
            # 记录索引
            if lTrimUpperLine.startswith("KEY "):
                replaceKey(line, currTable)
            # 检测到结尾,移除上一行最后一个逗号
            elif line.count(");") > 0:
                lastLine = result[-1:][0]
                if lastLine.rstrip().endswith(","):
                    lastLine = lastLine.rstrip(",")
                    result.pop()
                    result.append(lastLine)
                result.append(line)
            elif (lTrimUpperLine.strip() is None
                  or len(lTrimUpperLine.strip()) == 0
                  or lTrimUpperLine.startswith("/*")
                  or lTrimUpperLine.startswith("LOCK TABLES")
                  or lTrimUpperLine.startswith("UNLOCK TABLES;")
                  or lTrimUpperLine.startswith("--")
                  or lTrimUpperLine.strip() is None):
                pass
            else:
                result.append(line)
            line = file.readline()
    for x in index_sql_list:
        result.append(x)
    with open("dameng_ddl.sql", "w") as f:
        for r in result:
            f.writelines(r + "\n")

如果想直接转化为大写,则不用加""

python 复制代码
index_sql_list = []


def replaceKey(line, currTable):
    indexColumnStart = line.index("(")
    indexColumnEnd = line.index(")")
    if (line.lstrip().upper().startswith("KEY")):
        indexSql = f"CREATE INDEX {line.lstrip()[4: indexColumnStart - 2]} ON {currTable}({line[indexColumnStart + 1: indexColumnEnd]});"
    else:
        indexSql = f"CREATE UNIQUE INDEX {line.lstrip()[11: indexColumnStart - 2]} ON {currTable}({line[indexColumnStart + 1: indexColumnEnd]});"
    index_sql_list.append(indexSql)


def getTable(line):
    indexCreate = 0
    if line.startswith("CREATE TABLE IF NOT EXISTS"):
        indexCreate = len("CREATE TABLE IF NOT EXISTS")
    elif line.startswith("CREATE TABLE"):
        indexCreate = len("CREATE TABLE")
    indexEnd = line.index("(")
    return line[indexCreate:indexEnd].rstrip("(").strip()


if __name__ == "__main__":
    result = []
    currTable = ''
    with open('mysql_ddl.sql', 'r') as file:
        line = file.readline()
        while line:
            line = line.replace("\n", "")
            lTrimUpperLine = line.lstrip().upper()
            if lTrimUpperLine.startswith("COMMENT") or lTrimUpperLine.startswith("`COMMENT`"):
                # 替换`x`为"x"
                line = line.replace("`", "\"")
            else:
                # 移除``
                line = line.replace("`", "")
            # unsigned 替换
            line = line.replace("unsigned", "").replace("UNSIGNED", "")
            # longtext替换
            line = line.replace("longtext", "text").replace("LONGTEXT", "TEXT")
            # mediumblob 替换
            line = line.replace("mediumblob", "blob").replace("MEDIUMBLOB", "BLOB")
            # 替换DEFAULT CURRENT_TIMESTAMP ON UPDATE
            if lTrimUpperLine.count("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP") > 0:
                line = line.replace("ON UPDATE CURRENT_TIMESTAMP", "") \
                    .replace("on UPDATE CURRENT_TIMESTAMP", "") \
                    .replace("on update CURRENT_TIMESTAMP", "") \
                    .replace("ON update CURRENT_TIMESTAMP", "")
            # 替换ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT
            if lTrimUpperLine.count(") ENGINE=INNODB") > 0:
                line = ");"
            # 查询当前所属表
            if lTrimUpperLine.startswith("CREATE TABLE "):
                currTable = getTable(line)
            # 移除bigint、int、tinyint的显示占位符
            if line.count(" bigint(") > 0:
                indexBigint = line.find("bigint(")
                right = line[indexBigint + 6:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 6] + right
            if line.count(" int(") > 0:
                indexBigint = line.find("int(")
                right = line[indexBigint + 3:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 3] + right
            if line.count(" tinyint(") > 0:
                indexBigint = line.find("tinyint(")
                right = line[indexBigint + 7:]
                right = right[right.find(")") + 1:]
                line = line[:indexBigint + 7] + right
            # 唯一索引替换
            if lTrimUpperLine.startswith("UNIQUE "):
                column = line[line.index("("):line.index(")") + 1]
                line = f"UNIQUE {column},"
            # 记录索引
            if lTrimUpperLine.startswith("KEY "):
                replaceKey(line, currTable)
            # 检测到结尾,移除上一行最后一个逗号
            elif line.count(");") > 0:
                lastLine = result[-1:][0]
                if lastLine.rstrip().endswith(","):
                    lastLine = lastLine.rstrip(",")
                    result.pop()
                    result.append(lastLine)
                result.append(line)
            elif (lTrimUpperLine.strip() is None
                  or len(lTrimUpperLine.strip()) == 0
                  or lTrimUpperLine.startswith("/*")
                  or lTrimUpperLine.startswith("LOCK TABLES")
                  or lTrimUpperLine.startswith("UNLOCK TABLES;")
                  or lTrimUpperLine.startswith("--")
                  or lTrimUpperLine.strip() is None):
                pass
            else:
                result.append(line)
            line = file.readline()
    for x in index_sql_list:
        result.append(x)
    with open("dameng_ddl.sql", "w") as f:
        for r in result:
            f.writelines(r + "\n")
相关推荐
Gauss松鼠会几秒前
GaussDB全密态数据库等值查询
数据库·oracle·gaussdb
JSUITDLWXL3 分钟前
在Oracle数据中更新整个对象和更新对象的某几个字段时,他们的锁是相同的吗
数据库·oracle
杏花春雨江南3 分钟前
ddl/dml/dcl
数据库·oracle
好看资源平台7 分钟前
爬虫开发工具与环境搭建——环境配置
爬虫·python
大G哥15 分钟前
python 数据类型----可变数据类型
linux·服务器·开发语言·前端·python
Matrix7029 分钟前
HBase理论_HBase架构组件介绍
大数据·数据库·hbase
不太灵光的程序员31 分钟前
【HBase分布式数据库】第七章 数据的导入导出 importtsv导入数据
数据库·分布式·hbase
Mephisto.java36 分钟前
【大数据学习 | HBASE高级】region split机制和策略
数据库·学习·hbase
Lucifer三思而后行37 分钟前
YashanDB YAC 入门指南与技术详解
数据库·后端
赛丽曼41 分钟前
Python中的HTML
python·html