分割 SQL 脚本为多个 SQL 文件 Python
一、需求
由于日常分析中,常常会将一些 SQL 脚本写到一个文件中,而其中包括了多个建表语句,他们中部分是并列关系,因此将他们分割为多个文件就有一定的必要性。
包含有以下特性
- 以英文半角分号 ;为分割符号,将一个SQL文件分割为多个
- 只有单独一行的 ;才会作为分割文件的标识符,因为常常在建表语句前面有删表语句drop if exist ...;
- 分割出的文件名必须被指定
二、代码
def split_sql(sql_file, to_dir, file_names):
    """将一个SQL文件分割成几个SQL文件,以单独一行 `;` 作为标识
    Args:
        sql_file (str): 要分割的SQL文件路径
        to_dir (str): 要写入到的文件夹路径
        file_names (列表): 要生成的SQL文件列表
    """
    with open(sql_file, 'r', encoding='utf8') as sf:
        sf_list = sf.read().split('\n;')
        sf_list=[x for x in sf_list if x]
        assert len(sf_list) == len(file_names),'文件、名称数量不相等'
        n_files = len(sf_list)
        for i in range(n_files):
            with open("./"+to_dir+"/"+file_names[i], mode='w', encoding='utf8') as f1:
                f1.write(sf_list[i].strip()+'\n;\n')
                print("完成文件:"+file_names[i])
主要过程就是将文件读取,再利用 \n; 作为分隔符号对文件进行分割,再将这些文件写入到指定文件名的文件中。
三、测试
新建文件: testsql.sql
drop table if exists temp.tablename;
create table temp.tablename STORED AS PARQUET as
file1
;
drop table if exists temp.tablename;
create table temp.tablename STORED AS PARQUET as
file2
;
drop table if exists temp.tablename;
create table temp.tablename STORED AS PARQUET as
file3
;
drop table if exists temp.tablename;
create table temp.tablename STORED AS PARQUET as
file4
;
运行以下脚本进行测试:
if __name__ == '__main__':
    sql_file = './testsql.sql'
    file_names = ['test1.sql', 'test2.sql', 'test3.sql', 'test4.sql']
    to_dir = './dir_sql'
    os.mkdir(to_dir)
    split_sql(sql_file, to_dir,file_names)
函数包含三个参数是:要分割的文件、分割后的文件放到哪个文件夹中(此处是to_dir),和文件名列表。运行后就可以查看到分割后的文件了。
dir_sql/
├── test1.sql
├── test2.sql
├── test3.sql
└── test4.sql

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号