Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _run_explain(self, cursor, statement, schema):
# TODO: cleaner query cleaning to strip comments, etc.
if statement.strip().split(' ', 1)[0].lower() not in VALID_EXPLAIN_STATEMENTS:
return
try:
if schema is not None:
cursor.execute('USE `{}`'.format(schema))
cursor.execute('EXPLAIN FORMAT=json {statement}'.format(statement=statement))
except (pymysql.err.InternalError, pymysql.err.ProgrammingError) as e:
if len(e.args) != 2:
raise
if e.args[0] in (1046,):
self.log.warning('Failed to collect EXPLAIN due to a permissions error: %s', (e.args,))
return None
elif e.args[0] == 1064:
self.log.error('Programming error when collecting EXPLAIN: %s', (e.args,))
return None
else:
raise
return cursor.fetchone()[0]
async def execute(self, sql: str, params=None):
"""
Executes some SQL in the current transaction.
"""
# parse DictCursor in order to get a dict-like cursor back
# this will use the custom DictRow class passed from before
cursor = await self.connection.cursor(cursor=aiomysql.DictCursor)
# the doc lies btw
# we can pass a dict in instead of a list/tuple
# i don't fucking trust this at all though.
try:
res = await cursor.execute(sql, params)
except pymysql.err.IntegrityError as e:
raise IntegrityError(*e.args)
except (pymysql.err.ProgrammingError, pymysql.err.InternalError) as e:
raise DatabaseException(*e.args)
finally:
await cursor.close()
return res
def _check_executed(self):
if not self._executed:
raise ProgrammingError("execute() first")
def _get_db(self):
if not self._connection:
raise ProgrammingError("Cursor closed")
return self._connection
2013: "Server connection lost"}
if isinstance(client_error, client.err.OperationalError) and client_error.args[0] in disconnect_codes:
return errors.LostConnectionError(disconnect_codes[client_error.args[0]], *client_error.args[1:])
# Access errors
if isinstance(client_error, client.err.OperationalError) and client_error.args[0] in (1044, 1142):
return errors.AccessError('Insufficient privileges.', client_error.args[1], query)
# Integrity errors
if isinstance(client_error, client.err.IntegrityError) and client_error.args[0] == 1062:
return errors.DuplicateError(*client_error.args[1:])
if isinstance(client_error, client.err.IntegrityError) and client_error.args[0] == 1452:
return errors.IntegrityError(*client_error.args[1:])
# Syntax errors
if isinstance(client_error, client.err.ProgrammingError) and client_error.args[0] == 1064:
return errors.QuerySyntaxError(client_error.args[1], query)
# Existence errors
if isinstance(client_error, client.err.ProgrammingError) and client_error.args[0] == 1146:
return errors.MissingTableError(client_error.args[1], query)
if isinstance(client_error, client.err.InternalError) and client_error.args[0] == 1364:
return errors.MissingAttributeError(*client_error.args[1:])
if isinstance(client_error, client.err.InternalError) and client_error.args[0] == 1054:
return errors.UnknownAttributeError(*client_error.args[1:])
# all the other errors are re-raised in original form
return client_error
def prepare_table(args):
"""
To ensure the table structure was prepared.
"""
with connection.cursor() as cursor:
try:
print('Checking if `parts_filtered` exists...')
cursor.execute("DESCRIBE parts_filtered")
structures = cursor.fetchall()
except pymysql.err.ProgrammingError as e:
existence = False
print('`parts_filtered` does not exist')
else:
existence = True
print('`parts_filtered` exists')
if not existence or args.force_rebuild_table:
print(
'Rebuilding `parts_filtered` due to {}...'.format(
'non-existence'
if not existence
else '`force-rebuild-table` flag'
)
)
print('Reinstalling stored procedure...')
Links = {
"host": Config.mysql_host,
"port": Config.mysql_port,
"user": Config.mysql_usr,
"password": Config.mysql_pass,
}
try:
con = pymysql.connect(**Links)
with con.cursor() as cursor:
cursor.execute(
f"create database {Config.mysql_db} character set UTF8mb4 collate utf8mb4_bin"
)
con.close()
except pymysql.err.ProgrammingError as e:
if "1007" in str(e):
pass
except Exception as e:
raise e
class RetryOperationalError(object):
def execute_sql(self, sql, params=None, commit=True):
try:
cursor = super(RetryOperationalError, self).execute_sql(sql, params, commit)
except OperationalError:
if not self.is_closed():
self.close()
with __exception_wrapper__:
cursor = self.cursor()
cursor.execute(sql, params or ())
def _write_database_version(db_connection_string, version):
connection_params = _parse_mysql_dsn(db_connection_string)
db_conn = pymysql.connect(autocommit=True, **connection_params)
try:
with db_conn.cursor() as cursor:
sql = "UPDATE alembic_version SET version_num = %s"
cursor.execute(sql, (version))
except pymysql.err.ProgrammingError:
# Likely the table was missing
with db_conn.cursor() as cursor:
cursor.execute(TABLE_DEF)
create = "INSERT INTO alembic_version (version_num) VALUES (%s)"
cursor.execute(create, (version))