腳本工具---自動解析mysql建表語句,生成sqlalchemy表對象聲明


 

常規建表語句:

CREATE TABLE `test_table` (
  `id` int(11) NOT NULL,
  `name` char(64) NOT NULL,
  `password` char(64) NOT NULL,
  PRIMARY KEY (`name`,`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='test';

 

解析腳本代碼:

 
         
# coding:utf-8

import re
def table_design_transfer(table_design): type_map = {"varchar":"String","datetime":"DateTime","bigint":"BigInteger","smallint":"SmallInteger","tinyint":"SmallInteger","text":"Text","int":"Integer","double":"Float","char":"String","set":"Enum"} l = table_design.split("\n")    # 表設計行拆分
    length = len(l) s = [] primary_key_l = [] for i in range(length):     # 遍歷表設計行
        j = l[length-1-i].strip().split(" ")    # 倒序遍歷,並按空格切分
        if len(j)>2:        # 只關注行長度超過2的元素
            column = j[0].replace("`","") i_type = j[1] if column == "PRIMARY": primary_key_l = re.sub(r'`|\(|\)','',j[2]).split(",") # 拿到主鍵key
                continue
            elif column == "CREATE":    # 獲取表名
                table_name = j[2].replace("`","") s.append("    "+'__tablename__ = "%s"' % table_name) s.append("class %s(Base):" % table_name) continue
            elif column in ("UNIQUE",")","KEY"): # 非表列名,跳過
                continue
            if i_type in type_map.keys():   # 類型存在映射表中
                i_type = i_type.replace(i_type,type_map[i_type])+"()"
            elif "(" in i_type and i_type.split("(")[0] in type_map.keys(): # 類型有長度聲明,提取類型字段,找到映射表映射value,並替換
                old_type = i_type.split("(")[0] new_type = type_map[i_type.split("(")[0]] i_type = i_type.replace(old_type,new_type) else: print "Catch any case not in type_map:%s" % i_type if column in primary_key_l:     # 列名存在主鍵數組中
                i_type = i_type + ", primary_key=True" s.append("    "+column + " = Column(" + i_type + ")") for i in s[::-1]:   # 反序輸出
        print i

輸出結果:

class test_table(Base):
    __tablename__ = "test_table"
    id = Column(Integer(11), primary_key=True)
    name = Column(String(64), primary_key=True)
    password = Column(String(64))

 

 

sqlalchemy庫官方文檔:http://docs.sqlalchemy.org/en/latest/contents.html

sqlalchemy庫官方文檔(中文):http://www.cnblogs.com/iwangzc/p/4112078.html(感謝作者的分享)

faker庫官方文檔:https://faker.readthedocs.io/en/master/locales/zh_CN.html

faker庫博客:https://www.jianshu.com/p/6bd6869631d9

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM