# +====================================================================== # | DjangoAdmin 企业数字化开发平台 [ 赋能开发者,助力企业发展 ] # +---------------------------------------------------------------------- # | Copyright (c) 2021-2026 小蚂蚁云团队 版权所有 # +---------------------------------------------------------------------- # | 开源协议: Apache-2.0 # | 重要声明: 未经书面许可,不得移除或修改本框架相关版权标识。 # +---------------------------------------------------------------------- # | 官方网站: https://www.djangoadmin.cn # +---------------------------------------------------------------------- # | 研发团队: 小蚂蚁云团队 荣誉出品 # +====================================================================== # | 版权和免责声明: # | 一、知识产权声明 # | 本团队对该软件框架产品(以下简称“本产品”)拥有完整知识产权,包括但不限于商标权、专利权、 # | 著作权、商业秘密等。前述权利均受中华人民共和国及相关国际法律法规保护。未经本团队书面授权, # | 任何个人或单位不得基于本产品本身申请任何形式的知识产权。 # | 二、使用限制与禁止条款 # | 您理解并同意,禁止将本产品用于以下任何行为: # | 1. 任何违反中华人民共和国法律法规的用途; # | 2. 任何侵害他人合法权益(包括但不限于人身权、财产权、知识产权等)的行为; # | 3. 任何危害国家安全、公共利益及社会道德风尚的行为。 # | 三、责任豁免 # | 因使用本产品而产生的任何损失或法律纠纷(包括但不限于直接损失、间接损失、附带损失、衍生损失 # | 以及因违约、侵权等引发的责任),本团队均不承担任何法律责任。若因违规使用本产品导致任何第三 # | 方提起索赔或行政机关进行调查,您应独立承担全部责任。 # | 四、违约与法律责任 # | 如发现任何违反本声明的行为,本团队有权: # | 1. 无条件配合公安机关及其他有权机关的调查取证工作; # | 2. 依法追究相关方的民事责任,并要求赔偿全部损失; # | 3. 保留进一步采取刑事控告等法律措施的权利。 # | 五、许可范围说明 # | 1、被授权方应视本产品源代码为核心机密信息,负有最高标准的保密与保管义务。禁止以任何形式(包 # | 括但不限于直接或间接的分享、复制、传播、分发、转售、出租、开源、反向工程、反编译、反汇编或通 # | 过网络服务提供给任何第三方)泄露、披露或处置源代码的全部或部分内容。任何未经授权的复制、使用、 # | 传播行为均构成对本团队知识产权的严重侵权,本团队有权依法追究其全部法律责任,并要求赔偿因此造 # | 成的一切经济损失及商誉损害。 # | 2、本产品仅限于公司或个人在法律允许范围内,用于内部且合规的软件产品研发。具体权利义务以《软件 # | 许可协议》附件为准。 # +====================================================================== """ 数据库表结构查询服务模块 ============================================================= 该模块实现了数据库表结构查询相关的业务逻辑。 包括表的分页查询、详情查询等功能,用于代码生成器等场景。 通过查询 information_schema 数据库获取表的元数据信息。 """ import logging from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage from django.db import connection from constant.constants import PAGE_SIZE from generator import generate_config_from_table from generator_config import CodeGenerator from utils import R from utils.common import format_datetime # ============================================================= # 分页查询服务 # ============================================================= def get_table_page(request): """ 查询数据库表分页数据 Args: request: HttpRequest对象,包含查询参数 - pageNo: 当前页码(可选,默认为1) - pageSize: 每页记录数(可选,默认为PAGE_SIZE) - tableName: 表名(可选,模糊查询) - tableComment: 表注释(可选,模糊查询) Returns: R: 包含分页数据的JSON响应 """ try: # 获取分页参数 page_no = int(request.GET.get('pageNo', 1)) page_size = int(request.GET.get('pageSize', PAGE_SIZE)) # 获取筛选条件 table_name = request.GET.get('tableName', '') table_comment = request.GET.get('tableComment', '') # 执行SQL查询,获取所有符合条件的表 tables = _query_tables(table_name, table_comment) # 分页处理 page_data = _paginate_tables(tables, page_no, page_size) return R.ok(data=page_data) except Exception as e: logging.error(f"查询数据库表分页数据异常: {str(e)}") return R.failed(msg="查询失败,请稍后重试") def _query_tables(table_name='', table_comment=''): """ 查询数据库表信息(私有辅助函数) Args: table_name: 表名模糊查询条件 table_comment: 表注释模糊查询条件 Returns: list: 表信息列表 """ # 构建基础SQL查询语句 # information_schema.TABLES 中的字段名都是大写 sql = """ SELECT TABLE_NAME, TABLE_COMMENT, ENGINE, TABLE_ROWS, DATA_LENGTH, AUTO_INCREMENT, TABLE_COLLATION, CREATE_TIME, UPDATE_TIME FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME NOT LIKE 'auth_%%' AND TABLE_NAME NOT LIKE 'captcha_%%' AND TABLE_NAME NOT LIKE '%%_migrations' AND TABLE_NAME NOT LIKE '%%_session' AND TABLE_NAME NOT LIKE '%%_content_type' """ params = [] # 添加表名模糊查询条件 if table_name: sql += " AND TABLE_NAME LIKE %s" params.append(f"%{table_name}%") # 添加表注释模糊查询条件 if table_comment: sql += " AND TABLE_COMMENT LIKE %s" params.append(f"%{table_comment}%") # 按表名排序 sql += " ORDER BY TABLE_NAME" # 执行SQL查询 tables = [] with connection.cursor() as cursor: cursor.execute(sql, params) columns = [col[0] for col in cursor.description] rows = cursor.fetchall() for row in rows: row_dict = dict(zip(columns, row)) # 处理自增索引值:如果 AUTO_INCREMENT 为空但 TABLE_ROWS 有值,则设置为 TABLE_ROWS + 1 if row_dict.get('AUTO_INCREMENT') is None and row_dict.get('TABLE_ROWS'): row_dict['AUTO_INCREMENT'] = row_dict['TABLE_ROWS'] + 1 # 格式化时间字段 if row_dict.get('CREATE_TIME'): row_dict['CREATE_TIME'] = format_datetime(row_dict['CREATE_TIME']) if row_dict.get('UPDATE_TIME'): row_dict['UPDATE_TIME'] = format_datetime(row_dict['UPDATE_TIME']) tables.append(row_dict) return tables def _paginate_tables(tables, page_no, page_size): """ 对表列表进行分页处理(私有辅助函数) Args: tables: 表信息列表 page_no: 当前页码 page_size: 每页大小 Returns: dict: 标准格式的分页数据 """ paginator = Paginator(tables, page_size) try: page_list = paginator.page(page_no) except (PageNotAnInteger, InvalidPage, EmptyPage): page_list = paginator.page(1) page_no = 1 records = [] for item in page_list: records.append({ 'tableName': item.get('TABLE_NAME', ''), 'tableComment': item.get('TABLE_COMMENT', ''), 'engine': item.get('ENGINE', ''), 'tableRows': item.get('TABLE_ROWS', 0), 'dataLength': item.get('DATA_LENGTH', 0), 'autoIncrement': item.get('AUTO_INCREMENT'), 'tableCollation': item.get('TABLE_COLLATION', ''), 'createTime': item.get('CREATE_TIME'), 'updateTime': item.get('UPDATE_TIME') if item.get('UPDATE_TIME') else None, }) return { 'records': records, 'total': paginator.count, # 总记录数 'size': page_size, # 每页大小 'current': page_no, # 当前页码 'pages': paginator.num_pages # 总页数 } # ============================================================= # 详情查询服务 # ============================================================= def get_table_detail(table_name): """ 根据表名查询表详情 Args: table_name: 表名 Returns: dict/None: 表详情字典,不存在时返回None """ try: if not table_name: return None # 构建SQL查询语句 sql = """ SELECT TABLE_NAME, TABLE_COMMENT, ENGINE, TABLE_ROWS, DATA_LENGTH, AUTO_INCREMENT, TABLE_COLLATION, CREATE_TIME, UPDATE_TIME FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME = %s """ with connection.cursor() as cursor: cursor.execute(sql, [table_name]) columns = [col[0] for col in cursor.description] row = cursor.fetchone() if not row: return None row_dict = dict(zip(columns, row)) # 处理自增索引值 if row_dict.get('AUTO_INCREMENT') is None and row_dict.get('TABLE_ROWS'): row_dict['AUTO_INCREMENT'] = row_dict['TABLE_ROWS'] + 1 # 构建返回数据 result = { 'tableName': row_dict.get('TABLE_NAME', ''), 'tableComment': row_dict.get('TABLE_COMMENT', ''), 'engine': row_dict.get('ENGINE', ''), 'tableRows': row_dict.get('TABLE_ROWS', 0), 'dataLength': row_dict.get('DATA_LENGTH', 0), 'autoIncrement': row_dict.get('AUTO_INCREMENT'), 'tableCollation': row_dict.get('TABLE_COLLATION', ''), 'createTime': format_datetime(row_dict.get('CREATE_TIME')), 'updateTime': format_datetime(row_dict.get('UPDATE_TIME')), } return result except Exception as e: logging.error(f"查询表详情异常,表名: {table_name}, 错误: {str(e)}") return None # ============================================================= # 表字段查询服务 # ============================================================= def get_table_columns(table_name): """ 获取表的字段信息 Args: table_name: 表名 Returns: list: 字段信息列表 """ try: if not table_name: return [] # 构建SQL查询语句 sql = """ SELECT COLUMN_NAME, COLUMN_COMMENT, DATA_TYPE, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME = %s ORDER BY ORDINAL_POSITION """ columns = [] with connection.cursor() as cursor: cursor.execute(sql, [table_name]) col_columns = [col[0] for col in cursor.description] rows = cursor.fetchall() for row in rows: row_dict = dict(zip(col_columns, row)) columns.append({ 'columnName': row_dict.get('COLUMN_NAME', ''), 'columnComment': row_dict.get('COLUMN_COMMENT', ''), 'dataType': row_dict.get('DATA_TYPE', ''), 'columnType': row_dict.get('COLUMN_TYPE', ''), 'isNullable': row_dict.get('IS_NULLABLE', ''), 'columnDefault': row_dict.get('COLUMN_DEFAULT'), 'extra': row_dict.get('EXTRA', ''), }) return columns except Exception as e: logging.error(f"查询表字段信息异常,表名: {table_name}, 错误: {str(e)}") return [] # ============================================================= # 代码生成服务 # ============================================================= def generate_tables(table_names): """ 统一的代码生成服务方法 支持单个或多个表的代码生成,自动解析管道分隔格式。 Args: table_names (list): 表名列表,支持三种格式 格式1(管道分隔): ["django_article|文章管理表", "django_user|用户表"] 格式2(纯表名): ["django_article", "django_user"] 格式3(混合): ["django_article|文章管理表", "django_user"] Returns: R: 包含生成结果的JSON响应 """ for item in table_names: # 解析表名和注释 if isinstance(item, str): item = item.strip() if '|' in item: parts = item.split('|', 1) table_name = parts[0].strip() table_comment = parts[1].strip() if len(parts) > 1 else '' else: table_name = item table_comment = '' elif isinstance(item, dict): table_name = item.get('name', '').strip() table_comment = item.get('comment', '').strip() # 执行单表生成 try: # 解析表结构生成配置 config = generate_config_from_table(table_name) if not config: return R.failed(msg="配置不能为空") # 处理表注释 if table_comment: module_comment = table_comment.replace('表', '').strip() config['module_comment'] = module_comment config['business_description'] = f'标识系统中的{module_comment}数据' config['business_description_detail'] = f'每个{module_comment}包含相关属性' # 创建代码生成器并执行 generator = CodeGenerator(config) generator.generate(auto=True) except Exception as e: logging.error(f"生成表 {table_name} 代码失败: {str(e)}") return R.ok(msg=f'本次共计生成{len(table_names)}个模块')