disable commit in Psycopg2

I want to run a few tests in inserting data to a postgresql-9.3 db, I am using Python-2.7 and the Psycopg2 api.

Up to now i was using it in alot of modules and doing commit() after some operations. since there are many commit() locations, i dont want to go and add an test_mode IF to all those commits, so what i thought would be best is to redirect the commit in a test_mode case to a void function:

#create connection
connection = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pwd,)

#in test_mode disable commit functionality
def void():
    print("No commit,this is a test mode")
if settings.test_mode:
    connection.commit=void

But what i get is this

AttributeError: 'psycopg2._psycopg.connection' object attribute 'commit' is read-only 

Any advice is welcome!

Answers


You can wrap the connection object with a Proxy class:

class FakeConnection(object):
    def __init__(self, connection):
        self.connection = connection
    def __getattr__(self, name):
        return getattr(self.connection, name)
    def __setattr__(self, name, value):
        if name != "connection": 
            setattr(self.connection, name, value)
        else:
            super(self, FakeConnection).__setattr__(name, value)
    def commit(self, *args, **kwargs):
        pass

Though it would be much better if you can avoid sprinkling your code with commit all over the place.


You can use ROLLBACK

if settings.test_mode:
    connection.rollback()
else:
    connection.commit()

Need Your Help

php limit active database entries

php mysql datetime limit

i'm currently making a few php scripts that will let guests book a room in a hotel now there is a limit on the different kinds of rooms but how can i enforce this through php?

tinyMCE not working with jQuery 1.4.2 in IE6

javascript jquery internet-explorer-6 tinymce upgrade

I'm having trouble getting tinyMCE to work with the new jQuery 1.4.2 on IE6. In my project, we've been using tinyMCE with no problems with jQuery 1.3.2. But now the upgrade has brought on a weird p...