How to use the psycopg2.OperationalError 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 pypa / warehouse / tests / unit / test_db.py View on Github external
def raiser():
        raise OperationalError("foo", {}, psycopg2.OperationalError())
github psycopg / psycopg2 / sandbox / test_green_error.py View on Github external
def wait_cb(conn):
    """A wait callback useful to allow eventlet to work with Psycopg."""
    while 1:
        if panic:
            raise Exception('whatever')

        state = conn.poll()
        if state == extensions.POLL_OK:
            break
        elif state == extensions.POLL_READ:
            trampoline(conn.fileno(), read=True)
        elif state == extensions.POLL_WRITE:
            trampoline(conn.fileno(), write=True)
        else:
            raise psycopg2.OperationalError(
                "Bad result from poll: %r" % state)
github getredash / redash / redash / query_runner / pg.py View on Github external
def _wait(conn, timeout=None):
    while 1:
        try:
            state = conn.poll()
            if state == psycopg2.extensions.POLL_OK:
                break
            elif state == psycopg2.extensions.POLL_WRITE:
                select.select([], [conn.fileno()], [], timeout)
            elif state == psycopg2.extensions.POLL_READ:
                select.select([conn.fileno()], [], [], timeout)
            else:
                raise psycopg2.OperationalError("poll() returned %s" % state)
        except select.error:
            raise psycopg2.OperationalError("select.error received")
github forkandwait / LCFIT / INTERNET_APPLICATION / LcDB.py View on Github external
while tries_N >= 0:
		try:
			curs = dbcon.cursor()
			curs.execute(sql, data)
			if fetch_N == 'all':
				res = curs.fetchall()
			elif fetch_N == 'one':
				res = curs.fetchone()
			elif fetch_N == 'none':
				res = None
			else:
				raise Exception, "Bad value for fetch_N: %s" % fetch_N
			curs.close()
			dbcon.commit()
			return (res,dbcon)
		except (psycopg2.OperationalError, psycopg2.InterfaceError, psycopg2.InternalError), e:
			lcfitlogger.error( "Error trying to execute query, reconnecting: \"%s\", \"%s\"." % (sql, e))
			tries_N -= 1
			time.sleep(2**tries_comp)
			tries_comp += 1
			try:
				dbcon = psycopg2.connect(dbcon.dsn)
			except Exception, e:
				raise LcDataException, "Exception trying to connect: \"%s\"." % str(e)
			lcfitlogger.warning( "Successfully reconnected, re-executed cursor.")
		except:
			raise
	raise
github brushtyler / db_manager / db_plugins / postgis / connector.py View on Github external
def connection_error_types(self):
		return psycopg2.InterfaceError, psycopg2.OperationalError
github zalando / patroni / patroni / postgresql.py View on Github external
def _query(self, sql, *params):
        """We are always using the same cursor, therefore this method is not thread-safe!!!
        You can call it from different threads only if you are holding explicit `AsyncExecutor` lock,
        because the main thread is always holding this lock when running HA cycle."""
        cursor = None
        try:
            cursor = self._cursor()
            cursor.execute(sql, params)
            return cursor
        except psycopg2.Error as e:
            if cursor and cursor.connection.closed == 0:
                # When connected via unix socket, psycopg2 can't recoginze 'connection lost'
                # and leaves `_cursor_holder.connection.closed == 0`, but psycopg2.OperationalError
                # is still raised (what is correct). It doesn't make sense to continiue with existing
                # connection and we will close it, to avoid its reuse by the `_cursor` method.
                if isinstance(e, psycopg2.OperationalError):
                    self.close_connection()
                else:
                    raise e
            if self.state == 'restarting':
                raise RetryFailedError('cluster is being restarted')
            raise PostgresConnectionException('connection problems')
github aio-libs / aiopg / aiopg / connection.py View on Github external
def _close(self):
        """Remove the connection from the event_loop and close it."""
        # N.B. If connection contains uncommitted transaction the
        # transaction will be discarded
        if self._fileno is not None:
            self._loop.remove_reader(self._fileno)
            if self._writing:
                self._writing = False
                self._loop.remove_writer(self._fileno)

        self._conn.close()
        self.free_cursor()

        if self._waiter is not None and not self._waiter.done():
            self._waiter.set_exception(
                psycopg2.OperationalError("Connection closed"))
github switch-model / switch / switch_model / hawaii / scenario_data.py View on Github external
global psycopg2
            import psycopg2
        except ImportError:
            print(dedent("""
                ############################################################################################
                Unable to import psycopg2 module to access database server.
                Please install this module via 'conda install psycopg2' or 'pip install psycopg2'.
                ############################################################################################
                """))
            raise
        try:
            pghost='redr.eng.hawaii.edu'
            # note: the connection gets created when the module loads and never gets closed (until presumably python exits)
            con = psycopg2.connect(database='switch', host=pghost) #, user='switch_user')

        except psycopg2.OperationalError:
            print(dedent("""
                ############################################################################################
                Error while connecting to switch database on postgres server {server}.
                Please ensure that the PGUSER environment variable is set with your postgres username
                and there is a line like "*:*:*::" in ~/.pgpass (which should be chmod 0600)
                or in %APPDATA%\postgresql\pgpass.conf (Windows).
                See http://www.postgresql.org/docs/9.1/static/libpq-pgpass.html for more details.
                ############################################################################################
                """.format(server=pghost)))
            raise
    return con.cursor()
github jdelic / django-dbconn-retry / django_dbconn_retry / __init__.py View on Github external
_log = logging.getLogger(__name__)
default_app_config = 'django_dbconn_retry.DjangoIntegration'

pre_reconnect = Signal(providing_args=["dbwrapper"])
post_reconnect = Signal(providing_args=["dbwrapper"])


_operror_types = ()  # type: Union[Tuple[type], Tuple]
_operror_types += (django_db_utils.OperationalError,)
try:
    import psycopg2
except ImportError:
    pass
else:
    _operror_types += (psycopg2.OperationalError,)

try:
    import sqlite3
except ImportError:
    pass
else:
    _operror_types += (sqlite3.OperationalError,)

try:
    import MySQLdb
except ImportError:
    pass
else:
    _operror_types += (MySQLdb.OperationalError,)