How to use the psycopg2.IntegrityError 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 metabrainz / mbspotify / mbspotify / views.py View on Github external
# Check if threshold is reached. And if it is, marking mapping as deleted.
    try:
        cur.execute("SELECT * "
                    "FROM mapping_vote "
                    "JOIN mapping ON mapping_vote.mapping = mapping.id "
                    "WHERE mapping.mbid = %s"
                    "      AND mapping.spotify_uri = %s"
                    "      AND mapping.is_deleted = FALSE",
                    (mbid, spotify_uri))
        if cur.rowcount >= current_app.config["THRESHOLD"]:
            cur.execute("UPDATE mapping SET is_deleted = TRUE "
                        "WHERE mbid = %s AND spotify_uri = %s",
                        (mbid, spotify_uri))
            conn.commit()

    except psycopg2.IntegrityError as e:
        raise BadRequest(str(e))
    except psycopg2.OperationalError as e:
        raise ServiceUnavailable(str(e))

    response = Response()
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response
github mozilla / spade / vendor / django / db / backends / postgresql_psycopg2 / base.py View on Github external
def _commit(self):
        if self.connection is not None:
            try:
                return self.connection.commit()
            except Database.IntegrityError as e:
                six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
github arq5x / gemini / gemini / database_postgresql.py View on Github external
cursor.execute('insert into variants values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s, \
                                                         %s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', variant)
            cursor.execute("END TRANSACTION")
        # skip repeated keys until we get to the failed variant
        except psycopg2.IntegrityError, e:
            cursor.execute("END TRANSACTION")
            continue
        except psycopg2.ProgrammingError, e:
            print variant
            print "Error %s:" % (e.args[0])
            sys.exit(1)
github lablup / backend.ai-manager / src / ai / backend / manager / models / keypair.py View on Github external
async def mutate(cls, root, info, access_key):
        async with info.context['dbpool'].acquire() as conn, conn.begin():
            try:
                query = (keypairs.delete()
                                 .where(keypairs.c.access_key == access_key))
                result = await conn.execute(query)
                if result.rowcount > 0:
                    return cls(ok=True, msg='success')
                else:
                    return cls(ok=False, msg='no such keypair')
            except (pg.IntegrityError, sa.exc.IntegrityError) as e:
                return cls(ok=False,
                           msg=f'integrity error: {e}')
            except (asyncio.CancelledError, asyncio.TimeoutError):
                raise
            except Exception as e:
                return cls(ok=False,
                           msg=f'unexpected error: {e}')
github ooici / pyon / pyon / datastore / postgresql / base_store.py View on Github external
qual_ds_name = self._get_datastore_name(datastore_name)
        table = qual_ds_name + "_att"

        if isinstance(doc, str):
            doc_id = doc
        else:
            doc_id = doc['_id']
            self._assert_doc_rev(doc)

        statement_args = dict(docid=doc_id, rev=1, doc=buffer(data), name=attachment_name, content_type=content_type)
        with self.pool.cursor(**self.cursor_args) as cur:
            statement = "INSERT INTO " + table + " (docid, rev, doc, name, content_type) "+\
                        "VALUES (%(docid)s, 1, %(doc)s, %(name)s, %(content_type)s)"
            try:
                cur.execute(statement, statement_args)
            except IntegrityError:
                raise NotFound('Object with id %s does not exist.' % doc_id)
github istSOS / istsos2 / walib / istsos / services / services.py View on Github external
"""

                    insertMeasure = """
                        INSERT INTO %s.measures(
                            id_eti_fk, id_qi_fk, id_pro_fk, val_msr)
                    """ % (self.service)
                    insertMeasure += """
                        VALUES (%s, 100, %s, %s);
                    """

                    for observation in self.json:
                        try:
                            id_eti = conn.executeInTransaction(
                                insertEventTime, (rows[0][0], observation[0]))

                        except psycopg2.IntegrityError as ie:
                            conn.rollbackTransaction()
                            conn.executeInTransaction(
                                deleteEventTime, (rows[0][0], observation[0]))
                            id_eti = conn.executeInTransaction(
                                insertEventTime, (rows[0][0], observation[0]))

                        for idx in range(0, len(rows)):
                            conn.executeInTransaction(
                                insertMeasure, (int(id_eti[0][0]),
                                                int(rows[idx][1]),
                                                float(observation[(idx+1)])))

                        conn.commitTransaction()

                self.setMessage("Faster than light!")
github osm-fr / osmose-frontend / control / update.py View on Github external
def update_timestamp(self, attrs):
        self.ts = attrs.get("timestamp", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
        self.version = attrs.get("version", None)
        self.analyser_version = attrs.get("analyser_version", None)

        if not self._tstamp_updated:
            try:
                execute_sql(self._dbcurs, "INSERT INTO updates (source_id, timestamp, remote_url, remote_ip, version, analyser_version) VALUES(%s, %s, %s, %s, %s, %s);",
                                     (self._source_id, utils.pg_escape(self.ts),
                                      utils.pg_escape(self._source_url),
                                      utils.pg_escape(self._remote_ip),
                                      utils.pg_escape(self.version),
                                      utils.pg_escape(self.analyser_version)))
            except psycopg2.IntegrityError:
                self._dbconn.rollback()
                execute_sql(self._dbcurs, "SELECT count(*) FROM updates WHERE source_id = %s AND \"timestamp\" = %s",
                                     (self._source_id, utils.pg_escape(self.ts)))
                r = self._dbcurs.fetchone()
                if r["count"] == 1:
                    raise OsmoseUpdateAlreadyDone("source=%s and timestamp=%s are already present" % (self._source_id, utils.pg_escape(self.ts)))
                else:
                    raise

            execute_sql(self._dbcurs, "UPDATE updates_last SET timestamp=%s, version=%s, analyser_version=%s, remote_ip=%s WHERE source_id=%s;",
                                 (utils.pg_escape(self.ts),
                                  utils.pg_escape(self.version),
                                  utils.pg_escape(self.analyser_version),
                                  utils.pg_escape(self._remote_ip),
                                  self._source_id))
            if self._dbcurs.rowcount == 0:
github moskytw / mosql / archived / examples / postgresql / person.py View on Github external
print

    print '# Arrange Rows into Models'
    print
    for person in Person.arrange({'person_id': ('mosky', 'andy')}):
        print person
    # or use ``Person.find(person_id=('mosky', 'andy'))`` in for-loop
    print

    print '# Insert a New Person'
    print
    from psycopg2 import IntegrityError
    from mosql.util import star
    try:
        new_person = Person.insert({'person_id': 'new'}, returning=star)
    except IntegrityError:
        print '(skip it, because this person is existent.)'
    else:
        print new_person
    print

    print '# Delete the New Person'
    print
    new_person = Person.delete({'person_id': 'new'}, returning=star)
    print new_person
    print
github dfm / osrc / scraper.py View on Github external
def _upsert(c, tbl, up_cmd, where, ins_cmd, *args):
    up_cmd = "update {0} {1} where {2}".format(tbl, up_cmd, where)
    a = ",".join(["%s"] * len(args))
    ins_cmd = "insert into {0}({1}) values({2})".format(tbl, ins_cmd, a)

    while True:
        c.execute(up_cmd, args)
        if c.rowcount == 0:
            try:
                c.execute(ins_cmd, args)
            except psycopg2.IntegrityError:
                continue
        return