authentik.lib.utils.db
authentik database utilities
1"""authentik database utilities""" 2 3import gc 4from collections.abc import Generator 5 6from django.core.exceptions import EmptyResultSet, FullResultSet 7from django.db import connections, reset_queries, transaction 8from django.db.models import Model, QuerySet 9from django.db.models.deletion import Collector 10 11 12def chunked_queryset[T: Model](queryset: QuerySet[T], chunk_size: int = 1_000) -> Generator[T]: 13 if not queryset.exists(): 14 return 15 16 def get_chunks(qs: QuerySet) -> Generator[QuerySet[T]]: 17 qs = qs.order_by("pk") 18 pks = qs.values_list("pk", flat=True) 19 # The outer queryset.exists() guard can race with a concurrent 20 # transaction that deletes the last matching row (or with a 21 # different isolation-level snapshot), so by the time this 22 # generator starts iterating the queryset may be empty and 23 # pks[0] would raise IndexError and crash the caller. Using 24 # .first() returns None on an empty queryset, which we bail 25 # out on cleanly. See goauthentik/authentik#21643. 26 start_pk = pks.first() 27 if start_pk is None: 28 return 29 while True: 30 try: 31 end_pk = pks.filter(pk__gte=start_pk)[chunk_size] 32 except IndexError: 33 break 34 yield qs.filter(pk__gte=start_pk, pk__lt=end_pk) 35 start_pk = end_pk 36 yield qs.filter(pk__gte=start_pk) 37 38 for chunk in get_chunks(queryset): 39 reset_queries() 40 gc.collect() 41 yield from chunk.iterator(chunk_size=chunk_size) 42 43 44def _is_index_leading(model: type[Model], field_name: str) -> bool: 45 """Whether a full (not partial) index starts with `field_name`, so Postgres can read rows in 46 that order instead of sorting every match""" 47 field = model._meta.get_field(field_name) if field_name != "pk" else model._meta.pk 48 if field.primary_key or field.unique or field.db_index: 49 return True 50 return any( 51 index.fields and index.fields[0].lstrip("-") == field.name and index.condition is None 52 for index in model._meta.indexes 53 ) 54 55 56class LockingCollector(Collector): 57 """Collector that locks the rows it cascades to before collecting what references them. 58 59 Django collects the rows referencing a deleted row before it deletes it. A row that starts 60 referencing it in between is not collected, and the deferred foreign key check then fails 61 the deleting transaction on commit. With the referenced row locked first, the transaction 62 adding the reference either committed before and is collected, or waits for the deletion 63 and fails its own foreign key check instead.""" 64 65 def collect(self, objs, *args, **kwargs): 66 if isinstance(objs, QuerySet) and not self.can_fast_delete(objs): 67 objs = objs.select_for_update(of=("self",)) 68 return super().collect(objs, *args, **kwargs) 69 70 71def delete_in_batches[T: Model]( 72 queryset: QuerySet[T], batch_size: int = 1_000, order_by: str = "pk" 73) -> int: 74 """Delete matching rows in short transactions, returning the target model's count. 75 76 Call outside an enclosing transaction to release locks after each batch. Use only 77 for models that do not require instance-level delete/expiration hooks; Django's 78 deletion signals and cascades still run. Rows locked by another transaction are 79 skipped and may need a later cleanup run. 80 """ 81 if batch_size < 1: 82 raise ValueError("batch_size must be positive") 83 if not _is_index_leading(queryset.model, order_by): 84 raise ValueError(f"{queryset.model._meta.label} has no index starting with {order_by}") 85 86 # SELECT FOR UPDATE also selects the write database when routers are configured. 87 queryset = queryset.select_for_update(skip_locked=True, of=("self",)) 88 database = queryset.db 89 queryset = queryset.using(database) 90 deleted_total = 0 91 while True: 92 with transaction.atomic(using=database): 93 # Order by the column the filter ranges over, so Postgres scans just that index 94 # range. Without an order, Postgres may pick a sequential scan that reads most of 95 # the table when matching rows aren't spread evenly through it. 96 pks = list(queryset.order_by(order_by).values_list("pk", flat=True)[:batch_size]) 97 if not pks: 98 return deleted_total 99 # Hold the locks through the collector and DELETE so that a cache refresh 100 # cannot race with deletion after the expiration check. 101 collector = LockingCollector(using=database, origin=queryset) 102 collector.collect(queryset.model._base_manager.using(database).filter(pk__in=pks)) 103 _, counts = collector.delete() 104 deleted = counts.get(queryset.model._meta.label, 0) 105 # Locked rows that don't get deleted (a trigger, an inconsistent index) would be 106 # selected again forever. Raise to roll back this batch instead of looping. 107 if deleted == 0: 108 raise RuntimeError( 109 f"Locked {len(pks)} {queryset.model._meta.label} rows but deleted none" 110 ) 111 deleted_total += deleted 112 113 114def distinct_values(queryset: QuerySet, field: str) -> list: 115 """Return the distinct non-null values of `field` in `queryset` as the database returns 116 them, in ascending order. 117 118 `SELECT DISTINCT` reads every row. When `field` is indexed and has few distinct values, 119 stepping from each value to the next through the index reads one index entry per value 120 instead, which is far cheaper on large tables such as events. This is the recursive query 121 from https://wiki.postgresql.org/wiki/Loose_indexscan, with the queryset's filters applied 122 at each step. Those filters may only use the queryset's own table.""" 123 if len(queryset.query.alias_map) > 1: 124 raise ValueError("distinct_values cannot filter through a join") 125 db = connections[queryset.db] 126 table = db.ops.quote_name(queryset.model._meta.db_table) 127 column = f"{table}.{db.ops.quote_name(queryset.model._meta.get_field(field).column)}" 128 try: 129 where, params = queryset.query.get_compiler(using=queryset.db).compile(queryset.query.where) 130 except EmptyResultSet: 131 return [] 132 except FullResultSet: 133 where, params = "", () 134 where = f"AND {where}" if where else "" 135 with db.cursor() as cursor: 136 cursor.execute( 137 f""" 138 WITH RECURSIVE distinct_values(value) AS ( 139 SELECT MIN({column}) FROM {table} WHERE TRUE {where} 140 UNION ALL 141 SELECT ( 142 SELECT MIN({column}) FROM {table} 143 WHERE {column} > distinct_values.value {where} 144 ) 145 FROM distinct_values WHERE value IS NOT NULL 146 ) 147 SELECT value FROM distinct_values WHERE value IS NOT NULL 148 """, # nosec: identifiers come from the model and values are in params 149 (*params, *params), 150 ) 151 return [value for (value,) in cursor.fetchall()] 152 153 154def distinct_values_containing(queryset: QuerySet, field: str, needle: str) -> list[str]: 155 """Return distinct strings containing the substring, ignoring case.""" 156 needle = needle.casefold() 157 return [value for value in distinct_values(queryset, field) if needle in value.casefold()]
13def chunked_queryset[T: Model](queryset: QuerySet[T], chunk_size: int = 1_000) -> Generator[T]: 14 if not queryset.exists(): 15 return 16 17 def get_chunks(qs: QuerySet) -> Generator[QuerySet[T]]: 18 qs = qs.order_by("pk") 19 pks = qs.values_list("pk", flat=True) 20 # The outer queryset.exists() guard can race with a concurrent 21 # transaction that deletes the last matching row (or with a 22 # different isolation-level snapshot), so by the time this 23 # generator starts iterating the queryset may be empty and 24 # pks[0] would raise IndexError and crash the caller. Using 25 # .first() returns None on an empty queryset, which we bail 26 # out on cleanly. See goauthentik/authentik#21643. 27 start_pk = pks.first() 28 if start_pk is None: 29 return 30 while True: 31 try: 32 end_pk = pks.filter(pk__gte=start_pk)[chunk_size] 33 except IndexError: 34 break 35 yield qs.filter(pk__gte=start_pk, pk__lt=end_pk) 36 start_pk = end_pk 37 yield qs.filter(pk__gte=start_pk) 38 39 for chunk in get_chunks(queryset): 40 reset_queries() 41 gc.collect() 42 yield from chunk.iterator(chunk_size=chunk_size)
57class LockingCollector(Collector): 58 """Collector that locks the rows it cascades to before collecting what references them. 59 60 Django collects the rows referencing a deleted row before it deletes it. A row that starts 61 referencing it in between is not collected, and the deferred foreign key check then fails 62 the deleting transaction on commit. With the referenced row locked first, the transaction 63 adding the reference either committed before and is collected, or waits for the deletion 64 and fails its own foreign key check instead.""" 65 66 def collect(self, objs, *args, **kwargs): 67 if isinstance(objs, QuerySet) and not self.can_fast_delete(objs): 68 objs = objs.select_for_update(of=("self",)) 69 return super().collect(objs, *args, **kwargs)
Collector that locks the rows it cascades to before collecting what references them.
Django collects the rows referencing a deleted row before it deletes it. A row that starts referencing it in between is not collected, and the deferred foreign key check then fails the deleting transaction on commit. With the referenced row locked first, the transaction adding the reference either committed before and is collected, or waits for the deletion and fails its own foreign key check instead.
66 def collect(self, objs, *args, **kwargs): 67 if isinstance(objs, QuerySet) and not self.can_fast_delete(objs): 68 objs = objs.select_for_update(of=("self",)) 69 return super().collect(objs, *args, **kwargs)
Add 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler.
If the call is the result of a cascade, 'source' should be the model that caused it and 'nullable' should be set to True, if the relation can be null.
If 'reverse_dependency' is True, 'source' will be deleted before the current model, rather than after. (Needed for cascading to parent models, the one case in which the cascade follows the forwards direction of an FK rather than the reverse direction.)
If 'keep_parents' is True, data of parent model's will be not deleted.
If 'fail_on_restricted' is False, error won't be raised even if it's prohibited to delete such objects due to RESTRICT, that defers restricted object checking in recursive calls where the top-level call may need to collect more objects to determine whether restricted ones can be deleted.
72def delete_in_batches[T: Model]( 73 queryset: QuerySet[T], batch_size: int = 1_000, order_by: str = "pk" 74) -> int: 75 """Delete matching rows in short transactions, returning the target model's count. 76 77 Call outside an enclosing transaction to release locks after each batch. Use only 78 for models that do not require instance-level delete/expiration hooks; Django's 79 deletion signals and cascades still run. Rows locked by another transaction are 80 skipped and may need a later cleanup run. 81 """ 82 if batch_size < 1: 83 raise ValueError("batch_size must be positive") 84 if not _is_index_leading(queryset.model, order_by): 85 raise ValueError(f"{queryset.model._meta.label} has no index starting with {order_by}") 86 87 # SELECT FOR UPDATE also selects the write database when routers are configured. 88 queryset = queryset.select_for_update(skip_locked=True, of=("self",)) 89 database = queryset.db 90 queryset = queryset.using(database) 91 deleted_total = 0 92 while True: 93 with transaction.atomic(using=database): 94 # Order by the column the filter ranges over, so Postgres scans just that index 95 # range. Without an order, Postgres may pick a sequential scan that reads most of 96 # the table when matching rows aren't spread evenly through it. 97 pks = list(queryset.order_by(order_by).values_list("pk", flat=True)[:batch_size]) 98 if not pks: 99 return deleted_total 100 # Hold the locks through the collector and DELETE so that a cache refresh 101 # cannot race with deletion after the expiration check. 102 collector = LockingCollector(using=database, origin=queryset) 103 collector.collect(queryset.model._base_manager.using(database).filter(pk__in=pks)) 104 _, counts = collector.delete() 105 deleted = counts.get(queryset.model._meta.label, 0) 106 # Locked rows that don't get deleted (a trigger, an inconsistent index) would be 107 # selected again forever. Raise to roll back this batch instead of looping. 108 if deleted == 0: 109 raise RuntimeError( 110 f"Locked {len(pks)} {queryset.model._meta.label} rows but deleted none" 111 ) 112 deleted_total += deleted
Delete matching rows in short transactions, returning the target model's count.
Call outside an enclosing transaction to release locks after each batch. Use only for models that do not require instance-level delete/expiration hooks; Django's deletion signals and cascades still run. Rows locked by another transaction are skipped and may need a later cleanup run.
115def distinct_values(queryset: QuerySet, field: str) -> list: 116 """Return the distinct non-null values of `field` in `queryset` as the database returns 117 them, in ascending order. 118 119 `SELECT DISTINCT` reads every row. When `field` is indexed and has few distinct values, 120 stepping from each value to the next through the index reads one index entry per value 121 instead, which is far cheaper on large tables such as events. This is the recursive query 122 from https://wiki.postgresql.org/wiki/Loose_indexscan, with the queryset's filters applied 123 at each step. Those filters may only use the queryset's own table.""" 124 if len(queryset.query.alias_map) > 1: 125 raise ValueError("distinct_values cannot filter through a join") 126 db = connections[queryset.db] 127 table = db.ops.quote_name(queryset.model._meta.db_table) 128 column = f"{table}.{db.ops.quote_name(queryset.model._meta.get_field(field).column)}" 129 try: 130 where, params = queryset.query.get_compiler(using=queryset.db).compile(queryset.query.where) 131 except EmptyResultSet: 132 return [] 133 except FullResultSet: 134 where, params = "", () 135 where = f"AND {where}" if where else "" 136 with db.cursor() as cursor: 137 cursor.execute( 138 f""" 139 WITH RECURSIVE distinct_values(value) AS ( 140 SELECT MIN({column}) FROM {table} WHERE TRUE {where} 141 UNION ALL 142 SELECT ( 143 SELECT MIN({column}) FROM {table} 144 WHERE {column} > distinct_values.value {where} 145 ) 146 FROM distinct_values WHERE value IS NOT NULL 147 ) 148 SELECT value FROM distinct_values WHERE value IS NOT NULL 149 """, # nosec: identifiers come from the model and values are in params 150 (*params, *params), 151 ) 152 return [value for (value,) in cursor.fetchall()]
Return the distinct non-null values of field in queryset as the database returns
them, in ascending order.
SELECT DISTINCT reads every row. When field is indexed and has few distinct values,
stepping from each value to the next through the index reads one index entry per value
instead, which is far cheaper on large tables such as events. This is the recursive query
from https://wiki.postgresql.org/wiki/Loose_indexscan, with the queryset's filters applied
at each step. Those filters may only use the queryset's own table.
155def distinct_values_containing(queryset: QuerySet, field: str, needle: str) -> list[str]: 156 """Return distinct strings containing the substring, ignoring case.""" 157 needle = needle.casefold() 158 return [value for value in distinct_values(queryset, field) if needle in value.casefold()]
Return distinct strings containing the substring, ignoring case.