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_executemany_failure(self):
"""
Ensure that an exception is raised if one query in an executemany fails.
"""
self.cursor.execute("create table t1(a int, b varchar(10))")
params = [ (1, 'good'),
('error', 'not an int'),
(3, 'good') ]
self.assertRaises(pyodbc.Error, self.cursor.executemany, "insert into t1(a, b) value (?, ?)", params)
async def execute():
start = time.time()
while time.time() - start < 20:
await conn.execute('SELECT 1; SELECT pg_sleep(1);')
async def _kill_conn():
await asyncio.sleep(2)
await pg_server_local['container'].kill()
await pg_server_local['container'].delete(v=True, force=True)
pg_server_local['container'] = None
result = await asyncio.gather(
_kill_conn(), execute(), return_exceptions=True)
exc = result[1]
assert isinstance(exc, Error)
assert 9 == pool.freesize
assert not pool._used
def test_executemany_failure(self):
"""
Ensure that an exception is raised if one query in an executemany fails.
"""
self.cursor.execute("create table t1(a int, b varchar(10))")
params = [ (1, 'good'),
('error', 'not an int'),
(3, 'good') ]
self.assertRaises(pyodbc.Error, self.cursor.executemany, "insert into t1(a, b) value (?, ?)", params)
def test_is_disconnect(self):
connection = Mock(spec=_ConnectionFairy)
cursor = Mock(spec=pyodbc.Cursor)
errors = [
pyodbc.Error(
'HY000',
'[HY000] [Dremio][Dremio ODBC Driver]Connection lost in socket read attempt. Operation timed out (-1) (SQLExecDirectW)'
),
pyodbc.Error(
'HY000',
'[HY000] [Dremio][Dremio ODBC Driver]Socket closed by peer.'
),
]
for error in errors:
status = self.dialect.is_disconnect(error, connection, cursor)
eq_(status, True)
# check that the selected drain point type names are valid names
if params_dict[ParameterNames.demang_file]:
# check that the provided selected drainpoint types are valid drain point types
cursor = conn.cursor()
dp_type_rows = cursor.execute("SELECT * FROM DrainTypeDefinitions").fetchall()
conn.close()
valid_drainpoint_type_names = [row.DrainTypeName for row in dp_type_rows]
# create a list of drain point type names from the string of comma separated drain point type names
params_dict[ParameterNames.selected_drainpoint_types] = params_dict[ParameterNames.selected_drainpoint_types].split(",")
for drain_type_name in params_dict[ParameterNames.selected_drainpoint_types]:
if drain_type_name not in valid_drainpoint_type_names:
raise utils.ValidationException("Invalid drain type name (%s) found." % drain_type_name)
else:
conn.close()
except pyodbc.Error as ex:
raise utils.ValidationException(ex.message)
#
# The connection timeout period is set through SQLSetConnectAttr, SQL_ATTR_CONNECTION_TIMEOUT.
#
# SQL_ATTR_CONNECTION_TIMEOUT appears not be supported by the psqlodbc driver (PostgreSQL).
# Psqlodbc throws a general error 'HY000' for which no implementation-specific SQLSTATE was defined:
# ('HY000', u"[HY000] Couldn't set unsupported connect attribute 113 (216) (SQLSetConnectAttr)")
#
# Oracle11g driver (Oracle database) also appears not support timeout and throws an error:
# ('HYC00', u'[HYC00] [Oracle][ODBC]Optional feature not implemented ....(0) (SQLSetConnectAttr)')))
#
# Try to catch a pyodbc.Error, log it as warning and pass.
try:
# Query statement timeout defaults to 0, which means "no timeout"
db_connection.timeout = sql_query_timeout
except pyodbc.Error as e:
sql_state = e.args[0]
error_message = e.args[1]
LOG.warning("ODBC driver does not implement the connection timeout attribute. "
"Error code: %s - %s", sql_state, error_message)
pass
except Exception as e:
raise Exception("Could not setup the ODBC connection, Exception %s", e)
return db_connection
#except (pymssql.Error), (why):
except (pyodbc.Error), (why):
return '',2,why
#except (_mssql.error), (why):
# return '',3,why
else:
#if Debug: print self.cursor.description
try:
if not commit:
self.result = self.cursor.fetchall()
else:
self.result = ''
self.db.close()
except (pyodbc.Warning), (why):
return '',3,why
except (pyodbc.Error), (why):
return '',4,why
else:
return self.result,0,''
def absent(user_facts, cursor, user, roles):
user_key = user.lower()
if user_key in user_facts:
update_roles(user_facts, cursor, user,
user_facts[user_key]['roles'], user_facts[user_key]['default_roles'], [])
try:
cursor.execute("drop user {0}".format(user_facts[user_key]['name']))
except pyodbc.Error:
raise CannotDropError("Dropping user failed due to dependencies.")
del user_facts[user_key]
return True
else:
return False
cursor.execute(query)
data = cursor.fetchall()
if cursor.description is not None:
columns = self.fetch_columns([(i[0], types_map.get(i[1], None)) for i in cursor.description])
rows = [dict(zip((column['name'] for column in columns), row)) for row in data]
data = {'columns': columns, 'rows': rows}
json_data = json_dumps(data)
error = None
else:
error = "No data was returned."
json_data = None
cursor.close()
except pyodbc.Error as e:
try:
# Query errors are at `args[1]`
error = e.args[1]
except IndexError:
# Connection errors are `args[0][1]`
error = e.args[0][1]
json_data = None
except KeyboardInterrupt:
connection.cancel()
error = "Query cancelled by user."
json_data = None
finally:
if connection:
connection.close()
return json_data, error
def _is_conn_close_error(e):
if not isinstance(e, Error) or len(e.args) < 2:
return False
sqlstate, msg = e.args[0], e.args[1]
if sqlstate not in _CONN_CLOSE_ERRORS:
return False
check_msg = _CONN_CLOSE_ERRORS[sqlstate]
if not check_msg:
return True
return msg.startswith(check_msg)