How to use the psycopg2.ProgrammingError 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 BioDepot / BioDepot-workflow-builder / orange3 / Orange / widgets / data / owsql.py View on Github external
with self.backend.execute_sql_query(
                        "DROP TABLE IF EXISTS " + self.materialize_table_name
                    ):
                        pass
                    with self.backend.execute_sql_query(
                        "CREATE TABLE "
                        + self.materialize_table_name
                        + " AS "
                        + self.sql
                    ):
                        pass
                    with self.backend.execute_sql_query(
                        "ANALYZE " + self.materialize_table_name
                    ):
                        pass
                except (psycopg2.ProgrammingError, BackendError) as ex:
                    self.Error.connection(str(ex))
                    return

        try:
            table = SqlTable(
                dict(
                    host=self.host,
                    port=self.port,
                    database=self.database,
                    user=self.username,
                    password=self.password,
                ),
                what,
                backend=type(self.backend),
                inspect_values=False,
            )
github Thurion / EDSM-RSE-for-EDMC / psycopg2 / extras.py View on Github external
else:
            lsn = "%X/%08X" % ((start_lsn >> 32) & 0xFFFFFFFF,
                               start_lsn & 0xFFFFFFFF)

        command += lsn

        if timeline != 0:
            if slot_type == REPLICATION_LOGICAL:
                raise psycopg2.ProgrammingError(
                    "cannot specify timeline for logical replication")

            command += " TIMELINE %d" % timeline

        if options:
            if slot_type == REPLICATION_PHYSICAL:
                raise psycopg2.ProgrammingError(
                    "cannot specify output plugin options for physical replication")

            command += " ("
            for k, v in options.iteritems():
                if not command.endswith('('):
                    command += ", "
                command += "%s %s" % (quote_ident(k, self), _A(str(v)))
            command += ")"

        self.start_replication_expert(command, decode=decode)
github psycopg / psycopg2 / lib / extras.py View on Github external
*oid* parameter, which can be found using a query such as :sql:`SELECT
    'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid*
    using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`.

    Note that, when passing a dictionary from Python to the database, both
    strings and unicode keys and values are supported. Dictionaries returned
    from the database have keys/values according to the *unicode* parameter.

    The |hstore| contrib module must be already installed in the database
    (executing the ``hstore.sql`` script in your ``contrib`` directory).
    Raise `~psycopg2.ProgrammingError` if the type is not found.
    """
    if oid is None:
        oid = HstoreAdapter.get_oids(conn_or_curs)
        if oid is None or not oid[0]:
            raise psycopg2.ProgrammingError(
                "hstore type not found in the database. "
                "please install it from your 'contrib/hstore.sql' file")
        else:
            array_oid = oid[1]
            oid = oid[0]

    if isinstance(oid, int):
        oid = (oid,)

    if array_oid is not None:
        if isinstance(array_oid, int):
            array_oid = (array_oid,)
        else:
            array_oid = tuple([x for x in array_oid if x])

    # create and register the typecaster
github aio-libs / aiopg / aiopg / utils.py View on Github external
def __exit__(self, *args):
        try:
            self._cur.close()
        except psycopg2.ProgrammingError:
            # seen instances where the cursor fails to close:
            #   https://github.com/aio-libs/aiopg/issues/364
            # We close it here so we don't return a bad connection to the pool
            self._conn.close()
            raise
        finally:
            try:
                self._pool.release(self._conn)
            finally:
                self._pool = None
                self._conn = None
                self._cur = None
github za-arthur / apod_fts / apod.py View on Github external
cur.execute(query_text)
        query_time = "%0.2f" % ((time.time() - starttime) * 1000)

        if faceted:
            entries = cur.fetchone()[0]
            no_entries = entries == None
        else:
            entries = cur.fetchall()
            no_entries = cur.rowcount == 0

        # There is no result. So show hints to user
        if no_entries:
            query = ("SELECT word FROM words WHERE word %% %s")
            cur.execute(query, [request.args['pattern']])
            hints = cur.fetchall()
    except ProgrammingError as e:
        error = e.pgerror

    query_text = query_text.decode('utf-8')

    return render_template(
        'show_apods.html',
        order=order,
        rank_func=rank_func,
        faceted=faceted,
        entries=entries,
        hints=hints,
        error=error,
        pattern=escape(request.args['pattern']),
        query_text=escape(query_text),
        query_time=query_time)
github tart / tart-mailer / libtart / postgres.py View on Github external
def __execute(self, query, parameters=[], table=True):
        """Execute a query on the database; return None, the value of the cell, the values in the row in
        a dictionary or the values of the rows in a list of dictionary."""

        with self.cursor() as cursor:
            if debug:
                print('QUERY: ' + str(cursor.mogrify(query, list(parameters))))

            try:
                cursor.execute(query, list(parameters))
            except psycopg2.ProgrammingError as error:
                raise ProgrammingError(error)
            except psycopg2.IntegrityError as error:
                raise IntegrityError(error)

            if table:
                if cursor.rowcount > 0:
                    return cursor.fetchall()

                return []

            if cursor.rowcount == 0:
                raise NoRow('Query does not return any rows.')

            if cursor.rowcount > 1:
                raise MoreThanOneRow('Query returned more than one row.')
github uptimejp / postgres-toolkit / postgres_toolkit / PsqlWrapper.py View on Github external
def connect(self):
        try:
            self.conn = psycopg2.connect(self.connection_string)
            return True
        except psycopg2.OperationalError as ex:
            raise ConnectionError(str(ex))
        except psycopg2.ProgrammingError as ex:
            raise ConnectionError(str(ex))
        assert False
github UCL-ShippingGroup / pyrate / pyrate / repositories / aisraw.py View on Github external
def _status(self):
		with self.conn.cursor() as cur:
			try:
				cur.execute("SELECT COUNT(*) FROM \""+ self.getTableName() +"\"")
				return cur.fetchone()[0]
			except psycopg2.ProgrammingError:
				return -1
github Thurion / EDSM-RSE-for-EDMC / psycopg2 / extras.py View on Github external
def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None):
        """Create streaming replication slot."""

        command = "CREATE_REPLICATION_SLOT %s " % quote_ident(slot_name, self)

        if slot_type is None:
            slot_type = self.connection.replication_type

        if slot_type == REPLICATION_LOGICAL:
            if output_plugin is None:
                raise psycopg2.ProgrammingError(
                    "output plugin name is required to create "
                    "logical replication slot")

            command += "LOGICAL %s" % quote_ident(output_plugin, self)

        elif slot_type == REPLICATION_PHYSICAL:
            if output_plugin is not None:
                raise psycopg2.ProgrammingError(
                    "cannot specify output plugin name when creating "
                    "physical replication slot")

            command += "PHYSICAL"

        else:
            raise psycopg2.ProgrammingError(
                "unrecognized replication type: %s" % repr(slot_type))
github schwehr / noaadata / aisutils / database.py View on Github external
name=str(vessel)

        if name=="":
            name=str(vessel)
        #sys.stderr.write('a NAME for '+str(vessel)+' is "'+name+'"\n')

        cu.execute('SELECT '+trackKey+' FROM '+trackTable+' WHERE userid='+str(vessel)+'\n')
        track_keys = cu.fetchall()
        #print 'track_keys',track_keys
        now = datetime.datetime.utcnow()
        if len(track_keys)==0:
            # Does not exist in the database, so insert a new line
            query = 'INSERT INTO track_lines (userid,name,track,update_timestamp) VALUES (%s,%s,GeomFromText(%s,4326),%s);'
            try:
                cu.execute(query,(vessel,name,lineWKT,now))
            except psycopg.ProgrammingError,inst:
                sys.stderr.write('psycopg2 execute flailed: '+str(inst)+'\n')
                traceback.print_exc(file=sys.stderr)
            else:
                vesselsUpdated += 1
        elif len(track_keys)==1:
            # Need to replace an existing row
            query = 'UPDATE track_lines SET name = %s, track = GeomFromText(%s,4326), update_timestamp = %s WHERE '+trackKey+' = %s'
            key = track_keys[0][0]
            try:
                cu.execute(query,(name,lineWKT,now,key))
            except psycopg.ProgrammingError,inst:
                sys.stderr.write('psycopg2 execute flailed: '+str(inst)+'\n')
                traceback.print_exc(file=sys.stderr)
            else:
                vesselsUpdated += 1
        else: