Esempio n. 1
0
def main():
    is_new = input('是否重新导出数据? yes/no:')
    version = time.time()
    if is_new == 'no':
        version = input('请输入历史版本 ps:1601260075.6850908:')
        if not os.path.exists('./.sql/dump/{0}'.format(version)):
            raise Exception('版本不存在')
    path_dump = './.sql/dump/{0}'.format(version)
    if not os.path.exists(path_dump):
        os.makedirs(path_dump)
    db_from_config = {
        'ip': '',
        'port': 3306,
        'user': '',
        'passwd': '',
        'db': ''
    }
    db_to_config = {'ip': '', 'port': 3306, 'user': '', 'passwd': '', 'db': ''}
    if 'rds' in db_to_config['ip']:
        raise Exception('导入数据库存在敏感地址,请再次验证')
    all_tables = []
    mysql_util = MysqlUtil(config=db_from_config)
    sql_all_tables = 'SHOW TABLES'
    sql_all_tables_result = mysql_util.query_sql(sql_all_tables)
    for table in list(sql_all_tables_result):
        all_tables.append(table[0])

    if is_new == 'yes':
        for t in all_tables:
            print('----> from database <{0}>'.format(db_from_config['ip']))
            print('----> dump table <{0}>'.format(t))
            cmd_dump_sql = 'mysqldump --set-gtid-purged=off -h{h} -P{P} -u{u} -p{p} {db} --tables  {tb}>{path_dump}/{tb}.sql'.format(
                h=db_from_config['ip'],
                P=db_from_config['port'],
                u=db_from_config['user'],
                p=db_from_config['passwd'],
                db=db_from_config['db'],
                path_dump=path_dump,
                tb=t)
            execute_cmd(cmd_dump_sql)
    verify_code = ''.join(
        random.sample([
            'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n',
            'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'
        ], 5))
    print('----------WARNING START----------')
    print('----------infomation below must be readed carefully!----------')
    print(
        '----------or it will make a unexpectable and harmful issue----------')
    print('----------FROM DATABASE INFO----------')
    print('----------IP {0}----------'.format(db_from_config['ip']))
    print('----------DATABASE {0}----------'.format(db_from_config['db']))
    print('----------TO DATABASE INFO----------')
    print('----------IP {0}----------'.format(db_to_config['ip']))
    print('----------DATABASE {0}----------'.format(db_to_config['db']))
    print('----------WARNING END----------')
    print('----------VERIFY CODE: {0}------'.format(verify_code))
    is_confirm_do = input('已阅读警告 yes/no:')
    if is_confirm_do == 'no':
        print('程序退出')
        return
    if is_confirm_do == 'yes':
        check_verify_code = input('输入上述验证码:')
        if check_verify_code != verify_code:
            raise Exception('验证码错误')
        else:
            for t in all_tables:
                print('----> to database <{0}>'.format(db_to_config['ip']))
                print('----> import table <{0}>'.format(t))
                cmd_import_sql = 'mysql -h{h} -P{P} -u{u} -p{p} {db}<{path_dump}/{tb}.sql'.format(
                    h=db_to_config['ip'],
                    P=db_to_config['port'],
                    u=db_to_config['user'],
                    p=db_to_config['passwd'],
                    db=db_to_config['db'],
                    path_dump=path_dump,
                    tb=t)
                execute_cmd(cmd_import_sql)
Esempio n. 2
0
class GenFile():
    def __init__(self):
        self.path_tpl_entity = PathUtil.root('templates') + '/entity.tpl'
        self.path_tpl_mapper = PathUtil.root('templates') + '/mapper.tpl'
        self.project_java = 'test'
        self.mysql_util = MysqlUtil({
            'ip': 'localhost',
            'user': '******',
            'passwd': '123456',
            'db': 'tacomall'
        })
        self.all_tables = []
        self._query_all_tables()

    def _query_all_tables(self):
        sql_all_tables = '''
        SELECT
            table_name
        FROM
            information_schema.`TABLES`
        WHERE
            TABLE_SCHEMA = 'tacomall';
        '''
        result_sql_all_tables = self.mysql_util.query_sql(sql_all_tables)
        self.all_tables = list(map(lambda i: i[0], result_sql_all_tables))

    def _load_tpl(self, tpl_type=1):
        path = ''
        if tpl_type == 1:
            path = self.path_tpl_entity
        if tpl_type == 2:
            path = self.path_tpl_mapper
        tpl = ''
        with open(path) as f_tpl:
            tpl = f_tpl.read()
            f_tpl.close()
        return tpl

    def _2camel(self, s, capitalize=False):
        s = s.lower()
        class_name = ''
        for i, v in enumerate(s.split('_')):
            if i == 0 and not capitalize:
                class_name = v
                continue
            class_name = class_name + v.capitalize()
        return class_name

    def _gen_entity(self):
        tpl = self._load_tpl(1)
        for table in self.all_tables:
            new_tpl = ''
            spl_table = table.split('_')
            package = 'store.tacomall.db.entity.{0}'.format(spl_table[0])
            class_name = self._2camel(table, capitalize=True)
            fields_content = ''
            ignore_columns = [
                'id', 'is_delete', 'create_time', 'update_time', 'delete_time'
            ]
            filename_gen = PathUtil.root(self.project_java +
                                         '/entity/{0}/'.format(spl_table[0])
                                         ) + '{0}.java'.format(class_name)
            sql_table_structure = '''
            SELECT
                DATA_TYPE,
                column_name,
                column_comment
            FROM
                information_schema.COLUMNS
            WHERE
                table_name = '{0}';
            '''.format(table)
            if PathUtil.is_exists(filename_gen):
                print('实体类{0}.java文件已存在'.format(class_name))
                continue
            result_sql_table_structure = self.mysql_util.query_sql(
                sql_table_structure)
            for structure in list(
                    map(
                        lambda i: {
                            'type': i[0],
                            'column': i[1],
                            'comment': i[2]
                        }, result_sql_table_structure)):
                if structure['column'] in ignore_columns:
                    continue
                java_data_type = ''
                if structure['type'] == 'int':
                    java_data_type = 'int'
                if structure['type'] == 'varchar':
                    java_data_type = 'String'
                if structure['type'] == 'text':
                    java_data_type = 'String'
                if structure['type'] == 'datetime':
                    java_data_type = 'Date'
                fields_content = fields_content + \
                    '   private {0} {1}; // {2}\n\n'.format(
                        java_data_type, self._2camel(structure['column']), structure['comment'])
            new_tpl = tpl.replace('${PACKAGE}', package)
            new_tpl = new_tpl.replace('${CLASS}', class_name)
            new_tpl = new_tpl.replace('${FIELDS}', fields_content)
            with open(filename_gen, 'w+', encoding='utf8') as f_gen:
                f_gen.write(new_tpl)
                f_gen.close()

    def _gen_mapper(self):
        tpl = self._load_tpl(2)
        for table in self.all_tables:
            new_tpl = ''
            spl_table = table.split('_')
            package = 'store.tacomall.db.mapper.{0}'.format(spl_table[0])
            class_name = self._2camel(table, capitalize=True) + 'Mapper'
            filename_gen = PathUtil.root(self.project_java +
                                         '/mappper/{0}/'.format(spl_table[0])
                                         ) + '{0}.java'.format(class_name)
            if PathUtil.is_exists(filename_gen):
                print('mapper类{0}.java文件已存在'.format(class_name))
                continue
            new_tpl = tpl.replace('${PACKAGE}', package)
            new_tpl = new_tpl.replace('${CLASS}', class_name)
            new_tpl = new_tpl.replace('${ENTITY_DOMAIN}', spl_table[0])
            new_tpl = new_tpl.replace('${ENTITY_CLASS}',
                                      self._2camel(table, capitalize=True))
            with open(filename_gen, 'w+', encoding='utf8') as f_gen:
                f_gen.write(new_tpl)
                f_gen.close()

    def run(self):
        self._gen_entity()
        self._gen_mapper()