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

Question:

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 ?

Answers:

Code of stored procedures can be accessed via user_source view. So, if you query it, you’ll see what you want. Here’s how:

SQL> create or replace procedure p_test is
  2  begin
  3    null;
  4  end;
  5  /

Procedure created.

SQL> desc user_source
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 NAME                                               VARCHAR2(30)
 TYPE                                               VARCHAR2(12)
 LINE                                               NUMBER
 TEXT                                               VARCHAR2(4000)

SQL> select text from user_source where name = 'P_TEST' and type = 'PROCEDURE';

TEXT
--------------------------------------------------------------------------------
procedure p_test is
begin
  null;
end;

SQL>

Though, as I don’t speak Python, I can’t assist in actual code you need to use there. The last select I wrote is what you need; I hope you’ll manage to use it. Good luck!

Answered By: Littlefoot

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())
Answered By: Barbaros Özhan
import oracledb

db = oracledb.connect("<uname>/<pwd>@<host>:<port>/<service_name>")
cursor = db.cursor()

cursor.execute("SELECT DBMS_METADATA.GET_DDL('PROCEDURE', 'PROC_NAME', 'OWNER') FROM DUAL")
c = cursor.fetchall()
print( c[0][0] )

# To save on file    
sample = open('samplefile.txt', 'w')
print(c[0][0], file = sample)
sample.close()

Change connection details, PROC_NAME and OWNER and run.

Answered By: Vasim