pythonoracle-databasecx-oracledbms-metadata

How to i read the contents of Oracle stored procedures using Python


I am trying to read the contents/code of a stored procedure using python.

i used cx_Oracle function to establish the connection with oracle database.

here is the code

import cx_Oracle as co
import pandas as pd

dsn_tsn = co.makedsn(ip,port,SID)
db=co.connect(username,password,dsn_tsn)
cursor = db.cursor()

cursor.callproc(procedure_name,['argument']) # will be me result of the procedure.

However, i am trying to read the code of procedure itself. Is there any function to do that ?


Solution

  • You can call DBMS_METADATA.GET_DDL function from your code in such a way

    import cx_Oracle
    
    db = cx_Oracle.connect("<uname>/<pwd>@<host>:<port>/<service_name>")
    cursor = db.cursor()
    
    
        def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
            if defaultType == cx_Oracle.CLOB:
                return cursor.var(cx_Oracle.LONG_STRING, arraysize = cursor.arraysize)
    
        cursor.outputtypehandler = OutputTypeHandler
        cursor.execute("SELECT DBMS_METADATA.GET_DDL('PROCEDURE', :PrcName) FROM DUAL",
                PrcName="MY_LITTLE_PROC")
    
        print("returned DDL is :",cursor.fetchall())