Python django.db.utils.DatabaseError() Examples
The following are 30
code examples of django.db.utils.DatabaseError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.db.utils
, or try the search function
.
Example #1
Source File: features.py From openhgsenti with Apache License 2.0 | 6 votes |
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. """ with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support
Example #2
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def validate_thread_sharing(self): """ Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails. """ if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()): raise DatabaseError("DatabaseWrapper objects created in a " "thread can only be used in that same thread. The object " "with alias '%s' was created in thread id %s and this is " "thread id %s." % (self.alias, self._thread_ident, thread.get_ident())) # ##### Miscellaneous #####
Example #3
Source File: base.py From python2017 with MIT License | 6 votes |
def _nodb_connection(self): nodb_connection = super(DatabaseWrapper, self)._nodb_connection try: nodb_connection.ensure_connection() except (Database.DatabaseError, WrappedDatabaseError): warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the default database instead.", RuntimeWarning ) settings_dict = self.settings_dict.copy() settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'] nodb_connection = self.__class__( self.settings_dict.copy(), alias=self.alias, allow_thread_sharing=False) return nodb_connection
Example #4
Source File: creation.py From python2017 with MIT License | 6 votes |
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err): """ Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise. """ try: # Statement can fail when acceptable_ora_err is not None allow_quiet_fail = acceptable_ora_err is not None and len(acceptable_ora_err) > 0 self._execute_statements(cursor, statements, parameters, verbosity, allow_quiet_fail=allow_quiet_fail) return True except DatabaseError as err: description = str(err) if acceptable_ora_err is None or acceptable_ora_err not in description: raise return False
Example #5
Source File: base.py From python2017 with MIT License | 6 votes |
def validate_thread_sharing(self): """ Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails. """ if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()): raise DatabaseError( "DatabaseWrapper objects created in a " "thread can only be used in that same thread. The object " "with alias '%s' was created in thread id %s and this is " "thread id %s." % (self.alias, self._thread_ident, thread.get_ident()) ) # ##### Miscellaneous #####
Example #6
Source File: test_core.py From django-hordak with MIT License | 6 votes |
def test_postgres_trigger_sum_zero(self): """" Check the database enforces leg amounts summing to zero This is enforced by a postgres trigger applied in migration 0005. Note that this requires the test case extend TransactionTestCase, as the trigger is only run when changes are committed to the DB (which the normal TestCase will not do) """ account = self.account() transaction = Transaction.objects.create() with self.assertRaises(DatabaseError): Leg.objects.create(transaction=transaction, account=account, amount=100) with self.assertRaises(DatabaseError), db_transaction.atomic(): # Also ensure we distinguish between currencies Leg.objects.create(transaction=transaction, account=account, amount=Money(100, "EUR")) Leg.objects.create(transaction=transaction, account=account, amount=Money(-100, "GBP"))
Example #7
Source File: features.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. """ with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support
Example #8
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def _nodb_connection(self): nodb_connection = super(DatabaseWrapper, self)._nodb_connection try: nodb_connection.ensure_connection() except (DatabaseError, WrappedDatabaseError): warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the default database instead.", RuntimeWarning ) settings_dict = self.settings_dict.copy() settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'] nodb_connection = self.__class__( self.settings_dict.copy(), alias=self.alias, allow_thread_sharing=False) return nodb_connection
Example #9
Source File: features.py From python2017 with MIT License | 6 votes |
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. """ with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support
Example #10
Source File: schema.py From openhgsenti with Apache License 2.0 | 6 votes |
def delete_model(self, model, **kwargs): from django.contrib.gis.db.models.fields import GeometryField # Drop spatial metadata (dropping the table does not automatically remove them) for field in model._meta.local_fields: if isinstance(field, GeometryField): self.remove_geometry_metadata(model, field) # Make sure all geom stuff is gone for geom_table in self.geometry_tables: try: self.execute( self.sql_discard_geometry_columns % { "geom_table": geom_table, "table": self.quote_name(model._meta.db_table), } ) except DatabaseError: pass super(SpatialiteSchemaEditor, self).delete_model(model, **kwargs)
Example #11
Source File: base.py From openhgsenti with Apache License 2.0 | 6 votes |
def _nodb_connection(self): nodb_connection = super(DatabaseWrapper, self)._nodb_connection try: nodb_connection.ensure_connection() except (DatabaseError, WrappedDatabaseError): warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the default database instead.", RuntimeWarning ) settings_dict = self.settings_dict.copy() settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'] nodb_connection = self.__class__( self.settings_dict.copy(), alias=self.alias, allow_thread_sharing=False) return nodb_connection
Example #12
Source File: middleware.py From django-tenants with MIT License | 6 votes |
def process_request(self, request): connection.set_schema_to_public() hostname_without_port = remove_www_and_dev(request.get_host().split(':')[0]) try: domain = get_tenant_domain_model().objects.select_related('tenant').get(domain=hostname_without_port) request.tenant = domain.tenant except utils.DatabaseError: request.urlconf = settings.PUBLIC_SCHEMA_URLCONF return except get_tenant_domain_model().DoesNotExist: if hostname_without_port in ("127.0.0.1", "localhost"): request.urlconf = settings.PUBLIC_SCHEMA_URLCONF return else: raise Http404 connection.set_tenant(request.tenant) ContentType.objects.clear_cache() if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF') and request.tenant.schema_name == get_public_schema_name(): request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
Example #13
Source File: views.py From django-tenants with MIT License | 6 votes |
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) hostname_without_port = remove_www(self.request.get_host().split(':')[0]) try: Client.objects.get(schema_name='public') except utils.DatabaseError: context['need_sync'] = True context['shared_apps'] = settings.SHARED_APPS context['tenants_list'] = [] return context except Client.DoesNotExist: context['no_public_tenant'] = True context['hostname'] = hostname_without_port if Client.objects.count() == 1: context['only_public_tenant'] = True context['tenants_list'] = Client.objects.all() return context
Example #14
Source File: views.py From django-tenants with MIT License | 6 votes |
def form_valid(self, form): User.objects.all().delete() # clean current users # generate five random users users_to_generate = 5 first_names = ["Aiden", "Jackson", "Ethan", "Liam", "Mason", "Noah", "Lucas", "Jacob", "Jayden", "Jack", "Sophia", "Emma", "Olivia", "Isabella", "Ava", "Lily", "Zoe", "Chloe", "Mia", "Madison"] last_names = ["Smith", "Brown", "Lee", "Wilson", "Martin", "Patel", "Taylor", "Wong", "Campbell", "Williams"] while User.objects.count() != users_to_generate: first_name = choice(first_names) last_name = choice(last_names) try: user = User(username=(first_name+last_name).lower(), email="%s@%s.com" % (first_name, last_name), first_name=first_name, last_name=last_name) user.save() except DatabaseError: pass return super().form_valid(form)
Example #15
Source File: creation.py From openhgsenti with Apache License 2.0 | 6 votes |
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err): """ Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise. """ try: # Statement can fail when acceptable_ora_err is not None allow_quiet_fail = acceptable_ora_err is not None and len(acceptable_ora_err) > 0 self._execute_statements(cursor, statements, parameters, verbosity, allow_quiet_fail=allow_quiet_fail) return True except DatabaseError as err: description = str(err) if acceptable_ora_err is None or acceptable_ora_err not in description: raise return False
Example #16
Source File: mixins.py From django-mmc with GNU General Public License v2.0 | 6 votes |
def __mmc_log_start(self): try: from mmc.models import MMCLog self._mmc_log_instance = MMCLog.logging( start=self._mmc_start_date, hostname=self._mmc_hostname, script=self._mmc_script, elapsed=0.00, success=None, error_message="", traceback="", sys_argv=self.__mmc_get_sys_argv(), memory=0.00, cpu_time=0.00, queries=self.__mmc_get_queries(), ) except DatabaseError: pass except Exception as err: stderr("[MMC] Logging broken with message: {0}".format(err))
Example #17
Source File: __init__.py From django-db-mailer with GNU General Public License v2.0 | 6 votes |
def initial_signals(): from django.db.utils import DatabaseError, IntegrityError for cmd in ['schemamigration', 'migrate', 'test', 'createsuperuser', 'makemigrations', 'collectstatic', 'compilemessages']: if cmd in sys.argv: break else: try: from dbmail.signals import initial_signals as init_signals init_signals() except (ImportError, DatabaseError, IntegrityError): pass ## # Compatibility section ##
Example #18
Source File: base.py From openhgsenti with Apache License 2.0 | 6 votes |
def validate_thread_sharing(self): """ Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails. """ if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()): raise DatabaseError("DatabaseWrapper objects created in a " "thread can only be used in that same thread. The object " "with alias '%s' was created in thread id %s and this is " "thread id %s." % (self.alias, self._thread_ident, thread.get_ident())) # ##### Miscellaneous #####
Example #19
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def validate_thread_sharing(self): """ Validate that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raise an exception if the validation fails. """ if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()): raise DatabaseError( "DatabaseWrapper objects created in a " "thread can only be used in that same thread. The object " "with alias '%s' was created in thread id %s and this is " "thread id %s." % (self.alias, self._thread_ident, _thread.get_ident()) ) # ##### Miscellaneous #####
Example #20
Source File: features.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def supports_stddev(self): """ Confirm support for STDDEV and related stats functions. SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. Manually check whether the call works. """ with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support
Example #21
Source File: base.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def execute(self, query, params=None): if params is None: params = [] else: params = self._format_params(params) args = [(':arg%d' % i) for i in range(len(params))] # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it # it does want a trailing ';' but not a trailing '/'. However, these # characters must be included in the original query in case the query # is being passed to SQL*Plus. if query.endswith(';') or query.endswith('/'): query = query[:-1] query = convert_unicode(query % tuple(args), self.charset) self._guess_input_sizes([params]) try: return self.cursor.execute(query, self._param_generator(params)) except Database.IntegrityError as e: six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) except Database.DatabaseError as e: # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400. if hasattr(e.args[0], 'code') and e.args[0].code == 1400 and not isinstance(e, IntegrityError): six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
Example #22
Source File: creation.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err): """ Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise. """ try: # Statement can fail when acceptable_ora_err is not None allow_quiet_fail = acceptable_ora_err is not None and len(acceptable_ora_err) > 0 self._execute_statements(cursor, statements, parameters, verbosity, allow_quiet_fail=allow_quiet_fail) return True except DatabaseError as err: description = str(err) if acceptable_ora_err is None or acceptable_ora_err not in description: raise return False
Example #23
Source File: base.py From python-mysql-pool with MIT License | 6 votes |
def _execute_wrapper(self, method, query, args): """Wrapper around execute() and executemany()""" try: return method(query, args) except (PyMysqlPool.mysql.connector.ProgrammingError) as err: six.reraise(utils.ProgrammingError, utils.ProgrammingError(err.msg), sys.exc_info()[2]) except (PyMysqlPool.mysql.connector.IntegrityError) as err: six.reraise(utils.IntegrityError, utils.IntegrityError(err.msg), sys.exc_info()[2]) except PyMysqlPool.mysql.connector.OperationalError as err: # Map some error codes to IntegrityError, since they seem to be # misclassified and Django would prefer the more logical place. if err.args[0] in self.codes_for_integrityerror: six.reraise(utils.IntegrityError, utils.IntegrityError(err.msg), sys.exc_info()[2]) else: six.reraise(utils.DatabaseError, utils.DatabaseError(err.msg), sys.exc_info()[2]) except PyMysqlPool.mysql.connector.DatabaseError as err: six.reraise(utils.DatabaseError, utils.DatabaseError(err.msg), sys.exc_info()[2])
Example #24
Source File: base.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _nodb_connection(self): nodb_connection = super()._nodb_connection try: nodb_connection.ensure_connection() except (Database.DatabaseError, WrappedDatabaseError): warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the first PostgreSQL database instead.", RuntimeWarning ) for connection in connections.all(): if connection.vendor == 'postgresql' and connection.settings_dict['NAME'] != 'postgres': return self.__class__( {**self.settings_dict, 'NAME': connection.settings_dict['NAME']}, alias=self.alias, allow_thread_sharing=False, ) return nodb_connection
Example #25
Source File: base.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def _commit(self): if self.connection is not None: try: return self.connection.commit() except Database.IntegrityError as e: # In case cx_Oracle implements (now or in a future version) # raising this specific exception six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) except Database.DatabaseError as e: # cx_Oracle 5.0.4 raises a cx_Oracle.DatabaseError exception # with the following attributes and values: # code = 2091 # message = 'ORA-02091: transaction rolled back # 'ORA-02291: integrity constraint (TEST_DJANGOTEST.SYS # _C00102056) violated - parent key not found' # We convert that particular case to our IntegrityError exception x = e.args[0] if hasattr(x, 'code') and hasattr(x, 'message') \ and x.code == 2091 and 'ORA-02291' in x.message: six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
Example #26
Source File: base.py From python with Apache License 2.0 | 6 votes |
def validate_thread_sharing(self): """ Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails. """ if not (self.allow_thread_sharing or self._thread_ident == thread.get_ident()): raise DatabaseError( "DatabaseWrapper objects created in a " "thread can only be used in that same thread. The object " "with alias '%s' was created in thread id %s and this is " "thread id %s." % (self.alias, self._thread_ident, thread.get_ident()) ) # ##### Miscellaneous #####
Example #27
Source File: features.py From python with Apache License 2.0 | 6 votes |
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. """ with self.connection.cursor() as cursor: cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support
Example #28
Source File: creation.py From python with Apache License 2.0 | 6 votes |
def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err): """ Execute statements which are allowed to fail silently if the Oracle error code given by `acceptable_ora_err` is raised. Return True if the statements execute without an exception, or False otherwise. """ try: # Statement can fail when acceptable_ora_err is not None allow_quiet_fail = acceptable_ora_err is not None and len(acceptable_ora_err) > 0 self._execute_statements(cursor, statements, parameters, verbosity, allow_quiet_fail=allow_quiet_fail) return True except DatabaseError as err: description = str(err) if acceptable_ora_err is None or acceptable_ora_err not in description: raise return False
Example #29
Source File: base.py From python with Apache License 2.0 | 6 votes |
def _nodb_connection(self): nodb_connection = super(DatabaseWrapper, self)._nodb_connection try: nodb_connection.ensure_connection() except (Database.DatabaseError, WrappedDatabaseError): warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the default database instead.", RuntimeWarning ) settings_dict = self.settings_dict.copy() settings_dict['NAME'] = settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'] nodb_connection = self.__class__( self.settings_dict.copy(), alias=self.alias, allow_thread_sharing=False) return nodb_connection
Example #30
Source File: base.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_aggregate_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. """ cursor = self.connection.cursor() cursor.execute('CREATE TABLE STDDEV_TEST (X INT)') try: cursor.execute('SELECT STDDEV(*) FROM STDDEV_TEST') has_support = True except utils.DatabaseError: has_support = False cursor.execute('DROP TABLE STDDEV_TEST') return has_support