Python django.db.utils.ProgrammingError() Examples
The following are 30
code examples of django.db.utils.ProgrammingError().
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: apps.py From django-river with BSD 3-Clause "New" or "Revised" License | 7 votes |
def ready(self): for field_name in self._get_all_workflow_fields(): try: workflows = self.get_model('Workflow').objects.filter(field_name=field_name) if workflows.count() == 0: LOGGER.warning("%s field doesn't seem have any workflow defined in database. You should create its workflow" % field_name) except (OperationalError, ProgrammingError): pass from river.config import app_config if app_config.INJECT_MODEL_ADMIN: for model_class in self._get_all_workflow_classes(): self._register_hook_inlines(model_class) LOGGER.debug('RiverApp is loaded.')
Example #2
Source File: sequence.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def current(self): """Return the current value of this sequence, or `None`. :return: The sequence value, or None if there is no current value for the sequence in the database session or if the sequence does not exist. :rtype: int / None """ try: with transaction.atomic(): with connection.cursor() as cursor: cursor.execute("SELECT currval(%s)", [self.name]) return cursor.fetchone()[0] except utils.OperationalError as error: if is_postgres_error(error, OBJECT_NOT_IN_PREREQUISITE_STATE): # There is no current value for the sequence in this session. return None else: raise except utils.ProgrammingError as error: if is_postgres_error(error, UNDEFINED_TABLE): # The sequence does not exist, hence has no current value. return None else: raise
Example #3
Source File: checks.py From django-pgschemas with MIT License | 6 votes |
def check_schema_names(app_configs, **kwargs): errors = [] static_names = set(settings.TENANTS.keys()) clone_reference = get_clone_reference() if clone_reference: static_names.add(clone_reference) try: dynamic_names = set(get_tenant_model().objects.values_list("schema_name", flat=True)) except ProgrammingError: # This happens on the first run of migrate, with empty database. # It can also happen when the tenant model contains unapplied migrations that break. dynamic_names = set() intersection = static_names & dynamic_names if intersection: errors.append( checks.Critical( "Name clash found between static and dynamic tenants: %s" % intersection, id="pgschemas.W004", ) ) return errors
Example #4
Source File: create_kobo_superuser.py From kpi with GNU Affero General Public License v3.0 | 6 votes |
def handle(self, *args, **options): super_username = os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo') if User.objects.filter(username=super_username).count() > 0: self.stdout.write('User already exists.') sys.exit() try: User.objects.create_superuser( os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo'), os.getenv('KOBO_SUPERUSER_EMAIL', 'kobo@example.com'), os.getenv('KOBO_SUPERUSER_PASSWORD', 'kobo')) except ProgrammingError: # Signals fail when `kc` database pass # doesn't exist yet. except Exception as e: self.stdout.write('Superuser could not be created.\n' 'Error: {}'.format(str(e))) if User.objects.filter(username=super_username).count() > 0: self.stdout.write('Superuser successfully created.')
Example #5
Source File: __init__.py From django-pgschemas with MIT License | 6 votes |
def get_schemas_from_options(self, **options): skip_schema_creation = options.get("skip_schema_creation", False) try: schemas = self._get_schemas_from_options(**options) except ProgrammingError: # This happens with unmigrated database. # It can also happen when the tenant model contains unapplied migrations that break. raise CommandError( "Error while attempting to retrieve dynamic schemas. " "Perhaps you need to migrate the 'public' schema first?" ) if self.specific_schemas is not None: schemas = [x for x in schemas if x in self.specific_schemas] if not schemas: raise CommandError("This command can only run in %s" % self.specific_schemas) if not skip_schema_creation: for schema in schemas: create_schema(schema, check_if_exists=True, sync_schema=False, verbosity=0) return schemas
Example #6
Source File: test_mixins.py From Disfactory with MIT License | 6 votes |
def setUp(self): # Create a dummy model which extends the mixin. A RuntimeWarning will # occur if the model is registered twice if not hasattr(self, 'model'): self.model = ModelBase( '__TestModel__' + self.mixin.__name__, (self.mixin,), {'__module__': self.mixin.__module__} ) # Create the schema for our test model. If the table already exists, # will pass try: with connection.schema_editor() as schema_editor: schema_editor.create_model(self.model) super(AbstractModelMixinTestCase, self).setUpClass() except ProgrammingError: pass
Example #7
Source File: apps.py From InvenTree with MIT License | 6 votes |
def generate_company_thumbs(self): from .models import Company print("InvenTree: Checking Company image thumbnails") try: for company in Company.objects.all(): if company.image: url = company.image.thumbnail.name loc = os.path.join(settings.MEDIA_ROOT, url) if not os.path.exists(loc): print("InvenTree: Generating thumbnail for Company '{c}'".format(c=company.name)) try: company.image.render_variations(replace=False) except FileNotFoundError: print("Image file missing") company.image = None company.save() except (OperationalError, ProgrammingError): print("Could not generate Company thumbnails")
Example #8
Source File: apps.py From InvenTree with MIT License | 6 votes |
def generate_part_thumbnails(self): from .models import Part print("InvenTree: Checking Part image thumbnails") try: for part in Part.objects.all(): if part.image: url = part.image.thumbnail.name loc = os.path.join(settings.MEDIA_ROOT, url) if not os.path.exists(loc): print("InvenTree: Generating thumbnail for Part '{p}'".format(p=part.name)) try: part.image.render_variations(replace=False) except FileNotFoundError: print("Image file missing") part.image = None part.save() except (OperationalError, ProgrammingError): print("Could not generate Part thumbnails")
Example #9
Source File: clone.py From django-tenants with MIT License | 6 votes |
def clone_schema(self, base_schema_name, new_schema_name, set_connection=True): """ Creates a new schema `new_schema_name` as a clone of an existing schema `old_schema_name`. """ if set_connection: connection.set_schema_to_public() cursor = connection.cursor() # check if the clone_schema function already exists in the db try: cursor.execute("SELECT 'clone_schema'::regproc") except ProgrammingError: self._create_clone_schema_function() transaction.commit() if schema_exists(new_schema_name): raise ValidationError("New schema name already exists") sql = 'SELECT clone_schema(%(base_schema)s, %(new_schema)s, true, false)' cursor.execute( sql, {'base_schema': base_schema_name, 'new_schema': new_schema_name} ) cursor.close()
Example #10
Source File: base.py From plugin.video.netflix with MIT License | 6 votes |
def _execute_wrapper(self, method, query, args): """Wrapper around execute() and executemany()""" try: return method(query, args) except (mysql.connector.ProgrammingError) as err: six.reraise(utils.ProgrammingError, utils.ProgrammingError(err.msg), sys.exc_info()[2]) except (mysql.connector.IntegrityError) as err: six.reraise(utils.IntegrityError, utils.IntegrityError(err.msg), sys.exc_info()[2]) except 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 mysql.connector.DatabaseError as err: six.reraise(utils.DatabaseError, utils.DatabaseError(err.msg), sys.exc_info()[2])
Example #11
Source File: test_basic.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_sql_psycopg2_string_composition(sentry_init, capture_events, query): sentry_init( integrations=[DjangoIntegration()], send_default_pii=True, _experiments={"record_sql_params": True}, ) from django.db import connections if "postgres" not in connections: pytest.skip("postgres tests disabled") import psycopg2.sql sql = connections["postgres"].cursor() events = capture_events() with pytest.raises(ProgrammingError): sql.execute(query(psycopg2.sql), {"my_param": 10}) capture_message("HI") (event,) = events crumb = event["breadcrumbs"][-1] assert crumb["message"] == ('SELECT %(my_param)s FROM "foobar"') assert crumb["data"]["db.params"] == {"my_param": 10}
Example #12
Source File: compiler.py From django-postgres-extra with MIT License | 6 votes |
def execute_sql(self, return_id=False): # execute all the generate queries with self.connection.cursor() as cursor: rows = [] for sql, params in self.as_sql(return_id): cursor.execute(sql, params) try: rows.extend(cursor.fetchall()) except ProgrammingError: pass # create a mapping between column names and column value return [ { column.name: row[column_index] for column_index, column in enumerate(cursor.description) if row } for row in rows ]
Example #13
Source File: checks.py From normandy with Mozilla Public License 2.0 | 6 votes |
def actions_have_consistent_hashes(app_configs, **kwargs): errors = [] try: Action = apps.get_model("recipes", "Action") actions = list(Action.objects.filter(implementation__isnull=False)) except (ProgrammingError, OperationalError, ImproperlyConfigured) as e: errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS)) else: for action in actions: if action.compute_implementation_hash() != action.implementation_hash: msg = "Action '{action}' (id={action.id}) has a mismatched hash".format( action=action ) errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH)) return errors
Example #14
Source File: test_harvester.py From tethys with BSD 2-Clause "Simplified" License | 6 votes |
def test_harvest_app_instances_programming_error(self, mock_permissions, mock_logwarning, mock_stdout): """ Test for SingletonHarvester._harvest_app_instances For the app permissions exception (ProgrammingError) With an exception mocked up for register_app_permissions :param mock_permissions: mock for throwing a ProgrammingError exception :param mock_logerror: mock for the tethys_log error :param mock_stdout: mock for the text output :return: """ list_apps = {'test_app': 'tethysapp.test_app'} mock_permissions.side_effect = ProgrammingError shv = SingletonHarvester() shv._harvest_app_instances(list_apps) mock_logwarning.assert_called() mock_permissions.assert_called() self.assertIn('Tethys Apps Loaded:', mock_stdout.getvalue()) self.assertIn('test_app', mock_stdout.getvalue())
Example #15
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 #16
Source File: operations.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def spatial_version(self): """Determine the version of the PostGIS library.""" # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. if hasattr(settings, 'POSTGIS_VERSION'): version = settings.POSTGIS_VERSION else: try: vtup = self.postgis_version_tuple() except ProgrammingError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.5. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) version = vtup[1:] return version
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_reraising_backend_specific_database_exception(self): with connection.cursor() as cursor: msg = 'table "X" does not exist' with self.assertRaisesMessage(ProgrammingError, msg) as cm: cursor.execute('DROP TABLE "X"') self.assertNotEqual(type(cm.exception), type(cm.exception.__cause__)) self.assertIsNotNone(cm.exception.__cause__) self.assertIsNotNone(cm.exception.__cause__.pgcode) self.assertIsNotNone(cm.exception.__cause__.pgerror)
Example #18
Source File: test_sequence.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_drop_sequence_fails_if_sequence_does_not_exist(self): name = factory.make_name("seq", sep="") seq = Sequence(name) self.assertRaisesRegex(ProgrammingError, "does not exist", seq.drop)
Example #19
Source File: test_app_base.py From tethys with BSD 2-Clause "Simplified" License | 5 votes |
def test_sync_with_tethys_db_programming_error(self, mock_ta, mock_log): mock_ta.objects.filter().all.side_effect = ProgrammingError self.app.sync_with_tethys_db() mock_log.warning.assert_called_with("Unable to sync app with database. " "tethys_apps_tethysapp table does not exist")
Example #20
Source File: test_app_base.py From tethys with BSD 2-Clause "Simplified" License | 5 votes |
def test_sync_with_tethys_db_exists_progamming_error(self, mock_te, mock_log): mock_warning = mock_log.warning ext = tethys_app_base.TethysExtensionBase() ext.root_url = 'test_url' mock_te.objects.filter().all.side_effect = ProgrammingError('test_error') ext.sync_with_tethys_db() # Check_result mock_warning.assert_called_with("Unable to sync extension with database. " "tethys_apps_tethysextension table does not exist")
Example #21
Source File: signals_handler.py From diting with GNU General Public License v2.0 | 5 votes |
def refresh_all_settings_on_django_ready(sender, **kwargs): logger.debug("Receive django ready signal") logger.debug(" - fresh all settings") try: Setting.refresh_all_settings() except (ProgrammingError, OperationalError): pass
Example #22
Source File: models.py From diting with GNU General Public License v2.0 | 5 votes |
def refresh_all_settings(cls): try: settings_list = cls.objects.all() for setting in settings_list: setting.refresh_setting() except (ProgrammingError, OperationalError): pass
Example #23
Source File: collector.py From albatross with GNU Affero General Public License v3.0 | 5 votes |
def _wait_for_db(self): try: self.logger.info("Looking for the database...") cursor = connections["default"].cursor() cursor.execute(f"SELECT count(*) FROM {SocialApp._meta.db_table}") assert cursor.fetchone() time.sleep(2) # Chill before startup except (OperationalError, ProgrammingError, AssertionError): time.sleep(1) self._wait_for_db()
Example #24
Source File: test_sequence.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_sequence_will_be_created_automatically_on_first_access(self): seq = Sequence("dave") # Accessing the sequence directly in the database we find that it's # not there. with ExpectedException(ProgrammingError, ".* does not exist"): with transaction.atomic(): self.query_seq(seq.name) # Iterating via `Sequence` automatically vivifies it. self.assertEqual(1, next(seq)) self.assertEqual(2, self.query_seq(seq.name))
Example #25
Source File: helpers.py From TWLight with MIT License | 5 votes |
def site_id(): # Prefer the current initialized site. try: return Site.objects.get_current().pk # If don't have an initialized database yet, fetch the default from settings. except ProgrammingError: return settings.SITE_ID
Example #26
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_reraising_backend_specific_database_exception(self): with connection.cursor() as cursor: msg = 'table "X" does not exist' with self.assertRaisesMessage(ProgrammingError, msg) as cm: cursor.execute('DROP TABLE "X"') self.assertNotEqual(type(cm.exception), type(cm.exception.__cause__)) self.assertIsNotNone(cm.exception.__cause__) self.assertIsNotNone(cm.exception.__cause__.pgcode) self.assertIsNotNone(cm.exception.__cause__.pgerror)
Example #27
Source File: 0009_remove_noderesult_schema.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def database_forwards( self, app_label, schema_editor, from_state, to_state ): try: super().database_forwards( app_label, schema_editor, from_state, to_state ) except utils.ProgrammingError: # Error is raised when the table has already been deleted. This # is for users that upgrade to 2.2 beta1 before 2.2 beta3. pass
Example #28
Source File: sequence.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def create_if_not_exists(self): """Create this sequence in the database. If it already exists, fine. """ try: self.create() except utils.ProgrammingError as error: if is_postgres_error(error, DUPLICATE_TABLE): pass # Sequence already exists. else: raise
Example #29
Source File: sequence.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def drop_if_exists(self): """Drop this sequence from the database. If it doesn't exist, fine. """ try: self.drop() except utils.ProgrammingError as error: if is_postgres_error(error, UNDEFINED_TABLE): pass # Sequence already dropped. else: raise
Example #30
Source File: sequence.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def __next__(self): """Return the next value of this sequence. This will create the sequence if it does not exist. This is dirty and nasty but it's a compromise. We can create sequences in migrations, but running tests with migrations is mind-bendinly slow, so we want to run tests outside of migrations... but Django without migrations does not grok sequences. So, for the sake of tests and our collective sanity we just create the wretched sequence. :return: The sequence value. :rtype: int """ try: with transaction.atomic(): with connection.cursor() as cursor: cursor.execute("SELECT nextval(%s)", [self.name]) return cursor.fetchone()[0] except utils.ProgrammingError as error: if is_postgres_error(error, UNDEFINED_TABLE): # The sequence does not exist. For the sake of tests we'll # create it on the fly because: we can create sequences in # migrations, running tests with migrations is mind-bendinly # slow, but tests without migrations do not grok sequences. # Suppress DUPLICATE_TABLE errors from races here. self.create_if_not_exists() return next(self) else: raise