57 lines
2.0 KiB
Python
57 lines
2.0 KiB
Python
import os
|
||
from pathlib import Path
|
||
|
||
def merge_sql_files(input_dir, output_filename):
|
||
"""
|
||
整合指定目录下的 SQL 文件到指定位置。
|
||
"""
|
||
# 转换为 Path 对象,处理路径更智能
|
||
source_path = Path(input_dir)
|
||
target_file = Path(output_filename)
|
||
|
||
# 1. 检查输入目录是否存在
|
||
if not source_path.exists() or not source_path.is_dir():
|
||
print(f"❌ 错误:输入路径 '{input_dir}' 不存在或不是文件夹。")
|
||
return
|
||
|
||
# 2. 确保输出文件的父级目录存在(如果不存在则自动创建)
|
||
target_file.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 3. 获取所有 SQL 文件并排序,排除输出文件本身
|
||
sql_files = sorted([
|
||
f for f in source_path.glob("*.sql")
|
||
if f.resolve() != target_file.resolve()
|
||
])
|
||
|
||
if not sql_files:
|
||
print(f"ℹ️ 提示:在目录 '{input_dir}' 中没有找到 .sql 文件。")
|
||
return
|
||
|
||
# 4. 执行合并逻辑
|
||
try:
|
||
with open(target_file, 'w', encoding='utf-8') as outfile:
|
||
for filepath in sql_files:
|
||
with open(filepath, 'r', encoding='utf-8') as infile:
|
||
# 写入注释,标记来源文件
|
||
outfile.write(f"\n-- {'='*20} START: {filepath.name} {'='*20}\n")
|
||
outfile.write(infile.read())
|
||
# 确保换行,防止 SQL 语句粘连
|
||
outfile.write(f"\n-- {'='*20} END: {filepath.name} {'='*20}\n")
|
||
print(f"✅ 已整合: {filepath.name}")
|
||
|
||
print(f"\n✨ 成功!整合后的文件位于: {target_file.absolute()}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ 运行过程中发生错误: {e}")
|
||
|
||
if __name__ == "__main__":
|
||
# --- 在这里直接修改你的配置 ---
|
||
|
||
# 想要读取的 SQL 文件夹路径
|
||
INPUT_PATH = r"C:\Users\Kris\Desktop\ruoyi (30)"
|
||
|
||
# 想要保存的完整路径和文件名
|
||
OUTPUT_NAME = r"C:\Users\Kris\Desktop\ruoyi (30)\all.sql"
|
||
|
||
# 执行合并
|
||
merge_sql_files(INPUT_PATH, OUTPUT_NAME) |