Fix error handling in user check (fixes #81)
[mygpo.git] / mygpo / users / checks.py
blob2810d1994887130d39d8b39b7f455468c43ec6ba
1 from django.core.checks import register, Warning
2 from django.db import connection
3 from django.db.utils import OperationalError, ProgrammingError
6 SQL = """
7 SELECT count(*), lower(username)
8 FROM auth_user
9 GROUP BY lower(username)
10 HAVING count(*) > 1;
11 """
13 @register()
14 def check_case_insensitive_users(app_configs=None, **kwargs):
15 errors = []
17 try:
18 cursor = connection.cursor()
19 cursor.execute(SQL)
20 non_unique = cursor.fetchall()
22 usernames = [t[1] for t in non_unique]
24 if len(non_unique) > 0:
25 txt = 'There are {0} non-unique usernames: {1}'.format(
26 len(non_unique),
27 ', '.join(usernames[:10] + ['...'])
29 wid = 'users.W001'
30 errors.append(Warning(txt, id=wid))
32 except OperationalError as oe:
33 if 'no such table: auth_user' in str(oe):
34 # Ignore if the table does not yet exist, eg when initally
35 # running ``manage.py migrate``
36 pass
37 else:
38 raise
40 except ProgrammingError as pe:
41 if 'relation "auth_user" does not exist' in str(pe):
42 # Ignore if the table does not yet exist, eg when initally
43 # running ``manage.py migrate``
44 pass
45 else:
46 raise
48 return errors