导出oracle存储过程

import cx_oracle
user = "my_user"
password = "password"
ip = "1.1.1.1"
sid = "bloom"
db_dsn = cx_oracle.makedsn(ip, '1521', sid=sid)

def start():
    db_conn, cursor = None, None
    try:
        db_conn = cx_oracle.connect(user, password, dsn=db_dsn)
        cursor = conn.cursor()

        procedures_name_list = ['a_hello_world']  # 需要导出的存储过程的名称
        procedures_name_list = procedures_name_list[i.upper() for i in procedures_name_list]
        
        with open(r"./procedures_text", 'w', encoding="utf8") as f:
            for procedures_name_now in procedures_name_list:
                procedures_text = cursor.var(cx_Oracle.CLOB) # 出参
                cursor.callproc('get_procedures_text', [procedures_name_str, procedures_text])
                print(procedures_text.getvalue())
                f.write(str(procedures_text.getvalue()))
                f.write("\n")
    except Exception as e:
        print(str(e))
    finally:
        if cursor:
            cursor.close()
        if db_conn:
            db_conn.close()


create or replace procedure get_proicedures_text(
    procedures_name_str in varchar2,
    procedures_text out clob
    )
as
begin
    declare
        cursor cur_2 is 
            SELECT CASE
                    WHEN LINE = 1 THEN
                    'CREATE OR REPLACE ' || TEXT
                    WHEN LINE = MAX_LINE THEN
                    TEXT || CHR(10 ) || '/'
                    ELSE
                    TEXT
                END as text_line
            FROM USER_SOURCE A
            LEFT JOIN (SELECT A.NAME,A.TYPE, MAX(LINE) MAX_LINE
                        FROM USER_SOURCE A
                        WHERE TYPE in ( 'PROCEDURE', 'PACKAGE' ,'PACKAGE BODY' )
                        GROUP BY A.NAME,A.TYPE ) B ON A.NAME||A.TYPE = B.NAME||B.TYPE
            WHERE A.TYPE in ('PROCEDURE' , 'PACKAGE', 'PACKAGE BODY' ) AND A.NAME IN
            (procedures_name_str) ORDER BY a.NAME||a.TYPE , LINE;
        begin
            for rec in cur_2 loop
                procedures_text := procedures_text || rec.text_line;
            end loop;
        end;
end get_proicedures_text;






你可能感兴趣的:(database)