How to use the psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT function in psycopg2

To help you get started, we’ve selected a few psycopg2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ronnix / pymongres / tests / __init__.py View on Github external
def _run_postgres_cmd(command):
    with connect(database='postgres') as connection:
        connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        with connection.cursor() as cursor:
            cursor.execute(command)
github HoloClean / holoclean / tests / testutils.py View on Github external
def random_database():
    """
    Creates a random database in the testing Postgres instance and returns the
    name of the database.
    """
    # Setup connection with default credentials for testing.
    with connect(dbname='holo', user='holocleanuser', password='abcd1234', host='localhost') as conn:
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        with conn.cursor() as cur:
            while True:
                # Generate a random DB name that is not already in Postgres.
                db_name = 'test_holo_{}'.format(random.randint(0, 1e6))
                cur.execute("""
                    SELECT EXISTS(
                        SELECT datname FROM pg_catalog.pg_database
                        WHERE datname = '{db_name}'
                    );
                """.format(db_name=db_name))
                if cur.fetchall()[0][0]:
                    continue

                cur.execute("CREATE DATABASE {db_name}".format(db_name=db_name))
                return db_name
github aatlasis / cve_manager / cve_management2.py View on Github external
def truncate_database(myuser,mypassword,myhost,database):
    con = None
    try:
        con = connect(dbname=database, user=myuser, host = myhost, password=mypassword)
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = con.cursor()
        print "Truncating CVEs tables"
        cur.execute("Truncate cpe, cve_problem, cvss;")
        con.commit()
    except (Exception, psycopg2.DatabaseError) as error :
        print ("Error while Truncating PostgreSQL Database", error)
    finally:
        if(con):
            cur.close()
            con.close()
            print("PostgreSQL connection is closed")
github GeoscienceAustralia / agdc / src / abstract_ingester / ingest_db_wrapper.py View on Github external
def turn_on_autocommit(self):
        """Turns autocommit on for the database connection.

        Returns the old commit mode in a form suitable for passing to
        the restore_commit_mode method. Note that changeing commit mode
        must be done outside a transaction."""

        old_commit_mode = (self.conn.autocommit, self.conn.isolation_level)

        self.conn.autocommit = True
        self.conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

        return old_commit_mode
github awesto / cookiecutter-django-shop / {{cookiecutter.project_slug}} / {{cookiecutter.app_name}} / management / commands / initialize_shop_demo.py View on Github external
except ImportError:
            return
        if os.getenv('DATABASE_ENGINE') != 'django.db.backends.postgresql':
            return

        dbname = os.getenv('DATABASE_NAME')
        if dbname is None:
            return
        host = os.getenv('DATABASE_HOST')
        user = os.getenv('DATABASE_USER')
        password = os.getenv('DATABASE_PASSWORD')
        try:
            con = psycopg2.connect(dbname=dbname, host=host, user=user, password=password)
        except psycopg2.OperationalError:
            con = psycopg2.connect(host=host, user=user, password=password)
            con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
            cur = con.cursor()
            cur.execute('CREATE DATABASE {};'.format(dbname))
        finally:
            con.close()
github aatlasis / cve_manager / cve_management2.py View on Github external
def drop_database(myuser,mypassword,myhost,database):
    con = None
    try:
        con = connect(dbname='postgres', user=myuser, host = myhost, password=mypassword)
        con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = con.cursor()
        cur.execute('DROP DATABASE ' + database)
        print "Database",database,"was dropped."
    except (Exception, psycopg2.DatabaseError) as error :
        print ("Error while dropping PostgreSQL Database", error)
    finally:
        #closing database connection.
        if(con):
            cur.close()
            con.close()
            print("PostgreSQL connection is closed")
github gvSIGAssociation / gvsig-online / gvsigol / gvsigol_services / utils.py View on Github external
def get_connection(host, port, database, user, password):
    try:
        conn = psycopg2.connect("host=" + host +" port=" + port +" dbname=" + database +" user=" + user +" password="+ password);
        conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
        print "Connect ... "

    except StandardError, e:
        print "Failed to connect!", e
        return []

    return conn;
github ansible / ansible / lib / ansible / modules / database / postgresql / postgresql_tablespace.py View on Github external
changed = tblspace.create(location)

    # Drop non-existing tablespace:
    elif not tblspace.exists and state == 'absent':
        # Nothing to do:
        module.fail_json(msg="Tries to drop nonexistent tablespace '%s'" % tblspace.name)

    # Drop existing tablespace:
    elif tblspace.exists and state == 'absent':
        # Because DROP TABLESPACE can not be run inside the transaction block:
        autocommit = True
        if PSYCOPG2_VERSION >= '2.4.2':
            db_connection.set_session(autocommit=True)
        else:
            db_connection.set_isolation_level(AUTOCOMMIT)

        changed = tblspace.drop()

    # Rename tablespace:
    elif tblspace.exists and rename_to:
        if tblspace.name != rename_to:
            changed = tblspace.rename(rename_to)

    if state == 'present':
        # Refresh information:
        tblspace.get_info()

    # Change owner and settings:
    if state == 'present' and tblspace.exists:
        if owner:
            changed = tblspace.set_owner(owner)
github psycopg / psycopg2 / examples / threads.py View on Github external
def select_func(conn_or_pool, z):
    name = threading.currentThread().getName()

    if MODE == 0:
        conn = conn_or_pool
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
    
    for i in range(SELECT_SIZE):
        if divmod(i, SELECT_STEP)[1] == 0:
            try:
                if MODE == 1:
                    conn = conn_or_pool.getconn()
                    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
                c = conn.cursor()
                c.execute("SELECT * FROM test_threads WHERE value2 < %s",
                          (int(i/z),))
                l = c.fetchall()
                if MODE == 1:
                    conn_or_pool.putconn(conn)
                s = name + ": number of rows fetched: " + str(len(l))
                print s
            except psycopg2.ProgrammingError, err:
github netdata / netdata / collectors / python.d.plugin / postgres / postgres.chart.py View on Github external
def connect(self):
        if self.conn:
            self.conn.close()
            self.conn = None

        try:
            self.conn = psycopg2.connect(**self.conn_params)
            self.conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
            self.conn.set_session(readonly=True)
        except OperationalError as error:
            self.error(error)
            self.alive = False
        else:
            self.alive = True

        return self.alive