1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-01-27 14:03:53 +03:00

Removing unique_together and index_together for newer Index and UniqueConstrains

This commit is contained in:
Adolfo Gómez García 2021-06-23 20:58:00 +02:00
parent eab51248cd
commit b914980793
10 changed files with 139 additions and 24 deletions

View File

@ -0,0 +1,81 @@
# Generated by Django 3.2.4 on 2021-06-23 20:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('uds', '0041_alter_statscounters_index_together'),
]
operations = [
migrations.AlterUniqueTogether(
name='config',
unique_together=set(),
),
migrations.AlterUniqueTogether(
name='group',
unique_together=set(),
),
migrations.AlterUniqueTogether(
name='service',
unique_together=set(),
),
migrations.AlterUniqueTogether(
name='uniqueid',
unique_together=set(),
),
migrations.AlterUniqueTogether(
name='user',
unique_together=set(),
),
migrations.AlterUniqueTogether(
name='userserviceproperty',
unique_together=set(),
),
migrations.AlterIndexTogether(
name='statscounters',
index_together=set(),
),
migrations.AlterIndexTogether(
name='userservice',
index_together=set(),
),
migrations.AddIndex(
model_name='statscounters',
index=models.Index(fields=['owner_type', 'stamp'], name='uds_stats_c_owner_t_db894d_idx'),
),
migrations.AddIndex(
model_name='statscounters',
index=models.Index(fields=['owner_type', 'counter_type', 'stamp'], name='uds_stats_c_owner_t_a195c1_idx'),
),
migrations.AddIndex(
model_name='userservice',
index=models.Index(fields=['deployed_service', 'cache_level', 'state'], name='uds__user_s_deploye_a38d25_idx'),
),
migrations.AddConstraint(
model_name='config',
constraint=models.UniqueConstraint(fields=('section', 'key'), name='u_cfg_section_key'),
),
migrations.AddConstraint(
model_name='group',
constraint=models.UniqueConstraint(fields=('manager', 'name'), name='u_grp_manager_name'),
),
migrations.AddConstraint(
model_name='service',
constraint=models.UniqueConstraint(fields=('provider', 'name'), name='u_srv_provider_name'),
),
migrations.AddConstraint(
model_name='uniqueid',
constraint=models.UniqueConstraint(fields=('basename', 'seq'), name='u_uid_base_seq'),
),
migrations.AddConstraint(
model_name='user',
constraint=models.UniqueConstraint(fields=('manager', 'name'), name='u_usr_manager_name'),
),
migrations.AddConstraint(
model_name='userserviceproperty',
constraint=models.UniqueConstraint(fields=('name', 'user_service'), name='u_uprop_name_userservice'),
),
]

View File

@ -87,7 +87,7 @@ class Account(UUIDModel, TaggingMixin): # type: ignore
return return
tmp = userService.accounting tmp = userService.accounting
tmp.user_service = None tmp.user_service = None # type: ignore
tmp.end = getSqlDatetime() tmp.end = getSqlDatetime()
tmp.save() tmp.save()

View File

@ -33,6 +33,7 @@
import logging import logging
from django.db import models from django.db import models
from django.db.models import constraints
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -60,7 +61,10 @@ class Config(models.Model):
""" """
db_table = 'uds_configuration' db_table = 'uds_configuration'
unique_together = (('section', 'key'),) constraints = [
models.UniqueConstraint(fields=['section', 'key'], name='u_cfg_section_key')
]
app_label = 'uds' app_label = 'uds'
def __str__(self) -> str: def __str__(self) -> str:

View File

@ -75,9 +75,11 @@ class Group(UUIDModel):
Meta class to declare default order and unique multiple field index Meta class to declare default order and unique multiple field index
""" """
unique_together = (("manager", "name"),)
ordering = ('name',) ordering = ('name',)
app_label = 'uds' app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['manager', 'name'], name='u_grp_manager_name')
]
@property @property
def pretty_name(self) -> str: def pretty_name(self) -> str:

View File

@ -86,8 +86,10 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore
""" """
ordering = ('name',) ordering = ('name',)
unique_together = (("provider", "name"),)
app_label = 'uds' app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['provider', 'name'], name='u_srv_provider_name')
]
def getEnvironment(self) -> Environment: def getEnvironment(self) -> Environment:
""" """

View File

@ -65,9 +65,9 @@ class StatsCounters(models.Model):
db_table = 'uds_stats_c' db_table = 'uds_stats_c'
app_label = 'uds' app_label = 'uds'
index_together= [ indexes = [
('owner_type', 'stamp'), models.Index(fields=['owner_type', 'stamp']),
('owner_type', 'counter_type', 'stamp'), models.Index(fields=['owner_type', 'counter_type', 'stamp']),
] ]
@staticmethod @staticmethod

View File

@ -57,9 +57,11 @@ class UniqueId(models.Model):
Meta class to declare default order and unique multiple field index Meta class to declare default order and unique multiple field index
""" """
unique_together = (('basename', 'seq'),)
ordering = ('-seq',) ordering = ('-seq',)
app_label = 'uds' app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['basename', 'seq'], name='u_uid_base_seq')
]
def __str__(self) -> str: def __str__(self) -> str:
return u"{0} {1}.{2}, assigned is {3}".format( return u"{0} {1}.{2}, assigned is {3}".format(

View File

@ -57,13 +57,20 @@ class User(UUIDModel):
""" """
This class represents a single user, associated with one authenticator This class represents a single user, associated with one authenticator
""" """
manager : 'models.ForeignKey[User, Authenticator]' = UnsavedForeignKey(Authenticator, on_delete=models.CASCADE, related_name='users')
manager: 'models.ForeignKey[User, Authenticator]' = UnsavedForeignKey(
Authenticator, on_delete=models.CASCADE, related_name='users'
)
name = models.CharField(max_length=128, db_index=True) name = models.CharField(max_length=128, db_index=True)
real_name = models.CharField(max_length=128) real_name = models.CharField(max_length=128)
comments = models.CharField(max_length=256) comments = models.CharField(max_length=256)
state = models.CharField(max_length=1, db_index=True) state = models.CharField(max_length=1, db_index=True)
password = models.CharField(max_length=128, default='') # Only used on "internal" sources password = models.CharField(
staff_member = models.BooleanField(default=False) # Staff members can login to admin max_length=128, default=''
) # Only used on "internal" sources
staff_member = models.BooleanField(
default=False
) # Staff members can login to admin
is_admin = models.BooleanField(default=False) # is true, this is a super-admin is_admin = models.BooleanField(default=False) # is true, this is a super-admin
last_access = models.DateTimeField(default=NEVER) last_access = models.DateTimeField(default=NEVER)
parent = models.CharField(max_length=50, default=None, null=True) parent = models.CharField(max_length=50, default=None, null=True)
@ -78,9 +85,12 @@ class User(UUIDModel):
""" """
Meta class to declare default order and unique multiple field index Meta class to declare default order and unique multiple field index
""" """
unique_together = (("manager", "name"),)
ordering = ('name',) ordering = ('name',)
app_label = 'uds' app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['manager', 'name'], name='u_usr_manager_name')
]
def getUsernameForAuth(self) -> str: def getUsernameForAuth(self) -> str:
""" """
@ -129,6 +139,7 @@ class User(UUIDModel):
""" """
from uds.core.managers.user_preferences import UserPrefsManager from uds.core.managers.user_preferences import UserPrefsManager
return UserPrefsManager.manager().getPreferencesForUser(modName, self) return UserPrefsManager.manager().getPreferencesForUser(modName, self)
def updateLastAccess(self) -> None: def updateLastAccess(self) -> None:
@ -151,7 +162,9 @@ class User(UUIDModel):
""" """
if self.parent: if self.parent:
try: try:
usr = User.objects.prefetch_related('authenticator', 'groups').get(uuid=self.parent) usr = User.objects.prefetch_related('authenticator', 'groups').get(
uuid=self.parent
)
except Exception: # If parent do not exists except Exception: # If parent do not exists
usr = self usr = self
else: else:
@ -164,14 +177,17 @@ class User(UUIDModel):
yield g yield g
# Locate metagroups # Locate metagroups
for g in (self.manager.groups.filter(is_meta=True) for g in (
.annotate(number_groups=Count('groups')) # g.groups.count() self.manager.groups.filter(is_meta=True)
.annotate(number_belongs_meta=Count('groups', filter=Q(groups__id__in=grps))) # g.groups.filter(id__in=grps).count() .annotate(number_groups=Count('groups')) # g.groups.count()
): .annotate(
numberGroupsBelongingInMeta: int = g.number_belongs_meta number_belongs_meta=Count('groups', filter=Q(groups__id__in=grps))
) # g.groups.filter(id__in=grps).count()
):
numberGroupsBelongingInMeta: int = g.number_belongs_meta
logger.debug('gn = %s', numberGroupsBelongingInMeta) logger.debug('gn = %s', numberGroupsBelongingInMeta)
logger.debug('groups count: %s', g.number_groups) logger.debug('groups count: %s', g.number_groups)
if g.meta_if_any is True and numberGroupsBelongingInMeta > 0: if g.meta_if_any is True and numberGroupsBelongingInMeta > 0:
numberGroupsBelongingInMeta = g.number_groups numberGroupsBelongingInMeta = g.number_groups
@ -179,12 +195,14 @@ class User(UUIDModel):
logger.debug('gn after = %s', numberGroupsBelongingInMeta) logger.debug('gn after = %s', numberGroupsBelongingInMeta)
# If a meta group is empty, all users belongs to it. we can use gn != 0 to check that if it is empty, is not valid # If a meta group is empty, all users belongs to it. we can use gn != 0 to check that if it is empty, is not valid
if numberGroupsBelongingInMeta == g.number_groups: if numberGroupsBelongingInMeta == g.number_groups:
# This group matches # This group matches
yield g yield g
def __str__(self): def __str__(self):
return 'User {} (id:{}) from auth {}'.format(self.name, self.id, self.manager.name) return 'User {} (id:{}) from auth {}'.format(
self.name, self.id, self.manager.name
)
@staticmethod @staticmethod
def beforeDelete(sender, **kwargs): def beforeDelete(sender, **kwargs):

View File

@ -132,7 +132,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
db_table = 'uds__user_service' db_table = 'uds__user_service'
ordering = ('creation_date',) ordering = ('creation_date',)
app_label = 'uds' app_label = 'uds'
index_together = ('deployed_service', 'cache_level', 'state') indexes = [
models.Index(fields=['deployed_service', 'cache_level', 'state']),
]
@property @property
def name(self) -> str: def name(self) -> str:
@ -535,7 +537,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods
dct[v.name] = v.value dct[v.name] = v.value
return dct return dct
def setProperty(self, propName: str, propValue: typing.Optional[str] = None) -> None: def setProperty(
self, propName: str, propValue: typing.Optional[str] = None
) -> None:
prop, _ = self.properties.get_or_create(name=propName) prop, _ = self.properties.get_or_create(name=propName)
prop.value = propValue or '' prop.value = propValue or ''
prop.save() prop.save()

View File

@ -61,8 +61,10 @@ class UserServiceProperty(models.Model): # pylint: disable=too-many-public-meth
""" """
db_table = 'uds__user_service_property' db_table = 'uds__user_service_property'
unique_together = (('name', 'user_service'),)
app_label = 'uds' app_label = 'uds'
constraints = [
models.UniqueConstraint(fields=['name', 'user_service'], name='u_uprop_name_userservice')
]
def __str__(self) -> str: def __str__(self) -> str:
return "Property of {}. {}={}".format( return "Property of {}. {}={}".format(