本文整理汇总了Python中psycopg2.IntegrityError方法的典型用法代码示例。如果您正苦于以下问题:Python psycopg2.IntegrityError方法的具体用法?Python psycopg2.IntegrityError怎么用?Python psycopg2.IntegrityError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类psycopg2
的用法示例。
在下文中一共展示了psycopg2.IntegrityError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simple_db_mutate_returning_item
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def simple_db_mutate_returning_item(result_cls, context, mutation_query, *,
item_query, item_cls):
async with context['dbpool'].acquire() as conn, conn.begin():
try:
result = await conn.execute(mutation_query)
if result.rowcount > 0:
result = await conn.execute(item_query)
item = await result.first()
return result_cls(True, 'success', item_cls.from_row(item))
else:
return result_cls(False, 'no matching record', None)
except (pg.IntegrityError, sa.exc.IntegrityError) as e:
return result_cls(False, f'integrity error: {e}', None)
except (asyncio.CancelledError, asyncio.TimeoutError):
raise
except Exception as e:
return result_cls(False, f'unexpected error: {e}', None)
示例2: mutate
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def mutate(cls, root, info, gid):
async with info.context['dbpool'].acquire() as conn, conn.begin():
try:
# query = groups.delete().where(groups.c.id == gid)
query = groups.update().values(is_active=False,
integration_id=None).where(groups.c.id == gid)
result = await conn.execute(query)
if result.rowcount > 0:
return cls(ok=True, msg='success')
else:
return cls(ok=False, msg='no such group')
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}')
示例3: aiopg_exception_handling
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def aiopg_exception_handling(exception):
err_msg = str(exception)
body = {"err_msg": err_msg}
if isinstance(exception, psycopg2.IntegrityError):
if "duplicate key" in err_msg:
return DBResponse(response_code=409, body=json.dumps(body))
elif "foreign key" in err_msg:
return DBResponse(response_code=404, body=json.dumps(body))
else:
return DBResponse(response_code=500, body=json.dumps(body))
elif isinstance(exception, psycopg2.errors.UniqueViolation):
return DBResponse(response_code=409, body=json.dumps(body))
elif isinstance(exception, IndexError):
return DBResponse(response_code=404, body="{}")
else:
return DBResponse(response_code=500, body=json.dumps(body))
示例4: insert_phash_link_many
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def insert_phash_link_many(self, link_tuples):
try:
with self.transaction() as cur:
for item_1, item_2, distance in link_tuples:
item_1, item_2 = min(item_1, item_2), max(item_1, item_2)
cur.execute(''' INSERT INTO
{table}_plink (item_1_link, item_2_link, distance)
VALUES (%s, %s, %s)
ON CONFLICT DO NOTHING
'''.format(table=self.tableName), (item_1, item_2, distance))
except (psycopg2.OperationalError, psycopg2.IntegrityError):
for item_1, item_2, distance in link_tuples:
item_1, item_2 = min(item_1, item_2), max(item_1, item_2)
try:
with self.transaction() as cur:
cur.execute(''' INSERT INTO
{table}_plink (item_1_link, item_2_link, distance)
VALUES (%s, %s, %s)
ON CONFLICT DO NOTHING
'''.format(table=self.tableName), (item_1, item_2, distance))
except (psycopg2.OperationalError, psycopg2.IntegrityError):
self.log.error("Failure inserting link between %s and %s with distance %s. Skipping", distance, item_1, item_2)
示例5: _create_database
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def _create_database(engine: "Engine", db: Text):
"""Create database `db` on `engine` if it does not exist."""
import psycopg2
conn = engine.connect()
cursor = conn.connection.cursor()
cursor.execute("COMMIT")
cursor.execute(f"SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{db}'")
exists = cursor.fetchone()
if not exists:
try:
cursor.execute(f"CREATE DATABASE {db}")
except psycopg2.IntegrityError as e:
logger.error(f"Could not create database '{db}': {e}")
cursor.close()
conn.close()
示例6: test_error
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def test_error(self):
cur = self.conn.cursor()
cur.execute("insert into table1 values (%s)", (1, ))
self.wait(cur)
cur.execute("insert into table1 values (%s)", (1, ))
# this should fail
self.assertRaises(psycopg2.IntegrityError, self.wait, cur)
cur.execute("insert into table1 values (%s); "
"insert into table1 values (%s)", (2, 2))
# this should fail as well
self.assertRaises(psycopg2.IntegrityError, self.wait, cur)
# but this should work
cur.execute("insert into table1 values (%s)", (2, ))
self.wait(cur)
# and the cursor should be usable afterwards
cur.execute("insert into table1 values (%s)", (3, ))
self.wait(cur)
cur.execute("select * from table1 order by id")
self.wait(cur)
self.assertEquals(cur.fetchall(), [(1, ), (2, ), (3, )])
cur.execute("delete from table1")
self.wait(cur)
示例7: tip_multiple
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def tip_multiple(token, source, dict):
db = database()
cur = db.cursor()
cur.execute("SELECT * FROM accounts WHERE account = ANY(%s) FOR UPDATE", (sorted(dict.keys() + [source]),))
spent = 0
for target in dict:
amount = dict[target]
try:
cur.execute("UPDATE accounts SET balance = balance - %s WHERE account = %s", (amount, source))
except psycopg2.IntegrityError as e:
raise NotEnoughMoney()
if not cur.rowcount:
raise NotEnoughMoney()
spent += amount
cur.execute("UPDATE accounts SET balance = balance + %s WHERE account = %s", (amount, target))
if not cur.rowcount:
cur.execute("INSERT INTO accounts VALUES (%s, %s)", (target, amount))
for target in dict:
txlog(cur, token, dict[target], src = source, dest = target)
db.commit()
示例8: withdraw
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def withdraw(token, account, address, amount):
db = database()
cur = db.cursor()
try:
cur.execute("UPDATE accounts SET balance = balance - %s WHERE account = %s", (amount + 1, account))
except psycopg2.IntegrityError as e:
raise NotEnoughMoney()
if not cur.rowcount:
raise NotEnoughMoney()
try:
tx = daemon().sendtoaddress(address, amount, comment = "sent with Doger")
except InsufficientFunds:
raise
except:
Logger.irclog("Emergency lock on account '%s'" % (account))
lock(account, True)
raise
db.commit()
txlog(cur, token, amount + 1, tx = tx.encode("ascii"), address = address, src = account)
db.commit()
return tx.encode("ascii")
示例9: lock
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def lock(account, state = None):
if state == None:
cur = database().cursor()
cur.execute("SELECT * FROM locked WHERE account = %s", (account,))
return not not cur.rowcount
elif state == True:
db = database()
cur = db.cursor()
try:
cur.execute("INSERT INTO locked VALUES (%s)", (account,))
db.commit()
except psycopg2.IntegrityError as e:
pass
elif state == False:
db = database()
cur = db.cursor()
cur.execute("DELETE FROM locked WHERE account = %s", (account,))
db.commit()
示例10: mutate
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def mutate(cls, root, info, email):
async with info.context['dbpool'].acquire() as conn, conn.begin():
try:
# Make all user keypairs inactive.
from ai.backend.manager.models import keypairs
query = (
keypairs.update()
.values(is_active=False)
.where(keypairs.c.user_id == email)
)
await conn.execute(query)
# Mark user as deleted.
query = (
users.update()
.values(status=UserStatus.DELETED)
.where(users.c.email == email)
)
result = await conn.execute(query)
if result.rowcount > 0:
return cls(ok=True, msg='success')
else:
return cls(ok=False, msg='no such user')
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}')
示例11: simple_db_mutate
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def simple_db_mutate(result_cls, context, mutation_query):
async with context['dbpool'].acquire() as conn, conn.begin():
try:
result = await conn.execute(mutation_query)
if result.rowcount > 0:
return result_cls(True, 'success')
else:
return result_cls(False, 'no matching record')
except (pg.IntegrityError, sa.exc.IntegrityError) as e:
return result_cls(False, f'integrity error: {e}')
except (asyncio.CancelledError, asyncio.TimeoutError):
raise
except Exception as e:
return result_cls(False, f'unexpected error: {e}')
示例12: populate_fixture
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def populate_fixture(db_connection, fixture_data, *,
ignore_unique_violation: bool = False):
def insert(table, row):
# convert enumtype to native values
for col in table.columns:
if isinstance(col.type, EnumType):
row[col.name] = col.type._enum_cls[row[col.name]]
elif isinstance(col.type, EnumValueType):
row[col.name] = col.type._enum_cls(row[col.name])
db_connection.execute(table.insert(), [row])
for table_name, rows in fixture_data.items():
table = getattr(models, table_name)
pk_cols = table.primary_key.columns
for row in rows:
if len(pk_cols) == 0:
# some tables may not have primary keys.
# (e.g., m2m relationship)
try:
insert(table, row)
except sa.exc.IntegrityError as e:
if ignore_unique_violation and isinstance(e.orig, pg.errors.UniqueViolation):
continue
raise
continue
# compose pk match where clause
pk_match = functools.reduce(lambda x, y: x & y, [
(col == row[col.name])
for col in pk_cols
])
ret = db_connection.execute(
sa.select(pk_cols).select_from(table).where(pk_match))
if ret.rowcount == 0:
insert(table, row)
else:
pk_tuple = tuple(row[col.name] for col in pk_cols)
log.info('skipped inserting {} to {} as the row already exists.',
f"[{','.join(pk_tuple)}]", table_name)
示例13: delete_invitation
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def delete_invitation(request: web.Request, params: Any) -> web.Response:
dbpool = request.app['dbpool']
access_key = request['keypair']['access_key']
request_email = request['user']['email']
inv_id = params['inv_id']
log.info('VFOLDER.DELETE_INVITATION (ak:{}, inv:{})', access_key, inv_id)
try:
async with dbpool.acquire() as conn:
query = (sa.select([vfolder_invitations.c.inviter,
vfolder_invitations.c.invitee])
.select_from(vfolder_invitations)
.where((vfolder_invitations.c.id == inv_id) &
(vfolder_invitations.c.state == VFolderInvitationState.PENDING)))
result = await conn.execute(query)
row = await result.first()
if row is None:
raise GenericNotFound('No such vfolder invitation')
if request_email == row.inviter:
state = VFolderInvitationState.CANCELED
elif request_email == row.invitee:
state = VFolderInvitationState.REJECTED
else:
raise GenericForbidden('Cannot change other user\'s invitaiton')
query = (vfolder_invitations
.update()
.where(vfolder_invitations.c.id == inv_id)
.values(state=state))
await conn.execute(query)
except (psycopg2.IntegrityError, sa.exc.IntegrityError) as e:
raise InternalServerError(f'integrity error: {e}')
except (asyncio.CancelledError, asyncio.TimeoutError):
raise
except Exception as e:
raise InternalServerError(f'unexpected error: {e}')
return web.json_response({})
示例14: add_weather_data
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def add_weather_data(self, data):
query = (
'INSERT INTO local_weather VALUES '
'(%(observation_time_rfc822)s, %(temp_c)s, '
'%(relative_humidity)s, %(pressure_mb)s, '
'%(weather)s)'
)
try:
self.query(query, data)
except pg.IntegrityError:
# already have weather for this datetime
pass
示例15: test_missing_column_required
# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import IntegrityError [as 别名]
def test_missing_column_required(self, db_session, missing_column_required):
with pytest.raises(psycopg2.IntegrityError):
dallinger.data.ingest_to_model(
missing_column_required, dallinger.models.Participant
)