sql转Html图形化展示(Python实现)

简介

  • 每当在powerdesigner设计好表结构之后, 有时候需要和别人讨论下设计的情况, 但直接丢个.sql给其他人又不直观, 于是就做了个可以将sql转为Html表格, 主要是字段后面带了注释, 便于了解字段的意义, 简洁直观, 效果如下
    sql转Html图形化展示(Python实现)_第1张图片

  • 源码: https://github.com/shuoGG1239/SqlToXXX

  • 效果



分析

  • 先解析sql语句, 然后根据提取出来的关键信息, 之前在Py小工具: .sql转JavaBean一步到位一节已经讲过, 就是用使用正则来匹配关键字并提取出来封装个Table对象的list出来, 再贴下解析的核心代码:
def get_tables(sql_text):
    """
    sql文本转Table对象列表
    :param sql_text: sql文本
    :return: list of Table
    """
    tables = []
    ret = re.findall(r'(create\stable\s(.+)[^(]+\(([^;]+)\);)', sql_text)
    for per_table_ret in ret:
        table_name = per_table_ret[1].replace('\r', '').replace('\n', '')
        table_body = per_table_ret[2]
        table_body_lines = list(map(lambda x: x.strip(), table_body.strip().splitlines()))
        new_table = Table()
        # 遍历( ... )里面的每一行
        key_names = []
        for line in table_body_lines:
            if 'primary key' in line:
                key_names.append(line[line.find('(') + 1:line.find(')')])
            if 'key ' not in line:
                ret_line = re.search(r'([\w_]+)\s+([^\s,]+)\s?(.*)', line)
                field_name = ret_line.group(1)
                field_type = ret_line.group(2)
                field_tail = ret_line.group(3)
                field_comment = '--'
                if 'comment ' in field_tail:
                    field_comment = re.search(r'[\w\s]+\'(.+)\'', line).group(1)
                new_field = Field(field_name, field_type, field_comment)
                if 'not null' in line:
                    new_field.is_not_null = True
                if 'auto_increment' in line:
                    new_field.is_auto_increase = True
                new_table.fields.append(new_field)
        # 处理primary key
        for per_field in new_table.fields:
            if per_field.name in key_names:
                per_field.is_key = True
        table_comment = 'null'
        ret_comment = re.search(
            r'alter\stable\s%s.+\'(.+)\'' % table_name.strip(), sql_text)
        if ret_comment is not None:
            table_comment = ret_comment.group(1)
        new_table.comment = table_comment
        new_table.name = table_name
        tables.append(new_table)
    return tables


class Field:
    def __init__(self, name='', type='', comment=''):
        self.name = name
        self.type = type
        self.comment = comment
        self.is_not_null = False
        self.is_key = False
        self.is_auto_increase = False

    def __repr__(self):
        return "Field(name=%s, type=%s, comment=%s)" % (self.name, self.type, self.comment)

class Table:
    def __init__(self):
        self.name = ''
        self.comment = ''
        self.fields = []

    def __repr__(self):
        return "Table(name=%s, comment=%s, field=%s)" % (self.name, self.comment, repr(self.fields))


  • 拿到Table list之后就可以根据关键信息来生成Html了, 这边是使用的BeautifulSoup来方便地生成Html文本, 生成完之后调用浏览器打开网页即可

  • BeautifulSoup是一个处理分析Html的库, 一般爬虫的时候用的较多, 用起来很方便. 安装依赖直接 pip install beautifulSoup4 即可

  • 生成Html的代码

HTML = """
PdmShow
""" % CSS

def sql_to_html(sql_text):
    table_list = sql_parser.get_tables(sql_text)
    soup = BeautifulSoup(HTML, 'lxml')
    # 遍历数据表
    for table in table_list:
        table1 = soup.new_tag(name='table')
        # 标题行
        tr_head = soup.new_tag(name='tr')
        td_head = soup.new_tag(name='th', colspan="3")
        td_head.append(table.name + '(' + table.comment + ')')
        tr_head.append(td_head)
        table1.append(tr_head)
        # field行
        for field in table.fields:
            tr_field = soup.new_tag(name='tr')
            td_name = soup.new_tag(name='td')
            td_name.append(field.name)
            td_type = soup.new_tag(name='td')
            td_type.append(field.type)
            td_comment = soup.new_tag(name='td')
            td_comment.append(field.comment)
            tr_field.append(td_name)
            tr_field.append(td_type)
            tr_field.append(td_comment)
            table1.append(tr_field)
        soup.body.append(table1)
    # 格式化生成
    result_html = soup.prettify()
    # 保存Html到当前文件夹
    file_util.write_file_content(HTML_FILE_NAME, result_html)
    full_path = os.path.join(os.getcwd(), HTML_FILE_NAME)
    # 用浏览器打开生成的Html文件
    system_util.open_with_default_browser(full_path)

你可能感兴趣的:(Python)