Thursday, 15 September 2011

Continue executing INSERT script even on error - PostgreSQL using Python script -



Continue executing INSERT script even on error - PostgreSQL using Python script -

i'm trying create mass insert postgresql db using python script (with psycopg connection). now, script has duplicates on primary column makes abort , rollback entire script. however, want skip duplicates , go on execution. script looks below

begin transaction; create table t1 (c1 float, unique(c1)); insert t1 values (1); insert t1 values (2); insert t1 values (1); --the script aborts , rolls commit;

i have looked around , found out setting on_error_rollback helps. seems like, can set psql command line.

is possible utilize on_error_rollback within python script? or there other alternative option?

thanks in advance!

usually transactions used homecoming savepoint. in case, utilize plain sql, not in transaction. each statement wrapped in begin - commit block implicitly.

insert t1(c1) values (1); insert t1(c1) values (2); insert t1(c1) values (1);

if still want utilize single transaction, write function , utilize exception handling:

create or replace function insertintot1(key int) returns void $$ begin begin insert t1(c1) values (key); exception when unique_violation -- nothing, raise notice raise notice 'key % exists!', key; end; end; $$ language plpgsql; begin; create table t1 (c1 float, unique(c1)); select insertintot1(1); select insertintot1(2); select insertintot1(1); commit;

more info exception handling , trapping errors in plpgsql http://www.postgresql.org/docs/9.4/static/plpgsql-control-structures.html#plpgsql-error-trapping

python postgresql psycopg2

No comments:

Post a Comment