Skip to content

Commit 306179e

Browse files
committed
feat: MySQLSafeUUIDField for migrating to Django 5 on MariaDB
Set USE_CHAR32_UUIDS=True in settings.py to enable
1 parent 086b4f2 commit 306179e

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

dev/dev_project/settings.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@
141141
}
142142
}
143143

144+
# Set to true if migrating to Django 5 from MariaDB/MySQL
145+
USE_CHAR32_UUIDS = False
146+
144147
# Default primary key field type
145148
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
146149

src/cdh/files/db/models.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from cdh.files.db.wrappers import FileWrapper
1010

1111

12+
USE_CHAR32_UUIDS = getattr(settings, "USE_CHAR32_UUIDS", False,)
1213
logger = logging.getLogger('cdh.files')
1314

1415

@@ -29,14 +30,44 @@ def __set__(self, instance, value):
2930
instance._file_wrapper_cache = value
3031

3132

33+
class MySQLSafeUUIDField(models.UUIDField,):
34+
"""
35+
Workaround class.
36+
37+
Django 5.0 switched from DB column type for UUID's on MySQL/MariaDB.
38+
The standard UUIDField is not aware of this change, and will fail to
39+
insert UUID's into the char(32) columns. For applications that run into
40+
this problem, this UUID field is provided which respects the setting
41+
USE_CHAR32_UUIDS in settings.py to support older fields.
42+
43+
Details: https://docs.djangoproject.com/en/6.0/releases/5.0/#migrating-existing-uuidfield-on-mariadb-10-7
44+
"""
45+
46+
def __init__(self, *args, **kwargs):
47+
self.use_char32_uuids = USE_CHAR32_UUIDS
48+
super().__init__(*args, **kwargs)
49+
50+
def db_type(self, connection):
51+
if self.use_char32_uuids:
52+
return "char(32)"
53+
return super().db_type(connection)
54+
55+
def get_db_prep_value(self, value, connection, prepared=False):
56+
value = super().get_db_prep_value(value, connection, prepared)
57+
breakpoint()
58+
if self.use_char32_uuids and value is not None:
59+
value = value.hex
60+
return value
61+
62+
3263
class BaseFile(models.Model):
3364
class Meta:
3465
abstract = True
3566

3667
objects = manager.FileManager()
3768

3869
# Human-facing PK; Also acts as the filename on disk
39-
uuid = models.UUIDField(
70+
uuid = MySQLSafeUUIDField(
4071
"Universally Unique IDentifier",
4172
unique=True,
4273
default=uuid.uuid4,

0 commit comments

Comments
 (0)