Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_insert_error_handler(self):
error = apsw.ConstraintError("audit_evt.request_id")
wrong_error = apsw.ConstraintError()
query = "iNserT something audit_evt.request_id"
wrong_query = "select"
values = ()
class Sqlite3WorkerMock:
def __init__(self):
pass
with mock.patch('evt.evt_pool_manager.logger') as logger_mock:
worker_mock = Sqlite3WorkerMock()
EventPoolManager.insert_error_handler(worker_mock, query, values=values, err=error)
self.assertTrue(logger_mock.warning.called)
self.assertFalse(logger_mock.error.called)
with mock.patch('evt.evt_pool_manager.logger') as logger_mock:
# Misses proper error message
def test_insert_error_handler(self):
error = apsw.ConstraintError("audit_evt.request_id")
wrong_error = apsw.ConstraintError()
query = "iNserT something audit_evt.request_id"
wrong_query = "select"
values = ()
class Sqlite3WorkerMock:
def __init__(self):
pass
with mock.patch('evt.evt_pool_manager.logger') as logger_mock:
worker_mock = Sqlite3WorkerMock()
EventPoolManager.insert_error_handler(worker_mock, query, values=values, err=error)
self.assertTrue(logger_mock.warning.called)
self.assertFalse(logger_mock.error.called)
with mock.patch('evt.evt_pool_manager.logger') as logger_mock:
result = self.worker.execute("select * from evt_status")
# The result is string if the database is locked (caused by previously failed tests)
self.assertFalse(isinstance(result, str))
self.assertEqual(len(result), 5,
'We are expecting 5 event type records. There are {0}'.format(len(result)))
new_value = [x for x in result if x['id'] == 'AS'][0]
self.assertEqual(new_value, original_value,
"The original value changed after the insert")
# This should stay at the very end after the worker thread has been merged
self.worker.close()
self.assertTrue(logger_mock.error.called)
args, _ = logger_mock.error.call_args
self.assertTrue(isinstance(args[3], apsw.ConstraintError))
countem = 'select count(*) from %s' % (qt,)
assert not bayesdb_has_table(bdb, t)
with pytest.raises(ValueError):
bayesdb_read_pandas_df(bdb, t, df, index=index)
bayesdb_read_pandas_df(bdb, t, df, create=True, ifnotexists=False,
index=index)
assert len(df.index) == bdb.execute(countem).fetchvalue()
with pytest.raises(ValueError):
bayesdb_read_pandas_df(bdb, t, df, create=True, ifnotexists=False,
index=index)
assert 4 == bdb.execute(countem).fetchvalue()
with pytest.raises(apsw.ConstraintError):
bayesdb_read_pandas_df(bdb, t, df, create=True, ifnotexists=True,
index=index)
assert 4 == bdb.execute(countem).fetchvalue()
if beeping:
printterm('\a\a')
colscompl=[]
updated_tables=set()
#Autoupdate in case of schema change
if re.search(r'(?i)(create|attach|drop)', statement):
update_tablelist()
except KeyboardInterrupt:
print
schemaprint(newcols)
printterm("KeyboardInterrupt exception: Query execution stopped", exit=True)
continue
except (apsw.SQLError, apsw.ConstraintError , functions.MadisError), e:
emsg=unicode(e)
if pipedinput:
exitwitherror(functions.mstr(emsg))
else:
try:
if u'Error:' in emsg:
emsgsplit=emsg.split(u':')
print Fore.RED+Style.BRIGHT+ emsgsplit[0] +u':'+Style.RESET_ALL+ u':'.join(emsgsplit[1:])
else:
print e
except:
print e
continue
except Exception, e:
trlines = []
if not TraktOAuthCredentialManager.update.from_pin(oauth, pin, save=False):
log.warn("Unable to update OAuthCredential (token exchange failed, hasn't changed, etc..)")
return None
# Validate the account authorization
with t_account.oauth_authorization(oauth).http(retry=True):
settings = Trakt['users/settings'].get()
if not settings:
log.warn('Unable to retrieve account details for authorization')
return None
# Update `TraktAccount` username
try:
self.update_username(t_account, settings)
except (apsw.ConstraintError, peewee.IntegrityError), ex:
log.debug('Trakt account already exists - %s', ex, exc_info=True)
raise TraktAccountExistsException('Trakt account already exists')
# Save oauth credential changes
oauth.save()
# Refresh `TraktAccount`
t_account.refresh(
force=True,
settings=settings
)
# Refresh `Account`
t_account.account.refresh(
force=True
INSERT INTO bayesdb_crosscat_column_dependency
(generator_id, colno0, colno1, dependent)
VALUES (?, ?, ?, ?)
'''
for columns, dependent in parsed_schema.dep_constraints:
for col1, col2 in itertools.combinations(columns, 2):
col1_id = core.bayesdb_generator_column_number(bdb,
generator_id, col1)
col2_id = core.bayesdb_generator_column_number(bdb,
generator_id, col2)
min_col_id = min(col1_id, col2_id)
max_col_id = max(col1_id, col2_id)
try:
bdb.sql_execute(insert_dep_constraint_sql,
(generator_id, min_col_id, max_col_id, dependent))
except apsw.ConstraintError:
# XXX This is a cop-out -- we should validate
# the relation ourselves (and show a more
# helpful error message).
raise BQLError(bdb, 'Invalid dependency constraints!')
def or_create(self, *query, **kwargs):
try:
return self.manager.create(**kwargs)
except (apsw.ConstraintError, peewee.IntegrityError), ex:
log.debug('or_create() - ex: %r', ex)
return self(*query)
'''Renumber inodes'''
log.info('Renumbering inodes...')
total = db.get_val('SELECT COUNT(id) FROM inodes')
db.execute('CREATE TEMPORARY TABLE inode_ids AS '
'SELECT id FROM inodes WHERE id > ? ORDER BY id DESC',
(max(total, CTRL_INODE),))
db.execute('CREATE INDEX IF NOT EXISTS ix_contents_inode ON contents(inode)')
try:
i = 0
cur = CTRL_INODE+1
for (id_,) in db.query("SELECT id FROM inode_ids"):
while True:
try:
db.execute('UPDATE inodes SET id=? WHERE id=?', (cur, id_))
except apsw.ConstraintError:
cur += 1
else:
break
db.execute('UPDATE contents SET inode=? WHERE inode=?', (cur, id_))
db.execute('UPDATE contents SET parent_inode=? WHERE parent_inode=?', (cur, id_))
db.execute('UPDATE inode_blocks SET inode=? WHERE inode=?', (cur, id_))
db.execute('UPDATE symlink_targets SET inode=? WHERE inode=?', (cur, id_))
db.execute('UPDATE ext_attributes SET inode=? WHERE inode=?', (cur, id_))
cur += 1
i += 1
if i % 5000 == 0:
log.info('..processed %d inodes so far..', i)
finally:
def insert_error_handler(sql_worker, query, values, err):
"""
Handles error coming from a request insert to the database. It logs a warning if the
request already exists (based on the query and raised exception) and an error in every other
case
"""
if query.lower().strip().startswith("insert") \
and isinstance(err, apsw.ConstraintError) \
and "audit_evt.request_id" in str(err):
# this error was caused by an already existing event
logger.warning(
"Audit request already exists: %s: %s: %s",
query,
values,
err
)
else:
logger.error(
"Query returned error: %s: %s: %s",
query,
values,
err
)