Adding Foreign Key to Postgre via cursor().execute( sql) does Nothing (No error - No result)

Viewed 26

I'm trying to add a foreign key constraint to one of my tables in my PostgreSQL DB via Python code but I could not succeed. I tried below code, it runs and gives no error (I hid connection string) however it also does nothing.

When I copy printed sql_text and run it on pg_Admin New Query tool, it works perfectly and adds the relation.

Now the very interesting thing is when the relation is present in this way, when I re-run my python code it says that;

DuplicateObject: constraint "R__t_PL_Re__t_001_P" for relation "t_PL_Res_UP" already exists

Therefore it actually recognizes the connection. I'm really confused at this point. Can somebody tell me what I am doing wrong ?

Thank you in advance...

import psycopg2

pgr_cnn = psycopg2.connect( database =  "***",
                            user =      "***",
                            password =  "***",
                            host =      "***",
                            port =      "***")

    sql_text =  """ALTER TABLE IF EXISTS public."t_PL_Res_UP"
        ADD CONSTRAINT "R__t_PL_Re__t_001_P" FOREIGN KEY ("up_pr_Code")
        REFERENCES public."t_001_Projects" ("p_Code") MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE RESTRICT;"""
    
    print( sql_text)
    
    pgr_cnn.cursor().execute( sql_text)
    pgr_cnn.close()
1 Answers
pgr_cnn.commit()

before

pgr_cnn.close()
Related