Python psycopg2.InterfaceError() Examples

The following are 28 code examples of psycopg2.InterfaceError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psycopg2 , or try the search function .
Example #1
Source File: test_pgexecute.py    From pgcli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_exit_without_active_connection(executor):
    quit_handler = MagicMock()
    pgspecial = PGSpecial()
    pgspecial.register(
        quit_handler,
        "\\q",
        "\\q",
        "Quit pgcli.",
        arg_type=NO_QUERY,
        case_sensitive=True,
        aliases=(":q",),
    )

    with patch.object(executor, "conn", BrokenConnection()):
        # we should be able to quit the app, even without active connection
        run(executor, "\\q", pgspecial=pgspecial)
        quit_handler.assert_called_once()

        # an exception should be raised when running a query without active connection
        with pytest.raises(psycopg2.InterfaceError):
            run(executor, "select 1", pgspecial=pgspecial) 
Example #2
Source File: report_processor.py    From koku with GNU Affero General Public License v3.0 6 votes vote down vote up
def process(self):
        """
        Process the current cost usage report.

        Args:
            None

        Returns:
            (List) List of filenames downloaded.

        """
        try:
            return self._processor.process()
        except (InterfaceError, DjangoInterfaceError, OperationalError) as err:
            raise ReportProcessorDBError(str(err))
        except Exception as err:
            raise ReportProcessorError(str(err)) 
Example #3
Source File: test_connection.py    From aiopg with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_closing_in_separate_task(connect, loop):
    closed_event = asyncio.Event(loop=loop)
    exec_created = asyncio.Event(loop=loop)

    async def waiter(conn):
        cur = await conn.cursor()
        fut = cur.execute("SELECT pg_sleep(1000)")
        exec_created.set()
        await closed_event.wait()
        with pytest.raises(psycopg2.InterfaceError):
            await fut

    async def closer(conn):
        await exec_created.wait()
        await conn.close()
        closed_event.set()

    conn = await connect()
    await asyncio.gather(waiter(conn), closer(conn), loop=loop) 
Example #4
Source File: postgres.py    From workload-automation with Apache License 2.0 5 votes vote down vote up
def cast_level(value, cur):  # pylint: disable=unused-argument
    """Generic Level caster for psycopg2"""
    if not InterfaceError:
        raise ImportError('There was a problem importing psycopg2.')
    if value is None:
        return None

    m = re.match(r"([^\()]*)\((\d*)\)", value)
    name = str(m.group(1))
    number = int(m.group(2))

    if m:
        return level(name, number)
    else:
        raise InterfaceError("Bad level representation: {}".format(value)) 
Example #5
Source File: test_pgexecute.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cursor(self):
        raise psycopg2.InterfaceError("I'm broken!") 
Example #6
Source File: test_cursor.py    From aiopg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_callproc(connect):
    conn = await connect()
    cur = await conn.cursor()
    await cur.callproc('inc', [1])
    ret = await cur.fetchone()
    assert (2,) == ret

    cur.close()
    with pytest.raises(psycopg2.InterfaceError):
        await cur.callproc('inc', [1])
    assert conn._waiter is None 
Example #7
Source File: test_cursor.py    From aiopg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_close_twice(connect):
    conn = await connect()
    cur = await conn.cursor()
    cur.close()
    cur.close()
    assert cur.closed
    with pytest.raises(psycopg2.InterfaceError):
        await cur.execute('SELECT 1')
    assert conn._waiter is None 
Example #8
Source File: test_cursor.py    From aiopg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_close(cursor):
    cursor.close()
    assert cursor.closed
    with pytest.raises(psycopg2.InterfaceError):
        await cursor.execute('SELECT 1') 
Example #9
Source File: extras.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def tokenize(self, s):
        rv = []
        for m in self._re_tokenize.finditer(s):
            if m is None:
                raise psycopg2.InterfaceError("can't parse type: %r" % s)
            if m.group(1) is not None:
                rv.append(None)
            elif m.group(2) is not None:
                rv.append(self._re_undouble.sub(r"\1", m.group(2)))
            else:
                rv.append(m.group(3))

        return rv 
Example #10
Source File: extras.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")):
        """Parse an hstore representation in a Python string.

        The hstore is represented as something like::

            "a"=>"1", "b"=>"2"

        with backslash-escaped strings.
        """
        if s is None:
            return None

        rv = {}
        start = 0
        for m in self._re_hstore.finditer(s):
            if m is None or m.start() != start:
                raise psycopg2.InterfaceError(
                    "error parsing hstore pair at char %d" % start)
            k = _bsdec.sub(r'\1', m.group(1))
            v = m.group(2)
            if v is not None:
                v = _bsdec.sub(r'\1', v)

            rv[k] = v
            start = m.end()

        if start < len(s):
            raise psycopg2.InterfaceError(
                "error parsing hstore: unparsed data after char %d" % start)

        return rv 
Example #11
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_truncate_larger_than_2gb(self):
        lo = self.conn.lobject()
        length = 1 << 32  # 4gb
        self.assertRaises(
            (OverflowError, psycopg2.InterfaceError, psycopg2.NotSupportedError),
            lo.truncate, length) 
Example #12
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_seek_larger_than_2gb(self):
        lo = self.conn.lobject()
        offset = 1 << 32  # 4gb
        self.assertRaises(
            (OverflowError, psycopg2.InterfaceError, psycopg2.NotSupportedError),
            lo.seek, offset, 0) 
Example #13
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_tell_after_close(self):
        lo = self.conn.lobject()
        lo.close()
        self.assertRaises(psycopg2.InterfaceError, lo.tell) 
Example #14
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_seek_after_close(self):
        lo = self.conn.lobject()
        lo.close()
        self.assertRaises(psycopg2.InterfaceError, lo.seek, 0) 
Example #15
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_read_after_close(self):
        lo = self.conn.lobject()
        lo.close()
        self.assertRaises(psycopg2.InterfaceError, lo.read, 5) 
Example #16
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_write_after_close(self):
        lo = self.conn.lobject()
        lo.close()
        self.assertRaises(psycopg2.InterfaceError, lo.write, b("some data")) 
Example #17
Source File: test_types_extras.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_parse(self):
        from psycopg2.extras import HstoreAdapter

        def ok(s, d):
            self.assertEqual(HstoreAdapter.parse(s, None), d)

        ok(None, None)
        ok('', {})
        ok('"a"=>"1", "b"=>"2"', {'a': '1', 'b': '2'})
        ok('"a"  => "1" ,"b"  =>  "2"', {'a': '1', 'b': '2'})
        ok('"a"=>NULL, "b"=>"2"', {'a': None, 'b': '2'})
        ok(r'"a"=>"\"", "\""=>"2"', {'a': '"', '"': '2'})
        ok('"a"=>"\'", "\'"=>"2"', {'a': "'", "'": '2'})
        ok('"a"=>"1", "b"=>NULL', {'a': '1', 'b': None})
        ok(r'"a\\"=>"1"', {'a\\': '1'})
        ok(r'"a\""=>"1"', {'a"': '1'})
        ok(r'"a\\\""=>"1"', {r'a\"': '1'})
        ok(r'"a\\\\\""=>"1"', {r'a\\"': '1'})

        def ko(s):
            self.assertRaises(psycopg2.InterfaceError,
                HstoreAdapter.parse, s, None)

        ko('a')
        ko('"a"')
        ko(r'"a\\""=>"1"')
        ko(r'"a\\\\""=>"1"')
        ko('"a=>"1"')
        ko('"a"=>"1", "b"=>NUL') 
Example #18
Source File: test_connection.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_closed(self):
        self.conn.close()
        self.assertRaises(psycopg2.InterfaceError,
            setattr, self.conn, 'autocommit', True)

        # The getter doesn't have a guard. We may change this in future
        # to make it consistent with other methods; meanwhile let's just check
        # it doesn't explode.
        try:
            self.assert_(self.conn.autocommit in (True, False))
        except psycopg2.InterfaceError:
            pass 
Example #19
Source File: test_connection.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_closed(self):
        self.conn.close()
        self.assertRaises(psycopg2.InterfaceError,
            self.conn.set_session,
            psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE) 
Example #20
Source File: test_connection.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_isolation_level_closed(self):
        cnn = self.connect()
        cnn.close()
        self.assertRaises(psycopg2.InterfaceError, getattr,
            cnn, 'isolation_level')
        self.assertRaises(psycopg2.InterfaceError,
            cnn.set_isolation_level, 0)
        self.assertRaises(psycopg2.InterfaceError,
            cnn.set_isolation_level, 1) 
Example #21
Source File: test_with.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_with_closed(self):
        def f():
            with self.conn:
                pass

        self.conn.close()
        self.assertRaises(psycopg2.InterfaceError, f) 
Example #22
Source File: test_async.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def test_async_cursor_gone(self):
        import gc
        cur = self.conn.cursor()
        cur.execute("select 42;");
        del cur
        gc.collect()
        self.assertRaises(psycopg2.InterfaceError, self.wait, self.conn)

        # The connection is still usable
        cur = self.conn.cursor()
        cur.execute("select 42;");
        self.wait(self.conn)
        self.assertEqual(cur.fetchone(), (42,)) 
Example #23
Source File: sql_manager.py    From zoe with Apache License 2.0 5 votes vote down vote up
def cursor(self):
        """Get a cursor, making sure the connection to the database is established."""
        try:
            cur = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        except psycopg2.InterfaceError:
            self._connect()
            cur = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        try:
            cur.execute('SET search_path TO {},public'.format(self.schema))
        except psycopg2.InternalError:
            self._connect()
            cur = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
            cur.execute('SET search_path TO {},public'.format(self.schema))
        return cur 
Example #24
Source File: connection_factory.py    From crontabber with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, config, local_config=None):
        """Initialize the parts needed to start making database connections

        parameters:
            config - the complete config for the app.  If a real app, this
                     would be where a logger or other resources could be
                     found.
            local_config - this is the namespace within the complete config
                           where the actual database parameters are found"""
        super(ConnectionFactory, self).__init__()
        self.config = config
        if local_config is None:
            local_config = config
        self.dsn = (
            "host=%(host)s "
            "dbname=%(dbname)s "
            "port=%(port)s "
            "user=%(user)s "
            "password=%(password)s"
            % local_config
        )
        self.operational_exceptions = (
            psycopg2.OperationalError,
            psycopg2.InterfaceError,
            socket.timeout
        )
        self.conditional_exceptions = (
            psycopg2.ProgrammingError,
        )
        self.pool = {}

    #-------------------------------------------------------------------------- 
Example #25
Source File: extras.py    From aws-workshop with MIT License 5 votes vote down vote up
def tokenize(self, s):
        rv = []
        for m in self._re_tokenize.finditer(s):
            if m is None:
                raise psycopg2.InterfaceError("can't parse type: %r" % s)
            if m.group(1) is not None:
                rv.append(None)
            elif m.group(2) is not None:
                rv.append(self._re_undouble.sub(r"\1", m.group(2)))
            else:
                rv.append(m.group(3))

        return rv 
Example #26
Source File: extras.py    From aws-workshop with MIT License 5 votes vote down vote up
def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")):
        """Parse an hstore representation in a Python string.

        The hstore is represented as something like::

            "a"=>"1", "b"=>"2"

        with backslash-escaped strings.
        """
        if s is None:
            return None

        rv = {}
        start = 0
        for m in self._re_hstore.finditer(s):
            if m is None or m.start() != start:
                raise psycopg2.InterfaceError(
                    "error parsing hstore pair at char %d" % start)
            k = _bsdec.sub(r'\1', m.group(1))
            v = m.group(2)
            if v is not None:
                v = _bsdec.sub(r'\1', v)

            rv[k] = v
            start = m.end()

        if start < len(s):
            raise psycopg2.InterfaceError(
                "error parsing hstore: unparsed data after char %d" % start)

        return rv 
Example #27
Source File: cluster_monitor.py    From pglookout with Apache License 2.0 4 votes vote down vote up
def _standby_status_query(self, instance, db_conn):
        """Status query that is executed on the standby node"""
        f_result = None
        result = {"fetch_time": get_iso_timestamp(), "connection": False}
        if not db_conn:
            db_conn = self._connect_to_db(instance, self.config["remote_conns"].get(instance))
            if not db_conn:
                return result
        try:
            phase = "querying status from"
            self.log.debug("%s %r", phase, instance)
            c = db_conn.cursor(cursor_factory=RealDictCursor)
            if db_conn.server_version >= 100000:
                fields = [
                    "now() AS db_time",
                    "pg_is_in_recovery()",
                    "pg_last_xact_replay_timestamp()",
                    "pg_last_wal_receive_lsn() AS pg_last_xlog_receive_location",
                    "pg_last_wal_replay_lsn() AS pg_last_xlog_replay_location",
                ]
            else:
                fields = [
                    "now() AS db_time",
                    "pg_is_in_recovery()",
                    "pg_last_xact_replay_timestamp()",
                    "pg_last_xlog_receive_location()",
                    "pg_last_xlog_replay_location()",
                ]
            query = "SELECT {}".format(", ".join(fields))
            c.execute(query)
            wait_select(c.connection)
            f_result = c.fetchone()
            if not f_result['pg_is_in_recovery']:
                # This is only run on masters to create txid traffic every db_poll_interval
                phase = "updating transaction on"
                self.log.debug("%s %r", phase, instance)
                # With pg_current_wal_lsn we simulate replay_location on the master
                # With txid_current we force a new transaction to occur every poll interval to ensure there's
                # a heartbeat for the replication lag.
                if db_conn.server_version >= 100000:
                    c.execute("SELECT txid_current(), pg_current_wal_lsn() AS pg_last_xlog_replay_location")
                else:
                    c.execute("SELECT txid_current(), pg_current_xlog_location() AS pg_last_xlog_replay_location")
                wait_select(c.connection)
                master_result = c.fetchone()
                f_result["pg_last_xlog_replay_location"] = master_result["pg_last_xlog_replay_location"]
        except (PglookoutTimeout, psycopg2.DatabaseError, psycopg2.InterfaceError, psycopg2.OperationalError) as ex:
            self.log.warning("%s (%s) %s %s", ex.__class__.__name__, str(ex).strip(), phase, instance)
            db_conn.close()
            self.db_conns[instance] = None
            # Return "no connection" result in case of any error. If we get an error for master server after the initial
            # query we'd end up returning completely invalid value for master's current position
            return result

        result.update(self._parse_status_query_result(f_result))
        return result 
Example #28
Source File: airbnb_listing.py    From airbnb-data-collection with MIT License 4 votes vote down vote up
def save(self, insert_replace_flag):
        """
        Save a listing in the database. Delegates to lower-level methods
        to do the actual database operations.
        Return values:
            True: listing is saved in the database
            False: listing already existed
        """
        try:
            rowcount = -1
            if self.deleted == 1:
                self.save_as_deleted()
            else:
                if insert_replace_flag == self.config.FLAGS_INSERT_REPLACE:
                    rowcount = self.__update()
                if (rowcount == 0 or
                        insert_replace_flag == self.config.FLAGS_INSERT_NO_REPLACE):
                    try:
                        self.__insert()
                        return True
                    except psycopg2.IntegrityError:
                        logger.debug("Room " + str(self.room_id) + ": already collected")
                        return False
        except psycopg2.OperationalError:
            # connection closed
            logger.error("Operational error (connection closed): resuming")
            del(self.config.connection)
        except psycopg2.DatabaseError as de:
            self.config.connection.conn.rollback()
            logger.erro(psycopg2.errorcodes.lookup(de.pgcode[:2]))
            logger.error("Database error: resuming")
            del(self.config.connection)
        except psycopg2.InterfaceError:
            # connection closed
            logger.error("Interface error: resuming")
            del(self.config.connection)
        except psycopg2.Error as pge:
            # database error: rollback operations and resume
            self.config.connection.conn.rollback()
            logger.error("Database error: " + str(self.room_id))
            logger.error("Diagnostics " + pge.diag.message_primary)
            del(self.config.connection)
        except (KeyboardInterrupt, SystemExit):
            raise
        except UnicodeEncodeError as uee:
            logger.error("UnicodeEncodeError Exception at " +
                         str(uee.object[uee.start:uee.end]))
            raise
        except ValueError:
            logger.error("ValueError for room_id = " + str(self.room_id))
        except AttributeError:
            logger.error("AttributeError")
            raise
        except Exception:
            self.config.connection.rollback()
            logger.error("Exception saving room")
            raise