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_tsql_to_python_exception_translation(self):
"""An error raised by a SP is translated to a PEP-249-dictated, pymssql layer exception."""
# See https://github.com/pymssql/pymssql/issues/61
cursor = self.pymssql.cursor()
# Must raise an exception
self.assertRaises(Exception, cursor.callproc, 'SPThatRaisesAnError')
# Must be a PEP-249 exception, not a _mssql-layer one
try:
cursor.callproc('SPThatRaisesAnError')
except Exception as e:
self.assertTrue(isinstance(e, pymssql.Error))
# Must be a DatabaseError exception
try:
cursor.callproc('SPThatRaisesAnError')
except Exception as e:
self.assertTrue(isinstance(e, pymssql.DatabaseError))
STRING = DBAPITypeObject(_mssql.STRING)
BINARY = DBAPITypeObject(_mssql.BINARY)
NUMBER = DBAPITypeObject(_mssql.NUMBER)
DATETIME = DBAPITypeObject(_mssql.DATETIME)
DECIMAL = DBAPITypeObject(_mssql.DECIMAL)
### exception hierarchy
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
cur.execute(query)
result = cur.fetchone()
match = self.EST_ROWS_RE.search(result[0])
if not match:
# Either StatementEstRows was not found or
# a float is received.
# If it is a float then it is most probable
# that the server's statistics are out of date
# and the result is false. In that case
# it is preferable to return None so
# an exact count be used.
return None
return int(match.group(1))
finally:
cur.execute("SET SHOWPLAN_XML OFF")
except pymssql.Error as ex:
if "SHOWPLAN permission denied" in str(ex):
warnings.warn("SHOWPLAN permission denied, count approximates will not be used")
return None
raise BackendError(parse_ex(ex)) from ex
def Open(self, p_autocommit=True):
try:
self.v_con = pymssql.connect(
host=self.v_host,
port=int(self.v_port),
database=self.v_service,
user=self.v_user,
password=self.v_password
)
self.v_cur = self.v_con.cursor()
self.v_start = True
except pymssql.Error as exc:
raise Spartacus.Database.Exception(str(exc))
except Exception as exc:
raise Spartacus.Database.Exception(str(exc))
def Query(self, p_sql, p_alltypesstr=False, p_simple=False):
def fetchall(self):
try:
return self.cursor.fetchall()
except (pymssql.Error, _mssql.MssqlDatabaseException) as ex:
logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) '%s'" % getSafeExString(ex).replace("\n", " "))
return None
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 pymssql.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 db_connect(args):
if args.type == "mysql" or args.type == "mariadb":
import mysql.connector
try:
connection = mysql.connector.connect(
user=args.user,
password=args.password,
database=args.db)
except mysql.connector.Error as err:
print(colorize("red", "[ERROR] {}".format(err)))
return None
elif args.type == "mssql":
import pymssql
try:
connection = pymssql.connect(server="localhost", database=args.db)
except pymssql.Error as err:
print(colorize("red", "[ERROR] {}".format(err)))
return None
elif args.type == "pgsql":
import psycopg2
try:
connection = psycopg2.connect(
"dbname='{}' user='{}' password='{}'".format(
args.db, args.user, args.password))
except psycopg2.Error as err:
print(colorize("red", "[ERROR] {}".format(err)))
return None
elif args.type == "oracle":
import cx_Oracle
try:
connection = cx_Oracle.connect(
args.user, args.password, cx_Oracle.makedsn(
NUMBER = DBAPITypeObject(_mssql.NUMBER)
DATETIME = DBAPITypeObject(_mssql.DATETIME)
DECIMAL = DBAPITypeObject(_mssql.DECIMAL)
### exception hierarchy
class Warning(StandardError):
pass
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class DataError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class InternalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
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((c['name'] for c in columns), row)) for row in data]
data = {'columns': columns, 'rows': rows}
json_data = json.dumps(data, cls=MSSQLJSONEncoder)
error = None
else:
error = "No data was returned."
json_data = None
cursor.close()
except pymssql.Error as e:
logging.exception(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
except Exception as e:
raise sys.exc_info()[1], None, sys.exc_info()[2]
finally:
if connection:
def fetchall(self):
try:
return self.cursor.fetchall()
except (pymssql.Error, _mssql.MssqlDatabaseException), msg:
logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " "))
return None